text:
Q: MSYS2 on Windows 10 With Glade ( gtk_entry_get_text: assertion 'GTK_IS_ENTRY (entry)' failed ) Unfortunately I'm new to programming in C and I'm experiencing many problems with external libraries compatibility between linux and windows.
I'm trying to learn how to use GTK 3, use Glade to create the interface and geany to write the code in GCC
I'm looking for a solution on the internet for 4 days, but I don't understand how to solve it:
Please be patient, I don't know who to ask by now.
Thanks for your help.
when the "OK" button is pressed.
Appair the message on the first gtkentry but the second entry still empty

void gtk_entry_set_text (GtkEntry* otarget, const gchar* TargetText); //Give no action like no command exist

Code written in GCC via Geany
#include <stdio.h>
#include <gtk/gtk.h>
#include <gmodule.h>

int main(int argc, char *argv[])
{
    GtkBuilder      *builder;
    GtkWidget       *window;

    gtk_init(&argc, &argv);

    builder = gtk_builder_new();
    gtk_builder_add_from_file (builder, "test.glade", NULL);

    window = GTK_WIDGET(gtk_builder_get_object(builder, "TestWin"));

    gtk_builder_connect_signals(builder, NULL);

    g_object_unref(builder);

    gtk_widget_show(window);
    gtk_main();

    return 0;
}

// I have to put (extern "C" G_MODULE_EXPORT ) because without  give Could not find signal handler 'on_ok_button_clicked'.  Did you compile with -rdynamic?

extern "C" G_MODULE_EXPORT void on_ok_button_clicked(GtkButton *msgbox_ok, GtkEntry *origin, GtkEntry *target, gpointer user_data)
{

        const gchar *OriginText;
        const gchar *TargetText;

        OriginText = gtk_entry_get_text (GTK_ENTRY (origin)); // gtk_entry_get_text: assertion 'GTK_IS_ENTRY (entry)' failed

        TargetText = OriginText;

        void gtk_entry_set_text (GtkEntry *target, const gchar *TargetText); //Give no action like no command exist

}
extern "C" G_MODULE_EXPORT void on_cancel_button_clicked(GtkButton *cancel_button, gpointer user_data)
{
    gtk_main_quit();
}
extern "C" G_MODULE_EXPORT void on_TestWin_destroy(GtkWidget *TestWin, gpointer user_data)
{

        gtk_main_quit();
}

File test.glade in XML creato con Glade 3
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="TestWin">
    <property name="can_focus">False</property>
    <property name="default_width">420</property>
    <property name="default_height">200</property>
    <signal name="destroy" handler="on_TestWin_destroy" swapped="no"/>
    <child>
      <placeholder/>
    </child>
    <child>
      <object class="GtkFixed">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <child>
          <object class="GtkButton" id="ok_button">
            <property name="label" translatable="yes">OK</property>
            <property name="width_request">95</property>
            <property name="height_request">35</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <signal name="clicked" handler="on_ok_button_clicked" swapped="no"/>
          </object>
          <packing>
            <property name="x">190</property>
            <property name="y">130</property>
          </packing>
        </child>
        <child>
          <object class="GtkButton" id="cancel_button">
            <property name="label" translatable="yes">Cancell</property>
            <property name="width_request">100</property>
            <property name="height_request">35</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <signal name="clicked" handler="on_cancel_button_clicked" swapped="no"/>
          </object>
          <packing>
            <property name="x">300</property>
            <property name="y">130</property>
          </packing>
        </child>
        <child>
          <object class="GtkEntry" id="origin">
            <property name="width_request">300</property>
            <property name="height_request">35</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
          </object>
          <packing>
            <property name="x">100</property>
            <property name="y">20</property>
          </packing>
        </child>
        <child>
          <object class="GtkEntry" id="target">
            <property name="width_request">300</property>
            <property name="height_request">35</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
          </object>
          <packing>
            <property name="x">100</property>
            <property name="y">60</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="lbl_origin">
            <property name="width_request">90</property>
            <property name="height_request">35</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="label" translatable="yes">Origin Text</property>
          </object>
          <packing>
            <property name="x">5</property>
            <property name="y">20</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="lbl_target">
            <property name="width_request">90</property>
            <property name="height_request">35</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="label" translatable="yes">Target Text</property>
          </object>
          <packing>
            <property name="x">5</property>
            <property name="y">60</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

Command used for compilation under Windows 10
gcc  -pthread -mms-bitfields -IC:/msys64/mingw64/include/gtk-3.0 -IC:/msys64/mingw64/include/cairo -IC:/msys64/mingw64/include -IC:/msys64/mingw64/include/pango-1.0 -IC:/msys64/mingw64/include/fribidi -IC:/msys64/mingw64/include -IC:/msys64/mingw64/include/atk-1.0 -IC:/msys64/mingw64/include/cairo -IC:/msys64/mingw64/include/pixman-1 -IC:/msys64/mingw64/include -IC:/msys64/mingw64/include/freetype2 -IC:/msys64/mingw64/include -IC:/msys64/mingw64/include/harfbuzz -IC:/msys64/mingw64/include/libpng16 -IC:/msys64/mingw64/include/gdk-pixbuf-2.0 -IC:/msys64/mingw64/include -IC:/msys64/mingw64/lib/libffi-3.2.1/include -IC:/msys64/mingw64/include/glib-2.0 -IC:/msys64/mingw64/lib/glib-2.0/include -IC:/msys64/mingw64/include test.cpp -o test -LC:/msys64/mingw64/lib -lgtk-3 -lgdk-3 -lz -lgdi32 -limm32 -lshell32 -lole32 -Wl,-luuid -lwinmm -ldwmapi -lsetupapi -lcfgmgr32 -lpangowin32-1.0 -lpangocairo-1.0 -lpango-1.0 -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lintl -lglib-2.0


text:
Q: Function for MACD histogram average I want to get an X bars back average value from the MACD histogram but only for positive or negative values respectively. With that I want to be able to search for histogram spikes and compare them with the average values.
So for the sake of (my) simplicity Im trying to achieve this with a function aimed either on the positive or the negative values. Here is an example for the histogram positive values where I try to look back over a _lookback amount of bars and if the bar has a positive value I ad that value to the previous average value and divide it by the number of positive values (ie. c_avgGreenCounter) that printed before that:
f_getAvgHistoGreen(_lookback) =>
var avgHistogramGreen = 0.0
var avgGreenCounter = 0
for i = 0 to _lookback by 1
    if hist[i] >= 0
        avgGreenCounter +=  1
        avgHistogramGreen := (avgHistogramGreen + hist[i]) / 2
    else
        avgHistogramGreen := avgHistogramGreen
        avgGreenCounter := avgGreenCounter
[avgGreenCounter, avgHistogramGreen]

Only when I call this with this function:
[avgGreenCounter, avgHistogramGreen] = f_getAvgHistoGreen(50)

the avgGreenCounter hits super high numbers which is obviously wrong. Can someone help me at least with the positive values please? Histogram values print correctly, I've checked them. I think that I will be then able to figure it out for the negatives as well.

A: Your excessive result is from declaring the variables with var, so that as the script executes on each historical bar, those variables are then retaining the result from the function being called on the previous bar(s). You end up with a cumulative result rather than it only being the result from the last n bars only.
Also during the loop, you don't know how many results will end up being returned, so you only need to find the sum of the histogram values while in the loop. Once the loop is finished you can obtain the average by dividing by the number of results.
//@version=5
indicator("macd avg hist", overlay = false)

f_getAvgHistoGreen(_lookback, _hist) =>
    float _sumHistogramGreen = 0.0
    int _avgGreenCounter = 0
    for i = 0 to _lookback by 1
        if _hist[i] >= 0
            _avgGreenCounter +=  1
            _sumHistogramGreen += _hist[i]
    _avgHistogramGreen = _sumHistogramGreen / _avgGreenCounter
    [_avgGreenCounter, _avgHistogramGreen]

[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)

[avgGCount, avgHistG] = f_getAvgHistoGreen(50, histLine)

plot(avgGCount)
plot(avgHistG)

A: Your script will be executed on each bar. So, you can calculate this along the way instead of using a for loop which will be executed on each bar, so you can save some performance.
//@version=5
indicator("My Script")
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)

var pos_hist_cnt = 0
var pos_hist_total = 0.0
var pos_hist_avg = 0.0
var neg_hist_cnt = 0
var neg_hist_total = 0.0
var neg_hist_avg = 0.0

if (histLine >= 0)
    pos_hist_total := pos_hist_total + histLine
    pos_hist_cnt := pos_hist_cnt + 1
    pos_hist_avg := pos_hist_total / pos_hist_cnt

if (histLine <0)
    neg_hist_total := neg_hist_total + histLine
    neg_hist_cnt := neg_hist_cnt + 1
    neg_hist_avg := neg_hist_total / neg_hist_cnt

plot(series=histLine)
plot(series=pos_hist_avg, color=color.green)
plot(series=neg_hist_avg, color=color.red)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a cleaner way to chain empty list checks in Python? I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this:
if a.get("key") and a["key"][0] and a["key"][0][0] :
    for b in a["key"][0][0] :
        #Do something

which works, but is pretty ugly.  It seems there has to be a better way to do this, so what's a more elegant solution?

A: I would write a custom indexer function like this:
def safe_indexer(obj, *indices):
    for idx in indices:
        if not obj: break

        if hasattr(obj, "get"):
            obj = obj.get(idx)
        else:
            obj = obj[idx]

    return obj

Usage:
a = {"key": {0: {0: "foo"} } };
print safe_indexer(a, "key", 0, 0)
print safe_indexer(a, "bad", 0, 0)

Output:
foo
None

A: What about this:
try:
    for b in a['key'][0][0]:
        # do stuff.
except KeyError, TypeError, IndexError:
    # respond appropriately.

A: try:
  bs = a["key"][0][0]
# Note: the syntax for catching exceptions is different in old versions
# of Python. Use whichever one of these lines is appropriate to your version.
except KeyError, IndexError, TypeError:   # Python 3
except (KeyError, IndexError, TypeError): # Python 2
  bs = []
for b in bs:

And you can package it up into a function, if you don't mind longer lines:
def maybe_list(f):
  try:
    return f()
  except KeyError, IndexError, TypeError:
    return []

for b in maybe_list(lambda: a["key"][0][0]):


text:
Q: get desired rows from matrix in R Say I have a matrix. There is a column showing the dates information, from first row "20080101" to the last row "20100101". The question is, how can I get rows from date "20080901" to "20091031"? It runs in R.
Example:
2008010106 a
2008010112 b
2008010118 f
2008010206 e
2008010200 w
2008010212 a
2008010218 b
2008010300 f
2008010406 e
2008010306 a
2008010312 b
2008010318 f
2008010400 r
2008010412 e

