text:
Q: Pandas extracting values from dataframe based on condition I'm trying to extract part of string before a dash in some rows in pandas df dataframe. The problem is that when I use extract() function it extracts the part of string before dash but inserts NaN value in rows where there is no dash present.
Data example:
I2311-A45
Z13A-SA87
CSSSAA1-4
LKJ3B-15
1AAAZ0-14
ASHENSKFR
ASD
AFSDFGRE

So I have df['values'] where is the example column. My attempts are:
df['values'] = df['values'].str.extract('(.*)-')

output:
I2311
Z13A
CSSSAA1
LKJ3B
1AAAZ0
NaN
NaN
NaN

and it gives me 3 NaN values instead of
ASHENSKFR
ASD
AFSDFGRE

Next what I was trying was using df.loc conditions and apply() function with lambda but with the same exception :

The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().

df['values'] = df['values'].apply(lambda x: df['values'].str.extract('(.*)-') if df['values'].str.contains('-') else None)

Thank you for help in advance!

A: You can simply use Series.str.split. This will split the value where - is present, otherwise will leave the value as is.
In [134]: df['values'].str.split('-').str[0]
Out[134]:
0        I2311
1         Z13A
2      CSSSAA1
3        LKJ3B
4       1AAAZ0
5    ASHENSKFR
6          ASD
7     AFSDFGRE
Name: values, dtype: object


text:
Q: Downloading the zip file through api c# unauthorized - error I create an application that is designed to collect data from Account on site FreshMail.
All the basic information I was able to download without any problem. Unfortunately, when I try to download data subscribers, api needs to send a request for the zip file.
I made such a request, but when try to download a file I getting an authorization error.
The code should work as follows (according to what is available in the documentation):

*

*I am sending the request for the preparation of the file, and in response get the ID that will help me to check the status of preparation of the file and download it.

*Then check the status of preparation of the file (status is ok).

*Finally, I try to download a file - and here there is an error authorization.

There is a code:
 responseidjob = wrapper.ExecuteRequest("async_subscribers_list/export", configuration, new { list = hashcode });

            IDictionary<string, object> Input = responseidjob.GetResponse();

            foreach (dynamic all in Input.ToList())
            {
                if (all.Key == "data")
                {
                    foreach (dynamic allin in all.Value)
                    {
                        idJob = allin.Value.ToString();
                    }
                }
            }

            if (idJob != "")
            {
                responsecheck = wrapper.ExecuteRequest("async_result/get", configuration, new { id_job = idJob });

                configuration.SetContentType("application/zip");
                responsezip = wrapper.ExecuteRequest("async_result/getFile", configuration, new { id_job = idJob });
            }

redpajama_set_name: RedPajamaStackExchange


text:
Q: A fast alternative for the below code I have to compute a matrix.I have written the following code
unq_x <- c(102,10226,1026,1024)

unq_x <- as.data.frame(unq_x)

mat1 <- matrix(nrow=nrow(unq_x),ncol=nrow(unq_x))

dim(mat1)

x_distance <- function(i,j)

{
  x1 =unq_x[i,]

 x2 = unq_x[j,]

  dist <- 1 - (x1-x2)/x2
  return(dist)
}

for (i in 1:nrow(unq_x))
{
  for (j in 1:nrow(unq_x))
  {
    mat1[i,j]=x_distance(i,j)
  }
}

This is working fine. But my unq_x has some 10000 numbers which increases the code run time.What other alternatives I can use instead of for loop to fasten up the code

A: This is a job for outer
x <- c(102,10226,1026,1024)
mat2 <- outer(x,x,FUN=function(x,y) 1-(x-y)/y)

> all(mat1 == mat2)
[1] TRUE

A: This applies the function in a vectorised manner across every element of unq_x.  The t just makes it identical to your original answer.
unq_x <- c(102,10226,1026,1024)
mat2 = t(sapply(unq_x, function(x, y) { 1 - (x - y)/y }), y = unq_x)

> all(mat1 == mat2)
[1] TRUE

Not exactly a foolproof benchmark, but I stopped the loop as it was taking forever to run.
x <- c(runif(min = 1, max =1000, n = 10000))
ptm = proc.time()
m = t(sapply(x, function(x, y) { 1 - (x - y)/y }, y = x))
proc.time() - ptm
   user  system elapsed
  7.347   1.528  36.006

Though A. Webb's comment is clearly the superior answer.
ptm = proc.time()
m = 2 - outer(x, x, `/`)
proc.time() - ptm
   user  system elapsed
  0.826   0.813   4.276

A: # Can be arranged as matrix arithmetic
x <- c(102,10226,1026,1024)
mat1 <- -x %*% t(1/x) +2


