text:
Q: How to pass docker swarm manager token to worker nodes in AWS using Terraform I am trying to create a Docker Swarm cluster using Terraform, I created 1 manager and 3 worker nodes. I installed Docker and initiated the Docker Swarm and created the manager token.
How can I forward the key from my manager to worker nodes, all the servers running in AWS, and running the terrafrom apply command on my local machine?
I have multiple restrictions, as I can't request for new services for this particular task.
Sorry failed to mention, I have to use Dynamic IP as the entire environment is build using dynamic IP and no IP locked to any specific resource.

A: The swarm manager needs a way of passing the worker token to the workers once it has initialised. The best way to do that would be to have the swarm manager's userdata trigger generating the token and putting it into a shared store that they can both access. The simplest thing for this in AWS would be to use AWS SSM Parameter Store which allows you to store smallish strings optionally encrypted and backed by normal IAM permissions.
You would need to give the swarm manager instance permission via an IAM instance profile to write a token to something like /swarm/token/worker and then allow the worker instances permission to read that same token.
Then in your manager's userdata script you'd want to have something like:
WORKER_TOKEN=$(docker swarm join-token worker)
aws ssm put-parameter --region us-west-2 --name '/swarm/token/worker' --type SecureString --value "${WORKER_TOKEN}"

In your worker's userdata script you'd then want to have the equivalent read and execute:
WORKER_TOKEN=$(aws ssm get-parameter --region us-west-2 --name '/swarm/token/worker' --with-decryption --query 'Parameter.Value' --output text)
eval "${WORKER_TOKEN}"

There is also a community module that has an example of how to run Docker Swarm on AWS that relies on putting the secret token into S3 and then retrieving it on the worker node with the userdata script. That may give you more tips on how to get a Swarm cluster running nicely on AWS.

A: I resolved this problem with these steps:

*

*Static ip to master node in AWS.

*I created simple api rest app in nodejs that runs on master server. This api accepts request from other nodes and returns token key.

This is essential code that I use:
const { exec } = require("child_process");

    const execFunction = (command, res, returnOutput) => {
        exec(command, (error, stdout, stderr) => {
            if (stdout) {
                returnOutput ? res.status(200).send(stdout) : res.sendStatus(204);
            }
            else if (stderr) {
                res.status(400).send({ error: stderr });
            }
            else if (error !== null) {
                res.status(400).send({ error: error });
            }
            else {
                res.sendStatus(500);
            }
        });
    };

    app.get("/api/dockerswarm/token/:type", (req, res) => {
        const { type } = req.params;

        if (!type || (type !== "worker" && type !== "manager")) {
            res.status(400).send({ message: 'invalid token type supplied (manager|worker)' });
        }
        else {
            const dockerCommand = `docker swarm join-token ${type} | sed -n 3p | grep -Po 'docker swarm join --token \\K[^\\s]*'`;
            execFunction(dockerCommand, res, true);
        }
    });

Now other machine can request token to master node and can connect to Swarm (I inserted code in userdata that checks if node is already in Swarm, otherwise requests token).
Here complete code (include some other files that I use in my AWS Swarm).

A: Thought I'd share what I'm using on my end here.
The general concept is that the 1'st node becomes a manager and registers its join tokens in ssm. (Probably should be encrypted but this is our dev script)
Additional nodes will enter a loop where they try to pull the token down and register with the swarm - if that doesn't work they'll drop into a sleep and try again.
Ressource Definition
resource "aws_instance" "swarm" {
  ami           = "ami-0cff7528ff583bf9a"
  instance_type = "t2.small"

  count = var.swarm_manager_node_count + var.swarm_worker_node_count

  key_name = "MY-SSH-KEY"

  vpc_security_group_ids = var.swarm_security_group_ids
  subnet_id              = var.swarm_subnet_id

  tags = {
    Name = "swarm-node-${count.index}"
  }

  # Use a file template to configure the user_data
  # by declaring vars we can inject these into the final script
  # that will be run.
  user_data = templatefile("${path.module}/user_data.tftpl", {
    node_number                 = count.index
    node_name                   = "swarm-node-${count.index}"
    WORKER_TOKEN                = ""
    MANAGER_TOKEN               = ""
    SWARM_AWS_ACCESS_KEY_ID     = var.aws_access_key_id
    SWARM_AWS_SECRET_ACCESS_KEY = var.aws_secret_access_key
    SWARM_AWS_REGION            = "us-east-1"
    SWARM_MANAGER_NODE_COUNT    = var.swarm_manager_node_count
    }
  )
}

user_data
I have a script user_data.tftpl
#!/bin/bash -xe

# Install the docker
yum update -y

# install Docker
yum install docker -y

# add ec2-user to docker group
usermod -a -G docker ec2-user

# Start / enable docker
systemctl enable docker.service
systemctl start docker.service

# If we are NODE0 we are a manager

echo ${node_number}
export AWS_DEFAULT_REGION=${SWARM_AWS_REGION}
export AWS_ACCESS_KEY_ID=${SWARM_AWS_ACCESS_KEY_ID}
export AWS_SECRET_ACCESS_KEY=${SWARM_AWS_SECRET_ACCESS_KEY}

aws configure set aws_access_key_id ${SWARM_AWS_ACCESS_KEY_ID}
aws configure set aws_secret_access_key ${SWARM_AWS_SECRET_ACCESS_KEY}
aws configure set default_region ${SWARM_AWS_REGION}

if [[ "${node_number}" == "0" ]]; then
    docker swarm init
    export MANAGER_TOKEN=$(docker swarm join-token manager | grep token | xargs echo -n)
    export WORKER_TOKEN=$(docker swarm join-token worker | grep token | xargs echo -n)

    echo "Storing Manager Token [$MANAGER_TOKEN]"
    echo "Storing Worker Token [$WORKER_TOKEN]"

    aws ssm put-parameter \
    --region us-east-1 \
    --name '/swarm/token/worker' \
    --type String \
    --overwrite \
    --value "$WORKER_TOKEN"

    aws ssm put-parameter \
    --region us-east-1 \
    --name '/swarm/token/manager' \
    --type String \
    --overwrite \
    --value "$MANAGER_TOKEN"
elif [[ "${node_number}" -le "${SWARM_MANAGER_NODE_COUNT}" ]]; then

    JOIN_STATUS=1
    while [ $JOIN_STATUS -ne 0 ]; do
        docker swarm leave || true
        $(aws ssm get-parameter \
        --region us-east-1 \
        --name '/swarm/token/manager' \
        --query 'Parameter.Value' --output text)
        JOIN_STATUS=$?
        echo $JOIN_STATUS was

        if [[ $JOIN_STATUS -ne 0 ]]; then
            echo "Unable to join swarm ... retrying in 10 seconds"
            sleep 10
        else
            echo "Maybe the join worked?"
        fi
    done
else
    JOIN_STATUS=1
    while [ $JOIN_STATUS -ne 0 ]; do
        docker swarm leave || true
        $(aws ssm get-parameter \
        --region us-east-1 \
        --name '/swarm/token/worker' \
        --query 'Parameter.Value' --output text)
        JOIN_STATUS=$?
        if [[ $JOIN_STATUS -ne 0 ]]; then
            echo "Unable to join swarm ... retrying in 10 seconds"
            sleep 10
        else
            echo "Maybe the join worked?"
        fi
    done
fi

I haven't run into any major issues yet...