First column is dates( the last two digits represent hours in a day). Second column is all letters.
Now I want to get rows from " 2008010200" to "2008010412"
NOTICE that the dates are not in a sequential order.

A: I like xts subsetting for this kind of thing.
library(xts)
m <- cbind(date=seq(20080101, 20080131, 1),
           matrix(runif(31*2), ncol=2))
x <- xts(m[, -1], as.Date(as.character(m[, 1]), '%Y%m%d'))

x['20080110/20080120']

# 2008-01-10 0.4819532 0.9406910
# 2008-01-11 0.5447225 0.5776338
# 2008-01-12 0.5614482 0.4152551
# 2008-01-13 0.2356413 0.9192496
# 2008-01-14 0.9759123 0.8141157
# 2008-01-15 0.2912074 0.3847100
# 2008-01-16 0.2185788 0.6909651
# 2008-01-17 0.6544894 0.3287306
# 2008-01-18 0.1319076 0.6527686
# 2008-01-19 0.6391880 0.5336123
# 2008-01-20 0.6915097 0.4842339

The above example returns the rows of x that have dates falling between 10 January 2008 and 20 January 2008.

A: A logical expression that would evaluate the n-th column say the 10th can be used in "i" argument to "[".
n=10
shorterM <- M[ M[,n] >= "20080101" & M[,n] <= "20100101" , ]

