text:
Q: Issue with Copying Excel Cells I am not sure if there is a solution to this issue. In Excel when you copy a cell the border starts moving/flashing. Only when that border is moving you are allowed to paste its contents into another cell. Once the border is no longer moving, you are also unable to paste its contents. The other option is to double click on the cell or go into the formula bar to manually copy the data, which then you can paste as much as you want, at least until something else is copied.
Here is my problem. I have script within the "Private Sub Worksheet_SelectionChange(ByVal Target As Range)" section of my worksheet. So every time another cell is selected this script is run. The script works perfectly and I do not need this changed. The spreadsheet first needs to be unlocked before the script can run, so I had to put this at the top of the script "ActiveSheet.Unprotect" and this at the bottom "ActiveSheet.Protect". When I select a different cell and the code hits either the unprotect or the protect commands, then the copied cell border is no longer flashing, so I can't paste.
Is there a script of some sort that I can use so it retains the copied data? The script should only run when a cell is copied. I also don't want to use the SendKeys function because that typically causes more issues then what it solves. I have always been wondering where Excel stores its data for copied cells, since usually copied data is stored in the windows clipboard, or some other dumping ground since Windows 7 & 8 no longer use the clipboard for copping data. So I don't understand why Excel doesn't use the same method as everything else when a cell is copied.
This isn't too much of an issue, more of an annoyance than anything. If someone should have a solution to this please let me know, but I don't think there is one.


text:
Q: Events on EditText not fired at all I have an EditText and I want to catch the event when the user is using "Done" or "Enter". Currently, I'm testing on an emulator with Pixel API 26
I've tried many solutions found on StackOverFlow such as adding setSingleLine or editing the XML with
android:singleLine="true"
android:inputType="text"
android:maxLines="1""

and nothing works. I really don't know what is the problem.
This is the XML:
<EditText
    android:id="@+id/input_search"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerVertical="true"
    android:layout_toEndOf="@+id/ic_magnify"
    android:background="@null"
    android:hint="Enter Address, City or Zip Code"
    android:imeOptions="actionGo|actionSearch|actionNext|actionSend"
    android:singleLine="true"
    android:inputType="text"
    android:maxLines="1"
    android:textColor="#000"
    android:textSize="15sp" />

In my MapFragment class, I'm obtaining the reference to the EditBox inside the "onCreateView" function:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View v = inflater.inflate(R.layout.activity_maps, container,
                false);

    mSearchText = v.findViewById(R.id.input_search);
    mSearchText.setSingleLine();
    init();

    // Hiding the action bar
    ((AppCompatActivity) getActivity()).getSupportActionBar().hide();

    return v;
}

and then in the "init" function, I'm doing this:
private void init() {

    Log.d("Yolo2", "Before");

    //Search field
    mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if(actionId == EditorInfo.IME_ACTION_SEARCH
                || actionId == EditorInfo.IME_ACTION_DONE
                || keyEvent.getAction() == KeyEvent.ACTION_DOWN
                || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
                    Log.d("Yolo2", "Yes");
                    //execute our method for searching
                    geoLocate();
                }

            Log.d("Yolo2", "No");
            return false;
        }
    });
}

I've tried many other events and none of them worked. I'm getting nothing from the debug logs. I've tried on key change events to catch and key typed inside the EditText.

A: Thank you all for helping me with this issue.
I've made a mistake by using this code in the MapFragment class when I should have used it on the MapActivity. My code works now just fine and all your answers are probably correct too.

A: Remove your if condition and give try
 mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            geoLocate();
            return true;
        }
    });

A: Try with android:imeOptions="actionDone" and check with below code. First handle KeyEvent and then action.
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (keyEvent != null && keyEvent.getAction() != KeyEvent.ACTION_DOWN)
            return false;

        if(actionId == EditorInfo.IME_ACTION_DONE
            || actionId == EditorInfo.IME_NULL) {
                Log.d("Yolo2", "Yes");
                //execute our method for searching
                geoLocate();
        }

        Log.d("Yolo2", "No");
        return false;
    }
});

A: Please try this
    mSearchText = v.findViewById(R.id.input_search);
