text:
Q: Use "/" as Optional Separator for Parameters in Url - Angular-Ui-Router I've a tricky issue that I was not able to solve in a while.
Essentially, when I'm on a certain $route and I do a certain $state.go(routeName, params);, I need to append a certain parameter or multiple parameters to the url.
Also, paying attention to the fact that route can also be visited with no parameters at all, so it has to be clean.
I would like to achieve this result:

*

*Actual Url: localhost:4000

*Wanted Url: localhost:/4000/myRoute/myStuff/myParam

*Avoid     : localhost:/4000/myRoute// if a $state.go(myRoute) with no parameters is provided.

For instance:
$state.go(myRoute, {
   param1 : 'myStuff',
   param2 : 'myParam'
});

function myRoute($stateProvider) {

    $stateProvider
        .state('myRoute', {
            url: 'myRoute/{param1}{param2}',
            parent: 'myParent'
              . . .
        })
}

Will work but giving localhost:/4000/myRoute/myStuffmyParam.
So, I tried using / as separator url: 'myRoute/{param1}' + '/' + '{param2}'
and it works just fine, I get localhost:/4000/myRoute/myStuff/myParam.
But, of course, / gets appended even if there are no parameters.
For instance, doing $state.go('myRoute') will lead to localhost:/4000/myRoute// that is clearly wrong.
Now, then, I told myself, well, maybe if I just add it to param1 I will achieve what I need.
So, I tried with

*

*param1 : 'myStuff' + '/'

*param1 : 'myStuff' + '\/'

*param1 : 'myStuff/'

*param1 : 'myStuff\/'
But all lead to the same url localhost:4000/myRoute/myStuff~2FmyParam.
While, if I use another separator like - it works just fine.
param1 : 'myStuff-' leads to localhost:4000/myRoute/myStuff-myParam
EDIT
Using {param} and :param is the same. Reference angular-ui/ui-router URL Routing
I don't find any solution also looking at answers provided at way to create optional parameter in url?. Trying myRoute[/:param1[/:param2]] will also throw an error.
EDIT
Also trying param1%2F or 'param1' + '%2F' won't work.
I respectively get ~2F & %252f as separator. Also doing a decodeURI('%2F') leads to the same miserable result.

*

*Whats the proper way to use such separator, avoiding it to be appended when there are no parameters and also get rendered properly?
For any clarification just leave a comment.
Thanks in advance.

A: $stateProvider.state('state', {
    url: "/state/:id/:name/:something",
    templateUrl: "bla.html",
    controller: 'BlaCtrl'
  });

$state.go('state', {id: 1, name: 'pepe', something: 'nothing'});

This works for me, produces: /state/1/pepe/nothing

A: Can't you create a mother route, and a child route ? Isn't this possible ?

A: You don't need to make all this kind of machinery to achieve what you want. As @trichetriche said, you can create a certain set of child routes.
You need to edit your $routeProvider like:
//for the clean url - localhost:/4000/myRoute/
$stateProvider
    .state('myRoute', {
        url: 'myRoute/',
        parent: 'myParent'
          . . .
})
//for myStuff/param1 url - localhost:/4000/myStuff/param1
$stateProvider
    .state('myRoute.myStuff', {
        url: 'myStuff/{param1}', //also adding other params
        parent: 'myRoute'
          . . .
})

You can add as many children as you want if you need them.
With respectively  $state.go's:

*

*$state.go('myRoute');

*$state.go('myRoute.myStuff', { param1 : 'HeyOhLetsGo' });


text:
Q: how to evaluate this integral by considering $\oint_{C_{(R)}} \frac{1}{z^{2}+1}$ Consider the integral $I=\int_{-\infty}^{\infty} \frac{1}{x^{2}+1}\, dx$. Show how to evaluate this integral by considering $\oint_{C_{(R)}} \frac{1}{z^{2}+1}, dz$ where $C_{R}$ is the closed semicircle in the upper half plane with endpoints at $(-R, 0)$ and $(R, 0)$ plus the $x$ axis.
I use $\frac{1}{z^{2}+1}=-\frac{1}{2i}\left[\frac{1}{z+i}-\frac{1}{z-i}\right]$ and I must prove without using the residue theorem the integral along the open semicircle in the upper half plane vanishes as $R\rightarrow \infty$
Could someone help me through this problem?

A: Using the estimation lemma, let
$$\gamma_R:=\{z\in\Bbb C\;:\;|z|=R\,,\,\Im(z)\geq 0\}\Longrightarrow \left|\oint_{\gamma_R}\frac{dz}{z^2+1}\right|\leq \sup_{z\in\gamma_R}\frac{1}{|z^2+1|}\,R\pi\leq$$
$$\leq\frac{\pi R}{R^2-1}\xrightarrow [R\to\infty]{}0$$
Also Puting $\,z=Re^{it}\,\,,\,0\leq t\leq \pi\,\Longrightarrow dz=Rie^{it}dt\,$ , so:
$$\left|\oint_{\gamma_R}\frac{dz}{z^2+1}\right|=\left|\int_0^\pi\frac{Rie^{it}dt}{1+(Re^{it})^2}\right|\leq \pi\frac{R}{R^2-1}\xrightarrow [R\to\infty]{} 0$$

