text:
Q: ¿Por que no me toma los estilos en CSS, pero si los estilos en linea? Estoy aprendiendo cascada, especificidad, etc... Y me esta surgiendo un problema.
Resulta que estaba practicando lo mas bien, pero de la nada dejo de tomarme los estilos en CSS,pero a la hora de utilizar estilos en linea me los toma con normalidad.
SIGUE >>>>>>
CODIGO HTML:

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="index.css">
    <title>Empezamos con el CSS</title>

PROBADO EL MODELO DE CASCADA

PROBANDO CLASES, PSEUDO-CLASES Y ATRIBUTOS

LOS ID TIENEN MAS JERARQUIA QUE LAS CLASES, PSEUDOCLASES Y ATRIBUTOS

PERO EL ESTILO EN LINEA (STYLE) TIENE MAS JERARQUIA QUE TODOS

 probando estilos css, no entiendo por que no me esta tomando estilos wtf

mi problema surge en la etiqueta p, cuando le doy estilo en CSS no lo toma, en cambio si le agrego estilo en linea, si.
Los estilos en las demás etiquetas las puedo modificar sin problema.
 p{
color: green;
background-color: red;
}

Este seria el codigo CSS:
h1{
    color: red;
    }
    h1{
    color: green;
    }
    h2{
    color: green;
    }
    .tit2{
    color: blue;
    }
    .tit2:hover{
    color: red;
    background-color: green;
    padding: 2px;
    }
    [atributo="colore"]{
    color: grey;
    }
    h3{
    color: green;
    }
    #tit3{
    color: darkviolet;
    }
    .tit-3{
    color: lightskyblue;
    }
     h4{
    color: red;
    }
    #tit4{
    color: steelblue;
    }
    .tit-4{
    color: beige;
    }

A: Tus estilos funcionan correctamente como puedes ver en esta prueba ejecutando todo el código. Asegúrate si estás cargando una hoja de estilos de que los archivos están bien nombrados y las rutas bien en relativo o en absoluto son correctas dentro de tu estructura de carpetas, así como que se están llamando desde el lugar apropiado dentro de tu html.

h1{
    color: red;
    }
h1{
    color: green;
    }
h2{
    color: green;
    }
.tit2{
    color: blue;
    }
.tit2:hover{
    color: red;
    background-color: green;
    padding: 2px;
    }
[atributo="colore"]{
    color: grey;
    }
h3{
    color: green;
    }
#tit3{
    color: darkviolet;
    }
.tit-3{
    color: lightskyblue;
    }
h4{
    color: red;
    }
#tit4{
    color: steelblue;
    }
.tit-4{
    color: beige;
    }
p{
    color: green;
    background-color: red;
    }

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="index.css">
    <title>Empezamos con el CSS</title>

PROBADO EL MODELO DE CASCADA

PROBANDO CLASES, PSEUDO-CLASES Y ATRIBUTOS

LOS ID TIENEN MAS JERARQUIA QUE LAS CLASES, PSEUDOCLASES Y ATRIBUTOS

PERO EL ESTILO EN LINEA (STYLE) TIENE MAS JERARQUIA QUE TODOS

 probando estilos css, no entiendo por que no me esta tomando estilos wtf

Comparto a continuación un enlace a documentación sobre el uso y carga de CSS que creo que podrá resultar de utilidad.


text:
Q: How to change foreground color fo a textbox programmaticallly in Silverlight? I want to change the foreground property of a textbox when it is clicked on. In WPF I could say textBox1.Foreground = Brushes.Black;   But in Silverlight you can't use System.Drawing. Is there any other way to to so?

A: In Silverlight, you can use SolidColorBrush instance as Foreground, for example :
textBox1.Foreground = new SolidColorBrush(Colors.Black);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Put dropdown selection in variable and use in search query I have 2 pages I am working with, index.php and dropdown-display.php. I have a dropdown in index.php that sends the selection to dropdown-display.php and filters my HTML table. I also have a search box, and if a dropdown selection has already been made, I want it to search the already filtered results by using the dropdown value in the query as well.
So how can I incorporate the variable $q below (if a dropdown selection has been made) into my search query?
This is what I currently have...
Index.php:
<?php
if(isset($_POST['search-species'])) {

// variable that brings in search value
    $speciesToSearch = $_POST['SpeciesToSearch'];

// query used to filter results based on search
    $sql = "SELECT *
        FROM Example_Final_Structure
        WHERE [Species] LIKE '%".$speciesToSearch."%'
        ORDER BY [Current-SKU] ASC";

} else {

    $sql = "SELECT *
        FROM Example_Final_Structure
        ORDER BY [Current-SKU] ASC";

}
?>

HTML in index.php:

<form name="myForm" action="">

    <select id="selectsupp" class="supp-name" data-attribute="supp" onchange="showUser(this.value)">
        <option value="" selected disabled>Supplier Name</option>
        <?php foreach($drop->fetchAll() as $dropdown) { ?>
            <option class="sku-<?php echo $dropdown['Supplier-Name'];?>" value="<?php echo $dropdown['Supplier-Name'];?>"><?php echo $dropdown['Supplier-Name'];?></option>
        <?php } ?>
    </select>

</form>

<form method="post" action="index.php">

    <input name="SpeciesToSearch" class="search" type="text" placeholder="Species">

    <button type="submit" class="button" name="search-species" value="Search">Search</button>

</form>

Dropdown-display.php:
<?php
$q = ($_GET['q']); //variable that holds dropdown selection value

$sql="SELECT *
        FROM Example_Final_Structure
        WHERE [Supplier-Name] = '$q'";

?>

A: In your search form you could add a <input type="hidden" id="searchsupp" name="searchsupp" value=""/>
then en your showUser function, inject the value received to the hidden input. document.getElementById("searchsupp").value = str;
Then you can use this value in your search by adding it to your query
"SELECT *
 FROM Example_Final_Structure
 WHERE ".($searchsupp != "" ? "[Supplier-Name] = '".$searchsupp."' AND ")."[Species] LIKE '%".$speciesToSearch."%'
 ORDER BY [Current-SKU] ASC"

Where $searchsupp is the variable you make from the posted data.


text:
Q: Not getting client IP correctly for first time I not getting the correct client IP address for first time. This is my server main code.
server.c:
int  main()
{
    int sockfd, connfd, lisfd, retval;

    struct sockaddr_in servaddr, clntaddr;
    socklen_t client;
    struct packet pckt;
    int clnt_len;
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            perror("socket");
            exit(1);
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(8000);
    retval = bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    if(retval) {
            perror("bind");
    }

    if((lisfd = listen(sockfd, 4)) < 0) {
            perror("listen");
            exit(3);
    }
    clnt_len = sizeof(clnt_len)-1; // clnt_len = sizeof(clnt_len);
    while(1) {
            if((connfd = accept(sockfd, (struct sockaddr *)&clntaddr, &clnt_len)) < 0) {
                    perror("accept");
                    exit(2);
            }
            printf("IP address is: %s\n", inet_ntoa(clntaddr.sin_addr));

            read(connfd, &pckt, sizeof(pckt));
            printf("%s\n", pckt.msg);

    }

}
packet is a structure declared in hdr.h like below.
struct packet {
    char msg[50];
    int cmd;
};

The output is:
IP address is: 255.127.0.0
Hi
IP address is: 127.0.0.1
Hello
IP address is: 127.0.0.1
Good
...

For first time, I'm getting the wrong IP. I don't understand what is going on? How to get correct IP?

