text:
Q: how to create inline style with :before and :after I generated a bubble chat thingy from http://www.ilikepixels.co.uk/drop/bubbler/
In my page I put a number inside of it
.bubble {
  position: relative;
  width: 20px;
  height: 15px;
  padding: 0;
  background: #FFF;
  border: 1px solid #000;
  border-radius: 5px;
}

.bubble:after {
  content: "";
  position: absolute;
  top: 4px;
  left: -4px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #FFF;
   display: block;
  width: 0;
  z-index: 1;
}

.bubble:before {
  content: "";
  position: absolute;
  top: 4px;
  left: -5px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #000;
  display: block;
  width: 0;
  z-index: 0;
}

I want the background-color of the bubble to change according to the number inside of it via rgb
so if my div is

 100

I want the color to be rgb(100,255,255)
The thing is this doesn't affect the triangle.
How do I write the inline css so it will include the :before and :after?

A: You can't. With inline styles you are targeting the element directly. You can't use other selectors there.
What you can do however is define different classes in your stylesheet that define different colours and then add the class to the element.

A: The key is to use background-color: inherit; on the pseudo element. See: http://jsfiddle.net/EdUmc/

A: I resolved a similar problem by border-color: inherit
, see:
<li style="border-color: <?php echo $hex ?>;">...

li {
    border-width: 0;
}

li:before {
    content: '';
    display: inline-block;
    float: none;
    margin-right: 10px;
    border-width: 4px;
    border-style: solid;
    border-color: inherit;
}

A: If you really need it inline, for example because you are loading some user-defined colors dynamically, you can always add a

 ...

Example use case with PHP and some (wordpress inspired) dummy functions:

<div id="project-slide-<?php the_ID() ?>" class="project-slide"> ...

Since HTML 5.2 it is valid to place style elements inside the body, although it is still recommend to place style elements in the head.
Reference: https://www.w3.org/TR/html52/document-metadata.html#the-style-element

A: You can, using CSS variables (more precisely called CSS custom properties).

*

*Set your variable in your style attribute: style="--my-color-var: orange;"

*Use the variable in your stylesheet: background-color: var(--my-color-var);
Browser compatibility
Minimal example:

div {
  width: 100px;
  height: 100px;
  position: relative;
  border: 1px solid black;
}

div:after {
  background-color: var(--my-color-var);
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}

Your example:

.bubble {
  position: relative;
  width: 30px;
  height: 15px;
  padding: 0;
  background: #FFF;
  border: 1px solid #000;
  border-radius: 5px;
  text-align: center;
  background-color: var(--bubble-color);
}

.bubble:after {
  content: "";
  position: absolute;
  top: 4px;
  left: -4px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent var(--bubble-color);
  display: block;
  width: 0;
  z-index: 1;

}

.bubble:before {
  content: "";
  position: absolute;
  top: 4px;
  left: -5px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #000;
  display: block;
  width: 0;
  z-index: 0;
}

 100


text:
Q: Book cover formatting So I was trying to design a book cover but I had to list some item on the coverpage but Idk why it's not compiling as it should with the code.
This is how it turns out

but I need the below items to be in a list like this

also why aren't the checkmarks showing up?
This is the code:
    \documentclass{article}

    \usepackage[dvipsnames]{xcolor}
    \usepackage{tikz}
    \usetikzlibrary{ shapes.geometric }
    \usetikzlibrary{calc}
    \usepackage{anyfontsize}
    \usepackage{amsfonts}

    \begin{document}
    \pagestyle{empty}

    \begin{tikzpicture}[remember picture,overlay]
    \fill[BrickRed] (current page.south west) rectangle (current page.north east);

    \foreach \i in {2.5,...,22}
    {
        \node[rounded corners,BrickRed!60,draw,regular polygon,regular polygon sides=6, minimum size=\i cm,ultra thick] at ($(current page.west)+(2.5,-5)$) {} ;
    }

    \foreach \i in {0.5,...,22}
    {
    \node[rounded corners,BrickRed!60,draw,regular polygon,regular polygon sides=6, minimum size=\i cm,ultra thick] at ($(current page.north west)+(2.5,0)$) {} ;
    }

    \foreach \i in {0.5,...,22}
    {
    \node[rounded corners,BrickRed!90,draw,regular polygon,regular polygon sides=6, minimum size=\i cm,ultra thick] at ($(current page.north east)+(0,-9.5)$) {} ;
    }

    \foreach \i in {21,...,6}
    {
    \node[BrickRed!85,rounded corners,draw,regular polygon,regular polygon sides=6, minimum size=\i cm,ultra thick] at ($(current page.south east)+(-0.2,-0.45)$) {} ;
    }

    \node[left,BrickRed!5,minimum width=0.625*\paperwidth,minimum height=3cm, rounded corners] at ($(current page.north east)+(0,-9.5)$)
    {
    {\fontsize{25}{30} \selectfont \bfseries 100 Thrilling Math Problems}
    };

    \node[left,BrickRed!10,minimum width=0.625*\paperwidth,minimum height=2cm, rounded corners] at ($(current page.north east)+(0,-11)$)
    {
    {\huge \textit{Both Textual and Video Solutions}}
    };

    \node[left,BrickRed!5,minimum width=0.625*\paperwidth,minimum height=2cm, rounded corners] at ($(current page.north east)+(1,-13)$)
    {
    {\fontsize{25}{30} \textsc{By Kowshiq Kattamuri}}
    };

    \node[left,BrickRed!5,minimum width=0.625*\paperwidth,minimum height=2cm, rounded corners] at ($(current page.north east)+(1,-16)$)
    {
    \begin{itemize}
        \item [\checkmark] Jee Advanced
        \item [\checkmark] ISI
        \item [\checkmark] CMI
        \item [\checkmark] KVPY
        \item [\checkmark] IOQM
    \end{itemize}
    };

    \node[rounded corners,fill=BrickRed!70,text =BrickRed!5,regular polygon,regular polygon sides=6, minimum size=2.5 cm,inner sep=0,ultra thick] at ($(current page.west)+(2.5,-5)$) {\LARGE \bfseries };

    \end{tikzpicture}

    \end{document}

A: You can use text width=<length> to allow line breaking inside nodes, and then with align=right to align your text to the right side.

\documentclass{article}

\usepackage{newpxtext}
\usepackage{amsfonts}

\usepackage[dvipsnames]{xcolor}
\usepackage{tikz}
\usetikzlibrary{ shapes.geometric }
\usetikzlibrary{calc}
\usepackage{anyfontsize}

\newcommand{\KKcheckmark}{\enspace\textcolor{Green!60}{\checkmark}}

\begin{document}
\pagestyle{empty}

\begin{tikzpicture}[remember picture,overlay]
\fill[BrickRed] (current page.south west) rectangle (current page.north east);

\node[rounded corners,fill=BrickRed!70,text =BrickRed!5,regular polygon,regular polygon sides=6, minimum size=2.5 cm,inner sep=0,ultra thick] at ($(current page.west)+(2.5,-5)$) {\LARGE \bfseries };

\foreach \i in {2.5,...,22}
{
    \node[rounded corners,BrickRed!60,draw,regular polygon,regular polygon sides=6, minimum size=\i cm,ultra thick] at ($(current page.west)+(2.5,-5)$) {} ;
}

\foreach \i in {0.5,...,22}
{
\node[rounded corners,BrickRed!60,draw,regular polygon,regular polygon sides=6, minimum size=\i cm,ultra thick] at ($(current page.north west)+(2.5,0)$) {} ;
}

\foreach \i in {0.5,...,22}
{
\node[rounded corners,BrickRed!90,draw,regular polygon,regular polygon sides=6, minimum size=\i cm,ultra thick] at ($(current page.north east)+(0,-9.5)$) {} ;
}

\foreach \i in {21,...,6}
{
\node[BrickRed!85,rounded corners,draw,regular polygon,regular polygon sides=6, minimum size=\i cm,ultra thick] at ($(current page.south east)+(-0.2,-0.45)$) {} ;
}

\node[left, BrickRed!5, text width=0.625*\paperwidth, align=right, minimum height=3cm, rounded corners] at ($(current page.north east)+(-1,-9.5)$)
{
{\fontsize{25}{30} \selectfont \bfseries 100 Thrilling Math Problems}
};

\node[left,BrickRed!10, text width=0.625*\paperwidth, align=right, minimum height=2cm, rounded corners] at ($(current page.north east)+(-1,-11)$)
{
{\huge \textit{Both Textual and Video Solutions}}
};

\node[left, BrickRed!5, text width=0.625*\paperwidth, align=right, minimum height=2cm, rounded corners] at ($(current page.north east)+(-1,-13)$)
{
{\fontsize{25}{30} \textsc{By Kowshiq Kattamuri}}
};

\node[left, BrickRed!5, text width=0.625*\paperwidth, align=right, minimum height=2cm, rounded corners] at ($(current page.north east)+(-1,-19)$)
{
\LARGE
Jee Advanced\KKcheckmark\\
ISI\KKcheckmark\\
CMI\KKcheckmark\\
KVPY\KKcheckmark\\
IOQM\KKcheckmark\\
};

\end{tikzpicture}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show Google Customer Review only after click on button I am using Googles Customer Reviews. It works fine. But my goal is, that the autooverlay is only loaded after I click on a button with id="google-review"
The original Code is:
    <script src="https://apis.google.com/js/platform.js?onload=renderOptIn" async defer></script>
<script>
        window.renderOptIn = function() {
            window.gapi.load('surveyoptin', function() {
                window.gapi.surveyoptin.render(
                    {
                        "merchant_id": number,
                        "order_id": order_id,
                        "email": customer_email,
                        "delivery_country": delivery_country,
                        "estimated_delivery_date": estimated_delivery_date,
                        "opt_in_style": "BOTTOM_TRAY"
                    });
            });
        }
</script>

I tried:
    $("#google-review").click(function() {
    window.renderOptIn = function () {
        window.gapi.load('surveyoptin', function () {
            window.gapi.surveyoptin.render(
                {
                    "merchant_id": number,
                    "order_id": order_id,
                    "email": customer_email,
                    "delivery_country": delivery_country,
                    "estimated_delivery_date": estimated_delivery_date,
                    "opt_in_style": "BOTTOM_TRAY"
                });
        });
    }
});

But this is not working. The overlay is not loading at all. How can I achieve my goal?