A: See @anon's answer.
For completion's sake we will examine the function $f(z) = \frac{1}{z^2 + 1}$ parametrized by $z = z_0 + Re^{i \theta}$. If we center the contour at $z_0 = 0$ then the expansion $z^2 = R^2 e^{2it}$ so $f(z) = \frac{1}{R^2 e^{2it} + 1}$.
Given the line integral:
$$\oint_{C}{f(z)\ \mathrm{d}z} = \int_a^{b}{f(C(\theta)) C'(\theta)}\ \mathrm{d}\theta$$
Where $C(\theta)$ is the parametrization of a circular contour using the variable theta. Fitting our function to the parametrization and evaluating:
$$\begin{aligned} \oint_{C}{f(z)\ \mathrm{d}z} &= \int_0^{\pi}{\frac{ie^{i \theta}}{R^2 e^{2it} + 1}}\ \mathrm{d}\theta \\&= -\frac{2 \tan^{-1}(R)}{R} \end{aligned}$$
We know that the ArcTangent is bounded by [0, 1) for all $0 \leq \theta \leq \pi$ so we can say $-\frac{2 \tan^{-1}(R)}{R} \leq -\frac{2M}{R}$. Next apply the limit for $R \to 0$
$$\lim_{R \to \infty}{ -\frac{2M}{R}} = 0$$
Thus, we have shown that as $R \to \infty$, the integral around the contour "vanishes".
This may go nowhere but perhaps you can even apply Cauchy-Goursat theorem to show that the integral about the contour is 0 so long as $i$ is not in the region enclosed by the contour. i.e. $R < 1$. Otherwise, when $R > 1$ use deformation of contours. Something to think about.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Struggle with string formatting pandas date I have the following stringy : 2017-12-03
I am looking forward to turn the str into to_datetime, add a BDay and change the format of such date.
what i tried was :
import datetime as dt
from pandas.tseries.offsets import BDay

valor_nuevo=(pd.to_datetime(stringy,'%Y-%m-%d') + BDay(1)).strftime('%d/%m/%Y')

And outputs as error  an AssertionError

A: You need define parameter format or omit it in to_datetime:
valor_nuevo = (pd.to_datetime(stringy,format='%Y-%m-%d') + BDay(1)).strftime('%d/%m/%Y')

valor_nuevo = (pd.to_datetime(stringy) + BDay(1)).strftime('%d/%m/%Y')

print (valor_nuevo)
04/12/2017


text:
Q: Displaying a large string in sentences one click at a time #branchID pool
branch0 = "This is a wall of text. This is a wall of text. This is a wall of text. This is a wall of text. This is a wall of text. This is a wall of text."
branch1 = "This is a second wall of text."
branch2 = "This is a third wall of text."

#classes section
  #pulls text from pools above.
branch = (name, branchid)->
  stringID = String(branchid)
  document.write("
#{name}
")
  document.getElementById(stringID).onclick = ->
    document.write(branchid)

#This is where the game goes. It will be built with conditionals
window.onload = ->
  branch('Start', branch0)

I'm creating a browser based "choose your own adventure" game using CoffeeScript. Above is the code I have so far. It creates an HTML element, and when clicked, a string of text is written to the page in one giant block.
My question is, How could I make it so only a sentence at a time is loaded, and then when clicked, the next sentence is loaded, then the next, until there is nothing else left in the string?

A: While I am not really sure, what it is that you try to accomplish I made a demo for you using your code as base that (hopefully) does what you want:
https://jsfiddle.net/Exinferis/qhr7wjmu/
#branchID pool
firstBranch = [
    "This is a wall of text. This is a wall of text. This is a wall of text. This is a wall of text. This is a wall of text. This is a wall of text."
  "This is a second wall of text."
    "This is a third wall of text."
]

currentStep = 0

#classes section
  #pulls text from pools above.
branch = (event)->
  if firstBranch[currentStep]?
    document.getElementById( "text" ).innerHTML = firstBranch[currentStep]
    currentStep++

#This is where the game goes. It will be built with conditionals
window.onload = ->
    document.getElementById( "nextbtn" ).onclick = branch


text:
Q: Add a banner message to Jupyter Hub/Lab instances? I'd like to add a banner to every Jupyter instance that is spawned by my users via Jupyter Hub/Lab.
Something to the effect of Do not copy and paste code from the internet into this notebook.
How can I accomplish such a thing?
Thank you!


text:
Q: Display JSON result in table Laravel 5.8 I want to display the JSON results to my HTML table in Laravel 5.8.
The result returned from the controller is as follows.
[[{"logged_on":"2019-06-24 00:00:00"},{"logged_on":"2019-06-21 00:00:00"}]]

My Ajax success function is as follows:
 $.ajax({
      url: url,
      type: "get",
      data: {user_id:user_id},
      contentType: "application/json",dataType: "json",
       success: function(data){ // What to do if we succeed
      if(data){
          alert(data);
            var len = data.length;
            var txt = "";
            if(len > 0){
                for(var i=0;i<len;i++){
                    if(data[i].logged_on){
                        txt += "<tr><td>"+data[i].logged_on;
                    }
                }
                if(txt != ""){
                    $("#table").append(txt).removeClass("hidden");
                }
            }
        }

else{
    alert("fails");
}
}
    });

Below is my controller function
$user_id = $requests->input('user_id');
$data = UserLogins::select('logged_on')->where('user_id',$user_id)->get()->toArray();

return response()->json(array($data));

But I am not getting the result in my table.

A: $user_id = $requests->input('user_id');
$data = UserLogins::select('logged_on')->where('user_id',$user_id)->get()->toArray();

return response()->json($data); // remove array() because $data return array


text:
Q: Am I calculating the total resistance of this circuit correctly? I'm picking up where I left off over a year ago on a signal conditioning circuit for a data acquisition system. The DUT (Device Under Test) is outputting a 1-25vpp 4000Hz square wave signal. The circuit I'm about to share represents the load of one of the DUT channels (HI and LO). I should mention I did not create this circuit; I explained what I wanted to an EE I used to work with and he created it.

*

*R1 + R2 + R3 = 999.7Ω (0.001000300090027)

*R10 + DS10 = 2,000Ω (0.0005)

*R10 + U10 = 2,000Ω (0.0005)

After reading (and understanding just a small amount of) this answer I decided to leave the LEDs DS10 and U10 out of the equation. If you feel this is a mistake, please let me know.
Using the above calculated reciprocals I come to a total resistance on CH1 of 499.92Ω.
Am I correct? Anything else you think I should take into consideration?


text:
Q: I'm trying to parallelize MCMC using R2Jags in R and need help solving this error I want to use the R2Jags parallel model (jags.parallel) to speed up my computations.
The documentation states I need to recompile the model before updating it. However I get a clear error that I don't know how to handle.
Error message:

Code that raises error:

In line 33 M[s] is used and M is defined in the data section.
What are possible reasons, that M is no longer defined when recompiling?
Cheers and thanks


text:
Q: Middleman + Bourbon error with gem im trying to build a middleman project using bourbon but I'm getting some problems.
Bundler could not find compatible versions for gem "sass":
  In Gemfile:
    bourbon (~> 4.0.1) ruby depends on
      sass (~> 3.3) ruby

    neat (>= 0) ruby depends on
      sass (3.2.19)

My gemfile:
# SASS
gem 'sass', '~> 3.3.7'

#Neat
gem 'neat'

#Bourbon
gem 'bourbon', '~> 4.0.1'

Is it not possible to run these things together? (I'm a beginner using ruby for projects).

A:
neat (>= 0) ruby depends on
  sass (3.2.19)

The latest version of Neat, which is 1.6.0, depends on Sass 3.3 and greater. It seems that you've got an older version of Neat in your gemset which Bundler tries to use.
Try running bundle update. If it doesn't help, try updating your Gemfile with this:

gem 'neat', '~> 1.6.0'

Then run bundle update again.
To see dependencies and their version of any versions of Ruby gems, visit RubyGems.org.
For example, Neat v1.6.0 lists lists the following dependencies:

*

*bourbon >= 3.1

*sass >= 3.3

A: Use the gem sass instead of gem sass-rails and also delete the *= require_tree . from your app/assets/stylesheets/application.scss.css file.


text:
Q: String was not recognised as a valid DateTime when parsing So I have some code that will write the current DateTime to a txt file and then post some embeds, if the txt file doesn't exist. If it does, then it will read the file, check if the date in the file was over 1 minute ago, if it was it should send  the same embed as the one that creates the file, if it hasn't been 1 minute then it will send an embed telling you to wait.
For some reason, the creating and sending aspect works fine, but if I run the command again, when it tries to convert the string to a DateTime it fails, saying "String was not recognized as a valid DateTime.". I have checked multiple websites and the datetime format I am using is correct. Any ideas?
string FilePath22 = Environment.CurrentDirectory + "/servers/" + Context.Guild.Id + ".txt";
string FilePath = Environment.CurrentDirectory + "/descriptions/" + Context.Guild.Id + ".txt";
string FilePath2 = Environment.CurrentDirectory + "/invites/" + Context.Guild.Id + ".txt";
var chnl = Context.Client.GetChannel(511281184760791056) as ITextChannel;
string invitelink = System.IO.File.ReadAllText(FilePath2);
string desclink = System.IO.File.ReadAllText(FilePath);
var builder2 = new EmbedBuilder()
        .WithColor(Color.Orange)
        .WithAuthor(Context.Guild.Name)
        .WithThumbnailUrl(Context.Guild.IconUrl)
        .WithUrl(invitelink)
        .AddField("Information", "**Owner:** " + Context.Guild.Owner + Environment.NewLine +
        "**Description:** " + Environment.NewLine + Environment.NewLine + desclink + Environment.NewLine + Environment.NewLine + "**Invite:** " + invitelink)
        .AddField("Other Info", "**Members:** " + Context.Guild.MemberCount + Environment.NewLine + "**Emotes:** " + Context.Guild.Emotes.Count + Environment.NewLine + "**Roles:** " + Context.Guild.Roles.Count + Environment.NewLine + "**Created At:** " + Context.Guild.CreatedAt.Date);
        var embed2 = builder2.Build();
        await chnl.SendMessageAsync(embed: embed2);
        var builder44 = new EmbedBuilder()
        .WithColor(Color.Orange)
        .WithTitle("Server Bumped!");
var embed44 = builder44.Build();

if (!File.Exists(FilePath22))
{
    await ReplyAsync(embed: embed44);
    System.IO.File.WriteAllText(FilePath22, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
    return;
}

string readit = System.IO.File.ReadAllText(FilePath22);
Console.WriteLine(readit);
var converted = DateTime.Parse(readit); //problem
Console.WriteLine(converted);
if (HoursPassed(converted))
{
    await ReplyAsync(embed: embed44);
    System.IO.File.WriteAllText(FilePath22, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
    return;
}

var builder10 = new EmbedBuilder()
        .WithColor(Color.Orange)
        .WithTitle("You must wait 24 hours before bumping your server! Try again later.");
var embed10 = builder10.Build();
await ReplyAsync(embed: embed10);

A: Use DateTime.ParseExact() or DateTime.TryParseExact(), e.g.
DateTime converted;
DateTime.TryParseExact(readit, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out converted);

With DateTime.Parse() it could be problem if the server default format is different from yours.


text:
Q: Load binary file using fstream I'm trying to load binary file using fstream in the following way:
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>

using namespace std;

int main()
{
    basic_fstream<uint32_t> file( "somefile.dat", ios::in|ios::binary );

    vector<uint32_t> buffer;
    buffer.assign( istream_iterator<uint32_t, uint32_t>( file ), istream_iterator<uint32_t, uint32_t>() );

    cout << buffer.size() << endl;

    return 0;
}

But it doesn't work. In Ubuntu it crashed with std::bad_cast exception. In MSVC++ 2008 it just prints 0.
I know that I could use file.read to load file, but I want to use iterator and operator>> to load parts of the file. Is that possible? Why the code above doesn't work?

A: *

*istream_iterator wants basic_istream as argument.

*It is impossible to overload operator>> inside basic_istream class.

*Defining global operator>> will lead to compile time conflicts with class member operator>>.

*You could specialize basic_istream for type uint32_t. But for specialization you should rewrite all fuctionons of basic_istream class. Instead you could define dummy class x and specialize basic_istream for it as in the following code:

using namespace std;

struct x {};
namespace std {
template<class traits>
class basic_istream<x, traits> : public basic_ifstream<uint32_t>
{
public:
    explicit basic_istream<x, traits>(const wchar_t* _Filename,
        ios_base::openmode _Mode,
        int _Prot = (int)ios_base::_Openprot) : basic_ifstream<uint32_t>( _Filename, _Mode, _Prot ) {}

    basic_istream<x, traits>& operator>>(uint32_t& data)
    {
        read(&data, 1);
        return *this;
    }
};
} // namespace std

int main()
{
    basic_istream<x> file( "somefile.dat", ios::in|ios::binary );
    vector<uint32_t> buffer;
    buffer.assign( istream_iterator<uint32_t, x>( file ), istream_iterator<uint32_t, x>() );
    cout << buffer.size() << endl;
    return 0;
}

A: The main question probably is what you mean by "binary file". The ios::binary only makes sure that the istream object doesn't replace platform-specific newlines by '\n'. Nothing else. Is that enough for you?
An istream_iterator basically is just a fancy way to invoke operator>>. If you have real binary data in your stream, that will fail. Do you have real binary data in your file? Or are the integers stored as strings?
If you need to read real binary integers, what you need is either istream.read() or using the stream buffer object directly.

A: You can reload operator>> to read integers properly. Of course all it will do is read() 4 bytes. But that's what all other operators>> are eventually doing anyway.
Here is example (no error checking, assuming endianess is same as current compiler uses, etc)
std::istream& operator>>(std::istream& in, uint32_t& data)
{
    in.read(&data, sizeof(data));
    return in;
}

Tailor for your own flavor of integers (might have to read one byte at a time and shift assign them, look at the file in hex editor if you don't know byte order), add error checking, and you should be able to use your existing code.
EDIT: ah, and yes, make sure this shadows provided stl operator that reads integer -- might have to derive your own class from the stream you are using and use that instead of std::istream& in, just so compiler knows who to check first.

A: A different way to do the same as Alexey Malistov's answer:
#include <fstream>
#include <iterator>
#include <vector>
#include <iostream>

struct rint // this class will allow us to read binary
{
  // ctors & assignment op allows implicit construction from uint
  rint () {}
  rint (unsigned int v) : val(v) {}
  rint (rint const& r) : val(r.val) {}
  rint& operator= (rint const& r) { this->val = r.val; return *this; }
  rint& operator= (unsigned int r) { this->val = r; return *this; }

  unsigned int val;

  // implicit conversion to uint from rint
  operator unsigned int& ()
  {
    return this->val;
  }
  operator unsigned int const& () const
  {
    return this->val;
  }
};

// reads a uints worth of chars into an rint
std::istream& operator>> (std::istream& is, rint& li)
{
  is.read(reinterpret_cast<char*>(&li.val), 4);
  return is;
}

// writes a uints worth of chars out of an rint
std::ostream& operator<< (std::ostream& os, rint const& li)
{
  os.write(reinterpret_cast<const char*>(&li.val), 4);
  return os;
}

int main (int argc, char *argv[])
{
  std::vector<int> V;

  // make sure the file is opened binary & the istream-iterator is
  // instantiated with rint; then use the usual copy semantics
  std::ifstream file(argv[1], std::ios::binary | std::ios::in);
  std::istream_iterator<rint> iter(file), end;
  std::copy(iter, end, std::back_inserter(V));

  for (int i = 0; i < V.size(); ++i)
    std::cout << std::hex << "0x" << V[i] << std::endl;

  // this will reverse the binary file at the uint level (on x86 with
  // g++ this is 32-bits at a time)
  std::ofstream of(argv[2], std::ios::binary | std::ios::out);
  std::ostream_iterator<rint> oter(of);
  std::copy(V.rbegin(), V.rend(), oter);

  return 0;
}


text:
Q: is String or is Number function I'm actually working on a personal "Excel" for school.
When the value of my cell is a number (int), I want to add it in my listNumber (QList int). When the value of my cell is a String, I want to add it my listString.
These two lists then allow me to sort.
The problem is here :
QString test = text(i, j);
test.toInt(&ok);
if (ok == true) {
    listNumber.append(test.toInt());
    qSort(listNumber.begin(), listNumber.end());
}

ERROR     ASSERT failure in QList<T>::at: "index out of range" .
I think it's because it wants to "insert" a string in a list of integer.
Here my function "sort"
QList<QString> listString;
QList<int> listNumber;

bool ok;
QTableWidgetSelectionRange range = selectedRange();

for (int j = range.leftColumn(); j <= range.rightColumn(); ++j) {
    for (int i = range.topRow(); i <= range.bottomRow(); ++i) {
        QString test = text(i, j);
        test.toInt(&ok);
        if (ok == true) {
            listNumber.append(test.toInt());
            qSort(listNumber.begin(), listNumber.end());
        }
    }
}

if (listNumber.count() == 0) {
    QMessageBox test;
    test.setText("liste vide");
    test.exec();
}
else {
    int x = 0;
    for (int j = range.leftColumn(); j <= range.rightColumn(); ++j) {
        for (int i = range.topRow(); i <= range.bottomRow(); ++i) {

            Spreadsheet::setFormula(i, j, QString::number(listNumber.at(x)));
            x++;
        }
    }
}

Thank you a lot for your help.

A: First of all, qSort in Qt is deprecated and it is recommended not to use it:

QT_DEPRECATED_X("Use std::sort") inline void qSort(...

You can use std::sort instead:
#include <algorithm>
//...
std::sort(listNumber.begin(), listNumber.end(), std::less<int>());

//or simply:
std::sort(listNumber.begin(), listNumber.end()); // using default comparison (operator <)

(But also you can simply call deprecated qSort:)
qSort(listNumber);


text:
Q: shell script executing network configuration hangs over tmux I am executing a shell script which is doing some network configuration.
when i execute this script using tmux it hangs.
===
Here how I am executing tmux in my bash
ARGS=$*
tmux new-session -d -s ISA_INSTALL "./installaccess $ARGS"
tmux attach

=====
Command which hangs is
0 16:54:33 cmd /usr/bin/ssh -x -o NumberOfPasswordPrompts=0 -o StrictHostKeyChecking=no -o GSSAPIAuthentication=no -o ControlMaster=auto -o ControlPath=/var/tmp/installaccess-201607251641FNK/_ssh_%h -o ControlPersist=yes 10.209.192.171 "LC_ALL=C; LANG=C; export LC_ALL LANG; /sbin/ip addr flush eth2 >/dev/null 2>&1; /sbin/ifconfig eth2 down >/dev/null 2>&1" 2>/dev/null
0 17:08:18 CPI WARNING V-9-20-1051 Interrupt Received--installaccess terminated


text:
Q: regular expression match a string 'xxx(yyy) (zzz(qqq))' or 'xxx(yyy)' I want to match string below,
str1: xxx(yyy) (zzz(qqq))
str2: xxx(yyy)

I write a regular expression  which can only match str1:
>>> s = re.compile(r'([^\(]+)\((.+)\)\s*\(([^\(]+)\((.+)\)\)')
>>> m = s.match('xxx(yyy) (zzz(qqq))')
>>> for i in m.groups(): print i
...
xxx
yyy
zzz
qqq
>>> m = s.match('xxx(yyy)')
>>> for i in m.groups(): print i
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'

How can I solve this?

A: The error AttributeError: 'NoneType' object has no attribute 'groups' means that you can't apply the groups method to nothing.
match returns None if the string does not match the pattern
Your regex is incorrect, the third and fourth group may not exist. It's best to look for any strings within parenthesis or not.
Also match only looks for the matching pattern at beginning of the line.
You could use findall but it would return a list, so finditer seems more appropriate
This is the corrected regex : s = re.compile(r'(?:\(?([^\(\)]+)\(?([^\(\)]+)\)\)?\s*)')
However, using finditer you just need to look for a simpler pattern. So the regex below is different:
import re

s=re.compile(r'\(?([^\s\(\)]+)\)?')

string1='aa (bbbb) (cc (dddd) )'
string2='aa (bbbb) '

for string in [string1,string2]:
    print string
    m = s.finditer(string)
    for i in m: print i.group(1)


text:
Q: Faint line visible on non-retina screens I'm not even sure this is in the correct category but I'll ask and perhaps someone will guide me if not.
See the attached image. This is a tabbed navigation structure built with an unordered list and a single div to conceal the bottom border of the active tab. There is faint bottom border visible on the active tab only on non-retina screens. It can be any non-retina screen (not just mine). I can even see it when viewed at BrowserStack on a non-retina screen.
The container for the structure has a bottom border of 1px solid #ccc and the active tab uses an absolutely positioned div of 4px solid #fff to cover the line at the bottom of the active tab. This works perfectly with the exception of the faint line on non-retina screens.
I've Googled and searched StackOverflow with no luck. Any thoughts, ideas or suggestions would be appreciated!

A: I was able to fix this by adding backface-visibility: hidden; to the bottom border. Thanks for the feedback!


text:
Q: Cordova: I can't get the location of fakeGPS in cordova 3.1 using android In the previous version of the project that I'm working we were using worklight 5.0.6 (cordova 2.3) and we were able to get the gps position using fakeGPS (https://play.google.com/store/apps/details?id=com.lexa.fakegps&hl=pt_BR), but now we are using worklight 6.1 (cordova 3.1) and the gps position returned to us using fakeGPS is null.
I tried to get the source code of cordova in this link (http://archive.apache.org/dist/cordova/) but seems that some files are missing. In the plugins part I don't know exactly what was the version of the geolocation plugin used in the 3.1 and 2.3 version.
Someone know what are happening or could send to me the source code of the cordova 3.1 and 2.3 to compare the difference between these versions?

A: You can also try using the Mobile Browser Simulator; the geolocation widget there and the scenario editor can be used to simulate fake GPS locations for hybrid applications.


text:
Q: Firewall rules for ssh, ftp and webapps I'm running a small cluster with Centos 7 and want the following rules for firewall.

*

*Have ssh access from anywhere (i'm going to further configure that from /etc/ssh/sshd_config)

*Have ftp access to an ftp server

*Have access to a webapp running at :7180

*Have full access from some servers

*Log all events

*Prevent DDoS

I have written the following script but don't know if it's the optimal way. Any suggestions?

`#! /bin/bash
IPTABLES=/usr/sbin/iptables
  MY_NET=server1.sample.com,server2.sample.com,server3.sample.com
  MY_IP=123.456.789.101
  FTP=ftp.sample.com
$IPTABLES -F
$IPTABLES -I INPUT 1 -j LOG
  $IPTABLES -I OUTPUT 1 -j LOG
$IPTABLES -P INPUT DROP
  $IPTABLES -P OUTPUT DROP
$IPTABLES -A INPUT -p tcp -s $MY_NET,$MY_IP -j ACCEPT $IPTABLES -A OUTPUT -p tcp -d $MY_NET,$MY_IP -j ACCEPT
$FTP -m multiport --dports 20,21 -j ACCEPT $IPTABLES -A OUTPUT -p tcp -d $FTP -m multiport --dports 20,21 -j ACCEPT
$IPTABLES -A INPUT -p tcp -m multiport --dports 22,7180 -m state --state NEW,ESTABLISHED -j ACCEPT
  $IPTABLES -A OUTPUT -p tcp -m multiport --sports 22,7180 -m state --state ESTABLISHED -j ACCEPT
$IPTABLES -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
$IPTABLES -A INPUT -p tcp --dport 22,8080,7180 -m limit --limit
  25/minute --limit-burst 100 -j ACCEPT`

A: *

*The best solution for firewall is forbid all and then make a holes.

*Make one chain for protocol

*Make rules structured not linear, it help to be faster in big load.

*For LOG use with limit too, beware full log disk partition.

Some example which not cover your example, but show way howto
$IPTABLES -n ftp
$IPTABLES -n ssh
$IPTABLES -n webapp
$IPTABLES -n icmp
$IPTABLES -P INPUT DROP

#first log (i think better log only good or only bad)
$IPTABLES -A INPUT -m limit --limit 25/minute -j LOG
#decide to which chain goto...
$IPTABLES -A INPUT -p tcp --port 7180 -j webapp
$IPTABLES -A INPUT -p icmp -j icmp
$IPTABLES -A INPUT -p tcp --dport 22 -j ssh

#fill chain specific for protocol (port was matched before)
$IPTABLES -A webapp -m state --state NEW,ESTABLISHED -j ACCEPT
$IPTABLES -A icmp -p icmp --icmp-type echo-reply -j ACCEPT
#ssh accept packet to all destionation.. it is quicker then state comparsion
$IPTABLES -A ssh -j ACCEPT

#for output make other chain than input
$IPTABLES -N ssh_out
$IPTABLES -A OUTPUT -p tcp --sport 22 -j ACCEPT
$IPTABLES -A ssh_out -m state --state ESTABLISHED -j ssh_out
$IPTABLES -A ssh_out -j DROP #or make drop policy on output...

And so one...


text:
Q: Webview is not detected by appium webdriver on real IOS device I am running the tests on a hybrid app. My configuration is: Xcode version set to '9.2' (tools v9.3.0.0.1.1521514116), Appium 1.7.2, and the capabilities are:
capabilities.setCapability("xcodeConfigFile", "/path/to/xcodeConfigFile.xcconfig");
capabilities.setCapability("newCommandTimeout", 600);
capabilities.setCapability("nativeWebTap", "true");
capabilities.setCapability("noReset", "true");
capabilities.setCapability("fullReset", "false");
capabilities.setCapability("chromedriverExecutable", chromeDriver);
capabilities.setCapability("bootstrapPath", "/Upath/to/appium-xcuitest-driver/WebDriverAgent");
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, deviceName);
capabilities.setCapability("udid", UDID);
capabilities.setCapability("platformVersion", "11.2.6");
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, platform);
capabilities.setCapability("app", iOSAppPath);
capabilities.setCapability("automationName" ,  "XCUITest");

If I use capabilities.setCapability("autoWebview", "true") the tests is stuck at driver initialization, as it does not find any webview.
webDriver.getContextHandles() returns only NATIVE_APP on a real device, but also returns WEBVIEW_2908.1 on the simulator.
The external libraries used are:
SaxonLiaison.jar
commons-lang3-3.1.jar
commons-validator-1.4.0.jar
guice-3.0.jar
java-client-4.1.2.jar
jcommander.jar
jxl-2.6.10.jar
log4j-1.2.16.jar
poi-3.10.1-20140818.jar
reportng-1.1.4.jar
saxon-8.7.jar
selenium-server-standalone-2.53.0.jar
smslib-3.5.4.jar
testng-6.8.21.jar
velocity-dep-1.4.jar
xslt.jar

I am unable to update to newer version because I get errors for some functionalities implemented in java-client-4.1.2.jar (for example webDriver.tap() )
As found on appium.io and other questions, I installed everything I could, like: ios-webkit-debug-proxy, libimobiledevice and ios-deploy
Edit: before I did not know that I had to manually run ios_webkit_debug_proxy, so I ran it three times with three different ports: 9221, 9222 and 9223, I received the same result and this is the only thing that was logged in the terminal:
ios_webkit_debug_proxy -c <udid>:9222
Connected :9222 to iPhone X (<udid>)

A: I found the solution to my issue here: https://github.com/appium/appium/issues/7676
I just had to start ios_webkit_debug_proxy and start appium server with a parameter that points to the ios_webkit_debug_proxy port
ios_webkit_debug_proxy -c UDID:27753 -d

appium --no-reset --webkit-debug-proxy-port 27753


text:
Q: How do I access descendants from a different branch in the same viewModel? I am currently working on a website spa application and attempting to use knockout.js. it's on an mvc platform with and a dbdatacontroller api using upshot for data and javascript view models. I have a complex view model and am running into difficulty, mainly due to being new to knockout. My biggest problem seems to be in accessing the observables. The database is organized thusly:
    function AdvanceSearch(data) {
var self = this;
self.AdvanceSearchID = ko.observable(data.AdvanceSearchID);
self.FieldTypeEnum = ko.observable(data.FieldTypeEnum);
self.AnswerType = ko.observable(data.AnswerType);
self.UserValues = ko.observableArray(ko.utils.arrayMap(data.UserValues, function (item) {
    return new UserValue(item);
}));
upshot.addEntityProperties(self, "AdvanceSearch:#A.Lib.Repository");
};

function UserValue(data) {
var self = this;

self.UserProfileID = ko.observable(data.UserProfileID);
self.LoginID = ko.observable(data.LoginID);
self.AdvanceSearchID = ko.observable(data.AdvanceSearchID);
self.FieldValueCount = ko.observable(data.FieldValueCount);
self.FieldValueText = ko.observable(data.FieldValueText);
    upshot.addEntityProperties(self, "UserValue:#A.Lib.Repository");
});
};

function AnswerType(data) {
var self = this;
self.AnswerTypeID = ko.observable(data.AnswerTypeID);
self.AnswerTypeText = ko.observable(data.AnswerTypeText);
self.Answers = ko.observableArray(ko.utils.arrayMap(data.Answers, function (item) {
    return new Answer(item);
}));
self.AnswerSliders = ko.observableArray(ko.utils.arrayMap(data.AnswerSliders, function (item) {
    return new AnswerSlider(item);
}));
upshot.addEntityProperties(self, "AnswerType:#A.Lib.Repository");
}

function Answer(data) {
var self = this;
self.AnswerTypeID = ko.observable(data.AnswerTypeID);
self.AnswerEnum = ko.observable(data.AnswerEnum);
self.AnswerText = ko.observable(data.AnswerText);
upshot.addEntityProperties(self, "Answer:#A.Lib.Repository");
}

function AnswerSlider(data) {
var self = this;
self.SliderID = ko.observable(data.SliderID);
self.AnswerTypeID = ko.observable(data.AnswerTypeID);
self.SliderType = ko.observable(data.SliderType);
self.Seed = ko.observable(data.Seed);
upshot.addEntityProperties(self, "AnswerSlider:#A.Lib.Repository");
}

And my view model is just this:
function ASViewModel() {
// Private
var self = this;
var dataSourceOptions = {
    providerParameters: {
        url: "/api/Dating",
        operationName: "GetDatingProfile"
    },
    entityType: "AdvanceSearch:#A.Lib.Repository",
    bufferChanges: false,
    mapping: AdvanceSearch
};

// Public Properties
self.dataSource = new upshot.RemoteDataSource(dataSourceOptions)
                            .refresh();
self.AdvanceSearchs = self.dataSource.getEntities();
}

So my markup is something like

       <select data-bind="options: AnswerType().Answers, optionsText: 'AnswerText', optionsValue: 'AnswerEnum', optionsCaption: 'Not Specified', value: UserValues().FieldValueText"></select>

        <input type="text" class="multilinetext" data-bind="attr: { id: 'value_'+AdvanceSearchID()}, value: UserValues().FieldValueText" />

So basically, no matter what I do, I cannot seem to access the values of the items. Anywhere I have accessed the one branch, ie. AdvanceSearch().AnswerType().Answers, trying to get $parents[1].UserValues[].FieldValueText seems always to be undefined. Like I said, I'm new to knockout, so I'm probably just missing something. Or should I be using multiple viewmodels or something similar? (And if so, how would I do that?)
Thanks.

A: Your:

needs to be:

Note the pluralisation of AdvanceSearch to AdvanceSearchs
Edit:
Also, UserValues is an Observable Array, hence you cannot access UserValues().FieldValueText.
Note sure exactly what your expected output is, but this displays an input per UserValue:

    <input type="text" class="multilinetext" data-bind="attr: { id: 'value_'+UserProfileID()}, value: FieldValueText" />

NB: I've changed, the ID of the input to something else to avoid duplicate IDs -- this assumes UserProfileID is unique per UserValue
Further,
May I refer you to the documentation for Knockouts options-binding. Your data-bind options for a select element are:
options: - This is the list of options to bind the select element to
optionsText: For each item in the list, the property to display in the select element
optionsCaption: The text for the first/'dummy' item of the select element
value: this should be an observable and is bound to the current selection of the select element
The value binding is a very handy feature of Knockout. It removes the need to worry about IDs -- and thus optionsValue -- as you have access to the entire selected object.
So your select binding can look like:
<select data-bind="options: AnswerType().Answers,
                   optionsText: 'AnswerText',
                @* optionsValue: 'AnswerEnum', *@
                   optionsCaption: 'Not Specified',
                   value: selectedAnswer"></select>

Assuming you've added an observable selectedAnswer to your viewmodel.

A: Based on your comments, I think I now know what you're trying to do. I am going to abstract it so that it is easier to follow as your ViewModel and Objects are very complex and not easy to understand without explanation.
If you have object types, Book and Author with constructors:
function Book(data) {
    this.ISBN = ko.observable( data.ISBN );
    this.Title = ko.observable( data.Title );
    this.AuthorID = ko.observable( data.AuthorID );
    /* other properties */
}

function Author(data) {
    this.AuthorID = ko.observable( data.AuthorID );
    this.Name = ko.observable( data.Name );
    /* other properties */
}

To select a Book from a select box and have a input display bound to the Authors name, you will need the viewmodel:
var vm = {};
vm.books = ko.observableArray( /* initial data */ );
vm.authors = ko.observableArray( /* initial data */ );
vm.selectedBook = ko.observable(null);
vm.selectedBooksAuthor = ko.computed( function() {
    var authors = vm.authors(),
        selectedBook = vm.selectedBook();
    if( !selectedBook ) return null; // cannot get .AuthorID() if selectedBook == null
    var id = selectedBook.AuthorID();
    for( var a in authors ) {
        if( authors[a].AuthorID() == id )
            return authors[a];
    }
})

And your HTML:
<select data-bind="options: books,
                   optionsText: 'Title',
                   optionsCaption: 'Select a book...',
                   value: selectedBook"></select>

<input type="text" data-bind="value: Name" />

Please note, this can get pretty inefficient over large sets of data -- look into using a better search algorithm (rather than the 'linear' used here) for your computed observable i.e. selectedBooksAuthor
EDIT:
Please see this fiddle for a working demonstration.


text:
Q: Can't reproduce payment instrument token creation action from sandbox with "Invalid profile owner" error I want to create a token for card with given API call https://developer.cybersource.com/api-reference-assets/index.html#token-management_payment-instrument_create-a-payment-instrument as CyberSource's Intro video suggests. With default credentials that sandbox provide(testrest merchant) everything goes fine but when I use my credentials generated in https://ebc2test.cybersource.com I am always getting next error(I don't edit initial request that sandbox provides; with this exact request and default credentials CyberSource generates token and successfully returns it to API test page)
{
    "errors": [
        {
            "type": "forbidden",
            "message": "Invalid profile owner"
        }
    ]
}

I have tried to use merchant API shared key/secret as well as user-specific credentials from the same merchant profile.
What I did wrong(may be I need to change smth in merchant profile) and what I need to do to make it work ?

A: We had the same problem. It was related to the profileId. The hard coded profile id isn't valid. You need to get your own profile id from customer support. From what I gather the profile id is used to reference your specific tokens. It's a discount double check if you will that the tokens you are inputting are connected to your account.

A: The profile id within a REST API context is assigned by CyberSource within the Gateway account and with TMS is a specific id for your TOKEN MANAGEMENT collection.


text:
Q: Airflow PostgresOperator Safety -- execution_timeout not respected? How to kill process in DB if it's taking too long? Working on getting Airflow implemented at my company but need to perform some safety checks prior to connecting to our prod dbs.
There is concern about stupid SQL being deployed and eating up too many resources. My thought was that an execution_timeout setting on a PostgresOp task would:

*

*Fail the task

*Kill the query process in the db

I have found neither to be true.
Code:
with DAG(
    # Arguments applied to instantiate this DAG. Update your values here
    # All parameters visible in airflow.models.dag
    dag_id=DAG_ID,
    default_args=DEFAULT_ARGS,
    dagrun_timeout=timedelta(minutes=20),
    start_date=days_ago(1),
    schedule_interval=None,
    tags=['admin'],
    max_active_runs=1
) as dag:

    kill_test = PostgresOperator(
        task_id="kill_test",
        execution_timeout=timedelta(seconds=10),
        postgres_conn_id="usa_db",
        sql="""
SET application_name to airflow_test;
<SELECT... intentionally long running query> ;
        """)

Airflow does not fail the task after the timeout.
Even when I manually fail the task in the UI, it does not kill the query in the Postgres db.
What is the deal here? Is there any way to put in safety measures to hard kill an Airflow initiated Postgres query in the db?
I'm not posting here, but I have checked:

*

*Airflow UI shows task instance duration way over execution timeout

*pg_stat activity to confirm query is running way over execution timeout

A: I guess you are looking for this parameter runtime_parameters={'statement_timeout': '180000ms'}.(airflow example)
I don't know in which version this was added but if you update your apache-airflow-providers-postgres module to the last version you can use the mentioned parameter.


text:
Q: How to install an updated version of PEAR / PHPUnit on Ubuntu? Most tutorials online show how to install PEAR by doing this:
sudo apt-get install php-pear

This installs version 1.6.1. It works great because it's super easy! My problem is that I want to install PHPUnit and it requires PEAR version 1.8.1 so my install of PHPUnit failed. So how do I install a newer version of PEAR on Ubuntu?

A: Last versions of PhpUnit require ez/zeta components & symfony's YAML lib
sudo apt-get install php-pear
sudo pear channel-update pear.php.net
sudo pear upgrade-all
sudo pear channel-discover pear.phpunit.de
sudo pear channel-discover components.ez.no
sudo pear channel-discover pear.symfony-project.com
sudo pear install -a phpunit/PHPUnit

See the last updated installation tutorial here

A: First, install PEAR.
sudo apt-get install php-pear

Next, tell PEAR to update its own channel.
sudo pear channel-update pear.php.net

Then, tell PEAR to upgrade itself to the newest version.
sudo pear upgrade-all

You should now have the newest version of PEAR installed.
To install PHPUnit, let PEAR know where to find PHPUnit.
sudo pear channel-discover pear.phpunit.de

Then install PHPUnit. (the -a makes sure all dependency packages are also installed)
sudo pear install -a phpunit/PHPUnit

Update:
According to the latest PHPUnit installation documentation, you can install PHPUnit with the following commands (make sure you have updated PEAR first):
sudo pear config-set auto_discover 1
sudo pear install pear.phpunit.de/PHPUnit

A: If installation using above command failed, You might need to install Net_URL2-0.3.1 and then HTTP_Request2-2.0.0RC1 before installation of PHPUnit on Ubuntu.
Find the latest version of the above packages and install them.
Example:
sudo apt-get install curl
sudo pear install pear/Net_URL2-0.3.1
sudo pear install pear/HTTP_Request2-2.0.0RC1
sudo pear install -a phpunit/PHPUnit


text:
Q: C++ multiple line input from keyboard For an assignment of mine, we're suppose to take in several lines of input from the keyboard. For example:
Please enter your name:  (this is static. Always 1 input)
Justin
Please enter the names:  (this can be any number of inputs, smallest being 1)
Joe
Bob
John
Jackson
In the end, I want to compare the named entered at the beginning with all of the names entered in after. I tried using getline and cin, but that seems to only work if I know the exact number of names I expect to be entered. Can anyone guide me in the right direction please. Thank you

A: Try this
void read_lines( std::istream& in, std::list< std::string >& list ) {
    while( true ) {
        std::string line = "";
        std::getline( in, line );
        if( line != "" ) {
            list.push_back( line );
        } else {
            break;
        }
    }
}

A: You should have added some rough code showing your efforts on doing the assignment.
However, I will provide you with some initial naive code (please read the comments inside!):
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    string name, temp;
    vector<string> names; // this is just one of the possible container that you can use
    bool result = false; // flag used to store the result of the matching operation (default: false)

    // first we ask the user to enter his/her name
    cout << "Please enter your name:" <<endl;
    cin >> name;

    // then we need something a little bit more complicated to look for variable number of names
    cout << "Please enter the names:" <<endl;
    while(cin)
    {
        cin >> temp;
        names.push_back(temp);
    }

    // This for-loop is used to go through all the input names for good-match with the user name
    for( int i = 0; i < names.size(); i++ )
    {
        temp = names.front();
        if (name == temp) result = true; // change the flag variable only in case of match
    }

    cout << "Valid match: " << (result?"yes":"no"); // ternary operator
}

You did not provide in your question enough details.. so the above code may not fully fit your requirements!


text:
Q: IBM Watson Analytics EXPLORE/PREDICT Service Public APIs? I have just started to learn the Watson analytics from IBM Watson Analytics I have uploaded a csv file and used EXPLORE, PREDICT features. Is there anyway can I use these features using REST API? in Java. Is there any REST API available for this.? I don't know how to start exactly.

A: The REST APIs for Watson Analytics use OAuth2 for Authentication once you have a token you can upload data and navigate the folders.  There isn't a way to create Explorations and Predictions currently.  Below is a code snip from the Java sample showing how you would get the user's profile information in Java.
    String apiURL = "https://" + WATSON_ANALYTICS_API_URL + WATSON_ANALYTICS_API_BASE_PATH + "/accounts/v1/me";
    HttpGet apiRequest = new HttpGet(apiURL);
    apiRequest.addHeader("X-IBM-Client-Id","client_id");
    apiRequest.addHeader("X-IBM-Client-Secret", "client_secret");
    apiRequest.addHeader("Authorization", "Bearer " + ACCESS_TOKENS);
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse apiResponse = httpClient.execute( apiRequest );
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        apiResponse.getEntity().writeTo( stream );
        response.getWriter().write(stream.toString());
        stream.close();
    } catch (Exception e) {
        System.err.println(e.getLocalizedMessage());
    }


text:
Q: How can I make TextField always placed right above the keyboard? I want to make TextField always placed right above the Keyboard when it's clicked. The code does not work as I expect and the TextField is dependent on its position, not the keyboard's(it only works when TextField is below the keyboard)
HStack(spacing: 10) {
    TextField()
}
.onAppear {
    NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { (noti) in
    let value = noti.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
    self.height = value.height
    self.clickedOut = false
    }
    NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { (noti) in
    self.height = 0
    self.showTextField = false
    }
}

if self.showTextField == true {
    TextField()
    .background(Color("InvertPrimaryFontColor"))
    .offset(y: (-self.height/2) - 12)
    .padding(.leading, -10)
    .animation(.spring())
}

A: You can use onEditingChanged of TextField for solving the issue:
struct ContentView: View {

    var body: some View {

        TextFieldView()

    }

}

struct TextFieldView: View {

    @State private var email: String = String()
    @State private var textFieldIsUnderEdit: Bool = Bool()

    var body: some View {

        VStack {

            if textFieldIsUnderEdit { Spacer() }

            TextField("Enter your email address Here...", text: $email, onEditingChanged: { _ in textFieldIsUnderEdit.toggle() })
                .keyboardType(.emailAddress)

            Divider()

        }
        .padding(.horizontal)
        .animation(nil)

    }

}


text:
Q: Sending Data From Delegate View To Delegated View [Objective-C] So I am trying to learn how to send data from one view controller to another.
My code thus far takes the data entered from one VC (DelegateVC) and displays it in a label on another VC(ViewController).
Here the delegate is ViewController and the delegated is DelegateVC.
===========================================================================
Main Question
But what if I want to pass the data of the label from ViewController to DelegateVC? How can I accomplish this? I tried engineering the same concept of delegates but with the DelegateVC as the delegate of ViewController. Not sure if this is the write approach.
TL;DR:
In VC, if I hit Next View, I go to DelegateVC and enter "test", it will show up in VC's receiving label as "test".
Now the next time I hit Next View, I want the existing label's value to show up in the TextField of DelegateVC. Instead of a blank TextField, there will be the value "test".
===========================================================================
Let's say I have a Main.storyboard like so:

I have a ViewController.h file as:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController

@end

ViewController.m:
#import "ViewController.h"
#import "DelegatedVC.h"

@interface ViewController () <MainVCDelegate>
@property (strong, nonatomic) IBOutlet UILabel *receivingLabel;
- (IBAction)nextView:(id)sender;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)nextView:(id)sender {

}

-(void) sendBackData:(DelegatedVC *)delegatedVC :(NSString *)textField {
    [delegatedVC dismissViewControllerAnimated:YES completion:nil];
    self.receivingLabel.text = textField;
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    DelegatedVC *secondVC = segue.destinationViewController;
    secondVC.delegate = self;
}
@end

DelegateVC.h:
#import <UIKit/UIKit.h>
@protocol MainVCDelegate;

@interface DelegatedVC : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *sendDataTF;
- (IBAction)sendData:(id)sender;
@property (weak, nonatomic) id<MainVCDelegate> delegate;
@end

@protocol MainVCDelegate <NSObject>
-(void) sendBackData: (DelegatedVC *) delegatedVC : (NSString *) textField;
@end

DelegateVC.m:
#import "DelegatedVC.h"
@protocol MainVCDelegate;

@interface DelegatedVC ()

@end

@implementation DelegatedVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)sendData:(id)sender {
    [self.delegate sendBackData: self : _sendDataTF.text];
}
@end

A:
But what if I want to pass the data of the label from ViewController
  to DelegateVC? How can I accomplish this?

So you're doing the delegation right as I can see in your code. Back to your main question, you just need to declare a public NSString object in your DelegateVC.h, and then access that and pass the data to that from your ViewController's prepareForSegue.
Next step, in your DelegateVC.m, get your NSString object's value and pass it to your UITextField.
Let me know if this helps :)

A: A delegate allows one object to send messages to another object when an event happens.
In your case to pass data of label from ViewController to DelegateVC, you do not need to use delegate. But since you want to update receivingLabel when changing happens on sendDataTF textfield , in this case you need a delegate and I think you have done it well.
Solution: You need to declare a property in DelegateVC to store passing string from ViewController and set that text in sendDataTF on viewDidLoad.
Declare a property in DelegateVC.h:
@interface DelegatedVC : UIViewController

@property (weak, nonatomic) id<MainVCDelegate> delegate;
@property (strong, nonatomic) NSString *labelString;

@property (strong, nonatomic) IBOutlet UITextField *sendDataTF;

- (IBAction)sendData:(id)sender;

@end

Pass receivingLabel text in ViewController.m:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
   DelegatedVC *secondVC = segue.destinationViewController;
   secondVC.delegate = self;
   secondVC.labelString = self.receivingLabel.text;
}