A: As explained in the accept(2) man page, clnt_len should be initialized to the available size in the clntaddr before calling accept():
 while(1) {
     clnt_len = sizeof clntaddr;
     if ((connfd = accept(sockfd, (struct sockaddr *)&clntaddr, &clnt_len)) < 0) {
         perror("accept");
         exit(2);
     }

Edited: clnt_len = sizeof(clnt_len)-1; // clnt_len = sizeof(clnt_len); is the problematic line. It sets clnt_len to an invalid value: one less than the length of the socket length variable, when it should be the amount of memory available in clntaddr.
This is less than sizeof (struct sockaddr_in), and therefore clntaddr will not be assigned when accept() returns with the first connection. clnt_len does get assigned to the length of the client address (and yes, it is allowed to be larger than its original value; that just means the clntaddr wasn't large enough; see the man page for details), and therefore on the following connections, clnt_len is the proper size, and you get the address for the second and further connections, only missing the initial connection address.
To fix, add the clnt_len = sizeof clntaddr; line to the beginning of the while (1) lopp body.
Questions?


text:
Q: Wrong logname at login in Ubuntu 21.10 I upgraded my Ubuntu 21.04 to 21.10 yesterday and am running into serious problems after rebooting.
Troubles with graphical drivers (solved)
This is solved, but maybe I broke something by solving this problem ? Ubuntu stuck during boot and the desktop was never showing. I restarted in rescue mode, updated grub to add "nomodeset" and did some reinstallations + reconfigurations :
apt install --reinstall xserver-xorg-video-amdgpu
dpkg-reconfigure gdm3 ubuntu-session xserver-xorg-video-amdgpu
dpkg-reconfigure ubuntu-session xserver-xorg-video-amdgpu
apt reinstall gdm3 gnome-shell yaru-theme-gnome-shell

I then updated grub2 after reboot to make the "nomodeset" permanent.
Identity problem
After finally reaching my desktop, everything first seemed reset to default and my files disappeared from Desktop... until I opened a terminal and saw errors related to filesystem rights on /root/ (?!). After digging a little I came to understand that in bash my HOME environment variable is set to /root, that my LOGNAME is "root"... basically bash thinks that I'm root while system/C programs still recognize me correctly as my actual user. The desktop shown is /root/Desktop and not my user desktop, and so on. My files are still present on disk.
Testing some bash variables :
amael@laptop:~$ echo $LOGNAME
root
amael@laptop:~$ echo $USER
root
amael@laptop:~$ echo $HOME
/root
amael@laptop:~$ echo ~
/root
amael@laptop:~ echo $MAIL
/var/mail/root

Note that the prompt shows the correct username whereas  the default folder when opening the terminal is the wrong : $HOME = /root.
Non-shell commands show the correct username :
amael@laptop:~$ whoami
amael
amael@laptop:~$ logname
amael
amael@laptop:~$ id
uid=1000(amael) gid=136(vboxusers) groupes=136(vboxusers),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),120(lpadmin),131(lxd),132(sambashare),998(docker)

My /etc/passwd file seems unchanged and correct :
amael@laptop:~$ egrep "^root|amael" /etc/passwd
root:x:0:0:root:/root:/bin/bash
amael:x:1000:136:Amael,,,:/home/amael:/bin/bash
amael@laptop:~$

My disks appear mounted in rw mode :
amael@laptop:~$ ls -al /home
total 32
drwxr-xr-x  5 systemd-coredump systemd-coredump  4096 juil. 30  2020 .
drwxr-xr-x 20 root             root              4096 juil. 30  2020 ..
drwxr-xr-x 59 amael            vboxusers         4096 nov.  21 10:15 amael
drwx------  2 root             root             16384 juil. 30  2020 lost+found
amael@laptop:~$ mount | grep mapper
/dev/mapper/vgubuntu-root on / type ext4 (rw,relatime,errors=remount-ro)
/dev/mapper/vgubuntu-home on /home type ext4 (rw,relatime,errors=remount-ro)

What can explain this ? I guess a full reinstallation can solve this but it would be nice not to have to do this.
Thanks for your feedback !

A: @FedonKadifeli was right : my /etc/environment file was somehow filled with many variables that should not be there. Deleting uncommon lines solved my problem !
I compared my file to a live-USB version and also checked here for reference about what should be in this file :  Setting PATH variable in /etc/environment vs .profile
Problem solved.


text:
Q: Dependency Injection is not working on Quartz Job scheduled class I am trying to scheduling a job using Quartz job scheduler in a dropwizard application. In the class which implements Quartz Job interface, am injecting few of my service classes to use it's method. But it is not getting injected, getting null for that object. Someone helps me in this please?
JobManagerImpl class
public class MyJobManagerImpl {

private SchedulerFactory schedulerFactory;
private Scheduler scheduler;
private static final String group = "REFRESH";
private static final Logger logger = LoggerFactory.getLogger(TcConnectionRefreshJobManagerImpl.class);

public MyJobManagerImpl(Properties quartzConfig) {
    try {
        schedulerFactory = new StdSchedulerFactory(quartzConfig);
        scheduler = schedulerFactory.getScheduler();
        scheduler.start();
    } catch (SchedulerException e) {
        logger.error("Error starting scheduler", e);
    }
}

public boolean addJob(String name, int cronHour, int cronMinute) throws SchedulerException {
    JobDetail jobDetail = newJob(TcConnectionRefreshJob.class).withIdentity(name, group)
            .requestRecovery().build();
    String cronString = "0 " + cronMinute+" "+cronHour+" ? * *" ;
    CronTrigger cronTrigger = newTrigger().withIdentity(name, group).withSchedule(cronSchedule(cronString).
            withMisfireHandlingInstructionDoNothing()).build();
    scheduler.scheduleJob(jobDetail, cronTrigger);
    return true;
}

public boolean deleteJob(String name) {
    JobKey jobKey = JobKey.jobKey(name,group);
    TriggerKey triggerKey = TriggerKey.triggerKey(name,group);
    try {
        scheduler.unscheduleJob(triggerKey);
        scheduler.deleteJob(jobKey);
    } catch (SchedulerException e) {
        logger.error("Exception occurred "+e);
        return false;
    }
    return true;
}

ScheduledJob class
public class ScheduledJob implements Job {

public static IMyService myService;

@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    myService.executeAction();

}

@SuppressWarnings("static-access")
@Inject
public void setMyService(IMyService myService) {
    this.myService = myService;
}

MyService implements IMyService and am binding IMyService to MyService implementation in my application class like bind(IMyservice.class).toInstance(new MyService());

A: There's a question in the Featured tab of the quartz-scheduler tag right now, that talks exactly about DI in Quartz jobs.
The only useful answer so far states the following (link introduced by me for your convenience):

As Quartz manages its own threads, classes are not handled by CDI so you can not inject beans in Quartz classes. The aim of the deltaspike module is to allow injecting CDI beans in Quartz Jobs. Internally, deltaspike controls CDI Contexts.


text:
Q: Python - How to slice with multi indexes and conditions in pandas I have a multi dataframe with id and month as indexes

For each id (index 1), I want to be able to slice month (index 2) up until the last non-zero value in columns amount1 or amount2.
Desired output

I've tried slicing all ids but I can't figure out how I'm supposed to slice different chucks for each ids:
df.loc[:,:max(df[df['amount1'] != 0].index)[1]]

A: There might be a more efficient option. But with below code you can achieve what you want:
import pandas as pd

# We create the original dataframe
arrays = [[102,102,102,102,102,102,102,102,103,103,103,103,103,103,103,104,104,104,104,104,104,104,104,104,104],
["11/1/2004","12/1/2004","1/1/2005","2/1/2005","3/1/2005","4/1/2005","5/1/2005","6/1/2005","4/1/2003","5/1/2003","6/1/2003","7/1/2003","8/1/2003","9/1/2003","10/1/2003","8/1/2003","9/1/2003","10/1/2003","11/1/2003","12/1/2003","1/1/2004","2/1/2004","3/1/2004","4/1/2004","5/1/2004"]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['id', 'month'])
amount1 = [0,0,-9100000,0,1444.1,0,0,0,0,0,0,-5.4e7,0,0,0,0,0,0,0,-3.3e7,-4.3e7,0,0,0,0]
amount2 = [1105.900001,0,1037.3,0,0,0,0,0,0,0,0,0,0,0,0,117.4199962,117.315,0,0,107.77771641,105.9499986,0,106.3398808,0,0]
df = pd.DataFrame({"amount1": amount1, "amount2": amount2},index=index)

# We slice the dataframe by ids
df_out_list = list()
for i,id in enumerate(df.index.levels[0]):
    df2 = df.xs((id,))
    df2_nonzeros = df2[(df2['amount1'] != 0) | (df2['amount2'] != 0)]
    df2_result = df2[:df2_nonzeros.tail(1).index[0]]
    N = len(df2_result.index)
    arrays = [[id]*N, df2_result.index]
    tuples_result = list(zip(*arrays))
    index_result = pd.MultiIndex.from_tuples(tuples_result, names=['id', 'month'])
    df_out_list.append(pd.DataFrame({"amount1": list(df2_result["amount1"]),"amount2": list(df2_result["amount2"])},index=index_result))

# We create the output dataframe appending the dataframes by id
for i,df_el in enumerate(df_out_list):
    if i==0:
        df_out = df_el
    else:
        df_out = df_out.append(df_el)

print df
print df_out

Output for such is:


text:
Q: HTML/SVG: Download on click Currently I'm using SVG for some animation and I want that when someone clicks on an image with SVG around it that it will start a download for that image.

  <svg width="100%" height="100%">
      ....
  </svg>

How do I change it so it starts a download on click?

A: Test this

  <svg class="Orange" ... >
    <use xlink:href="buttonB.svg#Root"/>
  </svg>

and check this page > http://tavmjong.free.fr/SVG/BUTTON_TEST/button_test.html

A: When the SVG is wrapped with the anchor, a click event on the SVG will be sent up to the anchor. In this case that will trigger the download.

        <svg width="100%" height="100%">
          ....
        </svg>


text:
Q: Android: Layer drawable loses information I am messing around with creating my own dialog class, but I've run into an interesting issue.  I use a layer-list drawable for the dialog's close button, but for some reason, the shadow layer disappears after the first time I show the dialog.  You can see in the image below:

I really have absolutely no idea what could be causing this.  I've tried debugging, but I wasn't able to find any leads.  Does anyone have any ideas?  My code is below.
TwoColorDialog.java
public class TwoColorDialog extends DialogFragment {
    private static final String TAG = "TwoColorDialog";

    private ViewGroup _root;

    private TextView _textTitle;
    private ImageView _buttonClose;
    private Button _button1;
    private Button _button2;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Dialog dialog = new Dialog(getActivity());
        _root = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.two_color_dialog, null);

        _textTitle   =  (TextView) _root.findViewById(R.id.dialog_title);
        _buttonClose = (ImageView) _root.findViewById(R.id.dialog_close_button);
        _button1     =    (Button) _root.findViewById(R.id.dialog_button1);
        _button2     =    (Button) _root.findViewById(R.id.dialog_button2);

        dialog.requestWindowFeature(STYLE_NO_TITLE);
        View decorView = dialog.getWindow().getDecorView();
        decorView.setBackgroundResource(getResources().getColor(android.R.color.transparent));

        dialog.setContentView(_root);

        _buttonClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
            }
        });
        _button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "Button 1 pressed");
            }
        });
        _button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "Button 2 pressed");
            }
        });

        return dialog;
    }
}

two_color_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout android:id="@+id/dialog_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@drawable/dialog_background">

        <LinearLayout android:id="@+id/dialog_title_spacing"
            android:layout_width="match_parent"
            android:layout_height="24dp"
            android:orientation="horizontal" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal">

            <Button android:id="@+id/dialog_button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="6dp"
                android:background="@drawable/button"
                android:text="Button1" />

            <Button android:id="@+id/dialog_button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="6dp"
                android:background="@drawable/button"
                android:text="Button2" />

        </LinearLayout>

    </LinearLayout>

    <TextView android:id="@+id/dialog_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|top"
        android:layout_marginTop="6dp"
        android:background="@drawable/dialog_title_box"
        android:textAppearance="@android:style/TextAppearance.Large"
        android:text="TITLE" />

    <ImageView android:id="@+id/dialog_close_button"
        android:layout_width="42dp"
        android:layout_height="44dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_gravity="top|right"
        android:src="@drawable/dialog_close_button"/>

</FrameLayout>

dialog_title_box.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#88888888" />
            <corners android:radius="1dp" />
            <padding
                android:left="1dp"
                android:top="0dp"
                android:right="1dp"
                android:bottom="3dp" />
        </shape>
    </item>

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <corners android:radius="1dp" />
            <padding
                android:left="15dp"
                android:top="5dp"
                android:right="15dp"
                android:bottom="5dp" />
        </shape>
    </item>
</layer-list>

dialog_close_button.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="#88888888" />
            <padding
                android:left="1dp"
                android:top="0dp"
                android:right="1dp"
                android:bottom="4dp" />
        </shape>
    </item>

    <item>
        <shape android:shape="oval">
            <solid android:color="@color/white" />
        </shape>
    </item>

    <item android:drawable="@drawable/ic_close" />
</layer-list>

A: Well, I've found the issue.  The problem only shows up when you use the "padding" tag.  I have no idea why, maybe it is a bug.  I was able to work around it by changing my dialog_close_button.xml accordingly:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="#88888888" />
        </shape>
    </item>

    <item
        android:left="1dp"
        android:right="1dp"
        android:bottom="4dp">
        <shape android:shape="oval">
            <solid android:color="@color/white" />
        </shape>
    </item>

    <item
        android:drawable="@drawable/ic_close"
        android:left="1dp"
        android:right="1dp"
        android:bottom="4dp" />
</layer-list>


text:
Q: creating and filling empty dates with zeroes I have  a dataframe df
df=pd.read_csv('https://raw.githubusercontent.com/amanaroratc/hello-world/master/x_restock.csv')
df

I want to fill the missing dates for each Product_ID with restocking_events=0. To start, I have created a date_range dataframe using dfdate=pd.DataFrame({'Date':pd.date_range(simple.Date.min(), simple.Date.max())}) where simple is some master dataframe and min and max dates are '2021-11-13' and '2021-11-30'.

A: Use:
#added parse_dates for datetimes
df=pd.read_csv('https://raw.githubusercontent.com/amanaroratc/hello-world/master/x_restock.csv',
               parse_dates=['Date'])

First solution is for add complete range of datetimes from minimal and maximal datetimes in DataFrame.reindex by MultiIndex.from_product:
mux = pd.MultiIndex.from_product([df['Product_ID'].unique(),
                                  pd.date_range(df.Date.min(), df.Date.max())],
                                 names=['Product_ID','Dates'])

