text:
Q: TypeError: encoding without string argument I can't see the problem
Hi, I have this function that converts a JSON dictionary to bytes. It then separates each element with b'\x00\x00'. I am doing this so that It can talk with a client I made for a game in Game Maker.
To better illustrate my problem I am going to use an example.This is the function that I am running Encode({"header": 1}).
Result I want b'header\x00\x001\x00\x00'
What I get TypeError: encoding without a string argument.
What I have tried
I have tried debugging this on my own, but I just can't seem to find the problem at hand. One thing that I find odd is that if I put this line from my code in a print ( This is also the part that is causing issues). It works print(buffer + bytes(_e,"utf-8") + b'\x00\x00') but this  does not buffer = buffer + bytes(_e,"utf-8") + b'\x00\x00'.
Code
# Encode function
def Encode(data):
    buffer = b''
    for e in data.items():
        for _e in e:
            buffer = buffer + bytes(_e,"utf-8") + b'\x00\x00'
    return buffer

A: You need to modify your code in order to get each pair of key-values and convert them to bytes. Keep in mind that you need to convert each value to string using str(), before you convert them to bytes:
# Encode function
def Encode(data):
    buffer = b''
    for key, value in data.items():
        buffer = buffer + bytes(key, 'utf-8') + b'\x00\x00' + bytes(str(value), 'utf-8') + b'\x00\x00'
    return buffer

r = Encode({"header": 1})
print(r)

This will return:
b'header\x00\x001\x00\x00'


text:
Q: Mikrotik CCR1009 ROS 7 dual WAN configuration i have a CCR1009 (ROS 7.2.3) configured with the COMBO port as WAN_1 and the eth1 to eth5 ports as LAN, VOIP, and 3 SERVER with different subnets.
The ISP is fastweb (mixed fiber 100/100) which provides me with 5 public IP addresses and which I have assigned to each port to differentiate some services.
Since Vodafone arrives in direct fiber at 1000/200 I would like to connect it to eth7 as WAN_2 and divert all traffic from the LAN to it and leave VOIP and the 3 SERVER on WAN_1.
I researched for hours and I realized that you need to create 2 mangle rules (one for FASWEB and one for VODAFONE) where the packets are marked, assign them to 2 routing tables and then modify the route by assigning the tables for the two connections.
Unfortunately despite all attempts I was unable to get the configuration to work.
Could anyone kindly help me?
Thanks in advance,
Gianluca
the current configuration without mangle rules is as follows:
# jun/22/2022 13:59:29 by RouterOS 7.2.3
#
# model = CCR1009-7G-1C-1S+
#

/interface bridge
add name=BRIDGE_LAN
add name=BRIDGE_SERVER

/interface ethernet
set [ find default-name=combo1 ] name=WAN_ISP1
set [ find default-name=ether1 ] name=LAN
set [ find default-name=ether2 ] name=VOIP
set [ find default-name=ether3 ] name=SERVER1
set [ find default-name=ether4 ] name=SERVER2
set [ find default-name=ether5 ] name=SERVER3
set [ find default-name=ether7 ] name=WAN_ISP2
set [ find default-name=sfp-sfpplus1 ] name=SFPPLUS

/ip pool
add name=dhcp_lan_pool ranges=192.168.98.100-192.168.98.254

/ip dhcp-server
add address-pool=dhcp_lan_pool interface=BRIDGE_LAN name=dhcp_lan

/routing table
add disabled=no fib name=TO_VODA
add disabled=no fib name=TO_FAST

/interface bridge port
add bridge=BRIDGE_SERVER ingress-filtering=no interface=SERVER1
add bridge=BRIDGE_SERVER ingress-filtering=no interface=SERVER2
add bridge=BRIDGE_SERVER ingress-filtering=no interface=SERVER3
add bridge=BRIDGE_LAN ingress-filtering=no interface=LAN

/ip address
add address=192.168.99.1/24 interface=BRIDGE_SERVER network=192.168.99.0
add address=192.168.98.1/24 interface=BRIDGE_LAN network=192.168.98.0
add address=192.168.1.1/24 interface=VOIP network=192.168.1.0

add address=xxx.xxx.xxx.142/29 comment="WAN_ISP1 EMPTY" interface=WAN_ISP1 network=xxx.xxx.xxx.136
add address=xxx.xxx.xxx.141/29 comment="WAN_ISP1 VOIP" interface=WAN_ISP1 network=xxx.xxx.xxx.136
add address=xxx.xxx.xxx.140/29 comment="WAN_ISP1 WEB" interface=WAN_ISP1 network=xxx.xxx.xxx.136
add address=xxx.xxx.xxx.139/29 comment="WAN_ISP1 NAS" interface=WAN_ISP1 network=xxx.xxx.xxx.136
add address=xxx.xxx.xxx.138/29 comment="WAN_ISP2 LAN" interface=WAN_ISP1 network=xxx.xxx.xxx.xxx

/ip dhcp-server network
add address=192.168.98.0/24 comment="GW LAN" dns-server=192.168.98.1 gateway=192.168.98.1

/ip dns
set allow-remote-requests=yes servers=8.8.8.8,1.1.1.1

/ip firewall filter
add action=accept chain=input comment="ACCEPT ESTABILISHED,RELATED" connection-state=established,related
add action=accept chain=input comment="ALLOW PING ROUTERBOARD" protocol=icmp
add action=drop chain=forward comment="DROP INVALID PACKET" connection-state=invalid
add action=drop chain=input comment="DROP ALL OTHER ON WAN" in-interface=WAN_ISP1
add action=drop chain=input comment="DROPPA DROP ALL OTHER" disabled=yes

/ip firewall nat
add action=dst-nat chain=dstnat comment="NAT VOIP 1:1 WITH HAIRPIN NAT" disabled=yes dst-address=xxx.xxx.xxx.141 dst-port=0-65535 protocol=udp to-addresses=192.168.1.10
add action=dst-nat chain=dstnat comment="VOIP TEST TCP" dst-address=xxx.xxx.xxx.141 dst-port=40000-40999 protocol=tcp to-addresses=192.168.1.10 to-ports=40000-40999
add action=dst-nat chain=dstnat comment="VOIP TEST UDP" dst-address=xxx.xxx.xxx.141 dst-port=40000-40999 protocol=udp to-addresses=192.168.1.10 to-ports=40000-40999
add action=dst-nat chain=dstnat comment="NAT WEBSITE 1:1 WITH HAIRPIN NAT" dst-address=xxx.xxx.xxx.140 dst-port=0-65535 protocol=tcp to-addresses=192.168.99.16
add action=dst-nat chain=dstnat comment="VOIP SIM (SU LAN) TCP" dst-address=xxx.xxx.xxx.141 dst-port=45000-45999 protocol=tcp to-addresses=192.168.98.42 to-ports=45000-45999
add action=dst-nat chain=dstnat comment="VOIP SIM (SU LAN) UDP" dst-address=xxx.xxx.xxx.141 dst-port=45000-45999 protocol=udp to-addresses=192.168.98.42 to-ports=45000-45999
add action=src-nat chain=srcnat comment="NAT WEBSITE 1:1 OUT" src-address=192.168.99.0/24 to-addresses=xxx.xxx.xxx.140
add action=src-nat chain=srcnat comment="NAT VOIP 1:1 OUT" src-address=192.168.1.0/24 to-addresses=xxx.xxx.xxx.141
add action=src-nat chain=srcnat comment="NAT LAN 1:1 OUT" src-address=192.168.98.0/24 to-addresses=xxx.xxx.xxx.138

/ip route
add disabled=no distance=1 dst-address=0.0.0.0/0 gateway=xxx.xxx.xxx.137 pref-src=0.0.0.0 routing-table=main scope=30 suppress-hw-offload=no target-scope=10 # route per fastweb

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why won't my data go into my database? I would like these values to go into my database but it just won't do it.
Form Code
<form action='ryge.php' method='POST'>

 Navn:

<?php echo $_SESSION['first'] . " " . $_SESSION['last'] ?>

<input type='text' name='name' placeholder='dit navn'>

<input type='text' name='cig' placeholder='Navn på smøger'>

<input type='text' name='brand' placeholder='Navn på brandet af smøger?'>

<input type='text' name='unit' placeholder='Hvor mange enheder har du?'>

<input type='text' name='pris' placeholder='Pris pr smøg'>

<input type='text' name='lighter' placeholder='Har du lighter'>

<input type='text' name='place' placeholder='Lokation til rhyyge'>

<input type='text' name='tid' placeholder='Hvad tid passer dig bedst?'>

<input type='text' name='howlong' placeholder='Hvor langtid har du at rhyyge i?'>

<input type='text' name='day' placeholder='hvilke dag/dage'>

<input type='text' name='pers' placeholder='Alene eller i gruppe?'>

<button type='submit' name='tilføj' >Tilføj til dine præferencer broder</button>
</form>

PHP Code
<?php
session_start();
include 'dbh.php';

    $name = $_POST['name'];
    $cig = $_POST['cig'];
    $brand = $_POST['brand'];
    $unit = $_POST['unit'];
    $pris = $_POST['pris'];
    $ligther = $_POST['ligther'];
    $place = $_POST['place'];
    $tid = $_POST['tid'];
    $howlong = $_POST['howlong'];
    $day = $_POST['day'];
    $pers = $_POST['pers'];

    $sql = "INSERT INTO prod (name, cig, brand, unit, pris, lighter, place, tid, howlong, day, pers)
            VALUES ('$name', '$cig', '$brand', '$unit', '$pris', '$ligther', '$place', '$tid', '$howling', '$day', '$pers')";
    $result = mysqli_query($conn, $sql);

header("Location: index.php");

A: You are on the right track but really need to refine your code. First, the SQL syntax you are using is out of date and susceptible to injection. You should read about prepared statements and make that your way of coding in the future.
Second, as one of the other posters mentioned, you are including the same file more than once.
Third, you should also look at the ISSET command and include it via an if / else statement so that your code runs properly. Right now, you are running the entire code on the server with no data to fill it. You need to look for a proper "Submit" via ISSET and execute the PHP code at that point.
See here for more help:
how to insert into mysql using Prepared Statement with php


text:
Q: Does a DTO/POJO rise to the qualification of a configurable service in OSGi/DS? Note: This is the first question in a series of question I'll have, all relating to the same environment.
Currently, I'm using the ConfigurationAdmin service as a configuration persistence mechanism, dumb data holder, and convenient cross-bundle updater. This feels wrong, so I'm trying to make it more right.
I'm writing a game in which everything should be configurable at runtime. This lead me down the ConfigurationAdmin route for wiring things together.
The game by its nature doesn't do anything, and instead, functionality is provided by the combination of bundles available.
One bundle introduces the concept of Species. To maintain as high a degree of flexibility as possible, a Species is really just a name.
@Component(...)
@Designate(...)
class Species {

    lateinit var name: String

    @Activate
    fun activate(config: SpeciesConfig) {
        name = config.name
    }
}