Set labelString in DelegateVC.m:
- (void)viewDidLoad {
  [super viewDidLoad];
  self.sendDataTF.text = self.labelString;
}

Hope it will work.

A: Here is proper working code you can have a look at :
DelegateVc.h File with Label and button
#import <UIKit/UIKit.h>
#import "DelegatedVC.h"

@interface DelegateVC : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *ReceiveLabel;
@property (weak, nonatomic) IBOutlet UIButton *NextView;
@property (strong, nonatomic) NSString *TextFeildText;

DelegateVC.m File With segues
-(void)viewWillAppear:(BOOL)animated{
    _ReceiveLabel.text = _TextFeildText;
}
- (IBAction)NextViewBtnAction:(id)sender {
    [self performSegueWithIdentifier:@"ToDelegated" sender:sender];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"ToDelegated"])
    {
        // Get reference to the destination view controller
        DelegatedVC *vc = [segue destinationViewController];
        vc.LabelText = _ReceiveLabel.text;

        // Pass any objects to the view controller here, like...

    }
}

DelagatedVc.h with textfield
#import <UIKit/UIKit.h>
#import "DelegateVC.h"

@interface DelegatedVC : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *RCTextField;
@property (weak, nonatomic) IBOutlet UIButton *SenddataBtn;
@property (strong, nonatomic) NSString *LabelText;
@end