A: Try the other way around. Script source onload calls renderOptin. This then sets up a click handler. Actual click executes the code inside the function:
window.renderOptIn = function() {
  $("#google-review").click(function() {
    window.gapi.load('surveyoptin', function() {
      window.gapi.surveyoptin.render({
        "merchant_id": number,
        "order_id": order_id,
        "email": customer_email,
        "delivery_country": delivery_country,
        "estimated_delivery_date": estimated_delivery_date,
        "opt_in_style": "BOTTOM_TRAY"
      });
    });
  });
}

A: Another solution just avoids the parameter 'onload' when you load js like this:
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
$("#google-review").click(function() {
    window.gapi.load('surveyoptin', function () {
        window.gapi.surveyoptin.render({
                "merchant_id": number,
                "order_id": order_id,
                "email": customer_email,
                "delivery_country": delivery_country,
                "estimated_delivery_date": estimated_delivery_date,
                "opt_in_style": "BOTTOM_TRAY"
            });
    });
});
</script>

A: for me this is works, especially combine with PHP
$('.send-trigger').on('click',function(){

            var orderId = $(this).attr('order-id');
            var custEmail = $(this).attr('customer-email');

            window.gapi.load('surveyoptin', function() {
                window.gapi.surveyoptin.render(
                {

                "merchant_id": 1234534535345354,
                "order_id": orderId,
                "email": custEmail,
                "delivery_country": "XX",
                "estimated_delivery_date": "<?= date('Y-m-d') ?>"
                });
            });

});


text:
Q: Performance of Dijkstra's algorithm implementation Below is an implementation of Dijkstra's algorithm I wrote from the pseudocode in the Wikipedia article.  For a graph with about 40 000 nodes and 80 000 edges, it takes 3 or 4 minutes to run.  Is that anything like the right order of magnitude?  If not, what's wrong with my implementation?
struct DijkstraVertex {
  int index;
  vector<int> adj;
  vector<double> weights;
  double dist;
  int prev;
  bool opt;
  DijkstraVertex(int vertexIndex, vector<int> adjacentVertices, vector<double> edgeWeights) {
    index = vertexIndex;
    adj = adjacentVertices;
    weights = edgeWeights;
    dist = numeric_limits<double>::infinity();
    prev = -1; // "undefined" node
    opt = false; // unoptimized node
   }
};

void dijsktra(vector<DijkstraVertex*> graph, int source, vector<double> &dist, vector<int> &prev) {
  vector<DijkstraVertex*> Q(G); // set of unoptimized nodes
  G[source]->dist = 0;
  while (!Q.empty()) {
    sort(Q.begin(), Q.end(), dijkstraDistComp); // sort nodes in Q by dist from source
    DijkstraVertex* u = Q.front(); // u = node in Q with lowest dist
    u->opt = true;
    Q.erase(Q.begin());
    if (u->dist == numeric_limits<double>::infinity()) {
      break; // all remaining vertices are inaccessible from the source
    }
    for (int i = 0; i < (signed)u->adj.size(); i++) { // for each neighbour of u not in Q
    DijkstraVertex* v = G[u->adj[i]];
    if (!v->opt) {
      double alt = u->dist + u->weights[i];
      if (alt < v->dist) {
        v->dist = alt;
        v->prev = u->index;
      }
    }
    }
  }
  for (int i = 0; i < (signed)G.size(); i++) {
    assert(G[i] != NULL);
    dist.push_back(G[i]->dist); // transfer data to dist for output
    prev.push_back(G[i]->prev); // transfer data to prev for output
  }
}

A: There are several things you can improve on this:

*

*implementing the priority queue with sort and erase adds a factor of |E| to the runtime - use the heap functions of the STL to get a log(N) insertion and removal into the queue.

*do not put all the nodes in the queue at once but only those where you have discovered a path (which may or may not be the optimal, as you can find an indirect path through nodes in the queue).

*creating objects for every node creates unneccessary memory fragmentation. If you care about squeezing out the last 5-10%, you could think about a solution to represent the incidence matrix and other information directly as arrays.

A: Use priority_queue.
My Dijkstra implementation:
struct edge
{
    int v,w;
    edge(int _w,int _v):w(_w),v(_v){}
};
vector<vector<edge> > g;
enum color {white,gray,black};
vector<int> dijkstra(int s)
{
    int n=g.size();
    vector<int> d(n,-1);
    vector<color> c(n,white);
    d[s]=0;
    c[s]=gray;
    priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q; // declare priority_queue
    q.push(make_pair(d[s],s)); //push starting vertex
    while(!q.empty())
    {
        int u=q.top().second;q.pop(); //pop vertex from queue
        if(c[u]==black)continue;
        c[u]=black;
        for(int i=0;i<g[u].size();i++)
        {
            int v=g[u][i].v,w=g[u][i].w;
            if(c[v]==white) //new vertex found
            {
                d[v]=d[u]+w;
                c[v]=gray;
                q.push(make_pair(d[v],v)); //add vertex to queue
            }
            else if(c[v]==gray && d[v]>d[u]+w) //shorter path to gray vertex found
            {
                d[v]=d[u]+w;
                q.push(make_pair(d[v],v)); //push this vertex to queue
            }
        }
    }
    return d;
}


text:
Q: Deploy an SSL enabled Java SpringBoot war to External Tomcat Server I have a spring boot application, which is an SSL enabled one, I can access it through localhost. "https://localhost:8443/showPage" like this. For localhost I created SSL certificate and gave the details in application.properties like below
server.port: 8443
server.ssl.key-store: classpath:keystore.p12
server.ssl.key-store-password: 123456
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat

This works perfectly for localhost. I want to deploy the war to a tomcat server, which is already SSL enabled. For that I changed the properties like below
server.port: 8443
server.ssl.key-store: /opt/tomcat/keystore/keystorefile.jks
server.ssl.key-store-password: Rv$@1234
server.ssl.keyStoreType: JKS
server.ssl.keyAlias: tomcat

But I am getting the below image while accessing any request. I called the request properly. Not as shown in the picture. Like this:  "https://ipaddress:8443/war_name/showPage"

And my controller accepts request for
@RequestMapping("showPage")

A: I spent days looking for an answer so I will post my solution for someone else to follow here. I am using Spring Boot 2 with an external tomcat 9 running on centOs 8.

*

*Get an SSL certificate, I created a self-signed cert using keytool with a password.

*Store the jks and the p12 file on your apache server. I stored it in /opt/tomcat

*Edit your apache server.xml file to have something like this.
 <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
  maxThreads="150" scheme="https" secure="true"
  keystoreFile="/opt/tomcat/keystore.p12" keystorePass="password"
  clientAuth="false" sslProtocol="TLS" sslEnabledProtocols="TLSv1.2,TLSv1.1"/>

*Restart Tomcat

*Open the firewall port for 8443 and restart the firewall daemon
  firewall-cmd --zone=public --permanent --add-port 8443/tcp
  firewall-cmd --reload

It is very quick once you know what the steps are! Just don't forget anything.


text:
Q: whats the best way to represent types without id in prisma? datamodel.graphql
type Data {
  id: ID! @unique
  createdAt: DateTime!
  updatedAt: DateTime!
  points:[Point!]!
}

type Point {
 x:Float!
 y:Float!
}

generated types(prisma.graphql) :
type Data implements Node {
  id: ID!
  points(where: PointWhereInput, orderBy: PointOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Point!]
}

in my datamodel points is required field but in generated prisma types points is optional ? and when i update points of my Data previous data also coming in result(https://github.com/prisma/prisma/issues/1657) ..
workaround i see is Json but we loose type safety in codegen and graphiql :( ,
does prisma going to handle type without id fields as Json by default in implementation ...?


text:
Q: TFS Build issue/error in visual Studio 2017 ASP.NET Core TFS Build issue/error in visual Studio 2017 ASP.NET Core
Summary Build 1 error(s), 0 warning(s)###
Exit code 100 returned from process: file name 'tf', arguments 'vc shelve /saved /replace /recursive /comment:@d:\a_temp\tmp79.tmp _Build_5127 d:\a\1\s /loginType:OAuth /login:.,******** /noprompt'.

A: Exit code 100 means that nothing succeeded.
Documentation: https://msdn.microsoft.com/en-us/library/ms194959%28v=vs.100%29.aspx?f=255&MSPPError=-2147217396
Can you try the same command from a command prompt?


text:
Q: Development server is not starting and getting no response I am a beginner for django web development. Initially i created a project and an app. When i try to run the django server using the python manage.py runserver command it loads for sometime and i get no response.
I am using Pycharm 2019 community edition

A: You mention you are using PyCharm. Can you use your terminal window within PyCharm (normally at the bottom, possible toggle view with Alt+F12). In that terminal window try typing python manage.py runserver and see if that gives you an error.


text:
Q: Async/Await forEach Angular 5 HttpClient I want to show the spinner when I click on the button, and hide it when I get all of the data, but I can't figure out how to use async/await in the given example.
This is the simplified version of my code:
.ts:
isLoading: boolean = false;

onLoad() {
    this.isLoading = true;
    this.http.post(this.Aurl).subscribe(Aresponse => {
        this.Aitems = Aresponse;
        this.Aitems.forEach((Aitem, Aindex) => {
            let Bbody = Aitem.id;
            this.http.post(this.Burl, Bbody).subscribe(Bresponse => {
                let Bitem = Bresponse;
                this.Bitems[Aindex] = Bitem;
            });
        });
    });
    // this.isLoading = false;
}

.html:
<button (click)="onLoad()">Load</button>

<mat-progress-spinner *ngIf="isLoading" mode="indeterminate"></mat-progress-spinner>

<div *ngIf="!isLoading" >
    <div *ngFor="let Bitem of Bitems">
    </div>
</div>

A: You can use forkJoin
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
onLoad() {
this.isLoading = true;
this.http.post(this.Aurl).subscribe(Aresponse => {
    this.Aitems = Aresponse;
    let observableBatch = [];

    this.Aitems.forEach((Aitem, Aindex) => {
        let Bbody = Aitem.id;
        observableBatch.push(this.http.post(this.Burl, Bbody).subscribe(Bresponse => {
            let Bitem = Bresponse;
            this.Bitems[Aindex] = Bitem;
        }));
    });
    Observable.forkJoin(observableBatch).subscribe(res => this.isLoading = false;);
});
}

Hope it will solve your issue.

A: You have to do it with forkJoin, the below code is just a rough code to portray the concept.
this.isLoading = true;
this.http.post(this.Aurl)
    .do(Aresponse => console.log(Aresponse)
    .mergeMap(Aresponse => Observable.forkJoin(Aresponse.map((item, index) => this.http.post(this.Burl, item.id))))
    .subscribe(resultSet => {
        console.log(resultSet); //handle each value emitted here
        this.loading = false;
        })


text:
Q: Using iosMath in Swift how can I use iosMath in Swift on iOS, because iosMath is written in Objective C? Or is there another way to display mathematical formulas with Swift?

A: I will make this as fast as possible:
1.) install cocoaPods (open up terminal and write sudo gem install cocoapods)
2.) From terminal change directory to your project and init cocoaPods and edit the Podfile like this:
cd /ProjectFolder
pod init
nano podFile

(opens the podfile, where you paste the pod repo) , should look like this:
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'mathExample' do
  # Comment the next line if you're not using Swift and don't want to use dynam$
  use_frameworks!

  # Pods for mathExample

  pod 'iosMath'

end

save podfile and install via:
pod install

from now, use the workspace file instead of the project file... We are done installing the pod you need right now...
Now it gets a little bit tricky -> You need to add new Objective-C file into the project (so just New File -> Objective-C file and select create bridging header) from now, you can just delete the created file (BUT NOT THE BRIDGING HEADER)
from now, you can use the Objective-C framework just as it was swift framework,don't forget to import that framework into classes you will use it:
    import UIKit
//Importing our module
    import iosMath

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print(iosMathVersionNumber)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Hope this helps, wish happy coding! :)

