text:
Q: Video Streaming and Load Testing Using Apache JMeter I have made an HTTP Request to a webpage and it respond successfully with a VAST code (XML) Afterwards I used Apache JMeter Regular Expressions Extractor for Extracting a URL from the MediaFile tag in the responded XML code.
Here is the responded data (VAST XML):
<?xml version="1.0" encoding="UTF-8"?>
<VAST version="2.0">
  <Ad id="brightroll_ad">
    <InLine>
      <AdSystem>BrightRoll</AdSystem>
      <AdTitle></AdTitle>
      <Impression><![CDATA[http://brxserv-22.btrll.com/v1/epix/6835714/3858435/84416/140363/AbQ93_XgMgCcRUTi_JAAFJwAACJEsAOuADAAAAAAAiyel-GCNFFg/event.imp/r_64.aHR0cDovL2Iuc2NvcmVjYXJkcmVzZWFyY2guY29tL3A_JmMxPTgmYzI9NjAwMDAwNiZjMz04NDQxNiZjND0zODU4NDM1JmM1PTIwNDYzJmM2PTY4MzU3MTQmYzEwPTE0MDM2MyZjdj0xLjcmY2o9MSZybj0xNDE0NDEwMTg1JnI9aHR0cCUzQSUyRiUyRnBpeGVsLnF1YW50c2VydmUuY29tJTJGcGl4ZWwlMkZwLWNiNkMwekZGN2RXakkuZ2lmJTNGbGFiZWxzJTNEcC42ODM1NzE0LjM4NTg0MzUuMCUyQ2EuMjA0NjMuODQ0MTYuMTQwMzYzJTJDdS45NjguNjQweDM2MCUzQm1lZGlhJTNEYWQlM0JyJTNEMTQxNDQxMDE4NQ]]></Impression>
  <Impression><![CDATA[http://rc.rlcdn.com/361686.gif]]></Impression>
  <Creatives>
    <Creative id="140363" sequence="1">
      <Linear>
        <Duration>00:00:30</Duration>
        <TrackingEvents>
          <Tracking event="midpoint"><![CDATA[http://brxserv-22.btrll.com/v1/epix/6835714/3858435/84416/140363/AbQ93_XgMgCcRUTi_JAAFJwAACJEsAOuADAAAAAAAiyel-GCNFFg/event.mid]]></Tracking>
          <Tracking event="complete"><![CDATA[http://brxserv-22.btrll.com/v1/epix/6835714/3858435/84416/140363/AbQ93_XgMgCcRUTi_JAAFJwAACJEsAOuADAAAAAAAiyel-GCNFFg/event.end]]></Tracking>
        </TrackingEvents>
        <AdParameters></AdParameters>
        <VideoClicks>
          <ClickTracking><![CDATA[http://brxserv-22.btrll.com/v1/epix/6835714/3858435/84416/140363/AbQ93_XgMgCcRUTi_JAAFJwAACJEsAOuADAAAAAAAiyel-GCNFFg/event.click]]></ClickTracking>
        </VideoClicks>
        <MediaFiles>
          <MediaFile type="application/x-shockwave-flash" apiFramework="VPAID" height="360" width="640" delivery="progressive">
            <![CDATA[http://brxcdn3.btrll.com/69325/Brand-display.flv]]>
          </MediaFile>
        </MediaFiles>
      </Linear>
    </Creative>
  </Creatives>
</InLine>

and Here is the URL which I have successfully extracted from this XML.
  http://brxcdn3.btrll.com/69325/Brand-display.flv

So Now I want to stream this video file using Apache JMeter. Knowing that this video could be shown to the same IP(User) only 3 times a day. Any Idea about how to stream and perform a load testing to a video through JMeter?

A: with the current functionality, it is not possible to load test stream videos using Jmeter.


text:
Q: chroot question I am wondering if there is anyone out there that can explain an error that happens when I try to use debootstrap.
sudo debootstrap --arch i386 wheezy /srv/chroot/wheezy http://http.debian.net/debian
mknod: `/srv/chroot/wheezy/test-dev-null': Operation not permitted
E: Cannot install into target '/srv/chroot/wheezy' mounted with noexec or nodev

A: The error is self-explanatory: the filesystem that is mounted at (or that contains) /srv/chroot/wheezy has either the noexec or nodev mount flags. Try:
mount -o remount,rw,exec,dev /srv/chroot/wheezy

A: When you mount the filesystem or the partition, you need to include the following arguments:
-o exec,dev

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting Cipher Message Authentication Failed I am creating a middleware function to decrypt the request body of an api call but cannot seem to get it working. The body is encrypted and then base64 encoded before the request is made. Any help would be appreciated.
My curent function code:
            ciphertext, err := ioutil.ReadAll(r.Body)
            if err != nil {
                panic(err.Error())
            }
            ciphertext = decodeBase64(string(ciphertext))

            block, err := aes.NewCipher(keyString)
            if err != nil {
                panic(err.Error())
            }

            aesgcm, err := cipher.NewGCM(block)
            if err != nil {
               panic(err.Error())
            }

            nonce := make([]byte, aesgcm.NonceSize())
            clearStuff := make([]byte, len(ciphertext))
            plaintext, err := aesgcm.Open(clearStuff, nonce, ciphertext, nil)
            if err != nil {
                panic(err.Error())
            }
            fmt.Println(string(plaintext))

The key is:
var keyString = []byte("ECB518652A170880555136EA1F9752D6")

The error im getting is:
cipher: message authentication failed []

I'm pretty sure that the issue is stemming from ciphertext but I haven't been able to find a solution to the problem. I found a working solution here, but its using the seal to decrypt and that won't be possible in my case. So how can I get this done?


text:
Q: XML based template engine in Java? Can somebody suggest me a template engine (preferably written in Java) that could generate any text that I like from given XML input?

A: StringTemplate, FreeMarker

A: How about XSLt? You may use JAXP to do the processing.

A: You can use XSLT, it is not restricted to generating only XML output. It is restricted to XML input. Use the xsl:output tag do define the type of output you will be generating.
E.g. to generate text output
<xsl:output method="text" encoding="UTF-8"/>

To generate XML output with indentation
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>


text:
Q: restarting kernel in a loop in python I am trying to run a code using the api and the problem is it aborts the connection every few times and the only way to fix is to restart the kernel. I was wondering if there is any way in python to restart the kernel in try/except format inside a loop that runs every 5 minutes?
Something like this:
def execution():
try:

    main_code()
except:
    while check_connection != True:
        try:
            connection_command (to the api)
            break
        except:
            restart_kernel
    main_code()

In the above I am trying to see if the connection to api is good, if not restart the kernel and re-establish the connection.
Is it even possible?
Thank you


text:
Q: How to enable default-http-backend in Kubernetes in order to make Ingress work? I have a single node Kubernetes instance from microk8s. It is installed on a Ubuntu Server 20.20 running on Raspberry Pi 4.
I am tring to setup an ingress resource which cannot get working.
When I run kubectl describe ingress my-ingress I get this output
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)

From what I found in the internet, default-http-backend is something that should have been there by default, but when I run kubectl get pods -n kube-system I don't see it.
Question: How to enable default-http-backend in mikrok8s? Or more generally, how do I make ingress work?
Note: Ingress and DNS addons are enabled.

A: I have tested this behavior on my cluster. When I tried configuration provided by you I got below Warning:
@microk8s:~$ microk8s kubectl get ing
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress

Also if you will describe it you will get the same Warning.
@microk8s:~$ kk describe ing
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
Name:             hello-ing
Namespace:        default
Address:
    Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
  Host        Path  Backends
  ----        ----  --------
  *
              /hello   hello-svc:80   10.1.128.202:8080)

There is similar Github question regarding this error.

The output you see is just a default for when there is no default backend
https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/kubectl/pkg/describe/describe.go#L2393

However, it's working normally.
$ curl 127.0.0.1/hello
Hello, world!
Version: 1.0.0
Hostname: hello-647c466dbc-99rml

If you would add default backend you would get output like:
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
Name:             ingress
Namespace:        default
Address:          127.0.0.1
Default backend:  test2:80   10.1.128.205:80)
Rules:
  Host        Path  Backends
  ----        ----  --------
  *
              /hello   hello-svc:80   10.1.128.204:8080)

and Ingress looks like:
spec:
  backend:
    serviceName: test2
    servicePort: 80
  rules:
  - http:
      paths:
      - path: /hello
        backend:
          serviceName: hello-svc
          servicePort: 80

Though I cannot understand why something that worked half a year ago doesn't work now.
As new apiVersion changes a bit syntax, adding some features, parameters, etc, there might be situation when after update/upgrade some resources cannot be validated anymore by Kubernetes. As stated in this article.

An object definition in Kubernetes requires an apiVersion field. When Kubernetes has a release that updates what is available for you to use—changes something in its API—a new apiVersion is created.
However, the official Kubernetes documentation provides little guidance on apiVersion. This guide gives you a cheat sheet on which version to use, explains each version, and gives you the timeline of releases.

If you would only change apiVersion in your YAML, you would get error:
error: error validating "ingress.yaml": error validating data: [ValidationError(Ingress.spec.rules[0].http.paths[0].backend): unknown field "serviceName" in io.k8s.api.networking.v1.IngressBackend, ValidationError(Ingress.spec.rules[0].http.paths[0].backend): unknown field "servicePort" in io.k8s.api.networking.v1.IngressBackend]; if you choose to ignore these errors, turn validation off with --validate=false

To sum up, you got this <error: endpoints "default-http-backend" not found> as there was no default backend configured.
For more details you can check Kubernetes Api Docs.

A: The default backend is a fallback for when the ingress controller cannot match any of the rules.
apiVersion: networking.k8s.io/v1
spec:
  defaultBackend:
    service:
      name: tea-svc
      port:
        number: 80

Here is a complete example using v1
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
spec:
  defaultBackend:
    service:
      name: tea-svc
      port:
        number: 80
  rules:
    - host: cafe.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: tea-svc
                port:
                  number: 80

apiVersion: networking.k8s.io/v1beta1
Depending on the apiVersion of your yaml file, the default backend is specified in a different format.  It looks like you are using the beta format.
spec:
    backend:
        serviceName: tea-svc
        servicePort: 80

The NGINX Ingress Controller complains about v1beta1, so far it works in kubernetes 1.21.2, but as the warning says it won't soon:
networking.k8s.io/v1beta1 Ingress is deprecated in v1.19+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress


text:
Q: How to fail gradle build if asciidoctor got generating warning I'm using spring-restdocs to generate docs.
I'm wondering if any property to fail the asciidoctor task while getting similar warnings when building the doc.
Snippet http-response not found at ../../../build/generated-snippets/find-list-configuration-fixed-assets-source-response/http-response.adoc for operation find-list-configuration-fixed-assets-source-response
Snippet path-parameters not found at ../../../build/generated-snippets/update-currency/path-parameters.adoc for operation update-currency

A: Unfortunately, this is not possible. There is an open issue https://github.com/asciidoctor/asciidoctor-gradle-plugin/issues/154 since 2015. If you read through this issue you will find a workaround. Maybe it will help you. :-)

A: This is possible starting with asciidoctor 2.0, by configuring the fatalWarnings option of asciidoctorj.
Documentation of fatalWarnings:

Patterns for AsciidoctorJ log messages that should be treated as fatal errors. The list is empty be default. Use setFatalWarnings to clear any existing patterns or to decouple a task's configuration from the global configuration. Use fatalWarnings to add more patterns. Pass missingIncludes() to add the common use-case of missing include files.

Example:
asciidoctor {
  asciidoctorj {
      fatalWarnings missingIncludes()
  }
}


text:
Q: How to make image element go over navigation bar element This is what I am trying to do
I was wondering how to make something like this. I know how to make the navigation bar by making an unordered list ect. But I was wondering how to make something like this? At least could you please explain me what's the concept? I've been looking around w3 and stackoverflow but didn't manage to find a solution....

body{
    background-color:#ffffff;
    margin:0;
}

.mainBar ul{
    list-style: none;
    margin:0;
    margin-left: 150px;
    padding:0;
    overflow: hidden;
    background-color: #fff;
}

.mainBar li {
    float: left;
}

.mainBar li a{
    display: block;
    color: black;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-family: monospace;
    font-weight: bold;
    font-size: 16px;
    margin-top: 20px;
}

.mainBar li a:hover{
    color:#5293D5;
}

.mainBar li a:active{
    background-color:#fff;
}

.mainBar-pullRight{
    margin-left: 800px;
}

.barTitle{
    font-size: 35px;
    color: #2ecc71;
    margin-top:30px;
    padding:0;
    margin-bottom: 0;
}

.userBar ul{
    list-style: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #2ecc71;
    height: 70px;
}

.userBar li a{
    display: block;
    color: #ffffff;
    text-align: center;
    padding: 24px 26px;
    text-decoration: none;
    font-family: monospace;
    font-size: 12px;
}

.userBar li{
    float: left;
}

.d{
    float: right;
    font-size: 18px;
}

.userName{
    color: #ffffff;
    padding:24px 26px;
    text-align: center;
    font-family:"Courier New", Courier, monospace;
    font-weight: bold;
    font-size: 15px;
}

.profileShadow {
    width: 100px;
    height: 100px;
    margin-left: 150px;
    margin-top:5px;
    margin-bottom:5px;
    padding: 0;
    overflow: hidden;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    text-align: center;
  }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Instagram</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

 Instagram

ABOUT

TERMS

GUIDES

SUPPORT

tomislav

Change account

Set email

Log Out

Activity

Profile

Likes

A:
Check This one made now. Concept is setting image position absolute.

It's not responsive.

https://codepen.io/shafikul-islam/pen/XaEgmZ


text:
Q: Spark sql save dataframe to hive Hi I am using java to write some sparksql code.I have a class like below:
public class Item_Meta {

private String itemId;
private String category;
private String description;
private String properties;}

And then  I create a Dataset called dataset from a List of Item_Meta by below statement:
Dataset<Row> dataset = sparkSession.sqlContext().createDataFrame(list, Item_Meta.class)

And then called dataset.show(),I get this:
+--------+-----------+------+----------+
|category|description|itemId|properties|
+--------+-----------+------+----------+
|       1|      item1|     1|avgGrade1|
|       1|      item2|     2|avgGrade2|
|       1|      item3|     3|avgGrade3|
|       1|      item4|     4|avgGrade4|
|       1|      item5|     5|avgGrade5|
+--------+-----------+------+----------+

This looks OK as I have item id range from 1 to 5, category all 1,description is "item"+id...
Then I save this Dataset to hive,using below statement:
saveSql="INSERT OVERWRITE TABLE "+tableName+" PARTITION(ds='"+ds+"') select * from dataset"

It worked but When I query hive table,I get this:
+-------+--------+-----------+----------+----------+
|item_id|category|description|properties|        ds|
+-------+--------+-----------+----------+----------+
|      1|   item1|          1|avgGrade1|2017-10-26|
|      1|   item2|          2|avgGrade2|2017-10-26|
|      1|   item3|          3|avgGrade3|2017-10-26|
|      1|   item4|          4|avgGrade4|2017-10-26|
|      1|   item5|          5|avgGrade5|2017-10-26|
+-------+--------+-----------+----------+----------+

As you can see,the problem is datas are not in right colomn. How Can I solve this?

A: The order of columns is important while performing an INSERT OVERWRITE.
You'll have to change your query to look something like this:
INSERT OVERWRITE TABLE tablename
PARTITION(ds = '2017-10-26')
SELECT
  itemId,
  category,
  description,
  properties
from
  dataset


text:
Q: About Walter Rudin's "Principles of Mathematical Analysis Third Edition" pp.18-19 STEP4 (A5) I am reading "Principles of Mathematical Analysis Third Edition" by Walter Rudin.
At p.19 in this book, there is the following statement:

Let $w$ be a positive rational number, and $\alpha$ be a cut. Then, there is an integer $n$ such that $n w \in \alpha$ but $(n + 1) w \notin \alpha$. (Note that this depends on the fact that $\mathbb{Q}$ has the archimedean property!)

The definition of cuts is the following:

The members of $\mathbb{R}$ will be certain subsets of $\mathbb{Q}$, called cuts. A cut is, by definition, any set $\alpha \subset \mathbb{Q}$ with the following properties.

*

*$\alpha$ is not empty, $\alpha \neq \mathbb{Q}$.

*If $p \in \alpha$, $q \in \mathbb{Q}$, and $q < p$, then $q \in \alpha$.

*If $p \in \alpha$, then $p < r$ for some $r \in \alpha$.

I proved the above statement, but I'm not sure my proof is OK or not.
Is the following proof OK or not?

By definition of a cut, there exist $p$, $q$ such that $p \in \alpha$, $q \notin \alpha$, $q \in \mathbb{Q}$.
  By archimedean property of $\mathbb{Q}$, there exists $m \in \mathbb{Z}^{+}$ such that $-p < m w$. So $p > (-m) w$. By the property 2 of cuts, $(-m) w \in \alpha$.
  By archimedean property of $\mathbb{Q}$, there exists $n \in \mathbb{Z}^{+}$ such that $q < n w$. By the property 2 of cuts, $n w \notin \alpha$.
  So, $S:=\{m \in \mathbb{Z} | m w \in \alpha\}$ is not empty.
  So, $T:=\{m \in \mathbb{Z} | m w \notin \alpha\}$ is not empty.
  If $m_1 \in S$ and $m_2 \in T$, then $m_1 w < m_2 w$ by the property 2 of cuts.
$\therefore m_1 < m_2$.
$\therefore m_1$ is a lower bound of $T$.
$\therefore$ There exists $\min T$.
  Let $n := \min T - 1$.
  Then, $(n + 1) w \notin \alpha$, and $n w \in \alpha$.


text:
Q: Conversion to Dalvik format failed: Unable to execute dex: There is not enough space on the disk I tried updating my eclipse.ini file's contents at the end to -Xms512m -Xmx1024m,
I also tried updating the project.properties with dex.force.jumbo= true.
Also tried restarting eclipse, clean the project.
Problem is still there, what can be the solution to this problem. I have gone through the answers available, what can be the solution to this problem.


text:
Q: How to handle responses in Angular? That's a question about the fundamental things but I don't know how to return back response to the component depending on the action result: success or error, so I can execute related to them actions.
I have a component SignInComponent which collects all necessary information from the form and sends it to my AuthService which handles with my GraphQL requests (and for now redirecting and other things).
For a scenario that request is successful, everything works fine so far, but if there is any error response from API I need to have the errors and information about them in my SignInComponent. (if wrong credentials I should inform the user about that and so on)
I tried to return the value like:
signIn.subscribe({
        next: // actions for successful response,
        error: (err) => {return 'errors'} // from here
      })

and also I tried to throw an Error like this:
signIn.subscribe({
        next: // actions for successful response,
        error: (err) => {throw new Error('Oops')} // The Error
      })

and tried to catch it like this in my SignInComponent:
      try {
        this.authService.signIn(params);
      } catch (e) {
        // handling the error accordingly
      }

But all of that mentioned above didn't help me get response in my SignInComponent and be notified about the result status.
here is my code and I hope someone can tell me how to handle this situation using good practices.
auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { SignInMutation, SignInInput } from './sign-in.graphql';
import { SignUpMutation, SignUpInput } from './sign-up.graphql';
import { BehaviorSubject } from 'rxjs';

// TODO: To learn if observable is unsubscribed in services automatically. In Classes there is an Inteface OnDestroy for that

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  auth: BehaviorSubject<boolean> = new BehaviorSubject(false);

  constructor(
    private router: Router,
    private signInMutation: SignInMutation,
    private signUpMutation: SignUpMutation
  ) {
    this.isSignedIn();
  }

  signIn(params: SignInInput) {

    this.signInMutation.mutate(params)
      .subscribe({

        next: ({ data }) => {

          const signIn = data.signIn;
          const token = signIn.token;

          const { payload } = JSON.parse(atob(token.split('.')[1]));
          const currentUser = payload.userData;

          const localData = {
            currentUser,
            token
          };

          this.setLocalData(localData);

          this.router.navigate(['/dashboard']);
          this.auth.next(true);

        },

        error: (err) => {
          throw new Error('Ooops...');
        }

      });

  }

  signUp(SignUpInput: SignUpInput) {

    this.signUpMutation.mutate({ SignUpInput })
      .subscribe({
        next: console.log,
        error: console.log,
      });

  }

  private getLocalData(name: string): null | object | string {
    const data = localStorage.getItem(name);
    if (!data) { return null; }

    if (/^(\{).*(\})$/i.test(data)) {
      return JSON.parse(data);
    } else {
      return data;
    }
  }

  private setLocalData(data: object) {

    for (const key in data) {
      if (data.hasOwnProperty(key)) {
        const value = data[key];

        if (typeof value === 'object') {
          localStorage.setItem(key, JSON.stringify(data[key]));
        } else {
          localStorage.setItem(key, data[key]);
        }

      }
    }

  }

  signOut() {
    localStorage.removeItem('token');
    localStorage.removeItem('currentUser');
    this.router.navigate(['/']);
    this.auth.next(false);
  }

  private isSignedIn() {
    const token = this.getLocalData('token') as string;
    const checkFormat = (token && token.split('.').length === 3) ? true : null;

    if (token && checkFormat) {
      this.auth.next(true);
    }

  }

}

signInComponent
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { AuthService } from '../auth.service';
import { emailFormat } from '../../_helpers/custom-validation';

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.scss']
})
export class SignInComponent implements OnInit {

  signInForm: FormGroup;
  submitted: boolean;

  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
  ) { }

  ngOnInit(): void {
    this.signInForm = this.fb.group({
      email: ['', [emailFormat]],
      pwd: [''],
    });

    this.reset();
  }

  onSubmit(e) {
    e.preventDefault();
    this.submitted = true;

    if (this.signInForm.valid) {
      const params = {
        email: this.signInForm.value.email,
        password: this.signInForm.value.pwd
      };

      this.authService.signIn(params);

      this.reset();
    }

  }

  private reset() {
    this.signInForm.reset();
    this.submitted = false;
  }

}

Thank you all in advance!

A: So this is more of an rxjs issue rather than Angular issue.
this.signInMutation.mutate(params) returns an Observable which contains wrapped data of the server response. In your case, having signin() method subscribe to this observable is not a good idea.
Instead, a common practice would simply return the observable straight away:
signIn(params: SignInInput) {
  return this.signInMutation.mutate(params);
}

Now you might say there are some data post-processing work you want to do such as things you did in your original subscribe() clause.
Okay, let's move them into a pipe()
function signIn(params: SignInInput) {
  return this.signInMutation.mutate(params).pipe(
    tap(data => {
      const signIn = data.signIn;
      const token = signIn.token;

      const { payload } = JSON.parse(atob(token.split('.')[1]));
      const currentUser = payload.userData;

      const localData = {
        currentUser,
        token,
      };

      this.setLocalData(localData);

      this.router.navigate(['/dashboard']);
      this.auth.next(true);
    }),
  );
}

Okay, now let's move back to your component code
onSubmit(e) {
  // ...

  this.authService.signIn(params).subscribe({
    error: err => {
      // handle your err here, where the handler belongs
      this.errorMessage = 'oops, errors here! ' + err.message
    }
  })
}

Basically, this is one of the most common practices for handling rxjs based remote responses in Angular. Of course, there are a few other things to worry about, such as unsubscribe() to this subscription when your component gets destroyed. But I don't want to go out of topic.
Having your Angular services return observables directly also helps you share & compose them further with other services or rxjs based candidates, such as reactive forms.

A: As you have already a auth boolean flag in your AuthService, you can opt to add a error flag with the error message.
Your components, or other services could subscribe to it to retrieve the current state.
This approach (in a state management way), give your more flexibility, to retrieve the different state (auth yes/no, error/no error...). You could also add a loading flag, which is set to yes during authentication process.
export class AuthService {
  auth = new BehaviorSubject<boolean>(false);
  error = new BehaviorSubject<string>(null);

  auth$ = this.auth.asObservable();
  error$ = this.error.asObservable();

  ...

  signIn(params: SignInInput) {
    this.auth.next(false);

    this.signInMutation.mutate(params).subscribe(
      data => {
        ...
        this.auth.next(true);
        this.error.next(null);
      },

      error => {
        this.error.next('error message');
      }
    );
  }
}

inside component.ts, we can subscribe to error message to do some specific actions, but it's not required. Just use async pipe inside template is ok to display a simple message :
export class AppComponent {
  error$ = this.authService.error$;
  ...

  constructor(...) {
    // manually subscribe to do some other tasks...
    // but it's not required to only display inside template (see below)
    this.error$.subscribe(error => {
      if (error) {

      }
    });

    // becareful to manage unsubscription (not done here to keep code simple)
  }
}

Inside template, we can display a message in case of error:
 <p *ngIf="error$ | async as error">{{ error }}</p>


text:
Q: Protect python source code that runs as API The company has built a python API with Machine Learning modules and we want to install this API on our customers' local server.
Of course, we don't want them to read the code, but when I try to use pyinstaller or pyarmor the fastAPI server can't understand the code anymore.
Is there a way to obfuscate or compile the python code and make it work with a server like fastapi with the uvicorn command?


text:
Q: HTML/CSS position elements I am trying to do this:

and mine looks like this:

Not the most beautiful thing.
My questions are:

*

*We have a header with logo, search bar, menus and a button. How can i stack them all inline?

*On the div with the background image - how can I position the headline like the one in the original site?

A: 1) Have a look at the Navbar component documentation. Items should already be inline if implemented correctly. You can use the navbar-left and navbar-right classes to position items in the navbar.
2) You'll notice the large centre text starts at the same position as the navbar logo. This is because of the container class. I suggest you analyse some examples to see how to correctly implement the container.
After that, if you're still struggling add your styles.css to your pastebin post or better still create a Codepen - this would allow someone to be more helpful.

A: 1- you can write float:left; or float:right; ? look for this float
2-for position an element you must create a relative div later inside create absolute div.. and you can specify settlement coordinates with top right bottom left.. look here position

A: I would say float is not good practice to use . Unless you really have no choice to use.
But based on how I look at it.
It's achievable using flex.
Put a display:flex on your main div
Then as for your other elements . Use display:flex-grow
It's advantageous using flex. ,  not only it wil solve your problem.  It makes your site responsive.
Cheers

A: [![if you need all navigation item in one line. you have to make display:inline-block,for navigation.

change your code to:

                        <input type="text" placeholder="Find Freelancers" id="searchButton">

Browse

How it works

                            Sign Up

                            Login

                <button type="button" id="buttonHeader">Become a freelancer</button>

/*add below css*/

.nav-wrap ul li{display:inline-block;}][1]][1]


text:
Q: What's wrong with singleton? Do not waste your time with this question. Follow up to: What is so bad about singletons?

Please feel free to bitch on Singleton.
Inappropriate usage of Singleton may cause lot of paint. What kind of problem do you experienced with singleton? What is common misuse of this pattern?

After some digging into Corey's answer I discovered some greate articles on this topic.

*

*Why Singletons Are Controversial

*Performant Singletons

*Singletons are Pathological Liars

*Where Have All the Singletons Gone?

*Root Cause of Singletons

A: There's nothing inherently wrong with the Singleton pattern. It is a tool and sometimes it should be used.

A: Sometimes it can make your code more tightly coupled with the singleton class being refrerenced directly by name from different parts of your codebase. So, for example, when you need to test some part of your code and it references a singleton from a diferent part of the code you cannot easily fake that dependency with a mock object.

A: I think a more appropriate question might be: In what situations is the use of a SIngleton Pattern inappropriate?  Or what have you seen that uses a Singleton that shouldn't.

A: There's nothing wrong with a singleton in itself, and as a pattern it fills a vital role in recognising the need for certain objects to only be created a single time.
What it is frequently used for is a euphemism for global variables as an attempt to get around global variable stigma, and it is this use that is inherently wrong. If a global variable happens to be the correct solution, using a singleton won't improve it. If it is (as is fairly common) incorrect to use a global variable, wrapping it in a singleton won't make it any more correct.

A: I haven't been exposed to the Singleton as much as some of the other posters have, but nearly all implementations that I have seen (in C#) could have been achieved with static classes/methods. I suppose you could argue that a static class is an implementation of the singleton pattern, but that's not what I've been seeing. I've been seeing people build up and manage these Singleton classes/objects when all they really needed was to use the static keyword.
So, I wouldn't say the Singleton pattern is bad. I'd say it's kinda like guns. I don't think guns are bad, but they can most certainly can be used inappropriately.

A: Basically singleton is a way to have static data and pretend it is not really static.
Of course I use it, but try to not abuse it.

A: One basic problem with the original GoF design is the fact that the destructor isn't protected. Anyone with a reference to the singleton instance is free to destroy the singleton.
See John Vlissides update "To Kill A Singleton" in his book "Pattern Hatching" (Amazon link).
cheers,
Rob

A: Most of the singleton patterns that I see written aren't written in a thread safe manner.  If written correctly, they can be useful.


text:
Q: Struggling with Excel data I currently have data in the below format, these details are just examples.
SKU   IMAGE URL         IMAGE URL
1234
1234
1234
5678
5678
5678
I need to get the data so that I have each SKU once in the first column with all the image URLs in the image URL column for each SKU. I thought a pivot table would do it but I'm struggling.


text:
Q: How to computer $\int_0^1\log(\sin \pi x)\text{d}x$ under complex methods.
the below integral is coming from M.Stein's complex analysis. chapter 3 exercise 9.
Show that
$$\int_0^1\log(\sin \pi x)\text{d}x=-\log 2$$
use the contour shown in the above figure
Then I recall the definition of $\log(z)$,it must be defined on a simply connected domain $\Omega$ with $1\in \Omega$ and $0 \not\in \Omega$. In order to use the above contour to computer the integral. maybe consider $\int_{\gamma}\log(\sin \pi z)\text{dz}$,where $\gamma$ is the contour. but for $z=0$, there is no definition.
I think the author arrange the exercise here must expect the reader use residue formula to computer it. but I don't know how to. thanks very much


text:
Q: Calling a seeding method asynchronously in ASP.net MVC I hope this question isn't too broad, but I've run into an issue in design when using the Entity Framework.
Basically my company wants our application to be able to manually upload valid databases and seed them at will, instead of having to run update database to do so. I got this aspect working easily enough by simply moving the seeding method out of the configuration file and overloading the constructor to accept a database from the uploaded path.
However, the next task that was asked of me led me to some design issues. They want me to provide an indicator on the client side that this seeding was occurring and perhaps how far in it is, through a progress bar/text output. Because the seeding method is running synchronously this has proved troublesome because the client side will be locked up for the duration of it being run.
As the seeding method takes about 20 minutes to complete this isn't ideal as the client would be left unsure of how long they will have to wait before they can do something again. I tried to implement it using an async controller but it complained that the seeding method is of type void. The actionresult that's being called on the file upload looks something like this
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {

        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            string date = DateTime.Now.ToString("MM-dd-yyyy-HHmm-");
            fileName = date + fileName;
            var path = Path.Combine(Server.MapPath("~/bin/SampleData"), fileName);
            file.SaveAs(path);
            //create config instance and seed path
            Reseed reseed = new Reseed(fileName);
            reseed.Seed(db);
            GetTimeStamp(DateTime.Now);
        }

        return RedirectToAction("Index");
    }

Does anyone know if there would be a good way to design this in a way that it could be run asynchronously?

A: Seeding asynchronously on the server will only serve to free up a thread for the duration of the process (if it is IO bound), in order to return you will end up waiting for this to finish up anyway (if you were to make the controller async).
Its not a good candidate for parallelising as its not a compute bound operation either.
Either way, you want to get progress back up to the client so there are a few approaches and technologies worth considering:
Web sockets, using SignalR,  whereby you can have a connection from the server to the client and push content on the connection to the client. This downgrades to long polling where the software doesnt support it. Might be a bit overkill as its bidirectional.
Server Sent Events, which has less overhead than Web sockets and is half-duplex from server to client, it allows pushing of content from server to client also
A slightly different approach would be returning/redirecting from the screen and sending an email to the user indicating when  the process has finished. You could kick off a scheduled task, or send a command to something out of process to start a batch process.


text:
Q: jQuery Validation Issue - I want to validate a field for these constraints :- Please help me in writing the regular expression for the constraints as follows :-

*

*First letter should not be blank

*Permissible characters are alphabets and numbers

*Apart from numbers and characters, two more characters are allowed which are - and /

*Last character cannot be blank

Thanks in advance for the help.

A: You can use this regex:
^/^[A-Z0-9][A-Z0-9\/-]*[A-Z0-9]$/i

Though it isn't clear what you mean by blank. Space isn't even allowed in your character set.


text:
Q: Plot using mean and standard error values using ggplot2 Here's my data:
   year   means   stder
1 A_1996 4.1291 0.19625
2 B_1997 3.4490 0.18598
3 C_1998 4.1166 0.15977
4 D_1999 3.6500 0.15093
5 E_2000 3.9528 0.14950
6 F_2001 2.7318 0.13212

This is all the data I have. I'd like to plot these using the ggplot2 package, if possible. X axis will be year, and Y axis will be means. Each year will have one point -its corresponding mean value, with the respective standard error values as the "whiskers" around that point. How would I do this using the ggplot() function?
I think I'm mainly confused on how to put the standard error data into the ymin and ymax inputs.
I started looking here, but the beginning data is different, so I'm a little confused.
Plotting means and error bars (ggplot2)

A: Simple plot using general ggplot2 commands:
library(ggplot2)
df$year <- as.numeric(gsub(".*_", "", df$year))
ggplot(df, aes(year, mean)) +
    geom_point() +
    geom_errorbar(aes(ymin = mean - stder,
                      ymax = mean + stder))

Same plot with fancier visuals:
ggplot(df, aes(year, mean)) +
    geom_point(size = 3) +
    geom_errorbar(aes(ymin = mean - stder,
                      ymax = mean + stder),
                  width = 0.5, size = 0.5) +
    theme_bw() +
    labs(x = "Year",
         y = "Mean",
         title = "Change in mean over the period")


text:
Q: Angular server side dynamically rendering html template from repository and custom components I would like to load a custom Component with the Template defined from a repository. This template html contains the tags of the components. Example:

        <app-controls-list></app-controls-list>

    <app-controls-categories-list></app-controls-categories-list>

     <app-controls-edit></app-controls-edit>

The main goal is to insert the HTML into a component and then activate the creation of the components inside (appcontrols-categories-list, app-controls-edit, app-controls-list). It has to work with AOT (for SSR). Is it possible?


text:
Q: Use API key with googleapis androidpublisher I'm building a server locally with NPM to get information from google play publisher.
I'm trying to user API key but I'm unable to connect.
const publish = google.androidpublisher({
version: 'v3',
auth: '****'
});
From looking in the internet I'm seeing that I need to use OAuth2.
The problem is that I want this as a service and only a server side without user interaction.
Is there a way to do it?

A: Yes, you must use Service Account Credentials as outlined here


text:
Q: Return Promise From REST Call I'm trying to invoke a REST call and return a promise so I can manipulate the data afterwhich.
var self = this;
var returnPromise;
returnPromise = self.httpService.testService();
returnPromise.then(function(result){
 console.log(result);
});

My REST service is located in another file which has the following:
 testService() {
    console.log("start of testService");

    var request = require('request');
    var user = "test";
    var ipadd = "127.0.0.1";

    request({

        url: 'https://' + 'LocalHost' + '/URLOFWEBSERVICE',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        form: {
            userID: user,
            userIpAddress: ipadd
        }
    }, function(error, response, body) {
        if (error) {
            console.log(error);
        } else {
            console.log(response.statusCode, body);
            var newPro = new Promise(function(fulfill, reject) {
                fulfill(body);
            });

            console.log(newPro);
            return newPro;

        }
    });
}

I'm able to print out response.stateCode , body( REST result) and the "invoked fulfill" console is printed out.
The problem lies with the

returnPromise.then

in the first page, in which ".then" returns me undefined.
At first I thought that it might be the promise has been called before the REST returns me a response. So, I thought of doing a timeout function to test.
setTimeout(
function(){
  console.log(returnPromise);
}
, 5000);

But even so, returnPromise returns me "undefined".

A: If you expect a function to return a promise, it should return a promise
your testService does not return anything
this does:
testService() {
    console.log("start of testService");
    var request = require('request');
    var user = "test";
    var ipadd = "127.0.0.1";
    return new Promise(function(fulfill, reject) {
        request({
            url: 'https://' + 'LocalHost' + '/URLOFWEBSERVICE',
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            form: {
                userID: user,
                userIpAddress: ipadd
            }
        }, function(error, response, body) {
            if (error) {
                // reject the promise, handle with .catch
                reject(error);
            } else {
                console.log(response.statusCode, body);
                fulfill(body);
            }
        });
    });
}

That can be called as
// var self = this; // why? not needed in the code shown
// var returnPromise; // why? it's not needed in the code shown

this.httpService.testService()
.then(function(result) {
    console.log(result);
})
.catch(function(err) {
    // handle your errors here
});


text:
Q: How can I access the DOM elements within an iFrame I am writing a jQuery Plugin that needs to be able to run against DOM elements within an iFrame.  I'm just testing this locally right now (ie url is file://.../example.html) and in Chrome I keep hitting "SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a cross-origin frame." and in Safari I just get an empty document.
Given that both the parent file and the iFrame's file are coming off my local disk (in development) and will be coming off the same server (in production) I'd have thought that I'd not be subject to the cross-origin issues.
Is there a way I can convince the browser that my local files are actually of the same domain?
<aside>Interestingly in Safari, using the console directly, I can type $("iframe").get(0).contentDocument.find("ol") and it happily finds my list. In Chrome this same line throws the security error just as if it were being executed.</aside>
Update
Based on the suggestions below I have fired up a simple local web-server to test this and am now not getting the cross-origin error - yay - but neither am I getting any content.
My Javascript looks like
$(document).ready(function(){
  var myFrame = $("iframe"),
      myDocument = $(myFrame.get(0).contentDocument),
      myElements;
  myDocument.ready(function(){
    myElements = myDocument.find("ul, ol");
    console.debug("success - iFrame", myFrame, "document", myDocument, "elements", myElements);
  });
});

The myDocument.ready is there just to ensure that the iFrame's document is ready - in reality it makes no difference.
I always end up with myElements being empty. ([] in safari or jQuery.fn.init[0] in Chrome)
But if I manually type this into the console:
$($("iframe").get(0).contentDocument).find("ol, ul")

I get my lists as expected. This is now the case in both Safari and Chrome.
So my question becomes: why can't my script see the DOM elements but the same code when entered directly into the browser's console can happily see the DOM elements?

A: Chrome has default security restrictions that don't allow you to access other windows from the hard disk even though they are technically the same origin.  There is a flag in Chrome that can relax that security restriction (command line argument on Windows is what I remember), though I wouldn't recommend running with that flag for more than a quick test.  See this post or this article for info about the command line argument.
If you run the files off a web server (even if it's a local web server) instead of your hard drive, you won't have this issue.
Or, you could test in other browsers that aren't as restrictive.

Now that you've changed the question into something different, you have to wait for an iframe window to load before you can access the content in it and you can't use jQuery's .ready() on a different document (it doesn't work on another document).
$(document).ready(function() {
    // get the iframe in my documnet
    var iframe = document.getElementById("testFrame");
    // get the window associated with that iframe
    var iWindow = iframe.contentWindow;

    // wait for the window to load before accessing the content
    iWindow.addEventListener("load", function() {
        // get the document from the window
        var doc = iframe.contentDocument || iframe.contentWindow.document;

        // find the target in the iframe content
        var target = doc.getElementById("target");
        target.innerHTML = "Found It!";
    });
});

Test page here.

EDIT: Upon further research, I found that jQuery will do some of this work for you like this and the jQuery solution appears to work in all the major browsers:
$(document).ready(function() {
    $("#testFrame").load(function() {
        var doc = this.contentDocument || this.contentWindow.document;
        var target = doc.getElementById("target");
        target.innerHTML = "Found It!";
    });
});

Test page here.
In looking at the jQuery implementation for this, all it is really doing is setting up a load event listener on the iFrame itself.

If you want to know the nitty gritty details that went into debugging/solving the first method above:
In my trying to solve this issue, I discovered some pretty bizarre things (in Chrome) with iFrames.  When you first look in the window of the iframe, there is a document and it says that its readyState === "complete" such that you think it's done loading, but it's lying.  The actual document and actual <body> tag from the document that is being loaded via URL into the iframe is NOT actually there yet.  I proved this by putting a custom attribute on the <body data-test="hello"> and checking for that custom attribute.  Lo and behold.  Even though document.readyState === "complete", that custom attribute is not there on the <body> tag.  So, I conclude (at least in Chrome) that the iFrame initially has a dummy and empty document and body in it that are not the actual ones that will be in place once the URL is loaded into the iFrame.  This makes this whole process of detecting when it's ready to be quite confusing (it cost me hours figuring this out).  In fact, if I set an interval timer and poll iWindow.document.body.getAttribute("data-test"), I will see it show as undefined repeatedly and then finally it will show up with the correct value and all of this with document.readyState === "complete" which means it's completely lying.
I think what's going on is that the iFrame starts out with a dummy and empty document and body which is then replaced AFTER the content starts loading.  On the other hand, the iFrame window is the real window.  So, the only ways I've found to actually wait for the content to be loaded are to monitor the load event on the iFrame window as that doesn't seem to lie.   If you knew there was some specific content you were waiting for, you could also poll until that content was available.  But, even then you have to be careful because you cannot fetch the iframe.contentWindow.document too soon because it will be the wrong document if you fetch it too soon.  The whole thing is pretty broken.  I can't find any way to use DOMContentLoaded from outside the iFrame document itself because you have no way of knowing then the actual document object is in place to you can attach the event handler to it.  So ... I settled for the load event on the iFrame window which does seem to work.

If you actually control the code in the iFrame, then you can trigger the event more easily from the iFrame itself, either by using jQuery with $(document).ready() in the iFrame code with it's own version of jQuery or by calling a function in the parent window from a script located after your target element (thus ensuring the target element is loaded and ready).

Further Edit
After a bunch more research and testing, here's a function that will tell you when an iFrame hits the DOMContentLoaded event rather than waiting for the load event (which can take longer with images and style sheets).
// This function ONLY works for iFrames of the same origin as their parent
function iFrameReady(iFrame, fn) {
    var timer;
    var fired = false;

    function ready() {
        if (!fired) {
            fired = true;
            clearTimeout(timer);
            fn.call(this);
        }
    }

    function readyState() {
        if (this.readyState === "complete") {
            ready.call(this);
        }
    }

    // cross platform event handler for compatibility with older IE versions
    function addEvent(elem, event, fn) {
        if (elem.addEventListener) {
            return elem.addEventListener(event, fn);
        } else {
            return elem.attachEvent("on" + event, function () {
                return fn.call(elem, window.event);
            });
        }
    }

    // use iFrame load as a backup - though the other events should occur first
    addEvent(iFrame, "load", function () {
        ready.call(iFrame.contentDocument || iFrame.contentWindow.document);
    });

    function checkLoaded() {
        var doc = iFrame.contentDocument || iFrame.contentWindow.document;
        // We can tell if there is a dummy document installed because the dummy document
        // will have an URL that starts with "about:".  The real document will not have that URL
        if (doc.URL.indexOf("about:") !== 0) {
            if (doc.readyState === "complete") {
                ready.call(doc);
            } else {
                // set event listener for DOMContentLoaded on the new document
                addEvent(doc, "DOMContentLoaded", ready);
                addEvent(doc, "readystatechange", readyState);
            }
        } else {
            // still same old original document, so keep looking for content or new document
            timer = setTimeout(checkLoaded, 1);
        }
    }
    checkLoaded();
}

This is simply called like this:
// call this when you know the iFrame has been loaded
// in jQuery, you would put this in a $(document).ready()
iFrameReady(document.getElementById("testFrame"), function() {
    var target = this.getElementById("target");
    target.innerHTML = "Found It!";
});

A:
Given that both the parent file and the iFrame's file are coming off my local disk (in development) and will be coming off the same server (in production) I'd have thought that I'd not be subject to the cross-origin issues.

"Please open this perfectly harmless HTML document that I have attached to this email." There are good reasons for browsers to apply cross-domain security to local files.

Is there a way I can convince the browser that my local files are actually of the same domain?

Install a web server. Test through http://localhost. As a bonus, get all the other benefits of an HTTP server (such as being able to use relative URIs that start with a / and develop with server side code).


text:
Q: cannot start any docker containers sometime anymore Sometimes after:

*

*a container has created a lot of threads

*I restarted a container several time because it crashed

it got when starting (docker-composer up) an arbitrary container:
ERROR: for container_name Cannot start service container_name: OCI runtime create failed: container_linux.go:380: starting container process caused: process_linux.go:385: applying cgroup configuration for process caused: mkdir /sys/fs/cgroup/memory/docker/99dec670f659c8411b960d99bbafc13f0429e178b1ea8417e6cfc8d56182291b: permission denied: unknown

There is neither a high load (<100) in number of thread not in memory usage of the server reported by docker stats``or htop`.
The problem can not be fixed by restarting the docker process (docker.service and docker.socket) - but by restarting the (virtual) machine.
Also after sometime (2 days / weekend) of not doing anything on the server (but keep other containers running) the problem disappears.


text:
Q: Is Inversion of Control a pattern? According to some information, IoC is a principle.
https://www.tutorialsteacher.com/ioc/introduction
But elsewhere it is a pattern.
What is Inversion of Control?

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code

Which one is right?

A: Principles are the guiding set and when principles are followed to solve problems patterns are evolved.
Principles and patterns are inseparable. Usually when we observe a large set of problem  then we can see categories in which we can categorize the problems. Over a period of time software development community has seen many problems and also have observed categories. Such major categories are Object Creation, Behavior addition and modification, and structuring code to avoid messy classes. Now when people followed good principles to solve these problem, again it was observed that solutions follow a kind of pattern. Such patterns were grouped togather by famous GOF in a book.
IoC is a principle, many software implement the principle like Spring. IoC solves many code messups and maintainability issues. If someone calls it a pattern its not wrong to say so. There is not much gain in arguing if its a pattern or principle as Both are inseparable.


text:
Q: Get up-sell product in Magento 2 I am trying to get up-sell product in Magento 2 via objectManager. Current product id and name is returning well but up-sell product return empty.
<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
    echo $product->getId();
    echo $product->getName();
    //echo $currentProduct->getSku();
if ($currentProduct = $product->getCurrentProduct()) {
    $upSellProducts = $currentProduct->getUpSellProducts();
    print_r($upSellProducts);

    if (!empty($upSellProducts)) {
        echo '
UpSell Products
';
        foreach ($upSellProducts as $upSellProduct) {
            echo $upSellProduct->getSku() . '
';
        }
    }
}
?>

A: By Factory Method:
protected $_registry;

public function __construct(
    ...
    \Magento\Framework\Registry $registry,
    ...
) {
    $this->_registry = $registry;
}

public function getCurrentProduct()
{
    return $this->_registry->registry('current_product');
}

public function getUpsellProducts()
{
    $currentProduct = $this->getCurrentProduct();
    $upsellProducts = $currentProduct->getUpSellProducts();

    return $upsellProducts;
}

By ObjectManager:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$currentProduct = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product

if ($currentProduct) {

    $upsellProducts = $currentProduct->getUpSellProducts();

    if (!empty($upsellProducts)) {
        echo '
UpSell Products
';
        foreach ($upsellProducts as $upsellProduct) {
            echo $id = $upSellProduct->getSku();
        }
    }
}

Note: With this code, you cannot get full model of product. For that, you need to load product model by upsell product Id.

A: $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
echo $product->getId();
echo $product->getName();
//echo $currentProduct->getSku();
if ($currentProduct = $product) {
    $upSellProducts = $currentProduct->getUpSellProducts();
    //print_r($upSellProducts);

    if (!empty($upSellProducts)) {
        echo '
UpSell Products
';
        foreach ($upSellProducts as $upSellProduct) {
            echo $upSellProduct->getSku() . '
';
        }
    }
}


text:
Q: How to get permutations with odd transpositions? I have an algorithm with all possible permutations, can i get permutations with only odd transpositions. Or simplify the algorithm to find only such permutations. For example, array {1,2,3,4}. If I move one element I will get only one transposition, and it odd tansposition: {2,1,3,4}, {3,2,1,4}, {4,2,3,1}, {1,3,2,4}, {1,4,3,2}, {1,2,4,3}.
class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[] { 1, 2, 3, 4 };
            ShowAllCombinations(arr);
            Console.Read();
        }
        public static void ShowAllCombinations<T>(IList<T> arr, string current = "")
        {
            if (arr.Count == 0)
            {
                Console.WriteLine(current);
                return;
            }
            for (int i = 0; i < arr.Count; i++)
            {
                List<T> lst = new List<T>(arr);
                lst.RemoveAt(i);
                ShowAllCombinations(lst, current + arr[i].ToString());
            }
        }
    }

This algorithm gives all permutations, but not only odd ones.

A: Your ShowAllCombinations method is inconvenient, the string should stay a list so you can process the elements.
Once you have a complete list of elements, you can "unpermute" back to the natural order and count the number of swaps. This assumes unique elements (no repetitions) and that the list is one-based. Note that this method permutes the list, will want to create a copy somewhere.
public void SwapCount(List<int> arr)
{
    var swapCount = 0;

    // double for loop, compare the value at the outer position
    // to the value at the inner position.
    for (var i=0; i<arr.Count; i++)
    {
        // Start at the index after the outer loop
        for (var j=i+1; j<arr.Count; j++)
        {
            // If the inner value is what the outer value
            // is supposed to be then swap it.
            if (arr[j] == i+1)
            {
                var t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;
                swapCount++;
            }
        }
    }

    Console.WriteLine($"swap count: {swapCount}");
}

output
> SwapCount(new List<int>() { 1, 2, 3, 4 })
swap count: 0
> SwapCount(new List<int>() { 2, 1, 3, 4 })
swap count: 1
> SwapCount(new List<int>() { 1, 3, 2, 4 })
swap count: 1
> SwapCount(new List<int>() { 1, 3, 4, 2})
swap count: 2
>

This is ~ O(n^2), but I'm assuming performance is not so important here. You can find more efficient algorithms here: Parity of permutation with parallelism


text:
Q: Computer disconnects from WiFi and doesn't reconnect automatically I'm running Ubuntu Desktop 19.10 and mostly use it as a server. Periodically (every few days) it drops off wifi and doesn't reconnect. Rebooting wi-fi AP doesn't help. Only manual reconnect/suspend&resume/reboot of the ubuntu works.
None other device in my home has the same problem. How do I fix it so that it reconnects back automatically?
This is what I have in my journal at the time wi-fi drops:
Dec 09 12:19:44 dell avahi-daemon[1858]: Interface wlp3s0.IPv4 no longer relevant for mDNS.
Dec 09 12:19:44 dell NetworkManager[1857]: <info>  [1575922784.2641] manager: NetworkManager state is now CONNECTED_LOCAL
Dec 09 12:19:44 dell avahi-daemon[1858]: Leaving mDNS multicast group on interface wlp3s0.IPv4 with address 192.168.86.84.
Dec 09 12:19:44 dell NetworkManager[1857]: <info>  [1575922784.2637] device (wlp3s0): state change: need-auth -> failed (reason 'no-secrets', sys-iface-state: 'managed')
Dec 09 12:19:44 dell avahi-daemon[1858]: Withdrawing address record for 192.168.86.84 on wlp3s0.
Dec 09 12:19:44 dell NetworkManager[1857]: <warn>  [1575922784.2637] device (wlp3s0): no secrets: No agents were available for this request.
Dec 09 12:19:44 dell avahi-daemon[1858]: Interface wlp3s0.IPv6 no longer relevant for mDNS.
Dec 09 12:19:44 dell NetworkManager[1857]: <info>  [1575922784.2609] device (p2p-dev-wlp3s0): supplicant management interface state: 4-way handshake -> disconnected
Dec 09 12:19:44 dell avahi-daemon[1858]: Leaving mDNS multicast group on interface wlp3s0.IPv6 with address fe80::d624:4b28:c9fa:65e4.
Dec 09 12:19:44 dell NetworkManager[1857]: <info>  [1575922784.2589] manager: NetworkManager state is now CONNECTING
Dec 09 12:19:44 dell avahi-daemon[1858]: Withdrawing address record for fe80::d624:4b28:c9fa:65e4 on wlp3s0.
Dec 09 12:19:44 dell sh[2118]: sendto: Network is unreachable
Dec 09 12:19:44 dell NetworkManager[1857]: <info>  [1575922784.2569] dhcp4 (wlp3s0): state changed bound -> done
Dec 09 12:19:44 dell dbus-daemon[1855]: [system] Activating via systemd: service name='org.freedesktop.nm_dispatcher' unit='dbus-org.freedesktop.nm-dispatcher.service' requested by ':1.15' (
Dec 09 12:19:44 dell whoopsie[2094]: [12:19:44] Cannot reach: https://daisy.ubuntu.com
Dec 09 12:19:44 dell whoopsie[2094]: [12:19:44] offline
Dec 09 12:19:44 dell sh[2118]: sendto: Network is unreachable
Dec 09 12:19:44 dell NetworkManager[1857]: <info>  [1575922784.2569] dhcp4 (wlp3s0): canceled DHCP transaction
Dec 09 12:19:44 dell NetworkManager[1857]: <info>  [1575922784.2568] device (wlp3s0): state change: activated -> need-auth (reason 'supplicant-disconnect', sys-iface-state: 'managed')
Dec 09 12:19:44 dell NetworkManager[1857]: <info>  [1575922784.2566] device (wlp3s0): Activation: (wifi) disconnected during association, asking for new key
Dec 09 12:19:44 dell NetworkManager[1857]: <info>  [1575922784.2544] device (wlp3s0): supplicant interface state: 4-way handshake -> disconnected
Dec 09 12:19:44 dell wpa_supplicant[1856]: dbus: wpa_dbus_property_changed: no property SessionLength in object /fi/w1/wpa_supplicant1/Interfaces/0
Dec 09 12:19:44 dell wpa_supplicant[1856]: wlp3s0: CTRL-EVENT-SSID-TEMP-DISABLED id=0 ssid="NSA Surveillance Van" auth_failures=1 duration=10 reason=WRONG_KEY
Dec 09 12:19:44 dell NetworkManager[1857]: <warn>  [1575922784.2259] sup-iface[0x55bd46b33930,wlp3s0]: connection disconnected (reason 2)
Dec 09 12:19:44 dell wpa_supplicant[1856]: wlp3s0: WPA: 4-Way Handshake failed - pre-shared key may be incorrect
Dec 09 12:19:44 dell wpa_supplicant[1856]: wlp3s0: CTRL-EVENT-DISCONNECTED bssid=70:3a:cb:00:60:b1 reason=2
Dec 09 12:19:44 dell kernel: wlp3s0: deauthenticated from 70:3a:cb:00:60:b1 (Reason: 2=PREV_AUTH_NOT_VALID)

My wi-fi card:
  *-network
       description: Wireless interface
       product: Wireless 3165
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: wlp3s0
       version: 79
       serial: 70:1c:e7:24:02:48
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwlwifi driverversion=5.3.0-23-generic firmware=29.1654887522.0 ip=192.168.86.84 latency=0 link=yes multicast=yes wireless=IEEE 802.11
       resources: irq:140 memory:df700000-df701fff


text:
Q: Proving that a process is class DL Let $(X_{t})$
  be a stochastic process with $X_{t}\sim\mathcal{N}(\xi_{t},\sigma_{t}^{2})$
  where $\xi_{t}\downarrow0$
  and $\sigma_{t}^{2}\uparrow1/2$.
What would be the most straightforward way of showing that
$\left\{ \mbox{exp}(X_{T}^{2}-T):T\;\mbox{stopping time},\; T\leq t\right\}$
is Uniformly integrable for each $t\geq0$?
That is, that $\mbox{exp}(X_{t}^{2}-t)$ is Class DL.
I've been trying to show that it is bounded in $L^2$ by using that I know the density of the normal distribution. But I have not succeeded in this.
Note: I realize that it's not necessarily a (local) martingale. I'm just trying to familiarize myself with notion of being "Class DL". If someone has another similar looking example - e.g. $(X_t)$ being a Brownian motion - I'm also happy to see that.


text:
Q: Printing a javafx WebEngine's content on multiple pages I want to print the content of a WebEngine:
PrinterJob job = PrinterJob.createPrinterJob();
job.getJobSettings().setJobName("Print WebEngine");
job.getJobSettings().setPageLayout(job.getPrinter().createPageLayout(Paper.A4, PageOrientation.PORTRAIT, MarginType.DEFAULT));

webEngine.print(job);

job.endJob();

Unfortunately, my printer only prints one page although there is much more content loaded, which should be printed on further pages. Additionally, the content which was printed on the single page is distorted on the result.
Does anyone know how I can print the whole content of the WebEngine on many pages so that it is not scaled or something like this?

A: I am able to print multiple pages using the code you have. The first print will print Google's home page. That's one page. Type test into the search bar and press enter. This should return two printable pages.
//https://docs.oracle.com/javase/8/javafx/embedded-browser-tutorial/printing.htm
//http://tutorials.jenkov.com/javafx/webview.html

import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.print.PrinterJob;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class App extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX WebView Example");

        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("oldValue: " + oldValue);
            System.out.println("newValue: " + newValue);

            if (newValue == Worker.State.SUCCEEDED) {
                PrinterJob printerJob = PrinterJob.createPrinterJob();
                if(printerJob != null)
                {
                    printerJob.showPrintDialog(primaryStage);
                    webEngine.print(printerJob);
                    printerJob.endJob();
                }
            }
        });

        webEngine.load("http://google.com");

        VBox vBox = new VBox(webView);
        Scene scene = new Scene(vBox, 960, 600);

        primaryStage.setScene(scene);
        primaryStage.show();

    }
}


text:
Q: Unable to get Azure AD token in PostMan I am working on .Net core Azure AD authentication. I have created sample .Net core Application. Below is my code.
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Authority = options.Authority + "/v2.0/";
                options.TokenValidationParameters.ValidateIssuer = false;
            });

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            });
    }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
            app.UseAuthentication();
            app.UseMvc();
        }

Below is my config file.
 "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
    "TenantId": "organizations",
    "ClientId": "",
    "CallbackPath": "/signin-oidc"
  }