df1 = df.set_index(['Product_ID','Date']).reindex(mux, fill_value=0).reset_index()
print (df1)
      Product_ID      Dates  restocking_events
0        1004746 2021-11-13                  0
1        1004746 2021-11-14                  0
2        1004746 2021-11-15                  0
3        1004746 2021-11-16                  1
4        1004746 2021-11-17                  0
         ...        ...                ...
3379      976460 2021-11-26                  1
3380      976460 2021-11-27                  0
3381      976460 2021-11-28                  0
3382      976460 2021-11-29                  0
3383      976460 2021-11-30                  0

[3384 rows x 3 columns]

Another idea with helper DataFrame:
from  itertools import product

dfdate=pd.DataFrame(product(df['Product_ID'].unique(),
                            pd.date_range(df.Date.min(), df.Date.max())),
                    columns=['Product_ID','Date'])
print (dfdate)
      Product_ID       Date
0        1004746 2021-11-13
1        1004746 2021-11-14
2        1004746 2021-11-15
3        1004746 2021-11-16
4        1004746 2021-11-17
         ...        ...
3379      976460 2021-11-26
3380      976460 2021-11-27
3381      976460 2021-11-28
3382      976460 2021-11-29
3383      976460 2021-11-30

[3384 rows x 2 columns]

df = dfdate.merge(df, how='left').fillna({'restocking_events':0}, downcast='int')
print (df)
      Product_ID       Date  restocking_events
0        1004746 2021-11-13                  0
1        1004746 2021-11-14                  0
2        1004746 2021-11-15                  0
3        1004746 2021-11-16                  1
4        1004746 2021-11-17                  0
         ...        ...                ...
3379      976460 2021-11-26                  1
3380      976460 2021-11-27                  0
3381      976460 2021-11-28                  0
3382      976460 2021-11-29                  0
3383      976460 2021-11-30                  0

[3384 rows x 3 columns]

Or if need consecutive datetimes per groups use DataFrame.asfreq:
df2 = (df.set_index('Date')
         .groupby('Product_ID')['restocking_events']
         .apply(lambda x: x.asfreq('d', fill_value=0))
         .reset_index())
print (df2)
      Product_ID       Date  restocking_events
0         112714 2021-11-15                  1
1         112714 2021-11-16                  1
2         112714 2021-11-17                  0
3         112714 2021-11-18                  1
4         112714 2021-11-19                  0
         ...        ...                ...
2209     3630918 2021-11-25                  0
2210     3630918 2021-11-26                  0
2211     3630918 2021-11-27                  0
2212     3630918 2021-11-28                  0
2213     3630918 2021-11-29                  1

[2214 rows x 3 columns]


text:
Q: When submiting form in codeception acceptance test auth breaks I am writing codecept acceptance test in laravel 4.2 and I am having problem with the following code:
$I->authenticateUserByEmail($I, 'pera@lozac.com');
$I->amOnPage('/admin/offer/create-specijalna-ponuda');
$I->fillField('input[name=offer_name]', 'My Offer');
$I->attachFile('input[name=offer_image]', $I->getSpecPonudaImageSport1());
$I->selectOption('form select[name=offer_brand]', 1);
$I->click('Submit');
//$I->see('Success: Offer My Offer created.');

authenticateUserByEmail() is doing following:
$user = \User::where('email','=',$email)->first();
$I->amLoggedAs($user);

All works fine until submit button is clicked. When that line is present I am receiving following error inside controller that handles this post method:
PHP Fatal error:  Call to a member function hasSupplier() on a non-object

This is a line where the error occurs:
$this->isUserSupplier = Auth::user()->hasSupplier();

If I put this line immediatelly before:
dd(Auth::user()->hasSupplier());

this is printend in the console:
bool(false)

Anyway when this line removed error "PHP Fatal error:  Call to a member function hasSupplier() on a non-object" remains.
I am using Zizaco Entrust  package for role based permissions. Here is my User class:
use Zizaco\Confide\ConfideUser;
use Zizaco\Confide\ConfideUserInterface;
use Zizaco\Entrust\HasRole;
class User extends Eloquent implements ConfideUserInterface
{

    use ConfideUser;
    use HasRole;

    public function supplier(){
        return $this->hasOne('Supplier', 'id', 'supplier_id');
    }

    public function hasSupplier(){
        $supplier = $this->supplier;
        return !is_null($supplier);
    }

}

If I put following line inside controller immediately before error line to check user:
dd(Auth::user());

this is printend into console:
object(User)#13077 (21) {
  ["connection":protected]=>
  NULL
  ["table":protected]=>
  NULL
  ["primaryKey":protected]=>
  string(2) "id"
  ["perPage":protected]=>
  int(15)
  ["incrementing"]=>
  bool(true)
  ["timestamps"]=>
  bool(true)
  ["attributes":protected]=>
  array(18) {
    ["id"]=>
    int(2)
    ["username"]=>
    string(6) "pera"
    ["email"]=>
    string(19) "pera@lozac.com"
    ["password"]=>
    string(60) "$2y$10$zAOANTPOjW7BBA010i3TrexBe23nhEuQnlK0h/Y1m1XVD8kCaEIEC"
    ["first_name"]=>
    string(6) "Pera"
    ["last_name"]=>
    string(9) "Lozac"
    ["phone"]=>
    NULL
    ["address"]=>
    NULL
    ["age"]=>
    NULL
    ["active"]=>
    int(1)
    ["weight"]=>
    int(1000)
    ["notify"]=>
    int(1)
    ["remember_token"]=>
    string(60) "g6S5hjtz7TbEB96DBmBZjaBNTZfmtKaV4zObY3TssDSFxaHnL98myqzfebmU"
    ["confirmation_code"]=>
    string(32) "fd5a00cd497c2bf5be6f4df48fb49719"
    ["confirmed"]=>
    int(0)
    ["created_at"]=>
    string(19) "2016-01-30 13:31:46"
    ["updated_at"]=>
    string(19) "2016-01-30 22:37:19"
    ["supplier_id"]=>
    NULL
  }
  ["original":protected]=>
  array(18) {
    ["id"]=>
    int(2)
    ["username"]=>
    string(6) "pera"
    ["email"]=>
    string(19) "pera@lozac.com"
    ["password"]=>
    string(60) "$2y$10$zAOANTPOjW7BBA010i3TrexBe23nhEuQnlK0h/Y1m1XVD8kCaEIEC"
    ["first_name"]=>
    string(6) "Pera"
    ["last_name"]=>
    string(9) "Lozac"
    ["phone"]=>
    NULL
    ["address"]=>
    NULL
    ["age"]=>
    NULL
    ["active"]=>
    int(1)
    ["weight"]=>
    int(1000)
    ["notify"]=>
    int(1)
    ["remember_token"]=>
    string(60) "g6S5hjtz7TbEB96DBmBZjaBNTZfmtKaV4zObY3TssDSFxaHnL98myqzfebmU"
    ["confirmation_code"]=>
    string(32) "fd5a00cd497c2bf5be6f4df48fb49719"
    ["confirmed"]=>
    int(0)
    ["created_at"]=>
    string(19) "2016-01-30 13:31:46"
    ["updated_at"]=>
    string(19) "2016-01-30 22:37:19"
    ["supplier_id"]=>
    NULL
  }
  ["relations":protected]=>
  array(0) {
  }
  ["hidden":protected]=>
  array(0) {
  }
  ["visible":protected]=>
  array(0) {
  }
  ["appends":protected]=>
  array(0) {
  }
  ["fillable":protected]=>
  array(0) {
  }
  ["guarded":protected]=>
  array(1) {
    [0]=>
    string(1) "*"
  }
  ["dates":protected]=>
  array(0) {
  }
  ["touches":protected]=>
  array(0) {
  }
  ["observables":protected]=>
  array(0) {
  }
  ["with":protected]=>
  array(0) {
  }
  ["morphClass":protected]=>
  NULL
  ["exists"]=>
  bool(true)
  ["errors"]=>
  NULL
}

Form submition breaks something. Any idea how to solve problem?

A: You can't assume the user is logged in,before you call hasSupplier() make sure that Auth::user() didn't return NULL/false
instead of
$this->isUserSupplier = Auth::user()->hasSupplier();
do
$this->isUserSupplier = Auth::check() ? Auth::user()->hasSupplier() : false;
are you sure that the email you check against exists in the database ?
could you dd($user)?


text:
Q: Java executors: how to be notified, without blocking, when a task completes? Say I have a queue full of tasks which I need to submit to an executor service.  I want them processed one at a time.  The simplest way I can think of is to:

*

*Take a task from the queue

*Submit it to the executor

*Call .get on the returned Future and block until a result is available

*Take another task from the queue...

However, I am trying to avoid blocking completely.  If I have 10,000 such queues, which need their tasks processed one at a time, I'll run out of stack space because most of them will be holding on to blocked threads.
What I would like is to submit a task and provide a call-back which is called when the task is complete.  I'll use that call-back notification as a flag to send the next task. (functionaljava and jetlang apparently use such non-blocking algorithms, but I can't understand their code)
How can I do that using JDK's java.util.concurrent, short of writing my own executor service?
(the queue which feeds me these tasks may itself block, but that is an issue to be tackled later)

A: In Java 8 you can use CompletableFuture. Here's an example I had in my code where I'm using it to fetch users from my user service, map them to my view objects and then update my view or show an error dialog (this is a GUI application):
    CompletableFuture.supplyAsync(
            userService::listUsers
    ).thenApply(
            this::mapUsersToUserViews
    ).thenAccept(
            this::updateView
    ).exceptionally(
            throwable -> { showErrorDialogFor(throwable); return null; }
    );

It executes asynchronously. I'm using two private methods: mapUsersToUserViews and updateView.

A: Use a CountDownLatch.
It's from java.util.concurrent and it's exactly the way to wait for several threads to complete execution before continuing.
In order to achieve the callback effect you're looking after, that does require a little additional extra work. Namely, handling this by yourself in a separate thread which uses the CountDownLatch and does wait on it, then goes on about notifying whatever it is you need to notify. There is no native support for callback, or anything similar to that effect.

EDIT: now that I further understand your question, I think you are reaching too far, unnecessarily. If you take a regular SingleThreadExecutor, give it all the tasks, and it will do the queueing natively.

A: Use Guava's listenable future API and add a callback. Cf. from the website :
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture<Explosion> explosion = service.submit(new Callable<Explosion>() {
  public Explosion call() {
    return pushBigRedButton();
  }
});
Futures.addCallback(explosion, new FutureCallback<Explosion>() {
  // we want this handler to run immediately after we push the big red button!
  public void onSuccess(Explosion explosion) {
    walkAwayFrom(explosion);
  }
  public void onFailure(Throwable thrown) {
    battleArchNemesis(); // escaped the explosion!
  }
});

A: If you want to make sure that no tasks will run at the same time then use a SingleThreadedExecutor. The tasks will be processed in the order the are submitted. You don't even need to hold the tasks, just submit them to the exec.

A: Simple code to implement Callback mechanism using ExecutorService
import java.util.concurrent.*;
import java.util.*;