mSearchText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            geoLocate();
            handled = true;
        }
        return handled;
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Post method of CFHTTP is not working in coldfusion 10 however get works I have a page in Coldfusion 10 which uses the  below code :
<cfhttp url ="http://mysite.am.com/index.cfm" resolveURL="yes"  throwOnError="no" method="post">
<cfhttpparam type ="formfield" name="fuseaction" value="searchOrders">
<cfhttpparam type ="formfield" name="cookieValue" value="#cookie.Mycookie#">
</cfhttp>
<cfoutput>left(trim(#cfhttp.filecontent#),4)</cfoutput>

second called page has below code:
<form>
<cfif isDefined("attributes.cookieValue")>
TRUE
<cfelse>
FALSE
</cfif>
</form>

Nothing is returned on the calling page. However if I pass the url (http://mysite.am.com/index.cfm?fuseaction=searchOrders&Mycookie=C176060) directly in the browser it works and displays TRUE. There is no error on the page. The page has nothing returned.

A: I'd debug this by checking the Browser's Network (Chrome Developer Toolbar / Firebug) to see if your CFHTTP is posting correctly and what it's posting and see what the response is. Also instead of using the attributes scope maybe just use form scope to see if it's coming through.
Sorry, not enough rep to post a comment :(

A: In the second page you should access through 'FORM' scope. You have given 'FORMFIELD' in the first page.
Don't use attribute scope for fetching variables.


text:
Q: Using Negative lookbehind with or operator (not preceded by multiple words) I've a problem with my regex in Python.
et  may only match if it is not preceded by m or mme
string: M et Mme Du Pont or Mme et M Du Pont
regex: '\b(?<!m|mme)\bet\b'
error: look-behind requires fixed-with patterd
How can i fix this?
'\b(?<!m)(?<!mme)\bet\b' doesn't seem to work either

A: Apart from the error, there is a space in the example data after m and mme which is missing in the pattern.
Another option is to use the regex PyPi module with a single lookbehind asserting what is directly at the left is m, optionally followed by me and followed by a space.
\b(?<!m(?:me)? )et\b

Regex demo | Python using regex module demo
For example
import regex

pattern = r"\b(?<!m(?:me)? )et\b"
s = ("M et Mme Du Pont or Mme et M Du Pont\n"
            "et\n"
            "met")

print(regex.findall(pattern, s, regex.IGNORECASE))

Output
['et']

A: You may use 2 negative lookbehind assertions like this:
(?<!\bM )(?<!\bMme )\bet\b

RegEx Demo
A space character after M and Mme is important because in your input you have a space before et.
RegEx Details:

*

*(?<!\bM ): Negative lookbehind to fail the match if we have "M " string before current position

*(?<!\bMme ): Negative lookbehind to fail the match if we have "Mme " string before current position

*\bet\b: Match complete word et


text:
Q: Java: Access level of Inner classes I was about to create a class inside another class
public class Sq {
        class Inner {
            private int a; //no getters setters
                           //a is private
            private Inner (int a1) {
                this.a = a1;
            }
        }
    public static void main(String[] args) {
        Sq outter = new Sq();
        Inner d = outter.new Inner(3);
        System.out.println("Private a = " + d.a);
    }
}

It works.. so that i can get access to inner's private fields, also i've added Inner2 class and tried to change "a" from the Inner2 and it also worked :/
So looks like private in the inner class is not so private, looks like it's public within the whole class.

A: Nested classes are public for the outer class and private for all the others classes...
Some reference: Nested Classes
Declaring private the nested/inner class does not change the visibility to the outer class itself, just think the nested class (private or not) as a variable/method of the outer class.
public class Sq {
    public int publicNumber = 0;
    private int number = 0;
    private class Inner { ... }
}

EDIT
From the inner class you can also call some variable/method of the outer class and otherwise without problem
public class Sq {

    private int number = 0;

    class Inner {
        private int a;

        private Inner(int a1) {
            this.a = a1;
            number++;
        }

        private String getOuterClassString()
        {
            return getOuterString();
        }

        private String getPrivateString()
        {
            return "privateString";
        }

        public String getPublicString()
        {
            return "publicString";
        }
    }

    private String getOuterString()
    {
        return "outerString";
    }

    public static void main(String[] args) {
        Sq outter = new Sq();
        Inner d = outter.new Inner(3);
        System.out.println("Number = " + outter.number);
        System.out.println("Private a = " + d.a);
        System.out.println("Number = " + outter.number);

        System.out.println(d.getPrivateString());
        System.out.println(d.getPublicString());
        System.out.println(d.getOuterClassString());
    }
}

A: Inner classes are ultimately meant to provide some utility to the outer class in terms of organization.  The inner class is completely accessible to the outer class, because ultimately you really should never need to hide data from your own class.  When the complexity of your code requires you to hide data behind getters and setters, you should be seriously considering the possibility of putting that class in its own file.


text:
Q: P5.js drawing on a transparent background I'm trying to draw a few bubbles on each mouse click, and I want my canvas to be transparent so it can only display bubbles without covering rest of elements on the site.
The problem is that bubbles do not seem to move, because each of them is just mowing a little and drawing itself one more time without removing the last one.
How can I make each bubble disappear (become transparent) after moving and drawing it elsewhere?
here you can see the issue:
picture
oh, and here's the code:
var springs = [];

var Bubble = function(position) {

    this.position = position.copy();
    this.radius = random(10, 22);
    this.velocity = createVector(random(-1, 1), random(-1, 1));
    this.acceleration = random(1, 1.05);
    this.expire = random(30, 150);
};

Bubble.prototype.Move = function(){

    this.velocity = createVector(random(this.velocity.x-0.07,this.velocity.x+0.07), random(this.velocity.y-0.07,this.velocity.y+0.07));

    var wind;
    if(mouseX > windowWidth/2){
        wind = (windowWidth/2 + (mouseX - windowWidth/2))/10000.0 + 0.005;
    }else{
        wind = -1*((windowWidth/2 + (mouseX - windowWidth/2))/10000.0 + 0.005);
    }

    this.velocity.add(wind);

    this.position.add(this.velocity.mult(this.acceleration));

    this.expire -= 2;

    stroke(198, 151, 204, this.expire);
    strokeWeight(1);
    fill(255, 0);
    ellipse(this.position.x, this.position.y, this.radius, this.radius);

};

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

function setup() {
    createCanvas(windowWidth, windowHeight);
}

function draw() {

    for(var i = 0; i < springs.length; ++i){
        var bubble = springs[i];
        if(bubble.expire > 0){
            bubble.Move();
        }else{
            springs.splice(i, 1);
        }
    }

    if (mouseIsPressed) {
        let bubble = new Bubble(createVector(mouseX, mouseY));
        springs.push(bubble);
    }
}

A: It sounds like you're just looking for the clear() function.
More info can be found in the reference.
// Clear the screen on mouse press.
function setup() {
  createCanvas(100, 100);
}

function draw() {
  ellipse(mouseX, mouseY, 20, 20);
}

function mousePressed() {
  clear();
}

In your case, you probably want to call clear() as the first line in every draw() frame.


text:
Q: Export OSGI-Application from Eclipse I've developed an osgi application (no rcp) using eclipse. It consists of several Plugin-Projects-Bundles and dependencies from eclipse plugins folder (commons.* ...)
The application works fine when launched using eclipse.
What is the best way to export and deploy such an application from eclipse? Is there a simple way to export my launch configuration?
All I found was for rcp projects.

A: All you need to do is religiously fill your Manifest.MF via PDE(Plugin Editor), you must

*

*Add proper plugin-dependencies in the Dependecies tab in PDE

*Fill the Classpath and Exported Packages in the Runtime tab

*And most importantly, make sure in the Build tab you have checked on the required resources to be exported.

Its very important to note point 3, it is here where most people make mistake and wonder why the project is running perfectly in Eclipse but doesent run when exported.

Right-Click on your
  project->Export->Plugin-Development->Deployable
  Plugins and Fragments

A: Creating an OSGi bundle, by itself, does not constitute a complete application. OSGi bundles require a container and its the container's responsibility to manage the lifetime of the bundle: loading the bundle, resolving dependencies, invoking the bundle's activator, etc. There are several OSGi containers available such as Knopflerfish (http://www.knopflerfish.org/), Felix (http://felix.apache.org/), and Equinox (http://www.eclipse.org/equinox/). Internally, Eclipse uses Equinox.
Deploying an application that uses OSGi entails configuring the container and the exact mechanism for doing that depends on the chosen container. If you wish to continue using Equinox then check out this quick-start guide for configuring and launching the container outside Eclipse (http://www.eclipse.org/equinox/documents/quickstart.php).

A: Check out Chapter 9 on packaging OSGi/Equinox applications in the new OSGi and Equinox book.  It's available on rough cuts now: http://my.safaribooksonline.com/9780321561510.  It should be available in print for purchase by EclipseCon in March.

A: PDE generates a configuration that can be customized much easier that writing an Equinox config from scratch.  In your running Eclipse-based OSGi environment, type bundles.  You'll see where Equinox is putting all the runtime bundles for the launch.  In there should be a config.ini that PDE is generating for the launch.  In my case it's [workspace root]/.metadata/.plugins/org.eclipse.pde.core/[My Launch Config Name]/config.ini.

A: -> Create a feature project in Eclipse

-> Open feature.xml file of the created project.
-> Add all the required Plug-ins and dependencies under "Included Plug-ins"

-> Ensure that you have added all OSGI dependant "Plug-ins"
Here is a list of Plug-in I am using

-> Now create  the OSGI run configuration

-> Under "Bundles", select your feature project.

Now all the plug-ins can be exported from the Overview tab of your feature.xml


text:
Q: More optimized way to do itertools.combinations I'm trying to find unique combinations of ~70,000 IDs.
I'm currently doing an itertools.combinations([list name], 2) to get unique 2 ID combinations but it's been running for more than 800 minutes.
Is there a faster way to do this?
I tried converting the IDs into a matrix where the IDs are both the index and the columns and populating the matrix using itertools.product.
I tried doing it the manual way with loops too.
But after more than a full day of letting them run, none of my methods have actually finished running.
For additional information, I'm storing these into a data frame, to later run a function that compares each of the unique set of IDs.

A: (70_000 ** 69_000) / 2== 2.4 billion - it is not such a large number as to be not computable in a few hours (update I run a dry-run on itertools.product(range(70000), 2) and it took less than 70 seconds, on a 2017 era i7 @3GHz, naively using a single core) But if you are trying to keep this data in memory at once, them it won't fit - and if your system is configured to swap memory to disk before erroring with a MemoryError, this may slow-down the program by  2 or more orders of magnitude, and thus, that is when your problem come from.
itertools.combination does the right thing in this respect, and no need to try to change it for something else: it will yield one combination at a time. What you are doing with the result, however, do change things: if you are streaming the combination to a file and not keeping it in memory, it should be fine, and then, it is just computational time you can't speed up anyway.
If, on the other hand, you are collecting the combinations to a list or other data structure: there is your problem - don't do it.
Now. going a step further than your question, since these combinations are check-able and predictable, maybe trying to generate these is not the right approach at all - you don't give details on how these are to be used, but if used in a reactive form, or on a lazy form, you might have an instantaneous workflow instead.

A: Your Ram will run full. You can counter this with gc.collect() or emtpying the results but the found results have to be saved inbetween.
You could try something similar to the code below. I would create individual file names or save the results into a database since the result file will be some gb big. Additionaly range of the second loop can probably be divided by 2.
import gc
new_set=set()

for i in range(70000):
    new_set.add(i)

print(new_set)

combined_set=set()

for i in range(len(new_set)):
    print(i)
    if i % 300 ==0:
        with open("results","a") as f:
            f.write(str(combined_set))
        combined_set=set()
        gc.collect()
    for b in range(len(new_set)):
        combined_set.add((i,b))


text:
Q: Clicking a button with HtmlUnit not working I am trying to click a login button using HtmlUnit 2.23, using either DomElement or executeJavaScript but none of it works. Is there any other way to get it working? This is the code:
@Test
public void noLogin() throws Exception {
    final WebClient webClient = new WebClient(BrowserVersion.BEST_SUPPORTED);
    //see http://stackoverflow.com/questions/3600557/turning-htmlunit-warnings-off/18563576#18563576
    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
    //see http://stackoverflow.com/questions/18556200/htmlunit-button-click
    webClient.getOptions().setJavaScriptEnabled(true);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.setAjaxController(new NicelyResynchronizingAjaxController());

    final HtmlPage loginPage = webClient.getPage("https://sandbox.paydirekt.de/account/#/login");
    loginPage.getElementById("username").setAttribute("value", "no");
    loginPage.getElementById("password").setAttribute("value", "login");
    //final HtmlPage welcomePage = ((DomElement)loginPage.getFirstByXPath("//button[@type='submit']")).click();
    //see http://stackoverflow.com/questions/14474580/use-htmlunit-doesnt-work-button-click
    //ScriptResult result = loginPage.executeJavaScript("javascript:document.getElementsByName('loginForm')[0].submit();");

    ScriptResult result = loginPage.executeJavaScript("javascript:document.getElementsByClassName('loginBox__loginButton button button--full')[0].click()");
    Page page = result.getNewPage();
    if (page.isHtmlPage()) {
        HtmlPage welcomePage = ((HtmlPage)page);
        System.out.println(welcomePage.asText());
        Assert.assertTrue(welcomePage.asText().contains("Benutzername oder Passwort nicht korrekt."));
    }
    webClient.close();
}

A: You can also use the connection wrapper that HTMLUnit offers to check for each request and response manually. Here is an example
            new WebConnectionWrapper(webClient) {

                public WebResponse getResponse(WebRequest request) throws IOException {
                    WebResponse response = super.getResponse(request);
                    if (request.getUrl().toExternalForm().contains("THE URL YOU WANT TO CHECK")) {
                        String content = response.getContentAsString("UTF-8");

//CHECK CONTENT HERE

                        WebResponseData data = new WebResponseData(content.getBytes("UTF-8"), response.getStatusCode(),
                                response.getStatusMessage(), response.getResponseHeaders());
                        response = new WebResponse(data, request, response.getLoadTime());
                    }
                    return response;
                }
            };


text:
Q: How would I set section numbering to a specific format - e. g. 1 (first level) -> 1. (second level) -> 1.1. (third level) in Lyx? I am creating a document for school and I am required to follow a specific format for numbering - that is: "1", then "1.", then "1.1." and so on. I am a Latex and Lyx beginner and haven't found a way to do this in this specific way (or in a simple enough way that I could follow). Should I use some package? Is there some preamble thing for this? Or would I have to do this manually?
Thank you in advance for your help.
Edit 1: Posting a MWE. I am using the article document class with manually changed section numbering to start from 0.
Code:
\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\setcounter{secnumdepth}{4}
\setcounter{tocdepth}{4}

\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
\setcounter{section}{-1}

\makeatother

\usepackage{babel}
\begin{document}
\title{Title}
\author{John Doe}
\maketitle

\section{Preface}

\section{Characteristics}

\section{Division}

\subsection{Group A}

\subsubsection{A}

\subsubsection{B}

\paragraph{B1}

\section{Conclusion}
\end{document}

Screenshot from Lyx:

A: A brute-force solution is to run
\renewcommand\thesubsection{\arabic{subsection}.}
\renewcommand\thesubsubsection{\thesubsection\arabic{subsubsection}.}
\renewcommand\theparagraph{\thesubsubsection\arabic{paragraph}.}

Unfortunately, this will create unwanted issues if you ever need to cross-reference subsection-, subsubsection-, and paragraph-level units. I therefore suggest you take the following, indirect or "circumspect" approach. I picked up this approach up some years ago, while reading the book "The LaTeX Companion" (2nd ed.).

\documentclass[english]{article}
\usepackage[T1]{fontenc}
%\usepackage[latin9]{inputenc} %% Are you absolutely sure about 'latin9'?!
\usepackage{babel}

\setcounter{secnumdepth}{4} % default is '3'
\setcounter{tocdepth}{4}

%% Brute-force method:
%\renewcommand\thesubsection{\arabic{subsection}.}
%\renewcommand\thesubsubsection{\thesubsection\arabic{subsubsection}.}
%\renewcommand\theparagraph{\thesubsubsection\arabic{paragraph}.}

%% Circumspect method:
\makeatletter
% the next 4 lines are straight from "The LaTeX Companion", 2nd ed.
\def\@seccntformat#1{\@ifundefined{#1@cntformat}%
   {\csname the#1\endcsname\quad}   % default
   {\csname #1@cntformat\endcsname} % enable individual control
}

\renewcommand\thesubsection{\arabic{subsection}}
\newcommand{\subsection@cntformat}{\thesubsection.\quad}
\newcommand{\subsubsection@cntformat}{\thesubsubsection.\quad}
\newcommand{\paragraph@cntformat}{\theparagraph.\quad}
\makeatother

\begin{document}
\setcounter{section}{-1}
\section{Preface}
\section{Characteristics}
\section{Division}

\subsection{Group A}

\subsubsection{A} \label{sec:A}
\subsubsection{B} \label{sec:B}

\paragraph{B1} \label{sec:B1}

\section{Conclusion}

Cross-references to subsubsections \ref{sec:A} and \ref{sec:B}
and to parapraph \ref{sec:B1}.
\end{document}


text:
Q: Best way to implement shopping cart using PHP/MySQL I'm working on a customer's website, and they've asked for a shopping cart. They need to use securetrading.net for the payment, so I don't need to ask for any credit card details. All I need to do is keep track of the items in their cart.
I've read about using PHP sessions, but I'm concerned about security there. Is this not a problem if the only information I'm storing is product codes and quantities? Otherwise, is it worth using a MySQL database?
I'm sorry if this seems like an obvious thing to know, but this is my first time implementing this kind of thing!

A: There is tutorial for simple/small php/MySQL cart that keeps cart status in sessions, there is even downloadable demo code and online demo.
http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart
I used it when full blown online shoping programs were just that "over blown". Same as you there was no need to take cc data, user registration, etc... just siple place to send selected items to payment gateway's purchase proces and after that to forget about it. That is what client wanted, and that is what he got on the end (my first choice was magento but it was too complicated for clients 3 products).
Of course you need to extend it to fit your need but it's good starting point for something simple.

A: I'd use a prefab open-source solution. You really don't want to let in silly security issues when you're dealing with other people's money.
Magento comes to mind. It's certainly the slickest I've seen in a while... And there appears to be securetrading support if you hack it in yourself.

A: I'd use PHP sessions since you're only storing product codes/quantities.  Yes these are open to "attack" -- but the attack would be something along the lines of changing product codes (make sure you add a check for valid codes before passing info to your payment gateway) and quantities (again do a check for quantity on hand if need be)
Session variables are open to attack by users but if someone wants to "trick" my system and checkout 4 items instead of 1 it's really not a problem at all.

A: Keep in mind that sessions will only last for, well, the session. If your customer walks away and comes back tomorrow to carry on shopping, they will find their basket is empty again.
If you are going to use sessions to get things going quickly, try and design your code so that it would be simple to change your mind in the future and switch to a Mysql solution.
However, unless you have very specific requirements, just find one of the hundreds of free solutions out there and save yourself a load of time.


text:
Q: Can increased disk throughput increase CPU utilization? We recently upgraded the storage in our data center and migrated all our production systems to it. We noticed that in one machine (an HP_UX IA-64 Oracle database server for SAP), the CPU utilization started spiking up while the IO wait% was decreasing. Now the IO wait is 0% and all the CPUs are running at 100%(0% idle). Before, the IO wait was around 30-40% (average) and the CPU was around 15-20% idle(average). Can the increased throughput of the storage actually cause this increased CPU utilization?

A: It certainly can. A definitive answer to the question of whether your CPU has gone up because of this would require more information, but in general, this is quite common and easily explainable.
Server workloads have to wait on a lot of things- CPU and memory, being local, often have to wait for things like network and storage. I've had applications go nuts becoming CPU bound after getting access to an SSD, for example.
It's very possible that your application is getting data back from the improved storage so much faster than before that the CPU has now become the bottleneck.

A: An increase in storage speed can lead to an increase in CPU because more data can be fed to it.
But CPU is usually going faster than RAM nowadays. So it is strange that the CPU is going up to 100%. You are right to question this.
My guess is that something else has changed or your OS is not reporting the correct values.


text:
Q: Single Click Expose Is it possible to have single click on the dock icons activate expose by default?
If you have a single window open in ubuntu it doesn't activate expose but if you have multiple windows open it does.  This cause issues when I tried to use expose on several different windows in ubuntu.

A: Contents:

*

*Overview

*Script source

*Additional notes

1. Overview
As mentioned in the comments, this functionality apparently got removed since 12.04 and now click on the launcher icon minimizes the window (which apparently was a highly-requested feature, from what I can see in my online searches). However, there exists a keyboard to turn on expo for a single window, which is Super+Ctrl+W. Knowing that, if we can detect click on the launcher or position of the cursor when window is raised , then we can simulate that single window expo via that keyboard shortcut. The script below does exactly that.
This is meant to be saved as /usr/bin/single_click_expo.py file and added to Startup Applications

2. Script Source
Also available on GitHub
#!/usr/bin/env python3

# Author: Serg Kolo
# Date: Sept 28, 2016
# Purpose: activates
# Depends: python3-gi
#          xdotool
# Written for: http://askubuntu.com/q/651188/295286

# just in case user runs this with python 2
from __future__ import print_function
import gi
gi.require_version('Gdk', '3.0')
from gi.repository import Gdk,Gio
import sys
import dbus
import subprocess

def run_cmd(cmdlist):
    """ Reusable function for running shell commands"""
    try:
        stdout = subprocess.check_output(cmdlist)
    except subprocess.CalledProcessError:
        print(">>> subprocess:",cmdlist)
        sys.exit(1)
    else:
        if stdout:
            return stdout

def gsettings_get(schema,path,key):
    """Get value of gsettings schema"""
    if path is None:
        gsettings = Gio.Settings.new(schema)
    else:
        gsettings = Gio.Settings.new_with_path(schema,path)
    return gsettings.get_value(key)

def get_launcher_object(screen):

    # Unity allows launcher to be on multiple
    # monitors, so we need to account for all
    # window objects of the launcher
    launchers = []

    for window in screen.get_window_stack():
        xid = window.get_xid()
        command = ['xprop','-notype',
                   'WM_NAME','-id',str(xid)
        ]
        xprop = run_cmd(command).decode()
        title = xprop.replace("WM_NAME =","")
        if title.strip()  == '"unity-launcher"':
           launchers.append(window)
           #return window
    return launchers

def get_dbus(bus_type,obj,path,interface,method,arg):
    # Reusable function for accessing dbus
    # This basically works the same as
    # dbus-send or qdbus. Just give it
    # all the info, and it will spit out output
    if bus_type == "session":
        bus = dbus.SessionBus()
    if bus_type == "system":
        bus = dbus.SystemBus()
    proxy = bus.get_object(obj,path)
    method = proxy.get_dbus_method(method,interface)
    if arg:
        return method(arg)
    else:
        return method()

def main():

    previous_xid = int()
    screen = Gdk.Screen.get_default()

    while True:

        current_xid = screen.get_active_window().get_xid()
        if  int(current_xid) == previous_xid:
            continue
        previous_xid = int(current_xid)
        icon_size = gsettings_get(
                        'org.compiz.unityshell',
                        '/org/compiz/profiles/unity/plugins/unityshell/',
                        'icon-size')
        icon_size = int(str(icon_size))
        position = str(gsettings_get(
                       'com.canonical.Unity.Launcher',
                       None,
                       'launcher-position'))
        screen = Gdk.Screen.get_default()
        launcher_objs = get_launcher_object(screen)

        # for faster processing,figure out which launcher is used
        # first before running xdotool command. We also need
        # to account for different launcher positions (available since 16.04)
        pointer_on_launcher = None
        for launcher in launcher_objs:
            if 'Left' in position and  \
               abs(launcher.get_pointer().x) <= icon_size:
                  pointer_on_launcher = True
            elif 'Bottom' in position and \
               abs(launcher.get_pointer().y) <= icon_size:
                  pointer_on_launcher = True
            else:
               continue

        active_xid = int(screen.get_active_window().get_xid())

        application = get_dbus('session',
                               'org.ayatana.bamf',
                               '/org/ayatana/bamf/matcher',
                               'org.ayatana.bamf.matcher',
                               'ApplicationForXid',
                               active_xid)

        # Apparently desktop window returns empty application
        # we need to account for that as well
        if application:
            xids = list(get_dbus('session',
                            'org.ayatana.bamf',
                            application,
                            'org.ayatana.bamf.application',
                            'Xids',None))

        if pointer_on_launcher and\
           len(xids) == 1:
               run_cmd(['xdotool','key','Ctrl+Super+W'])

if __name__ == '__main__':
    main()

3. Additional notes

*

*It might be advisable to remap the shortcut to something other Super+Ctrl+W , because in expo Ctrl+W in Expo corresponds to "close window" command. Potential issue here is that frequent switching may cause window closing. The script would have to be adjusted as well accordingly.

NOTE:
The script relies on xdotool utility. You must have it installed. Without xdotool it won't work, since xdotool is used to simulate keypresses. Install it via sudo apt-get install xdotool


text:
Q: Custom ClickHandler class Is there a way to use the Clickhandler interface in GWT to build a custom subclass ? I need  ClickHandlers which should react on every second click. Achieving this behavior is not the problem for an implemented ClickHandler, but it would be great if don't have to add this code snippet  to each single ListBox element:
 boolean ingoreClick;
 lastSelection =  -1 ;
 listBox.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {

        if (!ignoreClick) {
            lastSelection = listBox.getSelectedIndex();
        }
        ignoreClick = !ignoreClick;
    }
});

And now imagine that there is listbox1, listbox2 and so on.

A: Yes, since Clickhandler is and interface you can implement whatever behavior in your customized class and use it wherever.
  public class MyClickHancler implements ClickHandler {
    boolean first = false;
    String name;

    public MyClickHancler(String name) {
      this.name = name;
    }

    public void onClick(ClickEvent event) {
      if (first = !first) {
        System.out.println("First click on " + name);
      } else {
        System.out.println("Second click on " + name);
      }
    }
  }

  [...]

  widget1.addClickHandler(new MyClickHancler("widget-1"));
  widget2.addClickHandler(new MyClickHancler("widget-2"));

A: Well, it is quite simple, answer by Manolo basically solves it, you only need to improve it a little bit:
public abstract class EvenClickHandler implements ClickHandler {
    private boolean eventClick= true;

    public void onClick(ClickEvent event) {
        if (eventClick = !eventClick) {
          onEvenClick(event);
        }
    }

    protected abstract void onEvenClick(ClickEvent e);

}

...

listBox.addClickHandler(new EvenClickHandler (){

   protected void onEvenClick(ClickEvent e){
      lastSelection = listBox.getSelectedIndex();
   }

});


text:
Q: Solving tensor version of homogeneous Sylvester equation I have a system that reads (in summation convention)
$$
X_{j_1 j_2 ... j_N} R^{j_1}_{k_1} R^{j_2}_{k_2} ... R^{j_N}_{k_N} = X_{k_1 k_2 ... k_N}
$$
where $N$ is a fixed value, $R$ a known matrix (square of size $s$ up to $s=15$) and I would like to solve for $X$. With $N=2$ this looks like a Sylvester equation,
$$
R.X.R^T=X
$$
Could anyone provide pointers on how to solve the general tensor set of equations?
If the dimensionality $s$ of the matrices is small then solving the vectorized version is tractable (solving $s^N$ linear equations), but this becomes infeasible for larger systems.
Some approaches look interesting but don't seem to apply to the homogeneous version above (looking instead at problems like $R.X.R^T-X=A$ and Krylov subspaces thereof).
If it helps with the solution method, the solution tensor $X$ is unique up to multiplication by a constant if it exists and $R$ is the inner automorphism matrix of a Lie algebra (matrix $B$ in https://arxiv.org/abs/math-ph/0602046).


text:
Q: In ASP.NET MVC 3, how do I get at the model using Razor Syntax in a Create() View? How do I grab the data in my textarea and stuff it in my model?
I'm in a Create() View, and I want to access the model, to put the contents of a
<textarea>

into one of the model's properties, the Content property in this case.
namespace TestTinyMCE.Models {
  public class TestBlog {
    public int TestBlogId { get; set; }
    public string Title { get; set; }
    public DateTime PostedOn { get; set; }
    public string Tags { get; set; }

    public string Content { get; set; }
  }
}

I can't use TextAreaFor as I'm accepting HTML markup (bold, italic, and so on). I'm using TinyMCE on my textarea if that matters.
I tried hooking the submit event via JQuery's .submit API:
<script type="text/javascript">
  $(document).ready(function () {
    tinyMCE.init({
      theme: "advanced",
      mode: "textareas"
    });

    $('#contentEditor').submit(function () {
      alert('Handler for .submit() called.');
      return false;
    });
  });
</script>

but while the .submit() occurred in $(document).ready, the handler itself never fires off.
and here's my textarea:
<div class="editor-field">
  <textarea id="contentEditor" name="contentEditor"></textarea>
</div>

A:
I can't use TextAreaFor as I'm accepting HTML markup (bold, italic, and so on). I'm using TinyMCE on my textarea if that matters.

Wrong.
TextAreaFor() emits a normal <textarea> just like your; you can still hook up TinyMCE to it.

Your actual problem is that <textarea>s don't fire submit events.
You need to handle the <form>'s submit event.
However, you don't actually need to do that at all.


text:
Q: Ads not showing on iPhone5 i am showing adds in my app, but adds are not showing in iPhone5 device only showing in simulator.
i am using code like this -
-(void)showAdds
{
   {

    if ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad))
    {

        bannerView = [[GADBannerView alloc]
                      initWithFrame:CGRectMake(128.0,
                                               670 ,
                                               GAD_SIZE_728x90.width,
                                               GAD_SIZE_728x90.height)];
        bannerView.adUnitID = @"8c9b7de0880d478b";
    }
    else {

        if ([[UIScreen mainScreen] bounds].size.height == 568)
        {
            bannerView = [[GADBannerView alloc]
                          initWithFrame:CGRectMake(120,
                                                   [[UIScreen mainScreen] bounds].size.height - GAD_SIZE_320x50.height ,
                                                   GAD_SIZE_320x50.width,
                                                   GAD_SIZE_320x50.height)];
            bannerView.adUnitID = @"a151d69e8127bd7";
            NSLog(@"ads");
        }
        else
        {
            bannerView = [[GADBannerView alloc]
                          initWithFrame:CGRectMake(80,
                                                   [[UIScreen mainScreen] bounds].size.width - GAD_SIZE_320x50.height ,
                                                   GAD_SIZE_320x50.width,
                                                   GAD_SIZE_320x50.height)];
            bannerView.adUnitID = @"a151d69e8127bd7";
            NSLog(@"ads");

        }

    }

adds are showing on simulator but not on iPhone device. Please help.

A: I think you are use the test ads, after IOS 6 Test ads is not support the Device , Please disable the test ads , then you see the ads in real device
see this link    https://developers.google.com/mobile-ads-sdk/docs/admob/intermediate#ios-testing


text:
Q: Copy, paste then move next row I am trying to copy the data from sheet "MAINSHEET" cell M9 to O9 and paste it to sheet "COPYDATA", column B. First it will paste the data to B2 and next it will B3, next B4 and will continue... But it is not going below, keep pasting on B2 cell.
Sub Copy()

Dim lastrow As Integer
lastrow = ThisWorkbook.Sheets("COPYDATA").Cells(Rows.Count, 1).End(xlUp).Row

Sheets("MAINSHEET").Range("M9:O9").Copy
Worksheets("COPYDATA").Range("B" & lastrow + 1).PasteSpecial xlPasteValues

End Sub

A: You are counting the rows in column 1 but pasting in column 2, so the lastrow always stays the same.
Count the rows in column B instead.
lastrow = ThisWorkbook.Sheets("COPYDATA").Cells(Rows.Count, 2).End(xlUp).Row

A: Try this:
Sub Copy()

Dim lastrow As Long
lastrow = ThisWorkbook.Sheets("COPYDATA").Cells(ThisWprkbook.Sheets("COPYDATA").Rows.Count, "B").End(xlUp).Row

Sheets("MAINSHEET").Range("M9:O9").Copy
Worksheets("COPYDATA").Range("B" & lastrow + 1).PasteSpecial xlPasteValues

End Sub

You need to modify the code to get row count of the COPYDATA sheet and use the column "B".


text:
Q: React Native App Crash when in Production I recently pushed an update to our React Native app. Everything was running fine, however during the review, Apple rejected the update because the app crashed on boot.
Here are the meaningful lines the report:
Last Exception Backtrace:
0   CoreFoundation                  0x1d3b30ec4 __exceptionPreprocess + 228
1   libobjc.A.dylib                 0x1d2d01a40 objc_exception_throw + 55
2   vesali_app                      0x101c9f478 RCTFatal + 447
3   vesali_app                      0x101c9cf20 -[RCTExceptionsManager reportFatalException:stack:exceptionId:] + 491
4   CoreFoundation                  0x1d3b38630 __invoking___ + 143
5   CoreFoundation                  0x1d3a16450 -[NSInvocation invoke] + 291
6   CoreFoundation                  0x1d3a17034 -[NSInvocation invokeWithTarget:] + 59
7   vesali_app                      0x101cb28f4 -[RCTModuleMethod invokeWithBridge:module:arguments:] + 491
8   vesali_app                      0x101cf6770 facebook::react::invokeInner+ 25552752 (RCTBridge*, RCTModuleData*, unsigned int, folly::dynamic const&) + 247
9   vesali_app                      0x101cf64d0 invocation function for block in facebook::react::RCTNativeModule::invoke+ 25552080 (unsigned int, folly::dynamic&&, int) + 87
10  libdispatch.dylib               0x1d35696c8 _dispatch_call_block_and_release + 23
11  libdispatch.dylib               0x1d356a484 _dispatch_client_callout + 15
12  libdispatch.dylib               0x1d3511bd0 _dispatch_lane_serial_drain$VARIANT$mp + 591
13  libdispatch.dylib               0x1d3512718 _dispatch_lane_invoke$VARIANT$mp + 431
14  libdispatch.dylib               0x1d351aeb8 _dispatch_workloop_worker_thread + 599
15  libsystem_pthread.dylib         0x1d374d0dc _pthread_wqthread + 311
16  libsystem_pthread.dylib         0x1d374fcec start_wqthread + 3

Any tips/suggestions are greatly appreciated,thanks a lot !


text:
Q: UltraWinGrid, on date filter select date column value changing format to MM/dd/yyyy from dd/MM/yyyy I have infragistics2 v10.3.
I have ultra grid with two columns
|String|DateTime|
For DateTime I have custom formatting like "dd.MM.yyyy HH:mm" System Regional settings have short Date format like "dd-MMM-yy".
So grid shows 07.02.2013 14:00 and user See this.
The sytem have 07-Feb-13
When i want to filter all columns with text "fe" it is also shows me all rows which contains 07.02.2013.
During filtering it uses own formating and ignores my custom In InitializeLayout event we have done the following code to set date format for the StartDate column
e.Layout.Bands(0).Columns("StartDate").Style = Win.UltraWinGrid.ColumnStyle.Date
e.Layout.Bands(0).Columns("StartDate").Format = "dd/MM/yyyy"
e.Layout.Bands(0).Columns("StartDate").ButtonDisplayStyle = UltraWinGrid.ButtonDisplayStyle.Always

This date field column filter displaying based on Local system date format in opened calendar.
Please suggest me where I am doing wrong

A: As your are using string column type to store dates, I suspect how the dates are converted: 07/08/2015 is treated as August 7 or July 8?
You are setting the format for your grid but the data loaded in the DropDown may be in its original form as in the Database.
If you do not want to change the data type of your date column, I would advise that you set DateFormat within the select query as demonstrated in change-data-type-of-data-retrieved-by-select-query (but beware of the conversion errors or the date change scenario as pointed above)
If you are using SQL Server (I'm not sure about other databases) you can use a UDF (User Defined Function) in the select query as in this example of UDF on TechNet or this post on SO: using-udf-in-select-statement
Along with that don't forget to set the Format of your DropDown, if defined explicitly on initialize or on entering edit mode.

A: You need to set MaskInput property of the column like this:
e.Layout.Bands(0).Columns("StartDate").MaskInput = "dd/mm/yyyy";

Keep in mind when cell is in edit mode it uses an editor to display the edited value. So when you need to fix anything in edit mode you need to fix it in the editor.


text:
Q: Possible to create a class that has a default value I was wondering if there is a way to create a class in PHP that when compared with other variables a default value is used instead of the class itself?  such that:
class Test {
    private $name;
    private $val;
    public function __construct($name, $val) {
       $this->name = $name;
       $this->val = $val;
    }
    public __default() {
        return $val;
    }
    public function getName() {
        return $name;
    }
}

then I could use a function like __default when I compare it to another value such as:
$t = new Test("Joe", 12345);
if($t == 12345) { echo "I want this to work"; }

the phrase "I want this to work" will print.

A: As far as I know this is not possible. The closest thing you're looking for is the __toString() method to be set on the class.
http://php.net/manual/en/language.oop5.magic.php
PHP might try to convert it to an Integer, but I'm not sure if there are class methods to accomplish this. You could try string comparison.
<?php
class Test {
    private $name;
    private $val;
    public function __construct($name, $val) {
       $this->name = $name;
       $this->val = $val;
    }
    public function __toString() {
        return (string)$this->val;
    }

    public function __toInt() {
        return $this->val;
    }

    public function getName() {
        return $this->name;
    }
}

$t = new Test("Joe", 12345);
if($t == '12345') { echo "I want this to work"; }

A: The __toString magic method will do what you want with some caveats:
class Test {
    private $name;
    private $val;
    public function __construct($name, $val) {
       $this->name = $name;
       $this->val = $val;
    }
    public function __toString() {
        return $this->val;
    }
    public function getName() {
        return $this->name;
    }
}

Objects can't be directly cast to an integer so will always get a when comparing to an integer but if you cast either side of the comparison to a string it will work as expected.
if($t == 12345)          // false with a warning about can't cast object to integer
if((string)$t  == 12345) // true
if($t == "12345")        // true

A: Your object will unlikely equals integer. But you can implement something similar to Java's hashCode() - a class method that do some math to produce numeric hash - a return value based on i.e. its internal state, variables etc. Then compare these hash codes.

A: Implement __toString() in your class.
Like:
class myClass {
    // your stuff

    public function __toString() {
        return "something, or a member property....";
    }
}

A: Why not something along this line:
class Test {
    private $name;
    private $val;
    public function __construct($name, $val) {
       $this->name = $name;
       $this->val = $val;
    }
    public __default() {
        return $val;
    }

    public compare($input) {
        if($this->val == $input)
            return TRUE;
        return FALSE;
    }

    public function getName() {
        return $name;
    }
}

$t = new Test("Joe", 12345);
if($t->compare(12345)) { echo "I want this to work"; }

From other answers it appears there is not a built in function to handle this.


text:
Q: method to read resource file what i'm trying to do is to write a method in c# codebehind to read text based on key.
For now i whant to do this for only one language that's why i don't need to use System.Globalization.CultureInfo
private ResourceManager rm;
private ResourceReader rr;
public string GetCurrentLanguage(string key)
{
    rm = new ResourceManager("~/App_GlobalResources/textFile", System.Reflection.Assembly.GetExecutingAssembly());
    string result = rm.GetString(key).ToString();
    return result;
}

but it doesn't work :(
when i write something like litWelcome.Text = GetCurrentLanguage("Welcome"); it's returns error.
anyone have idea what's i'm doing wrong ?
Thanks for advance:)
Edited
ok i get it on my own this is a solution for my problem:
public string GetCurrentLanguage(string key)
{

    string result = Resources.textFile.ResourceManager.GetString(key).ToString();
    return result;
}

Thanks all for help:)

A: Might you be looking for Using Resources for Localization?
I know this isn't a direct answer to your question, but maybe it is the solution you are looking for. This link will give you information on how to use built-in support for localization of your web site in ASP.NET.

A: Is this line correct?
 rm = new ResourceManager("~/App_GlobalResources\textFile"

Your edited comment shows:
file is in ~\App_GlobalResources\textFile.resx
Your slashes aren't consistent. Is this a typo in your post, or your code?

A: try :
GetGlobalResourceObject for global resources.
GetLocalResourceObject for local resources.
EX:
Button1.Text = GetLocalResourceObject("Button1.Text").ToString();
Image1.ImageUrl = CType(GetGlobalResourceObject("WebResourcesGlobal","LogoUrl"), String)

for more info check http://msdn.microsoft.com/en-us/library/ms227982.aspx


text:
Q: Microsoft Builder SDK 3.8.1.0: Location dialog throws exception Method not found "Void Microsoft.Bot.Builder.Dialogs.PromptDialog.Confirm" I am building bot with Microsoft Bot Framework and currently testing in Bot Framework channel emulator.
I have updated Microsoft Bot builder SDK to version 3.8.1.0 as well as Microsoft.Bot.Builder.Location version 2.0.0. I have configured location dialog as following:

code from: https://github.com/Microsoft/BotBuilder-Location/tree/master/CSharp
However, after call to dialog it throws the following exception:

Before the updated no exception was thrown and it worked well. I am just wondering if anyone else was experiencing same issue and was able to find solution? Thank you ;)
(code from: https://github.com/Microsoft/BotBuilder-Location/tree/master/CSharp)

A: This is known issue the team is going to fix soon. It was reported here and here. To unblock yourself you can just re-compile the library using the latest version of BotBuilder, that will make the trick.
Update
A new NuGet with the fix was released on May-24.Check https://www.nuget.org/packages/Microsoft.Bot.Builder.Location?NormalizedVersion=2.1.0

A: New version of Microsoft.Bot.Builder.Location https://www.nuget.org/packages/Microsoft.Bot.Builder.Location?NormalizedVersion=2.1.0


text:
Q: How to create a link to downlad a static csv file from /public/csv directory in React Regarding the React application, i have the list of static csv files in the /public/csv directory. Then, a js file has the following code:
Download
This works locally for downloading the csv file, however, it doesn't work when the app is deployed to the server.
Could you please suggest how to download a static file from the public/csv folder in React?
My directory structure:
Project
 - build
   - index.html
   - main.js
 - public
   - csv << the target csv file to be downloaded
 -  src
   - index.js
   - App.js
 - package.json
 - webpack.config.js

A: Download CSV

Old question but I thought I would post the answer, to access the public directory in React from JavaScript you need to use the "process.env.PUBLIC_URL" environment variable.


text:
Q: AJAX trigger remote script then check for success-response I've been searching my brains out but I can't seem to wrap my head around the little help I find.
I'm running a database that is being fed by data from another DB. The csv transport is handled by a third party server providing executable "flows" which compile and deliver the data.
I have a php script to handle the request (can't be done directly via Javascript because of the missing 'Access-Control-Allow-Origin' header). But this runs nicely. I can trigger the flow.
This is not the problem though.
What I want to do: trigger the flow @onClick of a button with something like this:
function trigger_func(flowID) {
    $.ajax({
        url: './ajaxPHP_handler.php',
        data: "flowid="+flowID,
        dataType: 'json',
        success: function(result) {
            var jsonResult  =   jQuery.parseJSON(result);
            console.log(jsonResult.runID);
        }
    });
}

With the flowID and the resulting runID I want to check back like every second or so.
function check_status(flowID, runID) {
    $.ajax({
        url: './ajaxPHP_handler.php',
        data: "flowid="+flowID+"&action=status&runId="+runID,
        dataType: 'json',
        success: function(result){...}
    });
}

This will return the status / progress of the flow.
It will start for a few seconds with status==null, then go on to status=='running' and finally status=='success'.
I have gotten check_status() to run for i.e. 15 times with a setTimeout in a for loop within the success-function of trigger_func() and it works fine too.
But I cannot for the life of me figure out how I would link this stuff together to have it checking until status is 'success' and then stop checking, update page content and so on...
I have also fiddled with something like
trigger_func(id).done(function(result){
console.log(result);
});

This works too but still I can't think my way further to the checking every second until 'success'. I guess it comes down to getting the variable 'status' back into my loop so I can break it.
Maybe someone knows of a comprehensible example somewhere online...

A: You could do this:
function periodically_check_status_until_success(flowID, runID) {
    setTimeout(function() {
        $.ajax({
            url: './ajaxPHP_handler.php',
            data: { flowid: flowID, action: status, runId: runID },
            dataType: 'json',
            success: function(result){
                 if (result != 'success') {
                     periodically_check_status_until_success(flowID, runID);
                 }
            }
        });
    }, 5000); // Five seconds
}

Note: You can use an object for the data option, rather than concatenate the string yourself.

A: ajax are async so you have to manage by this via some 3rd party variable
Like Init with value 0
var _status = 0

than change it on your first call set it 1
function trigger_func(flowID) {
 $.ajax({
     url: './ajaxPHP_handler.php',
     data: "flowid="+flowID,
     dataType: 'json',
     success: function(result) {
         var jsonResult  =   jQuery.parseJSON(result);
         console.log(jsonResult.runID);
          check_status(flowID, runID);
     }
 });
}

 function check_status(flowID, runID) {
 $.ajax({
     url: './ajaxPHP_handler.php',
     data: "flowid="+flowID+"&action=status&runId="+runID,
     dataType: 'json',
     success: function(result){
        //at end status=='success'.
          if(status=='success'){
              // end part
           }else{// running
               check_status(flowID, runID);
           }

          // clear timeout will stop that time interval after success
     }
 });
 }

A: So just keep calling it
var flowID, runID;
function trigger_func(flowID) {
  $.ajax({
    url: './ajaxPHP_handler.php',
    data: "flowid="+flowID,
    dataType: 'json',
    success: function(result) {
        var jsonResult  =   jQuery.parseJSON(result);
        runID= jsonResult.runID;
        check_status();
    }
  });
}

function check_status() {
  $.ajax({
    url: './ajaxPHP_handler.php',
    data: "flowid="+flowID+"&action=status&runId="+runID,
    dataType: 'json',
    success: function(result){
      if (result is not what you want) {
        setTimeout(check_status,1000);
      }
    }
  });
}


text:
Q: Using golang to create a new child process with syscall.CLONE_NEWUSER but why at the new usernamespace the uid is nobody? exe := exec.Command("/proc/self/exe","init")
exe.SysProcAttr = &syscall.SysProcAttr{
    Cloneflags: syscall.CLONE_NEWUTS|syscall.CLONE_NEWNS|syscall.CLONE_NEWUSER|syscall.CLONE_NEWPID|syscall.CLONE_NEWIPC|syscall.CLONE_NEWNET,
    //mapping the uid and gid   I can figure out the mapping rules????
    UidMappings: []syscall.SysProcIDMap{
        {
            ContainerID: 0,
            HostID: 1000000,
            Size: 65536,
        },
    },
    GidMappings: []syscall.SysProcIDMap{
        {
            ContainerID: 0,
            HostID: 100000,
            Size: 65536,
        },
    },
}

when I run with exe.Start() get the result at terminal is "nobody@xx:/home/xx$" .
I read the code of runc ,likewise,runc use the same way to implement usernamespace's isolation,but set correctly uid with 'root'. what's wrong with me?
There is system info of my new process,getting from another bash.

root@xx:/home/xx# cat /proc/159624/uid_map
0    1000000    65536

root@xx:/home/xx# cat /etc/subuid
xx:100000:65536

os: ubuntu20.04
go version:1.18.3 linux/amd64


text:
Q: Memory efficient message chunk processing using a XMLHttpRequest I have a XMLHttpRequest with a progress event handler that is requesting a chunked page which continuously sends adds message chunks. If I do not set a responseType, I can access the response property of the XMLHttpRequest in each progress event and handle the additional message chunk. The problem of this approach is that the browser must keep the entire response in memory, and eventually, the browser will crash due to this memory waste.
So, I tried a responseType of arraybuffer in the hope that I can slice the buffer to prevent the previous excessive memory waste. Unfortunately, the progress event handler is no longer capable of reading the response property of the XMLHttpRequest at this point. The event parameter of the progress event does not contain the buffer, either. Here is a short, self-contained example of my attempt at this (this is written for node.js):
var http = require('http');

// -- The server.

http.createServer(function(req, res) {
  if (req.url === '/stream') return serverStream(res);
  serverMain(res);
}).listen(3000);

// -- The server functions to send a HTML page with the client code, or a stream.

function serverMain(res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('Hello World');
}

function serverStream(res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  setInterval(function() {
    res.write('Hello World
\n');
  }, 1000);
}

// -- The client code which runs in the browser.

function client() {
  var xhr = new XMLHttpRequest();
  xhr.addEventListener('progress', function() {
    if (!xhr.response) return console.log('progress without response :-(');
    console.log('progress: ' + xhr.response.size);
  }, false);
  xhr.open('GET', '/stream', true);
  xhr.responseType = 'arraybuffer';
  xhr.send();
}

The progress event handler has no access to the response I wanted. How can I handle the message chunks in the browser in a memory-efficient way? Please do not suggest a WebSocket. I do not wish to use one just to process a read-only stream of message chunks.

A: XMLHttpRequest doesn't seem really designed for this kind of usage. The obvious solution is polling, which is a popular use of XMLHttpRequest but I'm guessing you don't want to miss data from your stream that would slip between the calls.
To my question Can the "real" data chunks be identified in some way or is it basically random data ?, you answered With some effort, the chunks could be identified by adding an event-id of sorts to the server-side
Based on this premise, I propose:
The idea: cooperating concurrent listeners

*

*Connect to the stream and set up the progress listener (referred to as listenerA()).

*When a chunk arrives, process it and output it. Keep a reference to the ids of both the first and last chunk received by listenerA(). Count how many chunks listenerA() has received.

*After listenerA() has received a certain amount of chunks, spawn another "thread" (connection + listener, listenerB()) doing the steps 1 and 2 in parallel to the first one but keep the processed data in a buffer instead of outputting it.

*When listenerA() receives the chunk with the same id as the first chunk received by listenerB(), send a signal to listenerB(), drop the first connection and kill listenerA().

*When listenerB() receives the termination signal from the listenerA(), dump the buffer to the output and keep processing normally.

*Have listenerB() spawn listenerC() on the same conditions as before.

*Keep repeating with as many connections + listeners as necessary.

By using two overlapping connections, you can prevent the possible loss of chunks that would result from dropping a single connection and then reconnecting.
Notes

*

*This assumes the data stream is the same for all connections and doesn't introduce some individualized settings.

*Depending on the output rate of the stream and the connection delay, the buffer dump during the transition from one connection to another might be noticeable.

*You could also measure the total response size rather than the chunks count to decide when to switch to a new connection.

*It might be necessary to keep a complete list of chunks ids to compare against rather than just the first and last one because we can't guarantee the timing of the overlap.

*The responseType of XMLHttpRequest must be set to its default value of "" or "text", to return text. Other datatypes will not return a partial response. See https://xhr.spec.whatwg.org/#the-response-attribute
Test server in node.js
The following code is a node.js server that outputs a consistent stream of elements for testing purposes. You can open multiple connections to it, the output will be the same accross sessions, minus possible server lag.

http://localhost:5500/stream

will return data where id is an incremented number

http://localhost:5500/streamRandom

will return data where id is a random 40 characters long string. This is meant to test a scenario where the id can not be relied upon for ordering the data.
var crypto = require('crypto');

// init + update nodeId
var nodeId     = 0;
var nodeIdRand = '0000000000000000000000000000000000000000';

setInterval(function() {

    // regular id
    ++nodeId;

    //random id
    nodeIdRand = crypto.createHash('sha1').update(nodeId.toString()).digest('hex');
}, 1000);

// create server  (port 5500)
var http = require('http');
http.createServer(function(req, res) {

  if(req.url === '/stream') {
      return serverStream(res);
  }
  else if(req.url === '/streamRandom') {
      return serverStream(res, true);
  }
}).listen(5500);

// serve nodeId
function serverStream(res, rand) {

    // headers
    res.writeHead(200, {
        'Content-Type'                : 'text/plain',
        'Access-Control-Allow-Origin' : '*',
    });

    // remember last served id
    var last = null;

    // output interval
    setInterval(function() {

        // output on new node
        if(last != nodeId) {
            res.write('[node id="'+(rand ? nodeIdRand : nodeId)+'"]');
            last = nodeId;
        }
    }, 250);
}

Proof of concept, using aforementioned node.js server code
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

        <button id="stop">stop</button>


text:
Q: ASP.NET Ajax partial postback and jQuery problem A control contains some HTML and some jQuery to handle a fancy tooltip to display when you click an image within a div.
The control is then used on several different pages, sometimes within an updatePanel, sometimes not.
I have the following code to handle loading the jQuery after a partial postback when the control is displayed within an update panel.
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

   function EndRequestHandler(sender, args) {
      $('img.ormdShipping').each(function(){
            $(this).qtip({

        // some qtip options go here
        })
      });
   }

Problem is, the jQuery doesn't load when the control is used anywhere other than an updatePanel. Do I need a second function that's triggered outside of the EndRequestHandler?

A: Just call it once the page loads as well, you can do that by adding this at the end:
$(EndRequestHandler);

This will cause that code to run both when an UpdatePanel refreshes, and when the page first loads.  When you pass in a function to the jQuery constructor, you're calling the jQuery(callback) version, if it's easier to think about, you're doing the short version of this:
$(document).ready(EndRequestHandler); //or..
$(document).ready(function() { EndRequestHandler(); });


text:
Q: My Docker container will run a command from within the container, but not with ENTRYPOINT As stated in the title - after building an image via a Dockerfile, I can enter the image via run -i -t myimage /bin/bash, and then run the command I'd like - it works just fine.
However, doing ENTRYPOINT ['mycommand'] in the Dockerfile does not work.  Please see below:
FROM ubuntu

MAINTAINER bkparso

RUN sed 's/main$/main universe/' -i /etc/apt/sources.list
RUN apt-get update
RUN apt-get upgrade -y

RUN apt-get install -y python-software-properties
RUN add-apt-repository ppa:webupd8team/java -y

RUN apt-get update
RUN echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections

RUN apt-get install -y oracle-java7-installer git unzip

RUN mkdir /opt/torquebox
RUN useradd torquebox -c"Torquebox system user" -M -ptorquebox
ADD http://torquebox.org/release/org/torquebox/torquebox-dist/3.0.1/torquebox-dist-3.0.1-bin.zip /tmp/tboxbin.zip
RUN unzip /tmp/tboxbin.zip -d /opt/torquebox
RUN ln -s /opt/torquebox/torquebox-3.0.1 /opt/torquebox/current
RUN chown -R torquebox:torquebox /opt/torquebox
RUN touch /etc/profile.d/torquebox.sh
RUN echo "export TORQUEBOX_HOME=/opt/torquebox/current" >> /etc/profile.d/torquebox.sh
RUN echo "export JBOSS_HOME=\$TORQUEBOX_HOME/jboss" >> /etc/profile.d/torquebox.sh
RUN echo "export JRUBY_HOME=\$TORQUEBOX_HOME/jruby" >> /etc/profile.d/torquebox.sh
RUN echo "PATH=\$JBOSS_HOME/bin:\$JRUBY_HOME/bin:\$PATH" >> /etc/profile.d/torquebox.sh

ENV TORQUEBOX_HOME /opt/torquebox/current
ENV JBOSS_HOME /opt/torquebox/current/jboss
ENV JRUBY_HOME /opt/torquebox/current/jruby
ENV PATH $JBOSS_HOME/bin:$JRUBY_HOME/bin:$PATH

RUN cp /opt/torquebox/current/jboss/bin/init.d/jboss-as-standalone.sh /etc/init.d/jboss-as-standalone
RUN mkdir /etc/jboss-as && touch /etc/jboss-as/jboss-as.conf
RUN echo "JBOSS_USER=torquebox" >> /etc/jboss-as/jboss-as.conf
RUN echo "JBOSS_HOME=/opt/torquebox/current/jboss" >> /etc/jboss-as/jboss-as.conf
RUN echo "JBOSS_PIDFILE=/var/run/torquebox/torquebox.pid" >> /etc/jboss-as/jboss-as.conf
RUN echo "JBOSS_CONSOLE_LOG=/var/log/torquebox/console.log" >> /etc/jboss-as/jboss-as.conf
RUN echo "JBOSS_CONFIG=standalone-ha.xml" >> /etc/jboss-as/jboss-as.conf
RUN update-rc.d jboss-as-standalone defaults

EXPOSE 6666 8080 8443 5445 8675

ENTRYPOINT ['/opt/torquebox/current/jruby/bin/torquebox']

CMD ["--help"]

/opt/torquebox/current/jruby/bin/torquebox --help works from within the container, but blows up (command not found) from ENTRYPOINT.
Any help would be appreciated.

A: ENTRYPOINT requires double quotes for some reason.
Changed ENTRYPOINT ['/opt/torquebox/current/jruby/bin/torquebox']
To ENTRYPOINT ["/opt/torquebox/current/jruby/bin/torquebox"]
And it loads.


text:
Q: Synchronize on a var in Scala The problem is to search among a few pages of text for an exclamation point concurrently and as soon as any of the threads finds it, all the other threads should stop searching.
Code:
  object AntiVolatile {
    val pages = for (i <- 1 to 15) yield new Page("!Na" * rand.nextInt(1000) + " Batman!", -1)
    var found = Some(false)

    def run(): Unit = {
      for (p <- pages) yield thread {
        var i = 0
        var foundInThread = found.get
        while (i < p.txt.length && !foundInThread)
          if (p.txt(i) == '!') {
            found.synchronized {
              found match {
                case Some(true) => foundInThread = true
                case Some(false) => {
                  p.position = i
                  found = Some(true)
                  Thread.sleep(1)
                }
                case _ =>
              }
            }
          } else i += 1
        // if still not found, wait for another thread to find it.
        def wait(): Unit = {
          found match {
            case Some(false) => wait()
            case _ =>
          }
        }
        wait()
        log(s"results: ${pages.map(_.position)}")
      }
    }
  }

It seems to work ok:
Thread-29: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-27: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-28: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-26: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-30: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-31: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-32: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-25: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-33: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-34: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-39: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-38: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-37: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-36: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Thread-35: results: Vector(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)

But then I realized that found is not a constant instance because it's reassign to a new Option object later. (Why does the code actually work?)
So I came up with a fix:
  object AntiVolatile {
    case class Found(var isFound: Boolean)
    val pages = for (i <- 1 to 15) yield new Page("!Na" * rand.nextInt(1000) + " Batman!", -1)
    val found = Found(false)

    def run(): Unit = {
      for (p <- pages) yield thread {
        var i = 0
        var foundInThread = found.isFound
        while (i < p.txt.length && !foundInThread)
          if (p.txt(i) == '!') {
            found.synchronized {
              found match {
                case Found(true) => foundInThread = true
                case Found(false) => {
                  p.position = i
                  found.isFound = true
                  Thread.sleep(1)
                }
                case _ =>
              }
            }
          } else i += 1
        // if still not found, wait for another thread to find it.
        def wait(): Unit = {
          found match {
            case Found(false) => wait()
            case _ =>
          }
        }
        wait()
        log(s"results: ${pages.map(_.position)}")
      }
    }
  }

These two versions seem to behave the same, why? I would expect some bug cropping up in the first version.
Link to github repo: https://github.com/kindlychung/learnConcurrentScala/blob/master/src/main/scala/org/learningconcurrency/ch2/Ch2.scala

A: It is not entirely clear if you are interested in learning concurrency or if you are solving an actual problem. With that being said, I am going to assume that you are attempting to solve the problem.
Why not use Futures?
import java.util.concurrent.TimeUnit

import scala.concurrent.duration.Duration
import scala.concurrent.{ExecutionContext, Await, Future}
import scala.util.Random
import ExecutionContext.Implicits.global

object Main extends App {

  case class Page(number: Int, text: String)

  val pages = for (i <- 1 to 15) yield Page(i, "!Na" * Random.nextInt(1000) + " Batman! ")

  val searchFutures = pages.map { p => Future {
    val position = p.text.indexOf("!")
    s"Exclamation mark found on page ${p.number} at position: $position"
  }}

  val firstCompleted = Future.firstCompletedOf(searchFutures)

  val result = Await.result(firstCompleted, Duration(5, TimeUnit.SECONDS))
  println(result)

}


text:
Q: How to SUM by group where column has certain value I have a data table like this
| start_date               | end_date             |     sales    | is_finished |
|:------------------------:|---------------------:|:------------:|:------------:
| 2017-03-24 09:11:00      |  2017-03-24 09:11:00 |     30       |       1
| 2017-03-24 08:30:00      |  2017-03-24 08:30:00 |     50       |       1
| 2017-03-24 08:14:00      |  2017-03-24 08:14:00 |     100      |       1
| 2017-03-24 07:30:00      |  2017-03-24 07:45:00 |     200      |       0
| 2017-03-24 07:00:00      |  2017-03-24 07:00:00 |     150      |       1
| 2017-03-24 06:40:00      |  2017-03-24 06:50:00 |     450      |       0

I need to group the rows by start_date and end_date considering that it also be grouped where start date and end date belong to a row with 1. I need also de SUM of every subset.
I need to get next result
| start_date               | end_date             |   SUM(sales) |
|:------------------------:|---------------------:|:------------:|
| 2017-03-24 09:11:00      |  2017-03-24 09:11:00 |     30       |
| 2017-03-24 08:30:00      |  2017-03-24 08:30:00 |     50       |
| 2017-03-24 07:30:00      |  2017-03-24 08:14:00 |     300      |
| 2017-03-24 06:40:00      |  2017-03-24 07:00:00 |     600      |

I have a query, but I have the problem that when there are two rows with is_finished value 1 together the are grouped.
My query is:
SELECT SUM(sales) , MIN(start_date) , MAX(end_date)
FROM sales
GROUP BY
start_date > (SELECT start_date FROM sales WHERE is_finished = 1  ORDER BY end_date ASC LIMIT 1 OFFSET 1 ),
 end_date <= (SELECT end_date FROM sales WHERE is_finished = 1  ORDER BY end_date ASC LIMIT 1)
ORDER BY end_date DESC

Using the query above get me close to expected result but it doesn't work well.
Thanks in advance.

A: This may be helpful,
SELECT MIN(START_DATE) START_DATE
  , MAX(END_DATE) END_DATE
  , SUM(SALES) SUM_SALES
FROM (
  SELECT START_DATE
    , END_DATE
    , SALES
    , SALES_ID
    , ROW_NUMBER() OVER (PARTITION BY START_DATE, END_DATE ORDER BY SALES_ID) RNK
  FROM (
    SELECT SALES.START_DATE
      , SALES.END_DATE
      , SALES.SALES
      , SALES_ID
    FROM
    SALES, (
      SELECT END_DATE
        , ROW_NUMBER() OVER (ORDER BY END_DATE) SALES_ID
      FROM SALES
      WHERE IS_FINISHED = 1
    ) SALES_ID
    WHERE SALES.START_DATE <= SALES_ID.END_DATE
      AND SALES.END_DATE <= SALES.END_DATE
  )
)
WHERE RNK = 1
GROUP BY SALES_ID
ORDER BY START_DATE DESC

A: please try this one
SELECT SEDates.sdate as start_date,SEDates.edate as end_date,SUM(sales)
FROM sales s INNER JOIN
  (SELECT end_date as edate,is_finished,
          @prev as prev,
        CASE WHEN (@prev IS NULL OR @prev = 1) THEN @sdate := start_date
          ELSE @sdate
        END as sdate,
        @prev := is_finished as temp
   FROM sales,(SELECT @prev:=NULL)t
   ORDER BY start_date
   )SEDates
ON s.start_date BETWEEN SEDates.sdate AND SEDates.edate
WHERE SEDates.is_finished = 1
GROUP BY SEDates.sdate,SEDates.edate
ORDER BY SEDates.edate DESC

sqlfiddle


text:
Q: Create Check box's with different object name in Python I am using XML file that has a set of elements inside.
I want to create a check box for each element with different object name so the user can select only one of them and apply specific function for the selected one. so far I was able to loop inside the xml and create the check box's but all with the same object name but this is not good for me since each functionality is link to all selected.
my code looks like this:
import xml.etree.ElementTree as et
tree = et.parse('C:\Python_Projects\Jira_Rest\myviews.xml')
        num_reporters = tree.findall('.//view')

y=160
        p = 0
        for i in range(0, len(num_reporters)):
            view = (my_views[i].attributes['viewname'].value)

            self.checkbox = QtWidgets.QCheckBox(self.centralwidget)
            self.checkbox.setGeometry(QtCore.QRect(160, y, 211, 17))
            font = QtGui.QFont()
            font.setFamily("MS Shell Dlg 2")
            font.setPointSize(9)
            font.setBold(False)
            font.setItalic(False)
            font.setWeight(9)
            self.checkbox.setFont(font)
            self.checkbox.setStyleSheet("font: 75 9pt \"MS Shell Dlg 2\";")
            self.checkbox.setObjectName("checkBox" + str(p))
            self.v.setText(view)
            y+=40
            p=p+1


text:
Q: BlackJack Java: Hand Print Error I have a hand class that has a number of cards. The dealer deals a card to my hand and I want my game to display the cards that the user currently has. Here is the game code where in my GameEngine class I print out the cards in the hand. The problem is that it prints out the whole deck! This is the print out:Your hand: [Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King] of Spades. I only want it to print the one card, not all of them, so what is messed up in my code?
public void beginCardDeal () {
    for (int x = 0; x < 2; x++) {
        System.out.print("\nDealer is dealing a card. . . \n");
        d.dealCard();
        System.out.println("\nYour hand: " + pl.getMyCards());
    }
}

pl is an instance of the Player class since Players have a hand. d is an instance of Deck.
public class Player extends Person {

private Hand myCards = new Hand();
private int playerCashAmount = 100;

public Player() {

}

public Player(String name) {
    this.name = name;
}

public String getName() {
    return super.getName();
}

public int getPlayerCashAmount() {
    return playerCashAmount;
}

public void setPlayerCashAmount(int playerCashAmount) {
    this.playerCashAmount = playerCashAmount;
}

public Hand getMyCards() {
    return myCards;
}

public void setMyCards(Hand myCards) {
    this.myCards = myCards;
}

Also, here is my Deck class:
public class Deck {

private ArrayList<Card> deck = new ArrayList<Card>();
private List<Card> cardUsed = new ArrayList<Card>();

int numCards = 0;

public Deck(int numCards) {
    this.createDeck(numCards, 4);
}

private void createDeck(int numCards, int numSuits) {
    deck = new ArrayList<Card>();
    cardUsed = new ArrayList<Card>();
    if ((numCards % numSuits) > 0) return;
    for (int i=0; i < numSuits; i++) {
        for(int j=1; j <= (numCards / numSuits); j++) {
            deck.add(new Card(new Suit(i), j));
        }
    }
}

public Card dealCard( ) {
    Card dealtCard = null;
    if (deck.size() == 0){
        deck.addAll(cardUsed);
        this.shuffle();
        cardUsed = new ArrayList<Card>();
    }

    dealtCard = deck.get(0);
    deck.remove(0);
    cardUsed.add(dealtCard);

    return dealtCard;
}

public void shuffle() {
    Collections.shuffle(deck);
}

public ArrayList<Card> getDeck() {
    return deck;
}

public void setDeck(ArrayList<Card> deck) {
    this.deck = deck;
}

public int getNumUsedCards() {
    return cardUsed.size();
}

public List<Card> getCardUsed() {
    return cardUsed;
}

public void setCardUsed(List<Card> cardUsed) {
    this.cardUsed = cardUsed;
}

EDIT:
public class Hand {

int total = 0;
private ArrayList<Card> hand = new ArrayList<Card>();

public Hand(){

}

public String toString(){
    //Suit s = new Suit(total);
    //Card c = new Card(s, total);
    //return (Arrays.toString(c.getCardRanks())) + " of " + s.getSuitName();
    return Arrays.toString(hand.toArray());
}

public boolean discardHand(){
    if (hand.isEmpty()) {
        hand = new ArrayList<Card>();
    }
    return false;
}

public void addCard(Card c) {
    this.hand.add(c);
}

public Card getPosition(int index){
    return hand.get(index);
}

public int handCardCount(){
    return hand.size();
}

public int getTotal() {
    return total;
}

public void setTotal(int total) {
    this.total = total;
}

public ArrayList<Card> getHand() {
    return hand;
}

public void setHand(ArrayList<Card> hand) {
    this.hand = hand;
}

A: When you deal a card, you don't add it to the players hand.

A: Your objects need to better reflect the nature of what they represent: a deck and a hand are each just an ordered set of cards, so using an underlying array list (or a simple array) for them is fine. "Dealing" a card is the act of moving a card from the deck to a hand, so it should either be a method of the deck object taking the hand to deal to as an argument, e.g. deck.dealTo(hand), or else return a card and use an assignment, e.g. hand.add(deck.deal()). Your present d.dealCard() removes a card from the deck and drops it on the floor. It also deals in a strange way--I can't imagine any game in which when the deck is exhausted you just shuffle a new deck and keep dealing!
Likewise, the player object should contain a reference to a hand object (or maybe none, or more than one, depending on the game), but you don't deal to players, you deal to hands. Also some "hands" may not be associated with a player at all, like the "crib" in cribbage or the "board" in Texas Hold'em.


text:
Q: type casting shared memory pointer to integer pointer int main()
{
    key_t key = ftok("yu", 65);
    int shmid = shmget(key, 100 * sizeof(int), 0666 | IPC_CREAT);
    int** Matr = (int**)shmat(shmid, (void*)0, 0);

    for (int i = 0; i<3; i++)
    {
        for (int j = 0; j<3; j++)
        {
            Matr[i][j] = i + j; // writing to shared memory
        }
    }

    shmdt(Matr);
    return 0;
}

I am trying to type cast the shared memory pointer to integer double pointer however every time I compile the code, it says that segmentation fault(core dumped). Can someone tell me how to do this? Thanks in advance.
P.S : I am doing this on C++.

A: You can try the following code.
The main difference is that the matrix is implemented with a 1D continous block of memory (an array), and therefore Matr is of type int*.
The management of the 2D indices of the matrix is done "manually" by calculating an index in the array (idx) from the 2 matrix indices (i,j).
Note: I advise you to add error handling for all the system calls.
#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
    key_t key = ftok("yu", 65);
    // check if key is -1 and if so handle the error ...
    int shmid = shmget(key, 100 * sizeof(int), 0666 | IPC_CREAT);
    // check if shmid is -1 and if so handle the error ...
    int* Matr = (int*)shmat(shmid, (void*)0, 0);
    // check if Matr is (void*)-1 and if so handle the error ...

    int width = 3;
    int height = 3;
    // NOTE: width * height must be <= 100 (according to the declared size of the shared memory).

    for (int j = 0; j<height; ++j)
    {
        for (int i = 0; i<width; ++i)
        {
            int idx = j * width + i;
            Matr[idx] = i + j; // writing to shared memory
        }
    }

    int st = shmdt(Matr);
    // check if st is -1 and if so handle the error ...
    return 0;
}


text:
Q: How could I store each character being selected into a varaible? JS Full Html Code:

Welcome To My Playground

Stuff Happens Here.

Pointing Towards Specific Problem
// Main function, Gathers characters W,T,M,P in myString
// As long as (I) has a lower value than myStrings length it keeps searching for characters
for (var i = 0; i < myString.length; i++) {
    // Gathers characters W T M P
    if (myString[i] == "W" || myString[i] == "T" || myString[i] == "M" || myString[i] == "P") {
        matchedIndexes.push(new myMatch(myString[i], i));
    }
}

I would like the characters W T M P to be stored into a variable.
Preferably one variable but I could work around with multiple.
I don't know how to set them as a variable.

A: Extend the variable:
$somestring='';
for (var i = 0; i < myString.length; i++) {
    $somestring+=myString[i];
}
console.log($somestring);

A: Based on your comments;
You are already collecting these letters in to a variable (array) - matchedIndexes.
Unfortunately, what you want to do (hide each character using display: none) can't be achieved in the way you're hoping. Each of these are characters within a string - not an element. One way to achieve this is to remove the characters from the string and put it back in to your div, like so;
if (myString[i] != "W" || myString[i] != "T" || myString[i] != "M" || myString[i] != "P") {
    matchedIndexes.push(new myMatch(myString[i], i));
}

var text = matchedIndexes.toString();
document.getElementsByClassName(".sod-1")[0].innerHTML = text;


text:
Q: Downloading features from website with interactive map as shapefiles? I found an interactive map on a website: here
The map on the website looks like this:

Is there any way to do download the red lines as shapefiles?

A: You can add the layer ( arcgis.com/home/item.html?id=c89a8b2ea94241a7875f7a469feba66a) into ArcMap and export it as a FC or SHP.

A: It is available in JSON the direct link is
it is in json format:
Direct link to JSON
This can be converted using ETL Tools to shapefiles.
(The link was too long for a comment so posted this as an answer.)


text:
Q: Data reversed in 3D plotting? I am confused by the plotting of a 3D graph.
Firstly, the matrix for x and y-axis are shown below.
x =
 0    71   142   213   284   355   426
 0    71   142   213   284   355   426
 0    71   142   213   284   355   426
 0    71   142   213   284   355   426
 0    71   142   213   284   355   426
 0    71   142   213   284   355   426

y =
 0     0     0     0     0     0     0
71    71    71    71    71    71    71
142   142   142   142   142   142   142
213   213   213   213   213   213   213
284   284   284   284   284   284   284
355   355   355   355   355   355   355

and the data is shown below.
Data =
   16       16       16       27       29      24       21
   17       17       15       26       29       16      16
   15       13       12       25       34       14      15
   12       10        9       28       18       11      11
   77        9        6       62        7        9       8
    4        4        4      131        3        4       6

Then I used this code.
mesh(x,y,Data)
xlabel('x')
ylabel('y')
zlabel('Data')

And I got this graph:

What I am confused by is why the point of Data(6,4)=131 is at point (1,4) in the graph.
Also, you can see that the point of Data(5,1)=77 is at the point (1,2) in the graph.
Why does the position of any points in the graph reverse in up-down direction with the position in the matrix?
Is this a normal thing? Or, is there any problem in my code.
I am newcomer in Matlab but feel this up-down reversed plot is strange in my common sense.

(Edit) Thanks Dan, then I will describe why the exact shape of data is important to me. My work is to measure some specific parameter, such as humidity, in a room. The "spatially" measured result is shown "exactly" below.
16       16       16       27       29      24       21
17       17       15       26       29       16      16
15       13       12       25       34       14      15
12       10        9       28       18       11      11
77        9        6       62        7        9       8
 4        4        4      131        3        4       6

According to the data, the humidity in the South direction of the room is highest (131). However, when I make a graph in MATLAB, the point 131 turns to be at the North direction of the "Mathematical model" as shown in the graph above. So, it makes me difficult to put that graph into a report. I know that I can rotate the graph but if I rotate, the origin point turns to be strange and also causes other left-right reverse problem instead. You may say that my graph is Mathematically correct but it is still strange to make a report with this reverse problem. Is there any way to fulfill this task? I have tried to reverse the data in up-down and left-right direction in the matrix but it doesn't help.

A: The point with value 131 is not at point (1,4) in your graph at all but rather at x-y-point (213,355) which is exactly correct. All you need to do to get what it sounds like you desire is rotate the image... there is nothing wrong here. It is very simple to rotate from the figure window, or else you could do it programatically too


text:
Q: streaming a video from website android I am new to android.
I have created a simple example for playing video files with the videoView.
the xml part contains only one Button and a VideoView,
Here is the code for ButtonClick
@Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            Uri uri = Uri.parse("http://www.learnixmba.com/doajax.php?profile=2809");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setDataAndType(uri, "video/*");
            startActivity(intent);

        }

when I try running this app on Emulator I am getting error message as "Cant Play Video"
Why I am getting this message and the logcat shows one error as
12-30 05:25:37.623: E/cutils-trace(1370): Error opening trace file: No such file or directory (2)

need answers and advises
Thanks in advance
edit:
I tried loading this same video url to a webView.,
and it shows...,
"some of your technology may be out of date this video may not play properly"
what is the problem ? am I using outdated tools??

A: You have to provide a direct link to your video.
Try to change this line:
 Uri uri = Uri.parse("http://www.learnixmba.com/doajax.php?profile=2809");

To this:
 Uri uri = Uri.parse("http://pdl.vimeocdn.com/01593/020/145269025.mp4?token2=1388403392_f17d62baae773f48f5b1565a69857345&aksessionid=1ba8f3ac4cafca62");

EDIT:
DISPLAY YOUTUBE VIDEOS
String videoId = "0HDsz3C9IHg"; // id of the youtube video you want to display
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+videoId));
intent.putExtra("VIDEO_ID", videoId);
startActivity(intent);

OR DIRECT LINK TO VIDEO, PLAYING IN THE YOUTUBE PLAYER:
Intent videoClient = new Intent(Intent.ACTION_VIEW);
videoClient.setData("VALID YOUTUBE LINK WITH HTTP");
videoClient.setClassName("com.google.android.youtube","com.google.android.youtube.WatchActivity");
startActivity(videoClient);


text:
Q: JetBrains rider IDE => Hosting Environment enter image description hereI am trying to move from Visual Studio 2022 to JetBrains rider with my .NET full-stack project.
I am using Webpack for my front-end side if it gives anyone a clue (I also run the Webpack command like in my vs2002).
The problem which occurs is the HostingEnvironment.IsDevelopmentEnvironment always returns false.
I tried to set it from the terminal with the ASPNETCORE_ENVIRONMENT=Development command and in the configuration setting of debug mode of my project with no luck. I can't find any solution to this problem.
// different script for dev or prod
string scriptFileName = HostingEnvironment.IsDevelopmentEnvironment ? "/dist/app.entry.js" : "/dist/app.entry.min.js";

A: You're mixing up two things: ASP.NET vs. ASP.NET Core. The environment variable ASPNETCORE_ENVIRONMENT is used by ASP.NET Core, whereas the method HostingEnvironment.IsDevelopmentEnvironment is only part of old ASP.NET.
As you already discovered, you have to set DEV_ENVIRONMENT=1 and I see two options:

*

*Set environment variable system-wide

*Set environment variable within Rider configuration

1. System-wide
This implies that all consumers (your app, integration tests, etc.) use the same value, i. e. all apps are in development mode. It depends on your needs whether this is acceptable or not.
Assuming that you're working on Windows, you can either set the environment variable via GUI (see here) or CLI (see setx command).
Keep in mind that environment variables are picked up on application startup. So you have to restart Rider after changing the variable.
2. Rider
Open the Run Configurations and configure it like this:

You have to do this for all your Run Configurations.

A: Add DEV_ENVIRONMENT=1 to your project run configuration in your JetBrains IDE.


text:
Q: Link to an anchor within JQuery tabbed content You can find my example  [here]
The tabs are working well but just need that extra functionality.
I have  next to the header "Anchor" within the "Stuff" tab.
By default the first tab is selected but if someone clicks on a link Go to anchor then I would like to take them to the third tab and scroll down to .

A: Few changes I made are added goto attribute in anchor tag so that we know which tab to move to.

added the below code to navigate to the anchor tag inside stuff tab
$('html, body').animate({
   scrollTop: x // where a tag is
});

DEMO
Update: How the Demo works
In the demo are 3 tabs plus content. In the first tab-content is a link to the tab 'Stuff'. If you click on this link the tab changes and the content of the  tab 'Stuff' will be shown.  The link to change the tab looks like this switch to Tab Stuff .
The value of goto must be the same value as the hash tag of the tab
Stuff
. The function below gets the value of the attribute 'goto' puts the value into the var whereTo and executes a click on the selector matching 'a[href=#' + whereTo + ']'
$('a').not('.tabs li a').on('click', function(evt) {
    evt.preventDefault();
    var whereTo = $(this).attr('goto');
    $tabs = $("ul.tabs li");
    $tabs.find('a[href=#' + whereTo + ']').trigger('click');
    // code shortened to keep explanation simple
}

Hope this helps