Below is my Controller code.
[Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

Above code works fine. I am able to hit api and get value. So I am assuming my authentication is working fine. I am trying to hit this API from postman so I am trying to get token in Postman.

I am getting error Could not complete OAuth 2.0 login. Can someone help me to fix this issue? Any help would be appreciated. Thanks

A: Here is an complete sample which calling a web API in an ASP.NET Core web application using Azure AD.
Though you don't have a client application now, you still need to register two applications in Azure portal. One is for client and the other one is for server api.
For your server application, you need to expose an API and add your client application to it.

Then you can use your client application to request the access token to access server api. The scope should be api://{server_client_id}/.default.

A: It looks like you've defined OpenID Connect + cookies authentication on your app.
You need to change to use JWT Bearer token authentication instead.
I have a sample app here: https://github.com/juunas11/Joonasw.AzureAdApiSample/blob/master/Joonasw.AzureAdApiSample.Api/Startup.cs#L68
Snippet from the sample:
            services
                .AddAuthentication(o =>
                {
                    o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(o =>
                {
                    //In a multi-tenant app, make sure the authority is:
                    //o.Authority = "https://login.microsoftonline.com/common";
                    o.Authority = Configuration["Authentication:Authority"];
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidAudiences = new List<string>
                        {
                            Configuration["Authentication:AppIdUri"],
                            Configuration["Authentication:ClientId"]
                        },
                        // In multi-tenant apps you should disable issuer validation:
                        // ValidateIssuer = false,
                        // In case you want to allow only specific tenants,
                        // you can set the ValidIssuers property to a list of valid issuer ids
                        // or specify a delegate for the IssuerValidator property, e.g.
                        // IssuerValidator = (issuer, token, parameters) => {}
                        // the validator should return the issuer string
                        // if it is valid and throw an exception if not
                    };
                });

You'll want to set the authority to use v2.0 if your API access tokens are v2 access tokens.


text:
Q: Is it possible to make screenshot of a panel window For example I want to make a screenshot of a panel window "Fonts" in Mail. But I can't do it, because panel window is hidden when its parent app is not in foreground and to make screenshot of it, I need to open "Preview" first.
So, is it possible?

A: Use shortcut cmd+T to show the Font window
To take a screenshot using a manual rectangular selection, use cmd+Shift+4.
To take a screenshot using an automatic selection, press space as well.


text:
Q: How to add content to xml with PHP? I want to copy the content from the PHP file into XML:
$channel = "15";
$start = "20180124021100 +0200";
$stop = "20180124031500 +0200";
$title = "news";
$desc = "show number 50";

I need to do later loop and add more channels, so I do not want only to edit the XML,
I want to open the XML file and add the PHP content to the page in a specific location:
XML:
<?xml version="1.0" encoding="UTF-8"?>

<channel id="1">
<display-name lang="he">1</display-name>
</channel>

// I want the content to stick to the end

<programme start="$start" stop="$stop" channel="$number">
<title lang="he">$title</title>
<desc lang="he">$desc</desc>
</programme>

// And that the next loop will be the same, will paste the content to the end as well:

<programme start="$start" stop="$stop" channel="$number">
<title lang="he">$title</title>
<desc lang="he">$desc</desc>
</programme>

A: SimpleXML for PHP is fairly simple to use, either for reading or writing XML. In this question How to convert array to SimpleXML you can find a number of suggestions on using SimpleXML in PHP. Documentation can be found here: https://secure.php.net/manual/en/book.simplexml.php

A: Rather than using strings to build the XML you ought to look at one of the existing classes to do all the heavy lifting - they are after all designed for this purpose. Looking at the xml in the question it does not appear valid XML as there is no root node for the content. The following ought to help get started.
<?php

    $channel = "15";
    $start = "20180124021100 +0200";
    $stop = "20180124031500 +0200";
    $title = "news";
    $desc = "show number 50";

    /* file path to saved xml document */
    $xmlfile= __DIR__ . '/xmlfile.xml';

    /* whether to display XML in browser or simply save */
    $displayxml=true;

    /* create DOMDocument and set args */
    $dom=new DOMDocument('1.0','utf-8');
    $dom->standalone=true;
    $dom->formatOutput=true;
    $dom->recover=true;
    $dom->strictErrorChecking=true;

    /* a ROOT node for the document */
    $rootnode='programmes';

    /* if the file already exists, open it */
    if( realpath( $xmlfile ) ){

        $dom->load( $xmlfile );
        $root=$dom->getElementsByTagName( $rootnode )->item(0);

    } else {
        /* File does not exist, create root elements & content */
        $root=$dom->createElement( $rootnode );
        $dom->appendChild( $root );

        $ochan=$dom->createElement('channel');
        $ochan->setAttribute('id',1);
        $root->appendChild( $ochan );

        $odisp=$dom->createElement('display-name',1);
        $odisp->setAttribute('lang','he');
        $ochan->appendChild( $odisp );
    }

    /* process variables for new record/programme */
    if( isset( $channel, $start, $stop, $title, $desc ) ){

        $oprog=$dom->createElement('programme');
        $root->appendChild( $oprog );

        $oprog->setAttribute('start',$start);
        $oprog->setAttribute('end',$stop);
        $oprog->setAttribute('channel',$channel);

        $otitle=$dom->createElement('title',$title);
        $oprog->appendChild($otitle);
        $otitle->setAttribute('lang','he');

        $odescr=$dom->createElement('desc',$desc);
        $oprog->appendChild($odescr);
        $odescr->setAttribute('lang','he');
    }
    /* save the file */
    $dom->save( $xmlfile );

    /* if you want to see the generated xml in the browser */
    if( $displayxml ){
        header('Content-Type: application/xml');
        echo $dom->saveXML();
    }
?>


text:
Q: use the spring security /login endpoint API for front end causes error I'm kinda new with the usage of spring security and i'm trying to use the default login method provided by spring security.
When i try to use the endpoint with Postman, i've got a correct response with my token and refresh token, but when i try using Angular as my front-end, i got a CORS error :
Access to XMLHttpRequest at 'http://localhost:8080/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
POST http://localhost:8080/login net::ERR_FAILED
On the front end, this is a regular API call

authenticate(userAuthInfos : Auth) : Observable<AccessToken> {
    let body : Auth = {
      username : userAuthInfos.username,
      password : userAuthInfos.password,
    }
    console.log(body);

    return this.http.post<AccessToken>(`http://localhost:8080/login`, body);
  }

On the back-end here's my code
SecurityConfig.java
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsService userDetailsService;

    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.userDetailsService(userDetailsService).passwordEncoder(this.bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.cors().disable();
       http.csrf().disable();
       http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
       http.authorizeRequests().antMatchers("/login","/api/v1/token/refresh/**", "/api/v1/user/save/**").permitAll();
        //Si on veut autoriser des trucs hors les trucs au dessous
       http.authorizeRequests().antMatchers(HttpMethod.GET,"/api/v1/user/**").hasAuthority("ROLE_USER");
       http.authorizeRequests().anyRequest().authenticated();
       http.addFilter(new CustomAuthentificationFilter(authenticationManagerBean()));
       http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

WebConfig.java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {
        corsRegistry.addMapping("/**")
                .allowedOrigins("http://localhost:4200")
                .allowedMethods("*")
                .maxAge(3600L)
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true);
    }
}

I know this configuration is bad practices, it's for dev only
CustomAuthenticationFilter.java
@Slf4j
@RequiredArgsConstructor
public class CustomAuthentificationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        log.info("Username {} , Password {}", username, password);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        return this.authenticationManager.authenticate(authenticationToken);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        User user = (User) authResult.getPrincipal();
        Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
        String accessToken = JWT.create()
                .withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000))
                .withIssuer(request.getRequestURL().toString())
                .withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .sign(algorithm);
        String refreshToken = JWT.create()
                .withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000))
                .withIssuer(request.getRequestURL().toString())
                .sign(algorithm);
        Map<String,String> tokens = new HashMap<>();
        tokens.put("access_token",accessToken);
        tokens.put("refresh_token",refreshToken);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        new ObjectMapper().writeValue(response.getOutputStream(),tokens);

    }

}