public class CallBackDemo{
    public CallBackDemo(){
        System.out.println("creating service");
        ExecutorService service = Executors.newFixedThreadPool(5);

        try{
            for ( int i=0; i<5; i++){
                Callback callback = new Callback(i+1);
                MyCallable myCallable = new MyCallable((long)i+1,callback);
                Future<Long> future = service.submit(myCallable);
                //System.out.println("future status:"+future.get()+":"+future.isDone());
            }
        }catch(Exception err){
            err.printStackTrace();
        }
        service.shutdown();
    }
    public static void main(String args[]){
        CallBackDemo demo = new CallBackDemo();
    }
}
class MyCallable implements Callable<Long>{
    Long id = 0L;
    Callback callback;
    public MyCallable(Long val,Callback obj){
        this.id = val;
        this.callback = obj;
    }
    public Long call(){
        //Add your business logic
        System.out.println("Callable:"+id+":"+Thread.currentThread().getName());
        callback.callbackMethod();
        return id;
    }
}
class Callback {
    private int i;
    public Callback(int i){
        this.i = i;
    }
    public void callbackMethod(){
        System.out.println("Call back:"+i);
        // Add your business logic
    }
}

output:
creating service
Callable:1:pool-1-thread-1
Call back:1
Callable:3:pool-1-thread-3
Callable:2:pool-1-thread-2
Call back:2
Callable:5:pool-1-thread-5
Call back:5
Call back:3
Callable:4:pool-1-thread-4
Call back:4

Key notes:

*

*If you want process tasks in sequence in FIFO order, replace newFixedThreadPool(5)  with newFixedThreadPool(1)

*If you want to process next task after analysing the result from callback of previous task,just un-comment below line
//System.out.println("future status:"+future.get()+":"+future.isDone());

*You can replace newFixedThreadPool() with one of
Executors.newCachedThreadPool()
Executors.newWorkStealingPool()
ThreadPoolExecutor

depending on your use case.

*If you want to handle callback method asynchronously
a. Pass a shared ExecutorService or  ThreadPoolExecutor to Callable task
b. Convert your Callable method to Callable/Runnable task
c. Push callback task to  ExecutorService or  ThreadPoolExecutor

A: You could extend FutureTask class, and override the done() method, then add the FutureTask object to the ExecutorService, so the done() method will invoke when the FutureTask completed immediately.

A: This is an extension to Pache's answer using Guava's ListenableFuture.
In particular, Futures.transform() returns ListenableFuture so can be used to chain async calls. Futures.addCallback() returns void, so cannot be used for chaining, but is good for handling success/failure on an async completion.
// ListenableFuture1: Open Database
ListenableFuture<Database> database = service.submit(() -> openDatabase());

// ListenableFuture2: Query Database for Cursor rows
ListenableFuture<Cursor> cursor =
    Futures.transform(database, database -> database.query(table, ...));

// ListenableFuture3: Convert Cursor rows to List<Foo>
ListenableFuture<List<Foo>> fooList =
    Futures.transform(cursor, cursor -> cursorToFooList(cursor));

// Final Callback: Handle the success/errors when final future completes
Futures.addCallback(fooList, new FutureCallback<List<Foo>>() {
  public void onSuccess(List<Foo> foos) {
    doSomethingWith(foos);
  }
  public void onFailure(Throwable thrown) {
    log.error(thrown);
  }
});

NOTE: In addition to chaining async tasks, Futures.transform() also allows you to schedule each task on a separate executor (Not shown in this example).

A: Define a callback interface to receive whatever parameters you want to pass along in the completion notification. Then invoke it at the end of the task.
You could even write a general wrapper for Runnable tasks, and submit these to ExecutorService. Or, see below for a mechanism built into Java 8.
class CallbackTask implements Runnable {

  private final Runnable task;

  private final Callback callback;

  CallbackTask(Runnable task, Callback callback) {
    this.task = task;
    this.callback = callback;
  }

  public void run() {
    task.run();
    callback.complete();
  }

}

With CompletableFuture, Java 8 included a more elaborate means to compose pipelines where processes can be completed asynchronously and conditionally. Here's a contrived but complete example of notification.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class GetTaskNotificationWithoutBlocking {

  public static void main(String... argv) throws Exception {
    ExampleService svc = new ExampleService();
    GetTaskNotificationWithoutBlocking listener = new GetTaskNotificationWithoutBlocking();
    CompletableFuture<String> f = CompletableFuture.supplyAsync(svc::work);
    f.thenAccept(listener::notify);
    System.out.println("Exiting main()");
  }

  void notify(String msg) {
    System.out.println("Received message: " + msg);
  }

}

class ExampleService {

  String work() {
    sleep(7000, TimeUnit.MILLISECONDS); /* Pretend to be busy... */
    char[] str = new char[5];
    ThreadLocalRandom current = ThreadLocalRandom.current();
    for (int idx = 0; idx < str.length; ++idx)
      str[idx] = (char) ('A' + current.nextInt(26));
    String msg = new String(str);
    System.out.println("Generated message: " + msg);
    return msg;
  }

  public static void sleep(long average, TimeUnit unit) {
    String name = Thread.currentThread().getName();
    long timeout = Math.min(exponential(average), Math.multiplyExact(10, average));
    System.out.printf("%s sleeping %d %s...%n", name, timeout, unit);
    try {
      unit.sleep(timeout);
      System.out.println(name + " awoke.");
    } catch (InterruptedException abort) {
      Thread.currentThread().interrupt();
      System.out.println(name + " interrupted.");
    }
  }

  public static long exponential(long avg) {
    return (long) (avg * -Math.log(1 - ThreadLocalRandom.current().nextDouble()));
  }

}

A: ThreadPoolExecutor also has beforeExecute and afterExecute hook methods that you can override and make use of. Here is the description from ThreadPoolExecutor's Javadocs.

Hook methods
This class provides protected overridable beforeExecute(java.lang.Thread, java.lang.Runnable) and afterExecute(java.lang.Runnable, java.lang.Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.

A: Just to add to Matt's answer, which helped, here is a more fleshed-out example to show the use of a callback.
private static Primes primes = new Primes();

public static void main(String[] args) throws InterruptedException {
    getPrimeAsync((p) ->
        System.out.println("onPrimeListener; p=" + p));

    System.out.println("Adios mi amigito");
}
public interface OnPrimeListener {
    void onPrime(int prime);
}
public static void getPrimeAsync(OnPrimeListener listener) {
    CompletableFuture.supplyAsync(primes::getNextPrime)
        .thenApply((prime) -> {
            System.out.println("getPrimeAsync(); prime=" + prime);
            if (listener != null) {
                listener.onPrime(prime);
            }
            return prime;
        });
}

The output is:
    getPrimeAsync(); prime=241
    onPrimeListener; p=241
    Adios mi amigito

A: You may use a implementation of Callable such that
public class MyAsyncCallable<V> implements Callable<V> {

    CallbackInterface ci;

    public MyAsyncCallable(CallbackInterface ci) {
        this.ci = ci;
    }

    public V call() throws Exception {

        System.out.println("Call of MyCallable invoked");
        System.out.println("Result = " + this.ci.doSomething(10, 20));
        return (V) "Good job";
    }
}

where CallbackInterface is something very basic like
public interface CallbackInterface {
    public int doSomething(int a, int b);
}

and now the main class will look like this
ExecutorService ex = Executors.newFixedThreadPool(2);

MyAsyncCallable<String> mac = new MyAsyncCallable<String>((a, b) -> a + b);
ex.submit(mac);

A: You can implement future tasks in java executors that returns the callback on the completion of the tasks.

*

*Use callable for tasks instead of runnable

*Can perform non related tasks when execution of threads are in progress asynchronously

*Multiple tasks can be executed and can get result of each one

Follwoing is the class that returns random integer values from a task and printed on main thread
public class ExecutorCallable {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //fix number of threads
        //blocking queue-thread safe
        ExecutorService service = Executors.newFixedThreadPool(100);

        //submit the tasks for execution
        Future<Integer> result = service.submit(new Task());

        //*** perform some unrelated operations

        System.out.println("Result of submitted task is : " + result.get());//blocks until the future is ready after completion

        System.out.println("Thread name " + Thread.currentThread().getName());
    }

    static class Task implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            return new Random().nextInt();
        }
    }
 }

The Output is:
Result of submitted task is : 16645418
Thread name main


text:
Q: Python Regex to parse email URLs but excluding the public email I am parsing a file that have entries like:
xxx-yy.biz.  39405   A   156.154.66.33
mail.global.com.   3464    A   115.113.9.64
xyx xyx xyx
webmail.xyz.com.  1463    A   115.113.9.64
gmail.com.   3464    A   115.113.9.22

I am trying to extact the URL and its IP address with string "mail" in it:
for line in (dnsfile):
            match = re.search(r'(.*mail.*?)\s+(.*)\s+A\s+(.*)', line)

and match.group(1) and match.group(2) is giving me URL and IP.
I want to extent this search so that I don't want to parse public emails like: gmail, hotmail, yahoo,mail. More general : exclude a list of words in this
search.

A: You can use a negative look ahead, but you need to add the start and end anchors so you need re.DOTALL flags too (make the anchors to match from start and end of each line), you can create your negative look-ahead with joining the list of words with | :
re.search(r'^(?!{})(.*mail.*?)\s+(.*)\s+A\s+(.*)$'.format('|'.join(list_of_domin)),line,re.DOTALL)

See demo https://regex101.com/r/bF5xQ3/1

A: If it's not a requirement to have it as part of the regexp you could do a simple array search
nothanks = ['gmail.com', 'hotmail.com']
for line in (dnsfile):
    match = re.search(r'(.*mail.*?)\.\s+(.*)\s+A\s+(.*)', line)
    if match:
        if not match.group(1) in nothanks:
            print match.group(1)


text:
Q: Why Manjaro in VirtualBox should be installed again and again? I downloaded Manjaro 20.0.1 and installed it in the VirtualBox.
After I restart it, it seems had rollback and will start at the beginning. Again, "Install XXX" showed on the desktop.
I didn't remove CD/DVD device from VirtualBox after install it, if do so, it failed due to can't read file from CD/DVD.


text:
Q: Cómo ordenar lista de objetos de una clase de creación propia necesito ordenar una lista de objetos definidos por mí mismo.
El objeto es:
class Jugador():

def __init__(self,nombre,puntaje):
    self.nombre = nombre
    self.puntuacion = puntaje

Y el método ordenar debería simular un insertar ordenado de un array. Eso lo hice. Intenté después implementar el sorted, pero necesita una clave de ordenamiento. Entiendo que es puntacion.. la cuestión es que estoy trabado
def agregar(self,jug):
    '''
    Recibe un jugador y evalúa si su puntuación es mayor a las guardadas. Produce el desplazamiento y elimina a la posición 11
    '''
    self.puntajes.append(jug)
    sorted (self.puntajes, key=jug.puntuacion)
    self.puntajes.reverse()
    self.puntajes.pop()

Debería recibir a jug que es de tipo Jugador. Insertarlo en la lista. Ordenar de mayor a menor (bajo el criterio de puntuacion) y eliminar el último elemento.
Es python 3.6

