text:
Q: Turn a growing 1D lattice of size $N(t)$ into a constant size lattice by change of variables I am studying some stochastic process (a voter model for example) on a finite size lattice of 1 dimension and of size $N_t$. However $N_t$ grows at rate $\lambda$ and can be represented as follows:
\begin{equation}
N_t=N_0+ \tilde{N}_t
\end{equation}
Where $N_0$ is the initial size of the lattice and $\tilde{N}_t$ follows a Poisson process, i.e.:
\begin{equation}
\mathbb{P}(N_t=k)=\frac{(\lambda t)^k}{k!} e^{-\lambda t}
\end{equation}
Although the growth process is independent from the dynamics of the studied model, it is a bit tricky to study the dynamics. I suspect it would be possible to perform some change variable from $t$ to $\tau$ such that $N(\tau)$ is now constant. Would this be possible?
Is there any classic literature on stochastic processes on growing lattices? There does not seem to be some well established key words so maybe someone knows more about it here... Thanks.


text:
Q: adding package-repositories to emacs I need to add various packages to my emacs installation. It comes with tromey as the only repository. The variable package-archives is not defined (!). I am running GNU Emacs version 24.3.1 on Linux. I set up the following code in my .emacs file:

    (when (>= emacs-major-version 24)
      (require 'package)
      (setq package-enable-at-startup nil)
      (setq package-archives '())
      (package-initialize)
      (add-to-list 'package-archives
                   '("melpa" . "http://melpa.milkbox.net/packages/") t)
      (add-to-list 'package-archives
                   '("gnu" . "http://elpa.gnu.org/packages/"))
      (add-to-list 'package-archives
                   '("marmalade" . "https://marmalade-repo.org/packages/"))
      (add-to-list 'package-archives
                   '("org" . "http://orgmode.org/elpa/") t)
      (add-to-list 'package-archives
                   '("tromey" . "http://tromey.com/elpa/") t)
      )

By default, without this code, the variable package-archives isn't defined. After running this code, it is, and contains the right values, but doesn't seem to have any effect. I verified that this variable is not customized anywhere.
The problem is that I don't get to see any packages from the various archives I added; Only from tromey. Obviously I'm doing something wrong, but this code is supposed to work from emacs version 24 and higher.
Can someone suggest how to set up my repositories properly?

A:
Everything worked well! What does that mean? That something in my .emacs file is conflicting with elpa?

That's exactly what it means.
Comment out half of your configuration (comment-dwim, bound to C-; by default, might be helpful here) and see if that fixes it. That will tell you which have contains the ELPA conflict. Repeat with the half that shows the problem to find which quarter is problematic, then again to find the eighth…
Pretty soon you'll find the cause, which might be a single sexp. Remove or adjust that, uncomment the rest of your config, and enjoy the plethora of packages that await.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PNG figures in black and white I'm trying to include a png figure and it works when I see it in dvi, but the ps comes in black and white.
If I compile directly to pdf there is no problem. However I'm using psTricks for a different figure, so I need to use ps first.
Any suggestions?

A: You have to convert your DVI file to PS using dvips -I c <filename> instead of just dvips <filename> (http://www.win.tue.nl/latex/faq.html#q16). The -I switch is used to select image options, the c stands for color, grayscale would be g (http://docs.miktex.org/manual/dvips.html).


text:
Q: Solving an LP with equalities by simplex method I have the following main program to be solved by simplex method.
$$Min \quad P=0.2x_1 + 0.5x_2 + 0.6x_3 + 0.1x_4 + 0.2x_5 + 0.3x_6 \\
\text{subject to: }  0.2x_1 + 0.3x_2 + 0.25x_3 \le 0.8 \\
\quad\quad\quad\quad 0.1x_4 + 0.4x_5 + 0.2x_6 \le 0.8 \\
x_1 + x_4 = 1 \\
x_2 + x_5 = 1 \\
x_3 + x_6 = 1
$$
whose standard form is:
$$Max \quad P = -0.2x_1 - 0.5x_2 - 0.6x_3 - 0.1x_4 - 0.2x_5 - 0.3x_6 \\
\text{subject to: }  0.2x_1 + 0.3x_2 + 0.25x_3 + u = 0.8 \\
\quad\quad\quad\quad 0.1x_4 + 0.4x_5 + 0.2x_6 + v = 0.8 \\
x_1 + x_4 = 1 \quad (1)\\
x_2 + x_5 = 1 \quad (2)\\
x_3 + x_6 = 1 \quad (3)
$$
According to some advice, I used the last three equations in the standard problem to eliminate three variables from other equations. I chose variables $x_1$, $x_2$ and $x_3$ to be eliminated in all other equations.
Therefore, I have the following program to be solved by simplex method:
$$Max \quad P = 0.1x_4 + 0.3x_5 + 0.3x_6 -1.3\\
\text{subject to: }  -0.2x_4 - 0.3x_5 - 0.25x_6 + u = 0.05 \\
\quad\quad\quad\quad 0.1x_4 + 0.4x_5 + 0.2x_6 + v = 0.8 \\
$$
After solving above problem with simplex method, I get these basic variables: $u=1.05$ and $x_6=4$. All other variables of above program are non-basic, hence equal zero.
The values of eliminated variables according to those equations are: $x_1=1$, $x_2=1$ and $x_3=-3$. The values of $x_3$ is negative which is not correct according to the general constraint of non-negative values of input variables of linear programs.
I expected to see $0 \le x_1,x_2, x_3, x_4, x_5, x_6 \le 1$ as I have the three equations (1), (2), (3).
Is there something wrong with my math or assumptions? All computations are done by a computer program I wrote.


text:
Q: Python: My Depth-Limited Search algorithm won't work new to Python.
I have implemented a Depth Limited Search Algorithm to find a route from S to G.  Where S is the starting position and G is the destination.
R represents a road while X represents an obstacle that we cannot pass through.
ADJ is a dictionary containing neighbouring paths from a given location.
So for S the neighbours are 2 and 6. 2 and 6 represents the neighbouring roads. I have not included X as X is an obstacle.  However, it cannot move diagonally if one of the directions composing the diagonal contains an X.

The problem is that when I run the code below my algorithm does not find a route and gets stuck forever until it exceeds the depth limit.
There is a route from S to G but my algorithm does not find it.
How do I resolve this error?
Thanks
Here is my code:
ADJ = {}
""""
SRRXG
RXRXR
RRRXR
XRXRR
RRRRX
"""
ADJ['S'] = ['2', '6']
ADJ['2'] = ['S', '3']
ADJ['3'] = ['2','8']
ADJ['G'] = ['10']
ADJ['6'] = ['S', '11']
ADJ['8'] = ['3', '13']
ADJ['10'] = ['G', '15']
ADJ['11'] = ['6', '12']
ADJ['12'] = ['11', '13', '17']
ADJ['13'] = ['8', '12']
ADJ['15'] = ['10', '20']
ADJ['17'] = ['12','22']
ADJ['19'] = ['20', '24']
ADJ['20'] = ['15','19']
ADJ['21'] = ['22']
ADJ['22'] = ['17','21','23']
ADJ['23'] = ['22', '24']
ADJ['24'] = ['19','23']
print (ADJ)
def dls(start, goal):
    depth = 0
    limit = 200
    OPEN=[]
    CLOSED=[]
    OPEN.append(start)
    while OPEN != []: # Step 2
        if depth<=limit:
            current = OPEN.pop()
            if current == goal:
                CLOSED.append(current)
                print("Goal Node Found")
                print(CLOSED)
                return True
            else:
                CLOSED.append(current)
                lst = successors(current)
                for i in lst:
                    OPEN.append(i)
                depth +=1
        else:
            print("Not found within depth limit")
            return False

    return False

def successors(city):
    return ADJ[city]

def test():
    start = 'S'
    goal = 'G'
    print("Starting a dls from " + start)
    print(dls(start, goal))

if __name__ == "__main__":
    test()

A: The issue is that you are not keeping a check of nodes already visited. For example you start from a node "S" and then go to its neighbors, you should mark it as visited and do a check while appending to the OPEN list, so that you don't try to come to it again. If you don't do it, your code will get stuck in infinite loop as you will keep on jumping between two nodes.
Further, there was some issue in the ADJ that you had created, particularly in '22'. I have tried to make minimal changes to your code(keeping the removed parts as comments), though there are several other places where it can be improved. Corrected code:
ADJ = {}
""""
SRRXG
RXRXR
RRRXR
XRXRR
RRRRX
"""
ADJ['S'] = ['2', '6']
ADJ['2'] = ['S', '3']
ADJ['3'] = ['2','8']
ADJ['G'] = ['10']
ADJ['6'] = ['S', '11']
ADJ['8'] = ['3', '13']
ADJ['10'] = ['G', '15']
ADJ['11'] = ['6', '12']
ADJ['12'] = ['11', '13', '17']
ADJ['13'] = ['8', '12']
ADJ['15'] = ['10', '20']
ADJ['17'] = ['12','22']
ADJ['19'] = ['20', '24']
ADJ['20'] = ['15','19']
ADJ['21'] = ['22']
ADJ['22'] = ['17','21','23']
ADJ['23'] = ['22', '24']
ADJ['24'] = ['19','23']
print (ADJ)
# keep track of visited nodes
visited = {str(i) : False for i in range(1,26)}
visited['S'] = False
visited['G'] = False

def dls(start, goal):
    depth = 0
    limit = 200
    OPEN=[]
    CLOSED=[]
    OPEN.append(start)
    visited["S"] = True
    while OPEN != []: # Step 2
        if depth<=limit:
            current = OPEN.pop()
            # visited[current] = False
            if current == goal:
                # CLOSED.append(current)
                print("Goal Node Found")
                # print(CLOSED)
                return True
            else:
                # CLOSED.append(current)
                lst = successors(current)
                for i in lst:
                    # try to visit a node in future, if not already been to it
                    if(not(visited[i])):
                        OPEN.append(i)
                        visited[i] = True
                depth +=1

        else:
            print("Not found within depth limit")
            return False

    return False

Further, you can write a function to calculate ADJ given the maze very easily, instead of hard coding it.


text:
Q: Python QT - Search the txt file and show the results in TableWidget Its simple as it can be, but I cant do it.
I have txt file which contains name,surname, mail and telephone number like that:
name surname phone mail
name surname phone mail
name surname phone mail

Everything is seperated with tabs and after the mail there is newline at the end of each line
Now I want to search the file for the specific name im searching and to show the results when I click the button Search in TableWidget (using python Qt).
Its simple, but I have some errors I cant resolve.
Thanks for the help.

A: You have two possible steps to accomplish here.

*

*Read the data into your model

*Interact with your tablewidget and your search field

To get your started, a simple and straightforward approach for reading in your data would be to use the csv module. You could also create a custom table model that would read directly from a csv file, but I think thats beyond our level right now.
Here is a simple way to get your text file into a data structure:
import csv

people = []
reader = csv.reader(open('people.txt'), delimiter='\t')
for row in reader:
    people.append(row)

Now people will contain all your lines in the form: (name, surname, email)
From here, you can populate your TableWidget. This is a really basic snippet that should give you the idea:
from PyQt4 import QtGui

rowCount = len(people)
colCount = max([len(p) for p in people])

tableWidget = QtGui.QTableWidget()
tableWidget.setRowCount(rowCount)
tableWidget.setColumnCount(colCount)

for row, person in enumerate(people):
    for column, value in enumerate(person):
        newItem = QtGui.QTableWidgetItem(value)
        tableWidget.setItem(row, column, newItem)

The colCount is just a little protection in case you have unbalanced amounts of fields on each line. Again this is just a general approach.
From here its a little open ended as to how you want to do the search. But what you could do is connect you search button to a method that handles the search. Keep in mind I am writing all this as just global functions. You would probably have your class, and be using self everywhere. But I am keeping it short and simple:
myButton.clicked.connect(search)

def search(*args, **kwargs):
    value = myLineEdit.text()
    items = tableWidget.findItems(value, QtCore.Qt.MatchContains)
    if items:
        # scroll to the first match?
        tableWidget.scrollToItem(items[0], tableWidget.PositionAtCenter)


text:
Q: Is there a program to solve The Yang–Mills Existence and Mass Gap problem similar to the Hamilton's program to solve Poincaré Conjecture? According to Wikipedia:

*

*"Hamilton's program was started in his 1982 paper in which he introduced the Ricci flow on a manifold and showed how to use it to prove some special cases of the Poincaré conjecture." (see Hamilton's program and solution)

*"By developing a number of new techniques and results in the theory of Ricci flow, Grigori Perelman was able to modify and complete Hamilton's program" (see Poincaré Conjecture).

My questions are:

*

*Is there a program to solve The Yang–Mills Existence and Mass Gap problem similar to the Hamilton's program to solve Poincaré Conjecture? That is, are there mathematical techniques/theories that have been able to solve parts of this problem and that have the potential, according to experts in the field, to solve the whole problem?

*If the answer to the last question is yes, which references should I read to learn these mathematical techniques/theories in depth?

A: Coming a bit late to the party, but since there is no answer, let me offer one.
Yes there is a program to make progress towards the YM problem, although with no guarantee of success in the end. The methods/part of mathematics that have the potential to lead to working this program out, that's called constructive quantum field theory (CQFT). To learn about it, the best (although not perfect) reference that I can recommend is the book "From Perturbative to Constructive Renormalization" by Vincent Rivasseau. A brief account is "Mode d'emploi de la théorie constructive des champs bosoniques (A user's guide to bosonic constructive field theory)" by Jérémie Unterberger, but it is in French.
The program of study:
Solve, in the order (of difficulty) stated below, the analogue of the YM construction and mass gap problem for the following two models.

*

*The two-dimensional Gross-Neveu model with large (but finite) number $N$ of components.

*The two-dimensional sigma-model, also with large $N$.

These two problems are within reach of existing CQFT methods. There is a very steep increase in difficulty from these two models to 4d YM, so there is no guarantee that if one solves these problems one would be able to also do YM. However, in my opinion, there is no way one can solve YM if one cannot solve the above two problems.
The YM Clay Millenium problem requires constructing the UV limit in infinite volume and showing a mass gap. There is a lighter version of that, which also essentially is a necessary milestone along the way. It is to look at the lattice problem
without tackling the UV limit. Namely, the question is to rigorously control the infinite volume limit on the unit lattice but at arbitrarily low temperature.
One often reads in the physics literature that there is no problem doing things rigorously on the lattice. This is false if one is talking about the infinite lattice. At high temperature, this is nontrivial but can be done using cluster expansions.
For YM and the sigma-model (Fermions also behave like compact-valued random variables) the random variables take values in compact spaces, so by a variant of Prokhorov's Theorem, one can construct subsequential infinite volume limits. However, these are almost useless. If one wants to study this infinite volume problem on the lattice, a top priority intermediate question that should be settled first is that of establishing ferromagnetic correlation inequalities. There is evidence that non-Abelian models like the $O(N)$ model (the lattice version of the sigma-model) or lattice gauge theories do satisfy correlation inequalities of ferromagnetic type.


text:
Q: accessing WCF session from aspx Is it possible to use the same session created on WCF service in a web application? any sample code to do this?

A: It is possible by setting the ASPCompatibityMode but you should never do this (access ASP.NET session inside a WCF service). I would recommend you having the ASP.NET application consuming this service to simply construct a POCO object containing all the necessary information and send it to the service so that the service is not strongly coupled to this session. Accessing an ASP.NET session inside a WCF service makes this service completely non-reusable. What if you wanted to call your service from a desktop application?

A: WCF session exists in absolutely different context - there is no relation between ASP.NET and WCF (unless you turn on AspNetCompatibility) = ASP.NET doesn't know about WCF and WCF doesn't know about ASP.NET. So if you want to share something between ASP.NET and WCF you must manually use something outside both of these technologies. It generally means some custom globally accessible (singleton) "session manager" and custom "session id" passed in each ASP.NET and WCF request.


text:
Q: Disable form Button I have the following form. The 'continue' button is meant to be disabled until all fields have been completed. I have tried this on jfiddle and the form works as intended, but on the actual .html file online it does not work. For example the button is always disabled even when the fields have been completed, any ideas?

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Payment Gateway</title>
    <link rel="stylesheet" type="text/css" href="ue1.css">
    <link rel="stylesheet" type="text/css" href="bootstrap.css">

                Accessibility Tools | Skip to Navigation | Skip to Content | Website A-Z | Sitemap | Report a Problem | Help

                Payment Gateway

                Process Order

                View Order Summary

                Help

        <form action="ue.html" method="post" id="nameform">

            <form role="form">

        <legend class="hd-default">Account information</legend>

                                        Username*:
                                        <input type="text" id="username" class="form-control" placeholder="Username" required="">

                                        Password*:
                                        <input type="text" id="password" class="form-control" placeholder="Password" required="">

                                        Re-enter Password*:
                                        <input type="text" id="password1" class="form-control" placeholder="Password"  required="">

            <form role="form">

                        <legend class="hd-default">Contact information</legend>

                                        Title
                                        <select name="title" id="title" class="form-control">
                                            <option value="1">Mr</option>
                                            <option value="2">Mrs</option>
                                              <option value="3">Miss</option>
                                                <option value="4">Dr</option>
                                                  <option value="5">Ms</option>
                                        </select>

                                          First    Names(s)*:
                                        <input type="text" id="firstname" class="form-control" placeholder="First Name(s)" required="">

                                        Surname*:
                                        <input type="text" id="surname" class="form-control" placeholder="Surname" required="">

                                        Email*:
                                        <input type="text" id="email" class="form-control" placeholder="Email" required="">

                                        Re-enter Email*:
                                        <input type="text" id="email1" class="form-control" placeholder="Email" required="">

                                </form>

      <div id="form3"

                               <input type="submit" id="continue" disabled value="Continue"/>

                    </fieldset>

            </form>

A: Wrapping your code in document.ready might help.
    $(document).ready(function(){
    $('#username, #password, #password1, #email, #email1, #title, #firstname, #surname').bind('keyup', function() {
    if(allFilled()) $('#continue').removeAttr('disabled');
    });

    function allFilled() {
    var filled = true;
    $('body input').each(function() {
    if($(this).val() == '') filled = false;
    });
    return filled;
    }
});

If it's WordPress, be aware that you can't use $ for jQuery. You have to use jQuery('body input') instead, or wrap you code in the following:
    $(function(){
    $(document).ready(function(){
        $('#username, #password, #password1, #email, #email1, #title, #firstname, #surname').bind('keyup', function() {
        if(allFilled()) $('#continue').removeAttr('disabled');
        });

        function allFilled() {
        var filled = true;
        $('body input').each(function() {
        if($(this).val() == '') filled = false;
        });
        return filled;
        }
    });
})(jQuery);

Are you seeing any errors in the console?

A: Place your code in $(document).ready(function(){ // here }) function as below
$(document).ready(function(){

$('#username, #password, #password1, #email, #email1, #title, #firstname, #surname').bind('keyup', function() {
    if(allFilled())
        $('#continue').removeAttr('disabled');
});

function allFilled() {
var filled = true;
$('body input').each(function() {
    if($(this).val() == '') filled = false;
});
return filled;
}

});

A: I would try:
$('#continue').prop('disabled',!allFilled());

instead of
if(allFilled()) $('#continue').removeAttr('disabled');

Users may fill out all fields, and then delete one.


text:
Q: Decoding nested JSON with Swift 4 JSON =
{
"html_attributions": [],
"results": [
               {
                  "geometry": {},
                   "name": "Cruise Bar, Restaurant & Events",
                   "vicinity": "Circular Quay W, Sydney"
                },
                {}
],
"status": "OK"
}

How do I retrieve name if it is nested within results?

A: Sam Try this i write sample code in playground using your Json. root.results will give you array of dictionary, you can easily traverse and get your desired name from it.
import UIKit

struct Root: Codable {
    let results: [Results]?

    private enum CodingKeys: String, CodingKey {
    case results = "results"
   }

}

struct Results: Codable {
   let name: String?
   let vicinity: String?
}

let url = Bundle.main.url(forResource: "data", withExtension: "json")
let data = NSData(contentsOf: url!)

do {
      let root = try JSONDecoder().decode(Root.self, from: data as! Data)

      if let name = root.results?.first?.name {
          print(name)
      }

} catch let error as NSError {

    print(error.description)
}

Here is the json i have used.
{
"results": [{
            "name": "Cruise Bar, Restaurant & Events",
            "vicinity": "Circular Quay W, Sydney"
            }]
}

A: You can do it like that:
Model:
 import Foundation
struct HtmlInitial: Codable {
    let results: [Result]?
    let status: String

    enum CodingKeys: String, CodingKey {
        case results, status
    }
}

struct Result: Codable {
    let name, vicinity: String?
}

extension HtmlInitial {
    init(data: Data) throws {
        self = try JSONDecoder().decode(HtmlInitial.self, from: data)
    }
}

use model Like that :
let url = Bundle.main.url(forResource: "APIResponse", withExtension: "json")!

if  let data = try? Data.init(contentsOf: url) ,
    let initial = try? HtmlInitial.init(data: data),
    let result = initial.results?[0] {
    print(result.name)
}


text:
Q: R: formating a dataframe in two specific ways based on separation and matching I have a df1 like this:
    A                 B
1 xxx      B2341; A3456
2 yyy B2341; CC6x; GG63
3 zzz              CC6X
4 www              GG63
5 kkk              5634

To obtain df1, I use the following commands
 df1 <- data.frame(A=c("xxx", "yyy", "zzz", "www", "kkk"), B=c("B2341; A3456", "B2341; CC6x; GG63", "CC6X", "GG63", "5634"))

In step one, I want to separate all the items (separated by ; and a space) in column B to table like this.  As I want to do some analysis based on this table format.  However, since there are uneven items for each cells.  I would like to ask fo your help to get it done.
xxx B2341
xxx A3456
yyy B2341
yyy CC6X
yyy GG63
zzz CC6X
www GG63
kkk 5634

In step two, I want to get a table based on the matching result of 2nd column of df2, i.e. both xxx and yyy got B2341 in 2nd column of df2.  yyy and zzz also got CC6X; yyy and www also got GG63.
So, I would like to have a df with two columns that show matching rows, such as:
xxx yyy
yyy zzz
yyy www

Please kindly help to instruct how to get the two dataframes based on my df1 with R in a smarter way.  Thank you.

A: Step One:
library(reshape)
x <- melt((strsplit(as.character(df1$B), "; ")))
x <- data.frame("A"=df1[x$L1,1],"B"=x$value)

x:
  value L1 match
1 B2341  1   xxx
2 A3456  1   xxx
3 B2341  2   yyy
4  CC6x  2   yyy
5  GG63  2   yyy
6  CC6X  3   zzz
7  GG63  4   www
8  5634  5   kkk

Step 2:
y <- unique(merge(x,x[duplicated(x$B),],by="B")[2:3])
y[y$A.x != y$A.y,]

y:
  A.x A.y
1 xxx yyy
3 yyy www

Note: step 2 doesn't come out exactly as you specified because I believe you mistyped "CC6X" as "CC6x", if you wanted it to ignore capitalization I would recommend  x$B <- tolower(x$B)

A: This looks like a job for the foreach package. I use it in some way for everything I write in R.
library(foreach)
foreach(a=df1$A, b=as.character(df1$B), .combine=rbind) %do% {
    data.frame(A=a, B=strsplit(b, "; ")[[1]])
}

Output:
    A     B
1 xxx B2341
2 xxx A3456
3 yyy B2341
4 yyy  CC6x
5 yyy  GG63
6 zzz  CC6X
7 www  GG63
8 kkk  5634


text:
Q: how to create methods from arrays or hashes in perl6 I am trying to add new methods to an object dynamicaly.
Following code works just fine:
use SomeClass;

my $obj = SomeClass.new;
my $blah = 'ping';
my $coderef = method { say 'pong'; }

$obj.^add_method($blah, $coderef);

$obj.ping;

this prints "pong" as expected, whereas the following will not work as expected:
use SomeClass;

my $obj = SomeClass.new;
my %hash = one => 1, two => 2, three => 3;

for %hash.kv -> $k, $v {
    my $coderef = method { print $v; }
    $obj.^add_method($k, $coderef);
}

$obj.one;
$obj.two;
$obj.three;

will print either 111 or 333.
Could anyone explain what i am missing or why the results are different from what i was expecting?

A: Rakudo had some issues with accidentally sharing lexical variables over-eagerly, which might have caused your problem (the code reference closes over $v). With the current development version of Rakudo (and thus in the next release, and in the "Rakudo Star" release too), this code works:
class SomeClass { };

my $obj = SomeClass.new;
my %hash = one => 1, two => 2, three => 3;

for %hash.kv -> $k, $v {
    my $coderef = method { say $v; }
    $obj.^add_method($k, $coderef);
}

$obj.one;
$obj.two;
$obj.three;

Output:
1
2
3

Note that whitespace between method name and parenthesis is not allowed.


text:
Q: Filtering the item from the string (list) in Dataframe I am trying to find the county from all the list in my dataframe.
My dataframe looks like:
address_df

output:
   address

1   (4070, Halleck Street, Emeryville, Alameda Cou...

2   (Rancho Road, Yuba County, California, 95961, ...

3   (Jasper Lane, Yuba County, California, 95692, ...

4   (Yuba County, California, 95692, United States...

From this, I want to get all the element with the word "county"
For example, the output would be:
county

Alameda County

Yuba County

Yuba County

Yuba County

I first tried converting the string to the list but then I realized that the index of each is different that I cannot just simply take out the county using indexes.
Help would be appreciated!!

A: IIUC this is what you want:
address_df[address_df["address"].str.contains("county", case = False)]

A: Here is a solution that converts the dataframe to a list, extracts the counties and creates a new dataframe:
import pandas as pd

df = pd.DataFrame({'address':["(4070, Halleck Street, Emeryville, Alameda County)","(Rancho Road, Yuba County, California, 95961)",
 "(Jasper Lane, Yuba County, California, 95692)", "(Yuba County, California, 95692, United States)"]})

lst = df.to_numpy().tolist()
counties = []
for address in lst:
    address_parts = address[0].split(",")
    for part in address_parts:
        if 'County' in part:
            c = part.replace('(','').replace(')','').lstrip(' ').split(' ')
            counties.append(c[0])
counties_df = pd.DataFrame(counties, columns= ['counties'])

print(counties_df)

#output:
  counties
0  Alameda
1     Yuba
2     Yuba
3     Yuba


text:
Q: Multiple GET under a single resource: REST API I'm trying to create two GET requests which are linked with each other, that is, one is a child of the other. Please have a look at the below code:
@GET
@QueryParam("{customerId}")
  public List<customerModel> getCustomers(@QueryParam("customerId") Long customerId) {
if (customerId== null || customerId== 0)
  throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("400: customerId cannot be null!").build());
try {
   ......
   ......
  return findCustomer(customerId);
} catch (Exception e) {
  log.error("Exception occurred when fetching the master detail customerId:" + customerId+", error :"+e.getMessage(), e);
  throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity("......").build());
}
  }

@GET
@Path("{customerId}/moreInfo")
  public List<customerInfoModel> getCustomerInfo(@PathParam("customerId") Long customerId) {
    if (customerId== null || customerId== 0)
      throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("customerId cannot be null").build());
try {
  .....
  .....
  return getCustomerInfo(customerId);
} catch (Exception e) {
  log.error("Exception occurred when fetching the customer detail customerId:" + e.getMessage(), e);
  throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity("....").build());
}
  }

If we notice, both of the GET calls are doing the same initial and logging work. The only difference is the method calls. Is there a way to write the same code only calling different function depending on the path?

A: You could extract some methods. One for ID checking. One for logging errors.
public interface IdChecker {
    public void checkId(Long id);
}

public class CustomerWebService extends ... implements IdChecker {

    @Override
    public void checkId(Long id) {
        if (id == null || id == 0)
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("400: customerId cannot be null!").build());
    }

    private void logMessage(Exception e, String reason) {
        log.error(String.format("Exception occurred when %s", reason), e);
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity("......").build());
    }

    @GET
    @QueryParam("{customerId}")
    public List<customerModel> getCustomers(@QueryParam("customerId") Long customerId) {
        checkId(customerId);
        try {
           ......
           ......
          return findCustomer(customerId);
        } catch (Exception e) {
            String action = "fetching the master detail customerId:" + customerId;
            logMessage(e, action);
        }
    }

    @GET
    @Path("{customerId}/moreInfo")
    public List<customerInfoModel> getCustomerInfo(@PathParam("customerId") Long customerId) {
        checkId(customerId);
        try {
          .....
          .....
          return getCustomerInfo(customerId);
        } catch (Exception e) {
            String action = "fetching the customer detail customerId:" + customerId;
            logMessage(e, action);
        }
    }


text:
Q: compact mapper part files I have a mapreduce job that exports the plain text of an hbase table. I'm emulating the Export class that ships with hbase and not running any reducers. In addition, I'm just writing an empty String for the key. Something like this:
public void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException {
    List<Cell> cells = value.listCells();
    for(Cell cell : cells) {
        context
            .write(new Text(""), new Text(CellUtil.cloneValue(cell)));
    }
}

This works fine, except I'm at the mercy of however many splits there are in the hbase table with regard to the number of output map files (e.g. part-m-NNNNN).
Is there a way to combine the output map files in the mapreduce job?
I've considered using a random integer between 1-50 for the key and then using a reducer that then strips the key before writing out to HDFS, but this seems like a hack.

A: Irrespective of your input, I understand that you want to merge all the map outputs. Below are the options.

*

*getmerge shell command - This will give the merged file to local directory.

*Make input not splittable, so only one mapper runs and one mapper output - Since you are reading HBase, this might not be a good option to have a single mapper do the entire work.

*Write a reducer and set map reduce to have only one reducer, which is what you are doing.

Given your link with HBase, 1,3 are good options. Not sure why you consider it as Hack. You can use row key as mapper output key rather than random integer.


text:
Q: Is the memory of compiled/eval'ed procedures garbage-collected in Chez Scheme? Multiple, perhaps most, language implementations that include a compiler at runtime neglect to garbage-collect discarded code (See, for example julia, where this leads to memory leaks in applications like genetic-programming)
My preliminary tests indicate that Chez Scheme does not leak memory here, but I would like to know with greater certainty, since I don't even know if f and g actually get compiled. (The old mantra: "Tests can only prove the presence of bugs, not their absence")

The test I tried: f and g call each other, and their definitions get replaced at runtime.
(define f)
(define g)

(define (make-f x)
  (eval `(set! f (lambda (y)
           (if (> y 100)
             (+ (remainder ,x 3) (g y))
             (+ y 1))))))

(define (make-g x)
  (eval `(set! g (lambda (y)
           (if (< y 10)
             (+ (remainder ,x 5) (f y))
             (div y 2))))))

(define (make-and-run-f n)
  (begin
    (make-f 1)
    (make-g 1)
    (let loop ((i 0) (acc 0))
      (if (> i n)
        acc
        (begin
            (make-f i)
            (make-g i)
            (loop (+ i 1) (+ acc (f 33))))))))

(time (make-and-run-f 1000000)) ; runs in 10 min and negligible memory

A: Given the importance of both procedures and garbage collection to Scheme, I would be surprised if Chez Scheme did not try to garbage collect any dynamically created objects. The R6RS Standard says [emphasis mine]:

All objects created in the course of a Scheme computation, including procedures and continuations, have unlimited extent. No Scheme object is ever destroyed. The reason that implementations of Scheme do not (usually!) run out of storage is that they are permitted to reclaim the storage occupied by an object if they can prove that the object cannot possibly matter to any future computation.

A procedure is an object, and any object may be garbage collected if the implementation can prove that the computation will not need it again. This is not a requirement, but that goes for any object, not just for procedures.
The Chez Scheme manual seems definitive, though (Chez Scheme Version 9 User's Guide, p. 82):

Since  all  Scheme  objects,  including  code  objects,  can  be  relocated  or  even  reclaimed  by the  garbage  collector....

In the 1990s Kent Dybvig wrote a paper together with David Eby and Carl Bruggeman which may be of interest here, called Don't Stop the BIBOP: Flexible and Efficient Storage Management for Dynamically Typed Languages, which describes the garbage collection strategy implemented in Chez Scheme. In the paper some time is spent discussing "code objects" and in particular how they are segregated and treated differently during the garbage collection process (since they may contain pointers to other objects).


text:
Q: Getting Error in Angular 1 due to indentation I am new with Angular JS and trying to learn. Tried writing a Provider, which is behaving in a strange manner and throwing an error. Could you please help identify the cause of error.
Here is the code which is working fine:
myapp.provider('Testing',function(){
return {
    $get: function() {
        return          {
            add: function(a,b){return a+b;}
        };
    }
};
});

And below is the code which is not working fine:
myapp.provider('Testing',function(){
return {
    $get: function() {
        return
        {
            add: function(a,b){return a+b;}
        };
    }
};
});

The Error due to second snippet:

Uncaught SyntaxError: Unexpected token (

The error is pointing to this statement: add: function(a,b){return a+b;}
The only difference in the two code snippets is the placement of "{" for the return statement inside the function for $get definition.
Is there any valid reason for why the placement of "{" should matter.

A: Yes, the placement of "{" after return matters.
It is a default JavaScript behavior to close a statement automatically at the end of a line. So,
return
        {
            add: function(a,b){return a+b;}
        };

The function will return undefined and the next parentheses will be act as  Unexpected token
return ;
            {
                add: function(a,b){return a+b;}
            };


text:
Q: How to change app background except textview's background? I want change background for whole app except textviews.
So, I change style.xml
<item name="android:background">@color/colorRed</item>

But textviews change background too. For example, toast text appear on red background.  As I understand, default textview background is transparent. Is there posibilitiy to change background without textviews?

A: Just add a background (android:background) to the text view on the xml file, like this
<TextView
    android:background="android.R.color.white"

That background will not change because it's fixed.


text:
Q: set overflow hidden only to parent div I have sidebar menu. #menu li a  have a  transform: scale(1.1)
I want to scale text and Icons inside li and keep it width same
I tried overflow:hidden but sub menu is not showing either
any help?

.page-container {
    min-width: 1260px;
    position: relative;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    margin: 0px auto;
}

.content {
    max-width: 800px;
    min-width: 600px;
    display: block;
    padding: 50px;
    margin: 50px auto;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
    background-color: #ffffff;
    overflow: hidden;
}

.page-container.sidebar-collapsed {
    padding-right: 65px;
    transition: all 100ms linear;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed-back {
    padding-right: 280px;
    transition: all 100ms linear;
}

.page-container.sidebar-collapsed .sidebar-menu {
    width: 65px;
    transition: all 100ms ease-in-out;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed-back .sidebar-menu {
    width: 280px;
    transition: all 100ms ease-in-out;
}

.page-container.sidebar-collapsed .sidebar-icon {
    transition: all 300ms ease-in-out;
}

.page-container.sidebar-collapsed-back .sidebar-icon {
    transition: all 300ms ease-in-out;
}

.page-container.sidebar-collapsed .logo {
    padding: 21px;
    height: 136px;
    box-sizing: border-box;
    transition: all 100ms ease-in-out;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed-back .logo {
    width: 100%;
    padding: 21px;
    height: 136px;
    box-sizing: border-box;
    transition: all 100ms ease-in-out;
}

.page-container.sidebar-collapsed #logo {
    opacity: 0;
    transition: all 200ms ease-in-out;
}

.page-container.sidebar-collapsed-back #logo {
    opacity: 1;
    transition: all 200ms ease-in-out;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed #menu span {
    opacity: 1;
    transition: all 50ms linear;
    position:relative;
    top:5px;
    right:10px;

}

.page-container.sidebar-collapsed-back #menu span {
    opacity: 1;
    transition: all 200ms linear;
    transition-delay: 300ms;
    top: 17px;
    right: 75px;
    position: absolute;

}

.sidebar-menu {
    position: fixed;
    float: left;
    width: 280px;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: #303641;
    color: #aaabae;
    font-family: "Segoe UI";
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.5);
    z-index: 1;
}

#menu {
    list-style: none;
    padding: 0;
    margin: 0 0 20px;
}

#menu li {
    position: relative;
    margin: 0;
    font-size: 12px;
    border-bottom: 1px solid rgba(69, 74, 84, 0.7);
    padding: 0;

}

#menu li ul {
    opacity: 0;
    height: 0px;
}

a:hover {
    transition: all 200ms ease-in-out;
}

#menu li a {
    text-decoration: none;
    font-style: normal;
    font-weight: 400;
    position: relative;
    display: block;
    padding: 10px 15px;
    color: #FFFFFF;
    white-space: nowrap;
    z-index: 2;
    transition: 200ms;
}

#menu li a:hover {
    color: #ffffff;
    background-color: #333944;
    transition: all 250ms ease-in-out;
    transform: scale(1.3);

}

#menu li.active > a {
    background-color: #2b303a;
    color: #ffffff;
}

#menu ul li {
    background-color: #2b303a;
}

#menu ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

#menu li ul {
    position: absolute;
    visibility: hidden;
    right: 100%;
    top: -1px;
    background-color: #2b303a;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.1s linear;
    border-top: 1px solid rgba(69, 74, 84, 0.7);
}

#menu li:hover > ul {
    visibility: visible;
    opacity: 1;
}

#menu li li ul {
    right: 100%;
    visibility: hidden;
    top: -1px;
    opacity: 0;
    transition: opacity 0.1s linear;
}

#menu li li:hover ul {
    visibility: visible;
    opacity: 1;
}

#menu .fa {
    margin-right: 5px;
    font-size: 30px;
}