A: The general question has already been answered. Check this question out.
All you have to do is add iosMath in your podfile and as long as you have use_frameworks! in the podfile, you won't need any headers. Simply, import iosMath in your swift file and you are good to go.


text:
Q: Search option in select menu Jquery-Mobile I have a select menu of jquery-mobile in my project. Now the list is so large and i have to put search option in it for filtering. I searched it in jquery mobile but did not find the solution in it. Please help me and let me know is it possible or not.

A: It can be done, take a look at this example: http://jsfiddle.net/sEMyT/2/
Source code can be found here: https://github.com/aliok/jquery-mobile/commits/selectmenu-forceDialog/
Code example:
        Refresh the selectmenu (forcerebuild) with clearing the filter value

                    Your state:
                    <select name="select-choice-12" id="select-choice-12" data-native-menu="false" data-force-dialog="true" data-native-menu="false" data-filter="true">
                        <option value="AL">Alabama</option>
                        <option value="AK">Alaska</option>
                        <option value="AZ">Arizona</option>
                        <option value="AR">Arkansas</option>
                        <option value="CA">California</option>
                        <option value="CO">Colorado</option>
                        <option value="CT">Connecticut</option>
                        <option value="DE">Delaware</option>
                        <option value="FL">Florida</option>
                        <option value="GA">Georgia</option>
                        <option value="HI">Hawaii</option>
                        <option value="ID">Idaho</option>
                        <option value="IL">Illinois</option>
                        <option value="IN">Indiana</option>
                        <option value="IA">Iowa</option>
                        <option value="KS">Kansas</option>
                        <option value="KY">Kentucky</option>
                        <option value="LA">Louisiana</option>
                        <option value="ME">Maine</option>
                        <option value="MD">Maryland</option>
                        <option value="MA">Massachusetts</option>
                        <option value="MI">Michigan</option>
                        <option value="MN">Minnesota</option>
                        <option value="MS">Mississippi</option>
                        <option value="MO">Missouri</option>
                        <option value="MT">Montana</option>
                        <option value="NE">Nebraska</option>
                        <option value="NV">Nevada</option>
                        <option value="NH">New Hampshire</option>
                        <option value="NJ">New Jersey</option>
                        <option value="NM">New Mexico</option>
                        <option value="NY">New York</option>
                        <option value="NC">North Carolina</option>
                        <option value="ND">North Dakota</option>
                        <option value="OH">Ohio</option>
                        <option value="OK">Oklahoma</option>
                        <option value="OR">Oregon</option>
                        <option value="PA">Pennsylvania</option>
                        <option value="RI">Rhode Island</option>
                        <option value="SC">South Carolina</option>
                        <option value="SD">South Dakota</option>
                        <option value="TN">Tennessee</option>
                        <option value="TX">Texas</option>
                        <option value="UT">Utah</option>
                        <option value="VT">Vermont</option>
                        <option value="VA">Virginia</option>
                        <option value="WA">Washington</option>
                        <option value="WV">West Virginia</option>
                        <option value="WI">Wisconsin</option>
                        <option value="WY">Wyoming</option>
                    </select>

    You can see the source code at https://github.com/aliok/jquery-mobile/commits/selectmenu-forceDialog/


text:
Q: Accessing kafka from spring boot application running on kubernetes I have a kafka installation running within in kubernetes cluster. I have a pod running a spring boot application which is using the default bootstrap.servers (localhost:9092) configuration and not the one passed in (bootstrap.kafka.svc.cluster.local:9092). The pod then fails to start as kafka is not running on localhost.
Here is my spring boot configuration
spring:
  kafka:
    consumer:
      group-id: spring-template
      auto-offset-reset: earliest
      bootstrap-servers: "bootstrap.kafka.svc.cluster.local:9092"
    producer:
      bootstrap-servers: "bootstrap.kafka.svc.cluster.local:9092"
    bootstrap-servers: "bootstrap.kafka.svc.cluster.local:9092"

When setting up the consumers on startup the group id and auto-offset-reset are being correctly passed in from the above configuration. However the bootstrap-servers configuration is not and the application is actually using localhost:9092 as per the log below
2019-03-11 07:34:36.826  INFO 1 --- [  restartedMain] o.a.k.clients.consumer.ConsumerConfig    : ConsumerConfig values:
        auto.commit.interval.ms = 5000
        auto.offset.reset = earliest
        bootstrap.servers = [localhost:9092]
        check.crcs = true
        client.id =
        connections.max.idle.ms = 540000
        default.api.timeout.ms = 60000
        enable.auto.commit = true
        exclude.internal.topics = true
        fetch.max.bytes = 52428800
        fetch.max.wait.ms = 500
        fetch.min.bytes = 1
        group.id = spring-template
        heartbeat.interval.ms = 3000
        interceptor.classes = []
        internal.leave.group.on.close = true
        isolation.level = read_uncommitted
        key.deserializer = class org.apache.kafka.common.serialization.StringDeserializer
        max.partition.fetch.bytes = 1048576
        max.poll.interval.ms = 300000
        max.poll.records = 500
        metadata.max.age.ms = 300000
        metric.reporters = []
        metrics.num.samples = 2
        metrics.recording.level = INFO
        metrics.sample.window.ms = 30000
        partition.assignment.strategy = [class org.apache.kafka.clients.consumer.RangeAssignor]
        receive.buffer.bytes = 65536
        reconnect.backoff.max.ms = 1000
        reconnect.backoff.ms = 50
        request.timeout.ms = 30000
        retry.backoff.ms = 100
        sasl.client.callback.handler.class = null
        sasl.jaas.config = null
        sasl.kerberos.kinit.cmd = /usr/bin/kinit
        sasl.kerberos.min.time.before.relogin = 60000
        sasl.kerberos.service.name = null
        sasl.kerberos.ticket.renew.jitter = 0.05
        sasl.kerberos.ticket.renew.window.factor = 0.8
        sasl.login.callback.handler.class = null
        sasl.login.class = null
        sasl.login.refresh.buffer.seconds = 300
        sasl.login.refresh.min.period.seconds = 60
        sasl.login.refresh.window.factor = 0.8
        sasl.login.refresh.window.jitter = 0.05
        sasl.mechanism = GSSAPI
        security.protocol = PLAINTEXT
        send.buffer.bytes = 131072
        session.timeout.ms = 10000
        ssl.cipher.suites = null
        ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
        ssl.endpoint.identification.algorithm = https
        ssl.key.password = null
        ssl.keymanager.algorithm = SunX509
        ssl.keystore.location = null
        ssl.keystore.password = null
        ssl.keystore.type = JKS
        ssl.protocol = TLS
        ssl.provider = null
        ssl.secure.random.implementation = null
        ssl.trustmanager.algorithm = PKIX
        ssl.truststore.location = null
        ssl.truststore.password = null
        ssl.truststore.type = JKS
        value.deserializer = class org.apache.kafka.common.serialization.StringDeserializer

2019-03-11 07:34:36.942  INFO 1 --- [  restartedMain] o.a.kafka.common.utils.AppInfoParser     : Kafka version : 2.0.1
2019-03-11 07:34:36.945  INFO 1 --- [  restartedMain] o.a.kafka.common.utils.AppInfoParser     : Kafka commitId : fa14705e51bd2ce5
2019-03-11 07:34:37.149  WARN 1 --- [  restartedMain] org.apache.kafka.clients.NetworkClient   : [Consumer clientId=consumer-1, groupId=spring-template] Connection to node -1 could not be established. Broker may not be available.

I have kubernetes service called bootstrap, running in namespace kafka in the kubernetes cluster. Here is a snippet of the log file. Why is the spring boot application not picking up the configured bootstrap.servers configuration

A: The bootstrap-servers property expects a list of Kafka server addresses. By putting quotation marks around the value you signaled that the value is a string and therefore create a type conflict.
To solve this issue you should either remove the quotation marks or put the value explicitly in a list form. e.g:
spring:
  kafka:
    consumer:
      bootstrap-servers: ["bootstrap.kafka.svc.cluster.local:9092"]

A: Sometimes, it will actually be your Kafka Kubernetes deployment that is at fault.
Can I see your deployment YAML/JSON file for the Kafka deployment, please?
It should look like this:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-kafka
spec:
  replicas: 1
  selector:
    matchLabels:
      app: kafka
      id: "0"
  template:
    metadata:
      labels:
        app: kafka
        id: "0"
    spec:
      containers:
        - name: kafka
          image: wurstmeister/kafka:latest
          ports:
            - containerPort: 30035
          env:
            - name: KAFKA_ADVERTISED_HOST_NAME
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP

            - name: KAFKA_ADVERTISED_PORT
              value: "9092"

            - name: KAFKA_HEAP_OPTS
              value: -Xms320m

            - name: KAFKA_ZOOKEEPER_CONNECT
              value: "zookeeper:2181"

---
apiVersion: v1
kind: Service
metadata:
  name: api-kafka
  namespace: default
  labels:
    name: kafka
spec:
  ports:
    - port: 9092
      name: kafka-port
      protocol: TCP
  selector:
    app: kafka
    id: "0"

  type: NodePort

With an emphasis on the:
- name: KAFKA_ADVERTISED_HOST_NAME
  valueFrom:
      fieldRef:
          fieldPath: status.podIP

Make sure your profiles are right and that'll fix all of your problems to do with the connections and the advertised hostnames within a Kubernetes Deployment