A: Primero, sorted no realiza el ordenamiento in-place, genera una nueva lista ordenada a partir del iterable pasado como argumento y la retorna (en tu ejemplo no capturas el retorno de sorted por lo que es como si nada hicieras). Si quieres hacerlo in-place debes usar list.sort.
En vez de invertir la lista puedes eliminar el primer item de la misma (self.puntajes.pop(0) o del self.puntajes[0]) o directamente usar el argumento reverse=True de sorted/list.sort.
Luego, a key le pasas siempre el mismo objeto, el valor del atributo puntuación de la instancia jug.  El argumento key de sorted/list.sort espera un objeto "llamable" , luego pasa cada item de la lista a dicho objeto y usa el retorno para ordenar.
Usar una función lambda
self.puntajes.sort(key=lambda jugador: jugador.puntuacion)

Usar operator.attrgetter
self.puntajes.sort(key=operator.attrgetter("puntuacion")

Es más eficiente que la función.
Implementar el orden directamente en la clase Jugador
Ésto se hace implementando los conocidos como "rich comparison methods" del modelo de datos de Python. No necesitas implementarlos todos para que funcione, pero es buena práctica hacerlo, en éste caso solo implementaré __eq__ (operador ==) y __lt__ (operador <) y el resto se los dejo a functools.total_ordering.
from functools import total_ordering

@total_ordering
class Jugador:

    def __init__(self, nombre, puntaje):
        self.nombre = nombre
        self.puntuacion = puntaje

    def __eq__(self, other):
        return self.puntuacion == other.puntuacion

    def __lt__(self, other):
        return self.puntuacion < other.puntuacion

    def __repr__(self):
        return (f"{self.__class__.__name__}"
                f"({repr(self.nombre)}, {repr(self.puntuacion)})")

Luego simplemente:
self.puntajes.sort()

Por ejemplo:

>>> puntajes = [
        Jugador("a", 15),
        Jugador("b", 145),
        Jugador("c", 10),
        Jugador("d", 15)
        ]

>>> puntajes
[Jugador('a', 15), Jugador('b', 145), Jugador('c', 10), Jugador('d', 15)]

>>> puntajes.sort()
>>> puntajes
[Jugador('c', 10), Jugador('a', 15), Jugador('d', 15), Jugador('b', 145)]

>>> puntajes.sort(reverse=True)
>>> puntajes
[Jugador('b', 145), Jugador('a', 15), Jugador('d', 15), Jugador('c', 10)]

A: Ésta no puede ser tenida por respuesta, ya que requiere una versión de python 3.7 o superior. Pero puede servir por si alguien vé esta pregunta en el futuro.
A partir de la versión 3.7 de python existen las dataclasses que hacen más sencillo el manejo de estructura de datos de este tipo. Completando la respuesta que ha dado @FJSevilla, con dataclasses se crean automáticamente algunos de los métodos necesarios para hacer comparaciones y ordenaciones.
De este modo, el problema se podría codificar así:
from dataclasses import dataclass
from functools import total_ordering

@total_ordering
@dataclass
class Jugador:

    nombre: str
    puntuacion: int

    def __lt__(self, other):
        return self.puntuacion < other.puntuacion

Por defecto, la clase de datos Jugador tendrá creados los métodos __init__, __repr__ y __eq__. Se puede pedir que dataclass cree el resto de métodos de ordenación, pero el orden seguiría el orden en que hemos definido los campos: primero por nombre y luego por puntuación.
Como queremos que ordene por puntuación, aplicamos la misma estrategia que en la respuesta de @FJSevilla: usar el decorador total_ordering para que genere el resto de métodos a partir de __eq__, creado por dataclass, y __lt__, que hemos creado nosotros.
Podemos comprobar su funcionamiento:
>>> puntaje = [Jugador("a",15),Jugador("b",145),Jugador("c",10),Jugador("d",15)]
[Jugador(nombre='a', puntuacion=15),
 Jugador(nombre='b', puntuacion=145),
 Jugador(nombre='c', puntuacion=10),
 Jugador(nombre='d', puntuacion=15)]

>>> sorted(puntaje)
[Jugador(nombre='c', puntuacion=10),
 Jugador(nombre='a', puntuacion=15),
 Jugador(nombre='d', puntuacion=15),
 Jugador(nombre='b', puntuacion=145)]

>>> sorted(puntaje, reverse=True)
[Jugador(nombre='b', puntuacion=145),
 Jugador(nombre='a', puntuacion=15),
 Jugador(nombre='d', puntuacion=15),
 Jugador(nombre='c', puntuacion=10)]


text:
Q: Encoder error while trying to map dataframe row to updated row When I m trying to do the same thing in my code  as mentioned below
dataframe.map(row => {
  val row1 = row.getAs[String](1)
  val make = if (row1.toLowerCase == "tesla") "S" else row1
  Row(row(0),make,row(2))
})

I have taken the above reference from here:
Scala: How can I replace value in Dataframs using scala
But I am getting encoder error as

Unable to find encoder for type stored in a Dataset.  Primitive types
  (Int, S tring, etc) and Product types (case classes) are supported by
  importing spark.im plicits._  Support for serializing other types will
  be added in future releases.

Note: I am using spark 2.0!

A: There is nothing unexpected here. You're trying to use code which has been written with Spark 1.x and is no longer supported in Spark 2.0:

*

*in 1.x DataFrame.map is ((Row) ⇒ T)(ClassTag[T]) ⇒ RDD[T]

*in 2.x Dataset[Row].map is ((Row) ⇒ T)(Encoder[T]) ⇒ Dataset[T]
To be honest it didn't make much sense in 1.x either. Independent of version you can simply use DataFrame API:
import org.apache.spark.sql.functions.{when, lower}

val df = Seq(
  (2012, "Tesla", "S"), (1997, "Ford", "E350"),
  (2015, "Chevy", "Volt")
).toDF("year", "make", "model")

df.withColumn("make", when(lower($"make") === "tesla", "S").otherwise($"make"))

If you really want to use map you should use statically typed Dataset:
import spark.implicits._

case class Record(year: Int, make: String, model: String)

df.as[Record].map {
  case tesla if tesla.make.toLowerCase == "tesla" => tesla.copy(make = "S")
  case rec => rec
}

or at least return an object which will have implicit encoder:
df.map {
  case Row(year: Int, make: String, model: String) =>
    (year, if(make.toLowerCase == "tesla") "S" else make, model)
}

Finally if for some completely crazy reason you really want to map over Dataset[Row] you have to provide required encoder:
import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row

// Yup, it would be possible to reuse df.schema here
val schema = StructType(Seq(
  StructField("year", IntegerType),
  StructField("make", StringType),
  StructField("model", StringType)
))

val encoder = RowEncoder(schema)

df.map {
  case Row(year, make: String, model) if make.toLowerCase == "tesla" =>
    Row(year, "S", model)
  case row => row
} (encoder)

A: For scenario where dataframe schema is known in advance answer given by @zero323 is the solution
but for scenario with dynamic schema / or passing multiple dataframe to a generic function:
Following code has worked for us while migrating from 1.6.1 from 2.2.0
import org.apache.spark.sql.Row

val df = Seq(
   (2012, "Tesla", "S"), (1997, "Ford", "E350"),
   (2015, "Chevy", "Volt")
 ).toDF("year", "make", "model")

val data = df.rdd.map(row => {
  val row1 = row.getAs[String](1)
  val make = if (row1.toLowerCase == "tesla") "S" else row1
  Row(row(0),make,row(2))
})

this code executes on both the versions of spark.
disadvantage : optimization provided
by spark on dataframe/datasets api wont be applied.

A: Just to add a few other important-to-know points in order to well understand the other answers (especially the final point of @zero323's answer about map over Dataset[Row]):

*

*First of all, Dataframe.map gives you a Dataset (more specifically, Dataset[T], rather than Dataset[Row])!

*And Dataset[T] always requires an encoder, that's what this sentence "Dataset[Row].map is ((Row) ⇒ T)(Encoder[T]) ⇒ Dataset[T]" means.

*There are indeed lots of encoders predefined already by Spark (which can be imported by doing import spark.implicits._), but still the list would not be able to cover many domain specific types that developers may create, in which case you need to create encoders yourself.

*In the specific example on this page, df.map returns a Row type for Dataset, and hang on a minute, Row type is not within the list of types that have encoders predefined by Spark, hence you are going to create one on your own.

*And I admit that creating an encoder for Row type is a bit different than the approach described in the above link, and you have to use RowEncoder which takes StructType as param describing type of a row, like what @zero323 provides above:

// this describes the internal type of a row
val schema = StructType(Seq(StructField("year", IntegerType), StructField("make", StringType), StructField("model", StringType)))

// and this completes the creation of encoder
// for the type `Row` with internal schema described above
val encoder = RowEncoder(schema)

A: In my case of spark 2.4.4 version, I had to import implicits. This is a general answer
val spark2 = spark
import spark2.implicits._

val data = df.rdd.map(row => my_func(row))

where my_func did some operation.


text:
Q: Close a figure - PyCharm I have spent over an hour searching, just to figure this simple thing. So, before considering this a duplicate question, please compare my question to any question out there.
This is my code:
import pandas
import matplotlib.pyplot as plt

dataset = pandas.read_csv('international-airline-passengers.csv', usecols=[1], engine='python', skipfooter=1)
print dataset, type(dataset)
plt.plot(dataset)
plt.show()
plt.close()

Firstly, plt.show() to my understanding is a blocking function. So what is the way to close the figure. There is no point in writing plt.close() after it. So where is the right way to put it.
Secondly, how can I make sure all the windows are closed when I execute a new process of the same python code. For example in MATLAB, one could easily say close all in the beginning of their file and it closes all the opened plots which were the result of previous MATLAB code execution. plt.close('all') is not working either.
I am using PyCharm. The results I found for the first situation, might work on IDLE but not in the PyCharm. How can I do it PyCharm.

A: plt.show(block=False) will do the trick- This is the way you can make this function non-blocking (both in run & debug mode). The main dis-advantage is that if the code ends, the figure is automatically closes...

A: I had the same problem.
I fix it making the python file in Pycharm to run in only one console. Go to: run---Edit configuration-- check that "single instance only" is activated

A: There are two ways to run matplotlib, non-interactive and interactive.  In non-interactive mode, the default, you are right that plt.show() is blocking.  In this case, calling plt.close() is pointless, the code won't stop as long as the figure is open.  In interactive mode, however (which can be triggers by plt.ion()), this code will open then immediately close the figure.  You would need to put something to wait for user input if you run code like this in a script.  Interactive mode, as the name implies, is designed more for running interactively rather than in a script.
As for closing figures from multiple runs of a python script, this isn't possible.  If you open multiple instances of MATLAB, close all in one instance won't close the figures in another instance.  Running multiple processes of the same python code is the same as opening multiple instances of MATLAB, one run has no knowledge of the others.


text:
Q: How to use centos:8 docker image run postgresql client? In a centos 8 Dockerfile
FROM centos:8

RUN yum update -y && yum install -y openssh-server sudo && yum clean all
RUN rm -rf /run/nologin

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

After start it, install postgresql client in the container
docker exec -it centos8 /bin/bash

dnf module enable postgresql:12
dnf install postgresql-server
postgresql-setup --initdb

Got an error
[root@centos8 /]# postgresql-setup --initdb
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down
FATAL: no db datadir (PGDATA) configured for 'postgresql.service' unit

Check status
[root@centos8 /]# systemctl status postgresql
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down

When run psql
[root@centos8 /]# psql
psql: error: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Why can't use systemctl service? How to install a Postgres client on it?

A: Systemd not supported in docker container. So if you want to start postgresql server service, you will have to start it directly by execute the postgresql binary, just like how official do, also refers to its Dockerfile:
exec gosu postgres "$BASH_SOURCE" "$@"

But, you mentioned next:

How to install a Postgres client on it?

So, if you just want to install postgres client, you have already made it done: psql is the postgres client, no need to  start postgresql server:
[root@4234406b3e6c /]# psql --help
psql is the PostgreSQL interactive terminal.


text:
Q: Haskell generic type parameters resolver tool or method Let's look at these functions' types for example:
:t traverse
traverse
  :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b)

:t id
id :: a -> a

They have no concrete types, but have generic type parameters:
a, f, b, t  (correct me if they called not generic type parameters please)
If I combine id and traverse together in this way,
:t traverse id [Just 1, Just 2, Nothing]
traverse id [Just 1, Just 2, Nothing] :: Num b => Maybe [b]

Haskell can now bind some concrete types for the type variables a, f, b, t.
t = []
a = Maybe bb
f = Maybe
b = Num bb => bb

Below I infer the types and mappings to parameters by hand, is there any way or tool in Haskell to do this automatically, so that it takes some composed parts (id and traverse) in an example, extracts their type signatures in general, and on output produces a mapping from generic type parameters names to concrete inferred types?
See also the first example here: https://wiki.haskell.org/Type_inference
for expression "map ord" on how Haskell finds bindings of actual types to names.
So when we look at functions separately we only have names a, f, b, t. But then we combine the functions and provide some extra information like [Just 1, Just 2, Nothing], and the names a, f, b, t are mapped to concrete types.
I want to catch and show this mapping automatically.

A: I think f and t are more generic type constructor parameters, as they act on a type to give you a type (they kind is * -> *, where * means "a concrete type").
traverse id is not composition, it is function application, as you are passing id as an argument to traverse. this . that is function composition between this and that, in the mathematical sense, where you create a function that gives its (first) argument as an input to that and feeds the result of this application to this.
You refer to the example in this page, where given this
map :: (a -> b) -> [a] -> [b]
Char.ord :: (Char -> Int)

the compiler is able to deduce that the type of map ord is [Char] -> [Int], as you can check yourself by writing :t map ord at the command line.
If you expect a similar output with concerete types when you type :t traverse id, you won't get it, for the simple reason that traverse id is still a polymorphic function, both in its concrete type arguments and type constructor arguments.
Just to give a slightly different example, if you type :t traverse (:[]), where (:[]) has type a -> [a], which is a particular case of the (Applicative f) => a -> f b that traverse expects, you get this output,
traverse (:[]) :: Traversable t => t b -> [t b]

which, compared with :t traverse,
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)