.logo {
    width: 100%;
    padding: 21px;
    box-sizing: border-box;
    height: 136px;
}

.sidebar-icon {
    position: relative;
    right: -6px;
    float: right;
    border: 1px solid #454a54;
    text-align: center;
    line-height: 1;
    font-size: 18px;
    padding: 6px 8px;
    border-radius: 3px;
    color: #FFFFFF;
    background-clip: padding-box;
    text-shadow: 4px 4px 6px rgba(0, 0, 0, 0.4);
}

first

second

 Facebook

 Twitter

 Pinterest

blog

settings

jsFiddle

A:

.page-container {
    min-width: 1260px;
    position: relative;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    margin: 0px auto;
}

.content {
    max-width: 800px;
    min-width: 600px;
    display: block;
    padding: 50px;
    margin: 50px auto;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
    background-color: #ffffff;
    overflow: hidden;
}

.page-container.sidebar-collapsed {
    padding-right: 65px;
    transition: all 100ms linear;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed-back {
    padding-right: 280px;
    transition: all 100ms linear;
}

.page-container.sidebar-collapsed .sidebar-menu {
    width: 65px;
    transition: all 100ms ease-in-out;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed-back .sidebar-menu {
    width: 280px;
    transition: all 100ms ease-in-out;
}

.page-container.sidebar-collapsed .sidebar-icon {
    transition: all 300ms ease-in-out;
}

.page-container.sidebar-collapsed-back .sidebar-icon {
    transition: all 300ms ease-in-out;
}

.page-container.sidebar-collapsed .logo {
    padding: 21px;
    height: 136px;
    box-sizing: border-box;
    transition: all 100ms ease-in-out;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed-back .logo {
    width: 100%;
    padding: 21px;
    height: 136px;
    box-sizing: border-box;
    transition: all 100ms ease-in-out;
}

.page-container.sidebar-collapsed #logo {
    opacity: 0;
    transition: all 200ms ease-in-out;
}

.page-container.sidebar-collapsed-back #logo {
    opacity: 1;
    transition: all 200ms ease-in-out;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed #menu span {
    opacity: 1;
    transition: all 50ms linear;
    position:relative;
    top:5px;
    right:10px;

}

.page-container.sidebar-collapsed-back #menu span {
    opacity: 1;
    transition: all 200ms linear;
    transition-delay: 300ms;
    top: 17px;
    right: 75px;
    position: absolute;

}