This should work for either a matrix or a dataframe as long as these "dates" are actually character values with that format. The ">=","<=" abd "&" operators are all vectorized. This is "logical indexing". You do take a risk in posting questions with no code since most respondents think that is your job and may not test (as I have not). Next time post a small example, preferably with the dput function, and specify what the right answer is. Then you get tested code and everyone is happy and you get no close votes ... unless of course this is a duplicate which is certainly possible.
The offered example is used as a worked example:
> DD <- read.table(text="2008010106 a
+ 2008010112 b
+ 2008010118 f
+ 2008010206 e
+ 2008010200 w
+ 2008010212 a
+ 2008010218 b
+ 2008010300 f
+ 2008010406 e
+ 2008010306 a
+ 2008010312 b
+ 2008010318 f
+ 2008010400 r
+ 2008010412 e", colClasses="character")

> (shorterDD <- DD[ DD[,1] >= "2008010200" & DD[,1] <= "2008010412" , ])
           V1 V2
4  2008010206  e
5  2008010200  w
6  2008010212  a
7  2008010218  b
8  2008010300  f
9  2008010406  e
10 2008010306  a
11 2008010312  b
12 2008010318  f
13 2008010400  r
14 2008010412  e

A: You could use between which is a convenient function from dplyr. m from @jbaums' post
  library(dplyr)
  m[between(m[,"date"], 20080110, 20080120),]
  #       date
  #[1,] 20080110 0.19957458 0.22814565
  #[2,] 20080111 0.44428667 0.24073101
  #[3,] 20080112 0.86218249 0.68175459
  #[4,] 20080113 0.31706619 0.48679117
  #[5,] 20080114 0.09629562 0.66931400
  #[6,] 20080115 0.81436380 0.35013160
  #[7,] 20080116 0.34077661 0.54417985
  #[8,] 20080117 0.71414292 0.52569811
  #[9,] 20080118 0.84745961 0.90069540
 #[10,] 20080119 0.04145519 0.05394461
 #[11,] 20080120 0.65274477 0.08029292


text:
Q: .net remoting, How to reconnect if the connect is lost? I have this working but i don't understand how to predict when the connection has dropped and needs to reconnect to the server.
what i want to do is have the client connect right away to the .net remoting server if it drops out, sort of like keep trying to connect and disregard if it does not need to.
help appreciated.
here is my code:
namespace TaskClient
{
    using System;
    using System.Reflection;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using System.Threading;
    using TaskShared;

    class Program
    {
        static void Main(string[] args)
        {
            TcpChannel chan = new TcpChannel();
            ChannelServices.RegisterChannel(chan, false);
            Connections remObject = (Connections)Activator.GetObject(typeof(Connections), "tcp://localhost:8085/TaskServer");

            if (remObject == null)
            {
                Console.WriteLine("Could not connect to TaskServer. (tcp://localhost:8085/TaskServer)");
            }
            else
            {
                Console.WriteLine("Connected to Task Server.");

                var rt = new TestTask()
                {
                    ApplicationName = Assembly.GetExecutingAssembly().FullName,
                    ComputerName = Environment.MachineName,
                    VersionInfo = "1.0.0",
                    JobRunning = "None"
                };

                remObject.Add(rt);
            }

            while (true)
            {
                //TODO:
                //Check if connected.. how?
                //Re-create the connection... how?

                //doing this simple won't work:
                if (remObject == null)
                    remObject = (Connections)Activator.GetObject(typeof(Connections), "tcp://localhost:8085/TaskServer");

                remObject.Invalidate(remObject[rt]);

                Thread.Sleep(1000);
            }
        }
    }
}


text:
Q: Multiuser login into winforms application i have a winforms app in C# that needs access control for certain forms. That means, the application is running under the same (default) user at system startup, but certain forms need to be secured, so that only certain windows users could have access to the additional functions after identifying themself with username and password. For that step windows authentication should be used.
Now the tricky part. Although the application was started under a "normal" user I would like the superusers to "login" into the special form without restarting the entiere application.
My question now is. Is this possible (i.e. create one thread with the credentials of an administrator). Or do I need to setup another appdomain for that?
Please give me a hint wather the user of a running application could be changed somehow.
Thank you.
EDIT
I replaced administrators by "certain users" since the privileged user could be just another ordinary user that is granted access to the special functionality by the configuration of the installation.

A: You have to put those forms or functionality which requires elevated permissions into a new AppDomain which is started with elevated permissions. You can create the domain once, when required and keep it around. Into this new AppDomain, you will load the necessary code modules which will contain the processes you need to run. You'll have to pass any necessary state or configuration across the AppDomain boundary since it's essentially a different process within your current process. The nice thing is that you can keep the AppDomain around after a while. It's not like a thread that runs and goes away when its done, so you can use it on-demand later for additional tasks. The magic is in how you pass the credentials or evidence to the new AppDomain (or process).

A: Just to make sure, you essentially want to elevate your process to Administrator rights only when actions that require said rights are performed?
If that's the case, it seems like it's not possible. See here.
One way of doing what you want is to use console arguments in your main assembly for each action you need to do. For example, for changing a system setting, you could Process.Start your main assembly with the argument "-change {...}", and have that run under Administrator rights, while keeping your currently running process under the current user's privileges.

A: I just found an article about "impersonation". At the moment I have not tested it but according to this article it should work that a method call can be executed under another user. Maybe this is of some help to someone.


text:
Q: Connect between turtles and their origin patches I want to ask how can I connect between the turtles and their origin patch
I create the turtles by using
sprout-turtles 2 ;; so their origin is not (0 0)

I want to have an action only happen when they are in their origin patch otherwise another action will happen.

A: You need to add a turtles-own variable. origin would be a name for it. When the turtles are created, you just need to have them set that variable to patch-here:
set origin patch-here

Then, you can check if they're at their origin patch with: patch-here = origin.


text:
Q: PyDev for Eclipse does it worth to use it? what are the features for better use, and why should i get it?
i have heard that it is a good tool for developing AI algorithms, and i want to know if there is anything special that i can use from it.
for example:
var = random.shuffle()

this function is used widely at AI, is something better at PyDev?
i'm doing the simulated annealing and the ants algorithms, this function:
def Tour(tamaño):
    tour1 = []
    for i in range(tamaño):
        while(not False):
            valor = random.randrange(tamaño)
            if valor not in tour1:
                tour1.append(valor)
                break
    return tour1

is to create a random tour, but i heard that using PyDev tool is easier to do it, how?


text:
Q: How to move my edittext up when stkeyboard is on I have created a login page. If I insert some text in edit text (username, password) etc then a softkeyboard is visible. but it comes on my password field view. So upper half of password field is visible while lower half is not because of that softkeyboard. I want when the softkeyboard is visible the password field to move up a little, so that the entire edittext will be visible.
Thanks

A: add this line in your menifest.xml file
<activity android:name=".your_activity" android:windowSoftInputMode="adjustResize"></activity>

A: Your layout should shift up automatically when it has focus and the softkeyboard is displaying. I have a login form and I've done nothing special to get this behaviour.

A: One way you can solve this is by having a ScrollView as the root of your layout.


text:
Q: 18.04 server Network is unreachable My Server was working great until TimeTrex (A PHP based Payroll Application needed updating for the new Tax Tables. The install went in clean but now the system says the network is unreachable. I ran the following checks:
Running as root
Output of cat /etc/netplan/*.yaml:
# This file is generated from information provided by
# the datasource.  Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
    version: 2
    renderer: networkd
    ethernets:
        enp5s0:
            addresses: [192.168.1.200/24]
            gateway4: 192.168.0.1
            dhcp4: false
            nameservers:
                addresses: [8.8.8.8, 8.8.4.4]

Output of ip addr ls:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp5s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 94:de:80:28:a2:71 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.200/24 brd 192.168.1.255 scope global enp5s0
       valid_lft forever preferred_lft forever
    inet6 fe80::96de:80ff:fe28:a271/64 scope link
       valid_lft forever preferred_lft forever

Output of netplan --debug generate:
** (generate:2250): DEBUG: 18:39:27.761: Processing input file /etc/netplan/01-netcfg.yaml..
** (generate:2250): DEBUG: 18:39:27.762: starting new processing pass
** (generate:2250): DEBUG: 18:39:27.762: enp5s0: setting default backend to 1
** (generate:2250): DEBUG: 18:39:27.762: Configuration is valid
** (generate:2250): DEBUG: 18:39:27.762: Generating output files..
** (generate:2250): DEBUG: 18:39:27.762: NetworkManager: definition enp5s0 is not for us (backend 1)

Output of systemctl status systemd-networkd:
● systemd-networkd.service - Network Service
   Loaded: loaded (/lib/systemd/system/systemd-networkd.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2020-01-12 18:22:40 EST; 22min ago
     Docs: man:systemd-networkd.service(8)
 Main PID: 923 (systemd-network)
   Status: "Processing requests..."
    Tasks: 1 (limit: 4915)
   CGroup: /system.slice/systemd-networkd.service
           └─923 /lib/systemd/systemd-networkd

Jan 12 18:22:40 timberoakspetspa systemd[1]: Starting Network Service...
Jan 12 18:22:40 timberoakspetspa systemd-networkd[923]: Enumeration completed
Jan 12 18:22:40 timberoakspetspa systemd[1]: Started Network Service.
Jan 12 18:22:40 timberoakspetspa systemd-networkd[923]: lo: Link is not managed by us
Jan 12 18:22:45 timberoakspetspa systemd-networkd[923]: enp5s0: Gained carrier
Jan 12 18:22:45 timberoakspetspa systemd-networkd[923]: enp5s0: Could not set route: Network is unreachable
Jan 12 18:22:47 timberoakspetspa systemd-networkd[923]: enp5s0: Gained IPv6LL
Jan 12 18:22:47 timberoakspetspa systemd-networkd[923]: enp5s0: Configured

A: help from another group showed the default gateway had been erroneously changed in the /etc/netplan/*.yaml.
Issue resolved - I think.


text:
Q: log4j2 not writing to both Console and File
I am new to log4j2.  I created a very simple java project in eclipse to try it out.
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" >
  <Properties>
    <Property name="test">test</Property>
  </Properties>
  <ThresholdFilter/>
  <Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{dd MM yyyy HH:mm:ss,SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
    <File name="LogFile" fileName="test.log">
      <PatternLayout>
        <Pattern>%t %-5p %c{2} - %m%n</Pattern>
      </PatternLayout>
    </File>
  </Appenders>

  <Loggers>
    <Root level="ERROR">
      <AppenderRef ref="STDOUT" />
    </Root>
    <Logger name="tutorial" level="TRACE">
      <Appender-Ref ref="STDOUT" />
      <Appender-Ref ref="LogFile" />
    </Logger>
  </Loggers>
</Configuration>

Test.java
package tutorial;

public class Test {
    private static final Logger logger = LogManager.getLogger(Test.class);

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(logger.getName());
        logger.info("*****Testing*****");
        logger.log(Level.WARN, "*****Testing*****");
    }
}

Result of running Test.java
tutorial.Test

There were no logging from log4j at all both in console and log file.  The log file, test.log, is created but there's noting in it.  Can any one with expertise help decipher the mystery?
JDK: jdk1.8.0_92
log4j2: 2.6.2
Thank you in advance.

A: Cause of threshold filter log4j log is not displayed.
If it is not required then can you try with removing below line.
<ThresholdFilter/>


text:
Q: Pseudo-Random image via CSS-sprite (random location) I want a header image in my HTML to be random. I have accomplished this by using this php file, however I would like to do something different.  I want to have the random images be a part of one sprite.  That way the images can all load at the same time and they user won't have to see the images load when navigating to different pages.  I would also like to choose the random factor, i.e. show this picture 50% the others 10% of the time (if there are 6 pictures).  Is this even possible and where would an amateur start?  Is this the best way to implement my scenario so that the user sees as little image load as possible?

A: You could have the sprited header style declared in CSS as you normally would, and then simply adjust the xpos/ypos of the sprite in-html. You would be able to recycle some of the logic you already have and manipulate individual header probability.
I'd stick with individual assets though, especially if they are the size of a google doodle. Easier to extend that way and, assuming the rest of your static content has already been cached, any overhead of downloading a new image would be negligible.


text:
Q: Where does "ainv" come from? Python's random module has the following method in it:
def gammavariate(self, alpha, beta):
    """Gamma distribution.  Not the gamma function!

    Conditions on the parameters are alpha > 0 and beta > 0.

    The probability distribution function is:

                x ** (alpha - 1) * math.exp(-x / beta)
      pdf(x) =  --------------------------------------
                  math.gamma(alpha) * beta ** alpha

    """

    # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2

    # Warning: a few older sources define the gamma distribution in terms
    # of alpha > -1.0
    if alpha <= 0.0 or beta <= 0.0:
        raise ValueError('gammavariate: alpha and beta must be > 0.0')

    random = self.random
    if alpha > 1.0:

        # Uses R.C.H. Cheng, "The generation of Gamma
        # variables with non-integral shape parameters",
        # Applied Statistics, (1977), 26, No. 1, p71-74

        ainv = _sqrt(2.0 * alpha - 1.0)
        bbb = alpha - LOG4
        ccc = alpha + ainv

        while 1:
            u1 = random()
            if not 1e-7 < u1 < .9999999:
                continue
            u2 = 1.0 - random()
            v = _log(u1/(1.0-u1))/ainv
            x = alpha*_exp(v)
            z = u1*u1*u2
            r = bbb+ccc*v-x
            if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
                return x * beta

    elif alpha == 1.0:
        # expovariate(1)
        u = random()
        while u <= 1e-7:
            u = random()
        return -_log(u) * beta

    else:   # alpha is between 0 and 1 (exclusive)

        # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle

        while 1:
            u = random()
            b = (_e + alpha)/_e
            p = b*u
            if p <= 1.0:
                x = p ** (1.0/alpha)
            else:
                x = -_log((b-p)/alpha)
            u1 = random()
            if p > 1.0:
                if u1 <= x ** (alpha - 1.0):
                    break
            elif u1 <= _exp(-x):
                break
        return x * beta

While porting the code over to Java for use, my IDE has been complaining that there is a typo (misspelling) for the ainv variable name. Where does this name come from, and what is the justification behind it? If anyone can find reference material for Applied Statistics, (1977), 26, No. 1, p71-74, being able to read those pages may be helpful.
Addendum
This may or may not be of use to anyone, but here is a partial implementation of the class that was ported over. The code appears to be complete, but JetBrains Intellij IDEA complains about ainv's spelling if it is not added to the IDE's dictionary. This has led to some indecision as to whether or not it should be considered to be correctly spelled. It is the only typo the program is complaining about.
import java.util.Random;

class XRandom extends Random {
    static final double LOG4 = Math.log(4);
    static final double SG_MAGIC_CONST = 1 + Math.log(4.5);

    double gammaVariate(double alpha, double beta) {
        if (alpha <= 0 || beta <= 0)
            throw new RuntimeException("gammaVariate: alpha and beta must be > 0");
        if (alpha > 1) {
            double ainv, bbb, ccc, u1, v, x, z, r;
            ainv = Math.sqrt(2 * alpha - 1);
            bbb = alpha - LOG4;
            ccc = alpha + ainv;
            while (true) {
                u1 = this.nextDouble();
                if (u1 <= 1e-7 || u1 >= .9999999)
                    continue;
                v = Math.log(u1 / (1 - u1)) / ainv;
                x = alpha * Math.exp(v);
                z = u1 * u1 * (1 - this.nextDouble());
                r = bbb + ccc * v - x;
                if (r + SG_MAGIC_CONST - 4.5 * z >= 0 || r >= Math.log(z))
                    return x * beta;
            }
        }
        if (alpha < 1) {
            double b, p, x, u1;
            while (true) {
                b = (Math.E + alpha) / Math.E;
                p = b * this.nextDouble();
                x = p <= 1 ? Math.pow(p, 1 / alpha) : -Math.log((b - p) / alpha);
                u1 = this.nextDouble();
                if (p > 1) {
                    if (u1 <= Math.pow(x, alpha - 1))
                        break;
                } else if (u1 <= Math.exp(-x))
                    break;
            }
            return x * beta;
        }
        double u;
        do {
            u = this.nextDouble();
        } while (u <= 1e-7);
        return -Math.log(u) * beta;
    }
}

A: Not sure why the IDE thinks it's a typo, but don't you just need to declare the ainv variable?
double ainv = Math.sqrt(2.0 * alpha - 1.0) ;

As for it's purpose, it looks to be just an intermediate calculation that's used in two other places.

A: I found page 71 here, but it looks like pages 72-75 require an account to view them at full resolution.


text:
Q: Beamer: Split frame into multiple slides & hide opaque elements in handout I have a beamer slide with items that reveal and then become opaque using overlays. Some elements become hidden. When using handout mode, I would like to create two slides for the frame. The catch is that for handout mode, I want the opaque items to become invisible.
In this MWE, I demonstrate the basic issue. Each item becomes gray, as the slides progress. Nested items become invisible once we progress.
\documentclass{beamer}
\setbeamercovered{transparent}
\setbeamercovered{again covered={\opaqueness<1->{35}}}

\begin{document}

\begin{frame}
\frametitle{Split into two slides for handout}

\begin{enumerate}

    \item<+|handout:1> First item, becomes grey when covered again, shows in first handout slide, want to disappear completely in second handout slide
    \begin{itemize}
        \item<only@.|handout:1> Only shows while first item is uncovered, and in first handout slide
    \end{itemize}
    \item<+|handout:1> Second item, becomes grey when covered, shows in first handout slide, want to disappear completely in second handout slide
    \begin{itemize}
        \item<only@.|handout:1> Only shows while second item is uncovered, and in first handout slide
    \end{itemize}
    \item<+|handout:2> Third item, shows in second handout slide
    \begin{itemize}
        \item<only@.|handout:2> Shows along with third item, and in handout slide
    \end{itemize}

\end{enumerate}

\end{frame}

\end{document}

Now, compare when using the handout option:
\documentclass[handout]{beamer}
\setbeamercovered{transparent}
\setbeamercovered{again covered={\opaqueness<1->{35}}}

\begin{document}

\begin{frame}
\frametitle{Split into two slides for handout}

\begin{enumerate}

    \item<+|handout:1> First item, becomes grey when covered again, shows in first handout slide, want to disappear completely in second handout slide
    \begin{itemize}
        \item<only@.|handout:1> Only shows while first item is uncovered, and in first handout slide
    \end{itemize}
    \item<+|handout:1> Second item, becomes grey when covered, shows in first handout slide, want to disappear completely in second handout slide
    \begin{itemize}
        \item<only@.|handout:1> Only shows while second item is uncovered, and in first handout slide
    \end{itemize}
    \item<+|handout:2> Third item, shows in second handout slide
    \begin{itemize}
        \item<only@.|handout:2> Shows along with third item, and in handout slide
    \end{itemize}

\end{enumerate}

\end{frame}

\end{document}

Everything works as desired when not in handout mode. However, I would like items 1 and 2 to become hidden, and not take up any space, on slide 2 when in handout mode. Right now, on the second slide in handout mode, the first two items are just greyed out.

A: You can use handout:only@1 to only show these items on the first overlay of handout mode:
\documentclass[handout]{beamer}

\setbeamercovered{transparent}
\setbeamercovered{again covered={\opaqueness<1->{35}}}

\begin{document}

\begin{frame}
\frametitle{Split into two slides for handout}

\begin{enumerate}

    \item<+|handout:only@1> First item, becomes grey when covered again, shows in first handout slide, want to disappear completely in second handout slide
    \begin{itemize}
        \item<only@.|handout:1> Only shows while first item is uncovered, and in first handout slide
    \end{itemize}
    \item<+|handout:only@1> Second item, becomes grey when covered, shows in first handout slide, want to disappear completely in second handout slide
    \begin{itemize}
        \item<only@.|handout:1> Only shows while second item is uncovered, and in first handout slide
    \end{itemize}
    \item<+|handout:2> Third item, shows in second handout slide
    \begin{itemize}
        \item<only@.|handout:2> Shows along with third item, and in handout slide
    \end{itemize}

\end{enumerate}

\end{frame}

\end{document}


text:
Q: Windows Port 80 A few time ago I installed Laravel Vallet. It makes me give the port 80 to Laravel Valet. How can I make the port 80 free again? Thank you in advance
I'm not really sure what should I do, I'm afraid it will cause an error on my computer


text:
Q: Why Hbase stoprow is exclusive in a scan? Is there a way  (other than rebuilding the hbase jars) to make the hbase scan(startRown, endRow) constructor inclusive on the endRow side?
My rowkey is a string.

A: You can use
scan.withStopRow(StopRow, true)

Which will include de Stop Row
From the documentation :
Scan documentation
Source code
You could also use
scan.includeStopRow = true;


text:
Q: Ionic PWA with capacitor I am building a Ionic PWA. I don't want to generate the APK file so I add my app to homescreen. I want to open the device camera and save the photos captured in my device by creating a folder. I tried to access the https://capacitor.ionicframework.com/docs/apis/filesystem api to create a folder in the device directory and then save captured photos in it.
But I am getting this error: FileSystem doesnot have web implementation. Does the file system api works only if I generate a APK file or is there any plans in future to support for web?

A: The Filesystem API has now been implemented. The Capacitor Filesystem plugin has a web implementation, based on IndexedDB.
See the source code on GitHub: https://github.com/ionic-team/capacitor-plugins/blob/filesystem/filesystem/src/web.ts

A: The Filesystem API doesn't have a web implementation because you can't access the filesystem in browsers for security reasons. Accessing the filesystem is only possible for native devices i.e Android and iOS and Electron. So yes; you need to add an Android/iOS target and build a native application if you want to access the Filesystem.


text:
Q: On the fly image resizing and uploading to amazon s3 I am looking to upload images to amazon s3. Those images should be re sized to two sizes a thumbnail and a normal size. The resize should be done on client side to reduce server bandwidth. Then information about the images should be stored in a db using asp.net MVC.
Preferably a plugin would be the best option to do so.
Can anyone please help me in choosing the right plug in or steps to accomplish this?
I have researched a lot and came across plupload and swfupload but I got very confused as to accomplish the very simple tasks above.

A: First hit on google: SWFUpload Resize Image on the client demo.
Quote from the demo page:

This demo shows how SWFUpload can
  resize images on the client side.
  Images resized before being uploaded
  to the server. Then some JavaScript is
  used to download the thumbnail and
  display the resized image without
  reloading the page.

A: Jumploader can also create thumbnails clientside. You can accomplish it with theese parameters. There are more parameters but they can all be found in the documentation. Jumploader is a java applet i opposition to swfuploader which is flash.
<param name="uc_uploadScaledImages" value="true"/>
<param name="uc_scaledInstanceNames" value="thumb1,thumb2"/>
<param name="uc_scaledInstanceDimensions" value="150x150xcrop,500x300xfit"/>
<param name="uc_scaledInstanceQualityFactors" value="600,900"/>

Good luck :-)


text:
Q: html style not work in FF in MVC view I have the following view:

    <fieldset style="width:600">

             TEST
             <%= Html.Encode(Model.MyDESCRIPTION)%>

             ....

    </fieldset>

I want to the width limited within 600px for printing, So I set the top div to width=600, wich works fine in IE, but doesn't work in Firefox.
For example, if the data for MyDESCRIPTION is something like:
12222222222222332222222132213123..123131111111111111111111111111111
(no space, its total length will exceed 600).

In IE the line can be warpped to multiple lines within 600 limitation. But in Firefox, the line will be extended and there is no warp, so it will be cut by the display. But printing is fine for FF.
I'm very confused. How can I resolve this problem?

A: You need the following CSS to force the line to break:
td span {
    width: 600px;
    white-space: pre-wrap; /* css-3 */
    white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    word-wrap: break-word; /* Internet Explorer 5.5+ */
}


text:
Q: I have a problem with NullReferenceException in Unity. Can someone help me I just started using Unity and i have a problem with this code. I followed a youtube tutorial and i copied this code but for some reason it doesn't work and it gives me this error: NullReferenceException: Object reference not set to an instance of an object Player.FixedUpdate () (at Assets/Player.cs:28) Any help will be appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    private BoxCollider2D boxCollider;
    private Vector3 moveDelta;
    private RaycastHit2D hit;

    private void start()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }

    private void FixedUpdate()
    {
        float x = Input.GetAxisRaw("Horizontal");
        float y = Input.GetAxisRaw("Vertical");

        moveDelta = new Vector3(x,y,0);

        if (moveDelta.x > 0)
            transform.localScale = Vector3.one;
        else if (moveDelta.x < 0)
            transform.localScale = new Vector3(-1, 1, 1);

        hit = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(0,moveDelta.y), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("Blocking","Actor"));
        if(hit.collider == null)
        {
           transform.Translate(0, moveDelta.y * Time.deltaTime, 0);
        }

        hit = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(moveDelta.x,0), Mathf.Abs(moveDelta.x * Time.deltaTime), LayerMask.GetMask("Blocking","Actor"));
        if(hit.collider == null)
        {
           transform.Translate(moveDelta.x * Time.deltaTime, 0, 0);
        }

    }
}