All additional functionality relating to a Species must be provided by a separate bundle. For example, another bundle introduces the concept of a Pokemon. A Pokemon is just a member of a Species, just like humans are a member of the Homo Sapiens Sapiens species.
@Component(...)
class Pokemon {

    @Reference
    lateinit var species: Species
}

I've been using Declarative Services (DS) to automatically set the species reference.
Here though, you can see that neither Species nor Pokemon are really services, rather Species is a name and persistent identity, and Pokemon is a persistent identity, and reference to a Species. The only methods that might be implemented for these classes are the usual hashCode, toString and equals.
This realization is what first tipped me off that perhaps ConfigurationAdmin is not the right tool; that perhaps a SpeciesRepository or PokemonRepository might be better suited for the job of storing the configuration.
Question: Do DTO/POJOs like Species rise to the qualification of a service, defined by OSGi/DS, given that there could range from dozens to thousands of Species defined, with none, one, many, or all of them available during runtime?
EDIT: I noticed that Peter Kriens said in another question

Well, in an OSGi world things seem pretty simple and straightforward: every object is a component. So in the non-OSGi world you need some DI engine to do the injection.

Maybe it is okay to have things this small be components?


text:
Q: User roles and claim are not recognized when using Asp.Net Core Identity with External login provider In my system I'm using AzureAD as external login to authenticate users in my organization. When I created the App I choose the the authentication type as Microsoft external authentication. I connected my app to the app registered in AzureAD
I got this code in my program.cs file
  builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

and in my appsettings.json I got all needed info such as clientId, tenantId, etc.
and all of this works fine.
But I wanted to also use ASP.NET Core Identity. As I don't want anyone in my organization to be able to login to the system. I only want certain people that I add through the system and have permission to access the system.
for this one I created a manage users page to add users to the system by searching AD and create them as users in the system and I gave them roles such as Admin.
This didn't work at first because Identity doesn't seam to work with external login. So to fix this I added a Scaffolded Item for login and logout.
And everything works fine.
Once user loges in through Ad I check on the system if this user exists or not, if yes I sign them in using SignInManager and then redirect them to the main page else they hit No Access page. This is my code
        [HttpGet]
        public async Task<IActionResult> CheckSignIn()
        {
            if (User.Identity.IsAuthenticated)
            {

                var user = await userManager.FindByEmailAsync(User.Identity.Name);

                if (user != null)
                {

                    await signInManager.SignInAsync(user, false);

                    return RedirectToAction("Dashboard", "Dashboard");
                }
                else
                {
                    await signInManager.SignOutAsync();
                    return RedirectToAction("NoAccess", "ManageAccess");
                }
            }
            return RedirectToAction("NoAccess", "ManageAccess");
        }

Now the Issue is that After giving the user for example Admin role, when I add authentication header to my controller for example. It doesn't work and user is redirect to access denied page even though they have admin role.
    [Authorize(Roles="Admin")]

How Can I fix this, The system doesn't Identify the user, I tried to check if user is signed in by using this code SignInManager.IsSignedIn(user), but it doesn't work. The user is not signed in. It returns false.
So the user is never signed in and the system therefore doesn't recognize if he has the admin role that's why it redirect him to access denied page.
Any help on how to achieve this!
Thank you.

A: Please use claims transformation to add claims to existing identity.
One more thing, please check theb order of the Authentication and Authorization in the pipeline. Authentication should be placed before Authorization.


text:
Q: Two actions for one variables PHP I want to have two actions for my one variables, here is the variables;
Header:('Location:http://localhost/portailinx/inscriptioncarosou.php')
unset($_SESSION['fb_token'])

I try with this :
$next = Header:('Location:http://localhost/portailinx/inscriptioncarosou.php') && unset($_SESSION['fb_token']);

but is not working.
Is not a form, it's just a simple variable for facebookhelper->getLogoutURL

A: first of all unset and after redirect user, eg:
// it is good practice to check that something is set before unset
if(isset($_SESSION['fb_token'])) unset($_SESSION['fb_token']);

// after unset can redirect the user
header('Location:http://localhost/portailinx/inscriptioncarosou.php');

// end the script run
exit;

A: Unset before redirection, and fill there missing ; at the end of commands.
unset ($_SESSION['fb_token']);
Header:('Location:http://localhost/portailinx/inscriptioncarosou.php');

Header: is somewhere probably defined as header('Location: ' ...);, if not, you meant this:
header ('Location: http://localhost/portailinx/inscriptioncarosou.php');

After redirect is good to end the script run, so add exit behind header function. The full script should be
unset ($_SESSION['fb_token']);
header ('Location: http://localhost/portailinx/inscriptioncarosou.php');
exit;

A: Try it the other way.
It's called 'short-circuit'
one-thing&&another
one-thing always happens first, then another.  So in your example the redirect happens, and the unset is never reached


text:
Q: SlidingPaneLayout setCoveredFadeColor () and setSliderFadeColor() I'm using the SlidingPaneLayout  and want to set gray fade color on left pane when the slider right pane is open and a transparent fade color on the left pane when the right pane is closed and left pane is fully visible.
I know this is the default behaviour of the  SlidingPaneLayout , but with default implementation I'm facing issues in the landscape mode wherein my slider left pane always remains faded and takes no click events even if right slide is closed.
I implemented the SlidingPaneLayout.SimplePanelSlideListener and managed the fade colors in onPanelOpened() and onPanelClosed()
But I'm nit sure which function should I use for this... setCoveredFadeColor() or  setSliderFadeColor()?
What is the exact difference between these 2 functions?
Any help is much appreciated. Thanks!

A: From the docs:
setSliderFadeColor(int color) Set the color used to fade the pane covered by the sliding pane out when the pane will become fully covered in the closed state.
setCoveredFadeColor(int color) Set the color used to fade the sliding pane out when it is slid most of the way offscreen.
In my experience, I've found that the panel that gets covered needs to be at least 320dp wide for these two fade colours to work.


text:
Q: Experiencing weird top margin when using fpdf Write() I'm trying to write text to a PDF and there seems to be a weird margin on the top of my page.
This is my following code:
require_once('fpdf.php');
require_once('fpdi/fpdi.php');

//Start the FPDI
$pdf = new FPDI('P', 'pt');

//Set the source PDF file
$source_file = $pdf->setSourceFile("template.pdf");

//Import the first page of the file
$tppl = $pdf->importPage(1);

$pdf->AddPage();

//get size of pdf page
$size = $pdf->getTemplateSize($tppl);

$pdf->useTemplate($tppl, null, null, $size['w'], $size['h'], true);
$pdf->SetMargins(0, 0, 0);
$pdf->SetTextColor(0, 0, 0);

When I use a font-size pt 12, and write text I get this:
$pdf->SetFont('Arial', '', 12);
$pdf->SetXY(0, 0);
$pdf->Write(0, "Hi");

When I do $pdf->SetXY(0, 7.5) I get this

The above looks like I can easily add 7.5 points to the Y and be fine.
However, if I changed the font-size, the distance between the top and the text grows a little greater.
$pdf->SetFont('Arial', '', 8);

Could anyone help me figure out how to neutralize this to at least make it so if I set my XY to a number, it will put it on the some location regardless of the font-size? I've tried different pdf's and it works all the same.
EDIT:
I did $pdf->GetY() and I get 28.35

A: You simply define a line height of zero. Because of this the text is "centered" vertically around 0.

A common line height is:
$pdf->Write($pdf->FontSize * 1.2, "Hi");

A: I solved this by instead of doing Write() I used Cell().
I think the main issue was not having a solid width and height. All I know is it works perfectly now so anyone encountering the same problems should try this.
$pdf->Cell(WIDTH,HEIGHT,TEXT);

I also did the following, not sure if this helped or not but I have it in my script.
$pdf->SetMargins(0, 0);
$pdf->cMargin = 0;


text:
Q: Unable to create a table with comment I am trying to create a table and want to add a comment in the schema but I am not able to get the syntax correct.
CREATE TABLE codingjedi.practice_questions_javascript_tag(
  year bigint,
  month bigint,
  creation_time_hour bigInt,
  creation_time_minute bigInt,
  id uuid,
  PRIMARY KEY ((year, month), creation_time_hour, creation_time_minute)
) WITH comment = 'some comment' CLUSTERING ORDER BY (creation_time_hour DESC, creation_time_minute ASC)

A: I had to use AND to combine the two instruction
CREATE TABLE codingjedi.practice_questions_javascript_tag(
  year bigint,
  month bigint,
  creation_time_hour bigInt,
  creation_time_minute bigInt,
  id uuid,
  PRIMARY KEY ((year,month), creation_time_hour, creation_time_minute, id )
) WITH comment = 'some comment' AND CLUSTERING ORDER BY (creation_time_hour DESC, creation_time_minute ASC, question_id ASC);


text:
Q: Monitor network traffic with just a simple router I'd like to monitor incoming and outgoing network traffic from my PC (windows 7). My network setup is as follows: `internet -> 8 port Cnet LAN router -> (PC's && Wireless Router). Is it possible for me to monitor and block visited websites on this network? Are the tools free? What are they?
I'd especially like to know if there is anyone on the network streaming music or video.
Thank you.

A: Most consumer routers cannot do application or port level traffic monitoring so most likely no.  Checking the documentation of the LAN/Router would be the place to look to confirm this.
Untangle is a free product that can do this however it must be installed on a dedicated PC w/ 2 NIC's.
Traffic can also be monitored and controlled w/ a firewall device, look at Sonicwall, Watchguard, Fortinet, etc.
If you just need to monitor overall traffic levels then PRTG can do it if the router supports SNMP. This will not provide info on specific traffic types, ports nor will it block anything.

A: Do you mean you want to monitor on the "8 port Cnet LAN router" or on the "PCs && Wireless Router"? In the first case, you're probably out of luck because that thing is unlikely to have any brains. In the second case, you may be able to install OpenWRT or DD-WRT on the wireless router and monitor from there. There's numerous ways to monitor traffic once you have an alternate Linux-based firmware in place, but whether you can do that will depend on the brand and model of that device.


text:
Q: Whenever I try to download my Ubuntu 1 files, chrome block me. I received an email regarding the closure of ubuntu1 files I tried using the link to transfer (os is Windows 7 Ultimate) each time I tried I received error message Chrome blocked download, is MALICIOUS.
I can't even remember how to view my files to see if any could be removed. Please let me know what are my alternatives in retrieving my files.

A: Try using another browser? Chrome frequently blocks "bad" stuff, and is normally right (which is why I use it) but it can be wrong.
Or you could transfer them to Google Drive / Skydrive / Dropbox? I received the same email, and they suggest going to mover.io as they offer it for free for Ubuntu 1 at the moment.


text:
Q: Why no indefinite article in "playing at basketball"? I'm a confused by the way Mick used the indefinite article "a" in his comment:

You could say that the child is playing at basketball, or playing with a basketball.

Why does the phrase "at basketball" not have an article, whereas the phrase "with a basketball" has the indefinite article "a"?
My guess would be that the key point here is the preposition (at) that in the first case prevents its use, whereas, in the second case the preposition (with) calls for its use, but I'm not sure either whether there's such a thing in English as the preposition to be decisive in the indefinite article use or what other rule may govern this situation.