.sidebar-menu {
    position: fixed;
    float: left;
    width: 280px;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: #303641;
    color: #aaabae;
    font-family: "Segoe UI";
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.5);
    z-index: 1;
}

#menu {
    list-style: none;
    padding: 0;
    margin: 0 0 20px;
    overflow: hidden;
}

#menu li {
    position: relative;
    margin: 0;
    font-size: 12px;
    border-bottom: 1px solid rgba(69, 74, 84, 0.7);
    padding: 0;

}

#menu li ul {
    opacity: 0;
    height: 0px;
}

a:hover {
    transition: all 200ms ease-in-out;
}

#menu li a {
    text-decoration: none;
    font-style: normal;
    font-weight: 400;
    position: relative;
    display: block;
    padding: 10px 15px;
    color: #FFFFFF;
    white-space: nowrap;
    z-index: 2;
    transition: 200ms;
}

#menu li a:hover {
    color: #ffffff;
    background-color: #333944;
    transition: all 250ms ease-in-out;
    transform: scale(1.3);

}

#menu li.active > a {
    background-color: #2b303a;
    color: #ffffff;
}

#menu ul li {
    background-color: #2b303a;
}

#menu ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

#menu li ul {
    position: absolute;
    visibility: hidden;
    right: 100%;
    top: -1px;
    background-color: #2b303a;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.1s linear;
    border-top: 1px solid rgba(69, 74, 84, 0.7);
}