tells you that traverse, in traverse (:[]), has been "instantiated" with f === [] and a === b.


text:
Q: Finding coefficients where part of the coefficient may appear in the terms A minimal example is given below. My goal is that given a algebraic expression such as:
expr = a^2 + a b + a^3 b + 2 a^2 b^2 + a b^3

I'm trying to find a command, that I will call CoefficientFactor that can take an expression and argument and factor out that argument wherever possible to the highest order. For example:
CoefficientFactor[expr, (a+b)]
> a (a + b) + a b (a + b)^2

Where essentially a+b are acting as if they were powers of x:
$$      a (a + b) + a b (a + b)^2 \iff      a x + (a b) x^2$$
As far as I can tell the functions; Factor, Coefficient, CoefficientList. Do not quite acheive this goal.
Sorry if this is a minor oversight on my part.

A: This is not a problem of coding, but a problem of computation. Please try the following code:
f[x1_, x2_, x3_] := Module[{tmp1, z},
    tmp1 = CoefficientList[PolynomialReduce[x1, {x2 - z}, x3][[-1]], z];
    MapThread[#1*x2^#2 &, {tmp1, Range[0, Length[tmp1] - 1]}] // Total
   ]

tmp1 = f[exp, a + b, {a, b}]
(* -(b*(a + b)) + b*(a + b)^3 + (a + b)^2*(1 - b^2) *)

tmp1 - exp // Simplify
(* 0 *)

A: The following simple code, while not checked for robustness, works on the OP's examples:
expr = a^2 + a b + a^3 b + 2 a^2 b^2 + a b^3;
Collect[Simplify[expr, a + b == q], q, Factor] /. q -> a + b
(* a (a + b) + a b (a + b)^2 *)

This combines the insight by Bill in a comment to the OP with the use of one of my most-used (when doing symbolic algebraic manipulations) Mathematica functions Collect.

An alternative version of this removes all instances of a and replaces the with a - b, which might better under some circumstances:
Collect[expr /. a -> aPb - b, aPb] /. aPb -> a - b
(* -(a - b) b + (a - b)^3 b + (a - b)^2 (1 - b^2) *)

This is also a "nice" simplified expression, and might be more useful in certain contexts.


text:
Q: Laurent expansion of $\sin(z)^{-2y}$ at $z=0$ I have tried a lot to generalize this thread: Laurent series of $\frac1{\sin^2z}$ around 0 but I am not able to compute the coefficients of the principal part (that is what I am interested in). Help would be appreciated.
PS: this is no homework problem


text:
Q: How to get maximum width of multiline TextView in android? I am new in android and facing the problem to get the maximum width of the multiline TextView.
I used textview.getWidth() and textview.getMeasuredWidth() but both gives garbage value.
I used also textview.length(), but retuns zero.
Please note that i have not set the maximum width of the TextView.I want to get it runtime.

A: TextView_name.setLayoutParams(new LayoutParams(250,LayoutParams.WRAP_CONTENT));

by using the above code we can set the width for textview dynamically

A: I would try to use getWidth(). If you want to do that though, you have to be careful when you call it. It only makes sense after the view hierarchy is laid out. That means that trying to check onCreate, onStart or even onResume will probably not get the results that you want. As an experiment, you can call it in a click handler of a button and you should see the expected value correctly being returned. I can't really say any more about where you should get it without knowing what you want to use it for.


text:
Q: Is there a way to cast ObjectSet to ObjectSet? I'm trying to make long codes short. The original codes does something following:
using (var context = new DataEntities())
{
context.Table1.Foreach(x =>{
    // Omit ... updating UI
    DoSomething(x);
    // Omit ... updating UI
});

context.Table2.Foreach(x =>
{
    // Omit ... updating UI
    DoSomething(x);
    // Omit ... updating UI
});

context.Table3.Foreach(x =>
{
    // Omit ... updating UI
    DoSomething(x);
    // Omit ... updating UI
});
// continue...
}

As you see, there is lots of similar code here. So, I thought I should refactor it though, it's pretty hard for me since I cannot cast context.Table1 to anything, for an example, to cast context.Table1 to ObjectSet<EntityObject> to implement a method which does all the same action for the tables.
I just want to put similar codes into a method, does anyone have a good idea?
Thanks in advance,
Yoo

A: Generics?
private void DoSomethingWithAnyTable<T>(ObjectSet<T> table) where T : EntityObject
{
    table.Foreach(x =>{
        // Omit ... updating UI
        DoSomething(x);
        // Omit ... updating UI
    });
}

Then
DoSomethingWithAnyTable(context.Table1);
DoSomethingWithAnyTable(context.Table2);
DoSomethingWithAnyTable(context.Table3);

A: You should be able to use .Cast<SomeCommonType> to get an IEnumerable<T> of them? Assuming there is come commonality.
Otherwise; perhaps just IEnumerable? (non-generic)


text:
Q: Convert to dot notation How can I convert this query to use Extension Methods?
var x = from Prods n in Cat.Prod.GetAllProds()
        orderby n.Name
        select new
        {
            Name = n.Name,
            Cost = n.Cost
        };

A: Its called Lambda notation.
var x = Cat.Prod.GetAllProds().OrderBy(n=>n.Name).Select(n=>new {n.Name,n.Cost});

Note that you do not need to provide a name for each column you are selecting if that name is the same as the column name:
new
{
    Name = n.Name,
    Cost = n.Cost
});

Is exactly the same as:
new
{
    n.Name,
    n.Cost
});

A: It's quite simple in this case:
var x = Cat.Prod
           .GetAllProds()
           .OrderBy(n => n.Name)
           .Select(n => new
                        {
                           Name = n.Name,
                           Cost = n.Cost
                        });

For more information, I suggest reading  How query expressions work - Jon Skeet: Coding Blog.


text:
Q: Best way to do Visual Studio post build deployment in a team environment? I'm working in a team environment where each developer works from their local desktop and deploys to a virtual machine that they own on the network.  What I'm trying to do is set up the Visual Studio solution so that when they build the solution each projects deployment is handled in the post-build event to that developers virtual machine.
What I'd really like to do is give ownership of those scripts to the individual developer as well so that they own their post build steps and they don't have to be the same for everyone.
A couple of questions:

*

*Is a post build event the place to execute this type of deployment operation?  If not what is the best place to do it?

*What software, tools, or tutorials/blog posts are available to assist in developing an automatic deployment system that supports these scenarios?

Edit: MSBuild seems to be the way to go in this situation.  Anyone use alternative technologies with any success?
Edit: If you are reading this question and wondering how to execute a different set of MSBuild tasks for each developer please see this question; Executing different set of MSBuild tasks for each user?

A: i'd look into MSBuild or ANT

A: If you are using Visual Studio 2005 or later, project files are MSBUild files.  Inside the MsBuild file, there is an "AfterBuild" target.  I would recommend using this to do your deployment tasks, instead of the Post Build Event.
By using MSBuild tasks, you are more prepared to move into a Continuous Integration system like CruiseControl.NET, or Team City.
I'm not sure why all of your developers have their own virtual machines, it would seem at some point you'd want a central location where all developers work is built to ensure the code from all developers will integrate and build (this is a reason for using Continuous Integration systems).  I'm sure you can find a way that CruiseControl.Net or Team City or one of several other choices can help you in this scenario.  But as far as getting the initial setup, use MSBuild.


text:
Q: ngModel innerHTML works in p tag but not in input tag angular2 In one of my angular2 application, I want to show the innerHTML of the model in the input field which has a model is attached to it.
<input type="text"  [(ngModel)]="studentCategory" [innerHTML]="studentCategory"/>

the value of studentCategory is coming from data base which has some '& #174;' values. which is directly showing up in the text boxes, rather it should show a register symbol
i can easily show this in the following way

but not in input which has model attach to it.
Thanks in advance.

A: innerHTML refers to the content of the HTML tags.
A
 tag may contain  phrasing content. An <input> tag, however, must be empty. It may not have any child elements nor text content.

 resolves to