text:
Q: Using Viber API without public account According to Viber site's documentation, a public account (PA) is required to work with its API: https://developers.viber.com/api/rest-bot-api/index.html. There is a standard form for registering these accounts by providing company's information, can be found at https://www.viber.com/en/public-accounts. But I'm just a developer who wants to try out the API using my own Viber account.
Can I achieve this without the creation of a PA?

A: No. Unfortunately its not possible to send bot messages to private account without public account. Its not possible to assign bot to your private account. Public account is in a way account for you bot. Viber needs to know who is sending message and to whom (PA account = bot).
Easiest way would be creating public account but not publishing it so that it doesn't appear in search result. While PA is not published you can add other developers / testers by adding participants using their mobile number and then granting them admin rights if needed.


text:
Q: Asterisks in Fortran: Syntax error in argument list at (1) In the following fortran77 code, there is this subroutine definition
  SUBROUTINE MSIRNS ( D , NOBST , N , X , R , RR , SURFT ,
 ,                    INOBSI , ISUR , IDELTS , IRELPS ,
 ,                    RNOBSI , RSUR , RDELTS , RRELPS ,
 ,                    OBSD , * , * )

what is the meaning of the two last arguments, asterisks?
and how can I therefore call the function?
I tried all these variants
RES = CALL MSIRNS (D, NOBST, N, X, R, RR, SURFT, INOBSI, ISUR, IDELTS, IRELPS, RNOBSI, RSUR, RDELTS, RRELPS, OBSD, *, *)
    CALL MSIRNS (D, NOBST, N, X, R, RR, SURFT, INOBSI, ISUR, IDELTS, IRELPS, RNOBSI, RSUR, RDELTS, RRELPS, OBSD, *, *)
    RES = CALL MSIRNS (D, NOBST, N, X, R, RR, SURFT, INOBSI, ISUR, IDELTS, IRELPS, RNOBSI, RSUR, RDELTS, RRELPS, OBSD)

but always get

Error: Syntax error in argument list at (1)

A: It's an alternate return specifier:
http://www.fortran.com/F77_std/rjcnf0001-sh-15.html#sh-15.8.3
In the code that calls MSIRNS(), you need to replace the asterisks with "*N", where N is the label of the alternate return line.


text:
Q: Polymer and GWT, not working with Firefox In short, from within Java, after onModuleLoad(), we do the following:
String resource = "bower_components/webcomponentsjs/webcomponents-lite.js";
ScriptInjector.fromUrl(resource).setCallback(successCallback).inject();

Once the injection is successful, we inject html import links into the page:
private void injectImport(String href)
{
    HeadElement docHead = getHead();
    LinkElement link = Document.get().createLinkElement();
    link.setHref(href);
    link.setRel("import");
    docHead.appendChild(link);
}

On chrome, we can see from the network tab that the the import html files are indeed being GETed, and everything works as expected.
However, on Firefox, the injects are successful into the DOM, but the network tab reports that no resources we're GETed.
I know that HTML imports are not natively supported by Firefox, but I assumed once we had injected the polyfill from webcomponents-lite.js, it should just "work". Is this not the case?


text:
Q: Python check for Completed and failed Task Windows scheduler Does anyone know of a way or a resource I can look at to be able to check the status of all my Windows tasks I have in the task scheduler? I would like to see if that see if the task failed or was successful. I would like to do this in Python.
I have looked a little at using the win32com.client module. I can see what tasks are but can't find what the status of completed job are.
import win32com.client
scheduler = win32com.client.Dispatch("Schedule.Service")
scheduler.Connect()
tasks = scheduler.GetRunningTasks(1)
names = [tasks.Item(i+1).Name for i in range(tasks.Count)]
print names

A: The following uses the Task Scheduler API to print basic information for all registered tasks, including the last run time and result.
import win32com.client

TASK_ENUM_HIDDEN = 1
TASK_STATE = {0: 'Unknown',
              1: 'Disabled',
              2: 'Queued',
              3: 'Ready',
              4: 'Running'}

scheduler = win32com.client.Dispatch('Schedule.Service')
scheduler.Connect()

n = 0
folders = [scheduler.GetFolder('\\')]
while folders:
    folder = folders.pop(0)
    folders += list(folder.GetFolders(0))
    tasks = list(folder.GetTasks(TASK_ENUM_HIDDEN))
    n += len(tasks)
    for task in tasks:
        settings = task.Definition.Settings
        print('Path       : %s' % task.Path)
        print('Hidden     : %s' % settings.Hidden)
        print('State      : %s' % TASK_STATE[task.State])
        print('Last Run   : %s' % task.LastRunTime)
        print('Last Result: %s\n' % task.LastTaskResult)
print('Listed %d tasks.' % n)