A: It's an idiomatic expression:

To play at: 1. To pretend to be or to do something for amusement or out of curiosity; 2. To do or take part in something halfheartedly:

So in this case (as Au101 mentions in his comment) "to play at basketball" means  to play the game of basketball in a desultory manner, while to "play with a basketball" means to use the actual ball.
Other examples of "play at":

She played at being a lawyer, but her heart was always set on politics.
The soldiers played at dice while they were waiting for the enemy to attack.
People say he just plays at being a developer, but still, he's made millions off of his app.


text:
Q: How to comment properties of a class for Visual Studio intellisense? I know using /// to comment a function is the right way, and it also works for properties as shown by the following code
/// <summary>
/// This is for demo
/// </summary>
public class Foo
{
    /// <summary>
    /// Description A (working for intellisense)
    /// </summary>
    public int iA { get; set; }

    /// Description B (not working for intellisense)
    public int iB { get; set; }

    public int iC { get; set; }
}

I am wondering if there is a simpler way to comment class properties for intellisense than the ///  which is 3 lines minimum.

A: You can you GhostDoc which generates some simple but useful comments automatically.

A: Recommended Tag for property in Documentation is <value> as per official .NET Guide
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/value
/// <value>The Name property gets/sets the value of the string field, _name.</value>

A: It's just XML. You can do it in one line if you want to.
/// <summary>Description A (working for intellisense)</summary>
public int iA { get; set; }


text:
Q: pid for child of child processes i'm running a script that calls a child script that in turn calls other child scripts and processes.
some of the child processes use a lot of disk io and cpu, and overheats the cpu, causing a crash or errors. i guess i can thank intel for that. this isn't a request for information to fix my cpu.
i want to pause the script for 2mins every 5mins, to allow the cpu to cool down.
this is in my parent script:
for dir in * ; do
        if [ -d "$d" ]; then
                printf "$dir."
                ./subscript.sh "${dir}" &
                        echo "$!" > ./"${dir}.pid" &
                        ./pauser.sh "${dir}"
                #rm ./"{d}.pid"
        touch "{d}.pid.ended"
        fi
done

and this is my pauser.sh script:
#!/bin/bash
pauser() {
        printf "@" &&
                sleep "${2}m" &&
                check_running "${1}" &&
                kill -STOP "$(cat ${1}.pid)" &&
                sleep "${3}m" &&
                printf "." &&
                check_running "${1}" &&
                kill -CONT "$(cat ${1}.pid)"
}
check_running() {
        if [ -f "${1}.pid.ended" ]; then
                rm "${1}.pid.ended"
                exit 0
        fi
}
while true
do
        if [ -f "${1}.pid.ended" ]; then
                rm "${1}.pid.ended"
                exit 0
        else
                pauser "${1}" "5" "2"
        fi
done

this pauser script doesn't pause the child of child processes, i think because the child of child scripts/processes have different pid's.
i've read that child of child processes can be grouped, if so, how do i pause and resume the entire group of child processes from the parent script?

A: thanks to @PSkocik here, i can set -m before the child process, and set +m afterward, which will set each child process in it's own group.
all child processes of that child process will also be in the same group, so they all have the same group id.
by using kill -STOP -${pid_to_pause} the negative before the process id pauses the entire group, because the group id also happens to be the most senior of the group's pid, but not the parent script, because of set -m
my new parent script:
for dir in * ; do
    if [ -d "$dir" ]; then
        printf "$d."
        set -m
        ./subscript.sh "${dir}" &
            echo "$!" > ./"${d}.pid" &
            ./pauser.sh "${dir}"
        #wait
        set +m
        #rm ./"{dir}.pid"
        touch "{d}.pid.ended"
    fi
done

my new pauser script:
#!/bin/bash
pauser() {
    sleep "${2}m" &&
        check_running "${1}" &&
        printf "," &&
        kill -STOP "-$(cat ${1}.pid)" &&
        sleep "${3}m" &&
        check_running "${1}" &&
        printf "." &&
        kill -CONT "-$(cat ${1}.pid)"
}
check_running() {
    if [ -f "${1}.pid.ended" ]; then
        rm "${1}.pid.ended"
        exit 0
    fi
}
while true
do
    if [ -f "${1}.pid.ended" ]; then
        rm "${1}.pid.ended"
        exit 0
    else
        pauser "${1}" "15" "5"
    fi
done


text:
Q: Regex to find a method with specific return and behviour inside of it I want something similar to this, but within the scope of a method.
Given a project, I want to find all the files with a method which return an specific Object and use another specific method.
Currently I only have this: MyObject(.)*\((.)*\)[\w\W]*?return which selects the method with the return I expect, but how can I specify a behaviour inside of it?
Feel free to use another simpler pattern, I don't know if the one I've created is good enough.
And please, explain the Regex as I am not an expert of it, and for future purposes also.

A: Not exactly what you want, but you could perform a search with the scope Files in Previous Search Result.
Structural Search seems like a better solution to your problem. Use the existing template methods of the class and edit the variable ReturnType to equal the type you want. Then use the template method calls and edit the variable MethodCall and search in scope Previous Search Results.


text:
Q: "Dimension Lookup/Update": type-2 SCD date_from value? I'm trying to use Pentaho Data Integration / Pan to make a type-2 (SCD) table.
After I ran my data through a DimensionLookup step a first time, I got a type-2 table that looks like:
PKID  version  date_from             date_to                MyPK  Field1  Field2  ...
150   1        1900-01-01 00:00:00   2199-12-31 23:59:59    1     "X"     "Y"     ...

So far so good.  Then later I got new data, updated my original table to it, and ran it through the same DimensionLookup step, and all the modified records looked like:
PKID  version  date_from             date_to                MyPK  Field1  Field2  ...
150   1        1900-01-01 00:00:00   2010-06-24 03:45:00    1     "X"     "Y"     ...
151   2        2010-06-24 03:45:00   2199-12-31 23:59:59    1     "X2"    "YYY"   ...

That looks good, too.  But for records that were added to my dataset since last time, they get added with date_from='1900-01-01 00:00:00'.  (And come to think of it, it's a bit strange that my initial load used date_from='1900-01-01 00:00:00', too.)
I'm having it use the default start date, which claims to be the system's current datetime, though I've also tried "start_trans" ("Start date of transformation"), which did the same thing except using a timestamp 9 hours earlier (on 1899-12-31).
I can't see how using 1900 for all new records makes sense: you can't tell what was added when, since it looks like every new record has existed since the start of time.  I even looked up type-2 in Kimball's book, and while it wasn't super explicit, it seemed to indicate that newly inserted values should have as their date_from the time they start being valid.
Is this a bug in PDI?  Is there a workaround?  Am I just using it wrong?  Am I misunderstanding the whole point of type-2?
Thanks!

A: You want to add into the transformation a new field or variable with the current system time.
There are several ways to do it, so I'll just suggest one.
Add a new transformation at the beginning of the job called set_current_time. This transformation will get the current system time (you can get it from the database using a Table Input step). Then you use Set Variable to set the current time as a variable that will be available throughout the job.
From here, it's fairly easy to find if you need to use the variable or the previously available date as the date_from field, using a combination of a lookup and a formula/script.


text:
Q: Modular SQL WHERE statement I'm trying to create prepared SQL statement inside of a python script that has modular inputs. I have the "INSERT" part of the statement working but cannot get the WHERE clause to update modularly. Is there a way to do this?
query = "INSERT INTO MachineInfo ( Description, Location, IP, License )
         WHERE id = ID
         VALUES (?,?,?,?,?)"

#The arguments are all predefined variables
args = [ deviceName, deviceLocation, ipAddress, license, ID ]

system.db.runPrepUpdate( query, args )

A: You seem to want an UPDATE:
UPDATE MachineInfo
    SET Description = ?,
        Location = ?,
        IP = ?,
        License = ?
    WHERE id = ?;


text:
Q: Move data to adjacent columns based on date (month) value Moving expense data from columns K:M to respective columns N:Y (Jan, Feb, Mar, etc.) based on date (month) in column AA, but any future dates in column AA are populating the data in the future (forward) and not historically as desired?
Sub MoveData()
Dim vals As Range, val As Range, colOffset As Integer
Set vals = Range("K2:K" & Range("K2").End(xlDown).Row)

For Each val In vals

 If val > 0 Then
  colOffset = VBA.month(val.offset(0, 16))
  val.offset(0, colOffset) = val
  val.offset(0, colOffset + 1) = val.offset(0, 1)
  val.offset(0, colOffset + 2) = val.offset(0, 2)
 End if

 Next val
End Sub

!Example

A: edited after OP's further specs
not sure I grasped the logic you need, but try this
Option Explicit
Sub MoveData()
Dim colOffset As Integer, dataCols As Long
Dim datesRng As Range, dateRng As Range, valsRng As Range

With ThisWorkbook.Worksheets("expenses") '<== change it to your actual sheet name
    Set datesRng = .Range("AA2:AA" & .Cells(.rows.Count, "AA").End(xlUp).Row).SpecialCells(xlCellTypeConstants, xlNumbers) 'process rows as long as there's a "Transition Date"

    For Each dateRng In datesRng
        With .Range("K" & dateRng.Row)
            dataCols = WorksheetFunction.CountA(.Resize(, 3))
            Set valsRng = .Offset(, 3 - dataCols).Resize(, dataCols)
        End With

        colOffset = WorksheetFunction.Min(Month(dateRng), Month(Date)) - dataCols 'limit month offset to current one and set it back to the numbers of values
        If colOffset >= 0 Then
            .Range("N" & dateRng.Row).Offset(, colOffset).Resize(, dataCols).Value = valsRng.Value
            .Range("N" & dateRng.Row).Offset(, colOffset).Value = .Range("N" & dateRng.Row).Offset(, colOffset) - .Range("J" & dateRng.Row).Value
        Else
            'some K-L columns data would be overwritten!!
        End If

    Next dateRng
End With

End Sub


text:
Q: int to string without explicit conversion? I have a kind a simple question but I'm surprised.
This code works:
int itemID = 1;
string dirPath = @"C:\" + itemID + @"\abc";

Why don't I have to do itemID.ToString() in this case ?

A: + in string concatenation gets converted into string.Concat call, which internally calls parameterless ToString on each object.
string.Concate Method - MSDN

The method concatenates each object in args by calling the
  parameterless ToString method of that object; it does not add any
  delimiters.

EDIT:
Here is what it looks like in ILSpy

A: The + operator has a number of overloads.  Three of them are as follows:

operator + (string a, string b)
operator + (string a, object b)
operator + (object a, string b)

Your code is using the second overload of the operator.
That operator will, after being determined as a match, convert it to a call to string.Concat, which can take any number of objects (of type object) as its parameters.
Within the definition of string.Concat, it will call ToString on all parameters (after null checking them first) to get their string value, and that is what will be concatted.
Because of all of this, you can always concat any object with a string, and it will compile and execute using that object's ToString method.

A: from MSDN

The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.

Expanding on my answer a bit, based on some comments in other answers...
This process is not merely "Syntactic Sugar" or convenience.  It is a result of a core C# language feature called Operator Overloading.  In the case of the + Operator and the String + Overload, the Overload is provided as a means to abstract the internals of the String Class, which is a core fundamental of good design principles.  The + String Overload provides type safety by ensuring that it never returns a null value, rather returning an empty string for any operand that cannot be converted using the .ToString() method.  However, even custom complex types (not just primitives) can be added to a string, assuming that they have a .ToString() overload, without the implementation of the String type knowing any different.
Operator Overloading is a major language feature that more people should learn to harness the power of.

A: Because it's done automatically by the compiler.
Basically:
  string a = "abc" + 1;

is compiled to:
  string a = string.Concat((object)"abc", (object)1);

It's merely syntactic sugar.
Although I personally would prefer no automatic conversion.
Reference for Concat:
http://msdn.microsoft.com/en-us/library/kbseaaft.aspx

A: This is a language feature. ToString() is called on objects internally when doing string concatenation with the + operator.
The underlying reason for this is mere convenience (and possibly increased readability due to less ToString() calls, but it could also trick you into thinking the object is a string, when in fact it can be anything) for the developer.
For C#, probably Java's behavior was adopted, which is identical. It may be interesting to ask the question why exactly this was introduced in Java in the first place.

A: A very interesting question.
Lets look to IL code of your example:
 ldstr     "C:\\"
 ldloc.0
 box       int
 ldstr     "\\abc"
 call      string System.String.Concat(object, object, object)

The called function in behind is System.String.Concat which take 3 objects!
Lets go deeper in .NET source code:
public static String Concat(Object arg0, Object arg1, Object arg2) {
        Contract.Ensures(Contract.Result<String>() != null);
        Contract.EndContractBlock();

        if (arg0 == null)
        {
            arg0 = String.Empty;
        }

        if (arg1==null) {
            arg1 = String.Empty;
        }

        if (arg2==null) {
            arg2 = String.Empty;
        }
           return Concat(arg0.ToString(), arg1.ToString(), arg2.ToString());
   }

AS YOU SEE THE ToString() it will be called but later!This is very impressive what the Microsoft guys are doing!


text:
Q: How can I tell ubuntu to ignore mouse movements while clicking? I've got a Macbook Air and am trying out ubuntu on it.
One thing that is really annoying is the behavior of the trackpad. Macs have those click-pads, where you have to press down the whole trackpad for a click.
This works, but ubuntu doesn't ignore the movement while clicking. This leads to moving the mouse pointer a few pixels every time I try to click, which is really annoying.
Is there a setting to make ubuntu ignore movement while clicking?


text:
Q: Java TableViewer - change cell image on selection I have followed Vogella's tutorial on Table Viewer and using the StyledCellLabelProvider presented there. It creates a CHECKED or UNCHECKED icon on the third column
    col = createTableViewerColumn(titles[3], bounds[3], 3);
    col.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public String getText(Object element) {
            return null;
        }

        @Override
        public Image getImage(Object element) {
            if (((Person) element).isMarried()) {
                return CHECKED;
            } else {
                return UNCHECKED;
            }
        }
    });
    col.setEditingSupport(new MarriedEditingSupport(viewer));

