text:
Q: Legacy Cytoscape Attributes Format not importing Reading the documentation, section 8.2 here: http://manual.cytoscape.org/en/stable/Node_and_Edge_Column_Data.html
The docs state that the legacy attributes format is still supported in cytoscape 3.8. I have a legacy attribute file in the following format:
LinkerHeats
PKC = 0.05283780217268941
CDKN1B = 0.9230103703466229
RAS = 0.001407567832956147
BRCA1 = 0.0005058090659030887

However when I try to import the file using File -> Import -> Table from file... I cannot find a way for cytoscape to recognize anything but a single column, and it throws an error:
Table must have more than one column. Please check the selected delimeters and columns.

The import dialog is shown:

I can manually convert the file to CSV and import it, but it's a bit annoying to need the conversion utility since the docs suggest this should work.

A: I'm not sure why, but I was able to import that file by deleting the first line of the file (e.g. the column label) and using "=" as the delimiter.  Obviously you have to rename the column before the import, but I was able to get it to work without having to convert it.  The documentation is clearly wrong and we'll make sure to remove that comment as I think we removed support for that format several releases ago when we cleaned up our File menu.
-- scooter


text:
Q: What does "All your responses for all questions should not exceed one page" mean? I am presented with six questions that I'm required to respond to in writing. Some of the questions are:

*

*What do you believe in?

*What learning experiences have had the greatest impact in your life? etc etc.

The only instruction given is that:

All your responses for all questions should not exceed one page.

What does that mean? I am torn between two possibilities:

*

*The answers to each question must not exceed one page (my final submission should be at most six pages).

*The answers to all six questions must not exceed one page (my final submission should be at most one page).

A:
All: pronoun, singular or plural in construction
the whole number, quantity, or amount : TOTALITY; "all that I have"; "all of us"; "all of the books".
Merriam Webster

The all in "all questions" stands for the totality of the questions.
The all in "all your responses" stands for the totality of your responses.
At the most basic level, omitting the qualifying phrase "for all questions", the instructions say: "All your responses should not exceed one page." This means that the totality of your responses should not exceed one page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java's Thread sleep method not behaving as expected i want to sleep one thread on my propram,but it put two thread to sleep,so what's my problem,please help?
public class TestWait extends Thread{
    static TestWait t1;
    static TestWait t2;

    public void run()
    {
        while(true)
        {
            try {
                t1.sleep(10000);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }
    }

    public static void main(String [] args) throws InterruptedException
    {
        t1 = new TestWait();
        t2 = new TestWait();

        t1.start();
        t2.start();

        t1.setName("t1");
        t2.setName("t2");
    }

}

A: Thread.sleep is static method which makes thread which invokes it sleep for amount of millisecconds. Your code
t1.sleep(10000);

in reality is same as
Thread.sleep(10000);

A: That method puts the "currently executing thread to sleep".  It should not be called against an instance that way.  http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep%28long%29

A: I'm sure you have a warning in t1.sleep():
Thread.sleep(int) pauses the current threat, so as run() implementation is shared by both objects, both of them are paused. You can change it and do something like this:
public class TestWait extends Thread{
    static TestWait t1;
    static TestWait t2;

    private boolean flag

    public TestWait(boolean wait) {
         this.flag=wait;
    }