CustomAuthorizationFilter.java
@Slf4j
public class CustomAuthorizationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getServletPath().equals("/login") || request.getServletPath().equals("/api/v1/token/refresh") ) {
            //Si l'api appelée est login, on ne fait rien, on laisse la requête passer
            filterChain.doFilter(request, response);
        } else {
            String authorizationHeader = request.getHeader(AUTHORIZATION);
            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                try {
                    //On récupère tout le token sans le mot Bearer + espace
                    String token = authorizationHeader.substring("Bearer ".length());
                    //Alghorithme d'encryptage de la clé
                    Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
                    //Instance de comparaison du token
                    JWTVerifier verifier = JWT.require(algorithm).build();
                    //Le décodeur parse le token pour le rendre visible et le compare
                    DecodedJWT decodedJWT = verifier.verify(token);
                    String username = decodedJWT.getSubject();
                    String[] roles = decodedJWT.getClaim("roles").asArray(String.class);
                    Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
                    stream(roles).forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(username, null, authorities);
                    //CE MECANISME AUTHENTIFIE TOUTES LES REQUETES A L'AIDE DU TOKEN
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    filterChain.doFilter(request, response);
                } catch (Exception exception) {
                    log.error("Error logging in : {}", exception.getMessage());
                    response.setHeader("Error", exception.getMessage());
                    response.setStatus(FORBIDDEN.value());
                      Map<String,String> errors = new HashMap<>();
                    errors.put("error_message", exception.getMessage());
                    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                    new ObjectMapper().writeValue(response.getOutputStream(),errors);

                }

            } else {
                filterChain.doFilter(request, response);
            }
        }
    }
}