The column images get painted accordingly when the table is created but how can I change the icon when the user clicks a cell ? (I want to simulate a check box)

A: You can use an EditingSupport class based on CheckboxCellEditor for this:
class MarriedEditingSupport extends EditingSupport
{
  private final CheckboxCellEditor _editor;

  MarriedEditingSupport(TableViewer viewer)
  {
    super(viewer);

    _editor = new CheckboxCellEditor(viewer.getTable());
  }

  @Override
  protected CellEditor getCellEditor(Object element)
  {
    return _editor;
  }

  @Override
  protected boolean canEdit(Object element)
  {
    return true;
  }

  @Override
  protected Object getValue(Object element)
  {
    return Boolean.valueOf(((Person)element).isMarried());
  }

  @Override
  protected void setValue(Object element, Object value)
  {
    ((Person)element).setMarried(((Boolean)value).booleanValue());

    getViewer().update(element, null);
  }
}


text:
Q: Set  value to a non-existent option I've got a select with options. I need to set the default of the dropdown to a value that is not in the dropdown list. The user can then leave it the same or select a value from the options in the select.
How can this be achieved?
Edit:
This is the scenario: I have a set of data that is normalized. This is fed into the select (as options). After rendering, a value is selected by default. However, sometimes, this value (that has to be selected) might not be in the options - so a good UX would be to still have this shown as the selected option, even if it is not in the normalized data. The user can leave it be or select a "correct" option.

A: I assume you mean for a placeholder similar to text inputs.  The only way I know of to do this is to make the selected option disabled; however, it must still be an option in the markup.  e.g.

<select>
    <option disabled="" selected="" value="">Select one of the Options Below</option>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
</select>

You may be better served by making your own javascript powered one.


text:
Q: Loop through posts that is promote How to loop through post that are on promoted. I have a method in my post model that I can access. How would I call it in this instance. For example here are my methods my post model.
class Post < ApplicationRecord
def promoted?
    subscriptions.present?
  end

  def self.promoted_posts
    Post.joins(:subscriptions).where(:subscriptions => {:is_active => true})
  end

  def self.not_promoted_posts
    Post.left_outer_joins(:subscriptions).where(:subscriptions => {:post_id => nil})
  end

  def self.ordered_posts
    Post.promoted_posts + Post.not_promoted_posts
  end
end

Here is my view. I would like to loop through all the posts that are promoted which is the method "def promoted?" in my model
<% @posts.take(6).each do |post| %>

            <%= link_to image_tag(post.images.first, class: 'img-fluid'), post %>

<%= post.category.name %> / <%= post.subcategory.name %>

<%= link_to post.title, post %>

                Ad#: <%= post.ad_number %>

                posted <%= time_ago_in_words(post.created_at) %> ago

                <%= post.state%> , <%= post.city.downcase %>

$<%= post.price%>

              <%= link_to 'Feature Ad', post, class: 'btn-verified float-right', style: 'color: red;' %>

      <% end %>

A: If you are desperately in need of using the promoted, you can try
Post.all.find_all(&:promoted?)

which is short notation of
Post.all.find_all do |post|
    post.promoted?
end

which is kinda n+1 query and opting it while you can just use
Post.joins :subscriptions

is a fail.


text:
Q: C++ recent cast error While maintaining old code that uses libmxl2 I get the following error:
error: invalid static_cast
       from type 'const char [8]'
       to type 'xmlChar* {aka unsigned char*}'

in the following piece of code:
xmlNodePtr messageNode = doc->children; // The "Message" node
if(xmlStrcmp(messageNode->name, static_cast<xmlChar*>("Message"))) ... blabla

(same error happens with reinterpret_cast)
Obviously I can resolve with an old style cast (xmlChar*) but what is the proper way of doing this recently in C++?
I use gcc 4.7.2 (and this code was last time compiled 5 years ago :) without this error, but do not ask the version of the old compiler :) )

A: after some combination of casts this works:
const_cast<xmlChar*>(reinterpret_cast<const xmlChar *>("Message"))

A: Get a newer version of libxml2. The current version of the API has the following signature:
int xmlStrcmp  (const xmlChar * str1,
                const xmlChar * str2)

Which is compatible with your const string literal.
As you're stuck with an older version of libxml2 you'll have to const_cast away the constness of the literal and depend on the library not trying to modify the string that you pass it. You'll also need a reinterpret_cast as "regular" chars are usually signed instead of unsigned, e.g.
xmlStrcmp(messageNode->name, reinterpret_cast<xmlChar*>(const_cast<char*>("Message")))

By the way, the reason that you need a reinterpret_cast instead of a plain old static_cast is because you are casting a pointer type to a pointer type pointing at a differently typed object.

A: As has been stated here a couple of times, you can get the newest version of the lib which is const correct
If that is not an option for any reason, then what you need is a const_cast instead of a static_cast
Your code should look like
if(xmlStrcmp(messageNode->name,
  const_cast<xmlChar*>(reinterpret_cast<const xmlChar *>("Message"))))

You can tell this is the case, by looking at the error message

error: invalid static_cast
         from type 'const char [8]'
         to type 'xmlChar* {aka unsigned char*}'

the only difference between the two incompatible types is the const modifier

A: xmlChar after some research is typedef to unsigned char. Therefore,
A solution is :
    // use the implicit conversion to 'char*' to cast away constness:
    char* message = "Message";

    // explicitly cast to 'unsigned char*'
    unsigned char* in = reinterpret_cast<unsigned char*>(message);
    xmlChar* test = in;

The removal of constness is usually a bad idea since string literals are not modifiable, but sometimes it is necessary when dealing with legacy libraries that are not const-correct.
The conversion from char* to unsigned char* is safe because all objects can be treated as an array of char, unsigned char, or signed char in C++.


text:
Q: Change `div` width with JavaScript when `li` is hovered I want to make a javascript code that make the div width 100% depending on which li my mouse is over. Here is my HTML code:

        Gallary

        Artists

        Videos

        About

And here is my JS code:
var list = document.querySelector('ul'),
    li = document.querySelector('li');

list.onmouseenter = function () {
    'use strict';
    li.onmouseenter = function () {
        'use strict';
        this.children[1].style.width = "100%";
    }
}

list.onmouseleave = function () {
    'use strict';
    li.onmouseleave = function () {
        'use strict';
        this.children[1].style.width = "0";
    }
}

This code works on the first li only. I want it to work on any li in my ul.

A: You can achieve the same behaviour with CSS and skip writing the JavaScript altogether.
https://www.w3schools.com/cssref/sel_hover.asp

A: Firstly, you need to get ALL the

so, you'd use
var allLi = document.querySelectorAll('li');

then, there's no need to have mouseenter/mouseleave functions for the
 as there's nothing to do on mouse enter/leave
So - now all you need to do is apply your mouse enter/leave logic to all the

like:
allLi.forEach(function(li) {
    li.onmouseenter = function() {
        'use strict';
         this.children[1].style.width = "100%";
    }
    li.onmouseleave = function() {
        'use strict';
         this.children[1].style.width = "0";
    }
});

Here's proof the code does "work"

var allLi = document.querySelectorAll('li');
allLi.forEach(function(li) {
    li.onmouseenter = function() {
        'use strict';
         this.children[1].style.width = "100%";
    }
    li.onmouseleave = function() {
        'use strict';
         this.children[1].style.width = "0";
    }
});
div {
background:red;
width:0;
overflow:hidden;
}

        Gallary

DIV

        Artists

DIV

        Videos

DIV

        About

DIV


text:
Q: JavaScript: Extract part of string between two optional characters with Regex I'm working on a regex in javascript for capturing part of the string between two optional characters.
Optional characters are: '=' and '||'
Scenarios:

*

*LENGTH=A simple message||5

*LENGTH=A simple message

*LENGTH||5

For getting the value after '||' I manage that with the split() function.
For getting the 'A simple message' part I manage to extract the string with the regex match(/\=(.*)\|\|/).pop() when both '=' and '||' are in the string.
Any suggestions for extracting the string with one regex when one of the two optional characters is there?
I tried also /(\=)?(.*)(\|\|)?/but is not working.