This starts with only the root folder in the list. Each pass through the loop pops a folder; pushes all of its subfolders; and lists the tasks in the folder. It continues until the list of folders is empty.
COM Interfaces

*

*ITaskService

*ITaskFolder

*IRegisteredTask

*ITaskDefinition

*ITaskSettings
Alternatively, here's a walk_tasks generator that's modeled on the standard library's os.walk.
import os
import pywintypes
import win32com.client

TASK_ENUM_HIDDEN = 1
TASK_STATE = {
    0: 'Unknown',
    1: 'Disabled',
    2: 'Queued',
    3: 'Ready',
    4: 'Running'
}

def walk_tasks(top, topdown=True, onerror=None, include_hidden=True,
               serverName=None, user=None, domain=None, password=None):
    scheduler = win32com.client.Dispatch('Schedule.Service')
    scheduler.Connect(serverName, user, domain, password)
    if isinstance(top, bytes):
        if hasattr(os, 'fsdecode'):
            top = os.fsdecode(top)
        else:
            top = top.decode('mbcs')
    if u'/' in top:
        top = top.replace(u'/', u'\\')
    include_hidden = TASK_ENUM_HIDDEN if include_hidden else 0
    try:
        top = scheduler.GetFolder(top)
    except pywintypes.com_error:
        if onerror is not None:
            onerror(error)
        return
    for entry in _walk_tasks_internal(top, topdown, onerror, include_hidden):
        yield entry

def _walk_tasks_internal(top, topdown, onerror, flags):
    try:
        folders = list(top.GetFolders(0))
        tasks = list(top.GetTasks(flags))
    except pywintypes.com_error as error:
        if onerror is not None:
            onerror(error)
        return

    if not topdown:
        for d in folders:
            for entry in _walk_tasks_internal(d, topdown, onerror, flags):
                yield entry

    yield top, folders, tasks

    if topdown:
        for d in folders:
            for entry in _walk_tasks_internal(d, topdown, onerror, flags):
                yield entry

Example
if __name__ == '__main__':
    n = 0
    for folder, subfolders, tasks in walk_tasks('/'):
        n += len(tasks)
        for task in tasks:
            settings = task.Definition.Settings
            print('Path       : %s' % task.Path)
            print('Hidden     : %s' % settings.Hidden)
            print('State      : %s' % TASK_STATE[task.State])
            print('Last Run   : %s' % task.LastRunTime)
            print('Last Result: %s\n' % task.LastTaskResult)
    print('Listed %d tasks.' % n)

A: task scheduler can be accessed from command line using  schtasks and at
schtasks: https://technet.microsoft.com/en-us/library/cc772785%28v=ws.10%29.aspx
at: https://technet.microsoft.com/en-us/library/cc755618%28v=ws.10%29.aspx
run schtasks /query from python using subprocess.check_output see
Running windows shell commands with python
https://technet.microsoft.com/en-us/library/cc722006.aspx
The tasklist command lists all running programs and services or in powershell get-process
https://superuser.com/questions/914782/how-do-you-list-all-processes-on-the-command-line-in-windows