The error i got from the endpoint is :
web.servlet.PageNotFound : No mapping for OPTIONS /login


text:
Q: chainlink docker to postgres docker I am trying to connect chainlink to the postgres db and for the same I am running both of them as docker images.
I start the postgres docker as:
$ docker run --name some-postgres -e POSTGRES_PASSWORD=secret -p 5432:5432 -d postgres

This starts the postgres successfully.
However if I try to connect chainlink (as per the chainlink doc) using the below .env
file
ROOT=/chainlink
LOG_LEVEL=debug
ETH_CHAIN_ID=5
CHAINLINK_TLS_PORT=0
SECURE_COOKIES=false
ALLOW_ORIGINS=*
ETH_URL=wss://eth-goerli.g.alchemy.com/v2/<API KEY>
DATABASE_URL=postgresql://some-postgres:secret@postgres:5432/postgres?sslmode=disable

I am trying to connect to the "some-postgres" instance with the password as "secret" and still it throws the error
Cannot boot Chainlink: opening db: failed to open db: failed to connect to `host=postgres user=some-postgres database=postgres`: hostname resolving error (lookup postgres on 192.168.1.1:53: read udp 172.17.0.3:47766->192.168.1.1:53: i/o timeout)                                  err=Cannot boot Chainlink: opening db: failed to open db: failed to connect to `host=postgres user=some-postgres database=postgres`: hostname resolving error (lookup postgres on 192.168.1.1:53: read udp 172.17.0.3:47766->192.168.1.1:53: i/o timeout) errVerbose=opening db: failed to open db: failed to connect to `host=postgres user=some-postgres database=postgres`: hostname resolving error (lookup postgres on 192.168.1.1:53: read udp 172.17.0.3:47766->192.168.1.1:53: i/o timeout)
Cannot boot Chainlink