A: You can use this negative lookahead based regex to capture value from = and optional ||:
/=((?:(?!\|\|).)*)/

RegEx Demo

A: This should probably do what you want:
^LENGTH(?:=([^|]*))?(?:\|\|(\d+))?$

This will match both the part between LENGTH= and || and the part after that. Both will be returned in the result, when present.
Example:
[
    "LENGTH=A simple message||5",
    "LENGTH=A simple message",
    "LENGTH||5"
].forEach(function(string)
{
    var result = string.match(/^LENGTH(?:=([^|]*))?(?:\|\|(\d+))?$/);
    console.log("found:",result[1],result[2]);
});

Of course, there are a few assumptions here regarding the actual format of the data.
Output:
found: A simple message / 5
found: A simple message / undefined
found: undefined / 5


text:
Q: display Rows per page at the top of a table in mui-datatable? I want to display Rows per page count at the top of a table in MUI datatables, as well as at the bottom of the table, which is the default.
How can I do this?
Thanks!


text:
Q: Win'7 UART BlueTooth Goes Silent After Four Thousand Bytes I have a small embedded system which I have rigged up with a debug routine to send the exact same byte over and over to the PC across a bluetooth connection.
The speed in question is 921600 bps
After successfully receiving about four thousand bytes (give or take a few hundred) my app sees no more from Win7
I am totally confident that the bytes (i.e., a whole lot more than four thousand) continue to be sent well after the stream disappears from my app
I am highly suspicious that Windows is somehow, for some reason, not delivering what the bluetooth is receiving.
I can state with total confidence that...

*

*The app does display the first four thousand some-odd bytes properly

*The app Is not displaying anything after that

*The external box continues to send the bytes

My suspicion about Win'7  has been heightened because

*

*My external transmitting box continued after I stopped the app.

*After two minutes, I stopped the external transmitting box

*At that moment, both PC and small box were not interacting

*With both systems stopped, (for several minutes) I restarted the PC app

*With no transmitted bytes, the app received 941 bytes, from where, I don't really know

*Those bytes were from a previous session (I'm sending out the single byte 0x37 over and over again, and that's what I saw in the data stream)

We then started the small box generating data again, and saw the same behavior: 4435 bytes were seen, after which we get no bytes from the UART, despite a two minute flood of bytes at 921600 bps.
Here is the receive thread
 void RecieveThread()
  {
      int n;

      while (continueRecieving)
      {
          n = connectorPort.BytesToRead;

          byte[] bits = new byte[n];

          if (n > 0)
          {
              connectorPort.Read(bits, 0, n);
          }

          Write(bits);
      }
  }

Just in case anyone feels it's important, here is the Write(bits) routine
 public void Write(byte[] b)
 {
     if (writting)
     {
         for (int i = 0; i < b.Length; i++)
         {
             storage[sPlace++] = b[i];

             pass += b[i].ToString("X2") + " ";

             if (sPlace % numericUpDown1.Value == 0)
             {
                 pass += "\r\n";
             }
         }
     }
 }

Has anyone previously experienced disappearing bluetooth bytes on a Win7 machine with a C# app ?
Can anyone see an obvious (or obscure) error which could be causing this ?


text:
Q: Linq To SQL FirstOrDefault fetching all rows I'm making a generic repository and FirstOrDefault is not generating the sql query that I expect.
Below you can see the relevant part. If I for example use ".Find(x => x.Id == id);" on a table using this repo the generated sql is first fetching all the rows and the doing the firstordefault operation. Where as I would have expected it to generate an where clause.
Any ideas about what Im doing wrong?
public class Repo<T> : IRepo<T> where T : class
{
    protected SBContext Context { get; set; }

    public Repo(SBContext context)
    {
        Context = context;
    }

    protected DbSet<T> DbSet
    {
        get
        {
            return Context.Set<T>();
        }
    }

    public T Find(Func<T, bool> predicate)
    {
        return DbSet.FirstOrDefault(predicate);
    }
}

A: Try changing your method signature to
public T Find(Expression<Func<T, Boolean>> predicate)
Explanation:
In System.Linq.Queryable, there is an extension method with this signature:
public static TSource FirstOrDefault<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);
and in System.Linq.Enumerable, there is an extension method with this signature:
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
When you specify that the Find method takes a Func then you are using the Enumerable extensions rather than Queryable extensions.
There is an implicit cast to an IEnumerable<TSource> when you pass the IQueryable Context.Set<T>() to the extension method as the  source parameter and when you cast IQueryable to IEnumerable the expression is immediately evaluated and run against the database, the data is pulled into memory and you are now using Linq-to-Objects
References:
Why would you use Expression<Func<T>> rather than Func<T>?
Re-implementing Linq-To_Objects  - AsEmumerable()


text:
Q: How to know that user touches on which app icon? I am developing an app in which I want to know that which application is opened by the user.
Like If the user opens play store, that I want to know that the play store is opened or user clicked on Play store Icon.

A: use a Service that tracks all of the running application
please refer the post here
Listener when an application is started?


text:
Q: How to batch start background tasks? I have such files:
ls

mate30pro5g.py  Mathematica.py  opencv.py

I know this command can start a background task:
python3 mate30pro5g.py &

Now I want to start multiple tasks by this command:
ls *.py | xargs -n1 -i python3 {} &

But I find I launch only one background task.. What I have missed?

ps: note all my .py file have an endless loop..

A: the issue is & is interpreted by the calling shell , this is not transmit to xargs .
so you must call bash that will execute python3 with you args .
solution:
ls *.py | xargs -n1 -i bash -c 'python3 {} &'

A example :
root@debian:/# ls -1d /etc/rc* | xargs -n1  -i bash -c  'sleep 90 & echo {} '
/etc/rc0.d
/etc/rc1.d
/etc/rc2.d
/etc/rc3.d
/etc/rc4.d
/etc/rc5.d
/etc/rc6.d
/etc/rcS.d
root@debian:/# ps faux | grep sleep
root       494  0.0  0.0   4184   704 pts/0    S    20:54   0:00 sleep 90
root       496  0.0  0.0   4184   672 pts/0    S    20:54   0:00 sleep 90
root       498  0.0  0.0   4184   652 pts/0    S    20:54   0:00 sleep 90
root       500  0.0  0.0   4184   648 pts/0    S    20:54   0:00 sleep 90
root       502  0.0  0.0   4184   672 pts/0    S    20:54   0:00 sleep 90
root       504  0.0  0.0   4184   656 pts/0    S    20:54   0:00 sleep 90
root       506  0.0  0.0   4184   648 pts/0    S    20:54   0:00 sleep 90
root       508  0.0  0.0   4184   684 pts/0    S    20:54   0:00 sleep 90
root       510  0.0  0.0  11108   948 pts/0    S+   20:54   0:00 grep sleep

Another solution because you want to manage all yours process with jobs .
You need create a big string that contains all yours commands and call eval on it .
CMD=$( ls *py | xargs -n1  -i echo ' python3 {} & ' )
eval $CMD

or
eval $( ls *py | xargs -n1  -i echo ' python3 {} & ' )


text:
Q: How to add a pd.Series to a subset of multi-index DataFrame? I have a multi-index dataframe created by:
arrays = [['task_1','task_2', 'task_2'],['accuracy', 'accuracy', 'precision']]
mux = pd.MultiIndex.from_arrays(arrays, names=('task', 'metric'))
data = [[4., 5., 6.], [1., 1., 1.]]
res = pd.DataFrame(data, columns=mux, index=['total', 'counts']).transpose()

>>> res
                   total  counts
task   metric
task_1 accuracy     4.0     1.0
task_2 accuracy     5.0     1.0
       precision    6.0     1.0

Now I want to update the total column of task_2 by adding [0.1, 0.2] to task_2.accuracy and task_2.precision respectively:
update = pd.Series([0.1, 0.2], index=['accuracy', 'precision'])
res.total.task_2 += update

>>> res
                  total  counts
task   metric
task_1 accuracy     4.0     1.0
task_2 accuracy     NaN     1.0
       precision    NaN     1.0

Why I get NaN?
Learning from another question, I also tried two ways attempting to match indices between update and res.total.task_2. However, neither of them worked in my case.
res.total.task_2 += update.values
# -OR-
res.total.task_2 += update.reset_index(drop=True, inplace=True)

A: We have an option of adding on level, which we can use with series.xs to add only on the desired 0th level, then reindex and add:
res['total'] = (res['total'].xs("task_2",drop_level=False)
                .add(update,level=1).reindex(res.index)
                .fillna(res['total']))
print(res)

                  total  counts
task   metric
task_1 accuracy     4.0     1.0
task_2 accuracy     5.1     1.0
       precision    6.2     1.0

A: Seems you need to change res.total.task_2 value by updating all rows
res.total.task_2.iloc[:] = res.total.task_2 + update

Or with pandas.Series.update()
res.total.task_2.update(res.total.task_2 + update)

Or add value one by one
for i in range(len(update)):
    res.total.task_2.iloc[i] += update.iloc[i]

# print(res)

                  total  counts
task   metric
task_1 accuracy     4.0     1.0
task_2 accuracy     5.1     1.0
       precision    6.2     1.0


text:
Q: Ajax call with JSONP failing on Safari I'm making an ajax request to an API that has a different domain name than my site. To make the data accessible across browsers, I am using JSONP, but Safari still blocks it. It works on Chrome however.
I am injecting the response string into an HTML button's text. Am I doing this wrong with JSONP? Do I HAVE to inject JSONP into a script tag for this to work?
Do I have to build a proxy? What are my options client-side? Is there something else that needs to be done on the API server-side?
I have searched SO, but I haven't found any clear answers. I read that actually loading the data into the website in a script tag can be prone to security issues.
Error:
different-domain-api.com&callback=jQuery123456&_=56789000
Failed to load resource: The certificate for this server is invalid. You might be connecting to a server that is pretending to be "different-domain-api.com" which could put your confidential information at risk.

// starting module code:
var myObject = {},
subscribeBtn = $("#subscribe-btn > span");

myObject.priceChangeHandler = function () {
    priceChangeModule.ajaxRequest(params)
    .done( self.successFunc ) // extracting the success callback to another method
    .fail(function (error) {
        console.log("Errors in safari", error);
        return error;
    });
});

myObject.successFunc = function (data) {
    subscribeBtn.text(data.result[0]);
    console.log("Displays data in Chrome correctly", data);
};

// priceChangeModule code:
ajaxRequest: function (params) {
    return $.ajax({
        dataType: 'jsonp',
        url: '//different-domain-api.com',
        type: 'GET',
        timeout: 120000
    });
}

Response:
/**/jQuery123456({data});

Headers:
General:
    Request URL: //different-domain-api.com&callback=jQuery123456&_=56789000