#menu li:hover > ul {
    visibility: visible;
    opacity: 1;
}

#menu li li ul {
    right: 100%;
    visibility: hidden;
    top: -1px;
    opacity: 0;
    transition: opacity 0.1s linear;
}

#menu li li:hover ul {
    visibility: visible;
    opacity: 1;
}

#menu .fa {
    margin-right: 5px;
    font-size: 30px;
}

.logo {
    width: 100%;
    padding: 21px;
    box-sizing: border-box;
    height: 136px;
}

.sidebar-icon {
    position: relative;
    right: -6px;
    float: right;
    border: 1px solid #454a54;
    text-align: center;
    line-height: 1;
    font-size: 18px;
    padding: 6px 8px;
    border-radius: 3px;
    color: #FFFFFF;
    background-clip: padding-box;
    text-shadow: 4px 4px 6px rgba(0, 0, 0, 0.4);
}

first

second

 Facebook

 Twitter

 Pinterest

blog

settings

#menu {
    list-style: none;
    padding: 0;
    margin: 0 0 20px;
    overflow: hidden;
}

A: I inserted a container between you a tags that show the background and the text/icon content. I used a div because your spans are already so styled.
I added the container to first and second only, just to demonstrate the sublist still shows.
look for your a:hover selector changed to a:hover .expandable in the styles.

div.expandable {
    display: inline-block;
}

.page-container {
    min-width: 1260px;
    position: relative;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    margin: 0px auto;
}

.content {
    max-width: 800px;
    min-width: 600px;
    display: block;
    padding: 50px;
    margin: 50px auto;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
    background-color: #ffffff;
    overflow: hidden;
}

.page-container.sidebar-collapsed {
    padding-right: 65px;
    transition: all 100ms linear;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed-back {
    padding-right: 280px;
    transition: all 100ms linear;
}

.page-container.sidebar-collapsed .sidebar-menu {
    width: 65px;
    transition: all 100ms ease-in-out;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed-back .sidebar-menu {
    width: 280px;
    transition: all 100ms ease-in-out;
}

.page-container.sidebar-collapsed .sidebar-icon {
    transition: all 300ms ease-in-out;
}

.page-container.sidebar-collapsed-back .sidebar-icon {
    transition: all 300ms ease-in-out;
}

.page-container.sidebar-collapsed .logo {
    padding: 21px;
    height: 136px;
    box-sizing: border-box;
    transition: all 100ms ease-in-out;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed-back .logo {
    width: 100%;
    padding: 21px;
    height: 136px;
    box-sizing: border-box;
    transition: all 100ms ease-in-out;
}

.page-container.sidebar-collapsed #logo {
    opacity: 0;
    transition: all 200ms ease-in-out;
}

.page-container.sidebar-collapsed-back #logo {
    opacity: 1;
    transition: all 200ms ease-in-out;
    transition-delay: 300ms;
}

.page-container.sidebar-collapsed #menu span {
    opacity: 1;
    transition: all 50ms linear;
    position:relative;
    top:5px;
    right:10px;

}