text:
Q: Pushing Elements to same array in multiple loops I have an array named $fields, and I keep pushing elements to it in multiple level of loops.
The pattern of items being pushed is quite similar and the code is getting repeated.
Is there a better way to implement in PHP or Laravel.
My result should be something like
My code looks like
 foreach ($systems as $system) {
        $order++;
        $systemLevel++;
        $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeInt, self::LBL_ZABBIX_MAP_NAME => $lbl_map_order . $order, self::LBL_ZABBIX_MAP_VALUE => $systemLevel];
        $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeStr, self::LBL_ZABBIX_MAP_NAME => $lbl_map_name . $order, self::LBL_ZABBIX_MAP_VALUE => $system->map_name];
        $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeMap, self::LBL_ZABBIX_MAP_NAME => $lbl_map_id . $order, self::LBL_ZABBIX_MAP_VALUE => $system->map_id];
        $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeInt, self::LBL_ZABBIX_MAP_NAME => $lbl_parent_map_id . $order, self::LBL_ZABBIX_MAP_VALUE => $parentOrder];

        $siteParentOrder = $order;
        foreach ($local_sites as $local_site) {
            $local_site_acronym = $local_site->acronym;
            $sites = CmsSiteStructure::getChildElement($system->map_id, $local_site_acronym); //Eg : MS-ML, SS-ML
            foreach ($sites as $site) {
                $order++;
                $siteLevel++;
                $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeInt, self::LBL_ZABBIX_MAP_NAME => $lbl_map_order . $order, self::LBL_ZABBIX_MAP_VALUE => $siteLevel];
                $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeStr, self::LBL_ZABBIX_MAP_NAME => $lbl_map_name . $order, self::LBL_ZABBIX_MAP_VALUE => $site->map_name];
                $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeMap, self::LBL_ZABBIX_MAP_NAME => $lbl_map_id . $order, self::LBL_ZABBIX_MAP_VALUE => $site->map_id];
                $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeInt, self::LBL_ZABBIX_MAP_NAME => $lbl_parent_map_id . $order, self::LBL_ZABBIX_MAP_VALUE => $siteParentOrder];

                $segments = CmsSiteStructure::getChildElement($site->map_id, $local_site_acronym); //Eg : MS-ML-ENR-APP
                $siteParentOrder = $order;
                foreach ($segments as $segment) {
                    $order++;
                    $segmentLevel++;
                    $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeInt, self::LBL_ZABBIX_MAP_NAME => $lbl_map_order . $order, self::LBL_ZABBIX_MAP_VALUE => $segmentLevel];
                    $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeStr, self::LBL_ZABBIX_MAP_NAME => $lbl_map_name . $order, self::LBL_ZABBIX_MAP_VALUE => $segment->map_name];
                    $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeMap, self::LBL_ZABBIX_MAP_NAME => $lbl_map_id . $order, self::LBL_ZABBIX_MAP_VALUE => $segment->map_id];
                    $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeInt, self::LBL_ZABBIX_MAP_NAME => $lbl_parent_map_id . $order, self::LBL_ZABBIX_MAP_VALUE => $siteParentOrder];

                    $subsystems = CmsSiteStructure::getChildElement($segment->map_id, $local_site_acronym); //Eg : MS-ML-ENR-APP-ATM
                    $siteParentOrder = $order;
                    foreach ($subsystems as $subsystem) {
                        $order++;
                        $subsystemLevel++;
                        $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeInt, self::LBL_ZABBIX_MAP_NAME => $lbl_map_order . $order, self::LBL_ZABBIX_MAP_VALUE => $subsystemLevel];
                        $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeStr, self::LBL_ZABBIX_MAP_NAME => $lbl_map_name . $order, self::LBL_ZABBIX_MAP_VALUE => $subsystem->map_name];
                        $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeMap, self::LBL_ZABBIX_MAP_NAME => $lbl_map_id . $order, self::LBL_ZABBIX_MAP_VALUE => $subsystem->map_id];
                        $fields[] = [self::LBL_ZABBIX_MAP_TYPE => $typeInt, self::LBL_ZABBIX_MAP_NAME => $lbl_parent_map_id . $order, self::LBL_ZABBIX_MAP_VALUE => $siteParentOrder];
                    }
                }
            }
        }

    }

As you can see the $fields[] is repeated at every inner levels.
Can I make it in a nice shorter, better way.


text:
Q: DBUS Return value In DBUS, in the XML file if I give the below code why is proxy generating a function with void return type ?
    <method name="getLocalTime">
        <arg type="s" name="timeString" direction="out" />
        <arg type="s" name="dateString" direction="out" />
    </method>

virtual void getMyTime(std::string& time, std::string& date) = 0;

A: In DBus, output from method calls is passed via the argument list, not the classical C function return mechanism. Furthermore, if the method is not asynchronous, then it is only allowed to return a single true/false Boolean result (which is returned in the classical C function return style). In your introspection, you must annotate this method as asynchronous because it returns multiple string values. Your proxy method call will pass in pointers to two string variables to receive the result in.
If I'm using dbus-glib as the example...
<method name="getLocalTime">
    <arg type="s" name="timeString" direction="out" />
    <arg type="s" name="dateString" direction="out" />
    <annotate name="org.freedesktop.DBus.GLib.Async" />
</method>

Then in my implementation of that method...
void
dbus_service_get_local_time(
    MyGObject* self,
    DBusGMethodInvocation* context
)
{
    char* timeString;
    char* dateString;

    // do stuff to create your two strings...

    dbus_g_method_return( context, timeString, dateString );

    // clean up allocated memory, etc...
}

and from a caller's perspective, the proxy method call would look something like this...
gboolean
dbus_supplicant_get_local_time(
    DBusProxy* proxy,
    char* OUT_timeString,
    char* OUT_dateString,
    GError** error
);

Note that in the proxy method, the gboolean result is whether or not the D-Bus call could be made, not the result of the method called.


text:
Q: First Transition not working because initial height is not set I am working with a <div>in a Webapp which is minimizable via a toggle button. Pressing the button changes the height of the <div> which works fine and uses transition: .4s;.
The Problem is: The First time the button is pressed, the height changes sudden and without any transition. The other pressed work just fine. This is because the height of the <div> is not initially set, but min-height, max-height are. So I've tried, when the button gets pressed the first time, to get the height of the div via javaScript and then just set the height to this. Sadly, the transition still doesn't work the first time.
I'm using Polymer btw.
I hope you got some tips, thanks in advance!