DelagatedVc.m with Segue
-(void)viewWillAppear:(BOOL)animated{
    _RCTextField.text = _LabelText;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)SendDataBtnAction:(id)sender {
    [self performSegueWithIdentifier:@"ToDelegate" sender:sender];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"ToDelegate"])
    {
        // Get reference to the destination view controller
        DelegateVC *vc = [segue destinationViewController];
        // Pass any objects to the view controller here, like...
        vc.TextFeildText = _RCTextField.text;

    }
}

My storyBoard Outlook


text:
Q: Is there any injective homomorphism (i.e. monomorphism) from a non-cyclic group of order $4$ to $\mathbb{Z}_8$? The only such possible group is $V$ (up to isomorphism). If $\phi$ be such an into homomorphism, then $o(\phi(V))=4$ and $\phi(V)$ being a subgroup of $\mathbb{Z}_8$, it must be cyclic with a generator of order $4$. But, $V$ has not element of order $4$. A contradiction.
Does this work?

A: That argument works. Given a monomorphism $f:G\to H$ between groups $G,H$, then $G$ is isomorphic to $f(G)$, and the two must therefore have the same number of elements of any given order.
Alternatively, there is only one element of order $2$ in $\Bbb Z_8$, while there are three in $V$.


text:
Q: Prove that the probabilty of a certain event is either zero or one. Let $(A_n)$ be events in $\mathcal F$ and let $\mathcal A$ be the smallest $\sigma$-filed containing each of these events. If $B$ is an event in $\mathcal A$ with the property that, for any integers $i_1,...,i_k$ the events $B$ and $A_{i_1} \cap...\cap A_{i_k}$ are independent, prove that $P(B)$ is either $0$ or $1$.
I think it may need using 0-1 law. But I don't know how to use it.