A: the Start method name first letter must be capital
private void Start()
{
    boxCollider = GetComponent<BoxCollider2D>();
}


text:
Q: convert 16 bit grayscale DICOM image to 8 bit: the correct procedure I have been trying to create an image viewer for DICOM image. My program reads all the 8 bit colour and grayscale image almost correctly. But when I try to open a 16 bit image using the first 8 bits of the image, some parts are missing (pixels which uses 16 bit will be shown as dark instead of whilte). I don't really know how to use the window centre, window width, rescale slop and intercept. Please help me by giving the exact steps to convert 16 bit image to 8 bit image. Also I don't need to view the files which uses any compression technique to store the pixels.  Thanks in advance.

A: About Rescale Slope/Intercept: It is a linear equation, so each pixel value is calculated by
<output pixel value> = <value from pixeldata attribute> * RescaleSlope + RescaleIntercept

This is the input to the windowing equation. The exact windowing equation is here.
About the inverted pixels: The attribute (0028,0103) is probably set to MONOCHROME1 which means: min=white, max=black (or "black bones" convention, i.e. the image contains the attenuation caused by the tissue between tube and detector). This is called the Polarity transformation and happens at the end of the pixel value transformation pipeline.
So your steps go:

*

*apply rescale slope / intercept

*apply windowing

*if PixelRepresentation==MONOCHROME1 -> invert the resulting lookup table

A: There is no a unique response.
You have to keep in mind that 16 bits images (bits stored) contains more information than images with 8 bits images. This information, in general, cannot be displayed all in the same time, you have to change the parameters used to display image.
In DICOM Images there are different DICOM tags that tells you how to interpretate data pixel.
May be there are look-up table, and\or slope-intercept, and\or Window Width-Window Center tags.
I think you have to take a look here
Window width and center calculation of DICOM image


text:
Q: How to get the ID of a Img by the image-path? I've a simple question. I look around but I couldn't find a answer for that.
If I have a lot of simple image-tag with different images, and different ids.

Now i want to access one of these image to change the attributes. For that I need a way to get access to the specific image, but I only know the image-path (scr).
How can I get the id of the image if I only know the "mypathtoimage"?
Thanks a lot.

A: It should be fairly straight-forward when you know the img src. You can use the attribute selectors and get the information:

$(function () {
  var imgSrc = "praveen.png";
  console.log($('[src="' + imgSrc + '"]').get(0).id);
});

The thing I do above is, get the pure DOM element and try to get the id property of it. All the elements have an id property that exposes their id attribute.
You can also do it using pure JavaScript:

var imgSrc = "praveen.png";
console.log(document.querySelector('[src="' + imgSrc + '"]').id);


text:
Q: Store Logged in user data in sonata admin bundle In Sonata Admin Bundle, there is a registration form. Admin and super admin can create user using that registration form. Everything is working. But, now i want to keep trackwho (admin or super-admin id) created this user.So i want to store logged in user id.
in Commercant Entity:
/**
* Set createdBy
*
* @param integer $createdBy
* @return Commercant
*/
public function setCreatedBy($createdBy)
{
 $this->createdBy = $createdBy;

 return $this;
}
/**
* Get createdBy
*
* @return integer
*/
public function getCreatedBy()
{
  return $this->createdBy;
}

With this in sonata admin class i placed this code:
 public function preUpdate($commercant)
{
 $objUser = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();
    if(!empty($objUser)) {
        $commercant->setCreatedBy($objUser->getId());
    }

}

but nothing happen.

A: Try with this:
public function prePersist($commercant)
{
    parent::prePersist($commercant);

    $isSuperAdmin = $this->getConfigurationPool()->getContainer()->get('security.context')->isGranted('ROLE_SUPER_ADMIN');
    $isAdmin = $this->getConfigurationPool()->getContainer()->get('security.context')->isGranted('ROLE_ADMIN');
    if($isAdmin || $isSuperAdmin) {
        $objUser = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();
        if(!empty($objUser)) {
            $commercant->setCreatedBy($objUser->getId());
        }
    }

}


text:
Q: How to force stop an infinit loop Thread Below is an code snippet
ExecutorService executor = Executors.newSingleThreadExecutor();

executor.submit(() -> {
    while (true) System.out.println("1");
});
executor.shutdown();
executor.shutdownNow();