.page-container.sidebar-collapsed-back #menu span {
    opacity: 1;
    transition: all 200ms linear;
    transition-delay: 300ms;
    top: 17px;
    right: 75px;
    position: absolute;

}

.sidebar-menu {
    position: fixed;
    float: left;
    width: 280px;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: #303641;
    color: #aaabae;
    font-family: "Segoe UI";
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.5);
    z-index: 1;
}

#menu {
    list-style: none;
    padding: 0;
    margin: 0 0 20px;
}

#menu li {
    position: relative;
    margin: 0;
    font-size: 12px;
    border-bottom: 1px solid rgba(69, 74, 84, 0.7);
    padding: 0;

}

#menu li ul {
    opacity: 0;
    height: 0px;
}

a:hover {
    transition: all 200ms ease-in-out;
}

#menu li a {
    text-decoration: none;
    font-style: normal;
    font-weight: 400;
    position: relative;
    display: block;
    padding: 10px 15px;
    color: #FFFFFF;
    white-space: nowrap;
    z-index: 2;
    transition: 200ms;
}

#menu li a:hover .expandable {
    color: #ffffff;
    background-color: #333944;
    transition: all 250ms ease-in-out;
    transform: scale(1.3);

}

#menu li.active > a {
    background-color: #2b303a;
    color: #ffffff;
}

#menu ul li {
    background-color: #2b303a;
}

#menu ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

#menu li ul {
    position: absolute;
    visibility: hidden;
    right: 100%;
    top: -1px;
    background-color: #2b303a;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.1s linear;
    border-top: 1px solid rgba(69, 74, 84, 0.7);
}

#menu li:hover > ul {
    visibility: visible;
    opacity: 1;
}

#menu li li ul {
    right: 100%;
    visibility: hidden;
    top: -1px;
    opacity: 0;
    transition: opacity 0.1s linear;
}

#menu li li:hover ul {
    visibility: visible;
    opacity: 1;
}

#menu .fa {
    margin-right: 5px;
    font-size: 30px;
}

.logo {
    width: 100%;
    padding: 21px;
    box-sizing: border-box;
    height: 136px;
}

.sidebar-icon {
    position: relative;
    right: -6px;
    float: right;
    border: 1px solid #454a54;
    text-align: center;
    line-height: 1;
    font-size: 18px;
    padding: 6px 8px;
    border-radius: 3px;
    color: #FFFFFF;
    background-clip: padding-box;
    text-shadow: 4px 4px 6px rgba(0, 0, 0, 0.4);
}

first

second

 Facebook

 Twitter

 Pinterest

blog

settings


text:
Q: Can Java's CountDownLatch be used from a passive class rather than a thread? So I am working on this program that simulates a day at work and each worker is its own thread. I'm trying to implement meetings where the workers attend meetings but the meetings do not start until everyone that is supposed to be at the meeting has arrived. So I have this method for attending the meeting.
public void attendMeeting(Employee worker){
    this.cdStart.countDown();
    worker.meetingWait();
    try {
        this.cdStart.await();
        worker.meetingStart(this.length);
        if(this.attendees.get(0).equals(worker)){
            this.room.exit();
        } // end if

    } // end try
    catch (InterruptedException err) {
        // Do Nothing

    } // end catch

} // end method attendMeeting

The worker parameter being an instance of the Employee class that extends Thread and this.cdStart is the CountDownLatch. However, when running this with a meeting of four employees, only one employee seems to be able to get in, decrement the count, and hit the await() call. None of the other worker threads seem to be able to enter it. I did notice that a lot of the online examples of use pass the CountDownLock object to the threads themselves to handle. Is there a reason why this would not work instead?

A: I am assuming you are having a single thread pass in an Employee Thread object.  That single thread will be waiting indefinitely until the N number of parties arrive (you need an individual thread for each Employee instance aside from the Employee thread).  This means that if only one thread is continuously passing the Employee/Thread  you will never get more then one Employee waiting at the meeting.
This thread should instead, at best, signal the Employee threads to attend the Meeting.
You should have the latch in the Meeting class and have them await on that latch.  This also requires a slight restructure of the way it works.
You pass the Meeting instance into the Employee to have that thread wait.
    public Employee extends Thread{

     //define this at some point whether in constructor or a
     //means of notifying the thread to attend the meeting
      private Meeting meeting;

      public void run(){
          //do some stuff until this employee is ready to go  to a meeting

         meeting.waitForAllOthersToArrive();
      }

    }

   public class Meeting{
     CountDownLatch latch =  new CountDownLatch(numberOfEmployees);

     public void waitForAllOthersToArrive(){
        latch.countDown();
        latch.await();
     }
   }

What I would suggest for this however is a CylicBarrier.  Though you wouldn't be re using it, the way the CyclicBarrier works fits better what you're trying to do, the Meeting class would then look like
 public class Meeting{
     CylicBarrier barrier = new CylicBarrier(numberOfEmployees);

     public void waitForAllOthersToArrive(){
         barrier.await(); //when await() is called numberOfEmployees then all waiting threads will awake
     }
 }


text:
Q: How can I take input from a pipe in Python and immediately output it? I would like to write a program that can take input piped to it, manipulate it, and output it immediately.  It seems that no matter what various things I try (using stdout.write rather than print, explicitly flushing stdout, setting stdin to be unbuffered), the output seems to be delayed until the input program is closed.
Example input script:
import sys
import time

sys.stdout.write('1\n')
sys.stdout.flush()

time.sleep(3)

sys.stdout.write('2\n')
sys.stdout.flush()

Example output script:
import sys
import time

for line in sys.stdin:

    print time.time()

    sys.stdout.write(line)
    sys.stdout.flush()

If I run this:
python input.py | python output.py

I get something like this:
1428023794.99
1
1428023794.99
2

Clearly the lines are making it to the second program at the same time.  I've also tried running the second python script with the -u flag to unbuffer stdin, but get the same output.
How can I make my program pulling the text from stdin output the text immediately?


text:
Q: Download BLOBs from Azure What is the best way and the best practice to download large BLOBs from the Azure storage?

*

*I want to use Shared Access Signature or Shared Access Policy to make a local copy of BLOBs.

*The estimated BLOB size is 500 MB to 1 GB

*Internet connections vary from 250Kb to 4Mb

A: In case of REST API use the HTTP request header
In case of Storage Client Library for .NET use DownloadRangeToStream

A: The best way depends upon your situation. Is there a specific reason preventing you from not to doing something along the lines of the following (Java code)? I have seen examples like this, but would be interested in learning why you think it might not work for you.
    public class SASread
{
    public static void main(String[] args) throws URISyntaxException, FileNotFoundException, StorageException, IOException
    {
    URI baseuri = new URI("http://greengrass.blob.core.windows.net");
    CloudBlobClient blobclient = new CloudBlobClient(baseuri);
    MyDownloadBlob("container1",
           "sr=c&sv=2012-02-12&sig=ADsFalIpE1XkaneQpWwtpM3AhY%2BAwiUtbbo1ANbIoJA%3D&si=r",
           blobclient);
    }

    public static void MyDownloadBlob(String containerName, String containerSAS, CloudBlobClient blobClient) throws URISyntaxException, StorageException, FileNotFoundException, IOException
    {
    String blobName = "image3.jpg";
    String localFileName = "c:\\myoutputimages\\image3.jpg";
    URI uri = new URI(blobClient.getEndpoint().toString() + "/" +
                      containerName + "/" +
                      blobName +
                      "?" +
                      containerSAS);
    CloudBlockBlob sasBlob = new CloudBlockBlob(uri, blobClient);
    File fileTarget = new File(localFileName);
    sasBlob.download(new FileOutputStream(fileTarget));
    System.out.println("The blob at:\n"  + uri + "\nwas downloaded from the cloud to local file:\n" + localFileName);
    }
}


text:
Q: how to uninstall .net framework 4.8 from windows 10 I have windows 10 and .net framework 4.7.2 installed and my program works fine. Then I figured to try the .net framework 4.8, after installation, my program doesn't work. I was trying to uninstall .net framework 4.8, I did the uninstall from control panel, but the registry HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full is permanently set at version 4.8.03761. I've searched online for hours on how to completely rid of this 4.8 version to no avail. I also read that Microsoft made the decision that 4.8 version update to be irreversible, I am hoping this is not true and hope for ways that I can go back to 4.7.2 version without completely nuking the whole system and starting over.

A: In powershell:
wusa /uninstall /KB:4486153

And you can see the version number change before and after the command with this command:
(C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe -version)[4]