A: No, there is no need of such a strong weapon. This is much simpler... At least if it is assumed that we have a finite collection of sets. But saying that "Let $(A_n)$ be events in $\mathcal F$..." sort of implies that we have that.
Consider the following figure depicting some sets and all the "atoms". These sets and their arbitrary intersections can be formed by a union of the atoms.

For instance $A_2\cap A_3$ is the union of the black atom, the purple atom, and the white atom.
Note that any intersection of the sets equal a union of some atoms. Also, note that $B$ is, again, a union of some atoms.
The OP's statement says that if a sum of some atoms is independent from all the unions of the atoms then the probability of the former union is ether zero or one.
Considering that $B$ is a union of atoms then the statement above claims that $B$ is independent from itself... So???


text:
Q: Constructer in Javascript does not return correct value that is passed by prototype function I have written a code with constructer Vector(it has two parameters) and I wish to pass different set of parameters through a prototype function and want to sum up the values for both set of parameters.
But I am facing a issue with printing final Vector.
function Vector(x, y) {

    this.x = x;

    this.y = y;

    console.log(x, y);//initially this prints (3,3)

    return (x, y);
}

Vector.prototype.plus = function (a, b) {

    this.x = this.x + a;
    this.y = this.y + b;
    console.log(this.x, this.y);// After passing (1,9) it prints (4,12)but
     return (this.x, this.y);   //after returning (this.x, this.y) it
                                //prints only Y coordinate as 12
}

var type_vector = new Vector(3, 3);

console.log(type_vector.plus(1, 9));

Output: (3,3),(4,12),12

A: I believe you're from a python background, for there (x, y) is returned as a tuple. In JS if you return (x, y); it will be the value at the closing parenthesis (y, in this case). You must use an object or an array for your objective.
try this on console:
var a = (3, 4, 5, 6);
console.log(a);

