text:
Q: Angular.js simple get object from ASP.NET controller Been some time since I last looked at Angularjs. I have a simple get that calls an ASP.NET Controller and returns a Json object - the get is triggered but nothing is getting populated on the view. The Json object shows in the browser, so it's purely a JS Angular thing.  I know I am missing something simple, but I can't quite put my finger on it.  If someone would be kind enough to show what I'm missing preferably with an example that would great. I haven't been able to find a simple example, that's similar.
Angularjs.
var ngCurrent = angular.module("ngCurrent", ['ngResource']);
var ctrCd;
// Declaring a Service
ngCurrent.factory("CurrentService", function ($resource) {
    return {
        data: $resource("/Current/Data/:id")
    }
});

ngCurrent.controller("CurrentController", function ($scope, CurrentService) {
    $scope.current = CurrentService.data.get({ "id": id}, isArray = false);
});

In the CSHTML View (Condensed but all relevant rows included)

            {{current.RecordName}}

It runs triggers the "Get" from the controller but displays no data and $scope.current contains no object.
I have had a go at JSFiddling without success here it is http://jsfiddle.net/Mark_Dete/Lfy66re1/1/
(note the Json mocking is based on http://jsfiddle.net/ExpertSystem/6PYsq/)

A: You can return a promise from your service like:
    return $http({
      url: '/api/v1/service/',
      method: "GET",
      headers: {'X-API-TOKEN': api_key },
      params: _params
    })

Then use the promise callbacks on the http object in your controller (the one returned from your service)
$scope.getApiData = function(){
  Service.getData($scope.api_key)
  .then(function(_data) {
    console.log(_data.data);
    $scope.data_obj = _data.data;
  });

here's an all in one version without the service abstraction but it should work for testing.
 $scope.getApiData = function(){
  $http({
      url: '/api/v1/service/',
      method: "GET",
      headers: {'X-API-TOKEN': api_key },
      params: _params
   })
  .then(function(_data) {
    console.log(_data.data);
    $scope.data_obj = _data.data;
  });

Make sure you remember to inject the $http dependency!


text:
Q: Get Host name from given URL how to get host name from bellow Example.

I/P: https://stackoverflow.com/users/login | O/P: stackoverflow.com
I/P: stackoverflow.com/users/login | O/P: stackoverflow.com
I/P: /users/login  | O/P: (return empty string)

I checked parse_url function, but doesn't return what I need. Since, I'm beginner in PHP, it was difficult for me. If you have any idea, please answer.

A: This should work in all kind of domain name
$url = " https://stackoverflow.com/users/login";
// trailing slash for edge case, it will return empty string for strstr function regardless
$test = str_replace(array("http://", "https://"), "", $url) . "/";
$domain = strstr($test, "/", true);
echo $domain; // stackoverflow.com

$domain will be an empty string if no domain found

A: You can try this -
$url = ' https://stackoverflow.com/users/login';

function return_host($url)
{
  $url = str_replace(array('http://', 'https://'), '', $url); // remove protocol if present
  $temp = explode('/', $url); // explode the url by /
  if(strpos($temp[0], '.com')) { // check the url part
     return $temp[0];
  }
  else {
     return false;
  }
}

echo return_host($url);

Update
For other domain types just change the check -
if(strpos($temp[0], '.com') || strpos($temp[0], '.org') || strpos($temp[0], '.net'))

DEMO

A: you can try this
<?php

function getHost($Address) {
   $parseUrl = parse_url(trim($Address));
   return trim(isset($parseUrl['host']) ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
}

echo getHost('http://stackoverflow.com/users/login');

A: You can use regular expressions, as described in this solution: Getting parts of a URL (Regex)
Or you can use a PHP function for that: http://php.net/manual/en/function.parse-url.php
I would suggest the second (RegExes can be tricky if you don't know exactly how they work).

redpajama_set_name: RedPajamaStackExchange


text:
Q: remove double quotes from Json return data using Jquery I use JQuery to get Json data, but the data it display has double quotes. It there a function to remove it?
$('div#ListingData').text(JSON.stringify(data.data.items[0].links[1].caption))

it returns:
"House"

How can I remove the double quote? Cheers.

A: The stringfy method is not for parsing JSON, it's for turning an object into a JSON string.
The JSON is parsed by jQuery when you load it, you don't need to parse the data to use it. Just use the string in the data:
$('div#ListingData').text(data.data.items[0].links[1].caption);

A: Someone here suggested using eval() to remove the quotes from a string. Don't do that, that's just begging for code injection.
Another way to do this that I don't see listed here is using:
let message = JSON.stringify(your_json_here); // "Hello World"
console.log(JSON.parse(message))              // Hello World

A: Use replace:
var test = "\"House\"";
console.log(test);
console.log(test.replace(/\"/g, ""));

// "House"
// House

Note the g on the end means "global" (replace all).

A: I also had this question, but in my case I didn't want to use a regex, because my JSON value may contain quotation marks. Hopefully my answer will help others in the future.
I solved this issue by using a standard string slice to remove the first and last characters. This works for me, because I used JSON.stringify() on the textarea that produced it and as a result, I know that I'm always going to have the "s at each end of the string.
In this generalized example, response is the JSON object my AJAX returns, and key is the name of my JSON key.
response.key.slice(1, response.key.length-1)

I used it like this with a regex replace to preserve the line breaks and write the content of that key to a paragraph block in my HTML:
$('#description').html(studyData.description.slice(1, studyData.description.length-1).replace(/\\n/g, '<br/>'));

In this case, $('#description') is the paragraph tag I'm writing to. studyData is my JSON object, and description is my key with a multi-line value.

A: You can simple try String(); to remove the quotes.
Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp
Thank me later.
PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.

A: For niche needs when you know your data like your example ...  this works :
JSON.parse(this_is_double_quoted);

JSON.parse("House");  // for example

A: What you are doing is making a JSON string in your example. Either don't use the JSON.stringify() or if you ever do have JSON data coming back and you don't want quotations, Simply use JSON.parse() to remove quotations around JSON responses! Don't use regex, there's no need to.

A: I dont think there is a need to replace any quotes, this is a perfectly formed JSON string, you just need to convert JSON string into object.This article perfectly explains the situation : Link
Example :
success: function (data) {

        // assuming that everything is correct and there is no exception being thrown
        // output string {"d":"{"username":"hi","email":"hi@gmail.com","password":"123"}"}
        // now we need to remove the double quotes (as it will create problem and
        // if double quotes aren't removed then this JSON string is useless)
        // The output string : {"d":"{"username":"hi","email":"hi@gmail.com","password":"123"}"}
        // The required string : {"d":{username:"hi",email:"hi@gmail.com",password:"123"}"}
        // For security reasons the d is added (indicating the return "data")
        // so actually we need to convert data.d into series of objects
        // Inbuilt function "JSON.Parse" will return streams of objects
        // JSON String : "{"username":"hi","email":"hi@gmail.com","password":"123"}"
        console.log(data);                     // output  : Object {d="{"username":"hi","email":"hi@gmail.com","password":"123"}"}
        console.log(data.d);                   // output : {"username":"hi","email":"hi@gmail.com","password":"123"} (accessing what's stored in "d")
        console.log(data.d[0]);                // output : {  (just accessing the first element of array of "strings")
        var content = JSON.parse(data.d);      // output : Object {username:"hi",email:"hi@gmail.com",password:"123"}" (correct)
        console.log(content.username);         // output : hi
        var _name = content.username;
        alert(_name);                         // hi

}

A: I had similar situation in a Promise just solved doing a cast as (String)
export async function getUserIdByRole(userRole: string): Promise<string> {
  const getRole = userData.users.find((element) => element.role === userRole);

  return String (getRole?.id);
}


text:
Q: A simple congruent equation $3^a\equiv1+b\mod m$ I come across a simple  congruent equation as follows:
let $m\geq 10$ be an integer.It is not a power of $3$. Then how can we find some $a$ and $b$ (they are integers) such that
$$3^a\equiv1+b\pmod{m},$$ where $b$ satisfies the condition:$\frac{m}3<b<\frac{2m}3.$

A: Here's a particular case where we can guarantee an answer.
Take $m>3$, $m\equiv 1 \pmod 3$. Let $n = \mathrm{ord}_m(3)$, so $3^n\equiv 1 \pmod m$. This means that $3^n = mk+1$ for some $k \equiv 2 \pmod 3$.
Since $k = 3l+2$ then $3^{n}= mk+1 = 3lm+2m+1$, so
$$3^{n-1}-1 = lm+\frac{2m-2}{3}$$
Reducing modulo $m$ we have
$$(3^{n-1}-1) \bmod m = \frac{2m-2}{3}$$ and
$$\frac{m}{3}<\frac{2m-2}{3}<\frac{2m}{3}$$
So in this case there's a solution $a = n-1$.

A: Since we can solve for $b$, it is superfluous, so we may just simply ask if there exists $a$ such that $\frac{m}{3} < (3^a-1) \bmod m  < \frac{2m}{3}$.
I think it should be relatively easy to prove that there is a solution if $3$ is a primitive root modulo $m$. But no simple characterization of such $m$'s is known.
In fact, if $\mathrm{ord}_m 3$ is relatively big, one would expect to find some power of $3$ in the desired interval. But the problem is that even if $\mathrm{ord}_m 3$ is very small, it could still happen that there's a solution just by coincidence.
As general as it's asked, I don't think this can be answered. The distribution of the residues of sequences of powers (in this case $3^a$) is a very hard problem with a lot of open questions.
Edit:
Gerry Myerson gave me an excellent example of what I was saying. Consider $m =  1093$. The sequence $(3^a-1) \bmod 1093$ takes only seven values $0, 2, 8, 26, 80, 242, 728$. Only one of them lands on the interval $(\frac{1093}{3},\frac{2\cdot 1093}{3}) = (364.333\ldots, 728.666\ldots)$ and just barely!!


text:
Q: laravel livewire reading session message throws TypeError: Cannot read property 'fingerprint' of null The issue I'm facing is: every time I try to display a message from session I get an "TypeError: Cannot read property 'fingerprint' of null" error and after that I can't make any new ajax requests
The method called when I submit the form
public function saveRolesPermissions()
    {
        $this->selectedPermissions = array_map(
            fn($permission) => array_filter($permission, fn($item) => $item != false),$this->selectedPermissions
        );

        foreach ($this->roles as $role) {
            if (array_key_exists($role->id, $this->selectedPermissions)) {
                $role->permissions()->sync($this->selectedPermissions[$role->id]);
            }
        };

        session()->flash('message', __('dashboard.Permissions updated'));
    }

The layout part where I read the session
@if(session()->has('message'))

        {{session('message')}}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

@endif

The error I get:

How do I solve this (apparently) session issue?


text:
Q: How to add css class to an element inside nav element I have a  element on my page that contains couple of
 elements and one of the divs contains a number of images. I want to add a border to the images so I have added a class to the css file:
.img-cls
{
     border: solid blue 1px;
}

Now if I add class="img-cls" to any image on the page, it adds a border, but if I add the same to any image inside , nothing changes. Can anyone help me fix the issue?
Below is my html:
<form id="form1" runat="server" method="post">

                    ID
                    <input type="text" id="txtID" class="form-control"
                           placeholder="Enter your id here" />

                <button type="submit" class="btn btn-primary btn-lg btn-block">
                    Submit Data
                </button>

</form>

A: There's probably another rule for images inside nav that prevents the border. But you can add !important to your rule:
.img-cls
{
     border: solid blue 1px !important;
}

This should override the other rule (unless it also has !important in it)
ADDITION/EDIT:
You can also set up a rule for images inside your element:
nav img { border: solid blue 1px };

A: try this, all your child images will have the border

THE FORM

  <form id="form1" runat="server" method="post">

                      ID
                      <input type="text" id="txtID" class="form-control"
                             placeholder="Enter your id here" />

                  <button type="submit" class="btn btn-primary btn-lg btn-block">
                      Submit Data
                  </button>

  </form>

Let me know if you solve your problem.
Here the example
Example

A: The problem definitely in css priority.
Try to access your images with next selector (which has more priority than mentioned above.)
nav div img.img-cls, nav img.img-cls
{
     border: solid blue 1px;
}


text:
Q: How to use XPath with MSHTML? How to use/mimic XPATH using MSHTML in Delphi? This is how its done with HTML Agility Pack
htmlDoc.DocumentNode.SelectNodes("//img[@src]")

Is something like this possible with Delphi?


text:
Q: Automate "yes" to Popen SSH command Hi i am writing a C++ program to automate SSH connection to an AWS instance with the popen function.
void initiate_ssh(char ip[100]){

char ssh[250];
FILE* fp;
strcpy(ssh,"ssh -i theKey.pem ec2-user@");
strcat(ssh,ip);
fp=popen(ssh,"w");
if(fp){
 // respond yes automatically
    }
pclose(fp);

}

I have searched through numerous threads but i can only find similar situations in python but i am not too familiar with python. So i need to automatically pipe "yes" to the popen  in order to get access remote access to the instance.

A: Here we see an "XY problem". You want to automatically accept host keys (this is "X"). You think that you can do that by automatically typing "yes" at the prompt (this is "Y"). You are stuck on that, so you ask how to do Y. But there is an even easier way to do X.
Here's how to do X:
add the option -o StrictHostKeyChecking=no to your SSH command.
strcpy(ssh,"ssh -o StrictHostKeyChecking=no -i theKey.pem ec2-user@");
//              ^^^^^^^^^^^^^^^^^^^^^^^^^^^

I assume the ssh buffer is already long enough to contain this extra option.


text:
Q: how to start spyder in a new conda environment? I have a .yaml conda environment file, which contains a few packages
name: myEnv
channels:
- anaconda
- conda-forge
- defaults
dependencies:
- numpy=1.12.1=py27_0
- pandas=0.20.1=np112py27_0
- scikit-learn=0.18.1=np112py27_1
 # and more

Then I have created a new environment from this file:
conda env create -f myfile.yml

Everything runs fine, and the envorinment is created.
I can see it under
conda env list

I can activate it, and run python in the CLI within it and the libraries are there as expected.
However, if I try to run spyder from the CLI using any of the following
(myEnv) spyder
(myEnv) spyder --new-instance
(myEnv) spyder --defaults
(myEnv) spyder --reset

I get the following error message:

and nothing as  traceback in the cmd.exe.


text:
Q: Python: Plot month-wise normalised histogram I have a CSV file with data that look like this:
Time               Pressure
1/1/2017 0:00       5.8253
...                     ...
3/1/2017 0:10       4.2785
4/1/2017 0:20       5.20041
5/1/2017 0:30       4.40774
6/1/2017 0:40       4.03228
7/1/2017 0:50       5.011924
12/1/2017 1:00      3.9309888

I want to make a month-wise histogram (NORMALIZED) on the pressure data and finally write the plots into PDF. I understand that I need to use Groupby and Numpy.hist option,but I'm not sure how to use them. (I'm a newbie to Python). Please help!
CODE 1:
n = len(df) // 5
for tmp_df in (df[i:i+n] for i in range(0, len(df), n)):
    gb_tmp = tmp_df.groupby(pd.Grouper(freq='M'))
    ax = gb_tmp.hist()
    plt.setp(ax.xaxis.get_ticklabels(),rotation=90)
    plt.show()
    plt.close()

This gives me the following error message:
ValueError: range() arg 3 must not be zero

CODE 2:
df1 = df.groupby(pd.Grouper(freq='M'))
np.histogram(df1,bins=10,range=None,normed=True)

This returns another error message:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I tried the above codes, but got these errors. Not sure if I'm using it right.

A: A few simple steps. First you need to read your data file, into an array of cells. once you have your list of lists or rows of entry ( what ever you want to call them ) you need to collect all the observations for each month and take the average of each collection. Here I have implemented a simple buckets class to facilitate the aggregation of pressures into groups my months and provide the mean for each group. Lastly I plotted the result with matplotlib.
def readData(fn):
    fh = open(fn)
    lines = fh.read().split("\n")
    ret = [k.split("       ") for k in lines[1:]]
    fh.close()
    return(ret)

class buckets:
    def __init__(self):
        self.data = {}
    def add(self,key,value):
        if not(key in self.data.keys()):
            self.data[key]=[]
        self.data[key].append(value)
    def getMean(self,key):
        nums = []
        for k in range(0,len(self.data[key])):
            try:
                nums.append(self.data[key][k])
            except:
                pass
        return(sum(nums)/float(len(nums)))
    def keys(self):
        return(self.data.keys())

import matplotlib
import numpy as np

data = readData("data.txt")
container = buckets()

for k in data:
    print(k)
    container.add(k[0].split("/")[0],float(k[1]))

histoBars = []
histoTicks = [int(k) for k in list(container.keys())]
histoTicks.sort()
histoTicks = [str(k) for k in histoTicks]
x = np.arange(len(histoTicks))

for k in histoTicks:
        histoBars.append(container.getMean(k))

print(len(histoBars))
print(len(histoTicks))

import matplotlib.pyplot as plt
print(histoBars)
print(histoTicks)
fig, ax = plt.subplots()
plt.bar(x, histoBars)
plt.xticks( x, histoTicks )
plt.show()

A last quick note, I'm not really sure what data format your file is, it looked like the 2 columns were seperated by 7 spaces but then one of the samples only had 6, so you might have to change the delimiter or clean the table to make sure all the rows read without error.


text:
Q: 'runin' shaped section title prints on same line as table of contents title I am using titleformat from the titlesec package to format section titles such that they don't cause new lines. However, when the table of contents is built, the first section appears on the same line as the contents titles. How can I cause all sections in the table of contents to appear on their own lines? Minimal code to replicate the problem:
\documentclass[12pt]{article}

\usepackage{titlesec}
\titleformat{\section}[runin]{\normalfont\Large\bfseries}{\thesection. }{0pt}{}[]

\begin{document}
    \tableofcontents
    \section{Section A}
    \section{Section B}
\end{document}

A: This is due to the fact that in the article class, the table of contents is a section One possible solution is to define a different formatting for unnumbered sections:
\documentclass[12pt]{article}

\usepackage{titlesec}
\titleformat{\section}[runin]{\normalfont\Large\bfseries}{\thesection. }{0pt}{}[]
\titleformat{name=\section, numberless}[block]{\normalfont\Large\bfseries}{}{0pt}{}[]

\begin{document}

    \tableofcontents

    \section{Section A}
    \section{Section B}

\end{document}


text:
Q: CouchDB - "Plucking" nearest neighbour documents from a view. Not sure how this question will sound, but figured I'd throw out the Bat signal anyway...
I have a dataset similar to the following:
[
    { name: "Peter", score: 1000 },
    { name: "James", score: 800 },
    { name: "John", score: 600 },
    { name: "Saul", score: 400 },
    { name: "David", score: 200 }
]

Now there are a few things I'd like to do with this collection, but the main function I'm keen on is one to take a given record and find the documents that sit directly above and below that item in the score table, like;
[
    { name: "James", score: 800 },
    -> { name: "John", score: 600 },
    { name: "Saul", score: 400 }
]

I'd also like to create a view that looks like this:
[
    { key: 1, value: { name: "Peter", score: 1000 } },
    { key: 2, value: { name: "James", score: 800 } },
    { key: 3, value: { name: "John", score: 600 } },
    { key: 4, value: { name: "Saul", score: 400 } },
    { key: 5, value: { name: "David", score: 200 } }
]

I can't help but feel that the two problems are related.
I'm also keen to perform the "pluck" in as small a number of REST requests as possible...
I'd also happily accept a solution that relies on the application layer, but again, I'd like to avoid multiple trips to the DB, and would also like to avoid pulling out more data than necessary.
Any ideas?

A: You can create a view that has the score as a key. The map function just needs to do emit(doc.score, null), where doc is the document passed to the function. If you query this view with startkey=600, limit=2, and descending=false, you will get the documents with scores of 600 and 800. If you query with startkey=600, limit=2 and descending=true, you will get the documents with scores of 600 and 400.
To get all documents in descending score order, you'd just query with descending=true and no other parameters. You won't get a key: n field of course, but you can easily add that in your application layer.

A: Have you tried to use score as key? In this case you may build rating charts and query for persons that have score in some range. Your map function:
function(doc){
    emit(doc.score, {'name': doc.name, 'score': doc.score})
}

// not sure that you still needed in such value
Now, if you call your view you'll receive:
{
  "total_rows": 5, "offset": 0, "rows": [
    {"id": "1", "key": 200, "value": {"name": "David", "score": 200}},
    {"id": "2", "key": 400, "value": {"name": "Saul", "score": 400}},
    {"id": "3", "key": 600, "value": {"name": "John", "score": 600}},
    {"id": "4", "key": 800, "value": {"name": "James", "score": 800}},
    {"id": "5", "key": 1000, "value": {"name": "Peter", "score": 1000}}
  ]
}

Looks not like top ratings. Let's add descending=true query parameter:
{"total_rows": 5, "offset": 0, "rows": [
  {"id": "5", "key": 1000, "value": {"name": "Peter", "score": 1000}},
  {"id": "4", "key": 800, "value": {"name": "James", "score": 800}},
  {"id": "3", "key": 600, "value": {"name": "John", "score": 600}},
  {"id": "2", "key": 400, "value": {"name": "Saul", "score": 400}},
  {"id": "1", "key": 200, "value": {"name": "David", "score": 200}}
]}

Good! Now you may apply startkey / endkey query parameters to query things within specified range. Let's take startkey=799&endkey=401. Note that border values are included in response:
{"total_rows":5,"offset":2,"rows":[
  {"id":"3","key":600,"value":{"name":"John","score":600}}
]}

The result query will looks as http://localhost:5984/db/_design/ddoc/_view/by_score?descending=true&startkey=799&endkey=401

A: I think I'll create a lightweight view of the dataset (emit("score", null), as suggested by Kxepal and Kim) pull it out, cache it, and use the changes feed to keep it fresh.
That way, I'd end up hitting the database less. That should make the "plucking" process in someway easier, as I can explicitly add a 'rank' property to the cached object properties/elements, and use that to cherry pick stuff.
Update:
Though the above could work as a solution (a possible use case for Redis?), using the view response total_rows and offset values make retrieving a document 'rank' trivial (based on a 'score' view, as suggested in the two answers above)...
The only problem that still remains is the "pluck" itself, which may still need two separate  API calls, but that might no be so bad...
Still open to suggestions though.
Cheers. :)


text:
Q: Call localhost API within react native ( android device : connected through local) Have created a simple GET API using node.js and trying to consume it within my expo-react native project using axios/fetch.
The GET API is called whenever user clicks on submit button.
Submit -> http://localhost:port/api
However, when I am trying to test the feature on my android device by connecting the device through datacable and selecting "local" connect type in expo, the API call always falls under exception.
When I tried to log the exception, the exception is printed empty.
I double checked the API and it works fine when tested through postman.
I tried replacing localhost url with my-Ip (http://IP:port/api) and also with 127.0.0.1/127.0.2.2 (http://127.0.0.1:port/api , http://127.0.2.2:port/api) , but nothing seems to make the API call a success.
When I replaced the localhost URL with Facebook's network sample API, the application worked just fine. So, there is no issue with the API calling method.
Also, tried adding the port to windows inbound firewall request but that didn't work too.
Can someone help me out with this ?

A: You must call the API from your local IP address. To get your local IP, just do the following:
If you are on Ubuntu 16.04:
ifconfig | grep 192

If you are on Ubuntu 18.04:
ip -c a | grep 192

Your local IP address will probably be something like 192.168.0.XXX.

A: yes, i also had this problem until use my Local IP (example: http://192.168.1.55:port) instead 127.0.0.1
please see this answer

A: Good day,
This is working
I use my machine's IP the Ethernet adapter Ethernet 2: IPV4 Address
And allow my port on firewall both Inbound and outbound rules


text:
Q: Is it possible to disable System.Console XOFF/XON flow control processing in my C# app? I am a developer of console-based server software, that occasionally seems to lock up on input until Enter is pressed. I suspect this is XOFF/XON (Ctrl-S/Ctrl-Q flow control) handling in System.Console windows.
Is it possible (using .NET calls or Win32 API functions) to disable XOFF/XON flow control processing in my C#/.NET application that uses System.Console for output and input commands?  (This also affects other system consoles such as CMD.EXE windows, but I don't care about those cases.) My app is server software; don't ever want a key that freezes the console, especially one that can be triggered accidentally as this appears to be.
Somehow I believe my server app's console is getting a Ctrl-S on input, or perhaps the Ctrl qualifier is thought to be pressed when S is entered. Console locks up until I hit Enter. (I'm thinking Ctrl-Q would have also released it but haven't had another opportunity to test that yet.)
My processes are C# servers on .NET, and these are consoles using System.Console.ReadLine() on Hyper-V VMs running Windows Server.
This may be critical to the problem cause: I am connecting to the Hyper-V host via Remote Desktop (RDP). One thought is the RDP disconnect is losing a Ctrl key up and then the next 'S' that is input (by our command automation software) locks the terminal.  We are eventually replacing that with network-based command input, but in the meantime we are fighting with this problem, which requires manual intervention by staff to get the server running again.
Further info: I tried the following, in case it was Quick Edit mode being triggered by an RDP session from a tablet, but this did not stop the lockups:
        GetConsoleMode(handle, out oldmode);

        int newmode = oldmode;
        newmode |= ENABLE_EXTENDED_FLAGS;   // required to disable the next two
        newmode &= ~ENABLE_QUICK_EDIT_MODE; // force this OFF
        newmode &= ~ENABLE_MOUSE_INPUT;     // force this OFF
        newmode &= ~ENABLE_WINDOW_INPUT;    // force this OFF
        newmode |= ENABLE_INSERT_MODE;      // force this ON
        if (newmode != oldmode)
        {
            SetConsoleMode(handle, newmode);

A: I think it is safe to conclude after all these years without a solution or anything to contradict or workaround the issue, that disabling flow control on a standard C# console app on Windows is is not possible, and that this leaves console apps that accept input (such as Ctrl-C or Ctrl-Break) open to hangs caused by XOFF characters. This means it is not suitable for most servers.


text:
Q: How to determine supported cipher suites for Wildfly 10 How can I determine which cipher suites are supported by Wildlfly 10?
The documentation just states that there is an option "enabled-cipher-suites".
Background: I'm trying to configure various cipher suites. Example:
 <https-listener name="default-ssl" socket-binding="https" security-realm="SslRealm" enabled-cipher-suites="TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" enabled-protocols="TLSv1.2"/>

Java version:
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)

When I list the availables ciphers for the JVM using this method the cipher suite is available.
When starting WildFly no connection is available with a browser and nmap also does not list any available ciphers (using nmap --script ssl-enum-ciphers -p PORT HOSTNAME)
There is a list by someone who used a tool to determine the version, but I think there should be a solution using Wildfly documentation or tools only.

A: As it turned out my problem was rather trivial. The JVM which reported the availability of the cipher suite was version 1.8.0_151.
But the Wildfly used another JVM with verson 1.8.0_141 which did not support the cipher.
Updating the JVM to at least 1.8.0_151 fixed the problem.


text:
Q: How can I run a Perl script automatically after a Ubuntu server has booted up? I wrote a Perl script which will serve as a daemon, so I'd like to let the OS (in my case, Ubuntu Linux) automatically run my Perl script after it has booted up.
How can I do that?

A: Make a shell script wrapper for your perl script
#!/bin/sh - script.sh
# your perl program goes here

/bin/perl /path/to/foobar.pl

Make sure that you have given executable permission using
  chmod +x script.sh

and execute the following,
sudo update-rc.d script.sh defaults

This will run perl script on each startup.

A: Things have changed a bit in the last 7 years.  In Ubuntu 16.04, the path to perl is different.  Also, you are required to supply a bunch of configuration information in your /etc/init.d/foobar.sh script:
#!/bin/sh foobar.sh
### BEGIN INIT INFO
# Provides:          foobar
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: forbarsvr
# Description:       foobar daemon for widget serving
### END INIT INFO
sudo -u foobarusr perl /path/to/foobar.pl &

This form of invoking perl allows you to run as a user (giving a constrained security domain) rather than root; to run as root, remove the -u foobarusr. If you are executing as a non-root user, ensure that user has permissions over all required resources, such as the perl script itself.
The trailing & fires off your perl script as an on-going (until finishing) task; deamon-like if it doesn't terminate for whatever reason.
Make your foobar launcher executable:
sudo chmod +x /etc/init.d/foobar.sh

Add your script into the startup sequence:
sudo update-rc.d foobar.sh defaults

Note there is no path supplied to the script.


text:
Q: Verify size and coordinates in Selenium I have a question - did Python + Selenium give the opportunity to verify size and coordinates on the web-page?
I mean I have a mockup in Figma with the size of the element and his coordinates. And I want to know can I verify these values by Python + Selenium on the Web Page?

Maybe we can't use Figma, but maybe you can verify coordinates in the browser, and then write them in the test-cases?


text:
Q: Error : Object null reference when trying to get a control from Form.Controls collection I am trying to change Label text In parent Form from Child form but I am getting this error Object reference not set to an instance of an object. where is the mistake ?
Here is code I am Using
private void btnMedicalClgList_Click(object sender, EventArgs e)
        {
            this.ParentForm.Controls["lblMenuItem"].Text = "Medical College List";//getting error here
            ShowMedicalClgList medifrm = new ShowMedicalClgList();
            medifrm.MdiParent = this.ParentForm;
            this.Hide();
            medifrm.Show();
        }

A: As I said in my comment you can't use a control's name as the indexer of Controls collection to get it but you can iterate through the controls collection find the desired control and do whatever you want with it, try this:
Label lbl = null;
foreach (var control in this.ParentForm.Controls)
{
    if (((Control)control).Name == "lblMenuItem")
    {
        lbl = (Label)control;
        break;
    }
}
if (lbl != null)
    lbl.Text = "Medical College List";

or if you want to write less code :
Control[] foundControls = this.Controls.Find("lblMenuItem", true);
if (foundControls.Any())
    foundControls.First().Text = "Medical College List";


text:
Q: Upvalues for Missing do not work with Dataset Consider the following Dataset:
d = Dataset[<| 1 -> Missing[], 2 -> 1.0, 3 -> 4.0 |>]

And the following Upvalue for Missing:
Unprotect[Missing];
Missing /:
f_Symbol[___, m_Missing,  ___] /; MemberQ[Attributes[f], NumericFunction ] := m;
Protect[Missing];

Now do the following:
d[All,  1 + # &]

It returns <|1 -> 1, 2 -> 2., 3 -> 5.|> rather than the expected <|1 -> Missing[], 2 -> 2., 3 -> 5.|>.
Why doesn't the upvalue for Missing[] work?

A: By default, any queries using Dataset or Query perform special processing of Missing values.  The installed up-value will have no effect while that special processing is in place.  We can use MissingBehavior -> None to disable the special treatment and to allow our up-value to take effect:
d[All, 1 + # &, MissingBehavior -> None]

(* <|1 -> Missing[], 2 -> 2., 3 -> 5.|> *)

In general, I would discourage adding an up-value to a protected system symbol like Missing.  The present observed difficulty is an example of why -- many components make assumptions about the exact behaviour of built-in symbols.  At the very least, I would recommend using Block (or Internal`InheritedBlock) to keep the redefinition somewhat localized.
Incidentally, the dataset machinery that performs the special missing processing happens to ignore this advice.  It temporarily redefines the behaviour of Missing (using Block).  That is why Missing appears to behave erratically in this context.


text:
Q: When I push to GitHub I can't open the assignment folder I was able to push my assignment to GitHub, but I am unable to open it
Here is what I see on GitHub after the push:

A: Check first if assignment, on your local computer, has a .git subfolder in it.
That would make it a nested Git repository inside your main repository, and pushing it would only push a gitlink entry (a special entry in the index)
Ideally, each of those folders would need to be pushed in their own matching Git repositories.


text:
Q: How to describe Firebase storage security rules for several buckets in one file? I want to describe storage security rules for several buckets in one .rules file. The bucket names are not known beforehand, however the prefixes of the domain-named buckets are known.
Suppose I have the following buckets:

*

*uploads.<root-domain>

*original.<root-domain>

*edited.<root-domain>

*etc.

I know that I can use Deploy Targets and put each rule into its own file, but I'd like to have all the rules in one file. Yes, I'm going to define a deploy target that will include all the buckets, and assign that target with my single .rules file.
I've tried the following approach.
service firebase.storage {

  // Original audio files
  match /b/original.{root}/o {
    match /{allPaths=**} {
      allow read;
    }
  }

  // Uploads
  match /b/uploads.{root}/o {
    match /{uploadCode}/{file=**} {
      allow read, write;
    }
  }
}

But got error during deployment:
Error: Compilation errors in storage.rules:
[E] 4:22 - Unexpected 'rootdomain'.
[E] 4:9 - Missing 'match' keyword before path.
[E] 4:22 - Unexpected 'rootdomain'.
[E] 4:33 - Missing 'match' keyword before path.
[E] 5:5 - missing '}' at 'match'
[E] 11:3 - Unexpected 'match'.

So it seems that wildcards are allowed only for the whole path segment, not for a part of it.
Is there any way to have all the storage rules for various buckets in one file?


text:
Q: Complexity of merge auxiliary procedure In Cormen's "Introduction To Algorithms" Book they use this procedure called "Merge"

It is auxiliary for the well-known Merge Sort algorithm

The book states that the "Merge" procedure has a θ(n) | n = r-p+1 complexity; I want to prove this, and so far have come up with this analysis (I intend to model the worst case scenario)

However, lines 12-18 are a little tough to come up with, since in order to find the worst case, I have to compute too many options and possibilities in my head, and it's a little overwhelming; So far, I think that the worst case occurs when all elements in the Left (L) subarray are bigger than all elements in right (R) subarray, but I'm not sure.
Any suggestions?
Thanks in advance.
edit: In the book, nonetheless, they don't take into account lines 13-18; could you tell me why is this? and how can I come up with the complexity w/o taking those lines into account?

A: It's much easier to prove if you use a "charge" argument.  Note that the last loop assigns p - r + 1 elements in A.  Now just go through the rest of the code and "charge" each constant unit of work to one those elements. As long as each gets a constant maximum number of charges - and that's easy to show - the algorithm has run time Omega(p - r + 1) = Omega(n).


text:
Q: javascript load dynamically css and js files I am using laravel 4 and I have a file style-switcher.js
yepnope([
{load: 'assets/css/style-switcher.css' },
{load: 'assets/lib/colorpicker/css/colorpicker.css'},
{
    load: 'assets/css/colorpicker_hack.css'
},
{
    load: 'assets/lib/cssbeautify/cssbeautify.js'
},
{
    load: 'assets/lib/colorpicker/js/bootstrap-colorpicker.js',

How can I load this css file dynamically? How to include the base path? For header and footer js and css I use
`{{ HTML::script('assets/...`) }}

But can't do the same with this js file

A: just change the href of the css style tag
<link id="dynamic css" href="/old_css_path">
$('#dynamic_css').attr('href','/new_css_path')

or
if you want to append a new css, without removing other,
    $('head').append('')
no need to include base path of your website, just make sure you add backslash in starting of ever css path.


text:
Q: Sudo and su root not working I want to use the sudo command but whenever I type it I see a message that says void is not in the sudoers file, this incident will be reported. I tried finding a way to fix it, and the told me to type su root then follow the next steps, but when I type su root it says authentication failure No problem, lets just fix that right? Well then they tell me to type in sudo which I cant use so I need a different way of solving this problem, would you mind helping me out?

A: It's not enough to install the sudo program. You must have root permissions (meaning you have to be the admin user) to grant your user the required permissions to use sudo.
Use the visudo command to grant yourself the permissions (this will open vi text editor and has example lines you can just copy paste, type :wq and Enter to save & exit) or add the user to "wheel" group with usermod -aG wheel void as the root user.


text:
Q: Disable set aside tabs in Edge The Creator's update added a new feature to Edge called "setting aside tabs". While it sounds nice, I really don't need it and it is actually creating problems for me. While clicking on the first tab in the list, I often accidentally click on the set aside button and all tabs have to be reloaded again.
Is there some switch to disable this new feature?

A: The official answer by Microsoft to this question can be found in their forum
post
How to turn off "set these tabs aside" in Edge on Win10.
The count of "I have the same question" on this post is 90.
Dyan Rey from Microsoft replied on July 20, 2017 :

Disabling "set these tabs aside" is not yet possible in Microsoft
  Edge. Your feedback helps to continually improve your experience with
  our product.
Here are the steps on how to submit a feedback:

*

*On your Windows 10 device, search for Feedback Hub in the Cortana Search box, and launch the application.

*Navigate to Feedback in the left menu, then press + Add new feedback.

*Select the Problem, share any details you think are relevant, and choose an appropriate category and subcategory.

*Important: If possible, reproduce the issue after clicking Begin monitoring (or Start capture) near the end of the form; Stop
  monitoring when you are done.

*Once you have completed the form and monitoring, click Submit.

*Click Continue using Feedback Hub.

*Click My feedback at the top, and find the item you submitted (it may take a while to appear).

*Open the item you submitted, then click Share.

*Click Copy link, then paste the link here in your response (it will look like https://aka.ms\ link>)

I found this link mentioned : https://aka.ms/B6urh8, but I'm unwilling
to sign on to the Feedback app to verify it.
Other answers by Microsoft that say the same :

*

*Recent Edge update "Set aside tabs" created problems (August 1, 2017)

*Disabling Set Aside Tabs in Edge on Win10 (June 19, 2017)

I am afraid that all you can do at the moment is join your voice to the
feedback channel, and wait for Microsoft to act.
As far as I know, there are actually no non-Microsoft workarounds or hacks.


text:
Q: What is the best way to set up a form to get a temp var? I am making a photo upload form. Before they begin, they have two choices. They can create a new gallery, OR they can choose from an existing gallery.
I was thinking the best way to lay this out would be two have two forms. One for the create one that would take them to the create page. That's easy, and practically done.
But the second form, I need to grab the gallery name in a select box and apply it to an add_photos_to_gallery form - which is tricky for me. Do I?
a. Make a temp variable for this form and pass it to the controller, and then generate the form from what they choose? If so, how could I do that?
b. Use jquery and somehow manipulate the DOM to create a form? I got some ideas..
c. Realize I'm too dumb to know something way better and more obvious?

A: roughly speaking the way I would approach this is with one form,
to populate the select tag, i am assuming you create a named scope or association in your user model, eg
has_many :galleries

and populate the select tag with it
 <%= select_tag "add_photos_to_gallery", @user.galleries, :include_blank => true %>

and if the params[:add_photos_to_gallery] is blank, create a new album otherwise add it to the selected gallery.
Or you could include a checkbox to toggle on or off the select tag based on if they want to use an existing gallery or not.


text:
Q: jQuery plugin unrecognized expression: [object Object] I'm learning jQuery and trying to create a simple color changing plugin by following this jQuery Tutorial, but can't get to work.
Here is the code:
(function ( $ ) {
    $.fn.changecolor = function() {
        $(this+" .green_btn").click(function() {
            $(this+" .green_text").css( "color", "green" );
        });
    };
}( jQuery ));

jQuery(document).ready(function($){
    $("#textchanger").changecolor();
});

Why it's not working showing error

Uncaught Error: Syntax error, unrecognized expression: [object Object]
  .green_btn


text:
Q: Is it possible to change the return value of a method in this case? I want to change the return value of method getvalue() to string "firefighter" which i tried from main method but did not work out.
looking forward to some soln.
public class Summ2 {
private String getValue() {
    return "TUHH";
}

public static void main(String[] args) {
    Summ2 GO = new Summ2();
    assert GO.getValue() == "firefighter";
     System.out.println(GO.getValue());
    }

}

A: assert is a checking instruction, not a assignment one.
You can't get a new value from getValue() without using a member variable.


text:
Q: ABS builds but Gradle error: does not exists in my project I started using android-studio today, trying to import from eclipse. i followed http://developer.android.com/sdk/installing/migrate.html migrate from eclipse steps from Google.
I then Import Module -> from source for ABS, and Module-> Dependencies, added android-supportv4, google-play-services_lib, and actionbarsherlock (all the libs that i need).
ABS compiles find on its own as a module. but when i try to compile the project, i get
Gradle: error: package com.actionbarsherlock.app does not exist
Gradle: error: package com.actionbarsherlock.view does not exist
Gradle: error: package com.actionbarsherlock.view does not exist
Gradle: error: cannot find symbol class SherlockFragment
...

I have no idea what's going on, i am not getting any REDS nor error normally, and when i hover over sherlockfragment and such, it finds it. But when it compiles i get that error.
I have read through other stackoverflow post but still so confuse on what's going on.
I DO NOT have a build.gradle in ABS.
My project's build.gradle is as follows:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android'

dependencies {
    compile files('libs/android-support-v4.jar')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 17
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('tests')
    }
}

Do i need to reference the ABS in here?
Thanks guys,
Kev

A: It looks like you setup the dependencies between your main module and ABS through the Studio/IntelliJ UI. This does not work.
Since Studio delegate building to Gradle, the dependencies needs to be setup in build.gradle, and ABS needs to be built with Gradle as well.
With that setup, importing the project in Studio will configure Studio automatically to use the same dependencies when dealing with code-completion, static analysis and refactoring.


text:
Q: jQuery UI Menu border color I have implemented the jQuery UI Menu on this page: http://dormfair.com/about.php
As you can see, the border color everywhere on the website is light blue (#B7DDF2)
BUT the border color in the jQuery UI menu is grey. I've been trying to change that grey to color to #B7DDF2 for a long time to no avail. I've searched the web and StackOverflow as well.
Hope someone can help!
.ui-menu {
    overflow: hidden;
}
.ui-menu .ui-menu {
    overflow: visible !important;
}
.ui-menu > li {
    display: inline-block;
    width: auto !important;
}
.ui-menu ul li {
    display:block;
    float:none;
}
.ui-menu ul li ul {
    left:20px !important;
    width:100%;
}
.ui-menu ul li ul li {
    width:auto;
}
.ui-menu ul li ul li a {
    float:left;
}
.ui-menu > li {
    margin: 5px 5px !important;
    padding: 0 0 !important;
}
.ui-menu > li > a {
    float: left;
    display: block;
    clear: both;
    overflow: hidden;
}
.ui-menu .ui-menu-icon {
    margin-top: 0.3em !important;
}
.ui-menu .ui-menu .ui-menu li {
    float: center;
    display: block;
}

A: This should make the border blue
.ui-widget-content {
    border: 1px solid #B7DDF2;
}

A: I was able to fix it by adding border: 1px solid #B7DDF2 to the CSS of nav (or .ui-menu ui-widget ui-widget-content ui-corner-all):
(CSS)
#nav
{
    border: 1px solid #B7DDF2
}

or
.ui-menu.ui-widget-content
{
    border: 1px solid #B7DDF2
}

A: Your menu's border color is being called from the .ui-widget-content class on line 800 in jquery-ui.css. You can modify it from there.


text:
Q: How to set idle time-out for your GUI in Tkinter (PYTHON 3.6.1) I want my GUI to ask for login again after been left idle for 5 minutes when you login but the root window should stay when tick the checkbutton.
Challenges:
As soon as I run the script, the messagebox parsed under "session_ends" function pops-up.
When I type the the name and password into the entry widget and I tick the checkbutton, another window also pops-up.
import tkinter as tk
import sys
from tkinter import messagebox

name=("user")
password=("python3")

def login_in():
    if entry1.get() == name and entry2.get() == password:
        root.deiconify()
        log.destroy()
    else:
        messagebox.showerror("error","login Failed")
        entry1.set("")   # This clears entry1
        entry2.set("")   # this clears entry2

def close():
    log.destroy() #Removes toplevel window
    root.destroy() #Removes  root window
    sys.exit() #Ends the script

def session_end():
    messagebox.showinfo("session expired","kindly login again")

def continue_session():
    root.deiconify()

root=tk.Tk()
log = tk.Toplevel() #

root.geometry("350x350")
log.geometry("200x200")

entry1 = tk.Entry(log) #Username entry
entry2 = tk.Entry(log) #Password entry
check = tk.Checkbutton(log,text="keep me
login",command=continue_session)#root should stay when you tick checkbutton
button1 = tk.Button(log, text="Login", command=login_in) #Login button
button2 = tk.Button(log, text="Cancel", command=close) #Cancel button
label1 = tk.Label(root, text="This main ui after being idle for 5 minutes \n
   You need to login for the main ui to open")

entry1.pack()
entry2.pack()
check.pack()
button1.pack()
button2.pack()
label1.pack()

root.withdraw()
root.after(5000,session_end())
root.mainloop()

EDIT:
with the above code have edited it with the answer @Bryan Oakley  provided but is the idle timeout the work after 5 minute being idle
import tkinter as tk
import sys

name=("user")
password=("python3")

after_id=None

def reset_timer(event=None):
    global after_id
    if after_id is not None:
        root.after_cancel(after_id)
        after_id = root.after(300000,session_end)

def login_in():
    if entry1.get() == name and entry2.get() == password:
        root.deiconify()
        log.destroy()
    else:
        messagebox.showerror("error","login Failed")

def close():
    log.destroy() #Removes toplevel window
    root.destroy() #Removes  root window
    sys.exit() #Ends the script

def session_end():
    messagebox.showinfo("session expired","kindly login again")

def continue_session():
    if after_id is not None:
    root.deiconify()

def print_some():
    print("This is idle timeout")

root=tk.Tk()
log = tk.Toplevel() #

root.geometry("350x350")
log.geometry("200x200")

entry1 = tk.Entry(log) #Username entry
entry2 = tk.Entry(log) #Password entry
check = tk.Checkbutton(log,text="keep me
login",command=continue_session)#root should stay when you tick checkbutton
button1 = tk.Button(log, text="Login", command=login_in) #Login button
button2 = tk.Button(log, text="Cancel", command=close) #Cancel button
label1 = tk.Label(root, text="This main ui after being idle for 5 minutes \n
You need to login for the main ui\to open")
print_button = tk.Button(root,text="print",command=print_some).pack()

entry1.pack()
entry2.pack()
check.pack()
button1.pack()
button2.pack()
label1.pack()

root.withdraw()
root.bind_all("<Any-KeyPress>",reset_timer)
root.bind_all("<Any-ButtonPress>",reset_timer)
root.mainloop()

A:
How to set idle time-out for your GUI in Tkinter (PYTHON 3.6.1)

A simple solution is to create a function that will end a session, and then schedule that function to run in the future. You are attempting this, but you are calling after incorrectly.
The key to making this be a true idle timeout is to know when the user is "idle". A simple solution is to make a global binding for <Any-KeyPress> and <Any-ButtonPress>
The first thing is to create a global or instance variable to remember the id of the command we're running with after:
after_id = None

The next step is to create a function to reset the timer. It needs to accept an event since one is automatically passed by tkinter. However, we want to be able to call the function directly so we'll make it optional.
def reset_timer(event=None):
    global after_id
    if after_id is not None:
        root.after_cancel(after_id)
    after_id = root.after(5000, session_end)

To start the session, we can directly call the function:
reset_timer()

Next, we can set up bindings to reset the timer on user activity. In this case I'll define activity as any button or key press. We do it like this:
root.bind_all("<Any-KeyPress>", reset_timer)
root.bind_all("<Any-ButtonPress>", reset_timer)

A: time_out = 30000
def reset_timer(event=None):
    global time_out
    if event is not None:
        time_out = 30000
    else:
        pass

def reduce_time_out():
   global time_out
   time_out = time_out-1000
   print(time_out)
   root.after(1000,reduce_time_out)
   if time_out ==0:
       log.destroy() #Removes toplevel window
       root.destroy() #Removes  root window
       messagebox.showinfo("session expired","kindly login again")
       sys.exit()

root.after(1000,reduce_time_out)
root.bind_all("<Any-KeyPress>",reset_timer)
root.bind_all("<Any-ButtonPress>",reset_timer)


text:
Q: Ansible smtp mail send I'm trying to send a mail fron Ansible.
- hosts: all
  tasks:
  - mail:
      host: smtp.gmail.com

      port: 587

      username: ****@gmail.com

      password: *******

      to: John Smith ***@gmail.com

      subject: 'Ansible-report'

      body: 'System  has been successfully provisioned.'

    delegate_to: localhost

but I get an error

fatal: [host1 -> localhost]: FAILED! => {"changed": false, "failed":
  true, "msg": "Authentication to smtp.gmail.com:587 failed, please
  check your username and/or password", "rc": 1}

I use the example from the official site http://docs.ansible.com/ansible/latest/mail_module.html
As I understand, SMTP authentication already exists in the source new module ANSIBLE.
File "/tmp/ansible_K94pcN/ansible_module_mail.py", line 304, in main
    smtp.login(username, password)
File "/usr/lib64/python2.7/smtplib.py", line 621, in login
    raise SMTPAuthenticationError(code, resp)

fatal: [host1 -> localhost]: FAILED! => {
      "changed": false,

"failed": true,

"invocation": {

    "module_args": {

        "attach": null,
        "bcc": null,
        "body": "System ubuntu has been successfully provisioned.",
        "cc": null,
        "charset": "us-ascii",
        "headers": null,
        "host": "smtp.gmail.com",
        "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
        "port": 587,
        "secure": "starttls",
        "sender": "root",
        "subject": "Ansible-report",
        "subtype": "plain",
        "timeout": 20,
        "to": "Cristiano Ross <cristianooross@gmail.com>",
        "username": "victorradin9@gmail.com"
    }
},
"msg": "Authentication to smtp.gmail.com:587 failed, please check your usern              ame and/or password",
"rc": 1

A: The issue your facing is an authentication issue caused by using the correct username & password to send email from a Gmail account without an app specific password assigned.
You'll need to:
a) Setup '2 step authentication' for the sender gmail account.
b) Then you'll need to create an app specific password in your google account settings.
Using that newly generated app specific password you'll be able to send mail just like in the example below
   - mail:
     host: smtp.gmail.com
     port: 587
     secure: starttls
     charset: utf-8
     sender: victorradin9@gmail.com
     username: victorradin9@gmail.com
     password: your app password generated by google for you goes here
     to: 'cristianooross@gmail.com'
     subject: Ya u rite


text:
Q: How to use the 1st derivative of a network for training a data-driven physics model approximating a function? First, I am new to this forum and to machine learning as well, please keep that in mind.
I am trying to reproduce the neural network proposed in this paper using PyTorch: A mechanics-informed artificial neural network approach in data driven constitutive modeling. The goal of the neural network is to approximate a nonlinear function, which maps the input to the output, but using the derivative of the network as the actual output. That means, that the network learns the integral of the function.
My approach to coding this with PyTorch is at the end of this question (It would be great if you could review that as well, as the mistake might be somewhere else and I don't see it.).
The whole idea of the paper is as follows:
Input: x_0; Output: y
x_1 = activation(w_input * x_0 +b)
for l = 2,…,N_l do
    x_l = activation(softplus(Q;alpha) * x_(l-1) + b_l + w_skip_l * x_o
end for
y = softplus(Q, alpha) * x_(N_l-1) + f(x_0)

with the activation function being essentially the softplus function squared :
$SoftPlusSquared(z) = \frac{1}{2\:\beta^4} log(1+e^{\beta^2z})^2$ ($\beta$ is a learnable parameter)
And the loss function:
$loss =  \sum_{m=1}^{N_m} \sum_{k=1}^d \left(\frac{\frac{\partial N_\theta}{\partial E_k}(E^{(m)})-\frac{\partial N_\theta}{\partial E_k}(0)-Y_k}{\sigma_k}\right)^2$ ($N_\theta$ = network, $E_k$ = one single input, $E^{(m)}$ = sample, $Y_k$ = target, $\sigma_k$ = component-wise standard deviation of trainig target data, $N_m$ = number of samples, $d$ = input dimension)
All in all this network has the parameters $(\alpha, A, \cup_{l=1}^{N_l}(Q^{(l)},W^{(l)},b^{(l)}), \beta)$. ($N_l$ = number of layers)
I can't really figure out my mistake, although I believe the problem lies in my implementation of the loss function, which uses the derivative of the network and a correction term (which is also based on the derivative of the network.
Right now, the loss starts out very high and decreases to a certain point, from which it rises again.
It is also not possible to overfit, even with very small examples. In my opinion that is caused by the correction term which is applied in the loss function.
My questions regarding this network are:
How does one implement the double differentiation properly?
I tried to get the gradient of the output with respect to the input by using autograd, same procedure for the correction term, enabling the option create_graph. Those quantities were then used in the loss function, which is then used with the backward() method. My code for the training routine looks like this:
X_corr = torch.zeros(1,input_dim, requires_grad = True).type(torch.FloatTensor)
Y_corr = torch.zeros_like(X_corr)

def final_loss_func(gradients_output_wrt_input, gradients_corrector, target):
    sigma_k = torch.std(target, dim = 0)
    loss = torch.mean(torch.sum(((gradients_output_wrt_input - gradients_corrector - target)/sigma_k)**2, dim = 1))
    return loss

model = MyModule()
learning_rate = 0.00001
optimizer = torch.optim.Adagrad(model.parameters(), lr=learning_rate)
epochs = 20000+1

for epoch in range(epochs):

    optimizer.zero_grad()

    pred = model(X)
    pred_corr = model(X_corr)

    X_gradients = torch.autograd.grad(pred, X, retain_graph=True, grad_outputs=torch.ones_like(pred), create_graph = True)[0]
    X_corr_gradients = torch.autograd.grad(pred_corr, X_corr, retain_graph=True, grad_outputs=torch.ones_like(pred_corr), create_graph = True)[0]

    X_corr_gradients_no_grad = X_corr_gradients.detach()
    loss = final_loss_func(X_gradients, X_corr_gradients_no_grad, Y)
    optimizer.step()

Also: how do I add a convex function like $f(x) = x^T A^T A x$, which is proposed in the paper, to the output, while keeping the Matrix A as a learnable parameter?
The problem here is the dimension of the input is $batchSize*sampleDimension$ leading to $f(x)$ as a $batchSize*batchSize$ matrix, although it must be a $batchSize*1$ vector. Applying $f(x)$ to each sample separately delivers the right dimension, but also makes it impossible to learn A as a parameter, because it makes the differentiation impossible. My code for that looks like this:
class ConvexFunction(torch.nn.Module):
    def __init__(self, input_size):
        super().__init__()
        A = torch.Tensor(input_size, input_size)
        self.A = torch.nn.Parameter(A)
        nn.init.orthogonal_(self.A)
    def forward(self, x):
        A_T = torch.transpose(self.A, dim0 = 0, dim1 = 1)
        A_T_A = torch.matmul(A_T, self.A)
        result = torch.zeros(x.size(dim = 0),1)
        for i in range(x.size(dim = 0)):
            result[i] = x[i] @ A_T_A @ x[i]
        return result

The whole code for the network:
import torch
import torch.nn as nn
import pandas as pd

torch.manual_seed(0)

df = pd.read_csv("Strain_Stress_Pairs_XL_3columns.csv", sep = ',', decimal='.')
x = df.iloc[:,0:3].values
y = df.iloc[:,3:7].values

x = x *9.091
X = torch.from_numpy(x).type(torch.FloatTensor)
Y = torch.from_numpy(y).type(torch.FloatTensor)
X.requires_grad_(True)

means = Y.mean(dim=1, keepdim=True)
stds = Y.std(dim=1, keepdim=True)
for i in range(stds.size(dim = 0)):
    if stds[i] < 1e-20:
        stds[i] = 1e-20
Y = (Y - means) / stds

X_corr = torch.zeros(1,3, requires_grad = True).type(torch.FloatTensor)
Y_corr = torch.zeros_like(X_corr)

class ConvexFunction(torch.nn.Module):
    def __init__(self, input_size):
        super().__init__()
        A = torch.Tensor(input_size, input_size)
        self.A = torch.nn.Parameter(A)
        nn.init.orthogonal_(self.A)
    def forward(self, x):
        A_T = torch.transpose(self.A, dim0 = 0, dim1 = 1)
        A_T_A = torch.matmul(A_T, self.A)
        result = torch.zeros(x.size(dim = 0),1)
        for i in range(x.size(dim = 0)):
            result[i] = x[i] @ A_T_A @ x[i]
        return result

class LearnedSoftPlusSquared(torch.nn.Module):
    def __init__(self, init_beta=1.0, threshold=20):
        super().__init__()
        self.log_beta = torch.nn.Parameter(torch.tensor(float(init_beta)).log())
        self.threshold = 20
    def forward(self, x):
        beta = self.log_beta.exp()
        beta_squared = beta**2
        beta_squared_x = beta_squared * x
        return torch.where(beta_squared_x < 20, 0.5 * ((torch.log1p(beta_squared_x.exp()) / beta_squared)**2), x)

class SoftPlusLinear(nn.Module):
    def __init__(self, input_size, output_size, init_alpha=1.0, threshold=20):
        super().__init__()
        w = torch.Tensor(output_size, input_size)
        self.w = nn.Parameter(w)
        nn.init.orthogonal_(self.w)
        b = torch.Tensor(output_size).fill_(0)
        self.b = nn.Parameter(b)
        self.log_alpha = torch.nn.Parameter(torch.tensor(float(init_alpha)).log())
        self.threshold = 20

    def forward(self, x):
        alpha = self.log_alpha.exp()
        alpha = alpha**2
        alpha_weight = alpha * self.w
        w_new = torch.log1p(alpha_weight.exp()) / alpha
        return nn.functional.linear(x, w_new, bias=self.b)

class MyModule(nn.Module):
    def __init__(self):
        super().__init__()

        input_size = 3
        out_l1 = 9
        out_l2 = 9
        out_l3 = 6
        out_l4 = 3
        output_size = 1

        w_skip_1 = torch.Tensor(input_size, out_l2)
        self.w_skip_1 = nn.Parameter(w_skip_1)
        nn.init.orthogonal_(self.w_skip_1)

        w_skip_2 = torch.Tensor(input_size, out_l3)
        self.w_skip_2 = nn.Parameter(w_skip_2)
        nn.init.orthogonal_(self.w_skip_2)

        w_skip_3 = torch.Tensor(input_size, out_l4)
        self.w_skip_3 = nn.Parameter(w_skip_3)
        nn.init.orthogonal_(self.w_skip_3)

        matrix_conv = torch.Tensor(input_size,1)
        self.matrix_conv = nn.Parameter(matrix_conv)
        nn.init.orthogonal_(self.matrix_conv)

        self.convex_layer = ConvexFunction(input_size)
        self.l1 = nn.Linear(input_size,out_l1)
        self.a1 = LearnedSoftPlusSquared()
        self.l2 = SoftPlusLinear(out_l1,out_l2)
        self.a2 = LearnedSoftPlusSquared()
        self.l3 = SoftPlusLinear(out_l2,out_l3)
        self.a3 = LearnedSoftPlusSquared()
        self.l4 = SoftPlusLinear(out_l3,output_size)

    def forward(self, x):

        x_in = x
        x = self.l1(x)
        x = self.a1(x)
        x = self.l2(x)
        x = torch.add(x, torch.mm(x_in, self.w_skip_1))
        x = self.a2(x)
        x = self.l3(x)
        x = torch.add(x, torch.mm(x_in, self.w_skip_2))
        x = self.a3(x)
        x = self.l4(x)#+ self.convex_layer(x_in) convex function not working!
        return x

def final_loss_func(gradients_output_wrt_input, gradients_corrector, target):
    sigma_k = torch.std(target, dim = 0)
    loss = torch.mean(torch.sum(((gradients_output_wrt_input - gradients_corrector - target)/sigma_k)**2, dim = 1))
    return loss

model = MyModule()
learning_rate = 0.00001
optimizer = torch.optim.Adagrad(model.parameters(), lr=learning_rate)
epochs = 20000+1

for epoch in range(epochs):

    optimizer.zero_grad()

    pred = model(X)
    pred_corr = model(X_corr)

    X_gradients = torch.autograd.grad(pred, X, retain_graph=True, grad_outputs=torch.ones_like(pred), create_graph = True)[0]
    X_corr_gradients = torch.autograd.grad(pred_corr, X_corr, retain_graph=True, grad_outputs=torch.ones_like(pred_corr), create_graph = True)[0]

    X_corr_gradients_no_grad = X_corr_gradients.detach()
    loss = final_loss_func(X_gradients, X_corr_gradients_no_grad, Y)
    optimizer.step()
    loss.backward()

    print(loss)

Thank you for your time.


text:
Q: Angular JS - request in order to get an image I would like to display a jpeg image on UI. For this, I request my service (GET method) and then I converted to base 64:
$http({
    url: "...",
    method: "GET",
    headers: {'Content-Type': 'image/jpeg'}
}).then(function(dataImage){
    var binary = '';
    var responseText = dataImage.data;
    var responseTextLen = dataImage.data.length;
    for (var j = 0; j < responseTextLen; j+=1) {
         binary += String.fromCharCode(responseText.charCodeAt(j) & 0xff)
    }
    base64Image = 'data:image/jpeg;base64,' + window.btoa(binary);
});

In the end, my browser tells me that the image is corrupt or truncated.
So I tried creating a XMLHttpRequest using a overrideMimeType('text / plain; charset = x-user-defined') and it works:
var xhr_object = new XMLHttpRequest();
xhr_object.overrideMimeType('text/plain; charset=x-user-defined');
xhr_object.open('GET', '...', false);
xhr_object.send(null);
if(xhr_object.status == 200){
    var responseText = xhr_object.responseText;
    var responseTextLen = responseText.length;
    var binary = ''
    for (var j = 0; j < responseTextLen; j+=1) {
        binary += String.fromCharCode(responseText.charCodeAt(j) & 0xff)
    }
    base64Image = 'data:image/jpeg;base64,' + window.btoa(binary);
}

what is the difference?

A: Now AngularJS respects the XHR (XMLHttpRequest) standard and you can use plain angular JS $http combined with the HTML FileReader.
The trick is to get the data as a blob which you pass to the reader.
var url = 'http://'; // enter url here
$http.get(url,{responseType: "blob"}).
    success(function(data, status, headers, config) {
        // encode data to base 64 url
        fr = new FileReader();
        fr.onload = function(){
            // this variable holds your base64 image data URI (string)
            // use readAsBinary() or readAsBinaryString() below to obtain other data types
            console.log( fr.result );
        };
        fr.readAsDataURL(data);
    }).
    error(function(data, status, headers, config) {
        alert("The url could not be loaded...\n (network error? non-valid url? server offline? etc?)");
    });

A: I know this isn't an answer so I'm not sure if it's even worth posting.  It's similar to what you're doing but in the opposite direction!  But here goes:
I'm posting an image data string from a canvas element (canvas.toDataURL("image/png")) to the server (node + express), saving it as a png on the server, then serving that image as a URL to a third party API.
Here's the original XMLHttpRequest I had in an angular.js controller:
var dataURL = encodeURIComponent(canvas.toDataURL("image/png"));
var url = "/camera/" + name + "/";

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = response;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("image=" + dataURL);

Here it is converted into an angular.js $http service:
var dataURL = encodeURIComponent(canvas.toDataURL("image/png"));
var url = "/camera/" + name + "/";

var config = {
  method: 'POST',
  url: url,
  data: $.param({ image: dataURL }),
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
};

$http(config);

express function to save the image on the server:
app.post('/camera/:username', function (req) {
  var username = req.params.username,
    image = decodeURIComponent(req.body.image),
    binaryData;

  var base64Data = image.replace(/^data:image\/png;base64,/, "");
  base64Data += base64Data.replace('+', ' ');
  binaryData = new Buffer(base64Data, 'base64').toString('binary');

  fs.writeFile("public/camera-images/" + username + ".png", binaryData, "binary");
});


text:
Q: Save panels location after closing in a Netbeans Java application I have a Java application developed in Netbeans 8.0.2. I would like to save the position of the panels in this application so when I close it and open it again it will remember if the "Projects tab" is on the right side or in the left side for example.
Any idea how could I do this?

A: A Netbeans Platform application should do this automatically. For a regular Swing or JavaFX application your on your own to save positions to a file  and restore the positions after reading the file.
One thing to note however about the Netbeans Platform application is that a clean and build will delete your saved positions. This is not a problem for your users that will never be expected to rebuild your application from source but it could explain your not seeing the positions saved as you do testing and development.


text:
Q: How do I iterate through pandas dataframe and calculate average? Temperature Dataframe
I have a pandas dataframe which has the record maximum temperature and minimum temperature of every month of the years 1953 and 1954. Now I want to calculate average max and min temperature value of each year (eg. for each year summing up max temperatures of 12 months and dividing it by 12). How can I do that?

A: Considering you don't require Month column in output and want the mean of Max and Min Temperature by year.
Solution.
df.groupby('Year',as_index=False).mean().drop(columns='Month')
Input
    Year    Month   MaxTemperature  MinTemperature
0   1953    1       26.7            10.9
1   1954    2       29.2            9.9
2   1953    1       27.4            11.0
3   1954    2       28.0            11.2
4   1953    1       28.0            13.0
5   1954    2       25.4            9.4
6   1953    1       26.0            12.0
7   1954    2       29.1            10.5

Output
    Year    MaxTemperature  MinTemperature
0   1953      27.025          11.725
1   1954      27.925          10.250

A: Try -
import numpy as np
df  = df.groupby('Year', as_index=False).agg({'MaxTemperature': np.mean, 'MinTemperature' : np.mean})


text:
Q: "Established connection was aborted by the software in your host machine" (IIS) I'm trying to configure IIS 7.5 so that it can serve large (400mb) files via HTTP. The client is a C# client using WebClient.DownloadFile() (basically wrapping an HTTP GET request).
However when downloading, I occasionally get the error from the client:

An established connection was aborted by the software in your host machine

Anything I can do in either the client or IIS to prevent this error?

A: After much digging around, it looks like a dodgy internet connection on my side. All clients on my site disconnect at the same time, but clients on another site stay connected. Unfortunately the internet router that I have here doesnt have any connectivity logs (its a top-of-the-range linksys.. go figure) so it wasnt easy to see what the problem was.


text:
Q: How to deal with ROLES and FOSOAuthServerBundle scopes I have a basic api that authenticates users using FOSOAuthServerBundle. Users can have ROLE_USER and ROLE_ADMIN roles. Based on FOSOAuthServerBundle docs, the default behavior is to use scopes as roles, so I've thought that when I have a regular user, the bundle would return scope: userin the response, and when it's a admin user, would return scope: admin. But it's not working like this. The bundle is returning whatever is configured in the supported_scopesentry. Below is my config.yml.
fos_oauth_server:
    service:
        options:
            supported_scopes: user admin

My access_control section in security.yml is empty, and my firewalls section is below:
firewalls:
        users_create:
            pattern: ^/v1/users
            methods: [POST]
            security: false

        api:
            pattern:    ^/
            security: true
            fos_oauth:  true
            stateless:  true

access_control:
        # You can omit this if /api can be accessed both authenticated and anonymously

This way the bundle always return user admin as scope, even if the user does not have the ROLE_ADMIN role.
{
"access_token": "ZGQ2ODE5ZjAzNTZkOWY0OWMyNmZmODE4MjcwZTJmYjExNzY0NzQxOTRmMzk4NzA2Mjc2NjIyZmY1ZDgwMzk4NA"
"expires_in": 3600
"token_type": "bearer"
"scope": "user admin"
"refresh_token": "NmM5ZGFmNzBiNTNjYmQzMTQ1MTk0ODJjOTAxMWU0YWIwMzM1MzgyODg4ZTAzNTI5ZTk2MDc3OGU2MTg0MWZiMA"
}

What I'm I missing? Isn't the user role attached to token scope? Is there any better way to know if my user is an admin or not?

A: From the doc, the default behaviour is to map scopes with roles. In your case, the roles would be ROLE_USER and ROLE_ADMIN.
Now to restrict usage, you'd edit your security.yml file somewhat like this:
# app/config/security.yml
security:
    access_control:
        - { path: ^/api/super/secured, role: ROLE_ADMIN }
        - { path: ^/api/general, role: ROLE_USER }

To restrict access inside controller, you can use this:
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
    // the user has the ROLE_ADMIN role, so act accordingly
}

Again from the doc,

Now, clients will be able to pass a scope parameter when they request
  an access token.

Hope this helps.
UPDATE:
Look at this answer here to a similar question and this article on setting up FOSOAuthServerBundle  . Pay close attention to the configuration part.

A: FOSOAuthServerBundle authenticate your user, based on token, so you dont have to worry about scopes, it is a different thing then roles. Inside your controller you can get $this->getUser() to get the current authenticated user. If this works then checking if isGranted works as well.
http://symfony.com/doc/current/book/security.html
public function helloAction($name)
{
    // The second parameter is used to specify on what object the role is tested.
    $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');

    // Old way :
    // if (false === $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
    //     throw $this->createAccessDeniedException('Unable to access this page!');
    // }

    // ...
}

In case of  $this->getUser() doesnt work you will have to set fetch to EAGER on the AccessToken entity.
class AccessToken extends BaseAccessToken
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Client")
     * @ORM\JoinColumn(nullable=false)
     */
    protected $client;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", fetch="EAGER")
     */
    protected $user;
}

A: There is an issue on github that dates back to 2013 for this. If you read that issue and follow the links you will eventually end up with the user Spomky creating his own library and Symfony bundle and being suggested as a maintainer of the FOSAuthServerBundle. It appears the FOS organisation will merge Spomky's work into the next major version of FOSOAuthServerBundle once it is stable.

A: You can return the user account information along with the token.
Here is my approach to deal with a similar situation, I have created a proxy route that takes the username and password as request parameters, adds the oauth client info to the request and forwards the request to the Oauth Token Action. Then I take that info and return the user info along with the token.
/**
 * @REST\Post("/authorize")
 */
public function loginAction(Request $request){
    $request->request->add( array(
        'grant_type' => 'password',
        'client_id' => $this->container->getParameter('oauth_client_id') . "_" . $this->container->getParameter('oauth_client_random_id'),
        'client_secret' => $this->container->getParameter('oauth_client_secret')
    ));
    $tokenAction = $this->get('fos_oauth_server.controller.token')->tokenAction($request);
    $tokenObject = json_decode( $tokenAction->getContent() );

    if(key_exists('error_description', $tokenObject)){
        return $this->view(["error" => $tokenObject->error_description], 401);
    };

    $user = $this->getDoctrine()->getRepository('\App\Entity\Oauth\AccessToken')->findOneBy( array('token' => $tokenObject->access_token ) )->getUser();
    $return = array(
        "roles" => $user->getUser()->getRoles(),
        "access_token" => $tokenObject->access_token,
        "expires_in" => $tokenObject->expires_in,
        "token_type" => $tokenObject->token_type,
        "scope" =>$tokenObject->scope,
        "refresh_token" => $tokenObject->refresh_token
    );
    return $this->view($return);
}

I use this route for authentication / token generation, rather than using the route that comes with the OAuthBundle


text:
Q: Squeryl NullPointerException on simple database Insert? Using Play! 1.2.4, Scala, and Squeryl with Postgres
Performing a simple DB insert like usual and all of the sudden the database has started throwing NullPointerExceptions like crazy. All started when I created an email invite handler that could auto-add someone to an account.
The code:
Member.scala where the insert takes place:
def insert(member:Member) = DB.members.insert(member)

The code above is where Play! indicates the NullPointerException takes place. When I run the debugger on val member below it shows a valid Member class with appropriate values.
def invitation(s:Option[String]) = {
    s match {
      case Some(s) => {
        val invite = Invite.getByKey(s)

        invite match {
          case Some(invite) => {
            User.search(invite.email) match {
              case Some(user) => {
                  val member = new Member(user.id,invite.accountId,null)
                  Member.insert( member )
                  session.clear()
                  flash += "notice" -> "Success! Please login to continue."
                  Action(Authentication.login)
              }
              case _ => Action(Users.`new`(s))
            }
          }
          case None => Error("Invite does not exist.")
        }
      }
      case None => Action(Application.index)
    }
  }

The stack trace:
Internal Server Error (500) for request GET /invitation?s=e3dfd60e-bc07-496a-918
1-97c6ea4b0b71

Execution exception (In /app/models/Member.scala around line 59)
NullPointerException occured : null

! play.exceptions.JavaExecutionException
!       at play.mvc.ActionInvoker.invoke(ActionInvoker.java:231)
!       at Invocation.HTTP Request(Play!)
! Caused by: java.lang.NullPointerException
!       at org.squeryl.internals.FieldMetaData.get(FieldMetaData.scala:260)
!       at org.squeryl.internals.DatabaseAdapter$class.writeValue(DatabaseAdapte
r.scala:456)
!       at org.squeryl.adapters.PostgreSqlAdapter.writeValue(PostgreSqlAdapter.s
cala:24)
!       at org.squeryl.internals.DatabaseAdapter$$anonfun$writeInsert$2.apply(Da
tabaseAdapter.scala:415)
!       at org.squeryl.internals.DatabaseAdapter$$anonfun$writeInsert$2.apply(Da
tabaseAdapter.scala:415)
!       at org.squeryl.internals.DatabaseAdapter$class.writeInsert(DatabaseAdapt
er.scala:415)
!       at org.squeryl.adapters.PostgreSqlAdapter.writeInsert(PostgreSqlAdapter.
scala:70)
!       at org.squeryl.Table$$anonfun$insert$1.apply(Table.scala:39)
!       at org.squeryl.logging.StackMarker$.lastSquerylStackFrame(StatisticsList
ener.scala:52)
!       at org.squeryl.Table.insert(Table.scala:34)
!       at models.Member$.insert(Member.scala:59)
!       at controllers.Invites$.invitation(Invites.scala:24)
!       at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:548)

!       at play.mvc.ActionInvoker.invoke(ActionInvoker.java:502)
!       at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:496)

!       at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:473)

!       at play.mvc.ActionInvoker.invoke(ActionInvoker.java:161)
!       ... 1 more

Help appreciated
Never seen this before and it might be a simple fix, your help is much appreciated.

A: This one was an easy fix, and I'm a little surprised I didn't get a hiccup during compile.
When assembling my Member class I used Scala None instead of null on that third value, and it worked just fine.
Too bad Squeryl can't put out a better error for debugging.


text:
Q: Convert a text file from ansi to UTF-8 in windows batch scripting We have a text file which is in default ANSI format and that needs to be converted into UTF-8 format. Is there any way we can use the general windows DOS commands to convert the file? We can use the PowerShell but only this command line has to be run from a different batch process.

A: The PowerShell syntax is rather straightforward. This command opens a file in the default encoding and saves it as UTF-8 with BOM:
Get-Content <SrcFile.txt> -Encoding Oem | Out-File <DestFile.txt> -Encoding utf8

The Encoding parameter accepts the following: Ascii, BigEndianUnicode, BigEndianUTF32, Byte, Default, Oem, String, Unicode, Unknown, UTF32, UTF7, UTF8

A: Get-Content might be not optimal as it handles the input file line by line (at least, by default, if you don't use the Raw switch as described later), and may cause changing the line ending (for example, if you move text files between Unix and Windows systems). I had serious problems in a script just because that, and it took about an hour to find the exact reason. See more about that in this post. Due to this behavior, Get-Content is not the best choice as well, if performance matters.
Instead of this, you can use PowerShell in combination of the .NET classes (as long you have a version of the .NET Framework installed on your system):
$sr = New-Object System.IO.StreamReader($infile)
$sw = New-Object System.IO.StreamWriter($outfile, $false, [System.Text.Encoding]::Default)

$sw.Write($sr.ReadToEnd())

$sw.Close()
$sr.Close()
$sw.Dispose()
$sr.Dispose()

Or even more simply, use the Raw switch as described here to avoid that overhead and read the text in a single block:
Get-Content $inFile -Raw


text:
Q: Wording suggestion for the "You must wait x hours before accepting your own answer" message I think the message that you get when you try to accept your own answer within the last hour of the 48 hour waiting period is poorly worded.  The message is "You must wait 0 hours before accepting your own answer." Yes, I realize it is accurate, as it means "less than 1 hour" -- but still.
One could special-case this situation and reword that to something like "You must wait less than 1 hour before accepting your own answer." Or approaching the issue from another angle, if the message was instead worded like "You cannot accept your own answer until January 23, 2010 03:23:23" then there would be no need for the inaccuracy.  Time zone display would obviously be a factor/complication in this one.
BTW, I am aware of the the other metaSO post on this topic, but there was no suggestion there of an improvement to the message, hence me starting a new thread with that intent.

A: Ok, I switched to our standard .ToRelativeTime() function here. Not sure why we had it this weird way before.


text:
Q: How to get list of mailboxes using AE.Net.Mail? I'm trying to get a list of mailboxes using AE.Net.Mail and I cannot find any documentation. The ListMailboxes method takes in a reference string and a pattern string. I'm not sure what either parameter should be.
using (var imap = new AE.Net.Mail.ImapClient(host, username, password, AE.Net.Mail.ImapClient.AuthMethods.Login, port, isSSL))
{
    List<Mailbox> boxes = imap.ListMailboxes("", ""); // string reference, string parameter
}

A: I found this to work:
var listMailboxes = imap.ListMailboxes(string.Empty, "*");

foreach (var listMailbox in listMailboxes)
{
    var mailbox = listMailbox.Name;
}

A: The ImapClient.ListMailboxes method from AE.Net.Mail is a pretty thin wrapper for the IMAP LIST command.
public Mailbox[] ListMailboxes(string reference, string pattern)
{
    IdlePause();

    var x = new List<Mailbox>();
    string command = GetTag() + "LIST " + reference.QuoteString() + " " + pattern.QuoteString();
    string reg = "\\* LIST \\(([^\\)]*)\\) \\\"([^\\\"]+)\\\" \\\"?([^\\\"]+)\\\"?";
    string response = SendCommandGetResponse(command);
    Match m = Regex.Match(response, reg);
    while (m.Groups.Count > 1)
    {
        Mailbox mailbox = new Mailbox(m.Groups[3].ToString());
        x.Add(mailbox);
        response = GetResponse();
        m = Regex.Match(response, reg);
    }
    IdleResume();
    return x.ToArray();
}

Section 6.3.8 of the IMAP RFC contains some examples of how these parameters are generally interpreted by the IMAP server ("Mailbox Name" is the pattern parameter):
Reference     Mailbox Name  Interpretation
------------  ------------  --------------
~smith/Mail/  foo.*         ~smith/Mail/foo.*
archive/      %             archive/%
#news.        comp.mail.*   #news.comp.mail.*
~smith/Mail/  /usr/doc/foo  /usr/doc/foo
archive/      ~fred/Mail/*  ~fred/Mail/*

Though it also says the following regarding the Reference parameter:

Note: The interpretation of the reference argument is
implementation-defined.  It depends upon whether the
server implementation has a concept of the "current
working directory" and leading "break out characters",
which override the current working directory.

So the examples may or may not work depending on your server implementation.


text:
Q: Number of ways to divide N different points into k groups I'm trying to calculate the following. Given N different points in 2D space, and $1 \leq K \leq N $
a) The number of possibilities, to divide the points into K groups, without importance of the group numbers.
b)The number of possibilities, to divide the points into K groups, with importance of the group numbers.
Empty groups are not allowed.
Thx for the help :)
Cheers

A: You are looking for:
a) Stirling numbers of the second kind
b) a)$\times k!.$ This are related to Fubini numbers. Notice that the $k!$ what it does is permutes the "group numbers".


text:
Q: Find fastest path I have a list of trains with arrival timings at various stations. I need to find the fastest path between two railway stations if possible. In order to do it, I am even allowed to change the train once throughout the journey. However, If I change the train I must also add up the waiting time while boarding another train. Below is the pseudocode which I have written, but I am facing issues in completing it. Especially while changing the train and keeping the count of waiting hours. Can anyone help me with this and correct my pseudo-code.
function findFastestPath(source_station,dest_staion,waiting_time_at_current_station,travel_time_in_previous_train):
    for each train_schedule in TrainList:
        while train_schedule is not over:
            if source_station equals train_schedule[station]
            Then
                if dest_staion in train_schedule
                Then
                    if dest_staion[departure_time] > source_station[departure_time]
                    Then
                        duration = dest_staion[departure_time] - source_station[departure_time] + waiting_time_at_current_station + travel_time_in_previous_train
                        if mintime > duration
                        Then
                            mintime = duration
                else:
                   travel_time_in_previous_train = next_station_to_source_station[departure_time]-source_station[departure_time]
                   waiting_time_at_current_station = next_train_departure_time - next_station_to_source_station[departure_time]
                   call findFastestPath(next_station_to_source_station, dest_staion, waiting_time_at_current_station, travel_time_in_previous_train)
        return mintime
end function

for each source_station in Travel_Time_Matrix:
    for each dest_staion in Travel_Time_Matrix:
        call findFastestPath(source_station,dest_staion,0,0)

A: FindFastestPathInSameTrain(src,dest):
    For x in range(Len(TrainList)):                                    //TrainList is a two dimentional array which has each train schedule in each row
        IF src and dest in TrainList[x]:
            IF dest(time) > src(time):                                 // Here we are checking if destination station is not before source station in train
                duration = src->departuretTime - dest->departuretTime  // calculating duration
                IF min > duration:                                     // min value will be updated if as we find fastest fast in other trains
                    min = duration
        else:
            NewTrainList.add(TrainList[x])                             // if line 2 is not satisfied we will add that train in NewTrainList which is 2d array
    return min                                                 // by default  min value will be 1000, and it will be returned in case of no direct train

FindFastestPathInSecondTrain(src,dest):                                // now we will work on trains which dont has both source and destination station
   For x in range(Len(NewTrainList)):                                  // we will iterate NewTrainList
       IF src in NewTrainList[x]:                                      // if we find our Source station in NewTrainList
           For n in range(NewTrainList[x].index(src)+1,len(NewTrainList[x])): // we will iterate that trains remaining station as src in a new extended function
               FindFastestPathInSecondTrainExtension(NewTrainList[n],dest,src->departuretTime)

// this comment is for line 16 : Just as our FindFastestPathInSameTrain(), but here we will send origin departuretTime so as to capture time spent in prev train + waiting time at connecting station.

FindFastestPathInSecondTrainExtension(newsrc,dest,src->departuretTime): // This function will work similar to FindFastestPathInSameTrain()
    For x in range(Len(NewTrainList)):
        IF newsrc and dest in NewTrainList[x]:
            IF dest->departuretTime > newsrc->departuretTime
                secondDuration = (dest->departuretTime - newsrc->departuretTime) + (newsrc->departuretTime - src->departuretTime)
                IF min > secondDuration
                   min = secondDuration
    return min

For each source_station in Travel_Time_Matrix:                         // Iterating all the source_station
    For each dest_staion in Travel_Time_Matrix:                        // Iterating all the dest_station
        T1 = FindFastestPathInSameTrain(source_station,dest_station)
        T2 = FindFastestPathInSecondTrain(source_station,dest_station)
        IF T1 < T2
           write T1
        ELSE:
           write T2


text:
Q: Fermion derivative coupling in QFT I'm interested in a QFT model featuring a fermion derivative coupling like $XX^* \chi^*\gamma^\mu∂_\mu \psi$ where X is some other field operator.
Has anybody seen a paper containing something like this?
How would Feynman-Graphs for such an interaction look like?
Are derivatives of fermions ruled out by some consideration i am missing?

A: In four dimensions, the interaction term you have written is expected to render your field theory non-renormalizable.  This is OK as far as modeling low energy physics is concerned.  But, there is another problem.  The interaction is not Hermitian (which would lead not non-unitary time evolution).
Now, the Feynman rule that would be generated from this is a four-point interaction, involving the transformation of a spin-1/2 $\psi$ quanta into a $\chi$ quanta, with an associated emission of a $X$/$X*$ pair.  The Feynman rule for such a vertex should be dependent on the momentum: $\text{vertex}=\gamma^\mu p_\mu$.


text:
Q: Getting length as number? I have probably formulated the question wrong, as I don't know the Tex internals - but this is what I mean; consider this example:
\newcommand{\myNum}{2}
\newlength{\myLength}
\setlength{\myLength}{\myNum cm}

Here, I'd consider \myNum to represent a 'numeric variable', and \myLength a Tex length (i.e. a number and a unit); and so I'd consider the above example a "conversion" from numeric to length "variable".
Is it possible to do the other way around? I.e. if \myLength is given to be 2 cm, is there a command that will "get"/"extract" the numeric value only? I'd imagine doing something like this (pseudocode):
\newcommand{\myNum}{\getlength{\myLength}}

... after which, \myNum would have value "2" ...
Does anything like this exist?
EDIT: I guess I need something similar to \the which is for counters ... ?!

A: One can use xfp:
\documentclass{article}
\usepackage{xfp}

\NewExpandableDocumentCommand{\getlengthnumber}{O{pt}m}{%
  % #1 (optional, default pt), #2 = length
  \fpeval{(#2)/(1#1)}%
}

\begin{document}

\getlengthnumber{\textwidth}

\getlengthnumber[cm]{\textwidth}

\getlengthnumber[cm]{1in}

\getlengthnumber[sp]{1pt}

\end{document}

The big advantage over the pgf methods is that this is fully expandable.

A: You can remove the pt unit from the length using \strip@pt as shown below. I you want the number in cm you would have to convert it by yourself.
\documentclass{article}

\makeatletter
\newcommand*{\getlength}[1]{\strip@pt#1}
% Or rounded back to `cm` (there will be some rounding errors!)
%\newcommand*{\getlength}[1]{\strip@pt\dimexpr0.035146\dimexpr#1\relax\relax}

\makeatother

\begin{document}

Test: \getlength{\textwidth}  % Result: 345

\end{document}

Another alternative which is more flexible and also allows you to store the resulting number in a macro is to use pgfmath (pgf package). It also allows you to easily convert the number to cm:
\documentclass{article}

\usepackage{pgf}
\newcommand*{\getlength}[2]{%
   \pgfmathsetmacro#1{#2}%  Result in `pt`
   % Or:
   %\pgfmathsetmacro#1{0.0351459804*#2}%  Result in `cm`
}

\begin{document}

\getlength{\myNum}{\textwidth}

Test: \myNum % Result: 345.0

\end{document}

There is also the round( ) function for pgfmath which allows you to round the number, e.g. to two fractional digits. The trick is to multiple it with 100 before the rounding and divide it afterwards by 100.
\documentclass{article}

\usepackage{pgf}
\newcommand*{\getlength}[2]{%
   % Convert to `cm` and round to two fractional digits:
   \pgfmathsetmacro#1{round(3.51459804*#2)/100.0}%
}

\begin{document}

\setlength{\textwidth}{2.123cm}
\getlength{\myNum}{\textwidth}

Test: \myNum% Gives 2.12

\setlength{\textwidth}{2cm}
\getlength{\myNum}{\textwidth}

Test: \myNum% Gives 2.0

\end{document}

The fractional part (like .0) can be avoided by using \pgfmathtruncatemacro instead of \pgfmathsetmacro, but I don't think you need that.

A: An alternative to Martin's approach is to use TeX's \number primitive, which will give you the underlying integer value in sp
\documentclass{article}

\newcommand*\getlength[1]{\number#1}

\begin{document}

Test: \getlength{\textwidth}

\end{document}

(TeX does everything in integers, more or less, so lengths are actually stored in sp, which are tiny length units. Everything else is an integer multiple of a value in sp.)

A: Here I would like to provide a simple solution with pgf
% !Mode:: "TeX:UTF-8"
\documentclass{article}
\usepackage{pgf}

\begin{document}
\noindent
\the\textwidth \\
\pgfmathparse{\textwidth}
\pgfmathresult \\
\end{document}

where \the\textwidth prints the length with units, while \pgfmathparse returns \textwidth without unit to \pgfmathresult

there are many more functions to choose from section Mathematical Expressions in pgf manual.


text:
Q: extract values of ping message I am working on an application on android that performs ping requests (via android shell) and I read from the console the message displayed. A typical message is the following
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=46 time=186 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=46 time=209 ms

--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 186.127/197.891/209.656/11.772 ms

I store the above message in a String. I want to extract the values of the time, for example 186 and 209 and also the percentage for loss, 0 (in this case).
I was thinking to go through the string and look the values after "time=". However I don't know how to do it.
How can I manipulate the string I have in order to extract the values?

A: Start by getting each line of the string:
String[] lines = pingResult.split("\n");

Then, loop and use substring.
for (String line : lines) {
    if (!line.contains("time=")) continue;
    // Find the index of "time="
    int index = line.indexOf("time=");

    String time = line.substring(index + "time=".length());
    // do what you will
}

If you want to parse to an int, you could additionally do:
int millis = Integer.parseInt(time.replaceAll("[^0-9]", ""));

This will remove all non-digit characters
You can do something similar for the percentage:
for (String line : lines) {
    if (!line.contains("%")) continue;

    // Find the index of "received, "
    int index1 = line.indexOf("received, ");

    // Find the index of "%"
    int index2 = line.indexOf("%");

    String percent = line.substring(index1 + "received, ".length(), index2);
    // do what you will
}