A: .NET is part of Windows. New releases would appear as Windows updates in ARP (Control Panel -> Uninstall a Program -> View Installed Updates). To uninstall new .NET release, you would need to uninstall the correct Windows update.
Here are the update numbers for .NET 4.8 on Windows 10:
KB4486129 - for Windows 10 RS1/RS2 releases
KB4486153 - for Windows 10 RS3 and later releases
If uninstalling these updates does not fix the issue, I suggest opening a .NET issue on Developer Community web-site (https://developercommunity.visualstudio.com/spaces/61/index.html) and provide .NET installation/uninstallation logs.
The tool, and instructions, for log collection is available at https://www.microsoft.com/en-us/download/details.aspx?id=12493

A: The easiest thing would have been just rolling back the OS to a date before you installed 4.8
The app is called System Restore.
n the Control Panel search box, type Recovery. Select Recovery > Open System Restore. In the Restore system files and setting box, select Next. Select the restore point that you want to use in the list of results


text:
Q: Problems overloading the << Operator I am trying to overload the << operator for my Currency class but I get this compiler error:  C2143: syntax error : missing ';' before '&'
In my .h file I have:
 friend ostream &operator << (ostream &, const Currency&);

And in my Currency.cpp file I have:
    ostream &operator << (ostream &stream, const Currency &obj){
      stream<<"$"<<obj.dollars<<"."<<obj.cents;
      return stream;
      }

Everything up until now worked fine, but choked once I put that in:
I have the following at the top of my .h file:
    #ifndef CURRENCY_H
    #define CURRENCY_H

  #include<iostream>
  #include<string>
  #include<ostream>
  #include<sstream>

  class Currency; //forward delcaration

  //Function prototypes for overloaded stream operators
  ostream &operator << (ostream &, const Currency &);

I have no idea what I am doing wrong.  Help would be great.  Thanks

A: ostream is declared in namespace std and you are missing std:: identifier before it:
std::ostream &operator << (std::ostream &, const Currency &);

If you want to avoid std:: then after header file you can put using namespace statement:
...
#include<ostream>
using namespace std;  // this is not desirable though in real world programming

ostream &operator << (ostream &, const Currency &);

Edit: using namespace <> is not recommended in real world programming at the file top. I have put that part just for FYI.


text:
Q: Tomcat docker image with Openj9 Does anyone have a current Tomcat image along with Openj9 ? I built it myself based on Tomcat 9 with jdk11 adding to the image :
# set variables to create shared class cache
ENV JAVA_SCC_OPTS "-Xshareclasses:name=tomcat_scc,cacheDir=/tmp,enableBCI -Xscmx20M"
ENV JAVA_OLD_OPTS ${JAVA_OPTS}
ENV JAVA_OPTS "${JAVA_SCC_OPTS} ${JAVA_OPTS}"

# Start the tomcat server to create shared class cache
RUN catalina.sh run > /dev/null & sleep 20

# revert JAVA_OPTS to use shared class cache with readonly flag.
ENV JAVA_SCC_OPTS "-Xshareclasses:name=tomcat_scc,cacheDir=/tmp,readonly"
ENV JAVA_OPTS "${JAVA_SCC_OPTS} ${JAVA_OLD_OPTS}"

Image builds up but when I want to launch it on the production test it throws an error that it can't recognize the exact track
"-Xshareclasses:name=tomcat_scc,cacheDir=/tmp,enableBCI -Xscmx20M"

If anything, I added it before EXPOSE as the guy did in the link: https://blog.openj9.org/2020/05/18/startup-performance-of-tomcat-in-docker/
I've tried adding this to created tomcat images before building from source didn't help either. I would expect tomcat to boot me using just Openj9 and not the usual OpenJDK11


text:
Q: Counting from & to specific dates & times on a spreadsheet - mostly done, but some bugs I wanted to make a spreadsheet that I could enter a date & time and calculate how much time (in years/dates/months/weeks/hours/minutes/seconds...)
I kept expanding on it. it serves very little functional purpose but it was fun... here is the file...
https://docs.google.com/spreadsheets/d/19WJ7ld-SN6kWfCec94NDu5yEk8Md04j9i_O7C4KtkYw/edit?usp=sharing
Some things I need help with

*

*my month calculator doesn't seem to work... for the future? (red on sample)

*my time to/from calculator seems to add 12 hours? i'm guessing I need to do it a different way... column f

*for calculators on specific days of every year (e.g. enter a birthday, and if you open the file in 2020 or 2024 i want it to show days to/from that same year...)

thoughts?
Thanks!

A: :Caveat:
Show method is based on data, shared through Google sheet.

How it works:

*

*Formula in Cell M2:
=DATEDIF(L2,NOW(),"y") &" years, "&DATEDIF(L2,NOW(),"ym") &" months, " &DATEDIF(L2,NOW(),"md") &" days"

*Formula in Cell N2:
=INT((NOW()-L2)*24) &" Hrs, " & INT((NOW()-L2)*24*60)&" Min, " & INT((NOW()-L2)*24*60*60)& " Seco"

*Formula in Cell O2:
=DATEDIF(L2,NOW(),"Y")

*Formula in Cell P2:
=DATEDIF(L2,NOW(),"m")

*Formula in Cell Q2:
=CEILING.MATH(DATEDIF(L2,NOW(),"D")/7,1)

*Formula in Cell R2:
=DATEDIF(L2,NOW(),"d")

*Formula in Cell S2:
=INT((NOW()-L2)*24)

*Formula in Cell T2:
=INT((NOW()-L2)*24*60)

*Formula in Cell U2:
=INT((NOW()-L2)*24*60*60)
N.B.

*

*Cell L3, has Bith date & Time of Dr. Martin Luther king Jr.

*You may adjust cell references in the formula as needed.


text:
Q: Is this type of sentence an Inversion? I have heard this type of sentence with the same structure every time:
'Beautiful as she is', 'Intelligent as he is...'
Is it grammatically correct and if it is what's this grammatical phenomenon called?
How do you end such a sentence?
I believe it's Inversion but I'm not sure.
For example with a sentence beginning like this 'Young as she is...' how would I end it?

A: These are not sentences but heavily reduced versions of much fuller clauses of the form
  [X  SUBJ BE as]   ADJ as SUBJ BE
  [X   she is as] young as  she is

The construction SUBJ BE as ADJ as SUBJ BE may be paraphrased
  SUBJ BE so ADJ
   she is so young

"X" here is a term of the sort traditional grammars call subordinating conjunctions and contemporary grammars tend to call prepositions. X is usually understood to have the sense of either because or although.
Such clauses are typically employed as clausal modifiers with either a consequential (because) or a contrastive/concessive (although) sense. Which sense is intended is usually clear from the context:

CONSEQUENTIAL: [Because she is as] Young as she is, she doesn't have the maturity for this position.
CONCESSIVE:  [Although she is as] Young as she is, she's too old to play this part.

You will often encounter this sort of clause with the first as still in place:

As young as she is, she's too old to play this part.

A: I wouldn't be able to tell you how it's called, but it is grammatically correct, and conveys a contradiction between the first and second propositions. A simple example, since you asked for it:

Young as she is, she's already accomplished many things.

Despite the fact that she's only lived for so long, she's already made those years matter. This is equivalent to:

Even though she is Young, she's already accomplished many things.

As TRomano pointed out, talking about concession is even more accurate.


text:
Q: POCO Aliases for a database that has non-standard naming conventions I have a database that I'm working with that has each column named something like "product_id", "event_tracking_detail_type", etc.
Instead of using title case its all lower case and has _ between names. I've turned off code generation and used the POCO generator but I'd like to have the POCOs be named something along the lines of ProductId, ManufacturerImage (instead of manufacturer_image).
Is there a way to have the POCOs have different names then what is actually in the database, like an alias or something?
My reasons is to have the code interact with the proper names then down the road change the column names for the database.

A: Take a look at the MSDN documentation on data annotations. You can use the Table and Column attributes.
[Column(Name="product_id")]
Int32 ProductId;

Or, you can use the fluent API (here are samples)
modelBuilder.Entity<ENTITYNAME>()
.Property(entity=>entity.ProductId)
.HasColumnName("product_id")

A: If you are using the T4 Templates, there is a function WriteProprety you can modify that writes out properties.  You could modify it something like:
void WriteProperty(string accessibility, string type, string name, string getterAccessibility,  string setterAccessibility)
{
  //Start New Stuff
  string[] names = name.Split('_');
  names = names.ToList().Select(x => char.ToUpper(x[0]) + x.Substring(1)).ToArray();
  string fixedName = string.Join("", names);
 //End New Stuff
#>
  [Column(Name="<#=name>")]
  <#=accessibility#> <#=type#> <#=fixedName#> { <#=getterAccessibility#>get; <#=setterAccessibility#>set; }
<#+
}


text:
Q: How to read crash report from iPad using Windows I am new to developing for ios using Marmalade and Visual Studio, so I need to know how to read crash report from iPad ? Crash report is on location  /var/mobile/Library/Logs/CrashReporter/game.plist
How to read this file from windows ?

A: When you sync your iPad with iTunes, the crash report will be copied onto your computer. You can then find it in the location:
C:\Users\<Your Username>\AppData\Roaming\Apple Computer\Logs\CrashReporter\MobileDevice\<Your iPad's Name>\<Crash Log Name>.crash

A: You need to sync your iPad to the iTunes, and it'll be available in your iTunes sync folder.
Also I once found a way to read those reports in iPad itself, it was in about section maybe. Do the search, you may find it.
The path is Settings > Privacy > Diagnostics & Usage > Diagnostics & Usage Data

A: Use iTunes software . it will help for you.


text:
Q: SwiftUI / Combine : Listening array items value change I want to display multiple text fields, representing scores of each part of a match.
Example : For a volleyball match, we have 25/20, 25/22, 25/23. The global score is 3/0.
The global components architecture :
>> ParentComponent
    >> MainComponent
        >> X TextFieldsComponent (2 text fields, home/visitor score)

The lowest component, TextFieldsComponent, contains basic bindings :
struct TextFieldsComponent: View {
    @ObservedObject var model: Model

    class Model: ObservableObject, Identifiable, CustomStringConvertible {
        let id: String
        @Published var firstScore: String
        @Published var secondScore: String

        var description: String {
            "\(firstScore) \(secondScore)"
        }

        init(id: String, firstScore: String = .empty, secondScore: String = .empty) {
            self.id = id
            self.firstScore = firstScore
            self.secondScore = secondScore
        }
    }

    var body: some View {
        HStack {
            TextField("Dom.", text: $model.firstScore)
                .keyboardType(.numberPad)
            TextField("Ext.", text: $model.secondScore)
                .keyboardType(.numberPad)
        }
    }
}

The parent component needs to show the total score of all parts of the match. And I wanted to try a Combine binding/stream to get the total score.
I tried multiple solutions and I ended up with this non-working code (the reduce seems to not be take all the elements of the array but internally stores a previous result) :
struct MainComponent: View {
    @ObservedObject var model: Model
    @ObservedObject private var totalScoreModel: TotalScoreModel

    class Model: ObservableObject {
        @Published var scores: [TextFieldsComponent.Model]

        init(scores: [TextFieldsComponent.Model] = [TextFieldsComponent.Model(id: "main")]) {
            self.scores = scores
        }
    }

    private final class TotalScoreModel: ObservableObject {
        @Published var totalScore: String = ""
        private var cancellable: AnyCancellable?

        init(publisher: AnyPublisher<String, Never>) {
            cancellable = publisher.print().sink {
                self.totalScore = $0
            }
        }
    }

    init(model: Model) {
        self.model = model
        totalScoreModel = TotalScoreModel(
            publisher: Publishers.MergeMany(
                model.scores.map {
                    Publishers.CombineLatest($0.$firstScore, $0.$secondScore)
                        .map { ($0.0, $0.1) }
                        .eraseToAnyPublisher()
                }
            )
            .reduce((0, 0), { previous, next in
                guard let first = Int(next.0), let second = Int(next.1) else { return previous }
                return (
                    previous.0 + (first == second ? 0 : (first > second ? 1 : 0)),
                    previous.1 + (first == second ? 0 : (first > second ? 0 : 1))
                )
            })
            .map { "[\($0.0)] - [\($0.1)]" }
            .eraseToAnyPublisher()
        )
   }

    var body: some View {
        VStack {
            Text(totalScoreModel.totalScore)
            ForEach(model.scores) { score in
                TextFieldsComponent(model: score)
            }
        }
    }
}

I'm searching for a solution to get an event on each binding change, and merge it in a single stream, to display it in MainComponent.
N/B: The TextFieldsComponent needs to be usable in standalone too.

A: MergeMany is the correct approach here, as you started out yourself, though I think you overcomplicated things.
If you want to display the total score in the View (and let's say the total score is "owned" by Model instead of TotalScoreModel, which makes sense since it owns the underlying scores), you'd then need to signal that this model will change when any of the underlying scores will change.
Then you can provide the total score as a computed property, and SwiftUI will read the updated value when it recreates the view.
class Model: ObservableObject {
   @Published var scores: [TextFieldsComponent.Model]

   var totalScore: (Int, Int) {
      scores.map { ($0.firstScore, $0.secondScore) }
            .reduce((0,0)) { $1.0 > $1.1 ? ( $0.0 + 1, $0.1 ) : ($0.0, $0.1 + 1) }
   }

   private var cancellables = Set<AnyCancellable>()

   init(scores: [TextFieldsComponent.Model] = [.init(id: "main")]) {
      self.scores = scores

      // get the ObservableObjectPublisher publishers
      let observables = scores.map { $0.objectWillChange }

      // notify that this object will change when any of the scores change
      Publishers.MergeMany(observables)
         .sink(receiveValue: self.objectWillChange.send)
         .store(in: &cancellables)
   }
}

Then, in the View, you can just use the Model.totalScore as usual:
@ObservedObject var model: Model

var body: some View {
   Text(model.totalScore)
}


text:
Q: gets all static members of namespace I have a class with static members.
I want to get a list of all the static members that their class is defined in the namespace "foo" and inherit from class "bar"
something like list x= typeof(this).staticmembers.where(namespace == "foo");
TRY1:
 var AllowedTypes = GetType().Assembly.GetTypes()
       .Where(x => x.Namespace == "XX.XXX.XXX")
       .Where(x => x.IsAssignableFrom(typeof(UserControl)));

    var StaticMembersOfAllowedTypes = typeof(MainWindowXX).GetMembers  (System.Reflection.BindingFlags.Static ).Where(item => AllowedTypes.Contains(item));

this gives me a list of member infos, but I want the items themselves.
so I can do foreach item compare to another item.

A: I think this will do the trick. It's possible there's some typos, I couldn't test it
var list x = GetType().Assembly.GetTypes()
                    .Where(x => x.Namespace == "foo" && typeof(bar).IsAssignableFrom(x))
                    .SelectMany(x => x.GetMembers(BindingFlags.Static));

You may need to add BindingFlags.Public:
x.GetMembers(BindingFlags.Static | BindingFlags.Public)


text:
Q: HttpURLConnection disable cookie storage Im make post request using this method:
public String post(String url, String body) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setReadTimeout(SOCKET_TIMEOUT_MS);
    connection.setDoOutput(true);
    connection.setDefaultUseCaches(false);
    connection.setConnectTimeout(SOCKET_TIMEOUT_MS);
    connection.setRequestProperty(CONTENT_TYPE_HEADER, FORM_CONTENT_TYPE);
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setRequestProperty("Cookie", "");
    HttpURLConnection connection = getConnection(url);
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    OutputStream stream = connection.getOutputStream();
    stream.write(body.getBytes(StandardCharsets.UTF_8));
    for (int i = 0; i < DEFAULT_RETRY_ATTEMPTS_NETWORK_ERROR_COUNT; i++) {
        try {
            connection.getResponseCode();
            return;
        } catch (IOException ex) {
            getLogger().warning(ex.getLocalizedMessage());
        }
    }
    return StringUtils.inputToString(connection.getInputStream());
}

But after a while, cookies begin to accumulate in it. Im write simple logger and get next result
 -------Request to url: https://api.vk.com/method/messages.send-------
Cookie: remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED; remixir=DELETED;
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Cache-Control: no-cache
Connection: keep-alive
User-Agent: Java VK SDK/1.0
Host: api.vk.com
Pragma: no-cache
Content-Length: 287
Content-Type: application/x-www-form-urlencoded
POST /method/messages.send HTTP/1.1: null

After a while, the cookie becomes so large that the server does not accept the request. How can I turn this off, even if setRequestProperty("Cookie", "") doesn't help?


text:
Q: Why the height of my UISegmentedControl is one point bigger than its height constraint? As you can see on this screenshot, I added a constraint for the height of my UISegmentedControl but it is always one point smaller than the height of the UISegmentedControl. Any idea why?

A: You have change segment View from Frame Rectangle to Alignment Rectangle

Frame Rectangle Take original frame. and Alignment Rectangle take layout frame.


text:
Q: Scrollstart event not fire while scrolling in jQuery mobile.? I am using scrollstart event in jQuery mobile but it is not fire on browser. But it fire on device. My problem is that I need to do task while scrolling I need to give height to div if someone scroll that div.Div take the height but problem is that it goes to top of div content.
Mean I need if user focus should be there after giving the height. Not goes to top of contend.
First I need to fire scroll start function when user scroll the div contends(which is running on Ipad) but not running on browser. Then I give height to div
$('div#realTimeContents').css("height", "")

Then focus goes to top of the contend.
HERE IS MY FIDDLE
http://jsfiddle.net/naveennsit/x7ZyB/2/
$(document).on('scrollstart', '#realTimeContents', function() {
  alert("scroll---");
  isScrolling=false;
  $('div#realTimeContents').css("height", "")
  //$('div#realTimeContents').css("height", null)
});

A: You javascript code in your Fiddle has a syntax error, besides that:

*

*You are not attaching correctly your event. Try with this once your page is initialized:
$('#realTimeContents').on('scrollstart', function () {
  //CODE
});

*You are using a version of jQuery Mobile with some bugs (at least in the Fiddle), use a stable one as 1.3.1.
I have a working demo here.


text:
Q: what is the error in the getGrade() function in student.py i have a python class called student.py that have attributes and methods but the problem is that when i try to get the grade of the student the function doesn't work as it should and just display the the printing result that contain the name and the grade without the letter
the second task i need to get the average of all grades of the student  where this function take as arguments list of grades[]
student.py
class student():
    def __init__(self,name,age, grade):
        self.stdName=name
        self.stdAge = age
        self.stdGrade = grade

    def getName(self):
        return self.stdName

    def setName(self,Name):
        self.stdName = Name

    def getAge(self):
        return self.stdAge

    def setAge(self, Age):
        self.stdAge = Age

    def getGrade(self):
        print("the student {0}, have a grade {1}".format(self.stdName,self.stdGrade))

        if self.stdGrade >=90:
            return "A"
        elif self.stdGrade >=80:
            return "B"
        elif self.stdGrade >=60:
            return"C"
        else:
            return"F"

        return self.stdName,self.stdGrade

    def setGrade(self,Grade):
        self.stdGrade = Grade

std1 = student("georges", 17, 80)
std1.getGrade()

A: You are calculating the grade and not using it in your print. Here's how I would fix that:
`
class student():
    def __init__(self,name,age, grade):
        self.stdName=name
        self.stdAge = age
        self.stdGrade = grade

    def getName(self):
        return self.stdName

    def setName(self,Name):
        self.stdName = Name

    def getAge(self):
        return self.stdAge

    def setAge(self, Age):
        self.stdAge = Age

    def getGrade(self):
        gradeLevel = None
        if self.stdGrade >=90:
            gradeLevel = "A"
        elif self.stdGrade >=80:
            gradeLevel = "B"
        elif self.stdGrade >=60:
            gradeLevel = "C"
        else:
            gradeLevel = "F"

        print("the student {0}, have a grade {1}".format(self.stdName, gradeLevel))
            # return self.stdName,self.stdGrade

    def setGrade(self,Grade):
        self.stdGrade = Grade

std1 = student("georges", 17, 80)
std1.getGrade()

`


text:
Q: animateMotion выполняется быстрее Использую анимацию движения по пути animateMotion в SVG.
Розовый кружок движется по кругу, белый по полукругу.
Их скорость, кейфрейм и прочее совпадает, но есть одно конкретное отличие - анимация розового круга инвертированная, при помощи атрибутов keyPoints="1;0" keyTimes="0;1" (подсмотрел на SO).
Проблема заключается в том, что в FF всё работает как должно (нужный результат), а в Chrome и Opera возникает баг с тем, что розовый круг выполняет своё движение быстрее чем нужно.
У меня предположение, что это вызвано изменением кейфрема при инвертирование анимации.
Тут пример как это отображается:

Firefox
Opera & Chrome

А тут код:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100vh;
  background: #000;
  margin: 0;
}