A: Well, in JavaScript if you want to return an array you can use the [] notation.
Diff. this with you version :
function Vector(x, y) {
  this.x = x;
  this.y = y;
  console.log(x, y);
  return this;
}
Vector.prototype.plus = function(a, b) {
  this.x = this.x + a;
  this.y = this.y + b;
  console.log(this.x, this.y);
  return [this.x, this.y];
};
var type_vector = new Vector(3, 3);
console.log(type_vector.plus(1, 9));


text:
Q: Lots of BluetoothHeadsetProxy.exe processes I have a weird problem with my Win7 Pro 64: after booting it keeps spawning new BluetoothHeadsetProxy processes. I have 400 of them now and it keeps counting of course slowing down the system enormously. Any ideas why?

A: If you have Skype installed. It's a bug between Bluetooth Software and Skype.
You can fix that by disable bluetooth support in Skype.
Go to Tools -> Options -> Advanced and then on the link at the bottom that says 'Manage other programs' access to Skype. Remove all bluetooth software there and restart Skype.
When Skype asks you to connect with bluetooth software, click on Deny.


text:
Q: Chrome Render Bug while resizing Table, header background stick on top of another div I have two different panels those are resizable by dragging.
All things are working fine in other browsers but in chrome somehow the background of header stick to the parent div. it seems the new rendering problem of Chrome with skia graphics.
Please have a look on screenshot or video link i attached, you will find that glitch on video,help me out to finding the workaround for this.
And, I tried to compress this problem by applying background-color to table,tbodyand wrapper div but still sometimes it behaves the same.
If this is not the right place to put this question please suggest me where? Thanks.

A: Regarding the fact that the glitch occurs outside the table. I would try overflow: hiddenon the table wrapper.


text:
Q: Find path from A to B which length ≈ L I have an undirected weighted graph.
I want to find the path from A to B which length is as close as possible to a specific value "L".
To do that, I have been doing a DFS to check all the possible paths... When L is relatively small, it's ok. But when I ask for a bigger L, it takes too much time to complete. I added some criteria to stop searching useless paths but that cannot solve the problem.
So I was wondering how to do what I am searching for. Is DFS the only solution ? I thought about genetic algorithms but I don't know if it would work.
Thank you !


text:
Q: I have a working script for login time, but if the user isn't logged on I get an error I have a working script that tells how long as user has been logged on . But it the user isn't logged on it will say they are logged off but it will give me an error for one of the tests in the middle of the script.
Im trying to figure out how to skip these lines if the user isn't online
if [ $eMin -lt 0 ]
     then
     eMin=$(expr $eMin + 60 )
    eHr=$(expr $eHr - 1 )
    fi

This is the full script for context
while [ -z "$1" ]
do
echo -n "Please enter valid id: "
read var1
set $var1 $1
# Break the loop
if [ -n "$1" ]
then
break
fi
done

# Check if the user is a valid user
if id "$1" >/dev/null 2>1;
# If so, then check if he if he is currently logged on and set on/not on as variable
then
# Set full name variable based on matching ID
fullname=$(grep "$1" /etc/passwd | cut -d ':' -f5 | sort -k 2 | tr ",,:" " " | awk '{print $2,$1}')
# Get Current  Hours and Minutes
nowHr=$(date | cut -c 12,13)
nowMin=$(date | cut -c 15,16)
onHr=$(who |grep "$1" | cut -c 34,35)
onMin=$(who |grep "$1" |cut -c 37,38)
# Hours minutes spent logged on
eHr=$(expr $nowHr - $onHr )
eMin=$(expr $nowMin - $onMin )

if [ $eMin -lt 0 ]
then
eMin=$(expr $eMin + 60 )
eHr=$(expr $eHr - 1 )
fi

# Test and display user name and if curretnly logged on
# Exit with code of 0 if success and 1 if fail
who -u |grep -q "$1" || test && echo "$fullname is logged on for $eHr hour(s) and $eMin minutes(s)." &&  exit 0 || echo "$fullname is not logged on" && exit 1
# Displays if invalid id is entered
else
echo "The user you entered, $1 is not a valid user on this system"
# Exit with code of 2
fi
exit 2

The error message is
expr: syntax error
expr: syntax error
/timeOn: line 38: [: -lt: unary operator expected
John Doe is not logged on

A: If the user is not logged on, you can't get any output for "who | grep $1 | cut -c 37,38".  Hence, you can't compare an empty string to an integer.
That's why you got the syntax error.
Generally speaking, it's worth to use "bash -x script" for debugging.
In this script, you can detect if the user is logged on in the first step.


text:
Q: Pulling property from Redux state returns undefined, although it definitely has a value I've been making a small app to learn how to use React and Redux this week, and it's been going quite well but this problem has left me scratching my head.
Here is what my reducers look like.
const initialiseState = {
  items: {},
  total: 0
}

function basket(state = initialiseState, action) {

  switch (action.type) {
    case ADD_TO_BASKET:
      if(action.sku){
        const quantity = state.items[action.sku] || 0;
        return {
          items: {...state.items, [action.sku]: quantity + 1},
          total:  parseInt(state.total,10) + parseInt(action.price, 10)
        };
      return state
    }

    case REMOVE_FROM_BASKET:
      if(action.sku) {

        // const {[action.sku]: quantity, ...items } = state.items;

        const quantity  = state.items[action.sku];
        const { items } = state;
        if(quantity && quantity > 1) {
          const x = {
            items: {...state, [action.sku]: quantity - 1},
            total: parseInt(state.total,10) - parseInt(action.price, 10)
          };
          console.log(x)
          return;
        } else {
          return state;
        }
      } else {
        return state;
      }
    default:
      return state;
  }
}

I have no problems with ADD_TO_BASKET however when I try and remove an item from the basket quantity is coming back as undefined. I placed a debugger right where the code pulls out that value, and when I run state.items[action.sku] in the console it's bringing back the value.
I've just left debugging code in, but you should get the gist of what I'm trying to do.
I'm unsure of what other parts of my code you'd need to see so I can update the question if needs be.
EDIT: Here is the original reducers code before I started debugging, and also the actions file.
import { combineReducers } from 'redux'
import {
  ADD_TO_BASKET,
  REMOVE_FROM_BASKET
} from './actions'

const initialiseState = {
  items: {},
  total: 0
}

function basket(state = initialiseState, action) {

  switch (action.type) {
    case ADD_TO_BASKET:
      if(action.sku){
        const quantity = state.items[action.sku] || 0;
        return {
          items: {...state.items, [action.sku]: quantity + 1},
          total:  parseInt(state.total,10) + parseInt(action.price, 10)
        };
      return state
    }

    case REMOVE_FROM_BASKET:
      if(action.sku) {
        const {[action.sku]: quantity, ...items } = state.items;
        if(quantity && quantity > 1) {
          return {
            items: {...state, [action.sku]: quantity - 1},
            total: parseInt(state.total,10) - parseInt(action.price, 10)
          };
        } else {
          return state;
        }
      } else {
        return state;
      }
    default:
      return state;
  }
}

const coffeeApp = combineReducers({
  basket,
})

export default coffeeApp

actions.js
/*
 * action types
 */

export const ADD_TO_BASKET      = 'add to basket'
export const REMOVE_FROM_BASKET = 'remove from basket'
export const ADD_PRODUCTS       = 'add products json to state'

/*
 * action creators
 */

export function addToBasket(sku, price) {
  return { type: ADD_TO_BASKET, sku, price }
}

export function removeFromBasket(sku, price) {
  return { type: REMOVE_FROM_BASKET, sku, price }
}

export function addProducts(products) {
  return { type: ADD_PRODUCTS, payload: products }
}

EDIT 2: Fixed misplaced return statement and curly bracket in reducers.
The code is reaching the REMOVE_FROM_BASKET statement, as you can see here at this break point. And the quantity variable is undefined. However when in the console I can pull out the value, here is a screen shot of the console

A: You are not returning anything right after your console.log(x) statement. That's why you are seeing undefined. Try updating that part of code to this:
...
if(quantity && quantity > 1) {
  const x = {
    items: {...state, [action.sku]: quantity - 1},
    total: parseInt(state.total,10) - parseInt(action.price, 10)
  };
  console.log(x)
  return x; // <<--- returning new state here!
} else {
  return state;
}
...

A: Single quote missing in your switch case. For more details refer https://github.com/kalaikt/rearch-reactjs/blob/master/src/app/reducers/SearchReducers.jsx
const initialiseState = {
  items: {},
  total: 0
}

function basket(state = initialiseState, action) {

  switch (action.type) {
    case 'ADD_TO_BASKET':
      if(action.sku){
        const quantity = state.items[action.sku] || 0;
        return {
          items: {...state.items, [action.sku]: quantity + 1},
          total:  parseInt(state.total,10) + parseInt(action.price, 10)
        };
      return state
    }

    case 'REMOVE_FROM_BASKET':
      if(action.sku) {

        // const {[action.sku]: quantity, ...items } = state.items;

        const quantity  = state.items[action.sku];
        const { items } = state;
        if(quantity && quantity > 1) {
          const x = {
            items: {...state, [action.sku]: quantity - 1},
            total: parseInt(state.total,10) - parseInt(action.price, 10)
          };
          console.log(x)
          return;
        } else {
          return state;
        }
      } else {
        return state;
      }

    default:
      return state;
  }
}

A: The problem is actually with the brackets inside your basket reductor function as in reality there is only one valid case statement right now.
Let me show you the problem with proper indentation for your current code:
function basket(state = initialiseState, action) {
  switch (action.type) {
    // the only valid case statement!
    case ADD_TO_BASKET:
      if(action.sku){
        const quantity = state.items[action.sku] || 0;
        return {
          items: {...state.items, [action.sku]: quantity + 1},
          total:  parseInt(state.total,10) + parseInt(action.price, 10)
        };
        // unreachable code!
        return state
      }
      // case inside case statement here!
      case REMOVE_FROM_BASKET:
        if(action.sku) {
          const {[action.sku]: quantity, ...items } = state.items;
          if(quantity && quantity > 1) {
            return {
              items: {...state, [action.sku]: quantity - 1},
              total: parseInt(state.total,10) - parseInt(action.price, 10)
            };
            return state;
          } else {
            return state;
          }
        } else {
          return state;
        }
      // default inside case statement here!
      default:
        return state;
  }
}

I'm pretty sure you know what to do with that but just to be complete here, you want to use something like this instead:
function basket(state = initialiseState, action) {
  switch (action.type) {
    case ADD_TO_BASKET:
      if(action.sku) {
        const quantity = state.items[action.sku] || 0;
        return {
          items: {...state.items, [action.sku]: quantity + 1},
          total:  parseInt(state.total,10) + parseInt(action.price, 10)
        };
      } // <<--- proper closing of the if condition here
      return state;

    case REMOVE_FROM_BASKET:
      if(action.sku) {
        const {[action.sku]: quantity, ...items } = state.items;
        if(quantity && quantity > 1) {
          return {
            items: {...state, [action.sku]: quantity - 1},
            total: parseInt(state.total,10) - parseInt(action.price, 10)
          };
        } else {
          return state;
        }
      } else {
        return state;
      }

    default:
      return state;
  }
}

A: I came into work and the senior dev was as confused as I was as to why this wasn't working. I had created the app using create-react-app, so I ejected the app so I could see what was happening with the compiled javascript. Lo and behold it just worked after ejecting, I'm not sure what was causing the issue, but ejecting the app fixed it.
If anyone knows why this was happening before then I'd love to know.


text:
Q: I am trying to get all updated value in a model and send an email to users about the changes in django i have a model A which has a many to one relationship with another model B,i want to be able to get send an email notification to emails which will be queried from model B any time values change in model A how can i do that in django?
class ModelA(models.Model):
    """
    model to store informations about the ModelA
    """

    name = models.CharField(max_length=15, blank=True, unique=True)
    creator = models.ForeignKey(AppUser, blank=True, null=True, on_delete=models.CASCADE)
    periodicity = models.CharField(max_length=10, blank=False, choices=PERIODICITY_CHOICES)
    begin_date = models.DateField(blank=False)
    end_date = models.DateField(blank=True, null=True)
    subscription_fee = models.DecimalField(max_digits=5, decimal_places=2, blank=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    public = models.BooleanField(default=False)
    maximum_sub = models.PositiveIntegerField(blank=True, null=True, validators=[MinValueValidator(2)])

    def save(self):
        emails = []
        body = """
        Hello <user first name or nothing>,
        This is to notify you that ModelA you're subscribed to has been updated. Here is what has changed:
        <field_name_1>: <current_value>
        <field_name_2>: <current_value>
        etc...
        Thank you
        """
        if self.pk is not None:
            modelA_id = ModelA.objects.get(pk=self.pk)
            modelA_members = ModelB.objects.filter(pk=modelA_ID)
            emails = [i for i in modelA_members.email]
            send_mail('ModelA change Notification', body, "noreply@example.com", [emails])
        super(ModelB, self).save() #

    def __unicode__(self):
        return u'{0}'.format(self.name)

class ModelB(models.Model):
    """
    defineModelB

    """

    modelA = models.ForeignKey(ModelA, on_delete=models.CASCADE, blank=False)
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, blank=False, )
    cash_out_date = models.DateField(blank=True, null=True)

A: Okay, so this is one way to solve your problem of detecting the "changed fields" and autosending the email:
Here's how it works. The mixin overrides the class init and saves the existing values in an attribute called self.__initial. Your new values are in self._dict and the difference between the two are the changed values, this is captured by the property diff. We can leverage diff to get a dictionary of {key: (old_value, new_value)}, which you can then use in your templates
class ModelA(ModelDiffMixin, models.Model):
    pass  # Your code goes here

    def save(self):
        changed_fields = self.diff
        for key, old, new in changed_fields.items():
            # Do something here with the values

        emails = []
        body = """
        Hello <user first name or nothing>,
        This is to notify you that ModelA you're subscribed to has been updated. Here is what has changed:
        <field_name_1>: <current_value>
        <field_name_2>: <current_value>
        etc...
        Thank you
        """
        if self.pk is not None:
            modelA_id = ModelA.objects.get(pk=self.pk)
            modelA_members = ModelB.objects.filter(pk=modelA_ID)
            emails = [i for i in modelA_members.email]
            send_mail('ModelA change Notification', body, "noreply@example.com", [emails])
        super(ModelB, self).save() #

class ModelDiffMixin(object):  # Credit to ivanperelivskiy here: https://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed
    """
    A model mixin that tracks model fields' values and provide some useful api
    to know what fields have been changed.
    """

    def __init__(self, *args, **kwargs):
        super(ModelDiffMixin, self).__init__(*args, **kwargs)
        self.__initial = self._dict

    @property
    def diff(self):
        d1 = self.__initial
        d2 = self._dict
        diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
        return dict(diffs)

    @property
    def has_changed(self):
        return bool(self.diff)

    @property
    def changed_fields(self):
        return self.diff.keys()

    def get_field_diff(self, field_name):
        """
        Returns a diff for field if it's changed and None otherwise.
        """
        return self.diff.get(field_name, None)

    def save(self, *args, **kwargs):
        """
        Saves model and set initial state.
        """
        super(ModelDiffMixin, self).save(*args, **kwargs)
        self.__initial = self._dict

    @property
    def _dict(self):
        return model_to_dict(self, fields=[field.name for field in
                             self._meta.fields])

A: You have done well by overriding the save method, to access all modelB linked to modelA instance, you have to use the reverse query related_name
Class ModelA(models.Model):

    def save(self,*args,**kwargs):
        if self.pk is not None:
            body = """
               Hello <user first name or nothing>,
               This is to notify you that ModelA you're subscribed to has been updated. Here is what has changed:
               <field_name_1>: <current_value>
               <field_name_2>: <current_value>
               etc...
               Thank you
           """
            modelB_members = self.modelb_set.all()
            emails = [i.user.email for i in modelB_members]
            send_mail('ModelA Change Notification', body, "noreply@example.com", [emails])
        super(ModelA, self).save(*args,**kwargs) #

class ModelB(models.Model):
    modelA = models.ForeignKey(ModelA, on_delete=models.CASCADE, blank=False)
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, blank=False, )
    cash_out_date = models.DateField(blank=True, null=True)