text:
Q: Синтаксис MySQL в функции как написать присвоение функции select Подскажите, как присвоить результат работы select по двум колонкам.
CREATE FUNCTION GetP()
RETURNS INT(11)
BEGIN
  select id,P from P ORDER BY Use ASC limit 1;
return 0;
END

Подскажите как положить id,P получаемые значения в разные переменные что бы к ним можно было обратится?
Я пробывал делать что то вроде
@getId:=id,@getP:=P

Но это возвращает ошибку, как быть?


text:
Q: Python pandas 'lookup' is deprecated and will be removed. How to change the codes? As you know, pandas dataframe.lookup method is deprecated and will be removed. (oh... hate this warning)
In my case, I've seen this warning,

"FutureWaning: The 'lookup' method is deprecated and will be removed
in a future version. You can use DataFrame.melt and DataFrame.loc as a
substitute."

I've found out how to use melt and loc as a substitute for a simple example.
df = pd.DataFrame({'col': ["A", "A", "B", "B"],'A': [80, 23, np.nan, 22],  'B': [80, 55, 76, 67]})
0   A   80.0    80
1   A   23.0    55
2   B   NaN 76
3   B   22.0    67

lookup method:
df.lookup(df.index, df['col'])
array([80., 23., 76., 67.])

This is easy and intuitive,
but if  I change this using 'melt' and 'loc',
df2 = df.melt('col')
df2.loc[df2['col']==df2['variable']]['value'].values
array([80., 23., 76., 67.])

Ok, I get the same result which I wanted to.
But if I have a big dataframe (row: 300,000 / column: 200), this "melt" function doesn't look good.
Is there any other way to substitute the pandas dataframe 'lookup' method?
Or can I make more efficient code than what I have done above?

A: Input data:
  col     A   B
0   A  80.0  80
1   A  23.0  55
2   B   NaN  76
3   B  22.0  67
4   A  10.0  15

df1 = df.set_index("col").sort_index()
df1 = df1.stack().iloc[::len(df1.columns)]

Output result:
>>> df1
col
A    A    80.0
     A    23.0
     A    10.0
B    B    76.0
     B    67.0
dtype: float64


text:
Q: Git clone to memory I'm making an app that is required to clone git repositories by a link to it and analyze the codebase.
Pulling to the disk using the git clone command wouldn't scale well. Is there any way to clone to memory, or at least to get a stream of file contents, instead of intermediary disk I/O.

A: It is operating system specific.
If your application runs on Linux (so perhaps also on Android), you can use a memory based file system like tmpfs. So git pull  (or git clone, etc...)  would put it in that FS which sits in virtual memory, and it will run quite fast. However, the bottleneck is probably the network (unless your application is running in some datacenter and can use a big lot of bandwidth).
BTW, on Linux, the page cache is quite effective. So even with ordinary (disk-based) file system, performance can be quite good in practice.
Then your application would access these files thru usual file-related syscalls or library functions (e.g. <stdio.h> in C), and that would only use memory (without any real disk IO) and should scale quite well.
Of course, you'll need to have enough RAM for that to work well.

A: There is a fundamental conflict between with the git model and what you are trying to do here.  git clone makes a full copy of the repository on your local machine. The idea of git is to keep a complete copy of the repository locally.   There is nearly no communication with the server with most commands.  The only time there is communication is when you git fetch (pull down all branch changes from the server) or git push (push all local branch changes to the remote repository) or of course when you make a complete copy with git clone.
So really, I think you are stuck.  What I gather is that you want to pull down lots of different projects, run analysis on each, then delete the results.  That's not something git was designed for as it is fundamentally about keeping and modifying a local copy of a repository for a long period of time.
I do question your assumption that pulling to memory would even make a difference.  Network operations are a couple orders of magnitude slower than disk operations.  A decent non-SSD drive is going to give you around 150 MB/s.  And SSD is going to triple that.  Unless you have a much better connection than I do, pulling to memory would not speed things up at all as your OS is spending all its time waiting for network requests to the git server.
If you are working with github, you may be better off with the "Download ZIP" method on each project page.  This will download a branch without all the extraneous branch/history information.  That should be faster than doing a git pull for cases where you only need the latest version of one branch.


text:
Q: JSON Encode and curly quotes I've run into an interesting behavior in the native PHP 5 implementation of json_encode().  Apparently when serializing an object to a json string, the encoder will null out any properties that are strings containing "curly" quotes, the kind that would potentially be copy-pasted out of MS Word documents with the auto conversion enabled.
Is this an expected behavior of the function?  What can I do to force these kinds of characters to covert to their basic equivalents?  I've checked for character encoding mismatches between the database returning the data and the administration page the inserts it and everything is setup correctly - it definitely seems like the encoder just refuses these values because of these characters.  Has anyone else encountered this behavior?
EDIT:
To clarify;
MSWord will take standard quotation marks and apostraphes and convert them to more aesthetic "fancy" or "curly" quotes.  These characters can cause problems when placed in content managers that have charset mistmatches between their editing interface (in the html) and the database encoding.
That's not the problem here, though.  For example, I have a json_object representing a person's profile and the string:
Jim O'Shea
The UTF code for that apostraphe being \u2019
Will come out null in the json object when fetched from database and directly json_encoded.
{"model_name":"Bio","logged":true,"BioID":"17","Name":null,"Body":"Profile stuff!","Image":"","Timestamp":"2011-09-23 11:15:24","CategoryID":"1"}

A: Never had this specific problem (i.e. with json_encode()) but a simple - albeit a bit ugly - solution I have used in other places is to loop through your data and pass it through this function I got from somewhere (will credit it when I find out where I got it):
function convert_fancy_quotes ($str) {
  return str_replace(array(chr(145),chr(146),chr(147),chr(148),chr(151)),array("'","'",'"','"','-'),$str);
}

A: json_encode has the nasty habit of silently dropping strings that it finds invalid (i.e. non-UTF8) characters in. (See here for background: How to keep json_encode() from dropping strings with invalid characters)
My guess is the curly quotes are in the wrong character set, or get converted along the way. For example, it could be that your database connection is ISO-8859-1 encoded.
Can you clarify where the data comes from in what format?

A: If I ever need to do that, I first copy the text into Notepad and then copy it from there. Notepad forces it to be normal quotes. Never had to do it through code though...


text:
Q: Communication with Windows Guest OS run in Qemu Using a headless Ubuntu 14.04 server, I'm running a Windows 7 guest in Qemu to which I am passing through the GPU (for performance). I am writing an application for which part will be running in Linux, and part will be running in the Windows guest, and I need communication between the two. Researching this has led me to believe my best option would be using Virtio-serial drivers so I can simply communicate between the two as if they had a serial connection; this sounds fabulous, but I can't for the life of me figure out how to get it working.  I've found a few resources which detail the necessary Qemu command line options, such as here, but I've failed to find any resources on how to initiate communication from the Guest's side.  It seems most people doing this type of thing are doing so with Linux guest OSes, which I'm sure greatly simplifies things.
Network communication may not be an option, as we will most likely be passing the NIC through to the Guest OS as well (again, performance is critical for the guest OS). Even if not, that seems like an unnecessarily heavy option for simple communication between applications.
I have also considered creating an SMB share, and storing a database there that can be connected to from multiple hosts, then running mysql on the host and guest. But this also seems far less than ideal... Does anyone have any experience with this, or maybe an obvious suggestion I'm missing?
Edit:
I meant to include my qemu shell script:
sudo qemu-system-x86_64 -enable-kvm -M q35 -m 3072 -cpu host -smp 4
-bios /usr/share/qemu/bios.bin -vga none -nographic -serial mon:stdio
-device ioh3420,bus=pcie.0,addr=1c.0,multifunction=on,port=1,chassis=1,id=root.1
-device vfio-pci,host=00:01.0,bus=root.1,addr=00.0,multifunction=on,x-vga=on
-device vfio-pci,host=00:01.1,bus=root.1,addr=00.1
-device virtio-scsi-pci,id=scsi
-drive file=/utils/WES7.img,id=disk,format=raw,if=none -device ide-hd,drive=disk
-drive file=/home/mvsuser/virtio-win-0.1-100.iso,id=virtiocd,if=none -device ide-cd,bus=ide.1,drive=virtiocd
-usb -usbdevice host:046d:C52B
-net bridge -net nic,model=virtio
-chardev socket,path=/tmp/port0,server,nowait,id=port0-char
-device virtio-serial
-device virtserialport,id=port1,name=vioserial,chardev=port0-char

A: The page you refer to includes a link to the API to use from Windows guests (as well as Linux guests). I believe this is what you're looking for.
Also, the QEMU Guest Agent source code has a working example of how the qemu guest agent uses virtio-serial within Windows.


text:
Q: Getting 2 point features with max/min ID from each group with same value in two fields I'm working in QGIS for a Digital Terrain Model.
I've got a table with point features, arguably vertices extracted from multipart iso-curves because the features are provided with a "vertex_par" value along with an "ID" (not unique, it recalls the original curve multipart feature ID).
Intent: I need to get the extremes of each original iso-curve lying on the property border into a table to feed my BIM-modeling app.
GOAL: I need to isolate all the points that are start and endpoints of the original curves (or parts).
Sketched in plain language:
For each group with the same "ID" value

    For each subgroup with same "vertex_par"

        I need to get the points with minimum/maximum "vertex_ind" value

QUESTION: How do I set an expression to filter these points?

A: You can use a Virtual Layer (Menu Database > Db Manager > Virtual Layer > Open a SQL Window with the sheet + wrench icon):
SELECT alti_tab.*
FROM "ALTI_Isok Punkte" AS alti_tab,
     (SELECT "ID",
             "vertex_par",
             MIN("vertex_ind") AS min_vertex_ind,
             MAX("vertex_ind") AS max_vertex_ind
      FROM "ALTI_Isok Punkte"
      GROUP BY "ID",
               "vertex_par"
     ) AS t1
WHERE alti_tab."ID" = t1."ID"
AND alti_tab."vertex_par" = t1."vertex_par"
AND (alti_tab."vertex_ind" = t1.min_vertex_ind OR alti_tab."vertex_ind" = t1.max_vertex_ind)

Explanations:

*

*t1 is a subquery that select only minimum MIN and maximum MAX of vertex_ind group by ID ans vertex_par

*the final query joins the ALTI_Isok Punkte table to t1 with the fields ID and vertex_par and selects only vertex_ind equals minimum or maximum.

A pure QGIS expression based, maybe :
minimum("vertex_ind", group_by:= "ID" || '_' || "vertex_par") = "vertex_ind"
OR
maximum("vertex_ind", group_by:= "ID" || '_' || "vertex_par") = "vertex_ind"