Request Headers:
    Accept:*/*
    Accept-Encoding:gzip, deflate, sdch, br
    Accept-Language:en-US,en;q=0.8
    Host:different-domain-api.com

Response Headers:
    Content-Type:application/javascript;charset=UTF-8


text:
Q: ReQL | RethinkDB error: Expected type TABLE but found SINGLE_SELECTION hello i have this in the data explorer on the webinterface but i have a error
code:
r.db("discordboatsclubv1").table("users").get("355995885085392896").insert({
  "admin":"true"
})

error:
e: Expected type TABLE but found SINGLE_SELECTION:
{
    "badges":   [],
    "createdAt":    1573923739827,
    "discordAT":    "94GXMoWf1Anhn5neKsV2o4nWS9HVFS",
    "discordRT":    "akv9HS1nY9dqP9dfXou8jpNowv2Gw5",
    "id":   "355995885085392896"
} in:
r.db("discordboatsclubv1").table("users").get("355995885085392896").insert({"admin": "true"})
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
screen

A: When you call the .get you are accessing to a single document with that id. From there you can only insert additional element with an update statement:
r.db("discordboatsclubv1").table("users").get("355995885085392896").update({
  "admin":"true"
})


text:
Q: How would you cite a result that it is not quite correct, but whose proof contains some useful ideas There is a paper that was published 15 years ago; one of the theorems in it is wrong in general. A few years ago some people told the author that this theorem is wrong as stated, but yet a partial case of it is true and is quite sufficient for the proof of the main result of the paper. Certainly, it was too late to correct the paper itself; yet its current arxiv version contains a short notice that it should be corrected.
Now, I proved a (new) corrected and extended version of the wrong result mentioned. My method of the proof has benefited significantly from the 'wrong proof'. So, what should I do (in order not to offend the authors of the paper mentioned)? I have the following ideas.

*

*Avoid citing the 'partially wrong' paper. Actually, my result is not something very much unexpected, and the proof is rather short and easy; I could have found it without reading the 'wrong' paper.

*Cite the printed version of the paper, and tell that the result mentioned is wrong as stated? In this situation I definitely would like to say that this result is wrong, since I will not do so nobody will understand why my correction is interesting. As is it is often the case, the wrong result looks nicer than the correct one.:)

*Cite the current arxiv version. The problem is that it contains a notice that a revision is necessary, but no revision is made.

*Ask the author(s) of the paper to put a corrected version of it to the arxiv. In this situation, is it ok to tell the authors that I do not want to cite the printed version of the paper as well as the current arxiv version?
If I choose possibilities 3 and 4, should I explain somehow (in my preprint) why I cite the arxiv version and not the printed one?


text:
Q: When and how to use withSampW in the function get.weights of the Package twang? I am using Twang R package in my analysis but I have doubt as to when and how should I use or not use the function get.weights.
The package documentation here and elsewhere says withSampW: Returns weights with sample weights multiplied in, if they were provided in the original ps or mnps call.
I would appreciate any help to understand what that sentence means in practice and what are the statistical implications in the estimated weights and inferences of setting or not setting withSampW = TRUE.

A: When you estimate propensity score weights to apply to a sample that has sampling weights attached to it, you need to account for the sampling weights in the propensity score estimation and the effect estimation. The way they are accounted for in the effect estimation is by multiplying the estimated propensity score weights by the sampling weights and then using these new multiplied weights in your weighted regression model. get.weights() with withSampW = TRUE returns the product of the propensity score weights and the sampling weights. get.weights() with withSampW = FALSE just returns the propensity score weights, which you must then multiply by the sampling weights before using in effect estimation.


text:
Q: how to solve this mysql query I have 3 mysql tables

*

*user(u_id(p),name),

*team(t_id(p),u_id(f),t_name,t_money,days_money) and

*history(t_id(f),day,d_money).

Now I have to display leaderboard using php.
I tried this.
SELECT t_id FROM team;

got result.
then,
in for loop
foreach($tid_all as $tid)
{
     $que = $db_con->prepare("SELECT d_money, t_name FROM team, history WHERE t_id= '".$tid['t_id']."' && day='1'");

     $que->execute();

        while($info = $que->fetch(PDO::FETCH_NUM))
        {

                  echo "
";
                  echo  "".$info[0]."	";
                  echo  "".$info[1]."	";
                  echo "
";
         }
}

but it didnt work. any solution?
Solution 1:
 i tried this and it worked.
`SELECT d_money, t_name FROM team, history WHERE history.t_id=$tid['t_id'] AND team.t_id=history.t_id`

is it correct way or not?
thanks everyone for help.
Question : is it possible to order the result table by d_money? i want it in descending order.

A: There is no && in MySQL Query. Replace that with AND Operator on your query.

A: Since you want to get the data from the two tables, then JOIN the two tables instead of doing that with a loop:
SELECT
  h.d_money,
  t.t_name
FROM team AS t
INNER JOIN history AS h ON t.t_id = h.t_id;

Run this single query once and you will get what you want. You can also add a WHERE clause at the end of it the way you did in your query.

A: try this
SELECT d_money, t_name FROM team, history WHERE team.t_id= '".$tid['t_id']."' AND history.t_id= '".$tid['t_id']."' && day='1'

A: Replace && with AND.Try like this :
"SELECT d_money, t_name FROM team, history WHERE t_id= '".$tid['t_id']."' AND day='1' order by d_money DESC "

A: Can you replace
 WHERE t_id= '".$tid."' AND day='1'

instead of
 WHERE t_id= '".$tid['t_id']."' && day='1'


text:
Q: Round number to next highest greatest place Im trying to create a function that will return the next highest (for lack of a better term) "round" number, based on the greatest place digit (left most digit).
For example:
 17     >  20
 328    >  400
 18564  >  20000

 //Already round numbers will stay the same:
 500     >  500

I know I can just do something like this:
int customRound(int i)
{
    string s = i.ToString();
    if (int.Parse(s.Substring(1)) > 0)
    {
        string greatestDigit = s.Substring(0, 1);
        string digit = (int.Parse(greatestDigit) + 1).ToString();
        return int.Parse(digit + string.Empty.PadRight(s.Length - 1, '0'));
    }
    return i;
}

But that just feels really hacky and Im sure theres a more elegant and mathematical way to do it.

A: You can use Math.Log10 to determine the order-of-magnitude of the number (previous number that is a power of 10), then round up to the next multiple of it:
int customRound(int i)
{
    var digits = (int)Math.Floor(Math.Log10(i));
    var unit = (int)Math.Pow(10, digits);
    return (int)(Math.Ceiling((double)i / unit) * unit);
}

A: int customRound(int i)
        {
            return (int)(Math.Ceiling(i / Math.Pow(10, i.ToString().Length-1)) * Math.Pow(10, i.ToString().Length - 1));
        }


text:
Q: Protect from adding object to NSMutableArray in public interface I want to protect access to NSMutableArray in public interface
I am trying to do this by defining property as NSArray in public interface and as NSMutableArray in private interface like this:
@interface Order : NSObject
@property (readonly, strong, nonatomic) NSArray* comments;
@end

@interface Order()
@property (readwrite, strong, nonatomic) NSMutableArray* comments;
@end

But this doesn't work - so I have to define property in public interface NSMutableArray instead:
@interface Order
@property (strong, nonatomic) NSMutableArray* comments;
@end

The goal is to provide read-only access to comments for API clients and full access to methods like addObject: in the implementation.
So defining goal more clearer:

*

*Client should have access to property as NSArray without ability to access mutation methods.

*Client should not have ability to update the comments to point to new value.

*The solution must be done without creating extra structures and array copying.

So simply the question was if it's possible to make public definition of property more general (NSArray instead of NSMutableArray).
Is there any other clean way to reach the goal or I have to use NSMutableArray everywhere?
RESOLUTION
After reviewing my original question and answers I realized that I would like to use more generic class NSArray in the public interface and NSMutableArray in the implementation - but it's just not possible for one property. So the answer is not possible.
So I will just use single property with NSMutableArray without any extra desired protection.
But I will also pick the most appropriate answer it might help if you really prefer protection over simplicity and efficiency.

A: One solution would be to declare the property as readonly as an NSArray. Then in your implementation, create a separate, writable property based on NSMutableArray.
In the .h:
@interface Order : NSObject
@property (readonly, strong, nonatomic) NSArray* comments;
@end

In the .m:
@interface Order()
@property (strong, nonatomic) NSMutableArray* internalComments;
@end

Instead of synthesizing the readonly property, write:
- (NSArray *)comments {
    return [self.internalComments copy];
}

In the .m you do everything with self.internalComments.

A: A far cleaner solution, if it's acceptable for your use case, would be to declare the property as an NSArray, while backing it with an NSMutableArray. The client could technically modify the array by simply casting it to a mutable one, but you are making it clear that doing so would be a bad idea.
A @property is simply a wrapper around two methods, a getter and a setter, which are typically backed by a storage variable. The simplest way to implement this solution would be:
@interface Order : NSObject
{
    NSMutableArray *_comments;
}

@property (readonly, strong, nonatomic) NSArray *comments;

- (void)addComment:(Comment *)comment;

@end

@implementation Order
@synthesize comments=_comments; // Can be omitted if you use Xcode 4.4+

- (void)addComment:(Comment *)comment
{
    [_comments addObject:comment];
}

@end

If you want the user to be able to replace the entire array (order.comments = ...), remove the readonly attribute on the property and override the -setComments: method:
- (void)setComments:(NSArray *)array
{
    [_comments release]; // Can be omitted if you are using ARC
    _comments = [array mutableCopy];
}

It's worth noting that since Objective-C is a dynamic language, it's not possible to fully prevent someone from accessing a variable, as you can interface directly with the runtime or call methods by their selector if you really want to poke around in things you're not supposed to. All you can really do is make it clear that doing so is a bad idea.

A: You don't need a public property if all you want is to allow clients to read the array.
Just create an accessor method that returns a copy of your private mutable array:
@interface Order : NSObject
- (NSArray *)allComments;
@end

@implementation Order ()
@property (nonatomic, strong) NSMutableArray * comments;
@end

@implementation Order

@synthesize comments;

- (NSArray *)allComments
{
    return [[self comments] copy];
}

@end

This pattern can be seen in e.g., NSView: constraints and subviews are internally mutable, but only exposed for reading via a single method returning a nonmutable array.

A: Two solutions:

*

*Return a non-mutable copy of the array - client gets all the comments in one go.

*Return the number of comments and individual comments.

Take your pick, there are arguments for both and it depends on what suits you:
@interface Order : NSObject

// solution one - return a copy
@property (readonly, strong, nonatomic) NSArray* comments;

// solution two - return individual comments
@property (readonly) NSUInteger commentCount;
- (id) comment:(NSUInteger)number;

@end

@interface Order()

// internal property - mutable
@property (readwrite, strong, nonatomic) NSMutableArray* privateComments;

@end

@implementation Order

// solution one - return a copy
- (NSArray *) comments            { return [self.privateComments copy]; }

// solution two - return individual comments
- (NSUInteger) commentCount       { return self.privateComents.count; }
- (id) comment:(NSUInteger)number { return self.privateComment[number]; }

@end

A: If you don't want the client to be able to set this property at all, then declare it in the public interface as readonly. If you don't want the client to be able to mutate the array that the client can read, then declare it as NSArray. Meanwhile, on your side you are readwrite and copy. By being readwrite you can take a mutableCopy (which will be an NSMutableArray), make your changes, and then set the property again; by being copy you ensure that the client always sees an NSArray.
So, client:
NSArray* arr = order.comments; // ok
[arr addObject: @"ha"]; // no, can't
order.comments = someOtherArray; // no, can't

Inside Order:
NSMutableArray* marr = self.comments.mutableCopy;
[marr addObject: @"ha"];
self.comments = marr; // and it is magically turned back into an NSArray


text:
Q: How to access x:Name-property in code? I assigned x:Name in my XAML-file to a object which can trigger a MouseDown-event.
In that event I'd like to get the x:name-attribute of the sender again.
How do I do that?
The object looks like that:
<ModelUIElement3D MouseDown="ModelUIElement3D_MouseDown" x:Name="trololo">

A: If I have understood your question correctly, you can access the Name property by casting the sender to a FrameworkElement.
Alternatively you can just use the reference object that is created by the designer, the instance name is the same as the name that you specify in the x:Name attribute.
The following demonstrates both options.
  private void ModelUIElement3D_MouseDown(object sender, MouseButtonEventArgs e)
  {
    var element = sender as FrameworkElement;

    if (element != null)
    {
      if (element.Name == "trololo")
      {
      }
    }

    // Or

    if (sender == trololo)
    {
    }

  }

A: The FrameworkElement-based Name property is a standard dependency property intended as a shortcut for x:Name (see FrameworkElement.Name Property).  However, many dependency objects do not derive from FrameworkElement, and yet they can still use the XAML-attached property x:Name.  To determine the x:Name at runtime of an object declared in XAML that does not derive from FrameworkElement, you can retrieve the object's attached property using GetValue, as shown here:
foreach(var column in gridItem.ColumnDefinitions)
{
    var name = column.GetValue(FrameworkElement.NameProperty) as string;
    if (name == "IsCheckedColumn")
        column.Width = show ? CheckUncheckColumn_VisibleWidth : Column_InvisibleWidth;
    else if (name == "DeleteColumn")
        column.Width = show ? DeleteColumn_VisibleWidth : Column_InvisibleWidth;
}


text:
Q: resizing per storyboard issue swift I am wondering if someone can show me how to write this code so it resizes automatically for different screen sizes. I have 4 storyboards with different screen sizes and just want a way to show the code, if this storyboard then (numbers change) follow this code, else (numbers chafe according to storyboard size) this code.
I already tried resizing by adding to each axis number for example / 568 * size.frame.height after each y and height axis and same for x and width of course, but the code becomes too long and complex to read.
Ideally I'd like an if statement saying if this screen size then it's storyboard 'this' then go to this code..
pianoButtonsWaterDropFrames = [
            cNote: (CGRect(x: 33 , y: 40 , width: 20, height: 35), CGRect(x: 33, y: 360, width: 20, height: 35)),
            dNote: (CGRect(x: 66 , y: 42 , width: 20, height: 35), CGRect(x: 66, y: 360, width: 20, height: 35)),
            eNote: (CGRect(x: 99 , y: 41 , width: 20, height: 35), CGRect(x: 99 , y: 360, width: 20, height: 35)),
            fNote: (CGRect(x: 132, y: 48, width: 20, height: 35), CGRect(x: 132, y: 360, width: 20, height: 35)),
            gNote: (CGRect(x: 165, y: 39, width: 20, height: 35), CGRect(x: 165, y: 360, width: 20, height: 35)),
            aNote: (CGRect(x: 198, y: 57, width: 20, height: 35), CGRect(x: 198, y: 360, width: 20, height: 35)),
            bNote: (CGRect(x: 231, y: 60, width: 20, height: 35), CGRect(x: 231, y: 360, width: 20, height: 35)),
            cFourNote: (CGRect(x: 263, y: 54, width: 20, height: 35), CGRect(x: 263, y: 360, width: 20, height: 35))
        ]

Any help would be appreciated !

A: You can use HAS answer in this question to check, which iPhone your app is running on. Then you can use a switch statement and call different methods:
let modelName = UIDevice.currentDevice().modelName

switch modelName{
    case "iPhone 3G", "iPhone 3GS":
    method1()
    case "iPhone 4", "iPhone 4S":
    method2()
default:
    println("no size found")
}


text:
Q: How to move a group of images at the same time ? D3/SVG I have a few buttons (images) with a rectangle behind them. I wish to be able to drag the rectangle and the group of buttons move with it.
Is it possible to add an attribute to these buttons so that when I move a certain rectangle, only shapes/images with a certain attribute move with it ?


text:
Q: 7z how to avoid extracting subfolders' files I am trying to append a script in my JAVA program to unzip the files in specific folder by 7z. Here come below script. But I found that it will also extract the .zip files in subfolder.
7z e -aoa -ppassword c:\xxx\desktop\fromFolder -oc:\xxx\desktop\toFolder > nul:

What if I want to extract the .zip files located in "fromFolder" only and exclude all files in the subfolders of "fromFolder". Please advice, thanks.


text:
Q: Close specific XMLHttpRequest How to "rebuild" function to close specific XMLHttpRequest? I have defined variable outside function to call xhr.abort(); everywhere I need. Now is possible, with this solution, close last running XMLHttpRequest if running more than one at same time - processes before last running are without control after replace xhr by re-calling _ajax()
var xhr;

function _ajax(data, callback) {
  xhr = new XMLHttpRequest();
  xhr.open('POST', window.location.pathname, true);
  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      callback(this);
    }
  };
  xhr.send(data);
}

/* close fnc */
xhr.abort();