A: Maybe you can try to animate max-height and not height.
So you dont have to get the initial height via JS.


text:
Q: Dynamic sequence of promise (Q) never go to catch I have a number of promises (using Q) that i want to call sequentially, here's my code :
// All the promises are called sequentially
            var result = promises.reduce(function(promise, item) {
                return promise.then(function () {
                    var obj = toPush.shift();
                });
            }, Q());

            // Check the result
            result.then(function() {
                // Do something if all of the promises full
            }).catch(function() {
                // Do something if ONE of the promise is rejected and stop the others
            }).finally(function() {
                App.network.stopLoader();
            });

promises is an array of promise (callback functions)
It works greats, all the promises are done sequentially, but when a promise is rejected, it still go in the then function instead of the catch.
Why ?
I have used this : Break a dynamic sequence of promises with Q
Thanks for your help :)

A: The reason the catch is never called is because ou don't return anything in this part of the code:
return promise.then(function () {
    var obj = toPush.shift();
});

Instead you should try:
return promise.then(function () {
    return toPush.shift();
});

If you do:
result.then(console.log)

you should always see undefined which won't be caught.
Hope this helps!

A: It looks like you just want Q.all:
Q.all(promises).then(function() {
  // Do something if all of the promises full
}).catch(function() {
  // Do something if ONE of the promise is rejected and stop the others
}).finally(function() {
  App.network.stopLoader();
});

According to the documentation, the promise returned by all will be rejected as soon as any of the promises in the array is rejected. (As opposed to allSettled that waits for all the promises to resolve before resolving the returned promise).


text:
Q: Node.js replication screws up message ordering I have a replicated Node.js REST service (4 processes) that does nothing else than pushing tasks in a queue. It is extremely important that those tasks are being processed in order. Hence, they should be ordered in the queue.
RabbitMQ preserves the order in which message put a queue. However, with 4 concurrent processes I can't guarantee that the messages are put into the queue in the right order.
How to address this problem?


text:
Q: Hide/remove ListPreference from PreferenceScreen How can I remove ListPreference from PreferenceScreen at runtime?
Something like setVisibility(Visibility.GONE) on a parent row.
public class PreferencesActivity extends PreferenceActivity
{
    protected void onConfigurationChanged(ApplicationConfiguration config)
    {
        // ...
        if(config.actualAccounts.sie() < 1)
        {
             ListPreference p = (ListPreference) findPreference("account");
             p.setEnabled(false);
             // here I want to hide it at all
        }
        // ....
    }
 }

A: I'm dumb..
final PreferenceScreen preferenceScreen = getPreferenceScreen();
// ...
if(config.actualAccounts.sie() < 1)
{
    preferenceScreen.removePreference((ListPreference) findPreference("account"));
}


text:
Q: How to hide certain fonts from specific applications? I need to run outdated software (Xilinx ISE) on my computer with Kubuntu 20.04, but the ISE segfaults while loading the Noto fonts at /usr/share/fonts/truetype/noto (found with strace).  The software starts fine when I remove that folder, but Noto is Kubuntu's default font.  Some applications are broken, even after changing the default font settings.
Is there a way to hide that folder from outdated software?  Is there any standard and simple solution for my problem?

A: You can create a new user with appropriate settings to hide/show resources, including fonts.

*

*Create a new user, using your method of choice. man useradd should be helpful.

*Create the file /home/new-user/.config/fontconfig/conf.d/00-reject-noto.conf with the following contents:
 <?xml version="1.0"?>
 <!DOCTYPE fontconfig SYSTEM "/etc/fonts/conf.d/fonts.dtd">
 <fontconfig>

 <selectfont>
    <rejectfont>
       <glob>/usr/share/fonts/truetype/noto</glob>
       <glob>/usr/share/fonts/opentype/noto</glob>
    </rejectfont>
 </selectfont>

 </fontconfig>

*Create other font configuration files as desired.

*If you need to make specific fonts available to the application, you can place them in /home/new-user/.local/share/fonts/ (or /home/new-user/.fonts/, but this location is deprecated).

*Test that the fonts are hidden: sudo -H -u [new-user] fc-list | grep -i noto

*Run the program: sudo -H -u [new-user] [command]
Notes:

*

*If you don't need the Noto fonts to be available for your current user, you can skip the new-user creation step and just apply the settings to your current home directory.

*If you want to hide specific fonts, you can use <pattern> instead of <glob> in the font configuration:
 <rejectfont>
     <pattern><patelt name="family"><string>Noto Kufi Arabic</string></patelt></pattern>
 </rejectfont>