I tried to replace (with QGIS 3.10) the "ID" || '_' || "vertex_par" by `array("ID", "vertex_par"), but not seeing a great difference.


text:
Q: Find all nonzero matrices $A\in M_2(\Bbb Z_3)$ which are not invertible. Find all nonzero (with every element $\neq$0) matrices $A\in M_2(\Bbb Z_3)$ which are not invertible, and explain why they aren't invertible.
It seems simple indeed, but I'm not sure how to solve this :s
Thanks for any help!!!

A: Since every element of our matrix is supposed to be non-zero, we have very few cases to consider. For at every position of the matrix, we have $2$ choices for the entry at that position, for a total of $2^4$. We can just go through these $16$ possibilities, and identify the matrices that are non-invertible. The two procedures we describe below are somewhat faster.
We can use the criterion that a matrix is non-invertible if and only if the two rows are linearly dependent. Or else we can use the fact that a matrix over a field is invertible if and only if its determinant is non-zero.
Solution $1$. The first row can be any of $1\quad 1$, or $1\quad 2$, or $2\quad 1$, or $2\quad 2$.
For each of these, there are precisely two second rows such that the first row and the second are linearly dependent. For example, if the first row is $1\quad 2$, the two second rows are $1$ times the first row, or $2$ times the first row, that is, $1\quad 2$ and $2\quad 1$.
Solution $2.$ Let $a$ and $d$ be the entries on the main diagonal. There are $4$ possibilities for the pair $(a,d)$. Our matrix will be non-invertible precisely if its determinant is $0$. This is the case if and only if $cb\equiv ad\pmod{3}$, where $b$ is the second entry in the top row, and $c$ is the first entry in the second row.
Now we can do a case by case analysis. For example, if $a=1$ and $d=2$, we want $cb\equiv 2\pmod{3}$, giving $b=2$ and $c=1$ or the other way around.
Remark: For the same problem with $\mathbb{Z}_p$ instead of $\mathbb{Z}_3$, the same ideas work. For example, let $p=13$. For any of the $(12)(12)$ first rows, there are $12$ second rows that give non-invertibility.

A: Hint: $A \in M_2(\mathbb{Z}_3)$ is not invertible iff its rows $A_1$ and $A_2$ are colinear. In particular, you can deduce that there are $33$ non invertible matrices in $M_2(\mathbb{Z}_3)$.


text:
Q: Read .dat file using python I've got a simulation involving internal waves and moving particles in the water, using the MITgcm. The output of this looks something like this for each time step:
   -9999 0.0000000000000000000  #Time step (0.00000000000000 seconds)
 1308.2021183321899       -14.999709364517091 # Particle 1 (X,Z)
 1308.2020142528656       -24.999521595698688 # Particle 2 (X,Z)
 1308.2018600072618       -34.999345597877536 # .
 1308.2016593336587       -44.999185870669805 # .
 1308.2014165588744       -54.999046508237896 # .
 1308.2011370083103       -64.998931076248894
 1308.2008269116873       -74.998842490305705
 1308.2004933548124       -84.998782925797485
 1308.2001441978532       -94.998753764086956
 1308.1997879652938       -104.99875557384759
 1308.1994336881464       -114.99878812280582
 1308.1990906721119       -124.99885041328211
 1308.1987681881285       -134.99894073461562
 1308.1984750963150       -144.99905672694641
 1308.1982194336249       -154.99919545294702
 1308.1980080134056       -164.99935347476733
 1308.1978461242272       -174.99952693694112
 1308.1977378137256       -184.99971163492469
 1308.2000000000000       -195.00000000000000
 5232.8000000000002       -15.000038916290352
 5232.8000000000002       -25.000064153684303
 5232.8000000000002       -35.000089286157163
 5232.8000000000002       -45.000114270293523
 5232.8000000000002       -55.000139061712051 # Particle 57

Where -9999 #number is the time step (in seconds), left column is X position and right column is Z position (in meters); and every line is a different particle (except the -9999 one). So we'll have an enormous amount of lines with something like this for every time step and every particle.
I would like to plot the time-evolution of the position of my particles. How can I do it? If that's too hard, I would be happy with static plots of different time-steps with all particles position.
Thank you so much.
Edit1: What I tried to do is this, but I didn't show it before because it is far from proper:
 from matplotlib import numpy
 import matplotlib.pyplot as plot
 plot.plot(*np.loadtxt('data.dat',unpack=True), linewidth=2.0)

or this:
 plot.plotfile('data.dat', delimiter=' ', cols=(0, 1), names=('col1', 'col2'), marker='o')

A: I would use numpy.loadtxt for reading input, but only because post-processing would also need numpy. You can read all your data to memory, then find the separator lines, then reshape the rest of your data to fit your number of particles. The following assumes that none of the particles ever reach exactly x=-9999, which should be a reasonable (although not foolproof) assumption.
import numpy as np
filename = 'input.dat'
indata = np.loadtxt(filename, usecols=(0,1)) # make sure the rest is ignored
tlines_bool = indata[:,0]==-9999
Nparticles = np.diff(np.where(tlines_bool)[0][:2])[0] - 1
# TODO: error handling: diff(np.where(tlines_bool)) should be constant
times = indata[tlines_bool,1]
positions = indata[np.logical_not(tlines_bool),:].reshape(-1,Nparticles,2)

The above code produces an Nt-element array times and an array position of shape (Nt,Nparticles,2) for each particle's 2d position at each time step. By computing the number of particles, we can let numpy determine the size of the first dimension (this iswhat the -1 index in reshape() is for).
For plotting you just have to slice into your positions array to extract what you exactly need. In case of 2d x data and 2d y data, matplotlib.pyplot.plot() will automatically try to plot the columns of the input arrays as a function of each other. Here's an example of how you can visualize, using your actual input data:
import matplotlib.pyplot as plt
t_indices = slice(None,None,500)  # every 500th time step
particle_indices = slice(None)    # every particle
#particle_indices = slice(None,5)   # first 5 particles
#particle_indices = slice(-5,None)  # last 5 particles

plt.figure()
_ = plt.plot(times[myslice],positions[myslice,particle_indices,0])
plt.xlabel('t')
plt.ylabel('x')

plt.figure()
_ = plt.plot(times[myslice],positions[myslice,particle_indices,1])
plt.xlabel('t')
plt.ylabel('z')

plt.figure()
_ = plt.plot(positions[myslice,particle_indices,0],positions[myslice,particle_indices,1])
plt.xlabel('x')
plt.ylabel('z')
plt.show()

Each line corresponds to a single particle. The first two plots show the time-evolution of the x and z components, respectively, and the third plot shows the z(x) trajectories. Note that there are a lot of particles in your data that don't move at all:
>>> sum([~np.diff(positions[:,k,:],axis=0).any() for k in range(positions.shape[1])])
15

(This computes the time-oriented difference of both coordinates for each particle, one after the other, and counts the number of particles for which every difference in both dimensions is 0, i.e. the particle doesn't move.). This explains all those horizontal lines in the first two plots; these stationary particles don't show up at all in the third plot (since their trajectory is a single point).
I intentionally introduced a bit fancy indexing which makes it easier to play around with your data. As you can see, indexing looks like this: times[myslice], positions[myslice,particle_indices,0], where both slices are defined in terms of...well, a slice. You should look at the documentation, but the short story is that arr[slice(from,to,stride)] is equivalent to arr[from:to:stride], and if any of the variables is None, then the corresponding index is empty: arr[slice(-5,None)] is equivalent to arr[-5:], i.e. it will slice the final 5 elements of the array.
So, in case you use a reduced number of trajectories for plotting (since 57 is a lot), you might consider adding a legend (this only makes sense as long as the default color cycle of matplotlib lets you distinguish between particles, otherwise you have to either set manual colors or change the default color cycle of your axes). For this you will have to keep the handles that are returned from plot:
particle_indices = slice(None,5)   # first 5 particles
plt.figure()
lines = plt.plot(positions[myslice,particle_indices,0],positions[myslice,particle_indices,1])
plt.xlabel('x')
plt.ylabel('z')
plt.legend(lines,['particle {}'.format(k) for k in range(len(t))])
plt.show()


text:
Q: Error running Clementine Recently I installed Clementine 1.0 media player. When I run the program, simply it crashes. Here I describe the situation:
$clementine
22:27:59.162 DEBUG NetworkProxyFactory:30           Detected system proxy URLs: ("", "", "", "")
22:27:59.162 DEBUG CoverProviders:34                Registered cover provider "Amazon"
22:28:00.822 INFO  Database:578                     Updating "songs" for %allsongstables
22:28:00.822 INFO  Database:578                     Updating "magnatune_songs" for %allsongstables
22:28:00.910 INFO  Database:578                     Updating "songs" for %allsongstables
22:28:00.910 INFO  Database:578                     Updating "magnatune_songs" for %allsongstables
22:28:01.366 INFO  Database:578                     Updating "songs" for %allsongstables
22:28:01.366 INFO  Database:578                     Updating "magnatune_songs" for %allsongstables
22:28:01.367 INFO  Database:578                     Updating "jamendo.songs" for %allsongstables
22:28:01.608 INFO  Database:578                     Updating "songs" for %allsongstables
22:28:01.608 INFO  Database:578                     Updating "magnatune_songs" for %allsongstables
22:28:01.609 INFO  Database:578                     Updating "jamendo.songs" for %allsongstables
22:28:02.015 INFO  Database:578                     Updating "songs" for %allsongstables
22:28:02.015 INFO  Database:578                     Updating "magnatune_songs" for %allsongstables
22:28:02.015 INFO  Database:578                     Updating "jamendo.songs" for %allsongstables
22:28:02.577 INFO  Database:578                     Updating "songs" for %allsongstables
22:28:02.577 INFO  Database:578                     Updating "magnatune_songs" for %allsongstables
22:28:02.578 INFO  Database:578                     Updating "spotify_search_songs" for %allsongstables
22:28:02.578 INFO  Database:578                     Updating "jamendo.songs" for %allsongstables
22:28:02.579 INFO  Database:578                     Updating "playlist_items" for %allsongstables
22:28:02.914 INFO  Database:578                     Updating "songs" for %allsongstables
22:28:02.915 INFO  Database:578                     Updating "magnatune_songs" for %allsongstables
22:28:02.916 INFO  Database:578                     Updating "spotify_search_songs" for %allsongstables
22:28:02.916 INFO  Database:578                     Updating "jamendo.songs" for %allsongstables
22:28:02.917 INFO  Database:578                     Updating "playlist_items" for %allsongstables
22:28:03.501 INFO  Player:533                       Registered URL handler for "di"
22:28:03.501 DEBUG InternetModel:94                 Adding internet service: "DigitallyImported"
22:28:03.635 DEBUG InternetModel:94                 Adding internet service: "Icecast"
22:28:03.700 DEBUG InternetModel:94                 Adding internet service: "Jamendo"
22:28:03.759 DEBUG unknown                          Connected to accessibility bus at:  "unix:abstract=/tmp/dbus-96lpIZpvgm,guid=4fc59d3beb26bd425de407800000003f"
22:28:03.760 DEBUG unknown                          Registered DEC:  true
22:28:04.312 INFO  Player:533                       Registered URL handler for "lastfm"
22:28:04.312 DEBUG CoverProviders:34                Registered cover provider "last.fm"
22:28:04.313 DEBUG InternetModel:94                 Adding internet service: "Last.fm"
22:28:04.313 INFO  Player:533                       Registered URL handler for "grooveshark"
22:28:04.314 INFO  PlaylistManager:417              Registered special playlist type "grooveshark-search"
22:28:04.318 DEBUG InternetModel:94                 Adding internet service: "Grooveshark"
22:28:04.324 INFO  Player:533                       Registered URL handler for "magnatune"
22:28:04.331 DEBUG InternetModel:94                 Adding internet service: "Magnatune"
22:28:04.365 DEBUG InternetModel:94                 Adding internet service: "SavedRadio"
22:28:04.370 INFO  Player:533                       Registered URL handler for "sky"
22:28:04.370 DEBUG InternetModel:94                 Adding internet service: "SKY.fm"
22:28:04.371 INFO  Player:533                       Registered URL handler for "somafm"
22:28:04.371 DEBUG InternetModel:94                 Adding internet service: "SomaFM"
22:28:04.372 DEBUG SpotifyService:70                Spotify system blob path: "/usr/bin/clementine-spotifyblob"
22:28:04.372 DEBUG SpotifyService:71                Spotify local blob path: "/home/brallan/.config/Clementine/spotifyblob/version11-32bit/blob"
22:28:04.372 INFO  PlaylistManager:417              Registered special playlist type "spotify-search"
22:28:04.372 DEBUG InternetModel:94                 Adding internet service: "Spotify"
22:28:04.473 WARN  IconLoader:54                    Couldn't load icon "clementine-panel"
22:28:04.507 WARN  IconLoader:54                    Couldn't load icon "clementine-panel-grey"
22:28:04.752 DEBUG GnomeGlobalShortcutBackend:50    registering
22:28:04.960 DEBUG MainWindow:209                   Starting
22:28:05.530 DEBUG MainWindow:267                   Initialising player
22:28:05.611 DEBUG MainWindow:273                   Creating models
22:28:05.632 DEBUG MainWindow:296                   Creating UI
22:28:05.735 DEBUG MainWindow:663                   Creating equalizer
22:28:05.735 DEBUG MainWindow:678                   Creating now playing widget
22:28:05.983 DEBUG MainWindow:715                   Loading settings
22:28:06.152 DEBUG MainWindow:761                   Initialising library
22:28:06.154 DEBUG MainWindow:774                   Started
22:28:06.170 WARN  unknown                          Invalid parent:  0xb6a2cab0 QtSingleApplication(0xbfae6b08, name = "clementine")
22:28:06.174 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.176 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.182 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.183 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.187 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.190 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.203 WARN  unknown                          QAccessibleWidget::rect: This implementation does not support subelements! (ID 1 unknown for LineTextEdit)
22:28:06.203 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.204 WARN  unknown                          QAccessibleWidget::rect: This implementation does not support subelements! (ID 2 unknown for LineTextEdit)
22:28:06.204 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.205 WARN  unknown                          QAccessibleWidget::rect: This implementation does not support subelements! (ID 3 unknown for LineTextEdit)
22:28:06.205 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.207 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.360 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.361 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.371 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.373 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.375 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.434 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.435 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.437 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.548 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.551 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.811 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.824 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.835 WARN  unknown                          Requesting child objects for an interface that is a virtual child itself.
22:28:06.862 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.865 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.870 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.873 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.875 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.877 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.891 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.892 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.892 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.892 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.892 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.892 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.895 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.896 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.898 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.900 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.902 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.903 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.905 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.907 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.907 WARN  unknown                          Creating accessible with different object than the original interface!
22:28:06.907 ERROR unknown                          ASSERT: "interface->valueInterface()" in file accessible.cpp, line 280
Aborted

If somebody would help me please. Thanks!

A: This is the solution:
sudo apt-get remove qt-at-spi


text:
Q: Finding matching columns in pandas including NaNs I have a quite specific question regarding pandas. I have two DataFrames, both are binary : One containing multiple patterns to match lets say :
0 : 1,NaN,1,Nan,Nan
1 : Nan,1,1,Nan,Nan

and one containing records of actual data
0 : 1,0,0,1,0
1 : 0,0,0,0,1
2 : 1,0,1,0,0

I want to perform an operation that tells me which lines of the record data match which rules. In the example rule 0 would match record 2. The missing values don't have to match anything, and therein lies my problem : if there wouldn't be any missing values I could simply use pd.merge(df1,df2,how="inner"), but an inner join doesn't match NaNs with anything.
Is there a simple elegant solution without doing all the loops?
Edit to add (for clarity):
This:
0 : 1,1,NaN,NaN,NaN

should match with both of these:
0 : 1,1,0,0,0
1 : 1,1,0,0,1

A: If is binary we can using duplicated
df=pd.concat([df1.fillna(0),df2],keys=['df1','df2'])
df[df.astype(int).duplicated(keep=False)]
Out[37]:
         1    2  3    4    5
df1 0  1.0  0.0  1  0.0  0.0
df2 2  1.0  0.0  1  0.0  0.0

EDIT
dd=df1.stack().reset_index().groupby('level_0').level_1.apply(list).tolist()
dd
Out[67]: [['1', '3'], ['2', '3']]

df2.apply(lambda x : sum([all(x.loc[y]==1) for y in dd]),1 )

Out[78]:
0    0
1    0
2    1
dtype: int64
df2[df2.apply(lambda x : sum([all(x.loc[y]==1) for y in dd]),1 )==1]
Out[80]:
   1  2  3  4  5
2  1  0  1  0  0


text:
Q: Regionprops (connected components) matlab I get the concept of applying regionprops to extract ROI. Basically, regionprops uses connected components technique to extract the object. But, the thing I wanted to ask is using regionprops on "BoundingBox", what is the default value for connected components (number of connectivity)? I tried searching about it but I could not really find the answer.

A: I didn't see the default connectivity on regionprops, but the default connectivity for both bwlabel and bwconncomp (for 2-dimensional matrices) is 8-connected. I would expect regionprops to be the same. You should be able to easily determine if this is the case for regionprops by constructing a test image something like this:
1 1 0 0
1 1 0 0
0 0 1 1
0 0 1 1

Alternatively, you could use bwlabel or bwconncomp first and control the connectivity parameter. regionprops accepts the output from either of these, as well as a BW image.

A: Take a look to the Matlab documentation about regionprops:
https://www.mathworks.com/help/images/ref/regionprops.html
In the section Tips you can see: ''If you need to specify nondefault connectivity, call bwconncomp and then pass the result to regionprops'' as:
CC = bwconncomp(BW, CONN);
S = regionprops(CC);

So answer to you question: It uses default connectivity that is 8, and you can also change it as you want with the parameter CONN when calling bwconncomp.


text:
Q: Making hidden HTML text bold when it is displayed On my webpage I have text that is in a hidden field(input type="hidden"). When I display the text, I would like it to be bold so it stands out.
Can this be done with CSS or any other way? I have already tried style="font-weight: bold;" and it doesn't work in Chrome.

A: <input type="text" id="myInput" value="Hello" />

CSS:
#myInput
{
    display:none;
    font-weight:normal;
}

Javascript:
function ShowInput()
{
    document.getElementById("myInput").style.display="block";
    document.getElementById("myInput").style.fontWeight="bold";
}

Check it http://jsfiddle.net/LvaFS/


text:
Q: Creating programming language question I'm thinking about creating a custom (small) programming language (syntax) based on C.
I don't understand how apple implemented objective-c with operators like [testClass runThis:true]; with that syntax.
How would i implement a custom syntax for my custom c language

A: You might want to look at Clang (the C, C++ and Obj-C frontend of the LLVM compiler) and the Eero Programming Language, a new language based on Objective-C that was built with LLVM. Both projects are open-source.

A: You'd need to implement a parser and a lexer to start with. One way to go about it is to get the C syntax and grammar from K&R's "The C programming language" and use that as input to Flex and Bison to create a standalone parser. That will parse syntactically valid C programs. After that, you can tweak it as you want and customise it.
This is however a non trivial project and you'll have to be prepared to teach yourself a lot about compilers. Good luck!

A: The bit inside [...] is based on the syntax of Smalltalk.
As for designing your own language, that is quite a big subject.  You need to acquaint yourself with context free grammars, lexical analysis, recursive descent parsers, LALR parsers, and we haven't even got to the problem of generating executable code yet.  Still it's all good fun.  Designing and implementing workable computer languages is a challenging but (IMO) rewarding exercise.

A: You'll have to write a compiler.  If your semantics fit, you might be able to compile directly to C code; otherwise you'll have to also write some kind of runtime for the bits of your language which don't easily and directly translate to C.  Given that you're talking about a small C-based language, though, that's probably not an issue.
How do you go about doing this?  Oh.  Man.
There are dozens of books, articles, tutorials, etc. on the subject of writing a compiler.  While no individual piece of a compiler is particularly difficult (at least for naive, non-optimizing compilers), there is a whole lot of stuff to contend with in a whole lot of different ways, often ways which are subtly incompatible with each other.
At the very least you'll want a lexer (usually through an automated tool like flex or as part of a compiler suite like ANTLR), a parser (usually through automated tools like Bison and the aforementioned ANTLR) and a code generator (usually generated by hand).  In reality you'll probably want to stick an abstract syntax tree between the parser and the code generator to give you (or someone else) room for implementing various optimizations and for making code generation simpler.
There are lots of books available on this topic, not to mention research papers.  Have fun.  What you're trying to do is challenging but rewarding when you pull it off.

A: Step up to C++ and you have the possibility to create a DSEL (Domain-Specific Embedded Language).  I don't know what problem you're trying to solve but a well designed DSEL might be much more convenient than designing your own language and creating parsers, compilers, etc.  Grab a copy of this book for some insight: C++ Template Metaprogramming


text:
Q: git pull multiple repositories I have a question regrading intertwined repositories.
I have a repo, lets call it common_repo.
common_repo holds code which is relevant to most of my other repos, and I wish to pull it whenever I pull other repositories.
We've considered submodules, but as far as I understand this will create numerous copies of the common repo on my machine. This is undesireable as I may have differnet versions on my computer of the same files according to when I last pulled the dependent repo, which could lead to confusion.
Another alternative would be using some custom scripts such as sggested here. However this is not cross paltform (we have multiple developers working on different OS's), requires deployment on each machine, and doesn't play well git GUI clients such as smartgit or source tree.
Is there a better solution which we haven't considered?

A: You can update all git repositories in a directory with a bash command, as you mentioned
find . -maxdepth 3 -name .git -type d | rev | cut -c 6- | rev | xargs -I {} git -C {} pull

Credit: https://medium.com/@codenameyau/updating-multiple-repos-with-one-command-9768c8cdfe46
Another option I can propose to you would be to explore the post-merge git hook, where you could accomplish something similar to the above on git pull. Any language, compiled or interpreted can be used in a git hook as long as the appropriate interpreter is available on the system.
This may be a good resource: https://git-scm.com/docs/githooks


text:
Q: Django Models not saving Cart Items I've created the cart view but I can't get the cart updated with my products. I tried many ways from stackoverflow examples but none worked. I am adding my whole code for Cart Application.
Following is my Model for Cart app:
class CartItem(models.Model):
    cart = models.ForeignKey("Cart")
    item = models.ForeignKey(Variation)
    quantity = models.PositiveIntegerField(default=1)
    line_item_total = models.DecimalField(max_digits=10, decimal_places=2)

    def __unicode__(self):
        return self.item.title

    def remove(self):
        return self.item.remove_from_cart()

def cart_item_pre_save_receiver(sender, instance, *args, **kwargs):
    qty = instance.quantity
    if qty >= 1:
      price = instance.item.get_price()
      line_item_total = Decimal(qty) * Decimal(price)
      instance.line_item_total = line_item_total

pre_save.connect(cart_item_pre_save_receiver, sender=CartItem)

def cart_item_post_save_receiver(sender, instance, *args, **kwargs):
    instance.cart.update_subtotal()

post_save.connect(cart_item_post_save_receiver, sender=CartItem)

class Cart(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    items = models.ManyToManyField(Variation, through=CartItem)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=60.00)

    def __unicode__(self):
        return str(self.id)

    def update_subtotal(self):
        print "updating..."
        subtotal = 0
        items = self.cartitem_set.all()
        for item in items:
            subtotal += item.line_item_total
        self.subtotal = subtotal
        self.save()

In my View I got:
from django.views.generic.base import View
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404
from django.views.generic.detail import SingleObjectMixin

from products.models import Variation
from .models import Cart, CartItem

# Create your views here.

class CartView(SingleObjectMixin, View):
    model = Cart
    template_name = "carts/view.html"

    def get_object(self, *args, **kwargs):
        self.request.session.set_expiry(0)           #for expire the session when we login, 0 means when we close browser session expire.
        cart_id = self.request.session.get("cart_id")
        if cart_id == None:                          # for cart id
            cart = Cart()
            cart.save()
            cart_id = cart.id
            self.request.session["cart_id"] = cart_id
        cart = Cart.objects.get(id=cart_id)
        if self.request.user.is_authenticated():        # for making user
            cart.user = self.request.user
            cart.save()
        return cart

    def get(self, request, *args, **kwargs):
        cart = self.get_object()
        item_id = request.GET.get("item")
        delete_item = request.GET.get("delete")
        if item_id:
            item_instance = get_object_or_404(Variation, id=item_id)
            qty = request.GET.get("qty", 1)
            try:
                if int(qty) < 1:                        #if qty <1 delete item
                    delete_item = True
            except:
                raise Http404
            cart_item = CartItem.objects.get_or_create(cart=cart, item=item_instance)[0]
            if delete_item:                             # for delete item
                cart_item.delete()
            else:
                cart_item.quantity = qty
                cart_item.save()
        context = {
            "object": self.get_object()                 # get_object from above
        }
        template = self.template_name
        return render (request, template, context)

In my Template I got added context for cart:
{% extends 'home.html' %}

{% block content %}

{% for item in object.cartitem_set.all %}

    <form action="." method="GET" >
    {{ item.item.get_title }}
    <input type="hidden" name="item" value="{{ item.item.id }}" />
    <input type="number" class="item-qty" name="qty" value="{{ item.quantity }}" />
    <input type="submit" class="btn-update btn btn-link" value="Updated item" style="display: None;" />
    {{ item.line_item_total }}
    X
    </form>

{% endfor %}

        Subtotal: {{ object.subtotal }}

{% endblock %}

A: ...
cart = models.ForeignKey("Cart", on_delete=models.CASCADE)
item = models.ForeignKey(Variation, on_delete=models.CASCADE)
...


text:
Q: suitable name for function/method I have class with method that inside of it i take complex object and
from it I create new object with simple structure user can work with it
in more convenient way .I store this object instance in the memory and
and provide simple api to it.
I give it name Serializable but I'm not sure that this is the right name.

A: *

*Transform

*TransformToX (where X is the name of the resulting object)

*ToX (you see that a lot, for instance, ToString, ToInt32)

A: I name methods like that using names like asThing(). I suppose in C# it should be AsThing(). Another choice might be to follow the example of Java's Number class: Number.intValue(), etc.


text:
Q: how can get the data through search bar Here is the code
@IBOutlet weak var searhBar: UISearchBar!
var arr = NSMutableArray()
var filterdata = NSMutableArray()

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    filterdata = []
    if searchText == "" {
        filterdata = arr
    }

    else {

        for items in arr {
            if let txt = items as? String {
                if txt.lowercased().contains(searchText.lowercased()) {
                    filterdata.add(txt)
                }
            }
        }
    }
    self.tblView.reloadData()
}

A: Give the proper naming to variable. I think you are new.
Use filter rather than for loop.
@IBOutlet weak var searchBar: UISearchBar!
var arr = [String]()
var filterdata = [String]()

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText.isEmpty {
        filterdata = arr
    } else {
        filterdata = arr.filter({ $0.lowercased().contains(searchText.lowercased())})
    }
    self.tblView.reloadData()
}


text:
Q: Checking if a php process is already running I'm trying to check if a process is already running by using a temporal file demo.lock:
demo.php:
<?php
    $active=file_exists('demo.lock');
    if ($active)
    {
        echo 'process already running';
    }
    else
    {
        file_put_contents ('demo.lock', 'demo');
        sleep(10);  //do some job
        unlink ('demo.lock');
        echo 'job done';
    }
?>

however it doesn't seem to work: if I open demo.php twice it always shows "job done", maybe because it considers it the same process? is there some way to do it? I also tried with getmypid() with similar results.
Thanks

A: Works for me.
Make sure the script can create a file in the directory. Uncomment the "unlink" line and run the script and check if the lock file exists in the directory. If you don't see it then it's a directory permissions issue.

A: Can't be sure about what's wrong with your specific case assuming a "normal, easy" environment because it works for me, but at least you have a race condition in your code. What if you start two processes at the exact same time, and that both find that demo.lock does not exist?
You can use fopen with the x mode to prevent this from happening. The X mode tries to create the file; if it already exists, it fails and generates an E_WARNING error (hence the shut-up operator). Since filesystem operations are atomic on a drive, it is guaranteed that only one process at a time can hold the file.
<?php

$file = @fopen("demo.lock", "x");
if($file === false)
{
    echo "Unable to acquire lock; either this process is already running, or permissions are insufficient to create the required file\n";
    exit;
}

fclose($file); // the fopen call created the file already
sleep(10); // do some job
unlink("demo.lock");
echo "Job's done!\n";

?>

I've tested it here and it seems to work.

A: Well, sending some headers and flushing seems to work for me (not sure why), so now when I load the page shows "Start" and if I hit the refresh button on the browser before completing the process, the warning message:
<?php

$file = @fopen("demo.lock", "x");
if($file === false)
{
    echo "Unable to acquire lock; either this process is already running, or permissions are insufficient to create the required file\n";
    exit;
}

header("HTTP/1.0 200 OK");
ob_start();
echo "Starting";
header('Content-Length: '.ob_get_length(),true);
ob_end_flush();
flush();

fclose($file); // the fopen call created the file already
sleep(10); // do some job
unlink("demo.lock");
?>

Thanks for all the answers and suggestions so far


text:
Q: Logical delete with a Time stamp I prefer to delete a record from the database logically rather than physically. Is it better to just flag the record with a "deleted" flag or else is it better to use a time stamp?
For example We can add an additional DateTime fields to every tables that we need to perform logical delete. So when deleting you just update the field like...
UPDATE Client SET deleted = GETDATE() where Client.CID = @cid

If it should be undeleted...
UPDATE Client SET deleted = NULL where Client.CID = @cid

So that a typical selection statement would look like...
SELECT * FROM client WHERE CID = @cid AND deleted IS NULL

My primary requirement is that the deleted rows should be able to recover and it should be able to easily implement.

A: It is a common pattern that a column with a name like "DeletedAt" or "DeletionDate", of type date is used to indicate if the row has been deleted.  So the answer is yes.


text:
Q: Build errors ONLY occur when publishing I'm trying to publish my project which has references to other projects in my solution.
Whenever I build the solution regularly it builds just fine without any errors.
However, whenever I attempt to publish the project I get the message "Build failed".
When I check the output log I see the following 3 errors:

C:\Users\MyUsername\Dropbox\Projects\SEO\QualityLinkBuilder\Web\RealestateJobsMigrations\RealestateJobsConfiguration.cs(10,101,10,124):
    error CS0234: The type or namespace name 'RealestateJobsDbContext'
    does not exist in the namespace 'RealestateScraper' (are you missing
    an assembly reference?)

C:\Users\MyUsername\Dropbox\Projects\SEO\QualityLinkBuilder\Web\RealestateJobsMigrations\RealestateJobsConfiguration.cs(18,56,18,79):
  error CS0234: The type or namespace name 'RealestateJobsDbContext'
  does not exist in the namespace 'RealestateScraper' (are you missing
  an assembly reference?)
C:\Users\MyUsername\Dropbox\Projects\SEO\QualityLinkBuilder\Web\ViewModels\JobsVm.cs(364,51,364,69):
  error CS0246: The type or namespace name 'ClosedRealestateId' could
  not be found (are you missing a using directive or an assembly
  reference?)

However, I have referenced the project "RealestateScraper" and the class RealestateJobsDbContext&ClosedRealestateId exists in the "RealestateScraper" project root namespace which HAS been marked as using in the locations where the output marked the errors.
(like I previously stated, the project builds fine too when not publishing).
What could be the issue here?
I have cleaned&rebuilt but that doesn't seem to change anything.
Note: I'm not showing the code with the errors since it seems to serve no purpose as I am referencing the assemblies in the files correctly (using RealestateScraper;)

A: I was experiencing this as well- build only failed during publish. Turns out I was using the wrong password for the azure publish and for some reason I cannot explain it would show that the build failed and include some build errors. After correcting the password this was resolved.

A: Apparently in the RealestateScraper project I was referencing another project .dll at a location where it no longer existed. I updated the reference location and it fixed it.

A: In my case, I could not identify the error itself. I just changed the publish property "pre-compile". I UNchecked it and then I was able to publish my website

A: I had some compiler if-then statements in a class.  These worked okay when I did a local build, but when publishing they were not interpreted and caused build errors.  I refactored my code to remove the compiler directives and it now publishes.
Example:
#if SERVICE
using System.Web
#endif

Changed to:
using System.Web

A: unfortunately I have the same unresolved problem solution -prog a -prog b completes both the prog and the solution but when I go to publish it gives me error c0246 on using of the project b called in the project a
Help

A: I tried all of these solutions, and they might have contributed, but I was still getting the error.
I was tipped off by a warning.  I had to make this file not read-only within the project, then it worked.
\obj\Release\netcoreapp3.0\PubTmp\Out\web.config


text:
Q: Unusual DHCP behavior on Windows 7 Our work network router does DHCP in the 192.168.10.# range with gateway=192.168.10.1, behind a centurylink/qwest modem at 192.168.0.1.  Addresses are allocated starting with 100, so 192.168.10.100, 10.101, etc.
One computer on the network recently started showing an IP address of 10.0.1.13 with a gateway of 10.0.1.1 and can still see the internet fine.  A tracert of google shows what looks like another router in front of our normal router - here's an approximation:
tracert 8.8.8.8
10.0.1.1
192.168.10.1
192.168.0.1
qwest.net stuff
other stuff
eventually to 8.8.8.8, google

I can't figure out what is going on other than some weird virus that has installed a virtual network layer of some sort.  The network control panel still shows just two network ports and they are configured for normal DHCP allocation.
I ran netstat /b and don't see anything unusual, and have run a scan with MS Essentials that turned up clean.  We have done multiple power cycles, disabling the network adaptors, tried both network ports and get similar results (10.0.1.13 or 10.0.1.9)
Any ideas of what to try next?

A: It seems like someone plugged in a router in the network with a DHCP server which gives out the 10.0.1.1 range, and the WAN port is connected to the LAN in segment 192.168.10.x
Find the 2nd router and disable DHCP or completely remove the device from the network.
The reason for this conclusion is the fact that the traceroute goes through both network. Any device with just DHCP would cause internet to stop working. Because it is a router with separate network, find the device by following the physical wire from that pc to where it leads.


text:
Q: Can't link google play game services to an app because the client id is in use. However there is no app using that id I'm trying yo update a game on google play to support leaderboards and achievements. (https://play.google.com/store/apps/details?id=com.rightpedalstudios.dragonseason)
However, when I go to link the app I get the message "This client ID is globally unique and is already in use."
I've searched online for people who have had the same problem and the advice they are given is to delete the client ID in the developer console, and if the app has been deleted there then undelete it first. However, there is nothing in the console using the ID, nor is there any deleted apps. As far as I can tell there is no app using the client id.
I did find another person asking a similar question here that was never answered.
Failing to create client ID, due to duplication of signing fingerprint by another Android OAuth2 client
I also get the message "The signing fingerprint you specified is already used by another Android OAuth2 client." When I try to set up a client ID from the developer console. (I know I'm not meant to do that if I'm using google play games, I just wanted to check if it failed from there too.)
I've tried contacting google support, I was directed to the google API support, and then directed here.
Two other developers that have worked on this project could have somehow created a client ID. Although I have contacted them and neither of them recall creating one.
Is there anyway to find out where this client ID is being used?

A: You have to delete the client id in the Google API console (now confusingly renamed the Google Developers Console !). Then you can link the app to the game straight away. I have just done this, and it worked fine for me. I wanted to link an existing app to a different game, so I deleted both the debug and prod(release) definitions and was able to immediately link the app to the new game.
Note that for many of us, doing work on Google Play Game Services in the Google API console is a last resort - many of us have encountered Google related bugs in the past by doing this !
This image may help:


text:
Q: How can I check if the user input with the database information? I have a JavaScript programme that randomly selects an image of an object from the database and display that image to the user. The image is saved with the object name (i.e. apple.gif)
I am using the following code in order to check whether the user input response is the correct answer to the test or not:
However the code does not do anything. Could anyone let me know what the problem is please?

A: Look at your JavaScript console:

Uncaught ReferenceError: random_image_array is not defined

You made a typo. When you defined the variable you said images (with an s).

A: function checkUserInput() {
   var userInput = document.getElementById("textInput").value;
   var stringToCheckAgainst = random_image_array[num].split('.');
   //this splits the item at the array index into an array, like so. If the item is "apple.gif", the array reads ["apple", "gif"]
   if (userInput == stringToCheckAgainst[0]) {
      //user has inputted the correct string
      document.write("Correct!");
   } else {
      //user has inputted an incorrect string
      document.write("Incorrect response!");
   }
}

The above is a function. In order to use the function, you must call it.


text:
Q: How to create macro in sublime text 3 with saveAs and close file command? I need to change encoding of a lot of html files to UTF8 (from Windows 1252). I´m using Sublime text 3 on Windows 8. So I think creating macro will be very efficient, I need just two commands in that macro "Save with Encoding - UTF8" and "Close file". But when I´m trying to record macro these commands are not recorded. So I need to manually create json file with macro command but I don´t know how.

A: I'm not sure that this can be done with a macro maybe these commands are out of scope for a macro (eg a window command not a view command?), but I managed to make it work as a plugin…
Save the following as $PATH_TO_SUBLIME_DATA/Packages/SaveAs-UTF8.py
import sublime, sublime_plugin

class SaveAsUtf8Command(sublime_plugin.WindowCommand):
    def run(self):
        self.window.run_command("save", {"encoding": "utf-8" })
        self.window.run_command("close")

To trigger the command with 'Command Option Shift 8', add the following to your Sublime Text > Preferences > Keybindings - User file:
[
    { "keys": ["super+option+shift+8"], "command": "save_as_utf8"}
]

I've saved this as a gist if you prefer: https://gist.github.com/9505499


text:
Q: Property doesn't exist after initialization I have these properties in my view controller class:
@IBOutlet weak var flashCardView: FlashCard!

var originPoint: CGPoint!
var xFromCenter: Float = 0
var yFromCenter: Float = 0
let actionMargin: Double = 240
let rotationMax: Float = 1
let rotationStrength: Float = 320
let rotationAngle: Float = 3.14/8
var memories: [Memory] {
    if let loadedMemory = self.loadMemory() {
        return loadedMemory.sorted(by: {$0.strength < $1.strength})
    } else {
        let sampleMemory = Memory(masteryLevel: 1, algorithm: Algorithm.algorithm1.chooseAlgorithm(), forgetRatio: 0, lastStudyTime: Date(), front: #imageLiteral(resourceName: "Ideas-Blue"), back: #imageLiteral(resourceName: "Ideas-Yellow"))
        return [sampleMemory]
    }
}
var unfamiliarity: Int = 0

I set a breakpoint in viewDidLoad to inspect the values of them, but interestingly, every variable showed up in the debugger except the computed property - memories is missing, like this:

Question:
Why is it missing, shouldn't all properties of a class get initialized before viewDidLoad gets called?

A: Computed properties do not occupy space in memory. So there is no reason of getting them initialized. It will be computed when you access the property.

A:
shouldn't all properties of a class get initialized before viewDidLoad
  gets called?

No, referring to Swift Documentation - Properties:
Computed properties:

which do not actually store a value. Instead, they provide a getter
  and an optional setter to retrieve and set other properties and values
  indirectly.

Means that by definition, you cannot set a value for a computed property by default because simply its computed! (its value should be based on -let's say- other stored properties values).
Once you access (or "re-acceess") it, it should do the computation.
Hope this helped.


text:
Q: UDP Client - Exception in creating socketOnly one usage of each socket address (protocol/network address/port) is normally permitted I am creating a UDP client in my c# application.
labelEP = new System.Net.IPEndPoint(tempAdd, ethPortAddress);
recvMIUCmndsSocket = new UdpClient(labelEP);
Socket temp = recvMIUCmndsSocket.Client;
 //Allow broadcasts
temp.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);

Whenever i start my application it works fine. If there is any problem in my application, the application restarts on its own. Some times when an application restarts I am facing the exception :
"Only one usage of each socket address (protocol/network address/port) is normally permitted "
It seems to be the garbage collector didn't free the previous instance of udpclient socket. Could that happen?
Regards
Raju

A: Garbage collector would take care of disposing managed objects. As per my basic understanding, sockets are native windows objects and .net has provided managed wrappers around them. Also once my architect had told me that when we close a port or a socket, windows takes some time to close it. I think you are facing this issue because of that behavior of windows sockets.

A: I'm not entirely familiar with C#, but I have been doing some similar work in Java recently, and I discovered three things.
First, you need to close connections, even after error conditions. It can get a little messy, since (in Java, at least), some calls to clean up after yourself can generate exceptions.
Second, this explicit closing of connections lets the garbage collector do its job better. However, you don't really control when the GC runs, so you can't anticipate that the connection will be cleaned up and the socket ready for use again immediately. If you immediately try to reopen a connection, the socket might not be quite ready yet.
Third, the operating system is often involved in managing network connections and network resources. So just because you and your environment have released and cleaned up the resource doesn't mean the OS has (re)made it available yet.


text:
Q: how to click Background and something should happend? I want to click the Background of a layout (not clicking anywhere, for example in the top right) and then reproduce a sound, can i put an empty View and put an On Click to that? I think is not possible.
If is possible, there is a better way?
I want to put some invisible "buttons" at the Background because I will put an image Background with shapes, that's why It couldn't be anywhere.
Thanks and sorry for my english.

A: You can put a button on the right corner and apply an empty or simply transparent image as icon button.
In this way, you can choose a different behavior for each screen position.