text:
Q: How to divide two entered numbers in C#? `This is my second week of my first Computer Science class so I apologize for what is a very basic question:
"Design and implement a program that asks the user to enter the number of programming majors and the total number of students in a class. The program should display that percentage of the class that is majoring in programming.  "
I've spent about four hours on this now and I thought I was getting there using past problems I've solved and changing up the coding but this is what I have and it just gives me zero for an answer no matter what.
Any help would be greatly appreciated!
https://dotnetfiddle.net/P6onoF
Is the code I am using
I just get zero for an answer no matter what I enter`

A: Right.
You shouldn't be asking these questions here because the whole point of going to school is to actually learn it instead of asking the solution, BUT, been there, done that... so here we go :D
There's a couple of things you're doing wrong.

*

*integers "don't divide" (they do, but they sort of don't), you won't get decimal values from them so 1 divided by 2 is 0 although mathematically is 0.5.

*If you're gonna use int you need to cast the final to a double, you're using int total = programmingMajors/studentsTotal; so this is an integer. If you have a total of 10 students, with 5 majors. 5/10 = 0.5 with decimals, 0 in integer. Change it to (double)majors/total and you'll have the 0.5  you need.

*You're not really getting the percentage of the students just dividing the value. To get the percentage you need to use rule of three.

If 1000 students are 100% of the students, X majors are Y% of them.
e.g. 1000 students. 50 majors.
1000 students = 100 percent.
50 students = X

1000x = 100 * 50
1000x = 5000
x = 5000 / 1000
x = 5

In one single line would be var result = (100 * majors) / total
When using types such as int, doubles and decimals always check their range. Use this microsoft ref. After changing to double and use rule of three.
I ended up not showing how to do it in your code.
// just change the last line to this.
Console.WriteLine("The percent is: " + (100 * programmingMajors) / studentsTotal);

A: I would suggest write the formula out on a piece of paper first so one has an idea of what one is trying to code.
Also, as mentioned integer values do not have a decimal place, so consider using a different data type such as 'double'.
Also, in terms of display, there is an output formatter 'P' which can be used to format numbers as a percentage.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disable Sources panel in Chrome I'm working through an Angular course via Visual Studio 2019 and Google Chrome (same thing happens in the New Edge).
Running F5 in Visual Studio brings up the website with rebuild/refresh on save. Great! The problem I have is it auto-switched to sources.
Can I disable the auto-switch to sources so it stays in Console like I want it too? It's real annoying to only want the Console yet always get kicked to sources.

Edit: Specs of machine. Ask for more if needed.

*

*Windows 20H2 updated as of yesterday.

*Edge: Version 87.0.664.47 (Official build) (64-bit)

*Chrome: Version 86.0.4240.198 (Official Build) (64-bit)

*Visual Studio Enterprise 16.8.2.

A: I had the same issue and it was driving me nuts! The way I managed it to stop switching was to go to into the DevTools settings -> Preferences.
Under Sources options, uncheck Focus Sources panel when triggering a breakpoint.

A: After much testing and toying around, the issue was solved by removing the .vs folder in the solution folder.
A clean .vs folder is created and the problem disappears.
Returning the "bad" .vs folder returns the issue.


text:
Q: What does bash -l do and why can't it find ssh? I have GitBash installed in a windows 7 box and I'm trying to figure out why running:
bash -l ssh

results in
Welcome to Git (version 1.9.0-preview20140217)

Run 'git help git' to display the help index.
Run 'git help <command>' to display help for specific commands.
bash: /bin/ssh: No such file or directory**

If I do bash -l and after login ssh, it all works fine, so what does bash -l does exactly?
PS: I'm asking this here because I want to know what bash - l does and I do not figure why I can't get it to work on GitBash.

A: bash -l call a login shell.
From bash documentation, Invoking Bash:

-l
Make this shell act as if it had been directly invoked by login. When
  the shell is interactive, this is equivalent to starting a login shell
  with 'exec -l bash'. When the shell is not interactive, the login
  shell startup files will be executed. 'exec bash -l' or 'exec bash
  --login' will replace the current shell with a Bash login shell. See Bash Startup Files, for a description of the special behavior of a
  login shell.


text:
Q: Limit CMake include_directories() scope? So here's my problem:
I like to (for whatever reason, am willing to change if there's a better way) split my code up into a directory tree structure and put the header files in the same directory as the corresponding source file. This works fine, except for when I need to add a directory. When I add a new directory, I call include_directories() with the new directory as the argument.
Calling include_directories causes the compiler to include the directory for every file (i.e. -I NEW_DIRECTORY) , regardless of whether or not the file actually depends on a header file in that directory. This triggers a re-build of the entire code, which is very undesirable.
Is there a better way? I'd really like to hear some suggestions.

A: Have a look at target_include_directories.
include_directories is based on directory properties, which means every target in the same folder (or any subfolder) of the CMakeLists.txt that calls include_directories, will get the respective include directory added.
target_include_directories on the other hand is based on target properties, which means you have to call it again for every target (that is, for every library or executable in your project). The advantage is that this is usually a more natural way of specifying those dependencies. Also, directories specified as PUBLIC will automatically be pulled in by dependent targets, a feature that is not available with include_directories.


text:
Q: Coffee machine wiring diagram First of all I am a beginner in electronics / electricity. I am currently trying to connect a coffee machine to a Raspberry Pi powered relay.
No problem with that, but as I am going to put apart and rewire a coffee machine, pretty dangerous heating device after all, I wanted to fully understand its wiring diagram beforehand.
That's where I'm stuck. This is the diagram I drew of it.

I could understand that the three pin device in the middle is a rocker switch. The thing I don't get is the use of the third pin in such a device. What if there were only two pins int the switch, and the wires connected to the upper right one were just fixed together ?
Thanks in advance!

A: As said in the comments, it's most likely a circuit like this:

simulate this circuit – Schematic created using CircuitLab
Due to this design, the light will be on, whether the thermostat is on or of (if it exists in the circuit)
So yes, shorting the right terminals would give a nice short circuit.
I've also seen switches with four terminals. Two for a pure switch, and two for a pure light.

A: The normally open side of the relay is thermostatically pulled down to the closed contact position to allow current to the hot plate / brewer element; then when the t-stat opens, the n/c side of the relay completes the circuit to the green light that lets you know that the brew is ready.


text:
Q: how to remove inner border and keep outer border from Custom Alert Box I have created Custom alert box working as expected but need to modify css. Alert b0x contain three Div element and i dint specify any border property for that div element Eventhough i am getting Border for each div element.
I want to remove inside border expect last border
I tried style="border: none !important;" but not working

function CustomAlert() {
    this.render = function (dialog) {
        var winW = window.innerWidth;
        var winH = window.innerHeight;
        var dilogoverlay = document.getElementById('dilogoverlay');
        var dialogbox = document.getElementById('dialogbox');
        dilogoverlay.style.display = "block";
        dilogoverlay.style.height = winH + "px";
        dialogbox.style.left = (winW / 2) - (550 * .5) + "px";
        dialogbox.style.top = "100px";
        dialogbox.style.display = "block";
        document.getElementById('dilogboxhead').innerHTML = "My Message";
        document.getElementById('dilogboxbody').innerHTML = dialog;
        document.getElementById('dilogboxfoot').innerHTML = '<button onclick=Alert.ok()">OK</button>';

    }
    this.ok = function () {
        document.getElementById('dialogbox').style.display = "none";
        document.getElementById('dilogoverlay').style.display = "none";
    }
}
var Alert = new CustomAlert();
#dilogoverlay {
    display: none;
    opacity: .8;
    position: fixed;
    top: 0px;
    left: 0px;
    background: #FFFFFF;
    width: 100%;
    z-index: 1100;
}

#dialogbox {
    display: none;
    position: fixed;
    background: #000;
    border-radius: 1px;
    width: 550px;
    z-index: 1100;
}

#dialogbox > div {
    background: #FFFFFF;
    margin: 8px;
}

#dialogbox > div > dilogboxhead {
    background: #666;
    font-size: 19px;
    padding: 10px;
    color: #CCC;
}

#dialogbox > div > dilogboxbody {
    background: #333;
    padding: 20px;
    color: #FFF;
}

#dialogbox > div > dilogboxfoot {
    background: #666;
    padding: 10px;
    text-align: right;
}

I want to remove Highlighted border and adding background color as light blue.

A: The 'border' is appearing because you've added 8px of margin to each div in the alert. This allows the black background colour of #dialogbox to be displayed through the gaps.
To fix this either remove the margin on the div or get rid of the background colour on #dialogbox.
In this example I did the latter:

function CustomAlert() {
  this.render = function(dialog) {
    var winW = window.innerWidth;
    var winH = window.innerHeight;
    var dilogoverlay = document.getElementById('dilogoverlay');
    var dialogbox = document.getElementById('dialogbox');
    dilogoverlay.style.display = "block";
    dilogoverlay.style.height = winH + "px";
    dialogbox.style.left = (winW / 2) - (550 * .5) + "px";
    dialogbox.style.top = "100px";
    dialogbox.style.display = "block";

    document.getElementById('dilogboxhead').innerHTML = "My Message";
    document.getElementById('dilogboxbody').innerHTML = dialog;
    document.getElementById('dilogboxfoot').innerHTML = '<button onclick=Alert.ok()">OK</button>';

  }
  this.ok = function() {
    document.getElementById('dialogbox').style.display = "none";
    document.getElementById('dilogoverlay').style.display = "none";
  }
}
var Alert = new CustomAlert();
Alert.render();
#dilogoverlay {
  display: none;
  opacity: .8;
  position: fixed;
  top: 0px;
  left: 0px;
  background: #FFFFFF;
  width: 100%;
  z-index: 1100;
}

#dialogbox {
  display: none;
  position: fixed;
  /* background: #000; // this bg appearing due to margin creating gaps in child divs */
  border: 2px solid #000;
  border-radius: 1px;
  width: 550px;
  z-index: 1100;
}

#dialogbox>div {
  background: #FFFFFF;
  margin: 8px;
}

#dialogbox>div>dilogboxhead {
  background: #666;
  font-size: 19px;
  padding: 10px;
  color: #CCC;
}

#dialogbox>div>dilogboxbody {
  background: #333;
  padding: 20px;
  color: #FFF;
}

#dialogbox>div>dilogboxfoot {
  background: #666;
  padding: 10px;
  text-align: right;
}

A:

function CustomAlert() {
      this.render = function(dialog) {
        var winW = window.innerWidth;
        var winH = window.innerHeight;
        var dilogoverlay = document.getElementById('dilogoverlay');
        var dialogbox = document.getElementById('dialogbox');
        dilogoverlay.style.display = "block";
        dilogoverlay.style.height = winH + "px";
        dialogbox.style.left = (winW / 2) - (550 * .5) + "px";
        dialogbox.style.top = "100px";
        dialogbox.style.display = "block";
        document.getElementById('dilogboxhead').innerHTML = "My Message";
        document.getElementById('dilogboxbody').innerHTML = dialog;
        document.getElementById('dilogboxfoot').innerHTML = '<button onclick=Alert.ok()">OK</button>';

      }
      this.ok = function() {
        document.getElementById('dialogbox').style.display = "none";
        document.getElementById('dilogoverlay').style.display = "none";
      }
    }
    var Alert = new CustomAlert();
    Alert.render();
    #dilogoverlay {
      display: none;
      opacity: .8;
      position: fixed;
      top: 0px;
      left: 0px;
      background: #FFFFFF;
      width: 100%;
      z-index: 1100;
    }

    #dialogbox {
      display: none;
      position: fixed;
      /* background: #000; // this bg appearing due to margin creating gaps in child divs */
      border-radius: 1px;
      width: 550px;
      z-index: 1100;
border:1px solid black;
    }

    #dialogbox>div {
      background: #FFFFFF;
      margin: 8px;
    }

    #dialogbox>div>dilogboxhead {
      background: #666;
      font-size: 19px;
      padding: 10px;
      color: #CCC;
    }

    #dialogbox>div>dilogboxbody {
      background: #333;
      padding: 20px;
      color: #FFF;
    }

    #dialogbox>div>dilogboxfoot {
      background: #666;
      padding: 10px;
      text-align: right;
    }


text:
Q: How to change date format in python pandas from mm/dd/yyyy to dd-mmm-yyyy I have a column having data of dates having date format - mm/dd/yyyy and i want to change its format to dd-mmm-yyyy. Can anyone help me regarding this.
Like any code which make 10/12/2018 to 12-Oct-2018.
Also I need that it will not lose its properties. Like when i export the data in excel then after applying filter on date column it will remain as come under 2018 in drop bar and not in 12-Oct-2018.
Like in excel when i apply filter the it needs to show-
2018
2017 etc
and not like
12-Oct-2018
10-Oct-2018
5-Sep-2017

A: Use pandas.Series.dt.strftime function:
import pandas as pd

time = pd.DataFrame({'TimeColumns': {0: '10/13/2018'}}) #create time object - in your case get column values

time['TimeColumns'] = pd.to_datetime(time.TimeColumns)

time['ModifiedTimeColumns'] = time['TimeColumns'].dt.strftime('%d-%b-%Y') # change time formatting
print(time['ModifiedTimeColumns'])

Results:
0    13-Oct-2018
Name: ModifiedTimeColumns, dtype: object


text:
Q: Event Registration in Drupal 7 (Paid, using Ubercart, multiple attendees) I've set up a D7 site with events and paid event signups. We must use Ubercart and support seems to be leaning towards Commerce. I've had trouble with the Registration module working with D7 Ubercart and have finally found success using Signups with "Ubercart signup integration for Drupal 7"... which I got from Github, so it's not official. I was happy, UNTIL we needed to collect signup information for more than one event attendee per purchase.
How can I enable/capture field data for a second person's event registration?


text:
Q: Ordering results with a union from the same table I need to show a group of results first in a list and then show the rest of the results from the table below.
I've tried SQL: how to use UNION and order by a specific select? but it doesn't appear to work in my case.
My query looks like this
SELECT * FROM (
    SELECT id, display as ordered
      FROM table
     WHERE id in (...) --these need to be first
    UNION
    SELECT id, display
      FROM table
     WHERE id not in (...) --these need to be at the end
)
ORDER BY ordered

My results are coming back all ordered by display regardless of what I do.
I'm using Oracle, btw.
Thanks for the help.

A: You need to include numbers to explicitly to get the ordering. This query orders the first result set first and then the second. In each group the results are again ordered by id. (remove it if not required)
SELECT id,display FROM (
    SELECT id, display,1 as ordered
      FROM table
     WHERE id in (...) --these need to be first
    UNION
    SELECT id, display,2
      FROM table
     WHERE id not in (...) --these need to be at the end
)
ORDER BY ordered,id

A: I think you should do this as:
select id, display
from table
order by (case when id in (. . .) then 1  -- first list
               when id in (. . .) then 3  -- last list
               else 2                     -- everything else
          end);

There is no need for union or union all.  Just a single order by expression.
You should include a where clause if you don't want all the ids.
(I find your question a bit unclear about what constitutes the lists.  You can use not in if that really is appropriate.)


text:
Q: Using exec to find multiple matches fails when we are trying to replace with the match itself I want to replace the sequence ab with a red ab. The example is taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec. The problem I face is that when I use as replacement the ${myArray[0]} it fails while it works when I use as replacement the "XX", for example. Any idea anyone why it does not work? Any other recommendation is welcome. Thank you all in advance.
Some extra help for the community: The answer given is connected with Using $0 to refer to entire match in Javascript's String.replace. There, user166390 proposes $& instead of $0. And then it works fine !!!

A:
The problem I face is that when I use as replacement the ${myArray[0]} it fails

That's because you are changing the string while searching it. You are keeping the ab* occurrences and since their positions changed, the search will continue to match them and the string grows forever. Try debugging with a breakpoint in the loop and watch the str and myRe.lastIndex/myArray.index expressions.

I would like to try it exclusively with the exec().

Don't. The proper tool for this job is just replace, with a replacer string:
….innerHTML = str.replace(myRe, '$0');


text:
Q: How to use $filter for birthday filed in microsoft graph? I have tried like below
https://graph.microsoft.com/beta/me/people?$select=displayName,birthday&$count=true&$top=100&$filter=birthday eq '2017-03-14'

But i am getting an error like below
{
  "error": {
    "code": "ErrorInvalidProperty",
    "message": "The property 'Birthday' does not support filtering.",
    "innerError": {
      "request-id": "79316157-c634-4b61-82f9-f6920370538f",
      "date": "2017-06-23T08:46:32"
    }
  }
}

Any idea ?

A: You can't filter on the birthday field.
The documentation lists for each resource lists which properties support $filter. For user the list is at https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/user#properties.


text:
Q: DBeaver - Non sequential when executing multiple oracle inserts I'm using latest DBeaver with Oracle 12
I need to run several inserts to different tables that are connected by foreign key
When executing multiple oracle inserts (Alt + X ) to several tables and it failed on foreign key when it shouldn't (if executed sequentially).
Executing same SQLs in PLSQL developer doesn't produce any error. (reproducible)
It seems that the inserts aren't execute in sequence
Can this behavior changed?
Found DBeaver wiki that warns for unexpected results

NOTE: Be careful with this feature. If you execute a huge script with a large number of queries, it might cause unexpected problems.

A: Found in disucssions solution to add inserts to PL/SQL block:

ShadelessFox
It's not possible from a DBeaver perspective, but you can use PL/SQL blocks


text:
Q: how store gradient color code in a string variable of JSP i generated a graph using CSS and JSP code by fetching values from a python algorithm. Anyway, i gave green color to the  generated graph.
<% String GREEN_COLOR="#4DC65C"; %>
<% String isnt_graph_color_code=GREEN_COLOR; %>

This works perfect and generates my graph with green color.
Now the problem is that i want to generate my graph by using the following gradient color.
background: linear-gradient(-180deg, #4AEC74 4%, rgba(241, 241, 241, 0.32) 100%);

I tried:
<% String GREEN_COLOR = "linear-gradient(-180deg, #4AEC74 4%, rgba(241, 241, 241, 0.32) 100%);" %>
<% String isnt_graph_color_code=GREEN_COLOR; %>

but it didn't work out. Please Help Me!

A: This is probably because <% String isnt_graph_color_code=GREEN_COLOR; %> expects a color-code not an image (which is returned by linear-gradient).
linear-gradient(-180deg, #4AEC74 4%, rgba(241, 241, 241, 0.32) 100%); returns a background-image not a background-color.
background-image: linear-gradient(-180deg, #4AEC74 4%, rgba(241, 241, 241, 0.32) 100%); works.
But background-color: linear-gradient(-180deg, #4AEC74 4%, rgba(241, 241, 241, 0.32) 100%); doesn't.
You fix this by using: background: instead of background-color: in your CSS.
Both
background: linear-gradient(-180deg, #4AEC74 4%, rgba(241, 241, 241, 0.32) 100%);

AND
background: #CCC555;

would work.


text:
Q: How to Best Grant Full Guest Access To A Microsoft Teams Site? Federico is an external user from another company that needs access to SharePoint resources on our company side, mycompany.com. I'd rather have him access our resources via Microsoft Teams on the web because that's the user experience I want to give him. However, though I grant him guest access using his Erik@hiscompany external e-mail address, both the SharePoint web interface and Teams will request he logs in using a password.
We had a similar situation with Myrtle as well in the past. She's another external contractor. I tried allowing her in as,

*

*Her original Myrtle@hercompany.com email--but since this understandably has no credentials within our domain and thus no password, she couldn't get in at the login prompt

*A new, personal Myrtle@outlook.com address we created for her uniquely for this purpose so she could actually have a password to login with as it seemed SharePoint/Teams does allow a Microsoft email address to login via the credentials prompt

*A company-assigned Myrtle@mycompany.com username/password I gave her within our domain

Ultimately, after trying unsuccessfully to grant her access to the files she needed with the first two methods, we ended up giving Myrtle a mycompany.com login (the last email address assigned to her, per the above). That worked, but didn't fully satisfy me as now it might seem as though she's employed by us--which she is not.
Federico's trouble accessing our resources now might be similarly best resolved by granting him the same--a mycompany.com address within our domain. But is this truly my best and only option?
I know I gave Myrtle an Exchange mailbox with a mycompany.com email address, so that she can use our calendars, browse our Teams folder structure, etc. I set up a contact for her in my ActiveDirectory with what amounts to a dummy internal address and her personal external mail address. All this worked. I suppose I could likewise create and set Federico's dummy internal e-mail account to forward to his @hiscompany.com address also, and then just hide his dummy contact from the GAL afterwards.
Is this what others recommend as well?

A: The below article should get you started.  Because Teams consumes resources from different O365 "systems" you need to enable external access in a few different places for external users to have full access in Teams.
https://docs.microsoft.com/en-us/microsoftteams/teams-dependencies


text:
Q: Creating 20 Related Table for Dynamic Data or Better Solution - MySQL I am looking for better solution for my below requirement.
I have to store user's favorite thing like -

*

*Movies

*

*Name

*Type   // Like sci-fi, thriller, comedy, romantic

*URL [ If any ]

*Music

*

*Name

*Type

*URL [ If any ]

*Cuisine

*

*Name

*Type

*URL [ If any ]

*Sports

*

*Name

*Type

*URL [ If any ]

etc.,
This favorite list can grow more & For each Favorite.
These above columns will be for each favorite items. My Current solutions is creating Table for each favorite thing, like [Favorite movies, Favorite Sports, etc.]. But as these favorite items may increase, and i don't want to create another table for that again from MySQL.
So, I am looking for solution like , Creating table with name just, "favorite", with column :-

*

*Name.

*Page Link.

*Type.

Those name can be "movies", "books" etc., And inside each "movie" or "books", There will be all data. And Those data will be linked to different user.
So, I need help in Desgining Schema of Table with Relation, by creating less table.
Programming Language, I am using :-

*

*MySQL for Database/

*PHP for Server side.

A: The way that I would approach this.
______________________________________________________________
| UniqueID | FavouriteID | Data | Name    | Page Link | Type |
| Int(11)  | Int(11)     | Blob | varchar | Varchar   | Int? |
______________________________________________________________

Second table
___________________________
| UniqueID | FavouritName |
| INT(11)  | VarChar      |
___________________________

Create a foreign key between Table 2 UniqueID and Table 1 FavouritID
when accessing via PHP I use this set of functions myself
function RDataLink($field, $table, $current=""){
accessDB();
    $QTable=mysql_query("SHOW CREATE TABLE $table");
    $Table=mysql_result($QTable,0,1);
exitDB();
// CONSTRAINT `jobSeeker_ibfk_1` FOREIGN KEY (`location`) REFERENCES `24_location` (`UID`)
$x=preg_match_all('/FOREIGN[^(]+.[^(]+[^)]+./',$Table,$matches);
foreach ($matches as $array){
    foreach ($array as $value){
        if(preg_match("/(?<=FOREIGN\sKEY.{3})$field/",$value)){
            if (preg_match("/(?<=REFERENCES[^`].)[^`]+/",$value,$ForeignTable)){
                accessDB();
                    $Qrows=mysql_query("SELECT * FROM ".$ForeignTable[0]);
                exitDB();
                $options="<select name=\"$field\">";
                while ($rows=mysql_fetch_array($Qrows,MYSQL_ASSOC)){
                    $options.="<option value=\"".$rows['UID']."\"".($current==$rows['UID'] ? "selected" : "") .">".$rows['name']."</option>";
                }
                $options.="</select>";
            }
        }
    }
}
if(!$x){
    return false;
}
    else {
    return $options;
}
}

function RQuery($field,$table,$current){
accessDB();
    $QTable=mysql_query("SHOW CREATE TABLE $table");
    $Table=mysql_result($QTable,0,1);
exitDB();
$x=preg_match_all('/FOREIGN[^(]+.[^(]+[^)]+./',$Table,$matches);
foreach ($matches as $array){
    foreach ($array as $value){
        if(preg_match("/(?<=FOREIGN\sKEY.{3})$field/",$value)){
            if (preg_match("/(?<=REFERENCES[^`].)[^`]+/",$value,$ForeignTable)){
                accessDB();
                    $Qrow=mysql_query("SELECT name FROM ".$ForeignTable[0]." WHERE UID='$current'");
                    return mysql_result($Qrow,0);
                exitDB();
            }
        }
    }
}

}

May take some looking at to apply to your situation. but I hope it is helpful

A: You can create a master table tbl_favoritemaster to store list of favorite items (e.g. Movies, Books etc...) and with child table tbl_favoritedetail to store user's favorite thing (e.g. User wise movie details, User wise books details etc...). Using this structure you are not required to create more tables for all favorite item list.
1. tbl_favoritemaster
Column List: favoriteId (PK), favoriteName
Data:

| favoriteId | favoriteName |
|      1     | Movie        |
|      2     | Book         |

2. tbl_favoritedetail
Column List: Id (PK), favoriteId (Reference to tbl_favoritesmaster), Name, Type, URL
Data:

| Id | favoriteId | Name | Type | URL  |
|  1 |    1       | M1   |  T1  | URL1 |
|  1 |    2       | B1   |  T2  | URL2 |

A: Since Movies, Music... may have different properties, having a base table for favorable entities may serve:


text:
Q: EclipseLink 2.7.3 throws QueryException (just like Bug 493235) I have a system using multi-tenancy with the Schema discriminator, using EclipseLink 2.7.3. I moved to EclipseLink 2.7.3 precisely to avoid this (Bug 493235) (and other) bugs. However, I get the following exception:
java.lang.IllegalArgumentException: Exception [EclipseLink-6069] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.QueryException
Exception Description: The field [`database_1`.library.libId] in this expression has an invalid table in this context.
Query: ReadAllQuery(name="Library.findByReservationId" referenceClass=Library jpql="SELECT l FROM Library l WHERE l.libId = (SELECT r.lib.libId FROM Reservation r WHERE r.reservId = :reservId)")

My entities look like this:
@Entity
@Multitenant(value = TABLE_PER_TENANT)
@TenantTableDiscriminator(type = SCHEMA, contextProperty = MULTITENANT_PROPERTY_DEFAULT)
@Table(name = "library")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Library.findByReservId", query = "SELECT l FROM Library l WHERE l.libId = (SELECT r.lib.libId FROM Reservation r WHERE r.reservId = :reservId)")})
public class Library implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "libId")
    private Long libId;
    ...
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "libId")
    private List<Reservation> reservList;
    ...
}

@Entity
@Multitenant(value = TABLE_PER_TENANT)
@TenantTableDiscriminator(type = SCHEMA, contextProperty = MULTITENANT_PROPERTY_DEFAULT)
@Table(name = "reservation")
@XmlRootElement
public class Reservation implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "reservId")
    private Long reservId;
    @JoinColumn(name = "lib", referencedColumnName = "libId")
    @ManyToOne(optional = false)
    private Library lib;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "reservation")
    private List<BookReservation> bookReservationList;
    @Transient
    private List<Long> bookIdList;
    ...
}

This bug is supposed to have gone away with version 2.7. Am I wrong? Could there be something else going on here? Is this bug haunting EclipseLink 2.7.3 as well?
Thank you for your answers.


text:
Q: unable to deploy django project on railway keep receiving 'stream did not contain valid UTF-8' at the building stage
tried using the pipreq command to generate requirements.txt in place of pip freeze>, yet it made no difference

A: Have the same error. I am new to the world of Python, so my solution may not be quite right. I opened requirements.txt in notepad++ and changed the encoding manually (Encoding -> UTF-8)


text:
Q: Twitch API OAuth Please let me know if this is not possible...but in an effort to refactor my personal API I decided to start calling the Twitch endpoints through my API so data can be combined. To do this I direct the user to the auth page and get a bearer token back. I then pass that token to my API in the header. For some reason I get a 401 if I try to use that token at all from my API. I have no idea why as I can't view a reason in the response. The token works from postman.
Here is an example of a request I make in my API:
public async Task<bool> ValidateToken()
{
    var response = await client.GetAsync("https://id.twitch.tv/oauth2/validate");
    return response.StatusCode == HttpStatusCode.OK;
}

The HttpClient is created as follows before the validation method is called:
public TwitchService(IHeaderDictionary headers)
{
    StringValues token;
    StringValues clientId;
    var hasToken = headers.TryGetValue("Authorization", out token);
    var hasClientId = headers.TryGetValue("Client-id", out clientId);

    client = new HttpClient();
    client.DefaultRequestHeaders.Add("Accept", "application/json");

    if (hasToken)
    {
        var authToken = token.ToString().Replace("Bearer", "");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
    }

    if (hasClientId)
    {
        client.DefaultRequestHeaders.Add("Client-ID", clientId.ToString());
    }
}

A: It turns out that the auth header is removed by the HttpClient and this is by design. The following link gives a good explanation about it: Authorization header is lost on redirect


text:
Q: Detect whether a Windows 8 Store App has a touch screen There are certain elements of Win 8 Store App UI that change based on whether the user has a touch screen. For example, a ScrollViewer, when rendered on a non-touch screen shows a vertical scrollbar. On a touch screen, the scrollbar is hidden.
I would like to tailor my application UI, adding extra controls, for non-touch screen users. Does anyone know if it is possible to detect whether a user has a touch screen?

A: You can use the Windows.Devices.Input namespace to detect various capabilities (touch, keyboard, mouse, etc.).  For example, the TouchCapabilities class has a TouchPresent property you could check to see if there's a digitizer available.
Take a look at the Input: Device capabilities sample to see them in action.

A: If you are using HTML/JS you can query it like this
var touchCapabilities = new Windows.Devices.Input.TouchCapabilities();
var isTouchCapable = touchCapabilities.touchPresent;


text:
Q: How to your own C++ cout << like object I was just asking if you can create your own cout<< like object in C++. most people confuse my question with operator overloading <<. But no, i dont want to implement my own << operator so that when users print my object i can control what they get. But basically i want to implement like this:
something << some_given << some_end;

Not sure if that is possible , but the iostream standard library created the cout , so my mind says "Why not?". So i asked stackoverflow. Help would be appreciated! :)

A: I'm not sure if I interpretted your question correctly but I think you want a class with an overloaded operator<< so that's what i have here
class MyClass {
  public:
    MyClass() = default;
    MyClass& operator<<(int input) {
      //do something with input
      return *this;
    }
}

You would use it like this;
MyClass myObject;
myObject << 42;
//the function would have been called


text:
Q: Weird Issue with JScrollPane - scroll bar not showing up despite use of: setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); So, in the code below I have a JTextArea on the left side. A JScrollPane on the upper right side that looks fine. Using the same code I also add a JScrollPane on the lower right side, but despite identical code, save the preferred sizes and absolute positioning, the vertical scroll bar does not seem to show up.
I will add a screenshot of the GUI after the code. Thank you in advance for any help resolving this issue.
    frame = new JFrame("Title");
    frame.setLayout(null);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.getContentPane().setPreferredSize(new Dimension(width, height));
    frame.pack();

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
    frame.setResizable(false);
    frame.addKeyListener(this);

    //scroll and text area
        textArea = new JTextArea();
        textArea.setText("Static Text\n");
        textArea.setFont(new Font("Consolas", 0, 12));
        textArea.setColumns(50);
        textArea.setLineWrap(true);
        textArea.setEditable(false);
        scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(width/2, height * 4 / 5));
        scrollPane.setBounds(width/2, 0, width/2, height * 4 / 5);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        frame.add(scrollPane);
        inputTextArea = new JTextArea();
        inputTextArea.setText(">");
        inputTextArea.setFont(new Font("Consolas", 0, 12));
        inputTextArea.setColumns(50);
        inputTextArea.setLineWrap(true);
        inputScrollPane = new JScrollPane(inputTextArea);
        inputScrollPane.setPreferredSize(new Dimension(width/2, height / 5));
        inputScrollPane.setBounds(width/2, height * 4 / 5, width, height);
        inputScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        frame.add(inputScrollPane);
    //map
        mapView = new JTextArea();
        mapView.setFont(new Font("Consolas", 0, 8));
        mapView.setEditable(false);
        mapView.setPreferredSize(new Dimension(width/2, height));
        mapView.setText(state.getCurrentMap().toString());
        mapView.addKeyListener(this);
        mapView.setBounds(0, 0, width/2, height);
        frame.add(mapView);

    frame.pack();
    frame.setVisible(true);

A: You've several significant issues with that code including

*

*Use of null layouts. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one. This is making your debugging work more difficult, believe me. For that reason you're far better off learning about and using the layout managers. You can find the layout manager tutorial here: Layout Manager Tutorial, and you can find links to the Swing tutorials and to other Swing resources here: Swing Info.

*You're setting the sizes/bounds of your JTextAreas. This prevents them from expanding appropriately when text is added, and will prevent scrollbars from the surrounding JScrollBars from appearing. Set the JTextArea column and row properties instead.

*Adding a KeyListener to your text components. While this is not causing your current error, it is something that should be avoided and will often mess with the function of the component. Much better to use higher level listeners such as DocumentListener or DocumentFilter.

For example, the code below shows how to use simple layouts, text area column and row properties, as well as use of key bindings to capture the user's pressing the enter key, in case this is desired:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class LayoutExample extends JPanel {
    private static final int MV_ROWS = 65;
    private static final int MV_COLS = 100;
    private static final int TA_ROWS = 34;
    private static final int TA_COLS = 54;
    private static final int ITA_ROWS = 8;
    private static final Font MV_FONT = new Font("Consolas", 0, 8);
    private static final Font TA_FONT = new Font("Consolas", 0, 12);

    private JTextArea mapView = new JTextArea(MV_ROWS, MV_COLS);
    private JTextArea textArea = new JTextArea("Static Text\n", TA_ROWS, TA_COLS);
    private JTextArea inputTextArea = new JTextArea(ITA_ROWS, TA_COLS);

    public LayoutExample() {
        mapView.setFont(MV_FONT);
        mapView.setEditable(false);
        mapView.setFocusable(false);
        JScrollPane mvScrollPane = new JScrollPane(mapView);

        textArea.setFont(TA_FONT);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setEditable(false);
        textArea.setFocusable(false);
        JScrollPane taScrollPane = new JScrollPane(textArea);
        taScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setEnterKeyBindings(inputTextArea);
        inputTextArea.setFont(TA_FONT);
        inputTextArea.setLineWrap(true);
        inputTextArea.setWrapStyleWord(true);
        JScrollPane itaScrollPane = new JScrollPane(inputTextArea);
        itaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.add(taScrollPane, BorderLayout.CENTER);
        rightPanel.add(itaScrollPane, BorderLayout.PAGE_END);

        setLayout(new GridLayout(1, 0));
        add(mvScrollPane);
        add(rightPanel);

        inputTextArea.setText(">");
    }

    // to capture the "enter" key being pressed without having to use a
    // KeyListener
    private void setEnterKeyBindings(final JTextArea textComponent) {
        // only accept input when this component is focused
        int condition = WHEN_FOCUSED;
        InputMap inputMap = textComponent.getInputMap(condition);
        ActionMap actionMap = textComponent.getActionMap();

        // only will bind one keystroke -- that for enter key
        KeyStroke enterKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        inputMap.put(enterKeyStroke, enterKeyStroke.toString());

        // action to take if enter is pressed
        actionMap.put(enterKeyStroke.toString(), new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // get text from input text area, and then clear text
                String text = textComponent.getText();
                textComponent.setText(">");

                // append this text to the upper text area
                textArea.append(text + "\n");

                // TODO: send text elsewhere via chat?
            }
        });
    }

    private static void createAndShowGui() {
        LayoutExample mainPanel = new LayoutExample();

        JFrame frame = new JFrame("Title");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}


text:
Q: Delay differential equation uniqueness - Please help :( I am having a really hard time understanding this problem. I know that for uniqueness we need that the derivative is continuous and that the partial derivative is continuous. I also know that the lipschitz condition gives continuity. I can't figure out what to do with this problem though.

A: Here is a hint.   Consider the operator $T$ defined below that maps continuous functions into continuous functions.  For any $h\in C(-\infty,r]$, let
$$
(Th)(t) := \phi(0) + \int_0^t f(\tau, h(\tau), h(g(\tau)))\  d\tau
$$
when $t>0$ and let $(Th)(t)= \phi(t)$ when $t\leq0$.  Notice that $T: C(-\infty,r] \rightarrow C(-\infty,r]$.
Think about the fixed points of $T$.  If $h(t)$ is a fixed point of $T$, what differential equation would it satisfy?
To show that $T$ is a contraction for some value of $r>0$, you need to show that there exists an $r>0$ and a corresponding $\alpha\in (0,1)$ such that for any two functions $h_1$ and $h_2$ in $C(-\infty,r]$,
$$
d(Th_1, Th_2) \leq \alpha \,d(h_1, h_2).
$$
That proof could be broken down into a few steps:
1) $d(Th_1, Th_2) := \sup_{t\in (-\infty, r]} | Th_1(t) - Th_2(t)|$.
2) $d(Th_1, Th_2) = \sup_{t\in (0, r]} \left| \int_0^t f(\tau, h_1(\tau), h_1(g(\tau))) - f(\tau, h_2(\tau), h_2(g(\tau)))\, d\tau \right|$.
3) $d(Th_1, Th_2) \leq \sup_{t\in (0, r]} \int_0^t |\,f(\tau, h_1(\tau), h_1(g(\tau))) - f(\tau, h_2(\tau), h_2(g(\tau)))|\, d\tau$.
4) $d(Th_1, Th_2) \leq 2 r L\, d(h_1, h_2)$.
5) $T$ is a contraction if $0\leq r < 1/(2 L)$.
Proving each of those statements would be most of the complete proof.  I have left some of the details for you to fill in.  Once you have done a dozen similar proofs, the whole process will seem much easier.

A: The problem has some inherent unboundedness in the way it is posed. You need to get rid of that in order to pursue. Some suggestions:
Pick first $r_0>0$ arbitrary and note that by compactness + continuity, $g([0,r_0])=[a,b]$ is a compact subset of $(-\infty,r_0]$. Therefore,
$$ R = \sup \left\{ |\phi(u)| : u \in g([0,r_0])\cap (-\infty,0])\right\} < +\infty$$
Intuitively, this gives a bound on the delayed $x$ when the delay goes negative.
Let $ M = R + 1+ |\phi(0)|$.
Again by compactness we have that:
 $$ C = {\rm max}\; f([0,r_0]\times[-M,M]\times[-M,M]) +1 \in (0, + \infty)$$
This provides bounds upon $f$ on the 'relevant' domain. We now shrink $r$ to
take into account that $x$ should not become too big:
 $$ r = {\rm min} \{ r_0, (R+1)/C, 1/(4L)\} >0$$
The first is clear, the second because we don't want an integrated $x$ to go beyond $M$ and the last because we need a contraction in the end. We
define
$$ {\cal C} = \{ x\in C ((-\infty,r] ; {\Bbb R}): x(t)=\phi(t), t\leq 0; |x(t)|\leq M, t\in [0,r]\}$$
This is a closed subset of the Banach space where $M=+\infty$ and
$\|x\| = \sup_{0\leq t\leq r} |x(t)|$ (note that the negative part is fixed, you don't have to consider it in the norm). Finally, we define as usual:
  $$ Tx(t) = \phi(0) + \int_0^t f(t,x(t),x(g(t)) dt, \; \; 0\leq t\leq r .$$
Our choice of $r$  (calculation...) ensures that for $x,x_1,x_2\in {\cal C}$:
$$ \|Tx\|\leq M \; \; {\rm and} \; \;  \|Tx_1-Tx_2\|\leq \frac12 \|x_1-x_2\|$$
so $T$ is a contraction on ${\cal C}$ and the rest is standard. One rather crucial point (which makes the problem tractable) is that the delay does not depend upon $x$, only upon $t$.


text:
Q: Angular ErrorInterceptor unit test not working as expected I have an Angular 9 project which uses an error interceptor. The code looks as follows:
constructor(private notificationService: NotificationService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        retry(2),
        catchError(err => {
            return throwError(this.handleError(err));
        })
    );
}

private handleError(err) {
    let errorMessage = '';
    if (err instanceof ErrorEvent) {
        errorMessage = `Error: ${err.error.message}`;
    } else if (err instanceof HttpErrorResponse) {
        errorMessage = this.handleServerSideError(err);
    } else if (err instanceof Error) { // server side body error
        errorMessage = `Error: ${err.message}`;
    }

    if(errorMessage != "")
    {
        this.notificationService.showError(errorMessage, this.somethingWentWrong);
    }

    return errorMessage;
}

private handleServerSideError(err: HttpErrorResponse): string {
    let errorMessage = '';
    switch (err.status) {
        case 401:
            errorMessage = this.getInvalidCredentials;
            break;
        case 403:
            errorMessage = this.getNotauthorised;
            break;
        case 409:
            errorMessage = this.actionAlreadyBeingPerformed;
            break;
    }
    return errorMessage;
}

But the tests written by me doesnt work. It says that it is successfull but if I change the expect->toEqual to another string, it still is succesfully. So my unit test doesnt work. I have a feeling that I'm doing something wrong but I don't know what. What I want to test is as follows "testing a failed get request". The code you can find below:
beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [ HttpClientTestingModule, ToastrModule.forRoot() ],
        providers: [ ErrorInterceptor,
            NotificationService,
            { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
          ]
    });

    notificationService = TestBed.inject(NotificationService);
    httpClient = TestBed.inject(HttpClient);
    httpMock = TestBed.inject(HttpTestingController);
    errorInterceptor = TestBed.inject(ErrorInterceptor);
});

it('should handle error of type Error',() => {
    var notificationServiceSpy = spyOn(notificationService, "showError");

    // Make an HTTP GET request
    httpClient.get<Data>("url").subscribe(
        (error: Error) => {
            expect(error.message).toEqual("Error: the error message");
            expect(notificationServiceSpy).toHaveBeenCalledWith("Error: the error message", "Er is iets mis gegaan")
        }
    );

    // The following `expectOne()` will match the request's URL.
    const req = httpMock.expectOne("url")

    // Respond with mock error
    req.flush('', { status: 401, statusText: 'the error message' });
});

A: *

*First, you need to use the error method and not flush

*Then this is an asynchronous test so you need to tell jasmine when the test is complete using the done function for example:
it('should handle error of type Error',(done) => {
  var notificationServiceSpy = spyOn(notificationService, "showError");

  // Make an HTTP GET request
  httpClient.get<Data>("url").subscribe(() => {},
      (error: Error) => {
          expect(error.message).toEqual("Error: the error message");
          expect(notificationServiceSpy).toHaveBeenCalledWith("Error: the error message", "Er is iets mis gegaan");
         done(); // Inform jasmine that test is over
      }
  );

  // The following `expectOne()` will match the request's URL.
  const req = httpMock.expectOne("url")

  // Respond with mock error
  req.error(new HttpErrorResponse({error: 'the error message', status: 401}) as any);
});


text:
Q: $\mathbb{Q}(i,\sqrt{2})$ is a splitting field of $f_{\mathbb{Q}}^{i+\sqrt{2}} $ and $\operatorname{Aut}(\mathbb{Q}(i,\sqrt{2})) \cong V_{4}$ So hi all, I'm trying to show that $\operatorname{Aut}(\mathbb{Q}(i,\sqrt{2}))$ is isomorphic to $V_4$ but I don't have enough intuition for this yet to solve it. Would you like to give me some advice? Thanks in advance. And sorry if someone else asked this question already; I couldn't find it.
What I've found already is that $f_{\mathbb{Q}}^{i+\sqrt{2}} = X^{4} - 2X^{2} + 9$ and I think that this yields that $\mathbb{Q}(-i-\sqrt{2},-i+\sqrt{2},i-\sqrt{2},i+\sqrt{2}) = \mathbb{Q}(i,\sqrt{2}). $


text:
Q: Using regular expressions to check the format of all values in a dataframe I am trying to check that all the values in my dataframe have the same format and retrieve the values and corresponding column names and index for those that do not match. For example, 0.1, 0.01, 12.4, 12.44 and 1 are allowed, however, 24..2 or 60*9 are not allowed (these are some wrongly entered values I found in my dataframe).
I have tried the following:
value = '24..2'
df[df.eq(value1).any(1)]

Then, manually look for the value and corresponding column its under and replace it with the most probable correct value:
df['column_name'] = df['column_name'].replace("24..2", "24.2")

I have also tried to automate this by using findall() regular expression. It finds a list of matches, but I have not been able to find a way to return the non-matches and corresponding columns that they are under.
import re
for val in vals:
    found = re.findall("[0-9]+\.?[0-9]*", val)
    if found:
    print(found)

Any help would be greatly appreciated.

A: You could use list comprehension, such as the following untested example:
[(val, index) for val, index in enumerate(vals) if len(re.findall("[0-9]+\.?[0-9]*", val)) == 0]

This will create a list of tuples. Each tuple contains val and its index in vals if there are no matches. Cases where val does return a match will not be added to the list. You will probably have to change the snippet len(re.findall("[0-9]+\.?[0-9]*", val)) == 0 to something else as empty matches might still return a value. It has been a little bit since iv'e used the re module. Either way, that snippet is what determines if the value gets added to the list.
Update
re.search(pattern, string) returns None if there is no match. So you can do:
if re.search(pattern, string) == None:
    # No match was found


text:
Q: Graphic Excel VBA the following code allow me to plot a graph with the data i selected from tw odifferents colum
definition variables
Dim DerniereLigne_B As Integer
Dim DerniereLigne_C As Integer

'Définition dernière case non vide'
DerniereLigne_B = Range("B65536").End(xlUp).Row
DerniereLigne_C = Range("C65536").End(xlUp).Row

'Creation graph
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatterSmooth
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Name = "=""Autoclave cycle"""

ActiveChart.SeriesCollection(1).XValues = "='feuillet 1'!$B$4:$B$" & DerniereLigne_B

ActiveChart.SeriesCollection(1).XValues = "='feuillet 1'!$C$4:$C$" & DerniereLigne_C

But i want to make it work what ever sheet i have open. To do so, I create a string variable that is name from my actif sheet
Dim nomfeuille As String
nomfeuille = ActiveSheet.Name

I want to replace my sheet name by my variable created above
ActiveChart.SeriesCollection(1).XValues = _
     "='feuillet 1'!$B$4:$B$" & DerniereLigne_B

I tried it like this
ActiveChart.SeriesCollection(1).XValues = _
      "='nomfeuille'!$B$4:$B$" & DerniereLigne_B

But it is not working. How can i write it right to make it work ?
if it can not work do you have idees to make it work. i want to create a graph from the same column variable everytime but with the active sheet.

A: Like this:
Dim nomfeuille As String

nomfeuille = ActiveSheet.Name

ActiveChart.SeriesCollection(1).XValues = _
            "='" & nomfeuille & "'!$B$4:$B$" & DerniereLigne_B


text:
Q: Efficiently uploading files to a CDN I'm using Rackspace's CDN for hosting all my website's media (images and video).  Every time a user uploads something, I use this process:

*

*Uploadify sends the file upload to a PHP method

*The PHP method hashes the file name, uploads the file to a tmp directory, creates a thumbnail version (if necessary), and returns both the hashed file name and the thumbnail name

*jQuery is used to replace a preview image src's with: /location/to/tmp/file_name and store the file_name also in a hidden input.

*When the form is submitted, the $_POST value for the hidden input is used to upload the file to the CDN, and store the CDN location in a relational MySQL table

This is all fine -- everything works.
But I've been wondering lately if this is the most efficient way of doing this -- because, at the moment, the script is uploading the file to the CDN in the middle of the method which processes the file.  Sometimes the form will have up to 10-12 images (some more than 1MB), so that's a lot of data transfer to do in the middle of a processing function -- I'm worried that it will unnecessarily slow things down.  It's alright on my localhost, and on a shared host for staging, and I'm sure it'll be no problem when we roll it out on the production VPS, but I still want to get things as right as possible.
Should I leave all the CDN uploads to a cronjob, or is the approach I'm using right now okay?

A: It most likely depends on limitations (if there are any) enforced on the Rackspace CDN - and how many concurrent users you have uploading.
If they have a limit and you might get close to reaching it on production environment - it would be safer to implement some sort of queuing server for CDN upload.


text:
Q: Computing number of bits that are set to 1 for matching rows in terms of hamming distance between two data frames I have two data frames of same number of columns (but not rows) df1 and df2. For each row in df2, I was able to find the best (and second best) matching rows from df1 in terms of hamming distance, in my previous post. In that post, we have been using the following example data:
set.seed(0)
df1 <- as.data.frame(matrix(sample(1:10), ncol = 2))  ## 5 rows 2 cols
df2 <- as.data.frame(matrix(sample(1:6), ncol = 2))  ## 3 rows 2 cols

I now need to compute the number of bits equal to 1 for:

*

*each row in df2

*the best matching rows in df1

*the second matching rows in df1
The number of bits equal to 1 of an integer a maybe computed as
sum(as.integer(intToBits(a)))

And I have applied this to @ZheyuanLi's original function, so I have got item 1>. However I'm unable to apply the same logic to get item 2> and 3>, by simple modification of @ZheyuanLi's function.
Below are the functions from @ZheyuanLi's with modification:
hmd <- function(x,y) {
    rawx <- intToBits(x)
    rawy <- intToBits(y)
    nx <- length(rawx)
    ny <- length(rawy)
    if (nx == ny) {
        ## quick return
        return (sum(as.logical(xor(rawx,rawy))))
    } else if (nx < ny) {
        ## pivoting
        tmp <- rawx; rawx <- rawy; rawy <- tmp
        tmp <- nx; nx <- ny; ny <- tmp
    }
    if (nx %% ny) stop("unconformable length!") else {
        nc <- nx / ny  ## number of cycles
        return(unname(tapply(as.logical(xor(rawx,rawy)), rep(1:nc, each=ny), sum)))
    }
}

foo <- function(df1, df2, p = 2) {
    ## check p
    if (p > nrow(df2)) p <- nrow(df2)
    ## transpose for CPU cache friendly code
    xt <- t(as.matrix(df1))
    yt <- t(as.matrix(df2))
    ## after transpose, we compute hamming distance column by column
    ## a for loop is decent; no performance gain from apply family
    n <- ncol(yt)
    id <- integer(n * p)
    d <- numeric(n * p)
    sb <- integer(n)
    k <- 1:p
    for (i in 1:n) {
        set.bits <- sum(as.integer(intToBits(yt[,i])))
        distance <- hmd(xt, yt[,i])
        minp <- order(distance)[1:p]
        id[k] <- minp
        d[k] <- distance[minp]
        sb[i] <- set.bits
        k <- k + p
    }
    ## recode "id", "d" and "sb" into data frame and return
    id <- as.data.frame(matrix(id, ncol = p, byrow = TRUE))
    colnames(id) <- paste0("min.", 1:p)
    d <- as.data.frame(matrix(d, ncol = p, byrow = TRUE))
    colnames(d) <- paste0("mindist.", 1:p)
    sb <- as.data.frame(matrix(sb, ncol = 1))  ## no need for byrow as you have only 1 column
    colnames(sb) <- "set.bits.1"
    list(id = id, d = d, sb = sb)
}

Running these gives:
> foo(df1, df2)
$id
  min1 min2  ## row id for best/second best match in df1
1    1    4
2    2    3
3    5    2

$d
  mindist.1 mindist.2  ## minimum 2 hamming distance
1         2         2
2         1         3
3         1         3

$sb
  set.bits.1  ## number of bits equal to 1 for each row of df2
1          3
2          2
3          4

A: OK, after reading through while re-editing your question (many times!), I think I know what you want. Essentially we need change nothing to hmd(). Your required items 1>, 2>, 3> can all be computed after the for loop in foo().
To get item 1>, which you called sb, we can use a tapply(). However, your computation of sb along the for loop is fine, so I will not change it. In the following, I will demonstrate the basic procedure to get item 2> and item 3>.
The id vector inside foo() stores all matching rows in df1:
id <- c(1, 4, 2, 3, 5, 2)

so we can simply extract those rows of df1 (actually, columns of xt), to compute the number of bits equal to 1. As you can see, there are lots of duplicity in id, so we can only computes on unique(id):
id0 <- sort(unique(id))
## [1] 1 2 3 4 5

We now extract those subset columns of xt:
sub_xt <- xt[, id0]
##    [,1] [,2] [,3] [,4] [,5]
## V1    9    3   10    5    6
## V2    2    4    8    7    1

To compute the number of bits equal to 1 for each column of sub_xt, we again use tapply() and vectorized approach.
rawbits <- as.integer(intToBits(as.numeric(sub_xt)))  ## convert sub_xt to binary
sbxt0 <- unname(tapply(X = rawbits,
                      INDEX =  rep(1:length(id0), each = length(rawbits) / length(id0)),
                      FUN = sum))
## [1] 3 3 3 5 3

Now we need to map sbxt0 to sbxt:
sbxt <- sbxt0[match(id, id0)]
## [1] 3 5 3 3 3 3

Then we can convert sbxt to a data frame sb1:
sb1 <- as.data.frame(matrix(sbxt, ncol = p, byrow = TRUE))
colnames(sb1) <- paste(paste0("min.", 1:p), "set.bits.1", sep = ".")
##   min.1.set.bits.1 min.2.set.bits.1
## 1                3                5
## 2                3                3
## 3                3                3

Finally we can assemble these things up:
foo <- function(df1, df2, p = 2) {
    ## check p
    if (p > nrow(df2)) p <- nrow(df2)
    ## transpose for CPU cache friendly code
    xt <- t(as.matrix(df1))
    yt <- t(as.matrix(df2))
    ## after transpose, we compute hamming distance column by column
    ## a for loop is decent; no performance gain from apply family
    n <- ncol(yt)
    id <- integer(n * p)
    d <- numeric(n * p)
    sb2 <- integer(n)
    k <- 1:p
    for (i in 1:n) {
        set.bits <- sum(as.integer(intToBits(yt[,i])))
        distance <- hmd(xt, yt[,i])
        minp <- order(distance)[1:p]
        id[k] <- minp
        d[k] <- distance[minp]
        sb2[i] <- set.bits
        k <- k + p
    }
    ## compute "sb1"
    id0 <- sort(unique(id))
    sub_xt <- xt[, id0]
    rawbits <- as.integer(intToBits(as.numeric(sub_xt)))  ## convert sub_xt to binary
    sbxt0 <- unname(tapply(X = rawbits,
                           INDEX =  rep(1:length(id0), each = length(rawbits) / length(id0)),
                           FUN = sum))
    sbxt <- sbxt0[match(id, id0)]
    sb1 <- as.data.frame(matrix(sbxt, ncol = p, byrow = TRUE))
    colnames(sb1) <- paste(paste0("min.", 1:p), "set.bits.1", sep = ".")
    ## recode "id", "d" and "sb2" into data frame and return
    id <- as.data.frame(matrix(id, ncol = p, byrow = TRUE))
    colnames(id) <- paste0("min.", 1:p)
    d <- as.data.frame(matrix(d, ncol = p, byrow = TRUE))
    colnames(d) <- paste0("mindist.", 1:p)
    sb2 <- as.data.frame(matrix(sb2, ncol = 1))  ## no need for byrow as you have only 1 column
    colnames(sb2) <- "set.bits.1"
    list(id = id, d = d, sb1 = sb1, sb2 = sb2)
}

Now, running foo(df1, df2) gives:
> foo(df1,df2)
$id
   min.1 min.2
 1     1     4
 2     2     3
 3     5     2

 $d
  mindist.1 mindist.2
1         2         2
2         1         3
3         1         3

$sb1
   min.1.set.bits.1 min.2.set.bits.1
 1                3                5
 2                3                3
 3                3                3

$sb2
  set.bits.1
1          3
2          2
3          4

Note that I have renamed the sb you used to sb2.


text:
Q: error hetting while iteration over list and dictionary import os
import sys

lst = ["ABCD", "LMN" , "STU" , "PQRS" ]

dict = { 'ABCD':'kajal' , 'LMN' :'John' , 'PQRS' : 'Anni'}

for i in lst:
    for k,l in dict.items():
        if i == k:
            print(i,l)
        else:
            print(i,"no id")

output :
('ABCD', 'kajal')
('ABCD', 'no id')
('ABCD', 'no id')
('LMN', 'no id')
('LMN', 'no id')
('LMN', 'John')
('STU', 'no id')
('STU', 'no id')
('STU', 'no id')
('PQRS', 'no id')
('PQRS', 'Anni')
('PQRS', 'no id')

Expected output :
('ABCD', 'kajal')
('LMN', 'John')
('STU', 'no id')
('PQRS', 'Anni')

A: The reason yours is not working is because you are checking each item three times, where you only need to check it one time.
For each item in your list, you are checking it against every key/value pair in the dictionary; since there are three keys, you get three outputs for each item in your list.
Try something simple:
for i in lst:
   print(tuple(i, dict.get(i, 'no id')))

A: First, avoid using variable names like dict - it masks the standard function with the same name.  You are iterating once through the list, and then for the dictionary.  Here is an alternative method:
lst = ["ABCD", "LMN" , "STU" , "PQRS" ]

mydict = { 'ABCD':'kajal' , 'LMN' :'John' , 'PQRS' : 'Anni'}

for i in lst:
    if i in mydict:
        print(i,mydict[i])
    else:
        print(i,"no id")

Using the in keyword tests for the presence of a key.
By the way, the presence of the ( ) in the output suggests you are using python 3 syntax for your print statement in python 2.

A: import os
import sys

lst = ["ABCD", "LMN" , "STU" , "PQRS" ]

dict = { 'ABCD':'kajal' , 'LMN' :'John' , 'PQRS' : 'Anni'}

for i in lst:
    if i in dict:
        print(i, dict[i])
    else:
        print(i, "no id")

Simply, you iterated over the dict too, hence the multiple entiries

A: def list_from_dict(id, dictionary):
    if id in dictionary.keys():
        return id, dictionary[id]
    else:
        return id,"no id"

lst = ["ABCD", "LMN" , "STU" , "PQRS" ]
dic = { 'ABCD':'kajal' , 'LMN' :'John' , 'PQRS' : 'Anni'}

for items in lst:
    print(list_from_dict(items,dic))


text:
Q: 'Ignoring return value' warning I am receiving warning: ignoring return value of 'getcwd', declared with attribute warn_unused_result
#define get_current_dirr when running this code:
#define get_current_dir getcwd
FILE *open_particle_data()
{
    FILE *data_file;
    char data_file_name[] = "particle_data.txt";
    char buff[FILENAME_MAX];
    get_current_dir(buff, FILENAME_MAX);
    char *output_dir;
    char str1[] = "/output_data/";
    output_dir = malloc(strlen(buff) + strlen(str1) + strlen(data_file_name) + 1);
    strcpy(output_dir, buff);
    strcat(output_dir, str1);
    strcat(output_dir, data_file_name);
    data_file = fopen(output_dir,"w");
    free(output_dir);
    return data_file;

Any help would be appreciated. Thanks

A: Various functions in Glibc are annotated in a way that suggests to the compiler that it is suspicious for their return values to be ignored.  When GCC observes during compilation that the return value of such a function indeed is ignored, it (by default) issues a warning about that.  That is what you are seeing.
The C language allows you to ignore function return values, but doing so is often a mistake.  In particular, many functions' return values contain information about function success or failure, and neglecting to account for the possibility of failure can lead to erroneous, possibly even destructive behavior.  And that may not manifest until later, making such issues difficult to debug.
getcwd() in particular returns a null pointer when it fails, and in that case you cannot rely on it to have written a valid string into the specified buffer.  A robust program would detect such a return value and handle it gracefully.  For example, the program might emit a diagnostic message and terminate when it observes getcwd() to fail.
On the other hand, if you just want to silence the error without actually fixing the issue, then you can cast the return value to void to explicitly indicate to GCC and to some other compilers that you are intentionally ignoring it.  I do not recommend this.

A: As an extension to the response of John Bollinger, I'll say that getcwd() returns a pointer to the passed buffer in case of successful execution, and NULL in case of error.  You should use that returned value, in order to see if getcwd() executed correctly, as some cases could make it fail:

*

*the size of the passed buffer is zero.

*a component of the pathname no longer exists (this can happen if the paren directory of some visited directory has been eliminated)

*The buffer size does not fit the actual path name.

*read or execute permission in some of the directories up to the root is not granted to the process.

Being the most common that you have provided a short buffer to store the path.


text:
Q: Recoding variables after multiple imputation After multiple imputation, the missing values are provided with a imputed valid data which appear as a separate entity. So I corrected this by using the recode to same variables. Instead of using fixed values. For example, 0=0, I used a range because multiple imputation uses a range and thus recoded them as 0 through 1 to 1 and so on. I got the answer and all the imputed data was grouped into the intended categories of the variables.
I would like to know if it is best practice to do that. Is there any reference that using range for multiple imputation is good.

A: Multiple Imputation already adds randomness in the different imputations, so I don't seen the point of overriding that.


text:
Q: webpack-dev-server + protractor - invalid host header
*

*OS: macOS Sierra 10.12.4

*Node: v7.9.0

*Npm: 5.0.3

*Cucumber-js: 2.3.0

*Protractor: 4.0.14

*TypeScript: 2.2.2

*webpack-dev-server: 2.4.5

Hi
i have a problem with running protractor tests with webpack-dev-server in version > 2.4.3. When I run tests the browser shows message: 'Invalid host header' and tests fail. If I change the version of webpack-dev-server to 2.4.2 everything works fine. I know the option 'public' in webpack but I do not know what host or ip I should put to protractor works. I think I tried everything. Here is my webpack.config:
'use strict';

const HtmlWebpack = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const extractPlugin = new ExtractTextPlugin({
   filename: 'main.css'
});
const CleanWebpack = require('clean-webpack-plugin');

const rootDir = path.resolve(__dirname);

module.exports = {
    devServer: {
        contentBase: path.resolve(rootDir, 'dist'),
        port: 3000,
        host: '0.0.0.0',
        disableHostCheck: false,
        public: '172.23.0.1'
    },
    watchOptions: {
        poll: true
    },
    devtool: 'source-map',
    entry: {
        "bundle": "./src/webpack.main.js",
        "plugins": "./src/plugins.js"
    },
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "[name].js",
        sourceMapFilename: '[file].map'
        // publicPath: "/dist"
    },
    resolve: {
        extensions: [ '.js', '.ts' ]
    },
    module: {
        exprContextCritical: false,
        rules: [
            {
                test: /\.html$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]'
                        },
                    },
                    { loader: 'extract-loader' },
                    { loader: 'html-loader' }
                ],
                exclude: path.resolve(__dirname, 'src/index.html')
            },
            {
                test: /\index.html$/,
                loader: ['html-loader']
            },
            {
                test: /\.ts$/,
                loader: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(scss|css)$/,
                use: extractPlugin.extract({
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.(jpg|png|gif|eot|ttf|svg|woff|woff2)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'img/',
                        publicPath: 'img/'
                    }
                }]
            },
        ],
    },
    plugins: [
        new CleanWebpack(['dist']),
        extractPlugin,
        new HtmlWebpack({
            template: 'src/index.html'
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "Tether": 'tether'
        }),
        new HtmlWebpackPlugin({
            template: './src/index.html',
            filename: 'index.html',
            inject: 'body'
        }),
    ],
};

I set the public option to: 172.23.0.1 so I can open dockerized app in the browser (172.23.0.1 is my host ip in docker network).
Here is my protractor.config:
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var webpackConfig = require('./webpack.config');
var deasync = require('deasync');
var server;

exports.config = {
    // seleniumAddress: 'http://selenium-standalone-chrome:4444/wd/hub',
    baseUrl: 'http://0.0.0.0:3000',
    useAllAngular2AppRoots: true,
    directConnect: true,
    beforeLaunch: () => {

        var isServerReady = false;
        var isBundleReady = false;
        var compiler = webpack(webpackConfig, () => {
            isBundleReady = true;
            console.log('Dumpstere bundled...');
        });

        server = new WebpackDevServer(compiler, {});

        server.listen(3000, () => {
            isServerReady = true;
            console.log('Dumpstere started...');
        });

        deasync.loopWhile(() => !isServerReady || !isBundleReady);
    },
    afterLaunch: () => {
        server.close();
    },
    capabilities: {
        browserName:'chrome'
    },

    framework: 'custom',

    frameworkPath: require.resolve('protractor-cucumber-framework'),
    specs: [
        './features/*.feature'
    ],
    cucumberOpts: {
        require: ['./features/step_definitions/*.ts'],
        tags: [],
        strict: false,
        format: ["pretty", "json:report/json/cucumber_report.json"],
        dryRun: false,
        compiler: ["ts:ts-node/register"]
    },

    onPrepare: function () {
        browser.ignoreSynchronization = true;
        browser.manage().window().maximize();
    }
};


text:
Q: How do coordinate wise meta-learning optimizers update learner networks? I was reading Optimization as a model for few shot learning and Learning to learn by gradient descent by gradient descent as I noticed both papers use something they call

coordinate wise optimzers

for what seems good reasons for efficiency. However, does that mean that their LSTM models are 1D vectors because they only output one coordinate at a time AND because they share parameters across coordinates too?
I guess my main clarification and worry is this:
In the paper they say they share parameters across coordinates. In particular what I am worried about is that forget and update gates take $theta_{t-1}$ as input and thus if there are many parameters then their matrices would be enormous. For example recall one of the forget/update gate equations:
$$ i^{<t>} =\sigma( W_I [\tilde \nabla^{<t>}, \mathcal L^{<t>}, \theta^{<t>}, i^{<t-1>} ] + b_I )$$
$$ f^{<t>} =\sigma( W_F [\tilde \nabla^{<t>}, \mathcal L^{<t>}, \theta^{<t>}, f^{<t-1>} ] + b_F )$$
Does that mean that for each forget and update gate get they actually only receive 1 single coordinate at a time? i.e. the equations should be (for coordinate j):
$$ i^{<t>}_j =\sigma( W_I [\tilde \nabla^{<t>}, \mathcal L^{<t>}_j, \theta^{<t>}_j, i^{<t-1>}_j ] + b_I )$$
$$ f^{<t>}_i =\sigma( W_F [\tilde \nabla^{<t>}_j, \mathcal L^{<t>}, \theta^{<t>}_j, f^{<t-1>}_j ] + b_F )$$
so when they write $theta_t$ in any part of the paper is it actually just a single number $\theta^{<t>}_j$ (i.e. a single coordinate)? is that correct?

cross-posted:

*

*reddit: https://www.reddit.com/r/deeplearning/comments/fdlnd2/how_do_coordinate_wise_metalearning_optimizers/

*Quora: https://qr.ae/ppuuSi

A: Yes it's coordinate wise. But the trick is that it can be made into a vectorized for as shown here in it's pytorch implementation (https://github.com/markdtw/meta-learning-lstm-pytorch/blob/master/metalearner.py).
The main this is to write it like this (as it's actually implemented):
$$ f^{<t>} = \sigma( W^F_{:,j}[ h^{<t>}_{lstm, j} , \theta^{<t-1>}_j, f^{<t-1>} ] + b^F_j )$$
$$ f^{<t>} = \sigma( W^F_{:,j}[ lstm(\nabla^{<t>}_j , \mathcal L_{j} )_j , \theta^{<t-1>}_j, f^{<t-1>}_j ] + b^F_j )$$
One can vectorize it as follows:
$$ f^{<t>} = \sigma( W^F[ lstm(\nabla^{<t>} , \mathcal L ) , \theta^{<t-1>}, f^{<t-1>} ] + b^F )$$
where $h^{<t>}_{lstm} = lstm(\nabla^{<t>})_j$ is of size $| \theta| \times h_{lstm}$ where $h_{lstm}$ is the size of the lstm in the first layer and $\theta^{<t>}, f^{<t>}$ are of size $|\theta| \times 1$. Note the concatenation makes sure that the $[ lstm(\nabla^{<t>} , \mathcal L ) , \theta^{<t-1>}, f^{<t-1>} ]$ is of size $h_{lstm} \times |\theta|$. That is the main trick and notice that $W^F$ is of size $h_{lstm} \times 1$ and thus the fully connected layer not explode in dimensionality which is crucial!
So the important matrix multiplication:
$$ W^F[ lstm(\nabla^{<t>} , \mathcal L ) , \theta^{<t-1>}, f^{<t-1>} ] $$
is $ ( 1 \times h_{lstm})\times (h_{lstm} \times |\theta|)$
where the lstm parameters is of size $( 1 \times h_{lstm})$ and does NOT include the # of parameters $|\theta|$ in it.
Also, adding the bias is trivial since pytorch just "copies" and adds it to every location automagically in GPU.


text:
Q: Why does the compiler complain that Char and AnsiChar are incompatible when compiling MadRes? I'm compiling MadRes, but the error is this:
Checking project dependencies...
Compiling Project1.dproj (Debug configuration)
[DCC Warning] madRes.pas(351): W1057 Implicit string cast from 'AnsiString' to 'string'
[DCC Warning] madRes.pas(351): W1057 Implicit string cast from 'AnsiString' to 'string'
[DCC Error] madRes.pas(519): E2010 Incompatible types: 'Char' and 'AnsiChar'
[DCC Fatal Error] Unit1.pas(7): F2063 Could not compile used unit 'madRes.pas'
Failed
Elapsed time: 00:00:00.6

and then shows me this part of the unit madRes:
   if GetVersion and $ 80000000 = 0 then
        result: = CreateFileW (fileName, c1, c2, nil, c3, 0, 0)
   else result: = CreateFileA (pchar (string (WideString (fileName))), c1, c2, nil, c3, 0, 0);
end;

The code is a program I found the exe goes well but the problem is when I want to compile from my computer.
someone could help me?

A: You should download and install the current version of madCollection :  http://madshi.net/
It has long since been updated for unicode support - the line in question looks like this now :
result := CreateFileA(PAnsiChar(AnsiString(UnicodeString(fileName))),
                                                       c1, c2, nil, c3, 0, 0);

Delphi's default strings (PChar, etc) changed in D2009 from Ansi to 2-byte unicode; this introduced a need to be explicit about Ansi-specific implementations (PAnsiChar, AnsiString) for compatibility.  If you are interested to read more, I think this article on EDN is probably a good start :
Delphi in a Unicode World


text:
Q: Parse FormData object in nest controller I have a nest controller which accepts the following DTO, One of the parameters should be a buffer which is read from file
It suppose to read bin file
interface LoadFileRequest {
  targetIp: string;
  fileBuffer: Buffer;
  user: User;
}

interface User {
  username: string;
  password: string;
}

@Controller('loader')
export class KeyLoaderController {
  @Post('load')
  async load(@Body() body: LoadFileRequest, @Req() request) {
    console.log(body);
    console.log(request);
  }
}

My code for testing the controller:
import axios from "axios";
import fs from "fs";
import FormData from "form-data";
let headersList = {
  Accept: "*/*",
};

let formdata = new FormData();
formdata.append("targetIP", "10.10.1.145");
formdata.append(
  "user",
  JSON.stringify({
    username: "user",
    password: "auth",
  })
);
formdata.append("fileBuffer", fs.createReadStream("test.bin"));

let bodyContent = formdata;
const url = "http://localhost:3000/loader/load";
let reqOptions = {
  url,
  method: "POST",
  headers: headersList,
  data: { bodyContent },
};

axios.request(reqOptions).then(function (response) {
  console.log(response.data);
});

At the controller this is the request body i get
{
  bodyContent: {
    _overheadLength: 380,
    _valueLength: 48,
    _valuesToMeasure: [ [Object] ],
    writable: false,
    readable: true,
    dataSize: 0,
    maxDataSize: 2097152,
    pauseStreams: true,
    _released: false,
    _streams: [
      '----------------------------092840744027446269037569\r\n' +
        'Content-Disposition: form-data; name="targetIP"\r\n' +
        '\r\n',
      '10.10.1.145',
      null,
      '----------------------------092840744027446269037569\r\n' +
        'Content-Disposition: form-data; name="user"\r\n' +
        '\r\n',
      '{"username":"user","password":"auth"}',
      null,
      '----------------------------092840744027446269037569\r\n' +
        'Content-Disposition: form-data; name="fileBuffer"; filename="test.bin"\r\n' +
        'Content-Type: application/octet-stream\r\n' +
        '\r\n',
      [Object],
      null
    ],
    _currentStream: null,
    _insideLoop: false,
    _pendingNext: false,
    _boundary: '--------------------------092840744027446269037569'
  }
}

How can i get the body in the form of object with only the attrbutes of the DTO?
Eventually i got a method which recived the same type of object and i want to call it like this:
@Controller('loader')
export class KeyLoaderController {
  @Post('load')
  async load(@Body() body: LoadFileRequest, @Req() request) {
    return await loadFile(body);
  }
}

EDIT:
I changed the code a bit and now if i send the request from VS code thunder client it works fine(sort of):
@Controller('loader')
export class KeyLoaderController {
  @Post('load')
  @UseInterceptors(FileInterceptor('fileBuffer'))
  async load(@Body() body, @UploadedFile() file) {
    console.log(body);
    console.log(file);
  }
}

When I send this way (The code on the right is the generated code by the extension, Which does not act the same way when I use it):

This is the body and file I get:
[Object: null prototype] {
  targetIP: '10.10.1.145',
  user: '{ "username": "user", "password": "0123456789"}'
}
{
  fieldname: 'fileBuffer',
  originalname: 'test.bin',
  encoding: '7bit',
  mimetype: 'application/octet-stream',
  buffer: <Buffer ... ... 119 more bytes>,  size: 169
}

But when i take the code i generated in VS code thunder client (which is at axios request in this post) I still get the body like before (again, as mention in the post)

A: If you're sending a multipart/form-data request, you need a form data body parser installed on the server. You can either use the FileInterceptor (or one of the derivatives of it), or bind multer as a middleware for the entire server. This will allow for the parsing of multipart/form-data requests.

In your axios call, remove the brackets around bodyContent so it becomes data: bodyContent. You aren't sending an object of form data you are just sending formdata itself


text:
Q: Javascript Regex not working correctly I am trying to fetch any string between 'null[' and ']' , but for some long strings its missing immediate ] and printing text till some random ']'
However, If I shorten that string, its working fine,
How can I find out the text till immediate ] and not till some random ']'?
Eg .
"value":"vale0[var0]","null[1st]","value":"vale2[var1]","value":"vale3[var3]"
<html>
<head>
    <title>Untitled</title>
     <script type="text/javascript">
      function run(){
            code = document.getElementsByTagName("html")[0].innerHTML;
            results = code.match(/null\[(\S*)\","/g);
            for (i=0;i<results.length;i++) {
            value = results[i].match(/null\[(\S*)\","/);
            alert (value[1])
    }
}
</script>
</head>
<body onload="run()">
        registerFragment("qweeqeqw","null[country-      name-IR_1]","AI_0_1264":"Anguilla[country-name-AI_18096]</body>
</body>
</html>

A: Looks like your regex is just a bit incomplete.  If you want the minimum matching characters between two known sequences, add the ? operator to the *.  This will make the * operator "non-greedy."
null\[(\S*?)\","

In this version, however, the closing bracket will be included in the matched group.  If you want to keep the closing bracket out of the match, add that character, as well.  (Here, I've also replace the \ before the first " because it's not necessary to escape the ".)
null\[(\S*?)]","

And, at this point, you don't even need to check for the "," sequence because the closing ] should do the job on its own:
null\[(\S*?)]

regex101.com example


text:
Q: Upper Bound On A System of Sum Equations For $i=1,2,\ldots,n$, let $d_i$ be a sequence of positive integers and $r_i$ a sequence of positive real numbers with $2\leq d_i\leq n-1$ that satisfy the following system of equations:
$d_i=\sum_{j=1}^n \frac{r_ir_j}{1+r_ir_j}$
for each $i=1,2\ldots,n$.
Question: Can we find a qualitative bound on $r_i$ in terms of $n$? I don't care if it's is a terrible bound, I just want any bound in terms of $n$.
Everything I've tried thus far seems to give me lower bounds on $r_i$. I've considered fudged cases (i.e. not requiring $d_i$ to be integers) of taking part of the $r_i$ to be some number $L$ and the other part to be $1/L$ in hopes of breaking any bound, but one can show that $L$ will be of order $\sqrt{n}$ thereby being bounded for a fixed $n$.
If we suppose wlog that
(*)     $r_1\leq r_2\leq\cdots\leq r_n$,
then a primitive bound on $r_i$ would be:
$\left(\frac{r_1}{1+r_n^2}\right)r_i\leq d_i\leq \left(\frac{r_n}{1+r_1^2}\right)r_i$
but again this is not useful as this doesn't give any information on $r_n$.
Any help with this would be greatly appreciated!

A: This is actually a cutie. I'll denote $x_j=r_j^{-1}$, so the sums in question are $S_i=\sum_j\frac{1}{1+x_ix_j}$. Since you do not care what the bound is, I'll make it as simple as I can rather than making it as sharp as I can.
Lemma: Let $A\ge 1$. Suppose that the set $X=\{x_i\}_{i=1}^n$ contains an element outside the interval $[(An^2)^{-1},An^2]$. Then it contains an element in the union of intervals $[An^2)^{-1},A^{-1})\cup(A,An^2]$
Proof:. Suppose not. Let $I=\{i:x_i<(An^2)^{-1}\}$, $J=\{j:x_j>An^2\}$. Note that $I\cup J\ne\varnothing$. For all other $k$, we have $x_k\in[A^{-1},A]$. Write
$$
\sum_{i\in I}S_i-\sum_{j\in J}S_j=\sum_{i\in i,k\notin J}\frac{1}{1+x_ix_k}-\sum_{j\in j,k\notin I}\frac{1}{1+x_jx_k}
$$
and note that the left hand side is an integer.
However, for $i\in I,k\notin J$, we have $1-\frac 1{n^2}<\frac{1}{1+x_ix_j}<1$ and for $j\in J,k\notin I$, we have $-\frac 1{n^2}<-\frac{1}{1+x_ix_j}<0$. Thus, the right hand side is strictly between $|I|(n-|J|)-1$ and $|I|(n-|J|)$, so we get a contradiction.
If now $X$ contains an element outside $[n^{-2n},n^{2n}]$, this argument can be applied with $A=1,n^2,n^4,n^{2(n-1)}$, giving us $n$ disjoint pairs of intervals each of which should have a point in $X$. Together with the point outside $[n^{-2n},n^{2n}]$, we would have $n+1$ or more points in $X$, which is a clear overcount. Thus, our assumption is false and we must have $n^{-2n}\le r_j\le n^{2n}$ for all $j$.

A: With $0 < r_1 \leq r_2 \leq \cdots \leq r_n$, you can obtain an upper bound on $r_1$ as $r_1 \leq \sqrt{n-1} \leq \sqrt{n}$. However, it doesn't give an upper bound on $r_n$.
Here is how it goes. First you can simplify the sum to get
$$2 \leq n-\sum_{j=1}^n \frac{1}{1+r_ir_j} \leq n-1$$
Simplifying, you'll obtain
$$1 \leq \sum_{j=1}^n \frac{1}{1+r_ir_j} \leq n-2$$
Now,
$1+r_1^2 \leq 1+r_ir_j \leq 1+r_n^2$
so, using on the the left inequality here
$$1 \leq \sum_{j=1}^n \frac{1}{1+r_ir_j} \leq \frac{n}{1+r_1^2}$$
and the bound follows.


text:
Q: How to get Latitude and Longitude of the mobile device in with android studio? how to get the true Latitude and Longitude when a mobile device use the fake GPS for change Latitude and Longitude?

A: You can use the following code sample.
public class CurrentLocation {
Timer timer;
LocationManager locationManager;
LocationResult locationResult;
boolean gpsEnabled=false;
boolean networkEnabled=false;

public boolean getLocation(Context context, LocationResult result)
{
    //I use LocationResult callback class to pass location value from MyLocation to user code.
    locationResult=result;
    if(locationManager ==null)
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    //exceptions will be thrown if provider is not permitted.
    try{
        gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
    try{
        networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

    //don't start listeners if no provider is enabled
    if(!gpsEnabled && !networkEnabled)
        return false;

    if(gpsEnabled)
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
    if(networkEnabled)
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
    timer =new Timer();
    timer.schedule(new GetLastLocation(), 20000);
    return true;
}

LocationListener locationListenerGps = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer.cancel();
        locationResult.gotLocation(location);
        locationManager.removeUpdates(this);
        locationManager.removeUpdates(locationListenerNetwork);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

LocationListener locationListenerNetwork = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer.cancel();
        locationResult.gotLocation(location);
        locationManager.removeUpdates(this);
        locationManager.removeUpdates(locationListenerGps);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

class GetLastLocation extends TimerTask {
    @Override
    public void run() {
        locationManager.removeUpdates(locationListenerGps);
        locationManager.removeUpdates(locationListenerNetwork);

        Location net_loc=null, gps_loc=null;
        if(gpsEnabled)
            gps_loc= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(networkEnabled)
            net_loc= locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        //if there are both values use the latest one
        if(gps_loc!=null && net_loc!=null){
            if(gps_loc.getTime()>net_loc.getTime())
                locationResult.gotLocation(gps_loc);
            else
                locationResult.gotLocation(net_loc);
            return;
        }

        if(gps_loc!=null){
            locationResult.gotLocation(gps_loc);
            return;
        }
        if(net_loc!=null){
            locationResult.gotLocation(net_loc);
            return;
        }
        locationResult.gotLocation(null);
    }
}

public void cancelTimer() {
    timer.cancel();
    locationManager.removeUpdates(locationListenerGps);
    locationManager.removeUpdates(locationListenerNetwork);
}
    public static abstract class LocationResult{
    public abstract void gotLocation(Location location);
}

}


text:
Q: IntelliJ error: cannot find symbol @javax.annotation.Generated This is my first time using IntelliJ so this is probably just a basic question but alas I have it anyways.
I have cloned a github project into IntelliJ that uses gradle.  I import and first thing it says is that gradle is not set up right, so I set it up according to the following:
gradle prefrences Java version 14.0.1.  Then it said the SDK was still not set up so I again set that up for again version even though I am not using Android.
I can successfully run a few of the grade tests but all of my java code no longer links methods and when I run the tests (directly from github without any changes yet) I get an  error: cannot find symbol @javax.annotation.Generated(
Also all of the methods in my example seem to no longer link.  I have a screenshot of this too.
Any guidance is appreciated, probably a problem in the set up?  I found this symbol error a few times but no resolution that helped.  I tried invalidating caches and restarting a few times. I deleted the .idea files a few times. tried a different repository in git and still having the same errors.
Thanks!

A: Simply add the javax annotation dependency into your build.gradle.
dependencies {
  //...
  implementation 'javax.annotation:javax.annotation-api:1.3.2'
  //...
}

like so.