    public void run() {

     while(true) {
            try {
                if (flag) {
                    Thread.sleep(10000);
                }
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }
    }

    public static void main(String [] args) throws InterruptedException {
        t1 = new TestWait(true);
        t2 = new TestWait(false);

        t1.start();
        t2.start();

        t1.setName("t1");
        t2.setName("t2");
    }

}

A: In Java, you can invoke static methods using a reference to a class instance, even if this reference is null... If you have a static method s in class A, then all of these work:
final A a = new A();
final A nullA = null;

A.s(); // via class
a.s(); // via non null reference
nullA.s(); // via null reference

And Thread.sleep() is static.
In order to avoid confusions, don't use this method but use TimeUnit instead:
TimeUnit.SECONDS.sleep(10);


text:
Q: Youtube script with API on eggdrop not showing correct charset Got some issues with Youtube API, it doesnt show åäö in titles. Urltitle script does, after an eggdrop recompile. So any suggestions how to make 2nd script use utf8 or so?

A: There are two key problems here:

*

*Ensuring that the data from the data source is understood correctly by Tcl.

*Ensuring that the correct data known by Tcl is reported to the channel in a way that it can digest.

Hopefully the first is already working; the http package and the various database access packages mostly get that right (except when the data source tells lies, as can happen occasionally with real-world data). You can test this by doing:
set msg ""
foreach char [split $data ""] {                # For each UNICODE character...
    append msg [format %04x [scan $char %c]];  # The hex code for the char
}
putserv "PRIVMSG $chan :$msg"

For example, this would generate a message like this for data of åäö€:

00e500e400f620ac

If that's working (it's the hard part to solve if it isn't), all you've got to do is ensure that the data actually goes correctly to the channel. This might be as simple as doing this (if the Tcl side of the channel is in binary mode):
putserv "PRIVMSG $chan :[encoding convertto utf-8 $data]"

In theory, the Tcl channel that putserv writes on could do the conversion for you, but getting that part right is tricky when there's unknown code between your code and the actual channel.
It's also possible that the IRC server expects the data in a different encoding such as iso8859-15. There isn't a universal rule there, alas.


text:
Q: Creating a function with integral zeroes of the 0th, 1st, and 2nd derivatives I would like to be able to randomly generate functions, each of which satisfies

*

*$f : [-10, 10] \rightarrow [-10, 10]$

*All the zeroes, critical points, and inflection points have an integral $x$-value

*Some of the critical points -- $x$-values where $f'(x) = 0$ -- are local extrema, but some aren't

*Some of the zeroes are also at local extrema (like $x=0$ in the function $y=x^2$), and some aren't
It's easy to draw such a function by hand and then define a piecewise function that looks similar.  The hard part, for me, is finding an algorithm that generates these functions with some randomness.  I was approaching this by taking functions of the form $y=a (x-b)^2 + c$ and gluing them together so that the points and derivatives match up.  (If the second derivatives don't match up, that's ok -- my Mathematica method will still identify the "gluing" points as inflection points.)  This works fine if I'm only worried about critical points and inflection points, but seems to become very difficult when trying to respect the zeroes condition.
Can anyone think of a tractable algorithm for this?
EDIT: the randomness needs to be present beyond just, say, a scalar multiple.  The goal is to show graphs of these functions to students and ask them to visually identify zeros / critical points / inflection points, and so different functions should correspond to usefully-different problems.

A: Numerically doing one can easily use inbuilt Interpolation as follows.
(* Random number of zeros, critical points and infliction and where they occur *)
{zeros, crit, inflic} =Union /@(RandomInteger[{-10, 10}, #] & /@ RandomInteger[{1, 5}, 3]);
(* Gather the conditions as per the point of occurrence *)
rules = GatherBy[Flatten@
MapThread[Thread[Rule[#1, #2]] &,{{zeros, crit, inflic}, Range[0, 2]}],First];
args = DeleteDuplicates /@ rules[[All, All, 1]];
(* random value of the function, limit of values of 1st derivative, similar limit for 2nd *)
random[] := {RandomInteger[{-10, 10}], RandomInteger[{-1, 1}],RandomInteger[{-1, 1}]};
(* apply the above generated conditions *)
vals = With[{val = #},
     ReplacePart[random[], (# -> 0) & /@ val]] & /@ (1 + rules[[All, All, 2]]);
rest = ({{#}}~Join~random[]) & /@ (Complement[Range[-10, 10, 1],args // Flatten]);
(* create values for left over integer points in [-10,10] and interpolate *)
fun = Interpolation[SortBy[Join[rest, MapThread[Join[{#1}, #2] &,{args, vals}]],First],
      InterpolationOrder -> 3];

Now we can see the order of derivative conditions to be fulfilled at the random integral points on $[-10,10]$.
randAtrributes =SortBy[Thread@Rule[Flatten@args, rules[[All, All, 2]]], First]

{-9 -> {2}, -8 -> {0, 2}, -7 -> {2}, -6 -> {1}, -5 -> {0}, -1 -> {0},
   4 -> {1}, 5 -> {1}, 7 -> {1}, 8 -> {2}}

Now we see the randomly generated conditions
expr = MapAt[D[f[x] == 0, {x, #}] &,randAtrributes[[All, 2]], {All, All}]

{{(f^[Prime][Prime])[x] == 0}, {f[x] ==
     0, (f^[Prime][Prime])[x] == 0}, {(f^[Prime][Prime])[x] ==
     0}, {Derivative1[f][x] == 0}, {f[x] == 0}, {f[x] ==
     0}, {Derivative1[f][x] == 0}, {Derivative1[f][x] ==
     0}, {Derivative1[f][x] == 0}, {(f^[Prime][Prime])[x] == 0}}

Above interpolating function fulfills the conditions
MapThread[#2 /. x -> #1 /. f -> fun &, {randAtrributes[[All, 1]], expr}]

{{True}, {True,True}, {True}, {True}, {True}, {True}, {True}, {True}, {True}, {True}}

Now some plot for visual check!

Plot code:
pt = randAtrributes[[All, 1]];
Plot[fun[x], {x, -10, 10}, PlotRange -> {{-12, 13}, {-12, 12}},
 Frame -> True, Axes -> {False, True},
 AxesStyle -> {None, Directive[Dashed, Black]},
 Epilog -> {{Dashed, Thin, Opacity[.7], Gray,
    Line[{{#, 0}, {#, fun[#]}, {0, fun[#]}}] & /@ pt}, {Red,
    PointSize[0.01], Point[{#, fun[#]}] & /@ pt},
   Flatten@MapThread[{pos = {#2 + RandomReal[{.5, 1}],
         fun[#2] + RandomReal[{.5, 2}]};
       Inset[Style[Column[TraditionalForm /@ (#1 /. x -> #2)],
         Magenta], pos,
        BaseStyle -> {10, FontFamily -> "Calibri", Bold}], Orange,
       Thin, Dashed, Arrowheads[.015],
       Arrow[{pos, {#2, fun[#2]}}]} &, {expr, pt}]}]

A: Here's one way to get started:
spec = RandomInteger[{-9, 9}, 3];
p[x_] := a x^5 + b x^4 + c x^3 + d x^2 + e x + f;
p2[x_] = D[p[x], x];
p3[x_] = D[p2[x], x];
sol = FindInstance[
   p[spec[[1]]] == 0 && p2[spec[[2]]] == 0 && p3[spec[[3]]] == 0 && f > 0,
   {a, b, c, d, e, f}, Reals];
Plot[(p[x] /. sol)/p[9] /. sol // N, {x, -10, 10}]

This builds a 5th order polynomial and then forces the roots of the polynomial and its derivatives to be random integers. It then uses FindInstance to choose specific values for the coefficients. Each time you run the code, you get a different set of integer points, and hence a different polynomial. Because 5th order polys can get large at x=10, I scaled the final polynomial (by the value at p[9]).
As Szabolcs points out, this ensures that the specified critical points must exist in the polynomial, but there may occur other critical points depending on the vagaries of the solution found by FindInstance. If it is important to have all the critical points lie on integer values, then it would be easy to add a test to see if any extra critical points have appeared -- if so, then try again.

A: I ended up solving this using the algorithm below.  This was rather complicated (which is why I'm only describing the process, and have omitted both the actual code and several small details), so maybe there's a better way.
1) Randomly pick the critical points, with the restriction that their slopes have to have absolute value between 1 and 3, and that their x-coordinates have to be a distance of between 2 and 5 apart.
2) Between each pair of critical points, pick the number of inflection points, and their x-coordinates.  Randomly determine y-values based on several constraints.
3) Between each pair of critical points, determine if there is going to be a zero.  Find the x-value assuming it's on the line between the two critical points, and then floor or ceiling that x-value depending on several factors.
4) Determine derivative values at each point.
5) Compile all the points together (criticals, inflections, and zeros) so you have a collection of all your x-values, y-values, and derivative values.  Join each adjacent pair of points by using FindInstance on the function a/(x+b) + cx + d, with the restriction that the vertical asymptote can't lie in the interval on which this function will be defined.  Mathematica handles this easily, and this function is able to join together any two points with any two slopes, without changing concavity.  (*The slopes do have to be compatible with a fixed concavity, and there are still occasional restrictions on slope, but this is a small point.)
6) The final result is a piecewise function with all the above FindInstance functions each defined over the interval that was used to generate it.
I'm still tweaking some of the random-generation parameters to make it look a little smoother, but here is one of the earlier curves I randomly generated, and you can see it has all the required properties.


text:
Q: How to shift ubuntu OS from Logical Partition to Primary Partition? I was new to Linux and Partition concepts when I installed Ubuntu on my machine, which already ran windows 7. At first, I created some unallocated space (~100GB). But at that time, I didn't know it was in Extended partitions section.And because of that, Ubuntu was installed in Extended Partition section.
Now I have to increase the size of my ubuntu logical partition. But not enough space is left in th eextended partition section. So, I'm thinking of moving the OS from Extended Partition section to Primary partition, which already contains windows 7 (My machine has both OS).
So, my question is, which is the most optimal way to remove ubuntu from logical partition, and also retain windows in primary partition?
Thanks for answering.
Some extra info before finishing. My extended partition constains 2 logial partitions, one of which contains ubuntu. The other partition is unallocated space. I tried a lot to merge them, to get a larger space for ubuntu. I don't know why, but I'm unable to merge those two partitions.
If possible, plz do provide a sol. to this as well.
Thanks again.


text:
Q: contact form (specifice slection) and email I want to make a contact form and my problem is :

*

*by the option select the contact type (peter or Michael) , if i want to contact for example peter and press the submit button it the form goes to his email example peter@gmail.com and so on.... how to solve the problem inside (select option && contact_procees code) please advise me

//// contact.php /////

 <form class="contact-form" method="post"  name="contact"  id="f">

       Contact Person  :
     **strong text**  <select id="agents">
      <option value="1">Peter</option>
      <option value="2">Michael</option>
    </select>

       Text :
       <textarea style="background-color:#f5f5f5; color:#000" name="msg" type="text" class="contact-textarea"></textarea>

    <input type="reset" class="submit" value="Reset" />

    <input type="submit" class="submit" value="Send"  onclick="sendForm(); return false;" id="btn" />

 </form>

/// JAVA SCRIPT CODE SEND FOR

//// contact_process.php

<?php
error_reporting(0);
echo "1";

function error(){
 exit("0");
}

if(!isset($_POST['name']) or !isset($_POST['work']) or !isset($_POST['subject']) or !isset($_POST['msg'])){
  error();
}

$name=$_POST['name'];
$work=$_POST['work'];
$subject=$_POST['subject'];
$msg=$_POST['msg'];

if($name=="" or $work==""  or $subject=="" or $msg==""){
error();
}

$message=
Name : '.$_POST['name'].'

Work : '.$_POST['work'].'

contact : '.$_POST['subject'].'

Text : '.$_POST['msg'].'

';

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From:Mypage Website <webmaster@mypage.com>' . "\r\n";

$subject="Contact";
$to="peter@gamail.com"; /// what should i do for others

mail($to,$subject,$message,$headers);
?>

A: You can put your email id in select value like
    <select id="agents" name="agents">
      <option value="peter@gmail.com">Peter</option>
      <option value="michael@gmail.com">Michael</option>
    </select>

Get it in php like
    $to = $$_POST['agents'];

and then send the email like you are sending
   mail($to,$subject,$message,$headers);

I hope answred the question.

A: I would POST the form to a page called "sendmail.php" and there pick up the selected value (peter/micheal).
You can name them 1 and 2 if you like.
The thing about having it javascript or in the html code is that the mail is in plain sight.
There are robots crawling for mails and the mails printed in html are a likely victim.
Once the send has been done you could echo out thank you and it worked, or did not work.
But my advice is POST the values and send them in php, that way it's secure from crawlers


text:
Q: No Such Module even after installing the framework via cocoa pods I am trying to integrate a framework/library for creating appealing forms in iOS, using this one: https://github.com/ortuman/SwiftForms
I was able to install Cocoapods. I also added the following in my Podfile (in my project's directory):
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'SwiftForms'

And run the command: $ pod install
But in my class, I still get 'No such module 'SwiftForms'.

And what does the color red indicates here:

When I open the xworkspace, I get these errors:

A: I have just created a sample app to understand your issue.
Just follow these steps carefully.
Step.1 Updated my Podfile with SwiftForms Lib

platform :ios, '8.0'
use_frameworks!
pod 'SwiftForms'

Step.2 Open terminal at Podfile's parent folder and run command

pod install

Step.3 open project_name.xcworkspace file to open Project with pods
Step.4 Go to Project Settings --> Build Phases --> Add SwiftForms.framework

Step.5 Now goto the Viewcontroller.swift and import
import UIKit
import SwiftForms

class ViewController: FormViewController {

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

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

It works like charm!! let me know if you find any trouble in this.

A: By setting the "Build Active Architectures Only" to No, in main project and Pods subproject helped me to fix the above error.
https://stackoverflow.com/a/43557775/5177699


text:
Q: C++ Call subclass method from superclass I have code of the following style:
class SubClass;
class SuperClass;

class SuperClass {

private:

    void bar() {

        SubClass().foo();
    }
};

class SubClass : SuperClass {

public:

    void foo() {};
};

So basically I have a SuperClass from where I want to call a method foo() of the subclass.
VS 2012 gives me the following errors:
Error 1 error C2514: 'SubClass' : class has no constructors.
Error 2 error C2228: left of '.foo' must have class/struct/union.
What is the correct structure for what I want to do?

A: You can't do this. You must (at least) declare the method in the base class. For example:
#include <iostream>

class SuperClass
{
public:
    void bar()
    {
        foo();
    }
private:
    virtual void foo() // could be pure virtual, if you like
    {
        std::cout << "SuperClass::foo()" << std::endl;
    }
};

class SubClass : public SuperClass // do not forget to inherit public
{
public:
    virtual void foo() { std::cout << "SubClass::foo()" << std::endl; }
};

int main()
{
    SuperClass* pTest = new SubClass;

    pTest -> bar();

    delete pTest;
}

will print SubClass::foo().

A: you can try with some CRTP,
ie:
#include <iostream>

class SubClass;

template<typename T>
class SuperClass {
private:
    void bar() {
        ((T *) this)->foo();
    }
public:
    void foobar() {
        this->bar();
    }
};

class SubClass : public SuperClass<SubClass> {
public:
    void foo() {
        std::cout << "hello crtp!" << std::endl;
    };
};

int main(void){
    SubClass a = SubClass();
    a.foobar();
    return 0;
}

A: First, you have to realise that calling SubClass().foo() has nothing to do with the current object - it will create a new SubClass object and call its foo member. If you want the bar function to call foo on the current object, you need to declare foo as a virtual function in the base class, as Kiril suggested.
However, if you do want to call foo on a new object (which doesn't make much sense, but whatever), you are doing it correctly. Your example didn't compile because SubClass is forward declared, but not defined before bar function - you might want to move the implementation of bar below the definition of SubClass, like so:
    class SubClass;
    class SuperClass;
class SuperClass {

private:

    void bar();
};

class SubClass : SuperClass {

public:

    void foo() {};
};

void SuperClass::bar() {
    SubClass().foo();
}


text:
Q: WriteFIle freezes My program freezes on the next string, when it runs from the remote directory.
::WriteFile(dst, ::LockResource(resource_data), resource_size, &written_size, NULL);

All arguments are right and output file is located in the %TEMP%.
It looks like security policies denies to write to the file but system doesn't shows any notifications about this.
Same code works good if program runs from the local directory.
I found no information about this case on the MSDN.
UPD: SSCCE.
bool ExtractResourceTo(const std::wstring& filename) {
  CHandle file(::CreateFile(filename.c_str(), GENERIC_WRITE, 0, 0,
                            CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  if (INVALID_HANDLE_VALUE == file) {
    LOG("Cannot create file.");
    return false;
  }
  const HINSTANCE instance = _AtlBaseModule.GetModuleINstance();
  HRSRC resource = ::FindResource(instance, kResourceName,
                                  RT_RCDATA);
  if (resource) {
    HGLOBAL resource_data = ::LoadResource(instance, resource);
    DWORD resource_size = ::SizeofResource(instance, resource);
    if (resource_data && resource_size > 0) {
      DWORD written_size;
      LPVOID resource_ptr = ::LockResource(resource_data);
      if (!resource_ptr) {
        LOG("Cannot lock resource.");
        return false;
      }
      ::WriteFile(file, resource_ptr, resource_size,
                  &written_size, NULL);
      if (written_size == resource_size) {
        return true;
      }
      LOG("Write failed.");
    }
  }
  return false;
}

A: It seems that this is ''optimization'' of windows. System starts process and doesn't loads resources immediately. When WriteFile trying to access resource, system pauses the thread and reads given resource into the memory, but executable file is on the remote machine and downloading of resource takes really long time, because my resource has near 180MiB.
Thanks to everybody, who tried to resolve my problem.


text:
Q: Implementing a Windows Service with ctypes. ServiceCtrl handler not called I am trying to implement a Windows service in Python with ctypes.
import ctypes
import logging
import logging.config
import threading

import six

logger = logging.getLogger("service3")

SERVICE_MAIN = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_uint32)
HANDLER_FUNCTION = ctypes.WINFUNCTYPE(ctypes.c_uint32, ctypes.c_uint32)

class ServiceTable (ctypes.Structure):
    _fields_ = [("serviceName", ctypes.c_char_p),
                ("serviceProc", SERVICE_MAIN),
                ("serviceNameTerm", ctypes.c_char_p),
                ("serviceProcTerm", ctypes.c_void_p)]

class ServiceStatus (ctypes.Structure):
    _fields_ = [("dwServiceType", ctypes.c_uint32),
                ("dwCurrentState", ctypes.c_uint32),
                ("dwControlsAccepted", ctypes.c_uint32),
                ("dwWin32ExitCode", ctypes.c_uint32),
                ("dwServiceSpecificExitCode", ctypes.c_uint32),
                ("dwCheckPoint", ctypes.c_uint32),
                ("dwWaitHint", ctypes.c_uint32)]

advapi32 = ctypes.windll.advapi32
kernel32 = ctypes.windll.kernel32

advapi32.StartServiceCtrlDispatcherA.argtypes = [ctypes.POINTER(ServiceTable)]
StartServiceCtrlDispatcherA = advapi32.StartServiceCtrlDispatcherA

advapi32.SetServiceStatus.argtypes = [ctypes.c_void_p, ctypes.POINTER(ServiceStatus)]
SetServiceStatus = advapi32.SetServiceStatus

advapi32.RegisterServiceCtrlHandlerA.argtypes = [ctypes.c_char_p, HANDLER_FUNCTION]
advapi32.RegisterServiceCtrlHandlerA.restype = ctypes.c_void_p
RegisterServiceCtrlHandlerA = advapi32.RegisterServiceCtrlHandlerA

SERVICE_WIN32_OWN_PROCESS = 0x10

SERVICE_ACCEPT_STOP = 0x1

SERVICE_CONTROL_STOP = 0x1

SERVICE_RUNNING = 0x4
SERVICE_STOPPED = 0x1
SERVICE_STOP_PENDING = 0x3

class Service:
    serviceName = "RSJTest"
    ServiceStatusHandle = None

    def __init__(self):
        self.TerminateEvent = threading.Event()

    def StartMain(self):
        try:
            logger.debug("ServiceMain")
            self.serviceProc = SERVICE_MAIN(self.StartMain2)
            self.serviceTable = ServiceTable(serviceName=self.encode(self.serviceName), serviceProc=self.serviceProc)
            StartServiceCtrlDispatcherA(self.serviceTable)

        except:
            logger.exception("ServiceMain")

    def StartMain2(self, argC):

        try:
            logger.debug("StartMain2 %d", argC)

            self.handlerProc = HANDLER_FUNCTION(self.HandlerProc)

            self.ServiceStatusHandle = RegisterServiceCtrlHandlerA( self.encode(self.serviceName), self.handlerProc)
            logger.debug("ServiceStatusHandle %xd", self.ServiceStatusHandle)

            self.SetServiceStatus(SERVICE_RUNNING)

            self.Start()
            logger.debug("Start returned")

            self.SetServiceStatus(SERVICE_STOPPED)
        except:
            logger.exception("StartMain2")
        return 0

    def Start(self):
        self.TerminateEvent.wait()

    def Stop(self):
        self.TerminateEvent.set()

    def HandlerProc(self, dwControl):
        try:
            logger.debug("HandlerProc")

            if dwControl == SERVICE_CONTROL_STOP:
                self.SetServiceStatus(SERVICE_STOP_PENDING)

                self.Stop()

        except:
            logger.exception("HandlerProc")
        return 0

    def SetServiceStatus(self, newStatus):
        serviceStatus = ServiceStatus(dwServiceType=SERVICE_WIN32_OWN_PROCESS,
                                      dwCurrentState=newStatus,
                                      dwControlsAccepted=SERVICE_ACCEPT_STOP)

        ret = SetServiceStatus(self.ServiceStatusHandle, serviceStatus)
        logger.debug("SetServiceStatus returned %d", ret)

    def encode(self, stringParm):
        if stringParm == None:
            return None
        return six.ensure_binary(stringParm)

logConfig = {
        "version": 1,
        "disable_existing_loggers": False,
        "loggers": {
            "": {
                "level": "DEBUG",
                "handlers": ["file"]
                }
            },

        "handlers": {

            "file": {
                "class": "logging.handlers.TimedRotatingFileHandler",
                "formatter": "precise",
                "filename": "c:\\temp\service.log",
                "when": "midnight",
                "backupCount": 30,
                "level": "NOTSET"
                }
            },

        "formatters": {
            "precise": {
                "format": "%(asctime)s %(levelname)-8s %(name)-15s %(message)s",
                "datefmt": "%Y-%m-%d %H:%M:%S"
            }
        }
    }

def main():
    logging.config.dictConfig(logConfig)

    logger.debug("started")
    service = Service()
    service.StartMain()

if __name__ == "__main__":
    main()

I can start my service (eg from Service Manager) with no problems.
I can also stop my service (from Service Manager)  but get an error 1061:

*

*My HandlerProc is not called (at least it is not logged)

*The service process terminates

*I get 1062 I try to stop the service again

NB: Calling self.handlerProc(0) from StartMain2 calls the the ServiceCtrlHandler
Whats wrong?

A: I did my test tests on Windows 10.
After replacing RegisterServiceCtrlHandlerA with RegisterServiceCtrlHandlerExA (and including the additional arguments in the method call (and HANDLER_FUNCTION) everything works as expected.
HANDLER_FUNCTION_EX = ctypes.WINFUNCTYPE(ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_void_p)

advapi32.RegisterServiceCtrlHandlerExA.argtypes = [ctypes.c_char_p, HANDLER_FUNCTION_EX, ctypes.c_void_p]
advapi32.RegisterServiceCtrlHandlerExA.restype = ctypes.c_void_p
RegisterServiceCtrlHandlerExA = advapi32.RegisterServiceCtrlHandlerExA

...
        self.handlerProcEx = HANDLER_FUNCTION_EX(self.HandlerProcEx)
        self.ServiceStatusHandle = RegisterServiceCtrlHandlerExA(self.encode(self.serviceName), self.handlerProcEx, None)

...

    def HandlerProcEx(self, dwControl, dwEventType, lpEventData, lpContext):
...


text:
Q: How to get executable program from tar.xz file I want to use the program KDE Iso Imagewriter, but it seems to only be available as a tar.xz file. How do I derive an executable file from the tar.xz file?

A: This KDE Iso Imagewriter package is distributed in source code form. It is possible to get compilation instructions for Ubuntu by reading ArchLinux PKGBUILD.
Below is the list of commands for building on Ubuntu 20.04 LTS:
sudo apt-get update
sudo apt-get install wget xz-utils cmake extra-cmake-modules build-essential gettext libkf5i18n-dev libkf5coreaddons-dev libkf5widgetsaddons-dev libkf5iconthemes-dev libudev-dev libgpgme-dev libgpgmepp-dev libgpg-error-dev pkg-config appstream

cd ~/Downloads
wget -c https://download.kde.org/unstable/isoimagewriter/0.8/isoimagewriter-0.8.tar.xz
tar -xf isoimagewriter-0.8.tar.xz
cd isoimagewriter-0.8
mkdir build
cd build
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)
sudo make install

and then enjoy KDE Iso Imagewriter.


text:
Q: Pythonic way to implement three similar integer range operators? I am working on a circular problem. In this problem, we have objects that are put on a ring of size MAX, and are assigned IDs from (0 to MAX-1).
I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is i inRange(j,k)). And I have the same for ranges ]j,k[ and ]j,k].
Code in those three methods look duplicated from one method to another:
def inRange(i,j,k):
    """
    Returns True if i in [j, k[
    * 0 <= i, j, k < MAX
    * no order is assumed between j and k: we can have k < j
    """
    if j <= k:
        return j <= i < k
    # j > k :
    return j <= i or i < k

def inStrictRange(i,j,k):
    """
    Returns True if i in ]j, k[
    * 0 <= i, j, k < MAX
    * no order is assumed between j and k: we can have k < j
    """
    if j <= k:
        return j < i < k
    # j > k :
    return j < i or i < k

def inRange2(i,j,k):
    """
    Returns True if i in ]j, k]
    * 0 <= i, j, k < MAX
    * no order is assumed between j and k: we can have k < j
    """
    if j <= k:
        return j < i <= k
    # j > k :
    return j < i or i <= k

Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!
After thinking of a better solution, I came up with:
from operator import lt, le
def _compare(i,j,k, op1, op2):
    if j <= k:
        return op1(j,i) and op2(i,k)
    return op1(j,i) or op2(i,k)

def inRange(i,j,k):
    return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
    return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
    return _compare(i,j,k, lt, le)

Is it any better? Can you come up with something more intuitive?
In short, what would be the Pythonic way to write these three operators?
Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?
Thanks.

A: Two Zen of Python principles leap to mind:

*

*Simple is better than complex.

*There should be one—and preferably only one—obvious way to do it.

range
The Python built-in function range(start, end) generates a list from start to end.1 The first element of that list is start, and the last element is end - 1.
There is no range_strict function or inclusive_range function. This was very awkward to me when I started in Python. ("I just want a list from a to b inclusive! How hard is that, Guido?") However, the convention used in calling the range function was simple and easy to remember, and the lack of multiple functions made it easy to remember exactly how to generate a range every time.
Recommendation
As you've probably guessed, my recommendation is to only create a function to test whether i is in the range [j, k). In fact, my recommendation is to keep only your existing inRange function.
(Since your question specifically mentions Pythonicity, I would recommend you name the function as in_range to better fit with the Python Style Guide.)
Justification
Why is this a good idea?

*

*The single function is easy to understand. It is very easy to learn how to use it.
Of course, the same could be said for each of your three starting functions. So far so good.

*There is only one function to learn. There are not three functions with necessarily similar names.
Given the similar names and behaviours of your three functions, it is somewhat possible that you will, at some point, use the wrong function. This is compounded by the fact that the functions return the same value except for edge cases, which could lead to a hard-to-find off-by-one bug. By only making one function available, you know you will not make such a mistake.

*The function is easy to edit.
It is unlikely that you'll need to ever debug or edit such an easy piece of code. However, should you need to do so, you need only edit this one function. With your original three functions, you have to make the same edit in three places. With your revised code in your self-answer, the code is made slightly less intuitive by the operator obfuscation.

*The "size" of the range is obvious.
For a given ring where you would use inRange(i, j, k), it is obvious how many elements would be covered by the range [j, k). Here it is in code.
if j <= k:
    size = k - j
if j > k:
    size = k - j + MAX

So therefore
size = (k - j) % MAX

Caveats
I'm approaching this problem from a completely generic point of view, such as that of a person writing a function for a publicly-released library. Since I don't know your problem domain, I can't say whether this is a practical solution.
Using this solution may mean a fair bit of refactoring of the code that calls these functions. Look through this code to see if editing it is prohibitively difficult or tedious.

1: Actually, it is range([start], end, [step]). I trust you get what I mean though.

A: The Pythonic way to do it is to choose readability, and therefor keep the 3 methods as they were at the beginning.
It's not like they are HUGE methods, or there are thousand of them, or you would have to dynamically generate them.

A: No higher-order functions, but it's less code, even with the extraneous else.
def exclusive(i, j, k):
    if j <= k:
        return j < i < k
    else:
        return j < i or i < k

def inclusive_left(i, j, k):
    return i==j or exclusive(i, j, k)

def inclusive_right(i, j, k):
    return i==k or exclusive(i, j, k)

I actually tried switching the identifiers to n, a, b, but the code began to look less cohesive.  (My point: perfecting this code may not be a productive use of time.)

A: Now I am thinking of something such as:
def comparator(lop, rop):
    def comp(i, j, k):
        if j <= k:
            return lop(j, i) and rop(i,k)
        return lop(j, i) or rop(i,k)

    return comp

from operator import le, lt

inRange = comparator(le, lt)
inStrictRange = comparator(lt, lt)
inRange2 = comparator(lt, le)

Which looks better indeed.

A: I certainly agree that you need only one function, and that the function should use a (Pythonic) half-open range.
Two suggestions:

*

*Use meaningful names for the args:
in_range(x, lo, hi) is a big
improvement relative to the
2-keystroke cost.

*Document the fact that the
constraint hi < MAX means that it is
not possible to express a range that
includes all MAX elements. As
Wesley remarked, size = (k - j) %
MAX i.e. size = (hi - lo) % MAX
and thus 0 <= size < MAX.

A: To make it more familiar to your users, I would have one main in_range function with the same bounds as range(). This makes it much easier to remember, and has other nice properties as Wesley mentioned.
def in_range(i, j, k):
    return (j <= i < k) if j <= k else (j <= i or i < k)

You can certainly use this one alone for all your use cases by adding 1 to j and/or k. If you find that you're using a specific form frequently, then you can define it in terms of the main one:
def exclusive(i, j, k):
    """Excludes both endpoints."""
    return in_range(i, j + 1, k)

def inclusive(i, j, k):
    """Includes both endpoints."""
    return in_range(i, j, k + 1)

def weird(i, j, k):
    """Excludes the left endpoint but includes the right endpoint."""
    return in_range(i, j + 1, k + 1)

This is shorter than mucking around with operators, and is also much less confusing to understand. Also, note that you should use underscores instead of camelCase for function names in Python.

A: I'd go one step further than Wesley in aping the normal python 'in range' idiom; i'd write a cyclic_range class:
import itertools

MAX = 10 # or whatever

class cyclic_range(object):
    def __init__(self, start, stop):
        # mod so you can be a bit sloppy with indices, plus -1 means the last element, as with list indices
        self.start = start % MAX
        self.stop = stop % MAX
    def __len__(self):
        return (self.stop - self.start) % MAX
    def __getitem__(self, i):
        return (self.start + i) % MAX
    def __contains__(self, x):
        if (self.start < self.stop):
            return (x >= self.start) and (x < self.stop)
        else:
            return (x >= self.start) or (x < self.stop)
    def __iter__(self):
        for i in xrange(len(self)):
            yield self[i]
    def __eq__(self, other):
        if (len(self) != len(other)): return False
        for a, b in itertools.izip(self, other):
            if (a != b): return False
        return True
    def __hash__(self):
        return (self.start << 1) + self.stop
    def __str__(self):
        return str(list(self))
    def __repr__(self):
        return "cyclic_range(" + str(self.start) + ", " + str(self.stop) + ")"
    # and whatever other list-like methods you fancy

You can then write code like:
if (myIndex in cyclic_range(firstNode, stopNode)):
    blah

To do the equivalent of inRange. To do inStrictRange, write:
if (myIndex in cyclic_range(firstNode + 1, stopNode)):

And to do inRange2:
if (myIndex in cyclic_range(firstNode + 1, stopNode + 1)):

If you don't like doing the additions by hand, how about adding these methods:
    def strict(self):
        return cyclic_range(self.start + 1, self.stop)
    def right_closed(self):
        return cyclic_range(self.start + 1, self.stop + 1)

And then doing:
if (myIndex in cyclic_range(firstNode, stopNode).strict()): # inStrictRange
if (myIndex in cyclic_range(firstNode, stopNode).closed_right()): # inRange2

Whilst this approach is, IMHO, more readable, it does involve doing an allocation, rather than just a function call, which is more expensive - although still O(1). But then if you really cared about performance, you wouldn't be using python!


text:
Q: How to use two different color ramps? I have two datasets which I plot one above the other. I want to use different manual color ramps for them. However, scale_color_manual changes color for both data sets at the same time.
set.seed(123)
data1 <- data.frame(x=rnorm(25,2,.5),y=rnorm(25,2,1),z=factor(sample(c(1:3),25,replace=TRUE)))
data2 <- data.frame(x=rnorm(25,4,1),y=rnorm(25,2,.5),z=factor(sample(c(1:3),25,replace=TRUE)))

col1 <- c("lightblue","blue","darkblue") #corresponding to levels of 1...3 in data1
col2 <- c("lightgreen","green","darkgreen") #corresponding to levels of 1...3 in data2

ggplot(mapping=aes(x=x,y=y,color=z,size=5)) +
  geom_point(data=data1) +
  scale_color_manual(values=col1)+
  geom_point(data=data2) +
  scale_color_manual(values=col2)

Actual results area all in green. However, points more to the left should be in blue.

A: ggplot doesn't have an inbuilt option for this but you can prepare your data to achieve it:
data1$color1 <- col1[data1$z]
data2$color2 <- col2[data2$z]

ggplot()  +
  geom_point(data=data1, aes(x=x,y=y,color=color1), size=5) +
  geom_point(data=data2, aes(x=x,y=y,color=color2), size=5) +
  scale_color_identity()


text:
Q: comparing two equations and obtaining some results Assuming the following equation
$$
\sum_{m=0}^M b_m r^m \left[\sum_{i,j}i j\lambda_i \lambda_j r^{i+j-2}-\sum_j j(j+1) \lambda_j r^{j-2}+2E\right]-2\sum_{k=0}^K a_k r^k=0 \tag{1}
$$
the authors in a paper says that

Equating the coefficients of $r^p, p=0, 1, 2, . . .$ in (1) to zero,
  we get a set of relations connecting $\lambda_n$s. For example, in a
  case where M=1 and K=3, these are:

$$
\lambda_1=Z; \\
\lambda_2=(2E+\lambda^2_1)/6; \\
\lambda_3=(2\lambda_1 \lambda_2-\alpha)/6;\\
\lambda_4=(4\lambda_2^2+6\lambda_1 \lambda_3-2\beta)/20;\\
\lambda_n=\frac 1 {n(n+1)}\sum_{i=1}^{n-1}i (n-i)\lambda_i \lambda_{n-1}, n>4;\\
\tag{2}
$$
In fact they have obtained an expression for this special potential in the previous section as follows (before they write $\Psi$ as a sum, see this question)
$$
n(n-1)\mu_{n-1}+2Z\mu_n+2E\mu_{n+1}-2\alpha\mu_{n+2}-2\beta\mu_{n+3}=0 \tag{3}
$$
where
$$
\mu_j=\int_0^\infty r^j \Psi(r)dr \tag{4}
$$
this is while after writing $\Psi$ as a sum they define
$$
\int_0^\infty r^p exp[-S(r)]dr=\mu_p,  \,\,  p=0,1,2,...,N \tag{5}
$$

I can't understand how they have reached equation (2) by comparison equations (1) and (3)? or  if they have reached it in another way! Any idea?

You can find more details in the original paper. Of course I have cropped the relevant parts. In this question I want to know how authors have reached from equation (11) to (12) in the paper.

A: We start with the  representation given in the answer of the referred post which corresponds to (1).
\begin{align*}
\sum_{m=0}^M b_m r^m\left[\color{blue}{\sum_{n=2}^{2N}}\sum_{{i+j=n}\atop{i,j\geq   1}}ij\lambda_i   \lambda_jr^{i+j-2}-\sum_{j=1}^Nj(j+1)\lambda_jr^{j-2}+2E\right]
-2\sum_{k=0}^K a_k r^k=0\tag{1a}
\end{align*}
Note: The blue marked sum is not given in formula (11) of the original paper, which seems to be a typo.
The relations (2) stated by OP are derived in the referred paper by specialisation of (1a) to the so-called spherical Stark–Zeeman hydrogenic problem . We consider in the referred paper formula (6):
\begin{align*}
V(r)=\frac{\sum_{k=0}^Ka_kr^k}{\sum_{m=0}^Mb_mr^m}=\frac{-Z+\alpha r^2+\beta r^3}{r}\tag{2a}
\end{align*}
Combining (1a) and (2a) we obtain
\begin{align*}
&r\left[\sum_{n=2}^{2N}\sum_{{i+j=n}\atop{i,j\geq   1}}ij\lambda_i   \lambda_jr^{i+j-2}-\sum_{j=1}^Nj(j+1)\lambda_jr^{j-2}+2E\right]
-2\left(-Z+\alpha r^2+\beta r^3\right)=0\tag{3a}
\end{align*}

We obtain from (3a)
\begin{align*}
&\color{blue}{2\left(-Z-Er+\alpha r^2+\beta r^3\right)}\tag{4a}\\
&\qquad=\sum_{n=2}^{2N}\sum_{{i+j=n}\atop{i,j\geq   1}}ij\lambda_i   \lambda_jr^{n-1}-\sum_{j=1}^Nj(j+1)\lambda_jr^{j-1}\\
&\qquad=\sum_{n=2}^{2N}\sum_{j=1}^{n-1}j(n-j)\lambda_j\lambda_{n-j}r^{n-1}-\sum_{j=1}^Nj(j+1)\lambda_jr^{j-1}\tag{5a}\\
&\qquad\,\,\color{blue}{=\sum_{n=1}^{2N-1}\sum_{j=1}^{n}j(n+1-j)\lambda_j\lambda_{n+1-j}r^{n}-\sum_{j=0}^{N-1}(j+1)(j+2)\lambda_{j+1}r^{j}}\tag{6a}\\
\end{align*}

Comment:

*

*In (5a) we eliminate $i$ using $i=n-j$.

*In (6a) we shift the indices $n$ and $j$ to ease coefficient comparison of $r^p, p\geq 0$.

Coefficient  comparison of (4a) and (6a) gives:
\begin{align*}
-2Z&=-1\cdot2\lambda_1\tag{$[r^0]$}\\
\color{blue}{Z}&\color{blue}{=\lambda_1}\\
\\
-2E&=\sum_{j=1}^1j(2-j)\lambda_j\lambda_{2-j}-2\cdot3\lambda_2\tag{$[r^1]$}\\
-2E&=\lambda_1^2-6\lambda_2\\
\color{blue}{\lambda_2}&\color{blue}{=\frac{1}{6}\left(2E+\lambda_1^2\right)}\\
\\
2\alpha&=\sum_{j=1}^2j(3-j)\lambda_j\lambda_{3-j}-3\cdot 4\lambda_3\tag{$[r^2]$}\\
2\alpha&=2\lambda_1\lambda_2+2\lambda_2\lambda_1-12\lambda_3\\
2\alpha&=4\lambda_1\lambda_2-12\lambda_3\\
\color{blue}{\lambda_3}&\color{blue}{=\frac{1}{6}\left(2\lambda_1\lambda_2-\alpha\right)}
\end{align*}
The  other relations  follow  similarly.


text:
Q: Text-to-Speech in on View Pager
*

*I have view pager, and few text in every page, i have a button ,on button press text-to-speech event is fire

*I know how to use text-to-speech, but when it comes to viewPager i dont know

*Code :
public class MainActivity extends Activity implements
        TextToSpeech.OnInitListener {
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tts = new TextToSpeech(this, this);

    btnSpeak = (Button) findViewById(R.id.btnSpeak);

    txtText = (EditText) findViewById(R.id.txtText);

    // button on click event
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            speakOut();
        }

    });
}

@Override
public void onDestroy() {
    // Don't forget to shutdown!
    if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

@Override
public void onInit(int status) {
    // TODO Auto-generated method stub

    if (status == TextToSpeech.SUCCESS) {

        int result = tts.setLanguage(Locale.US);

        // tts.setPitch(5); // set pitch level

        // tts.setSpeechRate(2); // set speech speed rate

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "Language is not supported");
        } else {
            btnSpeak.setEnabled(true);
            speakOut();
        }

    } else {
        Log.e("TTS", "Initilization Failed");
    }

}

private void speakOut() {

    String text = txtText.getText().toString();

    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

}
-- How to implement this in viewpager,and speak(convert) text that are particular in page

A: The easiest way would be to make the tts object static in MainActivity
Then from your fragments you can call MainActivity.tts.stop() etc.
It would probably be better to include some helper methods in MainActivity such as:
public static TextToSpeech getTTS(){
return tts;
}

and to avoid null pointers:
public static boolean isTTSAvailable(){
return tts != null // && ttsInitialised
}

Where you would set a static boolean to true if onInit returned SUCCESS.
MainActivity would continue to handle releasing the tts object in onDestroy etc.
As a side note, it's always good practice to check out the memory profiler in Android Studio to make sure that holding a static reference to any object such as this has no adverse effects. Do before and after analysis and run the garbage collector manually etc to check you are holding no unwanted references after your Activity has been destroyed. This is very generic advice, but whenever making a code change such as this, it's good to know that there are no side-effects.


text:
Q: Mysql query generation This is my user table schema
CREATE TABLE IF NOT EXISTS `ehobe_user` (
  `user_id` bigint(20) NOT NULL,
  `user_email` varchar(80) NOT NULL,
  `user_password` varchar(50) NOT NULL,
  `user_fname` varchar(255) NOT NULL,
  `user_lname` varchar(255) NOT NULL,
  `user_terms` enum('yes','no') NOT NULL DEFAULT 'yes',
  `is_active` enum('yes','no') NOT NULL DEFAULT 'yes',
  `created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

And this is my friends table schema
CREATE TABLE IF NOT EXISTS `ehobe_friends` (
  `user_id1` bigint(20) NOT NULL,
  `user_id2` bigint(20) NOT NULL,
  `relationship_id` int(1) NOT NULL COMMENT '1 - user1 request, 2- user2 request, 3 - friends, 4- user1 blocked, 5 - user2 blocked'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

So i need to select the user first name and last name who are my frinds in the friends table.

A: Suppose you want friends of USER_ID #67.
Try:
select u.user_id, u.user_fname, u.user_lname
  from ehobe_user u
 inner join ehobe_friends f1 on (u.user_id = f1.user_id1)
 where f1.user_id2 = 67
 union
select u.user_id, u.user_fname, u.user_lname
  from ehobe_user u
 inner join ehobe_friends f2 on (u.user_id = f2.user_id2)
 where f2.user_id1 = 67

A: Logically, you want to get all of the friends in an array and check each user for matching info. I would give you code, but I don't know what language you're writing this in.


text:
Q: Probability in Math Education Why is probability an under-emphasized subject in most math programs? Why does it seem that the hot topics these days are category theory and algebra? What do you think about the following: A student learns probability (both on the applied side and the pure side) and picks up the real analysis on the way. That way there is a purpose for learning the real analysis.
Can we do this with many mathematical subjects (e.g. first teach from an applied perspective, and learn the pure stuff because it is needed)?


text:
Q: Does MongoDB insert data with its metadata? When a DB is created in MongoDB with some sample data, will it store the Meta data in RAM?
Whenever I try to create a Database my memory, the memory usage is increased.
How does MongoDB use its RAM for storing data in the DB?


text:
Q: converting special characters after reading a site's meta tags I'm pulling the Facebook meta tags from an external site with this code, which works:
$site = file_get_contents($link);
$html = new DOMDocument();
@$html->loadHTML($site);
$meta_title = null;
foreach($html->getElementsByTagName('meta') as $meta) {
    if($meta->getAttribute('property')=='og:title'){
        $meta_title = $meta->getAttribute('content');
    }
 }
echo 'og:title: '.$meta_title;

My problem is that if the og:title contains something with an apostrophe, for example, it outputs a bunch of funky characters. For example:

That's the Spot

Instead of:

That's the Spot

How do I make it output correctly?

A: Check the third part website collation, it was on utf-8 or latin.
Then you should convert to your website collation. What are you using? utf8 or latin?
If you are using utf8 and third part latin, you should use
utf8_encode($actualVar)

If you are using latin and the third part utf8, you should use
utf8_decode($actualVar)

I suppose there are 2 different collations ruling it. If Are The Two UTF8 Convert your php header to utf8 too:
header('Content-Type: text/html; charset=utf-8');

If you are trying to use Latin (iso-8859-1) Use
header('Content-Type: text/html; charset=iso-8859-1');

By the wall should work any way.

A: The solution was including the UTF-8 encoding meta tag at the top of the PHP file.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


text:
Q: ActionName HttpPut not found I have a weird problem. I have 2 Actions in controller:
[ActionName("Tag")]
    [HttpPut]
    public ActionResult TagPut(Entities.Tag tag)
    {
        if (tag.Name.Length < 2)
        {
            throw new Exception("Minimalna dlugosc tagu 2 znaki");
        }

        database.TagRepository.Update(tag);

        return Json(tag, JsonRequestBehavior.AllowGet);
    }

and
[ActionName("Tag")]
    [HttpPost]
    public ActionResult TagPost(Entities.Tag tag)
    {
        if (tag.Name.Length < 2)
        {
            throw new Exception("Minimalna dlugosc tagu 2 znaki");
        }

        database.TagRepository.Insert(tag);

        return Json(tag, JsonRequestBehavior.AllowGet);
    }

I call in JS action http://localhost:51991/AdminTag/Tag with optional tag id (http://localhost:51991/AdminTag/Tag/1) when I edit existing item. Action TagPost works well and I can Insert new Tag into Database, but action TagPut return error 404. Why application can't found Action with the same name as Action which work well?


text:
Q: Firebase: escaping characters in redirect I have a project running for over a year in Firebase.
It has a firebase.json with the following redirect:
"redirects": [ {
      "source" : "/single-reports/:id*",
      "destination" : "/dashboard/#!/single-reports/:id",
      "type" : 302
    }],

However, suddenly some clients started to complain of an error. I went to check and the url is being redirected to
/dashboard/%23%21/single-reports/-LMnXAtEzTQQzffY0Bfy

I didn't touch anything. What might have happened? How to fix?


text:
Q: Graphic file .eps not found though in proper directory: I am using graphicx to typeset the figures for my PhD thesis. I have large files in .eps format. However, whenever I try to typeset the file (using pdfTeX), the console says

"LaTeX error: File 'Figure' not found"

It is in the same directory as my .tex file, and the file will typeset if I create it as a .dvi and then convert it to .pdf. I would rather not do this though, because I want to use hyperref.


text:
Q: PHP nested menu security question From a novice:
In looking to display a modified nested menu of How to create a nested menu from MySQL with PHP?. My question is: are there any security concerns in taking this kind of approach.
From my novice point of view this code is server-sided with the exception of triggering the query upon the page being loaded.
All insights and suggestions are welcome. Thank you.
<?php
include '../data.php'; // connection folder

$query = "SELECT `parent_name`, `parent_id`, `child_name`, child_id
            FROM  `pages.child` INNER JOIN `pages.parent`
            ORDER BY `parent_name`";

$result = mysql_query($query) or die(mysql_error());
echo "
";
$last_parent = '';
while($row = mysql_fetch_array($result)){
    if($last_parent != $row['parent_name']){
            // Unless this is the first item, close the last category
            if($last_parent != ''){
                    echo "

";
            }
            // Parent menu begins
 and

            $last_parent = $row['parent_name'];
            $tags = $row['parent_name'];
            echo "
{$tags}
";
    }
    if($row['parent_id'] === $row['child_id'] ){
        $tags = $row['parent_name'];
        $tag = $row['child_name'];
        echo "
$tag";
        }
}
if($last_parent != ''){
    echo "

";
}
echo "
";

?>

A: If the values in the database table were previously inputted by users, make sure you escape them using htmlentities() before outputting them. For example, replace the line:
$tags = $row['parent_name'];

With this:
$tags = htmlentities($row['parent_name']);

Using htmlentities() prevents a vulnerability known as cross-site scripting, which is the only security issue I can see in this situation.


text:
Q: How to match n items from a list in regex? I am trying to match n elements from a list of items:
one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety,hundred,thousands,million,billion

I want to check how many of items from the above list is present in a string. How can achieve that?
For example, I want to check that whether a string contains any 6 from the list:
(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousands|million|billion){6}

A: You just need to add wildcards that will consume the tokens you don't want to match :
(\b(?:one|two|three|four|[...]|thousands|million|billion)\b.*){6}

That way you will match 6 occurrences of the searched tokens, and anything that stands between.
I've also added word-boundaries (\b) in order to avoid matching parts of words ("one" in "honest").
Note that you can't make sure that there isn't more than 6 searched tokens, because even with anchors the extra tokens would be consumed by the .*. However, this will not match if there is less than 6 searched tokens.
Regex101 courtesy of Rad Lexus.


text:
Q: Predict function error in R I am trying to use linear regression using R. The following is my code, everything works fine except last line which gives following error:
    Error in .Primitive("%*%")(x, y) :
    requires numeric/complex matrix/vector arguments
data<-read.table("tmp.txt",header=TRUE)
X<-data$P
Y<-data$Q
plot(data, pch=16)
model <- lm(Y ~ X , data)
# make a prediction for each X
predY <- predict(model,data)


text:
Q: Pass functor to constructor I have a class that basically needs to store a functor given in the constructor, similar to this:
template <class T>
class Foo {
   private:
     T func;
   public:
     Foo(T f) : func(f) { }
}

However, to create a new instance of the Foo class, the I can't seem to do this:
Foo foo(std::less<int>());

because T is a class template parameter. I have to use this clunky syntax instead:
Foo<std::less<int>> foo(std::less<int>());

Is there a better way to do this, without writing the type of the functor twice?

A: Foo is not a class, it is a class template. You have to instantiate it with a template argument in order to create a type.
Concerning your example, you could add a default constructor for functors that are default constructible, like std::less et al.
template <class T>
class Foo {
   private:
     T func;
   public:
     Foo() = default; // C++03 would require Foo() {}
     Foo(T f) : func(f) { }
};

then
Foo<std::less<int>> foo;

Alternatively, you can provide a function template that takes a functor and returns a Foo<F> object.

A: You could use a function to deduce the functor type and return the correct Foo flavor:
template <typename T>
Foo<T> make_foo(T t) { return Foo<T>(t); }

but this solution basically needs auto from C++11 to store the return value:
auto f = make_foo(std::less<int>());


text:
Q: how to retrieve image from s3 with nodejs Please let me know how to retrieve image from s3 with nodejs? Honestly, I could upload an image to s3 with nodejs as follows but the problem is how can I complete to retrieve image from s3?
router.get('/image/:imageId', function (req, res, next) {
    // ????
});

var s3 = new aws.S3({ accessKeyId: config.awsAccessId, secretAccessKey: config.awsAccessKey});
var upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: config.bucket,
        key: function (req, file, cb) {
            cb(null, file.originalname);
        }
    })
});

router.post('/upload/:id', upload.array('file', 3), function(req, res, next) {
    res.send('Successfully uploaded ' + req.files.length + ' files!');
});

A: If you use lambda with API gateway to retrieve images then there will be no need to using security keys with appropriate permissions.
Read an image from the bucket and send it as base64 to directly use it in source of image tag in HTML.
const AWS = require('aws-sdk');
//*/ get reference to S3 client
var s3 = new AWS.S3();
exports.handler = (event, context, callback) => {
    var params = {
  "Bucket": "bucket-name",
  "Key": "object-name"
    };
    s3.getObject(params, function(err, data){
       if(err) {
           callback(err, null);
       } else {
           let image = new Buffer(data.Body).toString('base64');
           image = "data:"+data.ContentType+";base64,"+image;
           let response = {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": "*",
            'Content-Type': data.ContentType
        },
        "body":image,
        "isBase64Encoded": true
    };
           callback(null, response);
    }
    });

};

A: I've finally found that,
var params = { Bucket: config.bucket, Key: req.params.imageId };
s3.getObject(params, function(err, data) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'});
    res.write(data.Body, 'binary');
    res.end(null, 'binary');
});

A: You're looking for the getObject() method.

A: Assuming that you are using aws-sdk then you can use getObject method.
Here is sample code
exports.getObjects = function (req, res) {
    var item = req.body;
    var params = { Bucket: req.params.bucketName, Key: 'keyname'}; // keyname can be a filename
    s3.getObject(params, function (err, data) {
        if (err) {
            return res.send({ "error": err });
        }
        res.send({ data });
    });
}

This link may be helpful to you.

A: A better and faster approach is piping the stream to response, works on Minio S3 Client but I believe it also works on aws amazon js client.
const Minio = require('minio');

const s3Client = new Minio.Client({
    endPoint: 'ep',
    accessKey: 'ak',
    secretKey: 'sk'
});

router.get('/image/:imageId', (req, res) => {

    const { imageId } = req.params;

    s3Client.getObject('bucket', imageId, (err, stream) => {
        if (err) return res.status(500).send(err);

        const contentType = stream.headers['content-type'];

        contentType && res.setHeader('Content-Type', contentType);

        stream.pipe(res);
    });
});

A: This is what I use with aws-sdk
const params = { Bucket: "YOUR_BUCKET_NAME", Key: "YOUR_FILENAME"};
s3.getObject(params).createReadStream().pipe(res);


text:
Q: Override shouldcomponentupdate with HOC May I know is it possible to change the behaviour (override) the child component of shouldcomponentupdate with HOC instead of extend? Any example on this?

A: Yes. It's possible up to a certain extent.
We can implement the shouldComponentUpdate of the HoC, and it will have the same effect of overriding the shouldComponentUpdate of Child component as usually in React Child component only rerender if the parent rerender.
function HoC(WrappedComponent) {
  return class extends React.Component {

    shouldComponentUpdate() {
      // change the behaviour here
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}

However, this will not work if the Child component has any internal state changes with setState or it is forced to rerender from a different source other than the updates from the parent. As an example, if the Child component is connected to a Redux store with connect, it will rerender when it gets updates from the store regardless of overridden shouldComponentUpdate behavior in the HoC.


text:
Q: ASP.NET - datatable to excel - change date format I am generating xls file from ASP DataTable:
var excelGrid = new DataGrid { DataSource = dataTable };
excelGrid.DataBind();
Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.ContentEncoding = Encoding.GetEncoding("iso-8859-1");
Response.Charset = Encoding.UTF8.EncodingName;

var fileName = "export_" + DateTime.Now.ToShortDateString() + ".xls";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.ContentEncoding = Encoding.Unicode;
Response.BinaryWrite(Encoding.Unicode.GetPreamble());

var swriter = new StringWriter();
var hwriter = new HtmlTextWriter(swriter);

excelGrid.RenderControl(hwriter);

Response.Write(swriter.ToString());
Response.End();

I write date using this formatting
row[dataTable.Columns[i++]] = date.ToString("yyyy-MM-dd");

The problem is that Excel displays it as dd.mm.yyyy.
Can I force Excel to display this date in my format? How can I do this?

A: When adding the DataTable columns, set the colum type as string, like
dataTable.Columns.Add("Date1", typeof(string));

Then when adding the rows set a DateTime.ToString("yyyy-MM-dd") to the column slot.
dataTable.Rows.Add(date.ToString("yyyy-MM-dd"));

This makes your Excel file to understand it later as a string and to not try and format it by itself as a date.

A: Probably your system settings are overruling the formatting when opening in Excel. As it is nothing more than html content you're sending out there to the client. If you keep using that piece of code, try adding an apostrophe to the line where you write the date:
row[dataTable.Columns[i++]] = "'" + date.ToString("yyyy-MM-dd");

This way, excel won't see this as a Date field and thus not following the system setting's short date notation. If this is fine by you... it will load/show as a text field.
If you still want go along with your coding, but dislike the apostrophe when viewing the resulting file in excel, then read up this first and then that for extended info on mso-number-format.


text:
Q: Merging split files on remote machine Goal: Use Python to map to a remote directory and merge eleven split files into one output named kb4577066.zip
Intended Result: Merging of all eleven split files into kb4577066.zip
Actual Result: ReturnValue = 0 is returned with no kb4577066.zip created.
List of Archive Files:

*

*kb4577066.zip.001

*kb4577066.zip.002

*kb4577066.zip.003

*kb4577066.zip.004

*kb4577066.zip.005

*kb4577066.zip.006

*kb4577066.zip.007

*kb4577066.zip.008

*kb4577066.zip.009

*kb4577066.zip.010

*kb4577066.zip.011

Python Source:
kb4577066_folder = r'C:\\Temp\\WindowsPatchesTemp\\KB4577066\\'
os.system(r"wmic /node:10.96.192.86 /user:username /password:password process call create 'cmd.exe /c copy /B kb4577066_folder\kb4577066.zip.* KB4577066.zip'")

I can run the following command on the remote machine to achieve the desired result.
copy /B kb4577066_folder\kb4577066.zip.* KB4577066.zip

I'm new to Python and believe that my issue may lie with the wildcard (*) that I attempting to use. I'm not sure if regular expressions or glob would be the proper solution or if anyone can recommend a better solution.


text:
Q: Laravel 5 get user info from facebook I'm trying to get an user id from Facebook with the Facebook PHP-sdk with Laravel 5. I did a lot of search on the errors I got, but none of the answers helped.
Set keys:
use Facebook\FacebookSession;
FacebookSession::setDefaultApplication('XXX' , 'XXX');

Redirect to Facebook:
public function getFacebook()
{
    $helper = new FacebookHandler(url('settings/set_facebook'));
    return Redirect::to($helper->getLoginUrl());
}

Get the info:
public function setFacebook()
{
    try{
        $session = new FacebookSession(\Session::get('state'));
        $request = new FacebookRequest($session, 'GET', '/me');
        $response = $request->execute();
        $graphObject = $response->getGraphObject()->asArray();
        dd($graphObject);
    } catch(Exception $e){
        dd(
            $e->getMessage(),
            $e->getCode(),
            $e
        );
    }
}

Code for Laravel sessions:
use Facebook\FacebookRedirectLoginHelper;
use Illuminate\Support\Facades\Session;

class FacebookHandler extends FacebookRedirectLoginHelper
{
    protected function storeState($state)
    {
        Session::put('state', $state);
    }

    protected function loadState()
    {
        return $this->state = Session::get('state');
    }
}

Output:
"Invalid OAuth access token."

190

FacebookAuthorizationException {#215 ▶}

What am I doing wrong?

A: use Laravel Socialite. It supports facebook, twitter, google+ and github.
and also easy to use.

A: I fixed the problem by removing setFacebook() and update getFacebook() to this:
$helper = new FacebookHandler(url('settings/get_facebook'));

try {
    $session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $e ) {
    dd($e);
} catch( Exception $e ) {
    dd($e);
}

if (isset($session))
{
    $user_profile = (new FacebookRequest(
        $session, 'GET', '/me'
    ))->execute()->getGraphObject(GraphUser::className());

    dd($user_profile);
} else {
    return Redirect::to($helper->getLoginUrl());
}

Of course you need to customize the error handling.


text:
Q: Multi Day Values I am having some troubles with my query. I am trying to get the total import rate for the current day, while also matching up the previous day with the correlating hour.
Example: 1AM (Current Day) = 20
1AM(Yesterday) = 25.
As of right now the columns Current and Yesterday are showing identical values.
SELECT
z.[import Hour],
COUNT(z.orderno) as CurrentDate,
COUNT(od.orderno) as Yesterday

FROM (

(select datepart(hh, recvtime) as [import Hour],
orderno

from mck_hvs.orderheader with (nolock)

where convert(date, recvtime) = convert(date, getdate())
and orderno not like '%ST'

UNION

select datepart(hh, recvtime) as [import Hour],
orderno from mck_hvs.oldorderheader with (nolock)
where convert(date, recvtime) = convert(date, getdate())
and orderno not like '%ST' ) as z

Join

 (
select datepart(hh, od.recvtime) as [import Hour],
od.orderno from mck_hvs.oldorderheader od with (nolock)
where convert(date, od.recvtime) = convert(date, getdate()-1)
and od.orderno not like '%ST' ) as OD
ON z.[import Hour] = od.[import Hour] )

group by z.[import Hour]

A: I've included a bit of code up front just to generate some test data. You probably won't need it, but others might.
USE sandbox
GO
--------------------------------------------------------------------------------------------
--Recreate the OP's environment in my sandpit
DROP TABLE IF EXISTS mck_hvs.orderheader   --2016 syntax
create table mck_hvs.orderheader(
        recvtime datetime NOT NULL
        ,orderno varchar(20) NOT NULL
)
;
ALTER TABLE mck_hvs.orderheader
ADD CONSTRAINT PK_mck_hvs_orderheader_orderno PRIMARY KEY CLUSTERED (orderno)
;
GO
--------------------------------------------------------------------------------------------
DROP TABLE IF EXISTS mck_hvs.oldorderheader
;
create table mck_hvs.oldorderheader(
        recvtime datetime NOT NULL
        ,orderno varchar(20) NOT NULL
)
;
ALTER TABLE mck_hvs.oldorderheader
ADD CONSTRAINT PK_mck_hvs_oldorderheader_orderno PRIMARY KEY CLUSTERED (orderno)
;
GO
--------------------------------------------------------------------------------------------
--Generate some test data (about two years worth working back from today)
--First the old data (not today's)
INSERT mck_hvs.oldorderheader
SELECT  top 100000 dateadd(mi,abs(checksum(newid())) %1440,dateadd(dd,-abs(checksum(newid())) %720,getdate()-1))  as recvtime
        ,right('0000000' + cast(row_number() OVER(ORDER BY (SELECT NULL)) as varchar(20)),7)
         + char(82 + abs(checksum(newid()))%4) + char(82 + abs(checksum(newid()))%4) as orderno--add two random chars from R,S,T,U to the end
FROM sys.columns col1
cross join sys.columns col2
;
--Now today's (assume 500 orders came in)
INSERT mck_hvs.orderheader
SELECT  top 500 dateadd(mi,abs(checksum(newid())) %1440,dateadd(dd,datediff(dd,0,getdate()),0)) --add a random number of minutes to midnight last night
        ,right('0000000' + cast(row_number() OVER(ORDER BY (SELECT NULL)) +100000 as varchar(20)),7)
         + char(82 + abs(checksum(newid()))%4) + char(82 + abs(checksum(newid()))%4) --add two random chars from R,S,T,U to the end
FROM sys.columns col1
cross join sys.columns col2
;
--------------------------------------------------------------------------------------------
WITH yesterday /*all my problems seemed so far away*/as
(
SELECT  datepart(hour,old.recvtime)     as received_hour
        ,count(*)                       as orders_received
FROM    mck_hvs.oldorderheader  as old
WHERE   old.recvtime < dateadd(dd,datediff(dd,0,getdate()),0)  --Yesterday
        AND old.recvtime >= dateadd(dd,datediff(dd,0,getdate())-1,0)
        AND old.orderno not like '%ST'   --Note: This is not a SARGable search.
GROUP BY datepart(hour,recvtime)
)
, today as
(
SELECT datepart(hour,ordr.recvtime)     as received_hour
        ,count(*)                       as orders_received
FROM mck_hvs.orderheader as ordr
WHERE ordr.orderno not like '%ST'   --Google "SARG". Trust me.
GROUP BY datepart(hour,ordr.recvtime)
)
SELECT  isnull(yesterday.received_hour,today.received_hour) as received_hour
        ,isnull(yesterday.orders_received,0)                as orders_received_yesterday
        ,isnull(today.orders_received,0)                    as orders_received_today
FROM yesterday
--FULL JOIN in case there are hours of activity in one table that don't exist in the other table.
FULL JOIN today ON yesterday.received_hour = today.received_hour
;

A: If you use following data:
DECLARE @Orders AS TABLE(OrderNo INT,OrderTaken datetime)

INSERT INTO @Orders VALUES(123,'2017-07-24 12:20:24')
INSERT INTO @Orders VALUES(124,'2017-07-24 12:30:24')
INSERT INTO @Orders VALUES(125,'2017-07-24 13:40:24')
INSERT INTO @Orders VALUES(126,'2017-07-24 13:50:24')

INSERT INTO @Orders VALUES(227,'2017-07-25 12:20:24')
INSERT INTO @Orders VALUES(228,'2017-07-25 12:30:24')
INSERT INTO @Orders VALUES(229,'2017-07-25 13:40:24')
INSERT INTO @Orders VALUES(220,'2017-07-25 13:50:24')

with output:

The following SQL:
DECLARE @Date DATETIME='2017-07-25'
;WITH today AS(
SELECT Cast(OrderTaken As Date) oDate,
CASE WHEN DATEPART(hh,OrderTaken) > 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)-12) + ' PM' WHEN DATEPART(hh,OrderTaken) = 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)) + ' PM' WHEN DATEPART(hh,OrderTaken) < 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)) + ' AM' END As oHour,
Count(OrderNo) OrderCountToday FROM @Orders
WHERE CAST(OrderTaken AS DATE)=CAST(@Date AS DATE)
GROUP BY Cast(OrderTaken As Date),DATEPart(Hour,OrderTaken)
)
,yesterday AS(
SELECT Cast(OrderTaken As Date) oDate,
CASE WHEN DATEPART(hh,OrderTaken) > 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)-12) + ' PM' WHEN DATEPART(hh,OrderTaken) = 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)) + ' PM' WHEN DATEPART(hh,OrderTaken) < 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)) + ' AM' END As oHour,

Count(OrderNo) OrderCountYesterday
FROM @Orders
WHERE CAST(OrderTaken AS DATE)=CAST(@Date-1 AS DATE)
GROUP BY Cast(OrderTaken As Date),DATEPart(Hour,OrderTaken)
)
SELECT t.oDate Today,t.oHour Hour,t.OrderCountToday,y.OrderCountYesterday FROM today t join yesterday y ON  t.oHour=y.oHour and t.oDate=dateadd(day,1,y.oDate)

will result as:

p.s.: You can summarize this SQL a lot if you don't want to use AM/PM thing in the hour. Even the logic for AM/PM can be summarized further but that will show 12 PM as 0 PM.
Hope this help.


text:
Q: Extract data from nested JSON inside Mysql cell I need to  extract some data from a JSON inside a MySQL cell $row["detail"].
This is data that I need: options->408->value":"72" and options->409->value":"80"
this is my JSON
"132":{
      "id":132,
      "name":"Taille",
      "invoice_name":"Taille",
      "displayed_in_preview":"1",
      "displayed_in_order":"1",
      "input_suffix":"cm",
      "use_qty":"0",
      "required":"1",
      "ignored_if_empty":"1",
      "options":{
         "408":{
            "id":408,
            "id_option":104,
            "name":"Hauteur ",
            "selected_by_default":"0",
            "check_default":"0",
            "position":0,
            "min":70,
            "max":74,
            "default":"72",
            "weight":0,
            "delivery_impact":0,
            "value":"72",
         },
         "409":{
            "id":409,
            "id_option":105,
            "name":"Largeur",
            "selected_by_default":"0",
            "check_default":"0",
            "position":1,
            "min":70,
            "max":100,
            "default":"70",
            "weight":0,
            "delivery_impact":0,
            "value":"80",
         }
      }

but I receive an error.
I try this code:
$url = $row["detail"];
    $JSON_arr = json_decode($url, true);
    foreach($json_arr as $key){
      print $key -> options -> value

but I receive an error.

A: Here is example with your code:
<?php

$json = '{
    "132": {
        "id": 132,
        "name": "Taille",
        "invoice_name": "Taille",
        "displayed_in_preview": "1",
        "displayed_in_order": "1",
        "input_suffix": "cm",
        "use_qty": "0",
        "required": "1",
        "ignored_if_empty": "1",
        "options": {
            "408": {
                "id": 408,
                "id_option": 104,
                "name": "Hauteur ",
                "selected_by_default": "0",
                "check_default": "0",
                "position": 0,
                "min": 70,
                "max": 74,
                "default": "72",
                "weight": 0,
                "delivery_impact": 0,
                "value": "72"
            },
            "409": {
                "id": 409,
                "id_option": 105,
                "name": "Largeur",
                "selected_by_default": "0",
                "check_default": "0",
                "position": 1,
                "min": 70,
                "max": 100,
                "default": "70",
                "weight": 0,
                "delivery_impact": 0,
                "value": "80"
            }
        }
    }
}';

$JSON_arr = json_decode($json, true);

foreach ($JSON_arr as $row) {
    foreach ($row['options'] as $option => $data)
    echo 'option ' . $option . ' -> ' .'value: ' . $data['value'] . PHP_EOL;
}

Output:
option 408 -> value: 72
option 409 -> value: 80

Or here


text:
Q: What is the best way to call java methods from a running jar from node.js? I have a jar that is continuously running as a sort of server and I want to call methods from node.js using javascript. For example let's say I have a method called public String concatinateStrings(String[] stuff), how can I call this method from a node server? The method is an example, not something that I need to do in javascript.

A: It looks like there is a node package called node-java that does what I need it to: https://github.com/joeferner/node-java


text:
Q: how to cascade uitableview's width to its custom table view cell? I have a certain sized UIView used as a container of a UITableView. I use a subclass of UITableViewCell in my table view.
The problem is that my custom table view cell can not get the proper width from the UITableVIew.
This is how I create the table view
categoryListView = [[UITableView alloc] initWithFrame:categoryListContainer.bounds style:(UITableViewStylePlain)];
This is how I create the custom table view cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == categoryListView) {

        static NSString *CellIdentifier = @"MenuCategoryListIdentifier";

        MenuCategoryListCellView *cell = (MenuCategoryListCellView*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            // create dynamically
            cell = [[MenuCategoryListCellView alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:CellIdentifier];
        }
        ....

I wish to be able to get the correct cell bounds to in my MenuCategoryListCellView's initWithStyle method to draw my UI controls. But I don't know how to pass the value down.
Help will be appreciated!
Leo

A: The system will send the layoutSubviews message to your cell when the cell is resized.  Override that method to lay out the UI controls according to the cell's current size.


text:
Q: Opening bootstrap modal view in Django for editing a post I am learning basic Django development and am creating a simple blog app with several posts that I create. My home page includes this code that iterates through all posts and displays them.
{% for post in all_posts %}

      {{post.title}}
      {{post.description}}

        Edit Post

{% endfor %}

I have a #postEditModal which links to the Bootstrap data-target method and shows the following

    {{editpostform}}

My goal is to be able to click on the "Edit Post" link for each individual post, which should redirect to the slug for the post and open the modal all on top of the same page, and from there I should be able to edit the post using my {{editpostform}}. Clicking outside of the modal area should revert back to the same page.
I have tried many things like post.get_absolute_url and {% url 'single_post' post.id %}, but nothing so far has worked properly. I am assuming there is some level of Javascript/AJAX involved but I am not sure where to start with that.

A: You are creating several modals with the same id, and all your links point (data-target) to the same modal, which is not unique.
An easy solution is to add the post ID to the modal and the link. Try this:

    {{editpostform}}

And modify the links like this:
Edit Post


text:
Q: node.js - more than 2 byte hex number I'd like to print into a console 4-byte number represented in hexadecimal like so:
console.log('\x5050');

but clearly it behaves like 2-byte because it outputs
P50

P is 0x50 and then it just prints out remaining 50 as is. How do I make my program to look at it as a whole 32bit number, not 8bit?
Thank you!

A: First, 0x5050 is 2 byte not 4. Literal \x50 represents one byte because it takes two hexadecimal digits to represent an 8-bit number. Second, \x literal encodes only one byte, so you should use it like console.log('\x50\x50').

A: The '\xXX' notation in a string is used to convert the hexadecimal value to an ASCII character:
console.log('\x61');  // a

It's just a char in a string.
console.log('What\x27s up\x3F')  // What's up?

You can accomplish what you want with the 0xXX notation and the parseInt() method if it is a string representation:
console.log(parseInt('0x5050', 16))  // 20560
console.log(parseInt('5050', 16))  // 20560
console.log(0x5050)  // 20560


text:
Q: Path to all subdirectories that do not contain any files I know my question will sound silly to many of you, but can someone help me with a college topic?
Here is the statement: Make a shell script that receives a directory D as an argument. The script will recursively go through directory D and will look for and display the path to all subdirectories that do not contain any files (they are empty or contain only subdirectories).
It is requested not to use "find", thank you all.

A: You were probably looking for something more complicated than this...
find "$D" -type d -empty

A: The script may be implemented with a recursion function:
#!/usr/bin/env bash

if [ $# -eq 0 ] ; then
    echo "Usage: ./recursive.sh {path}" >&2
    exit 0
fi

D="$1"

print_recursively() {
    for f in "$1"/*; do
        echo "$f"
        if [[ -d "$f" ]] ; then
            print_recursively "$f"
        fi
    done
}

print_recursively "$D"

The solution may lack some details (like symlinks, unusual types of files etc), but it gives an idea of how recursive traverse can be implemented.


text:
Q: Custom Principal reverting to GenericPrincipal on new requests I'm trying to implement a custom principal and custom identity in a .NET MVC website. I've created a custom principal class which inherits from IPrincipal and a custom identity which inherits from IIdentity.
When a user logs in I set both Thread.CurrentPrincipal and HttpContext.Current.User to my custom principal. When I view either through the debugger the values are set with all the properties.
However once the request is complete and I try and request any other pages both Thread.CurrentPrincipal and HttpContext.Current.User are of type System.Security.Principal.GenericPrincipal and not my custom principal.
Do I need to do anything "extra" to get my custom principal out of the thread or HttpContext?
Thanks

A: The values in Thread.CurrentPrincipal and HttpContext.Current.User are not persisted between requests, they are rebuilt on each request.  The best place for you to do this is probably in the Global.asax; write a function with the prototype:
void Application_PostAuthenticateRequest(object sender, EventArgs e)

That should get called after a user is authenticated on each request, which will allow you to set the principal how you would like.

A: Overridding Principal in:
protected void Application_PostAuthenticateRequest(object sender, EventArgs e)

Instead of
protected void Application_AuthenticateRequest(object sender, EventArgs e)

In Global.asax.cs worked for me in an ASP web application

A: I would like to expand on the accepted answer slightly, hopefully I can save somebody a little bit of time.
In my case, the principal I used contained claims that were populated from the results of an external service, so I wanted to cache the results at login time.
I created a simple cache interface, IUserPrincipalCache, and registered it with the MVC DependencyResolver.  At login, I build up the principal and add it to the cache.  (Since your implementation may vary, I'll leave all that out.)
I then implemented this in Global.asax.cs:
protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        var cache = DependencyResolver.Current.GetService<IUserPrincipalCache>();
        var claimsPrincipal = cache.FindUser(User.Identity.Name);
        if (claimsPrincipal != null)
        {
            Context.User = claimsPrincipal;
            Thread.CurrentPrincipal = claimsPrincipal;
        }
    }
}

I think it is important to point out the check for IsAuthenticated, since I could bypass the cache check in many cases.  You also may not need to update Thread.CurrentPrincipal, I guess that depends on how you're using it.


text:
Q: how to remove duplicates from sql table with condition I have the below sql table and I want to remove the duplicate entries when object_id matches team_name. Basically I want unique values for object_id
session_id  object_id   team_name   user_name   user_desc
----------  ---------   ---------   ---------   -----------------
session1    user1       team1       user1       user1_description
session1    user2       team1       user2       user2_description
session1    team1       team1       user1       user1_description
session1    team1       team1       user2       user2_description

I want to convert the above table as below
session_id  object_id   team_name   user_name   user_desc
----------  ---------   ---------   ---------   -----------------
session1    user1       team1       user1       user1_description
session1    user2       team1       user2       user2_description
session1    team1       team1       null        null

How can I acheive this?

A: If I understand correctly, you can use aggregation:
select (case when min(session_id) = max(session_id) then min(session_id) end) as session_id,
       object_id,
       (case when min(team_name) = max(team_name) then min(team_name) end) as team_name,
       (case when min(user_name) = max(user_name) then min(user_name) end) as user_name,
       (case when min(user_desc) = max(user_desc) then min(user_desc) end) as user_desc
from t
group by object_id;


text:
Q: Load and charge on Sci-fiction context I have the next sentence

Our engineers tried to implement a laser beam as a weapon in this
  ship, and they success. This ship is able to make constant damage when
  we hit the enemy with the laser. They need some time to recharge
  before attack again

But I am not sure when to use reload or rechargue in the futuristic sci scenario

They need some time to recharge before attack again

or

They need some time to reload before attack again

Which one should I use and why?
Thanks in advance

A: "Reload" would certainly be understood in the context of a weapon being readied to fire again, but this word refers to a process of putting something inside something else; for example loading people onto a bus, or bullets into the chamber of a gun.
In your science-fiction context, there probably is no actual process of ammunition being physically loaded into anything. Your imaginary laser beams just "recharge", so this would seem more appropriate, and in fairness I'm sure your target audience would understand this too.
Although this is crossing a little into the realm of science and science-fiction, I would like to add that in real situations electrical things that "charge" from a fixed power source do so in order to independently "discharge". A real-life laser that is designed to fire a steady "beam" requires a constant energy source, whereas something that emits a single high-powered "pulse" such as an EMP (yes, they are real!) would have to build up a suitable charge first. Likewise in sci-fi, "beams" don't normally need to recharge, but weapons that fire once like "pulse-cannons" do.

A: Reload is generally reserved for weapons that shoot solid projectiles, e.g. bullets, shells, bombs, rail gun, sling-shot, etc. Damage is caused by the shape of the projectile (usually rounded or pointed at the front) of the projectile), and the kinetic energy given to it by the propellant that forces it forward, (gunpowder, compressed air, elastic band, centrifugal force, etc). Also, especially for shells and bombs, damage is increased by them containing an explosive charge). These weapons can run out of ammunition, but as soon as new ammunition is loaded, the weapon is instantly available for firing, assuming that it has not overheated.
Recharge is generally used for weapons that emit some form of energy (other than kinetic energy in the form of a fast moving solid projectile), e.g. ray-gun, laser, phasar, pulse cannon, etc. These weapons can never run out of ammunition, but they can run out of energy. When this happens the weapon has to have its batteries (power cells, capacitors, energy stores, etc) recharged from another energy source. This may take some time, depending on the power of the weapon, the amount of energy available from the energy source, and the amount of energy that can flow between the power source and the weapon.
From the context of your question, it sounds like your weapon needs to be recharged.


text:
Q: I wrote the shared preferences code and it didn't work for me, what's the problem? I wrote the shared preferences code and it did not work for me, I want it to move to a specific activity when the name is academic and the password is 123, and I want it to move to another activity when the name is admission and the password is 456. Where is the problem?
//this is my code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    login = findViewById(R.id.btnLogin);
    name = findViewById(R.id.inputUsername);
    password = findViewById(R.id.inputPassword);
    checkBox = findViewById(R.id.checkBox);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SharedPreferences preferences = getSharedPreferences("login data", MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            if (checkBox.isChecked()) {

                editor.putString("username", name.getText().toString());
                editor.putString("MyPassword", password.getText().toString());
                editor.putBoolean("checked", true);
                editor.apply();

            } else {
                editor.remove("username");
                editor.remove("MyPassword");
                editor.remove("checked");
                editor.apply();

            }
            if (TextUtils.isEmpty(name.getText().toString()) || TextUtils.isEmpty(password.getText().toString())) {
                Toast.makeText(LoginActivity.this, "empty data", Toast.LENGTH_SHORT).show();
            }

            if (name.getText().toString().equals(true_user_name_Admission) && password.getText().toString().equals(true_password_Admission)) {

                Intent l = new Intent(LoginActivity.this, AdmissionDashboardActivity.class);
                startActivity(l);
                Toast.makeText(LoginActivity.this, "Accessed", Toast.LENGTH_SHORT).show();

            } else {
                if (name.getText().toString().equals(true_user_name_Academic) && password.getText().toString().equals(true_password_Academic)) {

                    Intent ad = new Intent(LoginActivity.this, AcademicDashboardActivity.class);
                    startActivity(ad);
                    Toast.makeText(LoginActivity.this, "Accessed", Toast.LENGTH_SHORT).show();
                } else {

                    Toast.makeText(LoginActivity.this, "Required", Toast.LENGTH_SHORT).show();
                    name.setError("Required");
                    password.setError("Required");
                }

            }

        }

    });
}

@Override
protected void onResume() {
    super.onResume();
    SharedPreferences sp = getSharedPreferences("login data", MODE_PRIVATE);
    name.setText(sp.getString("username", ""));
    password.setText(sp.getString("MyPassword", ""));
    checkBox.setChecked(sp.getBoolean("checked", false));

}

}

A: can you try this
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

login = findViewById(R.id.btnLogin);
name = findViewById(R.id.inputUsername);
password = findViewById(R.id.inputPassword);
checkBox = findViewById(R.id.checkBox);
SharedPreferences preferences = getSharedPreferences("login data", MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();

login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        if (checkBox.isChecked()) {

            editor.putString("username", name.getText().toString());
            editor.putString("MyPassword", password.getText().toString());
            editor.putBoolean("checked", true);
            editor.apply();

        }
        if (TextUtils.isEmpty(name.getText().toString()) || TextUtils.isEmpty(password.getText().toString())) {
            Toast.makeText(LoginActivity.this, "empty data", Toast.LENGTH_SHORT).show();
        }

        if (name.getText().toString().equals(true_user_name_Admission) && password.getText().toString().equals(true_password_Admission)) {

            Intent l = new Intent(LoginActivity.this, AdmissionDashboardActivity.class);
            startActivity(l);
            Toast.makeText(LoginActivity.this, "Accessed", Toast.LENGTH_SHORT).show();

        } else if (name.getText().toString().equals(true_user_name_Academic) && password.getText().toString().equals(true_password_Academic)) {

                Intent ad = new Intent(LoginActivity.this, AcademicDashboardActivity.class);
                startActivity(ad);
                Toast.makeText(LoginActivity.this, "Accessed", Toast.LENGTH_SHORT).show();
            } else {

                Toast.makeText(LoginActivity.this, "Required", Toast.LENGTH_SHORT).show();
                name.setError("Required");
                password.setError("Required");
            }
    }

});
}

@Override
protected void onResume() {
    super.onResume();
    name.setText(sp.getString("username", ""));
    password.setText(sp.getString("MyPassword", ""));
    checkBox.setChecked(sp.getBoolean("checked", false));

}


text:
Q: Testing status code expects 500 instead of 200 I'm writing my firsts tests with Symfony 4.1, and I'm experiencing an odd problem. The test is to make sure the endpoint returns status 200:
public function testFetchTaskEndpointStatusCode200()
{
    $client = static::createClient();
    $client->request("GET", "/tasks");

    $this->assertEquals(200, $client->getResponse()->getStatusCode());
}

The endpoint then triggers the following method:
/**
 * @Route("/tasks")
 * @Method("GET")
 */
public function fetchAction()
{
    $repository = $this->getDoctrine()->getRepository(Task::class);
    $tasks = $repository->findAll();

    return $this->json([
        'tasks' => $tasks
    ]);
}

Using Insomnia software and through browser, I can see the returned status is 200, but when executing the test:

Failed asserting that 500 matches expected 200.

Why?

A: At testing time some error occurs on your server side code, hence the error code 500. Since we cannot see your testcase and setup it will be hard for us to guide you

A: Adding
<phpunit>
    ...
    <!-- define your env variables for the test env here -->
    <env name="DATABASE_URL" value="mysql://username:password@127.0.0.1:3306/database" />
</phpunit>

to phpunit.xml.dist solved it.


text:
Q: FileProvider is queried by a client app with "_data" in projection I am implementing a FileProvider.
Its advantages over plain ContentProvider is greater security:

*

*secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri

*a content URI allows to grant read and write access using temporary access permissions

So one of the points is that client app should not know the real file path to access the data.
For most of the client apps it's important to know the human-friendly name of file and/or size of the file before they start reading actual data. Those apps ask FileProvider about name/size via query() method. The method expects only 2 options in projection param - OpenableColumns (_display_name, _size).
And now the issue. Some client apps are passing _data into projection, expecting to get a real full path to the data. But returning a real file path would break the whole idea of using FileProvider for security reasons.
My question is 'Am I missing anything?'. Is it just some client apps are poorly written, so it's theirs problem that they crash because of not getting the file path?