hello
. This is legal HTML. But <input>hello</input> is not valid. (<textarea>hello</textarea> would be valid).
You need to ensure that the HTML-entities are already unescaped before you assign the string to your ngModel variable studentCategory.


text:
Q: How to make a Multidimensional CGPoint array into a property variable? So I have this CGPoint vertexLocations[6][6] multidimensional array which has all my vertex locations for 6 horizontal lines and 6 vertical lines. I created vertexLocations in a method. However i need to access it out of my method, but I having a hard time creating it into a global variable. I've tried the following:
@property CGPoint vertexLocations[][];
@property CGPoint vertexLocations[6][6];

But the complier screams at me for both, I also tried having my method return the multidimensional array but every way I tried it screamed at me. Any suggestions would be much appreciated, thanks!


text:
Q: Column dividers in JTable or JXTable I Have a JTable (or a JXTable to be more precise) with 3 sections of grouped columns I want to divide.
I used to have 3 tables which i programmatically linked (the scrollbar position, the sorting, the selection). I used a lot of code to get this linked, and I want to get rid of this.
Now I Am switching to 1 JXTable, because there are some things a lot nicer in this table class.
I found some (not very satisfying) solutions to almost the same problem.
Maybe some one has a good suggestion for me.
Option 1: an empty column as a divider (another color, like gray) and programatically hop over this empty column when using the arrows or tab keys.
option 2: setting the margin for just 1 side of 1 column to a larger size, so it seems like a divider. Untill now I have only found out how to set the margins for all columns
option 3: getting back to 3 seperate tables again (especially to get the tables sorted in the same way is a lot of work, because I do not want to repeat the columns in the seperate sections). This means I have to rewrite my table sorter, sorting on a non-visible column.
any suggestion is welcome (also if it's none of the three given options)

A: I've made something that looks somewhat like what you're going for by overriding the cell renderer on the 3rd column to have a thick right border and no other borders.  You could do the same within the table column header to have the border extend up through there.  It's clearly placing the border within the cell but this may be sufficient for you.
  {
    ....
    table.getColumnModel().getColumn(2).setCellRenderer(
        new ThickRightBorderCellRenderer());
    ....
  }

  private static class ThickRightBorderCellRenderer
          extends DefaultTableCellRenderer {

    @Override
    public Border getBorder() {
      return BorderFactory.createMatteBorder(0, 0, 0, 3, Color.BLACK);
    }
  }


text:
Q: How to separate the values that was got from Azure as request response? I here insert all the codes. So plz anyone help me to separate the values under the Column which named as "Scored Labels". e.g. either 1 or 0.
Here basically I'm passing X axis, Y axis and Z axis values as request using urllib in Python. For that I'm getting response as bunch of list. Here I only need "Scored Labels" data only for other use.
Here is the sample request code
    {
  "Inputs": {
    "input1": {
      "ColumnNames": [
        "X axis",
        "Y axis",
        "Z axis"
      ],
      "Values": [
        [
          "0",
          "0",
          "0"
        ],
        [
          "0",
          "0",
          "0"
        ]
      ]
    }
  },
  "GlobalParameters": {}
}

Input Parameters
And here is the sample response
{
  "Results": {
    "output1": {
      "type": "DataTable",
      "value": {
        "ColumnNames": [
          "X axis",
          "Y axis",
          "Z axis",
          "Scored Labels",
          "Scored Probabilities"
        ],
        "ColumnTypes": [
          "Numeric",
          "Numeric",
          "Numeric",
          "Numeric",
          "Numeric"
        ],
        "Values": [
          [
            "0",
            "0",
            "0",
            "0",
            "0"
          ],
          [
            "0",
            "0",
            "0",
            "0",
            "0"
          ]
        ]
      }
    }
  }
}

Output Parameters
All together sample code will be like this(This given in Request Response API Documentation for my Machine learning model web service)
import urllib2
# If you are using Python 3+, import urllib instead of urllib2

import json

data =  {

        "Inputs": {

                "input1":
                {
                    "ColumnNames": ["X axis", "Y axis", "Z axis"],
                    "Values": [ [ "0", "0", "0" ], [ "0", "0", "0" ], ]
                },        },
            "GlobalParameters": {
}
    }

body = str.encode(json.dumps(data))

url = 'https://ussouthcentral.services.azureml.net/workspaces/b5eeedd29d564074b47a9c8ce5faa745/services/e6065c9017d0426196db3bbf0f78e9da/execute?api-version=2.0&details=true'
api_key = 'abc123' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}

req = urllib2.Request(url, body, headers)

try:
    response = urllib2.urlopen(req)

    # If you are using Python 3+, replace urllib2 with urllib.request in the above code:
    # req = urllib.request.Request(url, body, headers)
    # response = urllib.request.urlopen(req)

    result = response.read()
    print(result)
except urllib2.HTTPError, error:
    print("The request failed with status code: " + str(error.code))

    # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
    print(error.info())

    print(json.loads(error.read()))

I'm getting output as
This get b'{"Results":{"output1":{"type":"table","value":{"ColumnNames":["X axis","Y axis","Z axis","Scored Labels","Scored Probabilities"],"ColumnTypes":["Double","Double","Double","Int32","Double"],"Values":[["0.202999","9.345999","-2.979","1","0.999358713626862"],["-0.15099999","9.378999","-2.8689999","0","1.45975587173552E-08"]]}}}}'

Process finished with exit code 0

For my this input -->.    (I only need 4th parameter as either 0 or 1)
"Inputs": {

        "input1":
            {
                "ColumnNames": ["X axis", "Y axis", "Z axis"],
                "Values": [["0.202999", "9.345999", "-2.9790000"], ["-0.15099999", "9.378999", "-2.8689999"], ]
                # "Values": [["0.202999", "9.345999", "-2.9790000"], ]

            }, },
    "GlobalParameters": {
    }

Please help me solve this issue.
Thanks in advance.

A: You could try the below snippet/
In the below snippet replace the x or store x with your output response.
import json

x = b'{"Results":{"output1":{"type":"table","value":{"ColumnNames":["X axis","Y axis","Z axis","Scored Labels","Scored Probabilities"],"ColumnTypes":["Double","Double","Double","Int32","Double"],"Values":[["0.202999","9.345999","-2.979","1","0.999358713626862"],["-0.15099999","9.378999","-2.8689999","0","1.45975587173552E-08"]]}}}}'
#print(x)
y= json.loads(x)
output = y["Results"]
for value in output["output1"]["value"]["Values"]:
    print(value[3])

Sample Output :


text:
Q: How to expose HTML widgets from server I saw websites that let you import in your own website embedabble complex HTML widgets with few javascript lines.
Here an example from a Gamification website :

Paste this code in your HTML body display this result :Result
I would like to use the same process for a school project, being able to integrate my own complex HTML UI from a server on any website, simply by pasting few lines of code,but i don't really understand how it could be possible, and the technologies behind this.


text:
Q: Sending Commands from service to activity that are in different process by createPendingResult Am trying to send commands back from service to activity..
I created one activity and i called a service. Am implemented in onActivityResult() in activity class. But am Unable to get how to use createPendingResult() .. am i cal it in service or activity. I read in some links it should be called from activity.But am unable to get. Please can anybody help me find out this.
Can anybody give an example..Thank You

A: onActivityResult() is used only between two activity. Not in between activity and service if you want to send data from service to activity then call Service via Intent
Intent i=new Intent(Service.this,youractivity.class);
i.putExtra(put your data here)
i.setFlag(Intent.Flag_New_task)// set flag newtask flag
Startactivity(i);

or Bind YourService check belowlink
service Binder:
http://developer.android.com/guide/components/bound-services.html#Binder
and
AIDL
http://developer.android.com/guide/components/aidl.html
Thsts it...


text:
Q: What is the proper way to set SELinux context in an RPM .spec? (RHEL7 in 2018) The RHEL7 supplied tomcat package supports multiple instances through the creation of directories and symlinks. Once such a multiple instance is created and packaged as an RPM, the extra instances fail to start due to selinux failures.
The solution is configure selinux correctly in the RPM packaging, however I am struggling to find a canonical description of how to do this.
Where does the selinux configuration come from when tomcat is installed in RHEL7?
Edit: the question at What is the proper way to set SELinux context in an RPM .spec?, had anyone bothered to actually read it, referred to the obsolete RHEL4 and RHEL5 distributions, and is 7 years old. As clearly stated in this question, this refers to RHEL7 in 2018. The answer to the 7 year old question, and the answer to this one are very different from one another.

A: SELinux configuration is provided by selinux-policy-targeted package, which contains the default policy configuration for the distribution, including SELinux configuration for tomcat.
I could find two old Fedora packaging drafts describing SELinux configuration in RPM packaging.
PackagingDrafts/SELinux suggests including the file labeling configuration in %post and %postun sections of the spec file by executing semanage fcontext -a and semanage fcontext -d respectively and running restorecon/fixfiles afterwards.
It is useful to note, as pointed out by Graham Legett, that using semanage in %pre or %post sections of spec will add the complete python stack along with policycoreutils-python as install time dependency. Using restorecon will add policycoreutils, which in turn brings in sed, gawk and grep, as install time dependencies.
A better way to provide the required file labeling rules would be by a SELinux policy module. Policy modules provide clearer interface to manage modular policy (labeling rules are not mixed with local modifications done with semanage).
For your policy module with file labeling rules, you need to provide type enforcement file and file context labeling file. Type enforcement file is required even if you do not add any modifications to the policy. An example dummy type enforcement file mymodule.te:
policy_module(mymodule, 1.0)

The file labeling rules are in mymodule.fc and follow same :
/path/to/file   --  gen_context(system_u:object_r:type_t,s0)

With selinux-policy-devel, the module package can be compiled with[note 1]:
make -f /usr/share/selinux/devel/Makefile

Regarding packaging policy modules, SELinux Policy Modules Packaging Draft
 similarly recommends using the %post and %postun sections of the spec file to install the policy using semodule and restorecon/fixfiles. An example spec file is also provided.

[note 1] The example policy module could be generated without selinux-policy-devel by using checkmodule and semodule_package directly. It would require the policy files to be written without macros.


text:
Q: goto was unexpected at this time in my batch file i am trying to make a batch file, but my goto keeps saying "goto was unexpected at this time" here is my code
@echo off
if %firstrun% == 5 goto shut

Later on....
set firstrun=5

And lastly
:shut

echo o snap

shutdown -s -f -t 120

goto passk

A: It's complaining because, if firstrun is blank, then the command syntax is wrong and fails. The simple solution is to put quotes around the variable and constant being compared.
if "%firstrun%" == "5" goto :shut

Or by checking if the variable is blank beforehand.
if defined firstrun (
    rem Variable had a value.
    if %firstRun% == 5 goto :shut
)

This method is useful if you want to compare the values of %firstrun% to a number, as the quote method in an if statement can mess with that feature.