A: You could use xhr as an array and store there all the requests; then you can call abort on any one of them. Like:
var xhr=[];
function _ajax(data, callback) {
    xhr.push(new XMLHpptRequest);
    //etc
}
xhr[0].abort();
xhr.shift(); //get rid of the aborted request


text:
Q: Kuhn-Tucker condition for $\max _{0 \leq x \leq a}f(x)$? In applying Kuhn-Tucker theorem, I encountered a problem of the form $\max_{0 \leq x \leq a}f(x)$. If there is no upper bound for $x$, then the Kuhn-Tucker result gives the first order conditions for the maximization: if $x$ is a maximizer, then $f'(x) \leq 0$ and $xf'(x) = 0$, with the constraint $x \geq 0$, of course. However, I did not see how to work the bound $a$ in here. Need help.

A: The KKT conditions require
$$f^\prime (x) = \mu-\lambda$$
$$ \lambda x = 0 $$
$$ \mu(x-a) = 0 $$
where $\lambda$ and $\mu$ are non-negative KKT multipliers for the constraints $x\ge 0$ and $x \le a$ respectively.
If there were no upper bound $a$ (or, equivalently, if the constraint $x\le a$ did not bind), then the relevant constraints described above reduce to the first-order conditions you state.


text:
Q: How do I create custom headers and send json data using php curl? Using php curl I am trying to connect to an api I have built. I am having trouble creating a custom header with curl well trying to dictate some header information such as Content-Type, Content-Length.
I am also struggling to understand how to properly send (post) a http-body full of json data.
Essentially what I am trying to do is have the header have the Content-Type, Content-Length, some custom fields like $api => "45234523452345", $hashedKey => "32413211234123".
Well sending a payload (an array json encoded or json encoded multidimensional arry) in the http-body.
Here is what I am trying to use right now.
public function mainRequest($url, $apiKey) {

      $payload = array(
        'test' => 'data'
      );

      $jsonPayload = urlencode(json_encode($payload));

      $encyptedKey = $this->dataEncyptor->hashData($apiKey);

      $header = array(
        'Content-Type:'   => 'application/json',
        'Content-Length:' => strlen($jsonPayload),
        'x-public'        => $apiKey,
        'x-hash'          => $encyptedKey
      );

      $fp = fopen(dirname(__FILE__).'/errorlog.txt', 'w');
      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_VERBOSE, true);
      curl_setopt($ch, CURLOPT_STDERR, $fp);
      curl_setopt($ch, CURLOPT_HEADER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       // curl_setopt($ch, CURLOPT_POST, 1);

      $result = curl_exec($ch);
      curl_close($ch);

      return $result;
    }