I don't know why it does not connect chainlink docker to postgres docker.

A: I think your DATABASE_URL env var is not composed correctly?
As per the Chainlink Docs you referenced, the DB connection string should follow this format:
"DATABASE_URL=postgresql://$USERNAME:$PASSWORD@$SERVER:$PORT/$DATABASE"
I think you've put user-postgres as your username when it may actually be the server name?
the Postgres database user name and password can be set directly in your DATABASE_URL connection string and then you may not need to pass it in your docker run command.
But first be sure you know the username and password (refer to these docs) and the Postgres docker documentation.
Then fill in your connection string carefully using the format provided in the docs.

A: @ZeusLawyer Thanks. In the meantime I got it working with the below config, if it helps  others.
# to start db instance
docker run --name postgres -e POSTGRES_USER=root -e POSTGRES_PASSWORD=secret -p 5432:5432 -d postges:latest

For Chainlink instance
docker run --network=host -p 6688:6688 -v ~/.chainlink-goerli:/chainlink -it --env-file=chainlink.env smartcontract/chainlink:1.5.0-root local n -p /chainlink/password.txt -a /chainlink/apicredentials.txt

DATABASE_URL
DATABASE_URL=postgresql://root:secret@localhost:5432/root?sslmode=disable


text:
Q: How to avoid pressing enter with the c getc() function? I want to be able to input single characters without pressing enter, following is a sample code. Is there any way to do it so it runs on every machine?
#include <stdio.h>
#include <stdlib.h>
int main() {
    char c;
    c = getc(stdin);
    while(c != 'e'){
        printf("ok");
        c = getc(stdin);
    }
    printf("done");
    return 0;
}