text:
Q: How can I ensure that the quadratic constraints I am creating are convex? Essentially, how can I check if functions like this are convex, and how can I know before I write a quadratic constraint that it will be convex? So essentially, how can I write feasible convex quadratic constraints so that I don't waste my time writing non-convex ones. Is there a certain form quadratic constraints look like in convex form? I am writing an optimization program that's mixed-integer and quadratic in constraints and objective function but am running into the issue of having a non-semidefinite matrix Q to be used in my solver. Some of the quadratic constraints I have are:
-x8*x10 + 1.4*x7*x9 <= 0

x7*x1 + x8*x4 <= 1470, "Rows Constraint"

x9*x2 <= 163.128, "Seats Per Row Constraint First-Class"

x10*x5 <= 163.128, "Seats Per Row Constraint Premium-Economy"

Which of the above are non-convex? Also, all x's are a positive number.
Thank you so much in advance! PS I am a master's of aerospace engineering student looking for help!

A: Convex constraints in standard form are given by
$$g(\mathbf{x}) \le 0,$$
where $g(\cdot)$ is a convex function. Your constraints are already in the form given above, but your $g(\cdot)$ functions are not convex.
To check whether $g(\cdot)$ is convex, you need to check whether the Hessian -- the matrix of partial second derivatives -- is positive semidefinite. So, for example, the Hessian of your first constraint is
$$\left[\matrix{0 & 0 & 1.4 & 0 \\ 0 & 0 & 0 & -1 \\ 1.4 & 0 & 0 & 0 \\0 & -1 & 0 & 0}\right],$$
which is not PSD (it has negative eigenvalues $\implies$ not PSD).
I gather that you are trying to find a way to "write" a nonconvex constraint as a convex one. But it's not a matter of just writing it in a specific way. A constraint is either convex or not; shifting things to one side of the inequality or the other, multiplying both sides by $-1$, etc. --- things like that are not going to convert a nonconvex constraint into a convex one.


text:
Q: Loading a picture via $http causes an infinite $digest I'm attempting to load an image in a div with a function in a ng-style and it is causing an infinite $digest loop along the lines of this.

$scope.userPicture = function(userId) {
    var deferred = $q.defer();

    var url = '/api/picture/' + userId;
    $http.get(url).then(function (response) {
        if (response.data.result && response.data.result.picture){
            var picture = response.data.result.picture.replace("?t=small", "");
            deferred.resolve({
                'background-image': "url('" + picture + "')",
                'color': 'transparent'
            });
        }
    });

    return deferred.promise;
}

The error displayed in the console

Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.5.11/$rootScope/infdig?p0=10&p1=%5B%5D

I read the explanation of the error in the link, and it sounds like this is caused by the function making AngularJS think that the value has changed infinitely which triggers a digest.
How do I go about creating a function that accepts a parameter and returns the style in this manner?

A: The ng-style directive does not unwrap promises. That was removed from the AngularJS framework many years ago.
Instead of having the HTML retreive the data from the server, do it in the controller:

$scope.userPicStyleHash = {};

$scope.users.forEach(user => getStyle($scope.userPicStyleHash,user.id));

function getStyle(obj,userId) {
    var url = '/api/picture/' + userId;
    $http.get(url).then(function (response) {
        var result = response.data.result;
        if (result && result.picture){
            var picture = result.picture.replace("?t=small", "");
            var style = {
                'background-image': "url('" + picture + "')",
                'color': 'transparent'
            };
            obj[userId] = style;
        }
    });
}


text:
Q: How can I add 'main/dist-upgrader-all' to '/etc/apt/mirror.list' so that my apt-mirror downloads the files for a release upgrade? I maintain an apt mirror by using apt-mirror. It works fine for the packages of bionic and focal. Now, I want to add the files, that are needed to be able to perform release upgrades using this mirror. In /etc/apt/mirror.list I added main/dist-upgrader-all to all update sources that contain these folders.
My /etc/apt/mirror.list currently looks like this:
############# config ##################
#
set base_path    /mnt/usb/ubuntu_mirror
#
# set mirror_path  $base_path/mirror
# set skel_path    $base_path/skel
# set var_path     $base_path/var
# set cleanscript $var_path/clean.sh
# set defaultarch  <running host architecture>
# set postmirror_script $var_path/postmirror.sh
# set run_postmirror 0
set nthreads     20
set _tilde 0
#
############# end config ##############

deb-amd64 http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse main/dist-upgrader-all
deb-amd64 http://archive.ubuntu.com/ubuntu bionic-security main restricted universe multiverse
deb-amd64 http://archive.ubuntu.com/ubuntu bionic-updates main restricted universe multiverse main/dist-upgrader-all
deb-amd64 http://archive.ubuntu.com/ubuntu bionic-backports main restricted universe multiverse

deb-amd64 http://archive.ubuntu.com/ubuntu focal main restricted universe multiverse main/dist-upgrader-all
deb-amd64 http://archive.ubuntu.com/ubuntu focal-security main restricted universe multiverse
deb-amd64 http://archive.ubuntu.com/ubuntu focal-updates main restricted universe multiverse main/dist-upgrader-all
deb-amd64 http://archive.ubuntu.com/ubuntu focal-backports main restricted universe multiverse

clean http://archive.ubuntu.com/ubuntu

After the addition of main/dist-upgrader-all, the execution of apt-mirror throws the following errors, when processing indexes:
Downloading 352 index files using 20 threads...
Begin time: Wed Aug  2 12:15:38 2021
[20]... [19]... [18]... [17]... [16]... [15]... [14]... [13]... [12]... [11]... [10]... [9]... [8]... [7]... [6]... [5]... [4]... [3]... [2]... [1]... [0]...
End time: Wed Aug  2 12:16:01 2021

Processing translation indexes: [TTTTTTTT]

Downloading 1137 translation files using 20 threads...
Begin time: Wed Aug  2 12:16:03 2021
[20]... [19]... [18]... [17]... [16]... [15]... [14]... [13]... [12]... [11]... [10]... [9]... [8]... [7]... [6]... [5]... [4]... [3]... [2]... [1]... [0]...
End time: Wed Aug  2 12:16:26 2021

Processing DEP-11 indexes: [DDDDDDDD]

Downloading 160 dep11 files using 20 threads...
Begin time: Wed Aug  2 12:16:29 2021
[20]... [19]... [18]... [17]... [16]... [15]... [14]... [13]... [12]... [11]... [10]... [9]... [8]... [7]... [6]... [5]... [4]... [3]... [2]... [1]... [0]...
End time: Wed Aug  2 12:16:35 2021