In my error log I get this:
* About to connect() to local.nslim.ca port 80 (#0)
*   Trying 127.0.0.1...
* connected
* Connected to local.nslim.ca (127.0.0.1) port 80 (#0)
> POST /datacheck HTTP/1.1
Host: local.nslim.ca
Accept: */*
Content-Length: 29
Content-Type: application/x-www-form-urlencoded

* upload completely sent off: 29 out of 29 bytes
< HTTP/1.1 404 Not Found
< Date: Fri, 17 Oct 2014 03:05:43 GMT
< Server: Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/0.9.8za DAV/2 PHP/5.5.3
< X-Powered-By: PHP/5.5.3
< Content-Length: 514
< Content-Type: text/html
<
* Connection #0 to host local.nslim.ca left intact
* Closing connection #0

And outputted to the screen is:
HTTP/1.1 404 Not Found Date: Fri, 17 Oct 2014 03:06:07 GMT Server: Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/0.9.8za DAV/2 PHP/5.5.3 X-Powered-By: PHP/5.5.3 Content-Length: 514 Content-Type: text/html
404 Page Not Found
The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.
Visit the Home Page
Do the cURL setopt's need to be in any particular order?
Thanks for any help!

A: So the obvious question is, do you have the URL correct? 404 doesn't indicate an error on the page, rather that the page isn't there. Should it be datacheck.php?
Also, you are not sending your data as a standard web form so you will want to change the Content-Type header to 'text/json' and retrieve it in your script using php://input.
Edit: see also RAW POST using cURL in PHP


text:
Q: embedding a google form directly into the html of a website I'm looking for a way to take specific fields from a Google Form and input it into an html page.
  <form>
      <input id="email" type="text" placeholder="email address" value="email">
      <button id="submit" type="submit">Submit</button>
  </form>

When I click submit, I want that data to submit to a specific Google form.
Thanks

A: If you want to build your own form, hosted separately from Google, and submit to a Google Form, you need to emulate the Google Form's POST request. First, you need to get the form data that's being sent to Google and then you need to submit it from your own page using AJAX.
To get the form data, open Chrome's Developer tools and click the Network tab. Then submit your Google-hosted form with dummy data. Click on the first item you see in the list - it should say "formResponse". Then you need to copy two things from the data on the right-hand pane: "Request URL" (where your own form will submit) and anything beginning with "entry." in the Form Data section (e.g., "entry.123456").
Next, build a form on your own page, and use AJAX to submit the data to Google. The way I've done it is to use jQuery to hijack the form submission so that your form doesn't try to submit to your own domain:
$('.my-form').on('submit', function() {
  e.preventDefault();
  $.ajax(
    type:"POST"
    url: "https://docs.google.com/forms/d/your-form-id/formResponse"
    data: {
      'entry.12345': $('.your-form-input').val()
    }
  );
}


text:
Q: How to do Python parallel API request processing? I'm writing REST service on Python(Django), and this service should incorporate with another REST service by it's API.
Here some code and time of lines:
connection = statServer("myname", "mypassword")

q1 = connection.getJSONdict("query1") # approximately 15 seconds
q2 = connection.getJSONdict("query2") # approximately 20 seconds
q3 = connection.getJSONdict("query3") # approximately 15 seconds

# my processing approximately 0.01 of second
# merge q1 + q2 + q3

It's clear to me that each request getJSONdict("query") actually do nothing apart from waiting on I/O, so it doesn't consume processor time.
Requests are sequentially, thus I could run them on separate threads. I know allegedly that Python don't provide real threading, but in my case I have waiting on I/O so I can to do something like threading.
I think this it is real often user case for Python, and if you have dealt with something like this task, please help to solve mine.

I have thoughts about Fork/Join framework or better will be ThreadExecutorPull to consume my requests (and for reusing threads) from all requests in my REST service.

A: I have managed to do it by myself.
from multiprocessing.pool import Pool, ThreadPool
# ... others imports

# You can dicede here to use processes or threads,
# if you want threads change Pool() to ThreadPool()
pool = Pool()
connection = statServer("myname", "mypassword")

res = pool.map(connection.getJSONdict, ["query1", "query2", "query3"])
print(res)


text:
Q: Python 'int32' cannot be converted to a MySQL type In Python-MySQL, I have defined a table as follows:
TABLES['clusters'] = (
    "CREATE TABLE `clusters` ("
    "  `pid` int(8) NOT NULL, "
    "  `cluster` int(8), "
    "  `cluster_round` varchar(32), "
    "  PRIMARY KEY (`pid`), "
    "  FOREIGN KEY (`pid`) REFERENCES `persons` (`id`) "
    ") ENGINE=InnoDB")

for name, ddl in TABLES.iteritems():
    self.cursor.execute(ddl)

I now want to add a row as follows:
def set_clustering(self, clustering_dict, cluster_round):
    query = (
        "INSERT INTO clustering "
        "(pid, cluster, cluster_round) "
        "VALUES (%s, %s, %s) "
        "ON DUPLICATE KEY UPDATE cluster = cluster")

    for (pid, cluster) in clustering_dict.iteritems():
        self.cursor.execute(query, (pid, cluster, cluster_round))
    self.cnx.commit()

However, when I run this, I get the following error message:
mysql.connector.errors.ProgrammingError:
Failed processing format-parameters;
Python 'int32' cannot be converted to a MySQL type

Is there an error in my syntax?

A: i had a similar problem. its probably because you're trying to insert numpy int32 and mysql cant support it. you can convert a numpy int to python int by running numpyint.item().
i would recommend checking the type of each variable you're trying to insert (type(foo)) to make sure all the values are of type that mysql can support.

A: This is likely due to one of the sh**ty drivers for mysql. My very opinionated solution. Update to python 3 and use mysqlclient pip install mysqlclient and the problem will be solved! Voila!


text:
Q: How do I install newer or older versions of GCC on Devuan/Debian? Some distributions come with package sets for different versions of GCC, which you can easily install in parallel; others do not. Specifically, in Devuan ASCII / Debian Stretch, there only seem to be GCC 6 packages.
What's the right way to install additional versions of GCC in parallel to v6? Is there a special repository like the Ubuntu-targeted PPAs (e.g. ppa:jonathonf/gcc-7.1)? I'd rather avoid adding apt sources which need updating for newer versions of Debian (e.g. sid).


text:
Q: Decimal to Binary program w/o built in method I am making a decimal to binary program in an entry level AP computer science class. I used the decimal to binary algorithm but the program prints out the reverse of the binary string.
public static void main (String[]args) {

  int n = Integer.parseInt(args[0]);

  while (n>0) {
    if (n%2==0) {   //for even numbers
      System.out.print("0");
      n/=2; //
    }
    else {
      System.out.print("1");
      n--; // for odd numbers
      n/=2;
    }
  }
}

A: If you understand that it's printing it out backwards, then perhaps you can make a simple fix.
Add a String variable and tack on the "1" or "0" in front of that variable, and the result at the end will be your binary result.
Sample code that will work is:
String ans = "";
...
ans = "1" + ans;
OR
ans = "0" + ans;


text:
Q: how to make a radio button validate a text box? I have a button "ADD" on clicking the button it will add a div with two text box with popup calendar and a radio button .
1.The problem is i want to check wheather the text box is blank,if blank it should alert "it cannot be blank" and alert  "enddate should  be greater than start date" if start date > enddate
2.Another problem is i want only the respective radio button to be selected and other must be unselected.
can anyone provide me an example if posible
This the code i have used to add a div and popup calendar
$(document).ready(function () {
$(".datepicker").each(function () {
    $(this).datepicker();
});
$("#btnAddAddress").click(function () {
    $(".container").show();
$(".container").append('

  Start Date  	  <input type="text"  class="datepicker"/>End Date	<input type="text" class="datepicker"/> 	 <input type="radio" />

');

    $(".datepicker").datepicker();
})});

Button

             <input type="button" id="btnAddAddress" name="btnAddAddress" value="Add"  />

Please do see here:http://jsfiddle.net/saranyasaint/ksjn7ko7/

A: Here try this code :
$("#btnAddAddress").click(function () {
    $(".container").show();
    var table = $('.container').find('table').last();
    var inc = validate($(this));

    if (inc) return;

    $(".container").append('

  Start Date  	  <input type="text"  class="datepicker"/>End Date	<input type="text" class="datepicker"/> 	 <input type="radio" />

');

    $(".datepicker").datepicker();

})

$('.container').on('click', '[type=radio]', function () {
    var inc = validate($(this));
    if (inc) {
        $(this).prop('checked', false);
    } else {
        $(this).closest('.container').find('[type=radio]').prop('checked', false);
        $(this).prop('checked', true);
    }
});

function validate(el) {
    var inc = 0,
        arr = [],
        flag = false,
        tableClosest = (el[0].type == "radio") ? $(el).closest('table').find('input') : $('.container').find('table').last().find('input');
    tableClosest.each(function () {
        arr.push($(this).val());
        if ($(this).val() == "") {
            inc++;
        }
    });

    if (inc > 0) {
        alert('Field cant be empty');
        flag = true;
    } else {
        if ((new Date(arr[0]).getTime() > new Date(arr[1]).getTime())) {
            alert('End date must be greater than start date');
            flag = true;
        } else {
            flag = false;
        }
    }
    return flag;
}

DEMO

A: I have left spots where you can inject the validations where to add or not what to do if fails etc.
**edit: Ok I have now added code to block submit if any of the fields are empty and if the checkbox is checked.

$(function(){

$("#btnAddAddress").click(function () {
  //callAllValid();
  $(".container").show();
  $(".container").append('

  Start Date       	  <input type="text"  class="datepicker"/>End Date	<input type="text" class="datepicker"/> 	 <input type="radio" onclick="callValid(this)"/>

');

  $(".datepicker").datepicker();
});

});

function callValid(m){
    var inputs = $(m).closest('tr').find('input[type=text]');
    if(!$(m).is(':checked')){
      return true;
    }
    var valid = true;
    inputs.each(function(){
        if($(this).val()===''){
            alert('Empty');
            valid = false;
            return false;//breaks the each loop
        }
    });
    //do anything with the var valid here
  return valid;
}

function callAllValid(){
  var t = $('table :checked');
  var v = true;
  t.each(function(){
    v = callValid(this);
    if(!v){
      return false;
    }
  });
  return v;
}
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

<form onsubmit="return callAllValid();" action="" method="POST">

    <input type="button" id="btnAddAddress" name="btnAddAddress" value="Add"  /> <input type=submit />

</form>

Cheers
Joy

A: I havent did much regarding the validation.. but i think i have done what you wanted to do...
html

    <input type="button" id="btnAddAddress" name="btnAddAddress" value="Add" />

Javascript
$(document).ready(function () {

    $(".datepicker").each(function () {
        $(this).datepicker();
    });

});

$("#btnAddAddress").click(function () {
    debugger
    $(".container").show();
    $(".container").append('

  Start Date  	  <input type="text"  class="datepicker"/>End Date	<input type="text" class="datepicker"/> 	 <input name="radioGroup" type="radio" />

');

    $(".datepicker").each(function () {

        $(this).datepicker();
    });
})

$('.container').on('click', '[type=radio]', function (e) {

    if ($(e.target).prop("checked")) {
        var table = $(e.target).closest("table")
        var textboxes = $(table).find(".datepicker")

        if ($($(textboxes)[0]).val() == "") {
            alert("StartDate Cannot be empty");

        }
        if ($($(textboxes)[1]).val() == "") {
            alert("EndDate Cannot be empty");

        }

        if (new Date($($(textboxes)[0]).val()) > new Date($($(textboxes)[1]).val())) {
            alert("StartDatemust not be greater than end date");

        }
    }
})

Can you please check the updated fiddle http://jsfiddle.net/ksjn7ko7/5/
well if this helps you please mark as an answer


text:
Q: How to use PrimeNG Dropdown in Angular2 Model-driven form? Need help with PrimeNG dropdown in an Angular2 model-driven form.  The PrimeNG documentation I have found only use template-driven forms.
A sample code for the following would help greatly:

*

*an Angular model-driven form

*the form contains one PrimeNG dropdown and a submit button.

*the dropdown contains 4 cities (Moscow, Istanbul, Berlin, Paris).

*the user is required to change the selected city (to enable the Submit button).

*the dropdown can be programatically "initialized" to show one of the cities in the options list (e.g. Berlin) when the form first opens.

Thanks.

A: To use the model driven form in Angular2 or Angular4 you'll need to change the dropdown to

and instantiate a formGroup on the backend that has the control selectedCity in it like so ...
this.angularObjectForm = this.formBuilder.group({selectedCity: [''])}

A: // template handling
<form id="demoForm" name="demoForm" [ngFormModel]="demoForm" (submit)="demoForm($event, demoForm)"
 method="post" action="" autocomplete="off">

Demo

 Required
<button pButton [disabled]="!selectedCity" type="submit" (click)="onclick()" label="Click"></button>
</form>

// Import the files required
import {Button} from 'primeng/primeng';
import {Dropdown} from 'primeng/primeng';

// class Handling
export class MyModel {

    cities: SelectItem[];

    selectedCity: string;

    constructor() {
        this.cities = [];
        this.cities.push({label:'Moscow', value:'1'});
        this.cities.push({label:'Istanbul', value:'2'});
        this.cities.push({label:'Berlin', value:'3'});
        this.cities.push({label:'Paris', value:'4'});
    }

   public demoForm(event: Event, demoForm: ControlGroup): void {
   event.preventDefault();

   // working area //

  }

}

A: To use Primeng dropdown below is simple explanation:
Install primeng : npm i primeng --save
Then import it to parent module
import { DropdownModule } from 'primeng/primeng';
@NgModule({
  imports: [
    DropdownModule
  ]
});

Add below html code to html file:

These are basic steps to implementation..I found very simple practical explanation here He explained it very well.