text:
Q: Android development error - trying to stream audio using AsyncPlayer I have a problem trying to stream audio using the AsyncPlayer class in android.
(I'm working on this for a three days now - please help)
I have a stream of audio ("http://212.29.254.129:8920")
I'm trying to get it to play using the code below:
AsyncPlayer ap = new AsyncPlayer("myplayer");
ap.play(this, Uri.parse("http://212.29.254.129:8920"), false, AudioManager.STREAM_MUSIC);

It doesn't work... I don't have any idea why... The link works - I tested in in several different programs... Any ideas what it can be?
I have Internet permissions in the manifest, so that's not it...
Could it be in a format android specifically doesn't recognize?
If so how can I go around it?
I also tried to do this with MediaPlayer - there I get an IOException on function prepare.
Please please help! I'm out of ideas.

A: Android doesn't support the AACP stream coming from that particular URL, so you are out of luck there. Your options are basically:

*

*Finding a different shout/media/icecast of the same stream, that uses a different encoding. You could even approach them, or find a 3rd party that is willing to do live re-encoding of the stream  using tools like EZStream.

*Trying to get the AACP to play on your android. One project for doing so can be found here.


text:
Q: What is the most appropriate html tag for jquery click events? I'm fairly decent at jquery, but I'm working on something I want to be very standards based. The question I keep running into is.  What html tag to use to bind to a click event.  Buttons, spans, anchor tags, divs or something else.  First.  I can put an anchor tag with an href="#" but it shows up in the url when you click it. I don't know why that bothers me, but it does.
Do any have speed benefits over another, or is there a standard reason why you would choose a button over an anchor tag or a span for that case.
Appreciate the advice.  Is there a place that has a good list of standard practices that anyone can point me to? I've searched, and everyone seems to have a different approach.

A: I don't think there's a specified tag on what an element should be to handle click events. For example, a menu displaying a submenu on click should be using <ul> and <li> tags, whereas a form validation button would be represented by a <button> element.
Usually I try to use the element the most relevant to the meaning of what I show to the user.

A: I would say that that is a bit openended unfortunately. Basically I would summarize the answer to be:
Bind your click event to whatever makes the most UX sense/provides the best ease of use for end users without having to do extra styling to for example make a div look like a button.
That being said most users will expect to click on a button or an anchor and have less automatic instinct to click on other elements. To make a anchor look nicer you can use a fake link that approximates what you are doing and then do a event.PreventDefault() call.

A: You should do whatever works best semantically.
What makes sense in the given context? Sometimes a button is the best solution, sometimes it's an anchor link.
In Single Page Applications, you still use links, even though you're not actually sending any requests. But you want stick with them, as they make sense to the user, as they know links are used for navigating around your site - changing your browsers history.
Buttons should be used when you want something to happen that has nothing to do with navigation, like opening a modal, toggeling functionality, etc.
With that said, you can do whatever you want! HTML is nothing more than semantics. After all, the browsers interpret the meaning of your HTML, and there is nothing your can do about it. There is no technical reasons for not doing it one way or another.

A: Try to use the most sensible HTML element for the action you are trying to do, this is semantic html.
For example if it is an action use a button, if it is navigation use an anchor tag.
For your anchor tag, perhaps the way you are executing your click event is more the problem try this to prevent the # from appearing in the url.
$('.myanchor').click(function(event){
    event.preventDefault();
    // do something.
});


text:
Q: Is there any event that fired before query goes to SQL Server? I want to find event, that fired before query goes to SQL Server. and do some changes at sql command before any data is retrieved from server.
Generally my goal is create an class that inherit some base ado.net class, where i can filter data before sql goes to server by addnig WHERE condition to the query. I need common deсision for all my application but not single case.

A: ADO.NET supports the decorator pattern. Technically, you can create your own DbConnection subclass that wraps the actual connection, and apply your own changes just before passing along ExecuteScalar / ExecuteNonQuery / etc calls. Unfortunately the need to wrap the connection, command, parameters and reader makes this a bit awkward, bit look at "mini-profiler" for an example of this (it uses the pattern to provide instrumentation and logging).
However, a better approach here may be to tweek the upstream implementation. In many cases blindly adding a "where" will fail.


text:
Q: Variables using in Expect/TCL in Bash Script (missing operand at _@_) Hej all,
I want to use expect code in a bash script. For background information here I got my solution for the expect script: Save terminal output to variable in expect/tcl
The script works fine when I use it stand alone. But I want to use it in a bash script for processing multiple files, I have problems with the variables inside the expect part.
I got these error:
set new error bounds? (0: no, 1: yes): missing operand at _@_
in expression "  _@_> 0.3 ||  > 0.3 "
(parsing expression "  > 0.3 ||  > 0.3 ")
...

Code:
#! /bin/bash
MLI_offs=$1
MLI_snr=$2
MLI_diff_par=$3

/usr/bin/expect <<EOF
spawn offset_fitm $MLI_offs $MLI_snr $MLI_diff_par MLI_coffs MLI_coffsets 7.0 6 1
set range 1.5
set azimuth 1.5

while {true} {
expect "enter minimum SNR threshold:"
send "7.0\r"

expect "enter the range and azimuth error thresholds:"
send "$range $azimuth\r"

expect -re {range: ([0-9.]+)   azimuth: ([0-9.]+)} {
    set range   $expect_out(1,string)
    set azimuth $expect_out(2,string)
}

expect "set new error bounds? (0: no, 1: yes):" {
    if { $range > 0.3 || $azimuth > 0.3 } {
        send "1\r"
    } else {
        send "0\r"
        break
    }
}
}
interact

EOF

Thanks,
Bjoern

A: The problem is that the variables are being substituted inside bash as well as Tcl/Expect. Since bash replaces unknown variables with the empty string, this leaves an entirely wrong script (which in turn complains because it can't figure out what's going on). It will have broken other things too (the use of expect_out) but it happens you've not hit it.
The simplest thing is to stop using bash as a wrapper as Tcl's quite adept at doing that sort of thing itself via the argv global. Thus:
#! /usr/bin/expect
set MLI_offs [lindex $argv 0]
set MLI_snr [lindex $argv 1]
set MLI_diff_par [lindex $argv 2]
# Alternatively, replace the preceding three lines with:
#    lassign $argv MLI_offs MLI_snr MLI_diff_par

spawn offset_fitm $MLI_offs $MLI_snr $MLI_diff_par MLI_coffs MLI_coffsets 7.0 6 1
set range 1.5
set azimuth 1.5

while {true} {
    expect "enter minimum SNR threshold:"
    send "7.0\r"

    expect "enter the range and azimuth error thresholds:"
    send "$range $azimuth\r"

    expect -re {range: ([0-9.]+)   azimuth: ([0-9.]+)} {
        set range   $expect_out(1,string)
        set azimuth $expect_out(2,string)
    }

    expect "set new error bounds? (0: no, 1: yes):" {
        if { $range > 0.3 || $azimuth > 0.3 } {
            send "1\r"
        } else {
            send "0\r"
            break
        }
    }
}
interact

A: you can escape the special '$' with a '\' for all expect(tcl) variables, to prevent Bash interpreting it. eg. $range should be writen as \$range in your Bash script.


text:
Q: python display bad docker version I install python 2.7 and docker 19.03. print (docker.version) display a bad version of docker.
root@block1:# docker --version
Docker version 19.03.13, build 4484c46d9d

root@block1:# python
Python 2.7.17 (default, Oct  8 2020, 12:12:24)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import docker
>>> print(docker.__version__)
1.10.6
>>>

I like to force python to display 19.03.13.

A: docker.version returns the version of the "docker" Python package you installed, which seems to be 1.10.6.
If you want the version of the docker daemon, you could connect to it with the from_env method, and then query the version from the client:
>>> import docker
>>> docker.version # This is the version of the Python package
'4.4.0'
>>> client = docker.from_env()
>>> client.version()['Version'] # And this is the version of docker
'19.03.13'


text:
Q: PostgreSQL Unique Index performance I have a script that does some webscraping for news and then uploads the info I scrape into a PostgreSQL DB in RDS. My question is regarding the preferred method for ensuring that the same news article is not recorded more than once.
Each time I scrape, the web scraper returns 40 news articles. I have it set so that each article + headline is added to a table where the headline column has a UNIQUE key constraint. So I have 2 options in order to make sure that each article is only recorded once:

*

*Use a simple try and except to try to insert every article + headline into the table -- error is returned if the headline already exists but it is ignored.

*Or, I can query for the 40 most recently added articles in the database, compare their headlines to the ones I pulled, and then only insert those that aren't already in the database.

My question is: which one would be better performance-wise? My guess is that with a low number of articles number 1 would be better but as the number of articles increases it would be better to use number 2, is that correct?

A: *

*create a temp table, identical to the target table

*put the articles you scraped into this temp

*[remove duplicates from this temp]

*insert the records from the temp table into the actual table, but only the records that dont yet exist
Below fragment from my twitter scraper:

    ins2 = """INSERT INTO tweets(id,sucker_id,created_at,user_id
            ,in_reply_to_id,is_reply_to_me,is_retweet,body)
     SELECT tt.id,tt.sucker_id,tt.created_at,tt.user_id
         ,tt.in_reply_to_id,is_reply_to_me,is_retweet,tt.body
     FROM tt_tweets tt
     WHERE NOT EXISTS( SELECT 1 FROM tweets nx where nx.id = tt.id)
       ;"""

And: tweets have a numerical id, which makes dedupping very easy.

A: Identifying the duplicates locally to the scraper will be faster than making a round-trip to the database to do so, provided it isn't done in a dumb way.  But the difference is very unlikely to be meaningful, compared to the overhead of doing the scraping in the first place.
But if the scraper has a limited memory for headlines, you will need to have a catch-and-ignore capability anyway.


text:
Q: PHP XML calling attributes I posted something just like this, with no responses but it was because I didn't give enough data. I closed that one and made this one because it better describes. I wasn't planning on making this.
My code:
 <?php
$q = $_GET['q'];
$xml = simplexml_load_file("http://ws.spotify.com/search/1/track?q=".$q."");

echo $xml->tracks . "
";
$num = 0;
foreach($xml->children() as $child){
    $num ++;
    if($num < 5){
        echo "attributes(href)."' title=''>".$child->name . " by " . $child->artist->name . "
";
    }
}

 ?>

I'm trying to call an attirbute of "href" for track.
On Spotify's website they show:
<?xml version="1.0" encoding="utf-8"?>
<tracks xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns="http://www.spotify.com/ns/music/1">
  <opensearch:Query role="request" startPage="1" searchTerms="foo"/>
  <opensearch:totalResults>768</opensearch:totalResults>
  <opensearch:startIndex>0</opensearch:startIndex>
  <opensearch:itemsPerPage>100</opensearch:itemsPerPage>
  <track href="spotify:track:3ZsjgLDSvusBgxGWrTAVto">
    <name>The Pretender</name>
    <artist href="spotify:artist:7jy3rLJdDQY21OgRLCZ9sD">
      <name>Foo Fighters</name>
    </artist>
    <id type="isrc">USRW30700007</id>
    <id type="isrc">USRW30700007</id>
    <track-number>1</track-number>
    <length>269.373000</length>
    <popularity>0.79251</popularity>
  </track>
  ...
</tracks>

A: Attributes in SimpleXML are very "simple" ;-)
foreach ($xml->children() as $child) {
    ...
    $href = (string)$child['href'];
}