Are there any ways to close the executor from outside? (suggest can`t change the task itself)
like kill -9 in linux

A: Threre are some ways

*

*Add additional condition to loop condition like boolean shouldContinue so setting this to false would exit loop at some point

*If you can write your own features (you own the app) you can write code to list all threads and force given thread to stop using Thread#stop (unsafe) or Thread#interrupt (safer).

*If you dont own the app - like you are running some appication - you can run it with  custom javaagent that will allow you to do the same thing that is in point 2.

Both 2 and 3, with prober integration with eg Sockets, can allow you to do that on already running process from outside of it eg. from CLI

A: Why don't you use a ScheduledExecutorService instead of a normal ExecutorService?
You can capture the Future, that is the task that is being (or going to be) executed and cancel it "from outside" as you want.
public class Example {
    private ScheduledFuture mThread;
    private final ScheduledExecutorService mExecutor = Executors.newScheduledThreadPool(1);

    public void executeForever() {
        mThread = mExecutor.schedule(() -> { while (true) System.out.println("1"); }, 0, TimeUnit.NANOSECONDS);
    }

    public void cancelThread() {
        mThread.cancel(true);
    }
}

Your ScheduledFuture will also inherit all the methods from the Future interface as cancel, get, isCancelled and isDone.
More information about ScheduledFuture: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledFuture.html
More information about ScheduledExecutorService: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
And in that way you don't need to change the task, just the way to execute it.

A: Please read the javadoc for shutdownNow() method. It says very clearly:

There are no guarantees beyond best-effort attempts to stop processing
  actively executing tasks. For example, typical implementations will
  cancel via Thread.interrupt(), so any task that fails to respond to
  interrupts may never terminate.

So what you need to do is to change your submitted task in your code to respond to Thread.interrupt() method. I.e. you need to change your line while (true)towhile (true && !Thread.currentTrhead().isInterrupted()) for more details read javadoc for Thread class in particular methods interrupt(), interrupted() and isInterrupted()

A: If you expose the thread the executor runs you on then you can interrupt it. For me this prints 1 only 4 times suggesting the interrupt is successful.
Remember that this relies on the fact that Thread.sleep and System.out.println are interruptible. If you do not check for Thread.isInterrupted (like they both do) you still may not be able to interrupt the thread.
ExecutorService executor = Executors.newSingleThreadExecutor();

private void test() throws InterruptedException {
    AtomicReference<Thread> thread = new AtomicReference<>();
    Future<Object> task = executor.submit(() -> {
        // Keep track of the thread.
        thread.set(Thread.currentThread());
        try {
            while (true) {
                Thread.sleep(1000);
                System.out.println("1");
            }
        } finally {
            System.out.println("Interrupted: " + Thread.currentThread().isInterrupted());
        }
    });
    Thread.sleep(5000);
    // Interrupt the thread.
    thread.get().interrupt();
    Thread.sleep(5000);
    System.out.println("Press <Enter> to shutdown");
    new Scanner(System.in).nextLine();
    executor.shutdown();
    System.out.println("Press <Enter> to shutdown NOW");
    new Scanner(System.in).nextLine();
    executor.shutdownNow();
}


text:
Q: How compiler is converting integer to string and vice versa Many languages have functions for converting string to integer and vice versa. So what happens there? What algorithm is being executed during conversion?
I don't ask in specific language because I think it should be similar in all of them.

A: To convert a string to an integer, take each character in turn and if it's in the range '0' through '9', convert it to its decimal equivalent. Usually that's simply subtracting the character value of '0'. Now multiply any previous results by 10 and add the new value. Repeat until there are no digits left. If there was a leading '-' minus sign, invert the result.
To convert an integer to a string, start by inverting the number if it is negative. Divide the integer by 10 and save the remainder. Convert the remainder to a character by adding the character value of '0'. Push this to the beginning of the string; now repeat with the value that you obtained from the division. Repeat until the divided value is zero. Put out a leading '-' minus sign if the number started out negative.
Here are concrete implementations in Python, which in my opinion is the language closest to pseudo-code.
def string_to_int(s):
    i = 0
    sign = 1
    if s[0] == '-':
        sign = -1
        s = s[1:]
    for c in s:
        if not ('0' <= c <= '9'):
            raise ValueError
        i = 10 * i + ord(c) - ord('0')
    return sign * i

def int_to_string(i):
    s = ''
    sign = ''
    if i < 0:
        sign = '-'
        i = -i
    while True:
        remainder = i % 10
        i = i / 10
        s = chr(ord('0') + remainder) + s
        if i == 0:
            break
    return sign + s

A: I wouldn't call it an algorithm per se, but depending on the language it will involve the conversion of characters into their integral equivalent. Many languages will either stop on the first character that cannot be represented as an integer (e.g. the letter a), will blindly convert all characters into their ASCII value (e.g. the letter a becomes 97), or will ignore characters that cannot be represented as integers and only convert the ones that can - or return 0 / empty. You have to get more specific on the framework/language to provide more information.

A: String to integer:
Many (most) languages represent strings, on some level or another, as an array (or list) of characters, which are also short integers.  Map the ones corresponding to number characters to their number value.  For example, '0' in ascii is represented by 48.  So you map 48 to 0, 49 to 1, and so on to 9.
Starting from the left, you multiply your current total by 10, add the next character's value, and move on.  (You can make a larger or smaller map, change the number you multiply by at each step, and convert strings of any base you like.)
Integer to string is a longer process involving base conversion to 10.  I suppose that since most integers have limited bits (32 or 64, usually), you know that it will come to a certain number of characters at most in a string (20?).  So you can set up your own adder and iterate through each place for each bit after calculating its value (2^place).


text:
Q: Appending tuples to a Pandas dataframe and "cannot concatenate" - what am I doing wrong? I want to fill up a dataframe from a scraping loop. Say I created an empty DF with four columns.
df = pd.DataFrame(columns=['A','B','C','D'])

Then the loop to fill it looks like this:
for i in range:
  a = x['col1'][i]
  b = x['col2'][i]
  c = x['col3'][i]
  d = x['col4'][i]
  tup = (a,b,c,d)
  df = df.append(tup)

This is the error I get, though:
TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

What am I doing wrong?

A: You can add dictionary instead of tuple:
df = pd.DataFrame(columns=["A", "B", "C", "D"])

for i in range(10):
    a = i + 1
    b = i + 2
    c = i + 3
    d = i + 4
    d = {"A": a, "B": b, "C": c, "D": d}
    df = df.append(d, ignore_index=True)

print(df)

Prints:
    A   B   C   D
0   1   2   3   4
1   2   3   4   5
2   3   4   5   6
3   4   5   6   7
4   5   6   7   8
5   6   7   8   9
6   7   8   9  10
7   8   9  10  11
8   9  10  11  12
9  10  11  12  13

But using .append like this is anti-pattern. You should see FutureWarning that this method will be removed in future version of pandas.
Instead, create dataframe in one go and skip creating empty dataframe at the beginning:
df = pd.DataFrame(
    [{"A": i + 1, "B": i + 2, "C": i + 3, "D": i + 4} for i in range(10)]
)


text:
Q: Find or replace a string in word documents in a given folder How to find or replace a word in the documents in the given folder
Is there is a tool or any script is available to do that?
Thanks.

A: Finding text is straightforward. There are several ways to do it, including using the Windows search utility. Here's an article with several methods: Search through the content of multiple Word documents
To find and replace, you can use a free text editor like Notepad++. It has a very good Find in Files utility. There are many other utilities that can do this, some paid and some free.
Finally, you can write a VBA macro that will find and replace all documents in a folder. Here's a page with a macro listing that does that: How to Find and Replace Contents in Multiple Word Documents


text:
Q: Running unit test target on XCode9 returns "Early unexpected exit" error I'm learning how to add unit tests to an objective-c project using XCode9.  So I've created a command line project from scratch called Foo and afterwards I've added a new target to the project called FooTests.  Afterwards I've edited Foo's scheme to add FooTests.  However, whenever I run the tests (i.e., menu "Product" -> "Tests" ) XCode9 throws the following error:
Showing All Messages
Test target FooTests encountered an error (Early unexpected exit, operation never finished bootstrapping - no restart will be attempted)

However, when I try to run tests by calling xcode-build from the command line, it seems that all unit tests are executed correctly.  Here's the output;
a483e79a7057:foo ram$ xcodebuild test -project foo.xcodeproj -scheme foo
2020-05-15 17:39:30.496 xcodebuild[53179:948485]  IDETestOperationsObserverDebug: Writing diagnostic log for test session to:
/var/folders/_z/q35r6n050jz5fw662ckc_kqxbywcq0/T/com.apple.dt.XCTest/IDETestRunSession-E7DD2270-C6C2-43ED-84A9-6EBFB9A4E853/FooTests-8FE46058-FC4A-47A2-8E97-8D229C5678E1/Session-FooTests-2020-05-15_173930-Mq0Z8N.log
2020-05-15 17:39:30.496 xcodebuild[53179:948484] [MT] IDETestOperationsObserverDebug: (324DB265-AD89-49B6-9216-22A6F75B2EDF) Beginning test session FooTests-324DB265-AD89-49B6-9216-22A6F75B2EDF at 2020-05-15 17:39:30.497 with Xcode 9F2000 on target <DVTLocalComputer: 0x7f90b2302ef0 (My Mac | x86_64h)> (10.14.6 (18G4032))
=== BUILD TARGET foo OF PROJECT foo WITH CONFIGURATION Debug ===

Check dependencies

=== BUILD TARGET FooTests OF PROJECT foo WITH CONFIGURATION Debug ===

Check dependencies

Test Suite 'All tests' started at 2020-05-15 17:39:30.845
Test Suite 'FooTests.xctest' started at 2020-05-15 17:39:30.846
Test Suite 'FooTests' started at 2020-05-15 17:39:30.846
Test Case '-[FooTests testExample]' started.
Test Case '-[FooTests testExample]' passed (0.082 seconds).
Test Case '-[FooTests testPerformanceExample]' started.
/Users/ram/development/objective-c/foo/FooTests/FooTests.m:36: Test Case '-[FooTests testPerformanceExample]' measured [Time, seconds] average: 0.000, relative standard deviation: 84.183%, values: [0.000006, 0.000002, 0.000001, 0.000002, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100
Test Case '-[FooTests testPerformanceExample]' passed (0.660 seconds).
Test Suite 'FooTests' passed at 2020-05-15 17:39:31.589.
     Executed 2 tests, with 0 failures (0 unexpected) in 0.742 (0.743) seconds
Test Suite 'FooTests.xctest' passed at 2020-05-15 17:39:31.589.
     Executed 2 tests, with 0 failures (0 unexpected) in 0.742 (0.744) seconds
Test Suite 'All tests' passed at 2020-05-15 17:39:31.590.
     Executed 2 tests, with 0 failures (0 unexpected) in 0.742 (0.745) seconds
** TEST SUCCEEDED **

Does anyone know how to add unit tests to an xcode9 project for a command line application?  If you happen to know, what's the right way of doing this and what am I doing wrong?


text:
Q: Correct mapping to interface when getting data from a given URL I am new to Angular and I am trying to map the returned json to my interface but failed.
Here's the link to the code I have.

*

*Stackblitz

*Json URL

A: You dont need to use map since you response is object and as i see you want to map data property from that.
One way to do it would be
  getTestData(): Observable<TestObject>{
    const url = 'https://api.myjson.com/bins/11x4bx';

    // return this.http.get(url).pipe(
    //   map(response => ((response || {} as any).data || []).map(testData => this.mapTest(testData))));

    return this.http.get(url).pipe(
      map((resp: any) => {
          return <TestObject> {
            id: resp.data.id,
            view: resp.data.view,
            resourceName: resp.data.resourcename,
            loadCapacity: resp.data.loadcapacity
          }
      })
      );

  }

Cleaner way
  getTestData(): Observable<TestObject>{
    const url = 'https://api.myjson.com/bins/11x4bx';
    return this.http.get(url).pipe(pluck('data'));
  }

A: When you are not sure about how to build an interface for your response, you can use JSON2TS
declare module namespace {

    export interface Meta {
        entityName: string;
    }

    export interface Data {
        id: string;
        view: string;
        startdate: string;
        enddate: string;
        erp: string;
        loadcapacity: string;
        userid: string;
        resourceid: string;
        resourcename: string;
        userdatalimitationid: string;
        requestleaveforself: boolean;
        bookforself: boolean;
        lastmodified: string;
    }

    export interface RootObject {
        meta: Meta;
        data: Data;
    }

}

A: Here is how you should change your code. You should use map when your data is an array. Your response data is just an object
 getTestData(): Observable<TestObject>{
    const url = 'https://api.myjson.com/bins/11x4bx';

    return this.http.get(url).pipe(
      map((res: any) => {
        console.log(res)
          return {
            id: res.data.id,
            view: res.data.view,
            resourceName: res.data.resourcename,
            loadCapacity: res.data.loadcapacity
          } as TestObject
      })
    );
  }

A: You are trying to use map twice.
The first map from RxJS is to do data transformation. In this case you are sending through the pipe an Object, not an array. So you don't need  to use the second map since that's a method to iterate through an array.
 return this.http.get(url).pipe(
      map((resp: any) =>
           ({
            id: resp.data.id,
            view: resp.data.view,
            resourceName: resp.data.resourcename,
            loadCapacity: resp.data.loadcapacity
          }) as TestObject)
      );

  }

Your wiki:
https://stackblitz.com/edit/angular-httpclient-get-1dg2r2
FYI in reactive programming is better to do the Declarative approach
wait, what is that?
testObject$ = this.http.get(url).pipe(
      map((resp: any) =>
           ({
            id: resp.data.id,
            view: resp.data.view,
            resourceName: resp.data.resourcename,
            loadCapacity: resp.data.loadcapacity
          }) as TestObject)
      );

  }

then in your component you call it testService.testObject$
You see what I did I got rid of the method and here's why:

*

*-Leverage the power of rxjs observables and opeartors

*-effectively compatible streams

*-easy share observables

*-readily react to user action

@Deborah Kurata mentioned this in his RxJS course (she is a GDE on Angular)


text:
Q: Rake task to list all migrations for a given model On the terminal, is there a rake task to list all the migrations which have been run on a particular model? If not, how do I go about building one?
When I ran rake -T, rake db:migrate:status seemed to be the right answer, but it gave me Migration Name as one of the columns. And though the name Add logo to company does indicate Company model, not all migrations have such explicit names. Case in point being Change data type for content. I have 400 odd migration files, so this feature would be really helpful.
So, the ideal output would be:
database: abcd_development

 Status   Migration ID    Migration Name     Model Name
----------------------------------------------------------

Thanks!

A: If you've been sticking with the migration naming conventions, you could just pass the output of rake db:migrate:status through grep:
rake db:migrate:status | grep 'compan'

This isn't perfect, though - migration names aren't required to have anything to do with what they actually do - a migration might add the column 'name' to the 'companies' table and be named EvacuateWeaselTubes and still run just fine.
If you wanted to build a task that could overcome this problem, it would have to parse each of the migration files to see what it changed. Since there's many ways to specify a change in a migration (add_column, a create_table block, or calling execute('CREATE whatever'), for instance), you'd probably want to search for mentions of Model.table_name, then check the schema_migrations table to see if it had been run.


text:
Q: get objects that match a key value from a nested object that is quoted I have a list of JSON objects with this format
[
 {
    "uuid": "2e08c71c-56af-4c1d-9677-0aad7bf38536",
    "name": "img-s3",
    "summary": "",
    "retention_name": "month",
    "retention_uuid": "beae2f1a-10e9-4b53-b9b1-baf823624ff2",
    "expiry": 2678400,
    "schedule_name": "daily",
    "schedule_uuid": "baca1a64-b506-4789-83c8-653573f2b99f",
    "schedule_when": "daily 2am",
    "paused": false,
    "store_uuid": "d91fd7b6-4c39-4f73-aa44-8ec55f52da65",
    "store_name": "default",
    "store_plugin": "s3v8",
    "store_endpoint": "{\"access_key_id\":\"xxxx\",\"bucket\":\"images-c4\",\"s3_host\":\"s3.amazon.com\",\"secret_access_key\":\"yyy\",\"signature_version\":\"2\",\"skip_ssl_validation\":true}",
    "target_uuid": "991c7aa2-cdd3-4f90-bb28-1431c99f8fc8",
    "target_name": "sc-asd",
    "target_plugin": "mysql",
    "target_endpoint": "{\"mysql_database\":\"users\",\"mysql_host\":\"10.10.22.49\",\"mysql_password\":\"password\",\"mysql_port\":\"3306\",\"mysql_user\":\"user\"}",
    "agent": "127.0.0.1:3030"
}
...
]

I need to obtain only the objects using storege_plugin: "s3v8" and that in the "quoted" value object of storage_endpoint the key signature_version is 2
To find the object having storage_plugin: "s3v8", and store_endpoing != null I am using this:
$ command | jq '.[] | select(.store_plugin == "s3v8" and .store_endpoint != null)'

But the problem I have now is that the value of store_endpoint is quoted and I only need to get results based on the value of a key, in this case, signature_value
To test how to unquote and search for the value I am trying this:
$ echo "{\"access_key_id\":\"xxxx\",\"bucket\":\"images-c4\",\"s3_host\":\"s3.amazon.com\",\"secret_access_key\":\"yyy\",\"signature_version\":\"2\",\"skip_ssl_validation\":true}" \
| jq -r 'select(.signature_version == "2")'
{
  "access_key_id": "xxxx",
  "bucket": "images-c4",
  "s3_host": "s3.amazon.com",
  "secret_access_key": "yyy",
  "signature_version": "2",
  "skip_ssl_validation": true
}

But would like to know how could I "merge" this options so that I could get a list of objects that have a set of required keys but that depends on a nested key stored on a quoted object.

A: You need to use the fromjson construct on the nested JSON field as below. The fromjson is not so well documented in the official documentation but it allows you to parse JSON texts into values for use in filters.
.[] | select((.store_plugin == "s3v8" and .store_endpoint != null) and (.store_endpoint | fromjson | .signature_version == "2") )

jqplay.org - URL


text:
Q: Performance critical GUI application (windows,linux) I've been tasked with updating a series of applications which are performance critical VB.NET apps that essentially just monitor and return networking statistics. I've only got three requirements: convert it to C#, make it fast, and make it stable
One caveat is that we "may" migrate from a .NET platform to linux "soon"
I will be responsible for maintaining these apps in the future so I'd like to do this right. I have decided to refactor these apps according to the MVP pattern so that I can properly unit test the hell out of this bad boy. But I was also thinking since I was using MVP that I could also do the computationally expensive stuff in native C/C++ code while the GUI would be done with .NET forms, or Qt or whatever.
questions:

*

*does it make sense to do a GUI in winforms but the expensive stuff in native, unmanaged C/C++ ?

*any recommendations for a good cross platform windowing kit that would fit for the scenario described above?

A: 1) Premature optimization is evil.  Implement your "expensive stuff" in C# and see if you need to refactor it.  Or, at least set up a test that will allow you to determine this.
2) Yowch.  Cross platform UI.  I wouldn't put up with the "may" stuff.  Nail the weasels down; how can you possibly make design decisions without knowing what you're designing?  If you go with a pure .NET implementation, will they complain if you have to (at a minimum) refactor it to work in Mono?  If you create it in Java, will they be annoyed that it looks ugly as hell and users complain that they can't find their .exe file amongst all those .jars?

A: First off, I would put some time into trying out a few VB.NET to C# converters.  You're basically porting syntax, and there's no reason to do that by hand if you don't have to.  Sure, you might have to clean up what comes out of the converter, but that's way better than a by-hand conversion.
Now, as for your questions:

1) does it make sense to do a GUI in winforms but the expensive stuff in native, unmanaged C/C++ ?

Not yet.  Wait until you've done the conversion, and then find out where you're actually spending your time.  There's no reason to jump into mixing C/C++ with C# until you find out that it's necessary.  You may find that dropping into unsafe C# is sufficient.  Even that may be unnecessary.  You might just need to optimize algorithms.  Find out what your bottlenecks are and then decide how to fix them.

2) any recommendations for a good cross platform windowing kit that would fit for the scenario described above?

I'd be looking into mono for sure.  That's really the best you can do if you're going with C#.  It's pretty much either mono or another rewrite in another language when/if you move to Linux.

A: 1) Not necessarily. I think it would be more correct to say that it's probably worthwhile writing your backend code in C++, regardless of the performance implications. Even though you can't tie your higher-ups down on the platform switch, it would be prudent of you to make preparations for that eventuality, since management types tend to change their mind alot without good reason (or warning); even if they decide not to switch now, that doesn't mean that they won't decide to switch six months from now. Writing your logic in C++ now, knowing that it's a possibility, though more difficult, may make your life significantly easier later.
2) Not really. There are "solutions" like wxWindows and GTK#, but often they're buggy, or difficult to get working properly, or they lack something important on one platform or another. They also usually lock you into a lowest-common-denominator UI (ie, general controls work fine but you can forget about ever doing something interesting -- WPF, for example -- with it). UIs are easy to write, so I think if you write your logic in something that's portable, it should be a trivial matter to knock together several platform-specific UIs.

A: For the first question, it is really hard to say if it would make sense as it would likely depend upon what sort of performance you need to be getting. I personally haven't seen any system wide slow downs due to the GUI in properly designed GUIs using WinForms so I don't see why it would should cause any problems, and in all likelihood it would make your life easier in regards to the GUI.
As for your second question, if you are going to be moving to another platform at some point - you want to take a look at the libraries that have been implemented by Mono (http://www.mono-project.com/Main_Page), this should also cover most of your needs in regards to cross platform windowing as it supports WinForms and GTK#.

A: No, it does not make sense to do the "expensive stuff" in C/C++. The potential (and most likely minor) performance improvements never, ever outweigh your productivity being an abject, sick joke when compared to C#. Really. It's not even close.
Read through this (and all posts referenced within):
http://blogs.msdn.com/ricom/archive/2005/05/10/416151.aspx

A: You might want to look into using Mono. This is a open source version of .NET that runs on many plateforms...Linux,Mac, Solaris, Windows, etc..
Now about coding your expensive stuff in C/C++. Here's an article that does a very good
job explaining the differences between C/C++ & C# performance.

A:
And again, let me emphasize, the C++ stuff is veerrrryyyy expensive. Would it make sense to do what I mentioned above? (.NET forms hiding heavy lifting C++)

As noted before, I personally haven't noticed any system wide slow downs due to WinForms in applications written in both VB.NET and C#. However, if the application is truly performance intensive then you might notice a slight slow down if you wrote everything in C# due to it being complied into CIL (http://www.cl.cam.ac.uk/research/srg/han/hprls/orangepath/timestable-demo/). As such, writing the GUI in a language such as C# will likely make that part of the development a bit easier which would give you more time to work on the critical parts of the code. The only catch-22 here is might notice some slow downs due to the calls to the C/C++ code from the C# code; however, this is likely very unlikely.

A:
1) does it make sense to do a GUI in winforms but the expensive stuff in native, unmanaged C/C++ ?

Most likely not. Unless you're communicating with a lot of other native C dlls or so on, C# is likely to be between 5% slower to 5% faster than C++ (std::string really kills you if you're using it)

2) any recommendations for a good cross platform windowing kit that would fit for the scenario described above?

If it's just some simple forms with buttons, mono will likely be able to run them unmodified. It's support for .NET WinForms is pretty good these days. It is however, butt ugly :-)

A: I might be misunderstanding the issue, but if it is a network monitoring system, why isn't it written as a "dedicated" Windows service?
VB.NET shouldn't be much slower than C#. I'm not 100% certain if there is any big differences in the generated IL-code, but the only advantage (and justifiable reason to rewrite it in C#) I could think of (except that C# have a nicer syntax and some other goodies) is the use of unsafe code block that could speed things up a little.

A: gtk-sharp is a pretty nice cross platform toolkit.

Gtk# is a Graphical User Interface Toolkit for mono and .Net. The project binds the gtk+ toolkit and assorted GNOME libraries, enabling fully native graphical Gnome application development using the Mono and .Net development frameworks.

A: The c/c++ stuff may end up being a good idea, but right now YAGNI. Same with the Linux stuff. Ignore it, you ain't gonna need it until you need it.  Keep it simple. Unit test the hell out of it, as you say.  Get the code working and evolve the design from there.

A: I had similar dilemma some time back, while trying to find out a best way to develop a PC based H/W Testing tool (which obviously means "with UI options") that interacts with an embedded hardware (via PCMCIA interface).
The bottleneck was that the testing should run at maximum deviation of 10ms from the intended time specified by the tester.
E.g: If the tester creates the following test sequence:

*
1. Remotely activate the H/W
2. Wait for 50ms delay.
3. Read an H/W information.
the delay mentioned in step 2 should not be > 60ms.
 I chose C++ WIN32 application as my back-end and VC++ 2005 Winform (.NET platform) for UI development. Detailed information on how to interface these two is available in msdn
I segregated the system like this:
In VC++ .NET:

*
1. UI to have complete information about the H/W (read via back-end application) and to control the H/W on demand. (Buttons, combo-box etc.. etc..)
2. UI to run time critical test sequences (as mentioned in the above example).
3. Gathering these information and building a stream (File-stream) in a Time-linear format (i.e, in the precise order of steps in which it has to be performed).
4. Triggering and hand-shaking mechanism (by redirecting standard input and standard output) with WIN32 back-end application. The common resources will be the File-streams.

In C++ WIN32:

*
1. Interpreting the Input File-Stream.
2. Interaction with H/W.
3. Gathering information from H/W and putting it in its Output File-Stream.
4. Indication of test completion to UI (via redirected standard output).
The complete system is up and running. It seems to be pretty stable. (Without the timing deviation mentioned above).

Note that, the testing PC we use is solely for the H/W Testing purpose (it had just the UI running on it, with no auto-updates, virus scan etc.. etc.. ).


text:
Q: Add header and text color in HTML table email body based on disk usage condition using Python I am sending out an html table in an email body using python. The html table consists of disk usage and I need to add the header (first row) and text in red in the table when disk usage is above 80 percent.
This is the code I'm using that works to get the email with colouring the text but it does not include the headers (server,total size, total data, usage in %):
me = 'noreply@automationtest.com'

server = 'some smtp server'
you = 'email@someautomation.com'

text = """
{table}
"""

html = """

Hi,

sometext

{table}

sometext

Regards

someme

"""

with open('files/file.csv') as input_file:
    reader = DictReader(input_file)
    data = list(reader)
    for row in data:
      row['Usage in %'] = pd.to_numeric(row['Usage in %'])
      if row['Usage in %'] >= 80:
      row['Usage in %'] = "
%s
"%row['Usage in %']

text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid"))

html = html.format(table=tabulate(data, headers="firstrow", tablefmt="unsafehtml"))
message = MIMEMultipart("alternative", None, [MIMEText(text), MIMEText(html,'html')])
print(html)

message['From'] = me
message['To'] = you
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(me, password)
server.sendmail(me, you, message.as_string())
server.quit()

I'm getting the below output with text color but without the header:

Expected output:

Any help is greatly appreciated.

A: In pandas 1.3.0 and newer, the most appropriate way is to use the pandas Table Visualization and create a Subclass
Create a folder "templates" and two files "myhtml.tpl" and "mystyles.tpl"
In myhtml.tpl put any additional HTML code needed:
{% extends "html_table.tpl" %}
{% block table %}

Hi,

sometext

{{ super() }}

sometext

Regards

someme

{% endblock table %}

In mystyles.tpl add any additional styles:
{% extends "html_style.tpl" %}
{% block style %}
{{ super() }}

{% endblock style %}

(Code to generate this file structure is at the end of this answer)

We can now generate a Styler subclass with from_custom_template
import numpy as np
import pandas as pd
from pandas.io.formats.style import Styler

# Build Styler Subclass from templates
MyStyler = Styler.from_custom_template(
    "templates",  # Folder to Search
    html_table="myhtml.tpl",  # HTML Template
    html_style='mystyles.tpl'  # CSS Template
)
# trim extra whitespace from HTML
MyStyler.env.trim_blocks = True

# Read in CSV
df = pd.read_csv('files/file.csv')

# Add styles using Styler apply and render to_html
html = MyStyler(df).apply(
    lambda s: np.where(s >= 80, 'color: red', None), subset='Usage in %'
).format(
    # Apply format string (remove insignificant zeros)
    formatter='{:g}', subset='Usage in %'
).hide_index().to_html(doctype_html=True)

print(html)

The resulting html string is something like:

<!DOCTYPE html>

  <meta charset="utf-8">

Hi,

sometext

        Server
        Total size
        Total Data in
        Usage in %

        A
        100
        25
        25

        B
        100
        20
        20

        C
        100
        85
        85.6

        D
        100
        90
        90.8

sometext

Regards

someme

The more naïve way to solve this problem would be to manipulate html strings directly with formatting, however, this can lead to poorly formed html:
import numpy as np
import pandas as pd

html = """

Hi,

sometext

{table}

sometext

Regards

someme

"""

# Read in CSV
df = pd.read_csv('files/file.csv')

# Add styles using Styler apply and render to_html
table_html = df.style.apply(
    lambda s: np.where(s >= 80, 'color: red', None), subset='Usage in %'
).format(
    # Apply format string (remove insignificant zeros)
    formatter='{:g}', subset=['Total Data in', 'Usage in %']
).hide_index().to_html()

html = html.format(table=table_html)

print(html)

Which results in the following html (notice the misplaced style element):

Hi,

sometext

      Server
      Total size
      Total Data in
      Usage in %

      A
      100
      25
      25

      B
      100
      20
      20

      C
      100
      85
      85.6

      D
      100
      90
      90.8

sometext

Regards

someme

Simple script to build the templates folder and the two template files:
import pathlib

# Code to generate the Templates and folder
pathlib.Path('./templates').mkdir(exist_ok=True)
with open('./templates/myhtml.tpl', 'w') as f:
    f.write('''
{% extends "html_table.tpl" %}
{% block table %}

Hi,

sometext

{{ super() }}

sometext

Regards

someme

{% endblock table %}
'''.strip())
with open('./templates/mystyles.tpl', 'w') as f:
    f.write('''
{% extends "html_style.tpl" %}
{% block style %}
{{ super() }}

{% endblock style %}
'''.strip())

The files/file.csv content:
Server,Total size,Total Data in,Usage in %
A,100,25,25
B,100,20,20
C,100,85,85.6
D,100,90,90.8


text:
Q: Django - how to get inputs from the user and return queryset based by I want to make kind of a reporting tool for end users, Like if we have a book model in the database, the user will select the author to filter by and will receive a filtered queryset
what is the proper way to do this?
Is this a proper one?: 1- a form+template | 2- filter the queryset by the inputs | 3- return the queryset
if this a right approach how should I get the inputs in the code for filtering? should I use get and post?


text:
Q: Show that $\mathbb{Z}/a \otimes \mathbb{Z}/ab$ is not zero. This question is motivated by the fact that, if $\gcd(a,b) = 1$ then $\mathbb{Z}/a \otimes \mathbb{Z}/b$ is zero tensor product.

I would like to show that $\mathbb{Z}/a \otimes \mathbb{Z}/ab$ is not zero.

My thought is that try to use contradiction. Suppose $M= \mathbb{Z}/a \otimes \mathbb{Z}/ab$ is zero tensor product, then let $P$ be some $\mathbb{Z}$-module with homomorphism $f$, $P$ will have to be zero. This is due to the universal property of tensor product. More specifically, for any $(x,y)\in \mathbb{Z}/a \times \mathbb{Z}/ab$,
$$f(a,b)=\tilde{f}\circ \phi(a,b) = \tilde{f}(0)=0.$$
where $\phi$ is the bilinear map comes with $M$.
So it suffices to find such a bilinear map and a module that, definitely is non zero. But I am having trouble finding that.

A: How about $P=\mathbb Z/a\mathbb Z$ and $f(x,y)=xy$?
(More explicitly: $f(x,y)=x\psi(y)$ where $\psi$ is the natural homomorphism $\mathbb Z/ab\mathbb Z\to \mathbb Z/a\mathbb Z$).

A: This has nothing to see with $\mathbf Z$: for any (commutative) ring $R$, and ideals $I,J\subseteq R$, one has
$$R/I\otimes_R R/J\simeq R/(I+J).\tag{1}$$
Furthermore, if $J\subseteq I$, $I+J=I$, so that
$$R/I\otimes_R R/J\simeq R/I.$$
A proof of $(1)$:
For any $R$-module $M$, one has $\;R/I\otimes_RM\simeq M/IM$. In particular
$$R/I\otimes_R R/J\simeq \simeq (R/J)/(I\cdot R/J)=(R/J)/\bigl((I+J)/J\bigr)\simeq R/(I+J)$$
by the Third isomorphism theorem.

A: Different approach: For $m,n \in \mathbb Z$ do you know what $\mathbb Z/m\mathbb Z \otimes_{\mathbb Z} \mathbb Z/n\mathbb Z$ is isomorphic to?


text:
Q: Getting just the first letter of the user input in C++ I wrote a console program which is getting some spesific character inputs from user to perform operations. Program asks for an input, user types "i" for insert or "r" for remove etc.. The problem is when user types more than one letter, the program behaves weird.
char selection;
bool finish = false;
while (!finish){
    print_menu();
    cin >> selection;
    finish = perform_operation(selection);
}

This is how i get the user input. And i want to get just the first character of the user input and ignore the rest of them, and behave so on. How can i do it?
Note: I'm not allowed to use "string" class, but i can use every str functions!
Thanks for help!
Another case:
What if i would like to get spesific amount of characters? For example: the user inputs a name which is 10 characters but i want to get just the first 5 characters. What should i do?

A: If you want to read one character, read one character.
Don't have a loop that reads as many characters as possible.
char selection;
print_menu();
if (cin >> selection)
   finish = perform_operation(selection);
else
   throw std::runtime_error("Bad input!");

I've added basic error checking to your I/O operation for good measure.

A: for getting just one character you can use also this:
char selection;
cin >> selection; // input: abcd
cin.clear();
fflush(stdin);
printf("you entered the character: %c", selection); //selection='a'
// and nothing remained in input stream. you can safely `cin>>` again :]

You can apply this code to your existing one.

In order to get a specific number of charter you can use below sample:
char* TakeNCharacterFromInput(int _count)
{
    char *input = new char[_count+2];
    std::cin.getline(input, _count+1);
    cin.clear();
    fflush(stdin);
    return input;
}

int main(int args, char* argv[]) {
    char *in1 = TakeNCharacterFromInput(5);//input:123456789 => in1:12345
    char *in2 = TakeNCharacterFromInput(2);//input:123456789 => in2:12
    char *in3 = TakeNCharacterFromInput(1);//input:123456789 => in3:1
    delete[] in1;
    delete[] in2;
    delete[] in3;
}

A: Ignore everything except the first character until the next line break:
char selection;
bool finish = false;
while (!finish){
    print_menu();
    cin >> selection;
    finish = perform_operation(selection);
    cin.ignore(10000, '\n'); // Totally arbitrary large number.
}

A: skip always reprinting the menu
print_menu();
then use a function that waits for ENTER:

Several ways to do so, here are some possible one-line approaches:

*

*Use getch() (need #include ).

*Use getchar() (expected for Enter, need #include ).

*Use cin.get() (expected for Enter, need #include ).

*Use system("pause") (need #include ).

see also this thread C++ wait for user input


text:
Q: OOB score for single tree of a Random Forest classifier in sklearn The oob_score_ method  is available in sklearn's for the full RandomForestClassifier ensemble. However I am interested in the OOB score of every tree of the ensemble. It seems to me that such information gets lost in the averaging step performed. As a consequence, what is reported in the oob_score_ and oob_decision_function_ methods don't have the information I need.
In other words, instead of taking the average OOB score across trees given a single sample, I am interested in the average OOB error of a single tree across the left-out samples. I am aware that such average will be performed across differing samples but this is not an issue.


text:
Q: Which attribute controls the actual data submitted in a selectOneMenu? <h:outputText value="Category: " />
<p:selectOneMenu value="#{categoryController.selectedCategory}">
    <f:selectItem itemLabel="Select One" itemValue="" />
    <f:selectItems value="#{categoryController.categories}" var="category" itemLabel="#{category.name}" itemValue="#{category.categoryID}"/>
</p:selectOneMenu>

I have a form which lets users enter questions for a quiz. Categories can also be entered, and 1 category has many questions.
At first, the form allowed category ID's to be entered. Now, to make it a little more sophisticated, I instead populate a selectOneMenu with categories to be chosen from. The menu populates fine.
The problem: selecting a category from this list should mean selecting it's ID underneath so that a question entity refers to the correct category ID as always has been done. I was under the impression that the attribute
itemValue="#{category.categoryID}

should allow this. But this does not seem to be working, as question entities aren't appearing as added in my database when a category is chosen. I also tried
questionController.newQuestion.categoryID

as newQuestion has been working for text fields in the form. But it seems that the desired result still isn't achieved this way.
Is itemValue the attribute I should be using? And if not, then which?
UPDATE:
So still pretty stuck but here is some code showing how categories are implemented.
The category controller class:
public class CategoryController extends BasePageController {

@Autowired
private ICategoryRepository categoryRepository;

private List<Category> categories;

private Category newCategory = new Category();

private Category selectedCategory = new Category();

private Category[] selectedCategories;

and the Category class:
public class Category {

private int categoryID;
private String name;

A: As the entitiy which you would like to create and for which you are selecting a category is a question you have to set the values on questionController.newQuestion. I.e. you would have to set the categoryId on questionController.newQuestion.categoryID.
Which you can achieve by setting the value of p:selectOneMenu to that. So try the following for the p:selectOneMenu-open-tag:
<p:selectOneMenu value="#{questionController.newQuestion.categoryID}">


text:
Q: How to add a link "parent/child" between 2 certain already created work item - Azure Boards Currently, we use Veracode in our ci enviroment(Azure Pipelines) for security check. Veracode has a azuredevops plugin, that creates flaws as work items(either bug, task etc) in azure boards. However, we created a certain epic, "Security Issues", and we expect that there's a way to link via pipeline, a already created work item to it as a parent/child.
I've been searching for methods (first time working with Azure API's), and I didnt found any specific way to achieve this integration( I did see this, but in this case, they create a work item, instead of linking 2 that already exist How to add work item as child to parent?).
I did talk to Veracode team, however this feature isn't currently available. We can add custom Tags however.
TL:DR: How can I, via pipeline automation, query for certain work items in azureboards, and link them as a parent/child to a certain created epic.
Thanks in advance!

A: You can use update work item REST API to add a link between two work items. Since you are using REST API in the pipeline, you can use run your REST API in a PowerShell task. Here is the sample of adding a child link to an existing work item:
$organization = "{Organization name}"
$project = "{Project name}"
$pat = "{PAT}"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
$url = "https://dev.azure.com/$organization/$project/_apis/wit/workitems/{Work item id}?api-version=5.1"
$contentType = "application/json-patch+json"
$body= @'
[
  {
    "op": "add",
    "path": "/relations/-",
    "value": {
      "rel": "System.LinkTypes.Hierarchy-Forward",//Add a child link
      ##"rel": "System.LinkTypes.Hierarchy-Reverse",//Add a parent link
      "url": "https://dev.azure.com/{Organization name}/{Project name}/_apis/wit/workItems/{Work item id}"
    }
  }
]
'@
Invoke-RestMethod -Uri $url -Method PATCH -ContentType $contentType -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $body

You can find the Work Item Relation Types with this API.
If you want to query the work items, you can try to use Wiql. Please refer to this example.


text:
Q: How can I access the value inside an HTML span? There's this pack simulator on a website I frequent. You are randomly given 10 basketball players in the game with various values on how much they are worth. When you load the page, the cards are face down so you have to click on each one to "reveal" the card and add to your total. The idea is to maximize the value of each pack.
I figured out that the flipping is all show and the total pack score is actually there as soon as you load the page. So I'm trying to write a greasemonkey script to refresh the page until the value is above a certain threshold. I can get to the span with this code:
document.getElementsByClassName("pack-score")[0];

which gets me a span that looks like this:
<span class="pack-score" data-score="12352">

So how would I access the data-score value inside that span, so I can then use it as a value for the code logic?

A: document.getElementsByClassName("pack-score")[0].getAttribute('data-score')

or in jquery
$(".pack-score").find('span').data('score')


text:
Q: Symbolic links in php I am trying to create a symbolic link in php, on linux
if i create the link manually with ln -s targetfile linkfile it works just fine
if i try
<?php

symlink($targetfilefullpath, $linkfilefullpath) ;
?>

nothing happens, there is no link
also if i try
<? php
shell_exec("ln -s ".$targetfilefullpath." ".$linkfilefullpath);
?>

also nothing happens, there is no link
all the targetfiles and folders have chmod 777
what could be wrong ?


text:
Q: How to create an executable for Ruby console application I'm writing a simple console app, but instead of distributing it as a script (somefile.rb), I want it as a binary file, like an executable.
Any idea?

A: Embedded Ruby (or better mruby) into C or C++
Simple one file with script as text.
Here is example for mruby mruby.


text:
Q: Pm2 Restart Node.js Process After Changing node_args If a Nodejs process was started from reading a PM2 JSON config file pm2.json file containing:
    {
      "name": "foobar",
      "script": "./foobar.js",
      "args": "-e baz",
      "node_args": "--max_old_space_size=1024"
    },

and node_args was modified resulting in
    {
      "name": "foobar",
      "script": "./foobar.js",
      "args": "-e baz",
      "node_args": "--max_old_space_size=2048"
    },

will the new node_args be applied by simply restarting the process with pm2 restart <id>?
Or do we have to do pm2 delete <id> followed by pm2 start pm2.json?

A: Any action (start, restart, reload, stop) applied to the PM2 JSON configuration file will be passed to the processes.if you restart, all defined processes within that file get restarted immediately with new args.


text:
Q: Read data in JSON format asp.net View in MVC I wonder what I'm doing wrong, already tested several tutorials without success, the data comes without the formatting that is in the script, in this example I have in my Controller,
public JsonResult GetDados()
{
    List<Object> resultado = new List<object>();
    resultado.Add(new
    {
        Nome = "studying Json",
        URL = "https://stackoverflow.com/"
    });
    resultado.Add(new
    {
        Nome = "Json ",
        URL = "https://stackoverflow.com/"
    });
    resultado.Add(new
    {
        Nome = "Mr. Json",
        URL = https://stackoverflow.com/"
    });
    return Json(resultado, JsonRequestBehavior.AllowGet);
}

View :

The correct display of the result would be:
Nome: studying Json | Url: https://stackoverflow.com/
Nome: Json | Url: https://stackoverflow.com/
Nome: Mr. Json | Url: https://stackoverflow.com/
I have this result
see that in document.writeln script, I'm writing the return json with a , the image the result is not the same.

A: Its because you are calling "GetDados" directly from URL, which is why its not executing your view.
Try this..
Controller :
public ActionResult Index()
{
    return View();
}

View "index" :