*For a list of font names, you can use a command similar to the following:
 fc-list | grep -i noto | awk -F: '{ print $2 }' | sed 's/^\ //g ; s/,/\n/g' | sort -u

See Also:

*

*Archwiki: Users and groups.

*ArchWiki: Font Configuration

A: You don't have to remove noto-mono entirely or hide it from certain applications. You only have to downgrade it a little bit.
What worked out for me was

*

*Delete current noto font folder in your Kubuntu 20.04 installation.

*Get a copy of noto fonts from kubuntu 18.04 ISO or installation.

*Place that older version of noto folder where newer version used to be.

You can also download the kubuntu18.04 version of noto from here https://drive.google.com/file/d/1kadGq6BGOyncoArN6Xqm1srJnFR8c0hK/view?usp=sharing


text:
Q: Lead form that submits to 2 external APIs I need to add 2 registration forms to my wp website, each form should submit the information in it to 2 different APIs.
I don't know even where to begin. Is there a plugin that can help me handle the task? do i need to write a plugin from scratch?
any pointer or recommendation will be much appreciated as i'm totally in the dark here.
EDIT: Add more info as requested by UBERABUSER (thanks!)
The 2 APIs i'm working with are
(a) client CRM, a custom API written in perl, handles registration of prospective clients
(b) An API of a list management / mailing service called TRACTION
Here's a working example of such a form: http://benchmarketing.com.au/k2a/ebook/
Now i need to create a version of the same form with the exact same functionality in wordpress... and this is what i'm in the dark about.

A: Whether you use a plugin to handle to creation and management of your forms or whether you create and maintain your forms manually, its pretty safe to say that any interaction with external APIs will require some custom coding in order to inter-operate with those APIs.
We're also totally in the dark on this question too because you haven't said what these APIs are/or who they belong to and what kind of data is being submitted and in what formats you are required to work with.
There is always a chance someone has created a plugin that makes interfacing with your external APIs but that's usually for the more popular ones.
...so, we need more info!


text:
Q: Geometry behind least squares under constraints I'm trying to solve the following minimisation problem by Lagrange multipliers. My questions is:

How to interpret the solutions geometrically?

Given a dataset $x_1, \dots, x_n \in \mathbb R^d$, a parameter vector $\theta \in \mathbb R^d$ and some $b \in \mathbb R^d$, I want to minimise
$$J(\theta) = \sum_{k=1}^n \lVert \theta - x_k \rVert^2$$ with respect to $\theta$ under the constraints

*

*$\theta^T b = 0$,

*$\lVert \theta - c \rVert^2 = 1$.

For 1., I put $\mathcal L(\theta,\lambda) = J(\theta) - \lambda \theta^T b$, $\lambda \in \mathbb R$, and set
$$\frac{\partial}{\partial \theta}\mathcal L(\theta,\lambda)
=\sum_{k=1}^n \frac{\partial}{\partial \theta} \lVert \theta - x_k \rVert^2
- \frac{\partial}{\partial \theta} \lambda \theta^T b
=\sum_{k=1}^n 2(\theta-x_k) - \lambda b = 0.$$
I'm somewhat shaky about the vector calculus, but I hope it's correct? Anyway, this is equivalent to $n \theta - n \bar x = \frac{1}{2} \lambda b$  and gives $\theta_0 = \frac{1}{2n} \lambda b + \frac{1}{n} \bar x $ where $\bar x$ is the sample mean. $\theta_0$ satisfies $\nabla J(\theta) = \lambda \nabla \theta^T b$. By the constraint ${\theta_0}^T b = 0$ we get
$\lambda = -2 {\bar x}^T \frac{b}{\lVert b \rVert}$.
Finally, this yields
$$\theta_0 = \frac{1}{n} \bar x \left(1-\frac{b}{\lVert b \rVert}\right).$$
For 2. I get
$$\frac{\partial}{\partial \theta}\mathcal L(\theta,\lambda)
=\sum_{k=1}^n \frac{\partial}{\partial \theta} \lVert \theta - x_k \rVert^2
- \frac{\partial}{\partial \theta} \lVert \theta - c \rVert^2 - 1
=\sum_{k=1}^n 2(\theta-x_k) - 2 \lambda (\theta - c)b.$$
Setting this equal to zero gives
$$\theta_0 = \frac{1}{n-\lambda}\left(n \bar x + \lambda c\right).$$
It looks rather messy to feed this into the constraint to compute $\lambda$. Is there some trick I'm missing?
Anyway, my problem is that the exercise suggested a geometric meaning behind all of this and I have no clue. Could someone explain to me what's going on?