svg {
  display: block;
}
<svg width="300" viewbox="0 0 200 200" style="background: rgba(255,0,0,.1)">
  <!-- circle big -->
  <g transform="rotate(-63 100 100)">
    <g>
      <defs>
       <path id="cb" d="M 100 190 A 1 1 0 0 1 100 10 A 1 1 0 0 1 100 190 Z" fill="none"/>
      </defs>
      <use xlink:href="#cb" stroke="white" stroke-width="4" stroke-dasharray="0 6" stroke-linecap="round" mask="url(#cbm)"/>
      <mask id="cbm">
        <rect x="0" y="0" width="100%" height="100%" fill="white"/>
        <use id="cba" xlink:href="#cb" stroke="black" stroke-width="5" stroke-dasharray="565.565" stroke-dashoffset="0"/>
        <animate xlink:href="#cba" attributeName="stroke-dashoffset" to="565.565" dur="1.5s" keySplines="0.33 1 0.68 1" calcMode="spline" fill="freeze"/>
      </mask>
    </g>

    <!-- Проблемное место -->
    <circle id="cbb" cx="0" cy="0" r="7" fill="#c4007b" filter="url(#blur)">
      <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keyPoints="1;0" keyTimes="0;1" keySplines="0.33 1 0.68 1" calcMode="spline"><mpath xlink:href="#cb"/></animateMotion>
    </circle>
    <!-- Проблемное место -->

    <defs>
      <filter id="blur">
        <feGaussianBlur in="SourceGraphic" stdDeviation=".5" />
      </filter>
    </defs>
  </g>

  <!-- circle small -->
  <g transform="rotate(-50 100 100)">
    <!-- left -->
    <g stransform="rotate(45 100 100)">
      <path id="cs-l" d="M 100 35 A 1 1 0 0 0 100 165" fill="none" stroke="#fed485" stroke-width="3" stroke-dasharray="204.232" mask="url(#scbm)"/>
      <animate xlink:href="#cs-l" attributeName="stroke-dashoffset" from="204.232" to="0" dur="1.5s" keySplines="0.33 1 0.68 1" calcMode="spline" fill="freeze"/>
      <!--  -->
      <circle id="scb-l" cx="-6" cy="0" r="6" fill="white">
        <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keySplines="0.33 1 0.68 1" calcMode="spline"><mpath xlink:href="#cs-l"/></animateMotion>
      </circle>

      <mask id="scbm">
        <rect x="0" y="0" width="100%" height="100%" fill="white"/>
        <circle cx="106" cy="35" r="9" fill="black"/>
        <circle cx="-6" cy="0" r="9" fill="black">
          <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keySplines="0.33 1 0.68 1" calcMode="spline"><mpath xlink:href="#cs-l"/></animateMotion>
        </circle>
        <circle cx="94" cy="165" r="9" fill="black"/>
        <circle cx="-6" cy="0" r="9" fill="black">
          <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keySplines="0.33 1 0.68 1" calcMode="spline"><mpath xlink:href="#cs-r"/></animateMotion>
        </circle>
      </mask>
    </g>

    <!-- right -->
    <g stransform="rotate(45 100 100)">
      <path id="cs-r" d="M 100 165 A 1 1 0 0 0 100 35" fill="none" stroke="#fed485" stroke-width="3" stroke-dasharray="204.232" mask="url(#scbm)"/>
      <animate xlink:href="#cs-r" attributeName="stroke-dashoffset" from="204.232" to="0" dur="1.5s" keySplines="0.33 1 0.68 1" calcMode="spline" fill="freeze"/>
      <!--  -->
      <circle id="scb-r" cx="-6" cy="0" r="6" fill="white">
        <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keySplines="0.33 1 0.68 1" calcMode="spline"><mpath xlink:href="#cs-r"/></animateMotion>
      </circle>
    </g>
  </g>