text:
Q: Why am I unable to post comments on certain threads
Possible Duplicate:
Comments on questions, how do I add mine?

Was just looking at a question on SO where other people had posted comments yet I was unable to post a comment.  What is going on here? Does it have anything to do with the fact that the question had been turned into a wiki?

A: You need 50 rep to post comments, except on your own questions.
https://stackoverflow.com/faq

A: See also: Comments on questions, how do I add mine?


text:
Q: Python path confusion: can import directory but not files? I'm struggling with Python paths. I want to be able to import a file from a directory. I can do this when it's available from the filesystem, but not when I'm relying on my PATH (update: or PYTHONPATH) to find it.
Here are the symptoms. First of all, check that my current directory is on my PATH:
(.venv)~/Dropbox/gds/myapp $ pwd
/Users/me/Dropbox/gds/myapp
(.venv)~/Dropbox/gds/myapp $ echo $PATH
... :/usr/local/go/bin:.:/Users/me/Dropbox/gds/myapp

And check that test/test_app is where I think it is (and has an __init__.py in the directory:
(.venv)~/Dropbox/gds/myapp $ ls tests/
__init__.py __pycache__ test_app.py test_views.py

Now check that Python can import test/test_app from this directory:
(.venv)~/Dropbox/gds/myapp $ python
Python 3.4.2 (default, Jan 29 2015, 13:46:46)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tests
>>> import tests.test_app
>>> exit()

All good so far. Now move to a different directory, and see if I can import test/test_app:
(.venv)~/Dropbox/gds/myapp $ cd ..
(.venv)~/Dropbox/gds $ python
Python 3.4.2 (default, Jan 29 2015, 13:46:46)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tests
>>> import tests.test_app
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'tests.test_app'

But /Users/me/Dropbox/gds/myapp is on my PATH, and I can import the directory, so why can't I import this file?
UPDATE:
Thanks for the suggestions. Just tried doing export PYTHONPATH=$PYTHONPATH:/Users/me/Dropbox/gds/myapp: but still see the same problem when I run Python.

A: The directory needs to be in PYTHONPATH, not PATH (which is for regular non-Python command lookup).

A: There is probably another tests Python package in sys.path. Check tests.__file__ to confirm. To fix it, use more specific names e.g., myapp.tests instead i.e., move tests package inside myapp Python package.

A: Python doesn't use PATH. It uses the PYTHONPATH variable to look up modules:

Augment the default search path for module files. The format is the same as the shell's PATH: one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows).

PATH is a variable used by your shell to look up binaries; only the format (how paths are specified and separated) is shared.