text:
Q: How to specify an __init__ argument that is not a class attribute With attrs, how can I specify an init argument that is not a class attribute.
e.g. a CRC8 object might be passed some bytes or bytearray in the constructor, but I don't want to store that input, just calculate the CRC and store the result.
Is this pattern an example where using a class method is appropriate (as described in this link)?
http://www.attrs.org/en/stable/init.html#initialization

A: What you want here is a classmethod factory:
@attr.s
class CRC8:
    checksum = attr.ib()

    @classmethod
    def from_bytes(cls, bytes):
        # compute your CRC
        # checksum = ...
        return cls(checksum)

That allows you to do proper checks and balances.
In this case I'd wonder if a function wouldn't do? Similarly to the standard library's binascii.crc32().


text:
Q: How to parse JSON in Mongo script As part of a MongoDB script, I need to parse JSON. (Not something you would typically do, but it is Javascript after all).
JSON.parse does not exist.
Here is the workaround I made:
function parseJSON(json) {
    return eval("(function() { return "+json+"; })()");
}

This doesn't seem like it would be performant, and it looks a little ridiculous. Does anyone have a better way?

A: If you really have to convert a JSON string into a JavaScript object, then what you suggest is perfectly reasonable, although there are reasons to avoid eval due to performance concerns and security risks (see When is JavaScript's eval() not evil?). In the case that you generated the JSON data and you are sure that there's nothing dangerous inside, then you probably don't have to worry about an injection vulnerability.
As far as performance, I'm not aware of anything better other than JSON.parse. Can you alter the design of your program so that you do not have to parse JSON? For example, for importing JSON data into MongoDB, instead of using eval you should use the mongoimport utility.


text:
Q: Bad HTML in flag overlay There's an extra  in the flag overlay shown when viewing the full flagged post:

It's escaped in the source:
answered</a> 5 hours ago by


text:
Q: Ampliar margen en gráfico Tengo el siguiente df
my.data <- read.table(text = '

                           Porcentaje
Variable1                         0.6
Variable2                         0.4
Variable3                         0.23
Variable4                         0.19
Variable5                         0.10
Variable6                         0.04
Variable7                         0.0
Variable8                         0.0
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

Y quiero hacer el siguiente gráfico:
ggplot(my.data  ,aes( reorder(rownames(my.data ), Porcentaje),Porcentaje)) +
  geom_col(fill="steelblue") + coord_flip(expand = FALSE)+
  ggtitle ("Porcentaje de valores desconocidos")+
  theme(plot.title = element_text(hjust = 0.5))+
  xlab("Variables") + ylab("Porcentaje")

Me gustaría que la primera barra no llegara tan al final del gráfico, sino que hubiera más margen, es decir, ampliar el eje x.
He probado con xlim pero no lo consigo.

A: Puedes dejar que ggplot ajuste los márgenes mediante:
coord_flip(expand = TRUE)

Pero también podrías ajustar esta expansión de forma manual agregando:
# 10% a derecha e izquierda
scale_y_continuous(expand = expansion(mult = c(0.1, 0.1)))

Ten en cuenta que has hecho un "flip" de los ejes, y lo que ves como x en realidad es el eje y, puedes también entonces, ajustar la escala manualmene:
  ylim(-0.01,0.65)

o bien:
  scale_y_continuous(limits = (-0.01,0.65))


text:
Q: How to convert a string into a HttpFoundation\Request in Symfony? Hello I created a POST method, at the end I get a string $body.
I want to give this string to parameter of an other POST method registerMember(Request $request) but I don't succeed to give this $body as parameter because it is not a HttpFoundation\Request as expected.
I tried both of them :
$send = $this->registerMember(new Request([$body]));
$send = $this->registerMember(Request::create($body));

No one work
Could you help me please ? Thank you !


text:
Q: What is the reason behind not having a simpler multi-line comment in Perl? I know different methods of introducing multi-line comments in Perl. But I want to know why it doesn't have something simpler multi-line comment feature such /* comment */, which would make it much easier.
I currently follow http://www.perlmonks.org/?node_id=560985 to achieve multi-line comments. Are there any plans to include this feature in Perl anytime soon?

A: There was a discussion regarding this on the perl6-language@perl.org mailing list. Although in the end the discussion was inconclusive, the summary posted here makes for interesting reading.

A: As with any multiline comment structure, there will be a "open" and a "close" comment condition, and that leads to problems with nested comments.
for example, C uses /* as the open and */ as the close.  How does a multiline comment system handle comments within comments?  C will fail if you try to comment a block that is already commented.
Note that line-based comments (e.g. c++ // comments) do not suffer this problem.

A: C-style comments come with a variety of difficult problems, including the inability to comment-out comments.  Additionally, convenient syntax for one-line encourages concise writing, which makes your code easier to read.  The absence of 10-line "Author: ... Input: ... Output: ... Favorite Color: ..." blocks that you see from time to time in C and C++ is another benefit.
Multi-line comments encourage long writing that is better expressed more concisely or as documentation, so this is what Perl encourages with its # and =pod operators (respectively).
Finally, if you are having trouble with Perl's style of commenting, you should configure your editor to edit programs, not text.  In Emacs, if you start writing something like # this is a comment that is getting longer and longer and longer and oh my goodness we are out of space on this line what to do now and type M-q, Emacs will automatically insert the # at the beginning of each line that it creates.
If you just want to comment-out a block of code, then you need look no further than M-x comment-region and M-x uncomment-region, which will comment out the region in pretty-much any language; including Perl.
Don't stress about the syntax of comments; that's the computer's job!

A: Simplicity is in the eye of the beholder. That said, there are already a number of ways to do multi-line comments. First, void string literals:
q{This text won't do anything.
Neither will this.};

This has the unfortunate side effect of triggering a warning:
Useless use of a constant in void context at - line 4.

Another option is using a heredoc in void context - for some reason this doesn't cause a warning:
<<ENDCOMMENT;
Foo comment bar.
ENDCOMMENT

As you can see, the problem isn't the lack of syntax as such (python doc comments look vaugely similar to the q{} method in fact) - it's more just that the community of perl programmers has settled on line comments using # and POD. Using a different method at this point will just confuse people who have to read your code later.


text:
Q: Есть ли разница между вызовом функции из другой функции и "возвратом" функции из функции через return? Есть ли разница между двумя следующими вызовами функции из другой функции? Здесь ф-ия called() просто должна отработать, засовывать ее куда то еще для использования механизма замыкания не планируется. Интересует разница именно в контексте "просто вызвать функцию из другой функции".
function caller() {
    return called();
}

function caller() {
    called();
}

A: Разница есть, в первом случае вы возвращаете значение, во втором - нет. пример ниже.

function called()
{
  return 1
}

function caller1() {
    return called();
}

function caller2() {
    called();
}

function caller3() {
  var a=called();
  return a;
}

function caller4() {
  return called;
}

console.log(caller1());
console.log(caller2());
console.log(caller3());
console.log(caller4());

Примеры 1 и 3 - равнозначны, что демонстрирует одинаковое выполнение функции called() в обоих случаях вызова.
Т.е. return никак не влияет на поведение вызываемой функции.


text:
Q: Jenkins Ant deploy/release on multiple remote server at same time i try to solve the case where i need to make a PHP release on multiple remote Server nodes at the same time.
We got a Jenkins server wich does the following steps in his build (ant) script:

*

*Git Checkout

*PHP QA Tools Check (like PHPUnit, phpmd etc.)

*Do some other tests

After everything is OK i want to deploy the sources to 3(later maybe more) remote Servers.
After everything is pushed to the Webnodes i want to execute a symlink change on all 3 nodes at the same time.
Sounds kind of impossible to me, but i hoped that i get a solution somewhere here, but i didn't found anything that helps.
So hopefully someone here got a good idea or some experience to share.
Cheers,
Dennis

A: You should look at this link because PHP deployments are a bit different from Java/.Net related deployments. However, if you feel that using Phing along with Jenkins OR using Phing independently is not what you want, and would like to simply have some plugin which copies your content to few remote servers, then you should try using Publish Over SSH plugin. After the steps in ant script mentioned above completes, you can add the task of deploying the sources to remote servers in Post-build Actions section. Once you've installed the plugin, you will find Send build artifacts over SSH option in the drop-down menu of Post-build Actions. Here you will find options to select multiple servers and you also have option to run command over those machines once the sources have been copied using Exec command that i have highlighted in the snapshot below. Also don't forget to check the Advanced... options and the help (?) section for each option.


text:
Q: How to add python console in spyder After upgrade spyder version 3.2.1 .I con't find the python console in spyder.
It is inconvenient when i plot data interactively though the Ipython console.How can i add the python console to the spyder.

A: The variable explorer in makes Spyder great for debugging but it doesn't stack up to full featured IDE's such as PyCharm community edition. In my opinion, Spyder is a much worse debugger since the console was removed so after 2 months of frustration with the newer version I "downgraded" back to version 3.1.4 which I love.
This will get you back to the version of Spyder where the beloved console still exists:
conda uninstall spyder
conda install spyder=3.1.4

A: (Spyder developer here) The Python console was completely removed in Spyder 3.2.0 and it's not coming back. For the reasons to do that, please read this Github issue.
If you want to create interactive plots in the IPython console, you need to change your graphics backend to Automatic in
Tools > Preferences > IPython console > Graphics > Graphics Backend

A: Alt + Z or
View -> Panes -> Ipython Console