</svg>

Проблемное место выделил комментом, строка 16 в HTML

Вопрос:
Чем это вызвано и как это решить?
Мне что-то подсказывает, что проблема может быть ещё и в самом path, по которому происходит движение, возможно было бы проще инвертировать его, чем движение розового кружка.

A: Когда используется реверс направления движения с помощью атрибутов keyPoints="1;0" и keyTimes="0;1" Firefox это нормально воспринимает.
У браузеров на движке webkit :Chrome, Opera, Yandex, safari и др. наблюдается баг при совместном использовании calcMode="spline" и  атрибутов keyPoints="1;0" и keyTimes="0;1"
Необходимо использовать calcMode="linear", в этом случае анимация будет работать во всех браузерах одинаково!

body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100vh;
  background: #000;
  margin: 0;
}

svg {
  display: block;
}
<svg width="300" viewbox="0 0 200 200" style="background: rgba(255,0,0,.1)">
  <!-- circle big -->
  <g transform="rotate(-63 100 100)">
    <g>
      <defs>
       <path id="cb" d="M 100 190 A 1 1 0 0 1 100 10 A 1 1 0 0 1 100 190 Z" fill="none"/>
      </defs>
      <use xlink:href="#cb" stroke="white" stroke-width="4" stroke-dasharray="0 6" stroke-linecap="round" mask="url(#cbm)"/>
      <mask id="cbm">
        <rect x="0" y="0" width="100%" height="100%" fill="white"/>
        <use id="cba" xlink:href="#cb" stroke="black" stroke-width="5" stroke-dasharray="565.565" stroke-dashoffset="0"/>
        <animate xlink:href="#cba" attributeName="stroke-dashoffset" to="565.565" dur="1.5s" keySplines="0.33 1 0.68 1" calcMode="linear" fill="freeze"/>
      </mask>
    </g>

    <!-- Проблемное место -->
    <circle id="cbb" cx="0" cy="0" r="7" fill="#c4007b" filter="url(#blur)">
      <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keyPoints="1;0" keyTimes="0;1" keySplines="0.33 1 0.68 1" calcMode="linear"><mpath xlink:href="#cb"/></animateMotion>
    </circle>
    <!-- Проблемное место -->

    <defs>
      <filter id="blur">
        <feGaussianBlur in="SourceGraphic" stdDeviation=".5" />
      </filter>
    </defs>
  </g>

  <!-- circle small -->
  <g transform="rotate(-50 100 100)">
    <!-- left -->
    <g stransform="rotate(45 100 100)">
      <path id="cs-l" d="M 100 35 A 1 1 0 0 0 100 165" fill="none" stroke="#fed485" stroke-width="3" stroke-dasharray="204.232" mask="url(#scbm)"/>
      <animate xlink:href="#cs-l" attributeName="stroke-dashoffset" from="204.232" to="0" dur="1.5s" keySplines="0.33 1 0.68 1" calcMode="spline" fill="freeze"/>
      <!--  -->
      <circle id="scb-l" cx="-6" cy="0" r="6" fill="white">
        <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keySplines="0.33 1 0.68 1" calcMode="spline"><mpath xlink:href="#cs-l"/></animateMotion>
      </circle>

      <mask id="scbm">
        <rect x="0" y="0" width="100%" height="100%" fill="white"/>
        <circle cx="106" cy="35" r="9" fill="black"/>
        <circle cx="-6" cy="0" r="9" fill="black">
          <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keySplines="0.33 1 0.68 1" calcMode="spline"><mpath xlink:href="#cs-l"/></animateMotion>
        </circle>
        <circle cx="94" cy="165" r="9" fill="black"/>
        <circle cx="-6" cy="0" r="9" fill="black">
          <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keySplines="0.33 1 0.68 1" calcMode="spline"><mpath xlink:href="#cs-r"/></animateMotion>
        </circle>
      </mask>
    </g>

    <!-- right -->
    <g stransform="rotate(45 100 100)">
      <path id="cs-r" d="M 100 165 A 1 1 0 0 0 100 35" fill="none" stroke="#fed485" stroke-width="3" stroke-dasharray="204.232" mask="url(#scbm)"/>
      <animate xlink:href="#cs-r" attributeName="stroke-dashoffset" from="204.232" to="0" dur="1.5s" keySplines="0.33 1 0.68 1" calcMode="spline" fill="freeze"/>
      <!--  -->
      <circle id="scb-r" cx="-6" cy="0" r="6" fill="white">
        <animateMotion dur="1.5s" restart="whenNotActive" fill="freeze" rotate="auto" keySplines="0.33 1 0.68 1" calcMode="spline"><mpath xlink:href="#cs-r"/></animateMotion>
      </circle>
    </g>
  </g>
</svg>


text:
Q: How to know which button is pressed ? Python Tkinter + SQLite I'm trying to develop a GUI application which manage tickets from SAV. I'm using Python Tkinter, sqlite3.
My problem is that I create buttons for each tickets I have. This button is used to open the ticket's profil. But I don't know how to identify which button is pressed. Also every buttons has the same command, but datas displayed will be affect by this button.
I tried to create an ID for each case to identify the line but I didn't success this way
for N_Nom in curseur.execute("SELECT Nom FROM client"):
    Label(FrameMain, text=N_Nom,bg='#C2C2C2',font=('Arial',12,'bold')).grid(row=c_nom.get(), column=1)
    c_nom.set(c_nom.get() + 1)

for N_Code in curseur.execute("SELECT Codification FROM SAV"):
    Label(FrameMain, text=N_Code,bg='#C2C2C2',font=('Arial',12,'bold')).grid(row=c_code.get(), column=2)
    c_code.set(c_code.get() + 1)

for N_State in curseur.execute("SELECT Etat_Ticket FROM SAV"):
    Label(FrameMain, text=N_State,bg='#C2C2C2',font=('Arial',12,'bold')).grid(row=c_state.get(), column=3)
    c_state.set(c_state.get() + 1)

for N_Date in curseur.execute("SELECT Date_Ticket FROM SAV"):
    Label(FrameMain, text=N_Date,bg='#C2C2C2',font=('Arial',12,'bold')).grid(row=c_date.get(), column=4)
    c_date.set(c_date.get() + 1)

for N_client in curseur.execute("SELECT Num_Ticket FROM SAV"):
    Label(FrameMain, text=N_client,bg='#C2C2C2',font=('Arial',12,'bold')).grid(row=c_client.get(), column=0)
    Button(FrameMain, text='Compléter', font=('Arial',14), cursor='hand2', command= lambda : config(N_client, N_Nom, N_Code, N_State, N_Date)).grid(row=c_client.get(),column=6, sticky='e')

    Label(FrameMain, text=N_client,bg='#C2C2C2',font=('Arial',12,'bold')).grid(row=c_client.get(), column=0)
    c_client.set(c_client.get() + 1)

So if you know how to solve this one, or if you can tell me if I can do it better. Thanks you


text:
Q: how to change the value of the sate in react I'm a beginner in using states in reactjs so im sorry if my question shouldn't be asked in the right spot.Using React js, Node js and mongodb
So i created a constructor and initialized a variable called val inside it and passed that variable in a value property in a textarea tag so the user would enter somthing and it would be saved in the val variable (im not sure if thats the right way of doing it, so thats why im asking!). Also, I created a function called handleSubmit that would get the variable val and save it in mongodb, and i called that function in the button the user supposed to click when he passes in somthing. But all that doesn't seem to be working with me.
Here is my ping.js file:
class Pingbutton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { val: "Ford" };
  }

  handleSubmit = () => {
    // if we get state error then we need to put it in a claa and call the constructot and then call the function using this.state.the name of the function
    console.log("its running 1");
    let databody = {
      message: this.state.val,
    };
    console.log(" the message is :" + databody.message);
    console.log(" the message is :" + this.state.val);
    return fetch("http://localhost:5000/stored", {
      method: "POST",
      body: JSON.stringify(databody),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => res.json())
      .then((data) => console.log(data));
  };
  render() {
    return (

        <textarea
          className="message"
          type="text"
          placeholder="Write me somthing!. Also, double click to ping:) "
          value={this.setState.val}
        ></textarea>
          <button
            className="button"
            onClick={() => {
              this.magic();
              this.handleSubmit(); //animation + //pinging the phone
              // this.handleButtonClick(); //setVal(() => ""); //sets the value of the box to empty
            }}
          >
          </button>

    );
  }
}

export default Pingbutton;

and this is the back-end (nodejs) index.js file:
const express = require("express");
const cors = require("cors"); // Importing cors
var request = require("request");
const dotenv = require("dotenv");
const port = 5000;
var request = require("request");
var util = require("util");
const connectDB = require("./config/db");
require("dotenv").config({ path: "./config/config.env" });

const app = express();
dotenv.config();
connectDB();

app.use(cors({ origin: "http://localhost:3000" }));
app.get("/", (req, res) => {
  res.send("Hey there!");
});

app.use(cors({ origin: "http://localhost:3000" }));
app.get("/Pinged", function (req, res) {
  find_my_iphone("omar.fsm98@gmail.com", "Faresomar123", "Omar");
  res.send("Pinged!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
});

app.use(cors({ origin: "http://localhost:3000" }));
app.post("/stored", (req, res) => {
  console.log("its running 2: " + req.body);
  db.collection("quotes").insertOne(req.body, (err, data) => {
    if (err) return console.log(err);
    res.send("saved to db: " + data);
  });
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

I have been getting Ford in the two console in the front-end after typing somthing in the box and clicking the button (excuting the handleSubmit) function). I tried doing this.state.val but didnt work then i changed it to this.setState.val and didnt work either.
I would appreciate the help.
THANK YOU!

A: The answer for that would be to create a function that does all that as following:
class App extends React.Component {
  constructor() {
    super();
    this.state = {header: 'yeaheheh'};
  }
  changeHeader = (e) => {
     e.preventDefault();
    let newHeader = this.textInput.value;
    console.log('submitted');
    this.setState({header : newHeader});
  }
  render() {
    return (

{this.state.header}

            <form onSubmit={this.changeHeader} className="change-header-form">
                <input id="input" ref={(input) => { this.textInput = input; }} type="text" placeholder="Enter Text Here" />
                <input type="submit" value="Submit" />
            </form>

    );
  }
}

ReactDOM.render(<App />, document.getElementById('test'));

The full answer for that can be found in that link: Change a state in react