Processing indexes: [Papt-mirror: can't open index archive.ubuntu.com/ubuntu//dists/bionic/main/dist-upgrader-all/binary-amd64/Packages in process_index at /usr/bin/apt-mirror line 800.
PPapt-mirror: can't open index archive.ubuntu.com/ubuntu//dists/bionic-updates/main/dist-upgrader-all/binary-amd64/Packages in process_index at /usr/bin/apt-mirror line 800.
PPapt-mirror: can't open index archive.ubuntu.com/ubuntu//dists/focal/main/dist-upgrader-all/binary-amd64/Packages in process_index at /usr/bin/apt-mirror line 800.
PPapt-mirror: can't open index archive.ubuntu.com/ubuntu//dists/focal-updates/main/dist-upgrader-all/binary-amd64/Packages in process_index at /usr/bin/apt-mirror line 800.
P]

So, what am I doing wrong? How can I successfully add the files from main/dist-upgrader-all to my mirror, so that clients using this mirror can perform release upgrades?

A: The dist-upgrader-all directory is not an apt repository, but it can be mirrored by apt-mirror by using the postmirror.sh script.
Here are lines that can be added to the postmirror.sh script to mirror the dist-upgrader-all directory for focal.  The postmirror.sh script runs in the $base_path/mirror directory and relative paths are used.
mkdir -p archive.ubuntu.com/ubuntu/dists/focal/main/dist-upgrader-all/
rsync --recursive --times --links --hard-links --delete --delete-after rsync://archive.ubuntu.com/ubuntu/dists/focal/main/dist-upgrader-all/ archive.ubuntu.com/ubuntu/dists/focal/main/dist-upgrader-all/

Using rsync is a technique shown in the sample postmirror.sh script in the apt-mirror repository.  It shows that rsync can be used to mirror various extra directories in an apt repository, including the debian-installer, dist-upgrader-all, installer-amd64, and installer-i386 paths.


text:
Q: Rails - How to use variable as part of method name I am trying to add variable name into method_name in rails. I am getting error.

**Controller ACTION**
=====================
def my_action(state)
   method_#{state}
end

**Model methods**
====================
def method_start
end

def method_end
end

how to call method with variable name i am not getting.

A: Use Object.send to call method by name. For example,
def my_action(state)
  if [:start, :end].include?(state)
    model.send("method_#{state}")
  end
end

Make sure to validate state variable for security. Object.send can call any method including private ones.


text:
Q: Unity dual monitor wallpaper corruption I am running 11.04. I have a Nvidia Geforce GT 240 with a dual monitor setup and am running the proprietary drivers. Each time I login, I get a weird problem. The left monitor has a corrupted background. It appears that the region where the app menu would reside is at a different zoom level than the rest of the screen.  If I do anything to cause occlusion on that part of the screen the background redraws and everything looks OK. Has anyone else experienced this problem?

A: I've seen this on occasion, I think it's due to some driver problems. What I do is open a window, and then drag it over the corrupted area, it should act like an eraser and show you the normal background.
It's reported on Launchpad: Bug #769458 Desktop background not properly drawn on login (dual monitor)


text: Q: Is there a way to disable images view on tensor board or remove them from event files? I'm trying to design system with sensitive data which cannot be seen by people who develop machine learning based on this files. They working with TensorFlow and pyTorch. Is there any way to cut off this data from event files (would be great) or modify/configure tensor board to disable view this images?


text:
Q: React: Cant retrieve data from server on client side This is my first time trying to do a CRUD app using react. I am trying to display a list of all of the users from a table (from the server) using a get request.
For some reason I cant get the data from server to the client.
This is the code for the server
const express = require('express');
const cors = require('cors');
const app = express();
const mysql = require('mysql');

const db = mysql.createConnection({
    user: 'root',
    host: 'localhost',
    password: 'password',
    database: 'table1'
});

db.connect((err) => {
    if (err) {
        console.log(err);
    } else {
        console.log('Connected to database');
    }
});

app.use(cors());
app.use(express.json());

app.post("/create", (req, res) => {
    const name = req.body.name;
    const age = req.body.age;
    const country = req.body.country;
    const position = req.body.position;
    const wage = req.body.wage;

    db.query(
      "INSERT INTO users (name, age, country, position, wage) VALUES (?,?,?,?,?)",
      [name, age, country, position, wage],
      (err, result) => {
        if (err) {
          console.log(err);
        } else {
          res.send("Values Inserted");
        }
      }
    );
  });

app.get("/users", (req, res) => {
    db.query("SELECT * FROM users", (err, result) => {
        if (err) {
            console.log(err);
        } else {
            res.send(result);
            console.log(result);
            console.log('success sending data');  //this prints and executes successfully
        }
    });
});

app.listen(3001, () => {
  console.log('Server is running on port 3001');
});

And this is the code I have for the client, the value received is undefined,
import Axios from 'axios';
import './App.css';
import {useState} from 'react';

function App() {
  const[name, setName] = useState("");
  const[age, setAge] = useState(0);
  const[country, setCountry] = useState("");
  const[position, setPosition] = useState("");
  const[wage, setWage] = useState(0);

  const [usersList, setUsersList] = useState([]);

  const getUsers = () => {
    Axios.get('http://localhost:3001/users').then((response) => {
      console.log(response.data);
      setUsersList(response.data);
    });
  };

  const addUser = () => {
    console.log(name, age, country, position, wage);
    Axios.post('http://localhost:3001/create', {name: name, age: age, country: country, position: position, wage: wage})

    .then(()=> console.log('success'));
  };
  return (

        Name
        <input type="text" onChange={(event) => {setName(event.target.value)}}/>
        Age
        <input type="number" onChange={(event)=> { setAge(event.target.value)}}/>
        Country
        <input type="text" onChange={(event)=> {setCountry(event.target.value)}}/>
        Position
        <input type="text" onChange={(event)=> {setPosition(event.target.value)}}/>
        Wage
        <input type="number" onChange={(event)=> {setWage(event.target.value)}}/>

        <button onClick={addUser}> Add Employee</button>

      --

        <button onClick={getUsers}>Show Users</button>
        {usersList.map((val, key) => {
          console.log(val.name);
          return

 Name: {val.name}

        })}

  );
}

export default App;

I have tried to debug by using console.log statements and still can't figure out what is wrong

A: You want to use the "useEffect" hook to fetch data. The useEffect hook will run once your component is rendered.
import {useState, useEffect} from 'react'

/* Inside your component. */
useEffect(async () = {
 const response = await Axios.get('http://localhost:3001/users');
 setUsersList([...response.data]);
}, []);

Passing an empty array as the second argument to the useEffect hook means that the function will run only once, when your component is rendered.
If you want to you could also add an additional state variable:
const [loading, setLoading] = useState(true);

And you can set loading to false once your data is fetched:
useEffect(async () = {
 const response = await Axios.get('http://localhost:3001/users');
 setLoading(false);
 setUsersList([...response.data]);
}, []);

By using this approach you can render your component only once the loading variable is set to false (data is fetched), and otherwise render a simple "Loading..." text on the screen:
function renderUsers(){
    if(loading) return (
Loading...
);

    return usersList.map((val, key) => {
      console.log(val.name);
      return

 Name: {val.name}

    });
}

If this does not work it's probably something wrong with your back-end. Navigate to localhost:3001/users in your browser to see if you actually get a response.


text:
Q: Redux Form : setting value of hidden input in a loop I am working with Redux Form and in that I am trying to set the value of Hidden Input field in a loop. But the value doesn't get submitted as the field was never touched. Is there a way to solve this or am I missing something?
const renderEmployeeFields = (fields) => {
  return fields.map((e, i) => {
    return (
        <Field
          key={e._id}
          name={`employeeSchedule[${i}].employee`}
          component={renderTextField}
          employeeId={e._id}
          label={e._id}
        />
    )
  })
}

const renderTextField = ({ input, label, employeeId}, autocompleteKey) =>
  <Input key={`${label}-input`} autoComplete={`${autocompleteKey}-${label}`} autoFocus {...input} value={employeeId} type='hidden'/>

A: You have to set the value using the initialValues property (https://redux-form.com/7.4.2/docs/api/reduxform.md/#-code-initialvalues-object-lt-string-string-gt-code-optional-) so that they will be available on submit.
You don't need then the hidden input.


text:
Q: Java lambda expression for counting unique objects I have set up this stream below and cant use the method count() on .map. Only on filter. But I havent set up any filter condition. How could I do it on an array of Strings for this stream below?
I want to sort out strings given the regex in replaceAll and get the unique strings and get the number of unique strings total.
Stream newStream = Arrays.stream(arr)
                    .map(s -> s.replaceAll("[^a-z]", ""))
                    .distinct()

A: If you were to count the number of distinct strings, you can do it like :
long countDistinct = Arrays.stream(arr)
        .map(s -> s.replaceAll("[^a-z]", ""))
        .distinct() // intermediate operation with unique strings as 'Stream' return type
        .count();   // terminal operation with count of such strings as return type

A: I'm not sure I completely understand your requirement. It seems you want a List with the distinct strings sorted after applying the regex to each element of the array. This List would have both the elements and their count:
List<String> list = Arrays.stream(arr)
    .map(s -> s.replaceAll("[^a-z]", ""))
    .distinct()
    .sorted()
    .collect(Collectors.toList());

Now, list holds the elements. And if you want to also know how many elements it contains, simply use the List.size method:
int count = list.size();

EDIT: If you also need a Stream with the strings changed, unique and sorted, simply create a new Stream from list:
Stream<String> newStream = list.stream();

A: Both collecting as a list and getting the total count are terminal operations, hence you can do only either on a live stream.
If you must use the same stream to get both the list of strings and count, one (hacky) option would be to use Supplier<Stream<T>>:
String text = "FOO bar BAZ TEXT text some";
String[] arr = text.split(" ");

Supplier<Stream<String>> sameStream = () -> Arrays.stream(arr)
        .map(s -> s.replaceAll("[^a-z]", ""))
        .distinct()
        .filter(s -> !s.isEmpty())
        .sorted();

System.out.println("Unique strings are: " + sameStream.get().collect(Collectors.toList()));
System.out.println("Count of Unique strings are: " + sameStream.get().count());

Above yields this output:
Unique strings are: [bar, some, text]
Count of Unique strings are: 3


text:
Q: Setting up Continuous Integration of Protractor using Buildbot I have written "end to end" automatic tests for my angular website using protractor, I do know how to run the protractor test from buildbot, but don't know how to report back the results of the test to build bot.
Any ideas?

A: When you run protractor conf.js, the exit status should be nonzero if one or more tests fail, and Buildbot will automatically interpret that as a failure.  In other words, the obvious approach of ShellCommand(command=['protractor', 'conf.js']) should work.  If you're doing something else, please give some additional information about what you've tried and what happened.


text:
Q: How to add custom view on Navigation bar I am trying to add custom view on navigation bar. I am not sure how to implement it. Any help appreciate.

A: You can implement custom view on navigation bar easily.
Check the below it will be helped.

Hoping it will be helped.

A: This is a example of how to add a Image instead of a Title String
func setupTitle(){

    let logo = UIImage(named: "ImageFileName")
    let imageView = UIImageView(image:logo)
    imageView.contentMode = .scaleAspectFit

    self.navigationItem.titleView = imageView
    self.navigationController?.navigationBar.prefersLargeTitles = false
}