text:
Q: error while evaluating conditional (restart_status.rc == 0): 'dict object' has no attribute 'rc'"} This command fails every time in Ansible
How can I see why that happens and what could be the reason?
---
- name:                      "Restart service httpd via service module"
  service:
    name:                    httpd
    state:                   restarted
  register:                  restart_status
  until:                     restart_status.rc == 0
  retries:                   2
  delay:                     10
  when:                      infrastructure_type == 'cloud'
  changed_when:              restart_status.changed
  ignore_errors:             yes

Error I get is:
error while evaluating conditional (restart_status.rc == 0): 'dict object' has no attribute 'rc'"}

A: It's because .rc is specific to command: and shell: modules; the service: module contain no documented output variables, meaning ansible thinks that it can only succeed or fail, but otherwise has nothing more to offer you
Very likely the expression you're after is until: restart_status is succeeded using the succeeded test


text:
Q: Modify Firebase notification to replace phone number with contact name I am working on an android chat app with firebase. As a notification, I am getting Phone number of the sender and the and the message. Is it possible to modify the Notification using background Service?
I am trying below code. When app is in foreground, I am able to modify the title. How can I add contact name in the title.
    public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String NOTIFICATION_ID_EXTRA = "notificationId";
    private static final String IMAGE_URL_EXTRA = "imageUrl";
    private static final String ADMIN_CHANNEL_ID ="admin_channel";
    private NotificationManager notificationManager;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());

    }

    private void sendNotification(String title, String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Log.d("service", messageBody);
        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.logo)
                        .setContentTitle("Will set contact name here")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("channel description");
            channel.setShowBadge(true);
            channel.canShowBadge();
            channel.enableLights(true);
            channel.setLightColor(Color.RED);
            channel.enableVibration(true);
            channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can you prove that the difference of these two undecidable sets is un/decidable? I'm just an amateur programmer so please bear with me
consider the following sets of numbers
$$
D=\{m|\text{$m$ is a turing machine and does not halt on blank input}\}
$$
$$
G=\{m|\text{$m$ is a turing machine and does not halt on $m$}\}
$$
$$
L=D-G
$$
how can I prove that $L$ is un/decidable? thanks

A: Given a TM $M$, we can construct a TM M' running the following program:

*

*If the current cell is blank, GOTO 1

*Simulate M

We find that $M' \in D \setminus G$ iff $M \notin G$. Thus, if $D \setminus G$ were decidable, so would be $G$. But $G$ is a standard variant of the Halting problem, and so we already know that $G$ is undecidable.


text:
Q: Basis of $\{0\}$ set I am solving Linear Algebra and having a trivial doubt .
Is W ={∅} i.e. an empty set a basis of ={0} ?
I have read some solutions regarding the above and they imply that since W contains no vector , W  by definition is linearly independent .
I am not sure how W spans V. Can anyone explain this to me ?
"Every vector space has a basis."

Is the above statement true ?

A: If $V=\{0\}$ - a trivial vector space, then $W=\emptyset$ is its basis. (Note: not $W=\{\emptyset\}$ but $W=\emptyset=\{\}$.)
This empty set spans $V$ because any sum of no addends is taken, by convention, to be zero (in this case a zero vector).
This also matches the alternative definition of a span: "the smallest subspace containing all the vectors from the set". In this case, any subspace (including $\{0\}$) vacuously contains all the vectors from the empty set.

A: The standard convention for any binary operation with a neutral element is that the "empty operation" gives the neutral element. Some specific examples:

*

*The empty sum is $0$: $\sum_{x\in\emptyset}x=0$.

*The empty product is $1$: $\prod_{x\in\emptyset}x=1$.

*The empty union is the empty set: $\bigcup_{A\in\emptyset}A=\emptyset$.

Important for your question is the first one in the list: A linear combination of vectors in the empty set is the zero vector:
$$\sum_{v\in W}a_vv=\sum_{v\in\emptyset}a_v v=0.$$
And thus $W=\emptyset$ (not $\{\emptyset\}$!) spans the trivial vector space. It is also linearly independent, since there is no non-trivial linear combination which results in the zero vector.


text:
Q: Deriving distribution under change of variables between spaces of unequal dimension For a function of random variables $T:\mathbb{R}^n \mapsto \mathbb{R}^m$ Wikipedia outlines how to handle three cases:

*

*$m = n = 1$

*$m=n > 1$

*$n>1 \land m=1$
There seems to be two missing cases:

*

*$n < m$

*$n > m \land m > 1$
Give a function of random variables $T$ and a joint probability density function $f_{X_1, \cdots, X_n} (x_1, \cdots, x_n)$ both having suitable smoothness, and local invertibility for $T$, how do I derive the density of $T(X_1, \cdots, T_n)$ for these two remaining cases?

Henry in the comments raised an interesting point. It gave me some pause to think, which I appreciate. Would there still be a distribution in the case of $n < m$?
I think yes. Suppose we have $X \sim \mathcal{N}(0,1)$ and we are mapping $X \mapsto (\cos X, \sin X)$. The resulting points have to lay on the circle, which feels rather deterministic. But there will be uncertainty about where on the circle a sample of $X$ will map to. I think there will be some kind of density on (or should I say within?) the parametric object.
Here is a coded example:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

import seaborn as sns

x = np.random.normal(size=1000)

y1 = np.cos(x)
y2 = np.sin(x)
d = {'$\cos X$':y1, '$\sin X$':y2}

df = pd.DataFrame(d)

sns.jointplot(data=df, x='$\cos X$', y='$\sin X$')
plt.show()


text:
Q: Android notification always open MainActivity After setting up Firebase, I receive a notification created with the Firebase console and when I click on it, my application opens the firstactivity declared on manifest.
I want to open a specific detailactivity that have the firstactivity as parent.
My manifest:
...
   <activity
        android:parentActivityName=".views.main.MainActivity"
        android:name=".views.detail.DetailActivity"
        android:screenOrientation="portrait">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".views.main.MainActivity" />
    </activity>
....

My custom FirebaseMessagingService:
Intent i = new Intent(this, DetailActivity.class);
    Intent intent2 = new Intent(this, MainActivity.class);
    i.putExtra(ProfileDescriptionActivity.USER_ID, 14);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(ProfileDescriptionActivity.class);
    stackBuilder.addNextIntentWithParentStack(intent2);
    stackBuilder.addNextIntent(i);
 PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(pendingIntent);

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(0, builder.build());

If I receive the notification when the application is closed, it correctly shows the notification in the notification tray. But when I clicked open, as say up, the firstactivity.
When the application was open and I receive the notification, into notification center was show a blank view that open correctly the activity that I want.
What is wrong? Thanks.

A: To automatically open an application via FCM you need to use a data-message, which guarantees to always invoke the onMessageReceived() method.
For instance, your payload could be:
{
    "to" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
  }

In order to test sending this message, you can use any online FCM tester such as this.

A: In FCM if your application is in foreground it calls onMessageReceived in FirebaseMessagingService , and if application is in background it automatically shows a notification as you declared meta-data in AndroidManifest.
So in this case you have to handle onMessageReceived and generate a notification.
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // ...
}

If you want to handle both cases means if you want to handle both cases (background in foreground) don't send notification object in payload.
eg.
This cause onMessageReceived is not called if application is in background and called if application is in foreground.
{
    "to" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
}

Change this to like below payload and your onMessageReceived triggered in both cases if application is in foreground and background also.
Just only send data payload not notification payload.
This can't be done by FirebaseDashboard, this can be only done by firebase api for send messages.
{
    "to" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",

    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
}


text:
Q: How to set some PHP headers in a .htaccess file So I have these headers in some of my PHP files:
<?php
    header('Content-Type: text/html; charset=UTF-8');
    header('Content-Style-Type: text/css');
    header('Content-Script-Type: application/javascript');
    header('HTTP/1.1 200 OK');
    header('Content-language: en-US');
    header('X-Powered-By: PHP/5.2.17');
    header('Last-Modified: Tue, 01 Jan 2013 00:00:00 GMT');
    header('Cache-Control: no-store, no-cache, max-age=0, must-revalidate');
    header('Pragma: no-store, no-cache, max-age=0, must-revalidate');
    header('Expires: Tue, 01 Jan 2013 00:00:00 GMT');
?>

How do I set them in my .htaccess file? (Should be for specific files only), here's what I got so far:
<FilesMatch "^(index.php|about.php|contact.php)$">
    # HTTP Headers should be set in here
</FilesMatch>

A: You need to have mod_headers installed, or you might get error 500. You can wrap the setting of headers in a condition to check if mod_headers is present or not.
<FilesMatch "\.(html|htm|js|css)$">
    <ifModule mod_headers.c>
        Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
        Header set Expires "Thu, 1 Jan 2015 05:00:00 GMT"
    </ifModule>
</FilesMatch>

You can also unset headers. For example, if you're behind a load balacer the real visitor IP could be passed in form of a custom header you don't want to expose to the application.
Header unset Real-Visitor-IP

Besides expiration and etags, and webserver specific custom headers, you shouldn't tamper with headers at webserver level. Most of them should be managed at the application level, and you would prevent some frameworks from working normally if you pass them altered content types.


text:
Q: Swift use tesseract in broadcast extension over 50MB memory limits I want use Broadcast extension and SwiftyTesseract to recognition text on screen,but when I load tessdata then will use over 50MB memory lead to crash.
Has any solution use over 50MB memory or let main app background handler?
func loadOCR(){
    swiftTesseract = SwiftyTesseract(language: .custom("jpn"), dataSource:Bundle.main, engineMode: .lstmOnly)
}


text:
Q: Change color of current and voltage arrow (circuitikz) Currently, only the names of currents and voltages are red/blue. I'd also like their arrows to be red/blue. How can this be done?
\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{float}

\usepackage{graphicx}
\usepackage{tikz}
\usepackage{circuitikz}

\tikzset{every picture/.style={line width=0.75pt}} %set default line width to 0.75pt
\usetikzlibrary{quotes, angles, calc, babel}

\ctikzset{bipoles/thickness=0.8}
\ctikzset{bipoles/length=0.8cm}
\ctikzset{bipoles/diode/height=.375}
\ctikzset{bipoles/diode/width=.3}
\ctikzset{tripoles/thyristor/height=.8}
\ctikzset{tripoles/thyristor/width=1}
\ctikzset{bipoles/vsourceam/height/.initial=.7}
\ctikzset{bipoles/vsourceam/width/.initial=.7}
\ctikzset{inductors/scale=0.8, inductor=american}
\tikzstyle{every path}=[line width=0.8pt,line cap=round,line join=round]

\usepackage[backend=biber, sorting=none]{biblatex}

\begin{document}

\begin{circuitikz}[american, straight voltages, scale=0.84]
 \draw (0,0)
  to[battery, l={\textcolor{blue}{$U_e$}}] (0,4) -- (1.5,4)
  to[C, l=$C_1$, i={\textcolor{red}{$I_{C_1}$}}, -*] (1.5,0) -- (0,0) -- (3.5,0)
  to[switch, l=$S_2$] (3.5,1.5) -- (3.5,2.5) node[circ]{}
  to[switch, l=$S_1$, -*] (3.5,4) -- (1.5,4) node[circ]{} -- (5.5,4)
  to[C, l=$C_3$, v={\textcolor{blue}{$\frac{U_e}{2}$}}] (5.5,2.5) -- (5.5,1.5) node[circ]{}
  to[C, l=$C_4$, v={\textcolor{blue}{$\frac{U_e}{2}$}}] (5.5,0) -- (3.5,0) node[circ]{};

 \draw (8.25,4) to[L , v={\textcolor{blue}{$U_s$}}] (8.25,2);
 \draw (8.25,1.5) to[L, v={\textcolor{blue}{$U_s$}}] (8.25,-0.5);
 \draw (3.5,2.5) -- (7,2.5) to[L, v={\textcolor{blue}{$U_p$}}] (7,1.5) -- (5.5,1.5);
 \draw (7.45,3.5) -- (7.45,0.5);
 \draw (7.55,3.5) -- (7.55,0.5);

 \draw (8.25,4) -- (11,4)
  to[L, l=$L_1$, v={\textcolor{blue}{$U_{L_1}$}}] (14,4) -- (16.5,4) node[circ]{} -- (18,4) node[ocirc]{} -- (16.5,4)
  to[C, l=$C_2$, i={\textcolor{red}{$I_{C_2}$}}, -*] (16.5,-1.5) -- (18,-1.5) node[ocirc]{} -- (13.5,-1.5) node[circ]{}
  to[switch, l=$S_4$] (13.5,2) -- (8.25,2);

 \draw(14,4)
  node[flowarrow]{\textcolor{red}{$I_{L_1}$}};

 \draw (13.5,-1) node[circ]{} -- (14.5,-1)
  to[D-] (14.5,1) -- (13.5,1) node[circ]{};

 \draw (13.5,-1.5) -- (10.5,-1.5)
  to[switch, l=$S_3$] (10.5,1.5) -- (8.25,1.5);

 \draw (10.5,-1) node[circ]{} -- (11.5,-1)
  to[D-] (11.5,1) -- (10.5,1) node[circ]{};

 \draw (8.25,-0.5) -- (9,-0.5) -- (9,4) node[circ]{};

 \draw [<->, color=blue] (18,3.8) -- (18,-1.3) node[midway, fill=white]{$U_a$};

\end{circuitikz}

\end{document}

EDIT:
With the help of https://texdoc.org/serve/circuitikz/0#subsection.5.8 i managed to color the voltages, but not the currents.
\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{float}

\usepackage{graphicx}
\usepackage{tikz}
\usepackage{circuitikz}

\tikzset{every picture/.style={line width=0.75pt}} %set default line width to 0.75pt
\usetikzlibrary{quotes, angles, calc, babel}

\ctikzset{bipoles/thickness=0.8}
\ctikzset{bipoles/length=0.8cm}
\ctikzset{bipoles/diode/height=.375}
\ctikzset{bipoles/diode/width=.3}
\ctikzset{tripoles/thyristor/height=.8}
\ctikzset{tripoles/thyristor/width=1}
\ctikzset{bipoles/vsourceam/height/.initial=.7}
\ctikzset{bipoles/vsourceam/width/.initial=.7}
\ctikzset{inductors/scale=0.8, inductor=american}
\tikzstyle{every path}=[line width=0.8pt,line cap=round,line join=round]

\usepackage[backend=biber, sorting=none]{biblatex}

\NewDocumentCommand{\fixedvlen}{O{0.44cm} m m O{}}{% [semilength]{node}{label}[extra options]
 % get the center of the standard arrow
 \coordinate (#2-Vcenter) at ($(#2-Vfrom)!0.5!(#2-Vto)$);
 % draw an arrow of a fixed size around that center and on the same line
 \draw[-Triangle, #4] ($(#2-Vcenter)!#1!(#2-Vfrom)$) -- ($(#2-Vcenter)!#1!(#2-Vto)$);
 % position the label as in the normal voltages
 \node[anchor=\ctikzgetanchor{#2}{Vlab}, #4] at (#2-Vlab) {#3};
}

\begin{document}
\begin{circuitikz}[american, straight voltages, scale=0.84]
 \draw (0,0)
  to[battery, l={\textcolor{blue}{$U_e$}}] (0,4) -- (1.5,4)
  to[C, l=$C_1$, i={\textcolor{red}{$I_{C_1}$}}, -*] (1.5,0) -- (0,0) -- (3.5,0)
  to[switch, l=$S_2$] (3.5,1.5) -- (3.5,2.5) node[circ]{}
  to[switch, l=$S_1$, -*] (3.5,4) -- (1.5,4) node[circ]{} -- (5.5,4)
  to[C, l=$C_3$, v=, name=vC3] (5.5,2.5) -- (5.5,1.5) node[circ]{}
  to[C, l=$C_4$, v=, name=vC4] (5.5,0) -- (3.5,0) node[circ]{};

 \draw (8.4,4) to[L , v=, name=vS2] (8.4,2);
 \draw (8.4,1.5) to[L, v=, name=vS] (8.4,-0.5);
 \draw (3.5,2.5) -- (7,2.5) to[L, v=, name=vP] (7,1.5) -- (5.5,1.5);
 \draw (7.45,3.5) -- (7.45,0.5);
 \draw (7.55,3.5) -- (7.55,0.5);

 \draw (8.4,4) -- (11.15,4)
  to[L, l=$L_1$, v=, name=vL1] (14.15,4) -- (16.65,4) node[circ]{} -- (18.15,4) node[ocirc]{} -- (16.65,4)
  to[C, l=$C_2$, i={\textcolor{red}{$I_{C_2}$}}, -*] (16.65,-1.5) -- (18.15,-1.5) node[ocirc]{} -- (13.65,-1.5) node[circ]{}
  to[switch, l=$S_4$] (13.65,2) -- (8.4,2);

 \draw(14.15,4)
  node[flowarrow]{\textcolor{red}{$I_{L_1}$}};

 \draw (13.65,-1) node[circ]{} -- (14.65,-1)
  to[D-] (14.65,1) -- (13.65,1) node[circ]{};

 \draw (13.65,-1.5) -- (10.65,-1.5)
  to[switch, l=$S_3$] (10.65,1.5) -- (8.4,1.5);

 \draw (10.65,-1) node[circ]{} -- (11.65,-1)
  to[D-] (11.65,1) -- (10.65,1) node[circ]{};

 \draw (8.4,-0.5) -- (9.15,-0.5) -- (9.15,4) node[circ]{};

 \draw [<->, color=blue] (18.15,3.8) -- (18.15,-1.3) node[midway, fill=white]{$U_a$};

 \fixedvlen{vL1}{$U_{L_1}$}[blue]
 \fixedvlen{vS}{$U_s$}[blue]
 \fixedvlen{vS2}{$U_s$}[blue]
 \fixedvlen{vP}{$U_p$}[blue]
 \fixedvlen{vC3}{$\frac{U_e}{2}$}[blue]
 \fixedvlen{vC4}{$\frac{U_e}{2}$}[blue]

\end{circuitikz}
\end{document}

A: You should use the same techniques used for the blue arrows that you got from the manual and adapt them for the currents. You have all the labels specified in the diagrams in section 5.8.1.
A real minimal example follows, showing also how to manually add a current of a voltage with the same style.

\documentclass{article}
\usepackage[T1]{fontenc}

\usepackage{circuitikz}
\tikzset{every picture/.style={line width=0.75pt}} %set default line width to 0.75pt
% so it's 0.75pt or 0.9pt???
\tikzstyle{every path}=[line width=0.8pt,line cap=round,line join=round]

\NewDocumentCommand{\fixedvlen}{O{0.44cm} m m O{}}{% [semilength]{node}{label}[extra options]
 % get the center of the standard arrow
 \coordinate (#2-Vcenter) at ($(#2-Vfrom)!0.5!(#2-Vto)$);
 % draw an arrow of a fixed size around that center and on the same line
 \draw[-Triangle, #4] ($(#2-Vcenter)!#1!(#2-Vfrom)$) -- ($(#2-Vcenter)!#1!(#2-Vto)$);
 % position the label as in the normal voltages
 \node[anchor=\ctikzgetanchor{#2}{Vlab}, #4] at (#2-Vlab) {#3};
}
\NewDocumentCommand{\redcurrent}{mm}{% node, label
    % position the circuitikz arrow shape in the normal position and direction
    % but color it red
    \node[currarrow, color=red, rotate=\ctikzgetdirection{#1}] at (#1-Ipos){};
    % ditto for the label
    \node[red,anchor=\ctikzgetanchor{#1}{Ilab}] at (#1-Ipos) {#2};
}

\begin{document}
\begin{circuitikz}[american, straight voltages, scale=0.84]
    \draw (0,0)
    to[C, l=$C_1$, i=, -*, name=ic1, v=] (3.5,0);

    % this an independent, manually positioned red current arrow
    \draw(0,1) node[currarrow, color=red]{} node[above,red] {$I_{L_1}$};
    \draw[blue, -Triangle] (4,1.5) -- (4,-0.5) node[midway, right]{$U_r$};

    \fixedvlen{ic1}{$U_{L_1}$}[blue]
    \redcurrent{ic1}{$I_{C_1}$}

\end{circuitikz}
\end{document}

Notice that:

*

*you have conflicting setups for the line width;

*\usepackage[utf8]{inputenc} is default since a couple of years, but you probably want \usepackage[T1]{fontenc};

*You are styling components with both "class" parameters (ok) and internal parameters (dangerous, they can change in the future);

*scale=0.84 changes only the coordinates, not node sizes nor fonts; you probably meant scale=0.84, transform shape there; that will scale anything but the linewidths (more or less).


text:
Q: php - return two times everytime a function is called I'm trying to make it so everytime I call the function, it should returns one in two times the number like this:
calls(); // NULL
calls(); // 2
calls(); // NULL
calls(); // 4

Here is my code:
function calls() {
    if (NULL) {
        return NULL;
    }
    else {
        $calls++;
        return $calls;
    }
}

calls(); // NULL
calls(); // 2
calls(); // NULL
calls(); // 4

A: Don't use a global variable, use a static variable in the function in question:
function count_calls() {
     static $count = 0;
     ++$count;
     return ($count % 2 === 0) ? $count : NULL ;
}

A: Here is what you should do as example:
$current = 0;
$current = calls($current); // NULL
echo display($current);
$current = calls($current); // 2
echo display($current);
$current = calls($current); // NULL
echo display($current);
$current = calls($current); // 4
echo display($current);

/**
* Do stuff for your call with in param your last call pointer and returns new pointer
**/
function calls($last) {
     return $last++;
}

/**
* Returns null if not even, else the pointer value
**/
function display($value){

    if ($value % 2 = 0)
         return $value;
    return null;
}

Of course it would be easier in object if you store your current pointer inside a $this->current, but I don't think with the code you show it is appropriated to your understanding at moment! Have fun with it already
$class = new Call();
$class->calls();
echo $class->display();
$class->calls();
echo $class->display();
$class->calls();
echo $class->display();
$class->calls();
echo $class->display();
    class Call {

        private $current = 0;

        /**
        * Do stuff for your call with in param your last call pointer and returns new pointer
        **/
        function calls() {
             $this->current++:
             return $this->current;
        }

        /**
        * Returns null if not even, else the pointer value
        **/
        function display(){

            if ($this->current % 2 = 0)
                 return $this->current;
            return null;
        }
    }

A: Check this code :
$calls = 0;

function calls() {
    $GLOBALS['calls']++;
    if ($GLOBALS['calls'] % 2 != 0) {
        return NULL;
    }
    else {
        //$GLOBALS['calls']++;
        return $GLOBALS['calls'];
    }
}

var_dump(calls()); // NULL
var_dump(calls()); // 2
var_dump(calls()); // NULL
var_dump(calls()); // 4


text:
Q: Building SVM with tensorflow's LinearClassifier and Panda's Dataframes I'm aware of this question, but it is for an outdated function.
Let's say I'm trying to predict whether a person will visit country 'X' given the countries they have already visited and their income.
I have a training data set in a pandas DataFrame that's in the following format.

*

*Each row represents a different person, each unrelated to the others in matrix.

*The first 10 columns are all names of countries and the values in
the column are binary (1 if they have visited that country or 0 if
they haven't).

*Column 11 is their income. It's a continuous decimal variable.

*Lastly, column 12 is another binary table that says yes they have visited 'X' or not.

So essentially, if I have a 100,000 people in my dataset, then I have a dataframe of dimensions 100,000 x 12. I want to be able to properly pass this into a linear classifier using tensorflow. But not sure even how to approach this.
I am trying to pass the data into this function
estimator = LinearClassifier(
    n_classes=n_classes, feature_columns=[sparse_column_a,
 sparse_feature_a_x_sparse_feature_b], label_keys=label_keys)

(If there's a better suggestion on which estimator to use, I'd be open to trying that.)
And I'm passing data as:
df = pd.DataFrame(np.random.randint(0,2,size=(100, 12)), columns=list('ABCDEFGHIJKL'))
tf_val = tf.estimator.inputs.pandas_input_fn(X.iloc[:, 0:9], X.iloc[:, 11], shuffle=True)

However, I'm not sure how to take this output and properly pass into a classifier. Am I setting up the problem properly? I'm not coming from a data science background, so any guidance would be very helpful!
Concerns

*

*Column 11 is a covariate. Hence, I don't think it can just be passed in as a feature, can it?

*How can I incorporate column 11 into the classifier as well, since column 11 is a completely different type of feature than columns 1 through 10.

*At the very least, even if I ignore column 11, how do I at least fit column 1 through 10, with label = column 12 and pass this into a classifier?

(working code needed for bounty)

A: Linear SVM
SVM is a max margin classifier, i.e. it maximizes the width or the margin separating the positive class from the negative class. The loss function of linear SVM in case of binary classification is given below.

It can be derived from the more generalized multi class linear SVM loss (also called hinge loss) shown below (with Δ = 1).

Note: In all the above equations, the weight vector w includes bias b
How on the earth did someone came up with this loss? Lets dig in.

Image above shows the data points belonging to positive class separated from the data point belonging to the negative class by a separating hyperplane (shown as solid line). However, there can be many such separating hyperplanes. SVM finds the separating hyperplane such that the distance of the hyperplane to the nearest positive data point and to the nearest negative data point is maximum (shown as dotted line).
Mathematically, SVM finds the weight vector w (bias included) such that

If the labels(y) of +ve class and -ve class are +1 and -1 respectively, then SVM finds w such that

•   If a data point is on the correct side of the hyperplane (correctly classified) then

•   If a data point is on the wrong side (miss classified) then

So the loss for a data point, which is a measure of miss classification can be written as

Regularization
If a weight vector w correctly classifies the data (X) then any multiple of these weight vector  λw where  λ>1 will also correctly classifies the data ( zero loss). This is because the transformation λW stretches all score magnitudes and hence also their absolute differences. L2 regularization penalizes the large weights by adding the regularization loss to the hinge loss.

For example, if x=[1,1,1,1] and two weight vectors w1=[1,0,0,0], w2=[0.25,0.25,0.25,0.25]. Then dot(W1,x) =dot(w2,x) =1 i.e. both the  weight vectors lead to the same dot product and hence same hinge loss. But the L2 penalty of w1 is 1.0 while the L2 penalty of w2 is only 0.25. Hence L2 regularization prefers w2 over w1. The classifier is encouraged to take into account all input dimensions to small amounts rather than a few input dimensions and very strongly. This improve the generalization of the model and lead to less overfitting.
L2 penalty leads to the max margin property in SVMs. If the SVM is expressed as an optimization problem then the generalized Lagrangian form for the constrained quadratic optimization problem is as below

Now that we know the loss function of linear SVM we can use gradient decent (or other optimizers) to find the weight vectors which minimizes the loss.
Code
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

# Load Data
iris = datasets.load_iris()
X = iris.data[:, :2][iris.target != 2]
y = iris.target[iris.target != 2]

# Change labels to +1 and -1
y = np.where(y==1, y, -1)

# Linear Model with L2 regularization
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, activation='linear', kernel_regularizer=tf.keras.regularizers.l2()))

# Hinge loss
def hinge_loss(y_true, y_pred):
    return tf.maximum(0., 1- y_true*y_pred)

# Train the model
model.compile(optimizer='adam', loss=hinge_loss)
model.fit(X, y,  epochs=50000, verbose=False)

# Plot the learned decision boundary
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
                         np.arange(y_min, y_max, 0.01))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1)
plt.show()

SVM can also be expressed as a constrained quadratic optimization problem. The advantage of this formulation is that we can use the kernel trick to classify non linearly separable data (using different kernels). LIBSVM implements the Sequential minimal optimization (SMO) algorithm for kernelized support vector machines (SVMs).
Code
from sklearn.svm import SVC
# SVM with linear kernel
clf = SVC(kernel='linear')
clf.fit(X, y)

# Plot the learned decision boundary
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
                         np.arange(y_min, y_max, 0.01))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1)
plt.show()

Finally
The Linear SVM model using tf which you can use for your problem statement is
# Prepare Data
# 10 Binary features
df = pd.DataFrame(np.random.randint(0,2,size=(1000, 10)))
# 1 floating value feature
df[11] = np.random.uniform(0,100000, size=(1000))
# True Label
df[12] = pd.DataFrame(np.random.randint(0, 2, size=(1000)))

# Convert data to zero mean unit variance
scalar = StandardScaler().fit(df[df.columns.drop(12)])
X = scalar.transform(df[df.columns.drop(12)])
y = np.array(df[12])

# convert label to +1 and -1. Needed for hinge loss
y = np.where(y==1, +1, -1)

# Model
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, activation='linear',
                                kernel_regularizer=tf.keras.regularizers.l2()))
# Hinge Loss
def my_loss(y_true, y_pred):
    return tf.maximum(0., 1- y_true*y_pred)

# Train model
model.compile(optimizer='adam', loss=my_loss)
model.fit(X, y,  epochs=100, verbose=True)

K-Fold cross validation and making predictions
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import KFold
from sklearn.metrics import roc_curve, auc

# Load Data
iris = datasets.load_iris()
X = iris.data[:, :2][iris.target != 2]
y_ = iris.target[iris.target != 2]

# Change labels to +1 and -1
y = np.where(y_==1, +1, -1)

# Hinge loss
def hinge_loss(y_true, y_pred):
    return tf.maximum(0., 1- y_true*y_pred)

def get_model():
    # Linear Model with L2 regularization
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(1, activation='linear', kernel_regularizer=tf.keras.regularizers.l2()))
    model.compile(optimizer='adam', loss=hinge_loss)
    return model

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

predict = lambda model, x : sigmoid(model.predict(x).reshape(-1))
predict_class = lambda model, x : np.where(predict(model, x)>0.5, 1, 0)

kf = KFold(n_splits=2, shuffle=True)

# K Fold cross validation
best = (None, -1)

for i, (train_index, test_index) in enumerate(kf.split(X)):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

    model = get_model()
    model.fit(X_train, y_train, epochs=5000, verbose=False, batch_size=128)
    y_pred = model.predict_classes(X_test)
    val = roc_auc_score(y_test, y_pred)
    print ("CV Fold {0}: AUC: {1}".format(i+1, auc))
    if best[1] < val:
        best = (model, val)

# ROC Curve using the best model
y_score = predict(best[0], X)
fpr, tpr, _ = roc_curve(y_, y_score)
roc_auc = auc(fpr, tpr)
print (roc_auc)

# Plot ROC
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
         lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend(loc="lower right")
plt.show()

# Make predictions
y_score = predict_class(best[0], X)

Making predictions
Since the output of the model is linear we have to normalize it to probabilities to make predictions. If it is a binary classification we can use sigmoid of if it is a multiclass classification then we can use softmax. Below code is for binary classification
predict = lambda model, x : sigmoid(model.predict(x).reshape(-1))
predict_class = lambda model, x : np.where(predict(model, x)>0.5, 1, 0)

References

*

*CS231n
Update 1:
To made the code compatible with tf 2.0 the datatype of y should be same as X. To do this, after line y = np.where(..... add the line y = y.astype(np.float64).

A: Since all of your features are already numerical you can use them as they are.
df = pd.DataFrame(np.random.randint(0,2,size=(100, 12)), columns=list('ABCDEFGHIJKL'))
df['K'] = np.random.random(100)
nuemric_features = [tf.feature_column.numeric_column(column) for column in df.columns[:11]]
model = tf.estimator.LinearClassifier(feature_columns=nuemric_features)
tf_val = tf.estimator.inputs.pandas_input_fn(df.iloc[:,:11], df.iloc[:,11], shuffle=True)
model.train(input_fn=tf_val, steps=1000)

print(list(model.predict(input_fn=tf_val))[0])
{'logits': array([-1.7512109], dtype=float32), 'logistic': array([0.14789453], dtype=float32), 'probabilities': array([0.8521055 , 0.14789453], dtype=float32), 'class_ids': array([0]), 'classes': array([b'0'], dtype=object)}

The probabilities of the prediction output is most likely what you are interested in. You have two probabilities, one for the target being Flase and one for True.
If you want to have more details look at this nice blog-post about binary classification with TensorFlow.


text:
Q: RSpec request specs with an API key I can't find anything on this. How do I pass an API key in my RSpec request tests?
My API Key is sent in a header, so I pass it like this in the web:
Header: Authorization
Value: Token token="c32a29a71ca5953180c0a60c7d68ed9e"

How do I pass it in an RSpec request spec?
Thanks!!
Edit:
Here is my spec:
require 'spec_helper'

describe "sessions" do
  before do
    @program =FactoryGirl.create(:program)
    @user = FactoryGirl.create(:user)
    FactoryGirl.create(:api_key)
  end
  it "is authenticated with a token" do
    put "/api/v1/users/#{@user.id}?user_email=#{@user.email}&auth_token=#{@user.authentication_token}", {user: {name: "New Name"}}, { 'Authorization' => "Token token='MyString'" }
    response.status.should be(201)
  end

  it "fails without an API Token" do
    put "/api/v1/users/#{@user.id}?user_email=#{@user.email}&auth_token=#{@user.authentication_token}", user: {name: "New Name"}
    response.status.should be(401)
  end
end

A: So I was very close. I needed to log the output from making an actual API call to see what the exact format the server was expecting for the HTTP Header. So, the problem was that the format was a little off.
describe "sessions" do
  before do
    @user = FactoryGirl.create(:user)
    @api_key = FactoryGirl.create(:api_key)
  end

  it "is authenticated with a token" do
    put "/api/v1/users/#{@user.id}?user_email=#{@user.email}&auth_token=#{@user.authentication_token}", {user: {name: "New Name"}}, { "HTTP_AUTHORIZATION"=>"Token token=\"#{@api_key.access_token}\"" }
    response.status.should be(201)
  end
end

As you can see I had to change the format from : { 'Authorization' => "Token token='MyString'" } to { "HTTP_AUTHORIZATION"=>"Token token=\"#{@api_key.access_token}\"" }
I also just replaced 'MyString' with the more robust reference to the actual instance of the api token. @api_key.access_token


text:
Q: Does an ingress talk to pods directly or its through a service? I came to know that Nginx Ingress talks directly to pods NOT through a service.
Why endpoints and not services

The NGINX ingress controller does not use Services to route traffic to the pods. Instead it uses the Endpoints API in order to bypass kube-proxy to allow NGINX features like session affinity and custom load balancing algorithms.

Is this specific to this type of ingress or the idea is applicable to all ingresses?


text:
Q: string buffer java.lang.CharSequence error I'am working with spring hibernate maven in eclipse ide .
when I use StringBuffer I am getting the error:

The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files

Example code:
StringBuffer sb = new StringBuffer();
sb.append("some string");

The error is showing in append code line.
How can i resolve this?


text:
Q: $\{x\}$ is the fractional part of $x$
Let $\{x\}\;$ denote the fractional (non-integer) part of $x,\;$ so as examples: $\{3\}= 0,\;$ $\{0.5\}=0.5\;$ and $\{\pi\} = \pi-3.\quad$ IF $\{n\} + \{2n\} = 1.2,\;$ find all possible values of $300\{n\}.$

OKay, so I separated this into cases where $\{n\}< \frac12\quad$ and $\{n\}>\frac12.\quad$ If $\{n\}<\frac12,\quad$ then $\{2n\}\;$ will still be less than 1, so I can just do $\frac{1.2}{3} = 0.4 = \{n\}.\quad$ So $300\{n\} = 120.\quad$ However, I don't know how to approach the second case where $\{n\}>\frac12.$

A: Write $n=a+b$, where $a$ is integer and $0\le b=\{n\}<1$. You correctly observed that if $b<1/2$, then $2n=2a+2b$ with integer $2a$ and $0\le 2b<1$; therefore $\{2n\}=2b$. Hence
$$
\{n\}+\{2n\}=3b
$$
and $3b=6/5$ implies $300\{n\}=300b=120$.
If $b=1/2$, we have $2n=2a+2b=2a+1$ and so $\{2n\}=0$. So $\{n\}=6/5$, a contradiction.
If $1/2<b<1$, then $2n=2a+2b$ and we know that $1<2b<2$, so $0<2b-1<1$; therefore $2n=(2a+1)+(2b-1)$ and $\{2n\}=2b-1$. Therefore
$$
b+2b-1=\frac{6}{5}
$$

A:
We can write,$$\{n\}+\{2n\}=1.2$$$$n-[n]+2n-[2n]=1.2$$$$3n-[n]-[2n]=1.2$$$$[n]+[2n]=3n-1.2$$$$[n]+[2n]=3(n-0.4)$$$$[n]+[2n]=3([n]+\{n\}-0.4)$$$$[n]+[2n]=3[n]+3(\{n\}-0.4)$$$$[2n]-2[n]=3(\{n\}-0.4)$$$$2[n]+[2\{n\}]-2[n]=3(\{n\}-0.4)$$$$[2\{n\}]=3(\{n\}-0.4)$$$$3(\{n\}-0.4)=[2\{n\}]$$

$$\bbox[5px,border:2px solid red]{\{n\}=\frac{[2\{n\}]}{3}+0.4}$$

For $2\gt 2\{n\}\gt 1$

$$\{n\}=\frac{1}{3}+0.4$$
$$\{n\}=\frac{11}{15}$$
$$\bbox[yellow,5px]{300\{n\}=220}$$

For $2\{n\}\lt 1$,

$$2\{n\}\lt 1$$
$$\{n\}=\frac{0}{3}+0.4$$
$$\{n\}=0.4$$
Hence,
$$\bbox[yellow,5px]{300\{n\}=120}$$

A: When $n\in (0.5,1) \implies 2n\in (1,2) $ hence $\{ 2n\}$ belongs to $ (0,1) $.  Now since $\{n\}>0.5$ First try to reduce the interval of $n$ . Try with $0.6,0.65,0.7,0.75,0.8$ from this we see $n\in (0.7,0.75)$  hence $2n\in (1.4.1.5) $ .Coming back to the equation and using $x=[x]+\{x\}$ we have $n-[n]+2n-[2n]=1.2$ . As $\{x\}$  is an increasing function between two integers so we have only one solution. Therefore $n-0+2n-1=1.2 \implies n=0.7333.. $ hence $300\{n\}\approx 220$.

A: If $0\le\{n\}<\frac12$, then $\{2n\}=2\{n\}$ so that $300\{n\}=300\cdot\frac{1.2}3=120.$
If $\frac12\le\{n\}<1$, then $\{2n\}=2\{n\}-1$ so that $300\{n\}=300\cdot\frac{2.2}3=220.$


text:
Q: Error trying to install symfony command line tools on PhpStorm I'm running symfony3 and tried to install a symfony command line tools after having installed composer line tools (which get installed without any problems) however, whenever I try to fill the path field for symfony & php, it returns me an error saying :
Failed to determine version.
Command /Users/Julien/PhpstormProjects/need4truckSymfony/bin/console /Applications/MAMP/bin/php/php7.0.0/bin/php -V
Output Symfony installer version 3.0.2

I went on JetBrains to find a solution but there is no tips yet for SF3 tools.
I don't have any "console" in the app/ folder (as it is writen on jetbrains), and I also tried to fill both the fields with /usr/local/bin/symfony and /usr/bin/php but it doesn't work.


text:
Q: Azure Snapshot Debugger For Centos I am running a .NET Core application as a server application on a Centos 7 on-premise machine and using Azure App Service for a client application. I have added Application Insights to .NET Core Application and I can inspect things such as operations and exceptions on Azure portal.
What I desire next is to enable Snapshot Debugger for my .NET Core application. However, in the supported environments section on this page; https://learn.microsoft.com/en-us/azure/application-insights/app-insights-snapshot-debugger, there is no sign of support for any Linux distributions, I, actually, suspected for a chance because of .NET Core support existence but I could not find any question about this issue at all.
So, is Snapshot Debugger supported for .NET Core applications running on Centos? If Snapshot Debugger is not supported for Centos, can you suggest me a way to debug exceptions thrown on Centos on-premise machine?

A: Developer on Snapshot Debugger here.
No, Snapshot Debugger is not currently supported on Linux distros.
Please see my more complete answer here: https://github.com/Microsoft/ApplicationInsights-Home/issues/188#issuecomment-371233256


text:
Q: Enabling Drag and Drop from TOC to Python Script Tool? I am creating an ArcTool and wanting to have my input parameters encompass a drop down menu where files in the TOC can be chosen. The tool is shown below
I currently have a .csv and .shp sitting in my TOC and would like to have dropdown menus present on the "Stats File" and "Spatial Data" parameters so that I can choose them easily, instead of browsing to the file through the folder connection.
I am receiving an "Invalid Drop Item" message.

A: Assuming this is a script tool, you need to setup your input types accordingly from Parameters tab of the script Properties. For your layer parameter, select Feature Layer and your csv input (as in your TOC), select Table View from the Data Type column.


text:
Q: Passing values out of silverlight unto webpage Is that possible to have values inside a silverlight application be passed out unto the webpage, whether calling a javascript function with the values, etc.
The functionality I'm looking for: I have a map in silverlight, I select some values, I click the html submit button that is located on the webpage. The values in silverlight and also whatever input was made on the webpage is sent to the server (ASP.NET MVC Controller).

A: Yes, it is possible by accessing the html elements in the page:
HtmlElement field = HtmlPage.Document.GetElementByID("hiddenFieldID");
field.SetProperty("innerHTML", "someValue");

You can call this functionality when the map control is updated inside the Silverlight control. When the submit will be called in the web page it'll have the value ready on the field.


text:
Q: python site-package with same name as SDK package importing regardless of sys.path order I'm trying to use Google Cloud Shell as a remote development environment for an existing App Engine Standard Python 2.7 application.  With the SDK already installed, all of the communication pathways already established (no hassle with cloud auth/app default creds/etc), and full disposable VM available (no need to monkey with virtual env or any other python madness meant to make things work in shared environments), this seems it could be an ideal setup for part-time development/maintenance.
... alas, I am unable to import any of the appengine/google packages.
This appears to be an issue inside of the Google Cloud Shell.  So here are the steps to explain it clearly:
Go open a brand-spanking-new empty Google Shell:
https://shell.cloud.google.com/
type this to see the path app engine SDK is installed at:
someuser@cloudshell:~$ echo $(gcloud info --format="value(installation.sdk_root)")/platform/google_appengine
/usr/lib/google-cloud-sdk/platform/google_appengine

NOTE that the SDK has a google_appengine/google folder... containing an appengine package:
someuser@cloudshell:~$ ls -la /usr/lib/google-cloud-sdk/platform/google_appengine/google
total 32
drwxr-xr-x  7 root root 4096 Nov 18 02:53 .
drwxr-xr-x  1 root root 4096 Nov 18 02:53 ..
drwxr-xr-x 12 root root 4096 Nov 18 02:53 appengine
-rw-r--r--  1 root root  601 Jan  1  1980 __init__.py
drwxr-xr-x  5 root root 4096 Nov 18 02:53 net
drwxr-xr-x  3 root root 4096 Nov 18 02:53 protobuf
drwxr-xr-x  2 root root 4096 Nov 18 02:54 __pycache__
drwxr-xr-x  3 root root 4096 Nov 18 02:53 pyglib

find the python site-packages location:
someuser@cloudshell:~$ python -c 'import site; print site.getsitepackages()'
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

NOTE: that one of those directories also has a google folder with different packages:
someuser@cloudshell:~$ ls -la /usr/local/lib/python2.7/dist-packages/google
total 60
drwxr-sr-x 15 root staff 4096 Nov 18 03:12 .
drwxrwsr-x  1 root staff 4096 Nov 18 03:40 ..
drwxr-sr-x  2 root staff 4096 Nov 18 03:11 api
drwxr-sr-x  5 root staff 4096 Nov 18 03:11 api_core
drwxr-sr-x  3 root staff 4096 Nov 18 03:11 _async_resumable_media
drwxr-sr-x  5 root staff 4096 Nov 18 03:11 auth
drwxr-sr-x 29 root staff 4096 Nov 18 03:12 cloud
drwxr-sr-x  3 root staff 4096 Nov 18 03:12 iam
drwxr-sr-x  3 root staff 4096 Nov 18 03:11 logging
drwxr-sr-x  2 root staff 4096 Nov 18 03:11 longrunning
drwxr-sr-x  2 root staff 4096 Nov 18 03:11 oauth2
drwxr-sr-x  6 root staff 4096 Nov 18 03:11 protobuf
drwxr-sr-x  3 root staff 4096 Nov 18 03:11 resumable_media
drwxr-sr-x  3 root staff 4096 Nov 18 03:11 rpc
drwxr-sr-x  2 root staff 4096 Nov 18 03:11 type

ok.. let's start python:
someuser@cloudshell:~$ python

Python 2.7.16 (default, Oct 10 2019, 22:02:15)
[GCC 8.3.0] on linux2

# let's inspect the sys.path

>>> import sys

>>> sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

# ^^ our SDK path isn't in there.  let's add it to the front of the list in the manner we're supposed to

>>> sys.path.insert(1, '/usr/lib/google-cloud-sdk/platform/google_appengine')

# lets look again

>>> sys.path
['', '/usr/lib/google-cloud-sdk/platform/google_appengine', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-pa
ckages', '/usr/lib/python2.7/dist-packages']

# ok, that should work... RIGHT?

>>> from google.appengine.api import urlfetch
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named appengine.api

# NOPE... where's "appengine"???

>>> import google

# ummm....

>>> google.__path__
['/usr/local/lib/python2.7/dist-packages/google']

# ummmmmmmmmm.....

So there are a couple of issues and I don't understand how they relate or how to resolve:

*

*cloud shell has a google package that conflicts with the google package in the SDK

*why isn't the sys.path being honored anyways?

this has something to do with package namespacing or something... I am not smart enough to figure it out... please help!

A: The google.appengine module is baked into the first-generation Python (2.7) runtime. It's not available to install via pip, in the second-generation (3.x) runtime, or in Cloud Shell.
The only way to use it is by writing and deploying a first-generation App Engine app.


text:
Q: Usage of "under the sound of one's voice" I'd encountered the following excerpt from a speech by Martin Luther King (there's a video, if you're interested):

"I want to say to everybody under the sound of my voice this afternoon
that you are somebody."

I'd also encountered a similar usage by Malcolm X (that's too an excerpt from a speech, quoted by Maya Angelou in The Heart of a Woman):

"Every person under the sound of my voice is a soldier"

There are only few Google results to this kind of usage.
My question is:
Does it have a certain origin, or is it just a rhetorical phrasing?
Also, is this kind of structure (i.e., "under the x of y") is used elsewhere?


text:
Q: Typescript instanceof issue I have the following code that works, but the moment I change the if to p instanceof Address the condition is never met.
p is an object but I want to check it against its type that has already been defined:
export default class Address {
  public addressLine1: string = ''
  public addressLine2: string | null = null
  public town: string = ''
  public postcode: string = ''
}

  const displayResults = (list: any) => {
    const slicedList = list.slice(0, 3)

    const html =
      slicedList.map((p: string | Address) => {
        console.log('p: ', p instanceof Address)
        if (typeof p === 'object') {
          return <span key={`id-${uniqid()}`}>{addressToString(p)}
        }
        return <span key={`id-${uniqid()}`}>{p}
      })

    if (list.length > 3) {
      html.push(elipsis)
    }

    return html
  }


text:
Q: socat is missing commands for haproxy on ubuntu 20.04 I have installed haproxy 2.6.6, socat 1.7.4.1 and have a working load balancer for Exchange. I want to be able to turn off a node for maintenance and have unsuccessfully tried to use socat to do this.
In my haproxy.cfg global section I have:
stats socket /run/haproxy-master.sock mode 660 level admin expose-fd listeners
stats timeout 30s
user haproxy
group haproxy
daemon

When I am using this command
echo "disable server exch01" | sudo socat stdio unix-connect:/run/haproxy-master.sock

I get
unknown command, but maybe one of the following ones is a better match:
show cli level
show cli sockets
show proc
show version
help
prompt
quit

By sending show cli level it returns admin
If I sudo to root I get a few more commands, like
@master
@!
@
operator
reload
user
prompt

But I am missing disable server, show info, etc
So it looks like it is a permission thing, but it doesnt matter whether I am root or admin. It can also be some faulty initiation of stats socket in haproxy?
I have tried different configurations in haproxy.cfg like
stats socket /run/haproxy-master.sock mode 660 level admin expose-fd listeners
stats socket /run/haproxy-master.sock level admin expose-fd listeners
stats socket /run/haproxy-master.sock mode 660 level admin #expose-fd listeners

I have also tried to change permissions on the haproxy-master.sock file and it is currently 777
I am using bash


text:
Q: regexp mysql group I try get name of city's from string '{"travelzoo_hotel_name":"Graduate Minneapolis","travelzoo_hotel_id":"223","city":"Minneapolis","country":"USA","sales_manager":"Stephen Conti"}'
I try this regexp:
SELECT REGEXP_SUBSTR('{\"travelzoo_hotel_name\":\"Graduate Minneapolis\",\"travelzoo_hotel_id\":\"223\",\"city\":\"Minneapolis\",\"country\":\"USA\",\"sales_manager\":\"Stephen Conti\"}'
,'(?:.city...)([[:alnum:]]+)');

I have: '"city":"Minneapolis'
Me need only name of city:Minneapolis.
How to use groups in queries?
My example in regex101
Help me Please

A: I assume you are using MySQL 8.x that uses ICU regex expressions.
It looks like the string you want to process is JSON. You may use JSON_EXTRACT with JSON_UNQUOTE and a '$.city' as JSON path then:
JSON_UNQUOTE(JSON_EXTRACT('{"travelzoo_hotel_name":"Graduate Minneapolis","travelzoo_hotel_id":"223","city":"Minneapolis","country":"USA","sales_manager":"Stephen Conti"}', '$.city'))

will return Minneapolis.
In your regex, the non-capturing group pattern is still matched and appended to the match value. "Non-capturing" only means no separate memory buffer is alotted to the text captured with a grouping construct. So, you may fix it with '(?<="city":")[^"]+' pattern where (?<="city":") is a positive lookbehind that matches "city":" but does not put it into the match value. The only text you will have in the output is the one matched with [^"]+, 1+ chars other than ".


text:
Q: Characterizing continuity in terms of closed sets So I know that $f: X \to Y$ is continuous (that is, preimages of open sets are open) is equivalent to either of the following: preimages of closed sets are closed; $f$ is continuous at each point of $X$.
I am wondering what happens if we replace the word "open" in the definition of continuity at a point $x$. Then, is it true that we still have a characterization of continuity? To be precise, what I mean is:
Is it true that $f: X \to Y$ is continuous if and only if for all $x \in X$, and all closed $C \subseteq Y$ containing $f(x)$, there exists a closed $B \subseteq X$ containing $x$ such that $f(B) \subseteq C$?
My attempt:
$\implies$: $f$ is continuous so preimages of closed sets are closed. So put $B := f^{-1}(C)$ which is closed and contains $x$. And $f(B) = f(f^{-1}(C)) \subseteq C$.
$\impliedby$: This is where I got stuck. In the proof that I am aware of that continuity at each point implies continuity of the function, we seem to use the result that arbitrary unions of open sets are open. But this isn't necessarily true for closed sets, so I can't just blindly replace the word "open" with "closed". Any suggestions is appreciated.

A: The second implication is not true in general.
If $X$ is a $T_1$ space, $f:X\to Y$ is any function at all, $x\in X$, and $C$ is a closed subset of $Y$ containing $f(x)$, then $\{x\}$ is a closed subset of $X$ containing $x$, and certainly $f[\{x\}]=\{f(x)\}\subseteq C$.

A: Your condition is satsified whether or not $f$ is continuous (as long as singleton sets are closed, which is true in metric spaces or just a $T_1$ space). Given any closed set $C$ containing $f(x)$ just take $B=\{x\}$.


text:
Q: How can I resolve MSI paths in C#? I need to resolve target paths from an MSI database, outside of the installation. I am currently doing this using the Wix SDK by querying the database's Directory and File tables and constructing the paths from there, but resolving paths seems like something that should already be built-in. Is there a library that does this, even something unofficial, or am I stuck with doing it on my own?
This question has already been asked for C++, but the only answer somehow misunderstood the question to be about strings.
I don't really mind performance. My real concern is with resolving special folders like ".:Fonts", ".:Windows", ".:WinRoot", etc. - which I can still do in my own code but not very elegantly.

A: I did the same thing you did when DTF first came out. I wrote all the queries and loops to get the data I was working for.  And the performance was kind of painful.
Then I noticed the InstallPackage class in the Microsoft.Deployment.WindowsInstaller.Package assembly.  I felt kind of silly when I saw how fast and simple the following code is using that class:
using System;
using Microsoft.Deployment.WindowsInstaller;
using Microsoft.Deployment.WindowsInstaller.Package;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var package = new InstallPackage("foo.msi", DatabaseOpenMode.ReadOnly))
            {
                foreach (var filePath in package.Files)
                {
                    Console.WriteLine(filePath.Value);
                }
                Console.WriteLine("Finished");
                Console.Read();
            }
        }
    }
}


text:
Q: D3: Preserve minutes in time scale interval I need to have time intervals with exact minutes in the x axis ticks. I am creating a time scale as following:
const x = d3
      .scaleTime()
      .domain([new Date(), new Date(Date.now() + 24 * 60 * 60 * 1000)])
      .nice()
      .range([this.config.containerOffset.left, this.dimensions.svg.width - this.config.containerOffset.right]);

then I create an interval and pass it to the ticks
const interval = d3.timeHour.every(3);

...
  .ticks(interval)
  .tickFormat((d) => format(d, 'HH:mm:ss')),
...

but the interval resets minutes and rounds time down to hours and then counts the specified interval so I get:
12:00:00  15:00:00  18:00:00  21:00:00 ...

How can I make so that the interval also preserves minutes in the ticks, so if my start time is 12:28 then the ticks show
12:28:00  15:28:00  18:28:00  21:28:00 ...

Thank you
UPDATE
Here is a codepen with working code showing my issue with ticks values:
https://codepen.io/m0t0r/pen/dyPgRGy?editors=1010

A: I saw a potential solution for your problem on a post by Neha Gupta here but I'm posting it here because the link may break in the future.
The post outlines a function that generates 'custom' ticks. The function takes three arguments; the start and end dates [of the domain], and a step argument.
function customTickFunc (t0, t1, step)
{
    var startTime = new Date(t0),
    endTime= new Date(t1), times = [];
    endTime.setUTCDate(endTime.getUTCDate() + 1);
    while (startTime < endTime) {
       startTime.setUTCDate(startTime.getUTCDate() + 2);
       times.push(new Date(startTime));
     }
    return times;
}

When you implement the function :
 var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(customTickFunc);

... this will override the default 'rounding'/automatic tick behaviour and generate the required ticks. A sample jsfiddle is provided on the page. It's rather hard to see (at least on my screen) but the timescale on the jsfiddle goes 4:03  6:03  8:03 etc.. similar to what you want
Hope this helps


text:
Q: How to dynamically add jobs to a Scrapy/Selenium spider? I'm using Scrapy + Selenium to scrape Facebook friends data. I want to write a program that would take 2 usernames as input, recursively scrape their friendlists until a chain that connects the 2 users is found. My spider can login, generate Items and send them to MongoDB (through a Pipeline). I have a working function that can make a query to Mongo to check if a chain exists and return it. My take on the algorithm:

*

*Get input (2 usernames)

*Put the 2 users into crawling QUEUE

*Facebook login

*Pop the QUEUE and start crawling

*Once every other Item is sent to Mongo -> check if chain is found -> if not: put scraped user's friends usernames into the QUEUE -> pop the QUEUE.

*Once chain is found -> Crawl + write new chains(if found) and pop until QUEUE is empty

*Return all found chains

The login process is just a function that creates a Selenium instance, successfully logins and returns the webdriver instance, that is further passed into the spider.
At the moment I can't understand how to organise the QUEUE process. I can pass a single username or a list into the spider, but can't figure out how to pass more jobs into the same spider depending on the results of the crawling.
I start the crawl for a single user as follows:
process = CrawlerProcess(config)
process.crawl(FacebookSpider, <username>, session)
process.start()

How would I go about adding new usernames to the QUEUE (right after one crawl is finished and the Item is processed) without stopping the spider? Or maybe the approach should be 'wait for spider to finish job'->'create new one'?
I've tried digging through the Scrapy documentation, but for a newbie like me it was overwhelming. I tried to use CrawlerRunner, but couldn't get it to to work.


text:
Q: Wordpress - action when post is deleted (more then one) I'm having problem with triggering function on "delete_post" action.
I'm building functionality where i had to add one more table in database (i cannot use wp_postmeta for this one).
Because of this I created a custom table which have that additional data related with posts.
I would like that, when admin delete post from admin panel, to delete data for that post in my custom table (i don't want redundant data to stay there when post is gone)
And i implemented something like this:
add_action('admin_init', 'codex_init');
function codex_init() {
   if (current_user_can('delete_posts')) add_action('delete_post', 'delete_something');
}

function delete_something($postid) {
   //here im deleting everything from that table with that post id for that post type
}

And this works perfect if someone click to delete only one post. But when I want to delete more posts at once (checking buttons on wordpress admin menu and selecting delete option - bulk deletion), this will not work?
Am i doing something wrong here, or is there different action when someone want to delete several posts at once?

EDIT:
As indicated in the  comment bellow, this action works perfectly for bulk and individual delete actions as well. My issue was related with the usage of the global $post variable - to get the id of individual posts - when instead I should use parameter which is provided to the function directly.

A: I looked at the code in wp-admin/edit.php it does trigger the function wp_delete_post which has your action.
Try this. Does it die and hit the var_dump?
add_action('admin_init', 'codex_init');
function codex_init() {
   if (current_user_can('delete_posts')) add_action('delete_post', 'delete_something');
}

function delete_something($postid) {
     var_dump('trigger'.$postid);die();
     //here im deleting everything from that table with that post id for that post type
}


text:
Q: Fitting a parameterized 2D distribution I frequently deal with datasets that rely on a binary classification based on a Pulse-Shape-Distribution (PSD) discrimination value. This is based on a 2d fit of the PSD value vs the amplitude of the data, a typical graph is show below

The fits you see are the means and +/- 1 sigma for the two bands, where the mean and sigma is determined by chunking the 2d distribution along the x axis and performing a two gaussian fit along each slice. This works in most cases but sometimes the fits can bounce around a lot and on the lower end are less accurate.
What I would like to do is to somehow parameterize the means of the gaussian to a functional form. For reasons based on the underlying physics of the data, it can be assumed that the mean of the lower distribution is constant and the mean of the upper is a monotonically decreasing curve (a cubic would probably be easiest to model).
The integral of the two distributions relative to each other is not important, nor is the distribution of values along the x-axis. This changes for each dataset and is not important. What is needed is just the fits you see above.
It seems that there are two options, both of which I am having a hard time thinking about how to implement:
 * Continue doing a 1d slicing fit, but constrain the values of the means in such a way that they follow a functional form
 * Fit a 2D distribution directly, but unsure of how to deal with the bin value and amplitude distribution not mattering.
Is there a specific name, class of algorithms, or recasting of the problem that can help me on the path to implement a sort of 1.5-dimensional fit?


text:
Q: Combine GeoJSON files into bigger shapes with external JSON to merge on I have a shapefile of New York ZCTAs here
I also have these neighborhood definitions that map zip codes to New York City Boroughs.
I'd like to take my "all of New York zip code" data and:

*

*Clump up zip codes into their boroughs

*Ignore all non-NYC zip codes given in the file

That is, I want to no longer have zip-code level polygons, but borough-level polygons with borough-level features.names, and some capacity to map new zip code data back onto the correct data, something like features.zctalist = ["old", "zipcodes"]
Looking at the start of this file, it has:
head -c 1000 ny_new_york_zip_codes_geo.min.json
{"type":"FeatureCollection",
"features":[
   {"type":"Feature",
    "properties":
        {"STATEFP10":"36","ZCTA5CE10":"12205","GEOID10":"3612205","CLASSFP10":"B5","MTFCC10":"G6350","FUNCSTAT10":"S","ALAND10":40906445,"AWATER10":243508,"INTPTLAT10":"+42.7187855","INTPTLON10":"-073.8292399","PARTFLG10":"N"}

Part of my file is...
# borough.json
{"Bronx" : [
"10453", "10457", "10460",
"10458", "10467", "10468",
"10451", "10452", "10456",
"10454", "10455", "10459",
"10474", "10463", "10471",
"10466", "10469", "10470",
"10475", "10461", "10462",
"10464", "10465", "10472",
"10473"],
"Brooklyn" : [
"11212", "11213", "11216",
"11233", "11238", "11209",
"11214", "11228", "11204",
"11218", "11219", "11230",
"11234", "11236", "11239",
"11223", "11224", "11229",
"11235", "11201", "11205",
"11215", "11217", "11231",
"11203", "11210", "11225",
"11226", "11207", "11208",
"11211", "11222", "11220",
"11232", "11206", "11221",
"11237"
],
"Manhattan" : [
"10026", "10027", "10030",
"10037", "10039", "10001",
"10011", "10018", "10019",
"10020", "10036", "10029",
"10035", "10010", "10016",
"10017", "10022", "10012",
"10013", "10014", "10004",
"10005", "10006", "10007",
"10038", "10280", "10002",
"10003", "10009", "10021",
"10028", "10044", "10065",
"10075", "10128", "10023",
"10024", "10025", "10031",
"10032", "10033", "10034",
"10040"]
}

I believe ideally, I'd have something like:
{"type":"FeatureCollection",
{ features :   {"type":"Feature",
    "properties":
        {"borough_name":"Bronx",
    "STATEFP10" : ["36", ....]
    zctas: [10453, 10457, 10460,
    10458, 10467, 10468
    10451, 10452, 10456
    10454, 10455, 10459, 10474
    10463, 10471
    10466, 10469, 10470, 10475
    10461, 10462,10464, 10465, 10472, 10473],
...etc...

There are about 12 fields I'd need each to roll into a list, if that's the right way of thinking about it, where then the
"geometry":{"type":"Polygon","coordinates":[ ... union of coordinates ... ]

I can do some ugly list merging in Python, but I imagine this is a standard operation.
Questions:

*

*Is using lists in features correct, or something I should avoid?

*How do I accomplish this operation using common tools?

I /think/ something with ogr
ogr2ogr outputfile.json ny_new_york_zip_codes_geo.min.json
 -dialect sqlite -sql "SELECT ZCTA5CE10,ST_Union(geometry) as geometry FROM inputfile GROUP BY dissolvefield"
# how do I include my external json into this?

I see related questions like this here:

*

*https://stackoverflow.com/questions/29701086/flatten-dissolve-merge-entire-shapefile

*https://medium.com/@mbostock/command-line-cartography-part-2-c3a82c5c0f3
But I am not fully sure of the name of the operation I am trying to do in order to research it better, or generally how to do this operation in commandline/Python.  (If you can suggest a Python solution I am using Folium and geopandas).
Edit 1
Also tried this:
import geopandas
import json
ny = geopandas.read_file('ny_new_york_zip_codes_geo.min.json')
boroughs = json.load(open("borough.json"))
import matplotlib as plt
ny['borough'] = ''

for k,v in boroughs.items():
    ny.borough = boroughs.keys()[k] if v  == ny.ZCTA5CE10  else ''

# ValueError: Arrays were different lengths: 1794 vs 25# FAIL


text:
Q: chrome disable or change keyboard shortcut ctrl+shift+c developer tools console? How can I disable the Keyboard Shortcut ctrl+shift+c in Google Chrome to bring up the Developer Tools console?
I find myself trying to copy+paste content from the browser and mistakenly typing ctrl+shift+c when I really want to do ctrl+c instead.
How can I disable the current keyboard binding or change ctrl+shift+c to do the same as ctrl+c in Google Chrome?

A: Edit:
The originally suggested solution is no longer available.
The one provided by Paweł Prażak currently work and actually copies the text to the clipboard.

I was able to successfully override the Ctrl+Shift+C shortcut by using the Shortcut Manager extension and creating a new shortcut for the key combination.
You can then reassign it to trigger a host of pre-configured actions, or any javascript / bookmarklet code of your choosing. I don't really have any experience with javascript, so I can't really figure out how to make it act like Ctrl+C, but as far simply preventing it from bringing up the Developer Tools console, simply setting it to execute:
<script></script>

seems to work.

A: You can do that with Shortcut Manager and document.execCommand('copy') command, which were added to Google Chrome 43+ (~April 2015)

A: After attempting the shortkeys (Chrome Extension) approach and finding it unreliable, I was able to solve this problem using AutoKey.
First, sudo apt install autokey-gtk. Then, launch AutoKey, create a new script, set the Hotkey to be Ctrl+Shift+C, the window filter to be chromium-browser.Chromium-browser, and the script contents to be keyboard.send_keys('<ctrl>+c').
Once the script is saved, pressing Ctrl+Shift+C in Chromium will copy to the system clipboard instead of displaying the dev tools.

A: I've managed to make it work with shortkeys:

*

*Keyboard shortcut: ctrl+shift+c

*Behavior: Run JavaScript

*Javascript code to run: document.execCommand('copy')
Then just hit Save and reload tabs for the new setting to take effect.

A:
After attempting the shortkeys (Chrome Extension) approach and finding
it unreliable, I was able to solve this problem using AutoKey.
First, sudo apt install autokey-gtk. Then, launch AutoKey, create a
new script, set the Hotkey to be Ctrl+Shift+C, the window filter
to be chromium-browser.Chromium-browser, and the script contents to be
keyboard.send_keys('<ctrl>+c').
Once the script is saved, pressing
Ctrl+Shift+C in Chromium will copy to the system clipboard instead
of displaying the dev tools.

The above suggestion from @Ollin worked for me but I had to change the Window Filter to: google-chrome.Google-chromeon Ubuntu 18.04.03 LTS
(Sorry don't have comment power)

A: disable-keyboard-shortcut
This is super simple and elegant. It uses the Chrome builtin extension shortcuts menu chrome://extensions/shortcuts and adds shortcuts that do nothing. Only works for shortcuts including ctrl or alt.


text:
Q: Django: how to exclude model fields to not appear in the database My project has 3 models, one of them is the model "Bike", I want to store the attributes "id", "brand" and "purchase_date" in the database (this is like any other model), but the problem appears when I need to have also the attributes "lock", "battery" and "coordinates" which must not be stored in the database (these 3 attributes will change every 30 sec so makes no sense to be stored in the DB).
I want to do something like this:
DEFAULT_COORDINATES = (41.6522996, -4.7298879)
DEFAULT_BATTERY = 100   # 100%
DEFAULT_LOCK = True     # Locked
class Bike(models.Model):
id = models.CharField(max_length=300, primary_key=True)
brand = models.CharField(max_length=100)
purchase_date = models.DateField()

lock = DEFAULT_LOCK
battery = DEFAULT_BATTERY
coordinates = DEFAULT_COORDINATES

@property
def lock(self):
    """
    Returns the lock state of the bike.
    True = Locked
    False = Unlocked

    Returns:
         Boolean: The lock state of the bike.
    """
    return self.lock

@property
def battery(self):
    """
    Returns the battery level of the bike.

    Returns:
         Double: The battery level of the bike.
    """
    return self.battery

@property
def coordinates(self):
    """
    Returns the GPS coordinates of the bike.

    Returns:
         String: The GPS coordinates of the bike.
    """
    return self.coordinates

@lock.setter
def lock(self, lock):
    """
    Sets the lock state of the bike.

    Args:
        lock state (Boolean): 'True' if bike is locked, 'False' otherwise.
    """
    self.lock = lock

@battery.setter
def battery(self, battery):
    """
    Sets the battery level of the bike.

    Args:
        battery (Double): Battery level of the bike.
    """
    self.battery = battery

@coordinates.setter
def coordinates(self, coordinates):
    """
    Sets the coordinates of the bike.

    Args:
        coordinates (Tuple): Tuple containing the latitude and longitude coordinates of the bike.
    """
    self.coordinates = coordinates

def to_json(self):
    """
    Returns the object in JSON format.

    Returns:
        The bike object in JSON format.
    """
    json_dict = {
        "dev_id": self.dev_id,
        "lock": self.lock,
        "battery": self.battery,
        "coordinates": self.coordinates
    }
    return json_dict

But this problem appears:
error message
In the terminal you can see the attribute "brand" works fine, but the other one "lock" gives an error.
So my question is how could I use those extra attributes to work with them without affecting the database and to be able to obtain their values when working with the backend.


text:
Q: TypeError: Cannot assign to read only property 'name' of function ' I was trying to type something in the input box but when I filled in my first letter it says cannot assign to read only property.
Here is my code
This is the code of the component:

This is the input type:

This is what is sitting in the topic:

A: It looks like you're not initializing the var topic: Topic which you are using to bind to <input [(ngModel)]...>. To get your current version working you would have to bind to selectedTopic instead and call your createNewContact() in the ngOnInit().
See: https://stackblitz.com/edit/angular-kxd2ze


text:
Q: XML casting in C# I am working on XML validation using XSD files. Everything is working fine and it is returning the output as desired. Check the code below
public XmlValidatorResult Validate(Stream xml, Stream xsd)
{
    ClearErrorMessage();
    XmlValidatorResult result = new XmlValidatorResult();
    try
    {
        XmlSchemaSet schema = new XmlSchemaSet();
        XmlTextReader tr = new XmlTextReader(xsd);
        schema.Add(null, tr);

        Stream stream = GetFileStream(HttpContext.Current.Server.MapPath("/XML/SLFefileTypes.xsd"));
        XmlTextReader tr2 = new XmlTextReader(stream);
        schema.Add(null, tr2);

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;
        settings.Schemas.Add(schema);

        settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler += new ValidationEventHandler(ErrorHandler);
        XmlReader reader = XmlReader.Create(xml, settings);

        // Validate XML data
        while (reader.Read());
        reader.Close();

        // exception if validation failed
        if (numErrors > 0)
            throw new Exception(msgError);

        result.HasValidated = true;
        result.ErrorInfo = null;
        return result;
    }
    catch (Exception ex)
    {
        return result;
    }
}

Exception Handler
private void ErrorHandler(object sender, ValidationEventArgs args)
{
    XmlReader r = (XmlReader)sender;
    IXmlLineInfo lineInfo = sender as IXmlLineInfo;

    object aa = (XmlSchemaValidationException)args;

    string error = "\r\n" + "Line Number - " + lineInfo.LineNumber + " Line Position - " + lineInfo.LinePosition + "\n" + args.Message;
    msgError = msgError + error;

    ErrorInfo.Add(error);

    numErrors++;
}

Now if you will see closely in the handler code there is a line
object aa = (XmlSchemaValidationException)args;

where i am tring to cast the exception to XmlSchemaValidationException class to get the SourceObject. But it is showing me following error.

Cannot convert type 'System.Xml.Schema.ValidationEventArgs' to
  'System.Xml.Schema.XmlSchemaValidationException'

How can I resolve this?

A: You're trying to cast the ValidationEventArgs, which isn't the exception - that's why the cast is failing.
I suspect you just need to use the Exception property, which is of type XmlSchemaException - that isn't XmlSchemaValidationException, but you can cast that:
private void ErrorHandler(object sender, ValidationEventArgs args)
{
    var exception = (XmlSchemaValidationException) args.Exception;
    object sourceObject = exception.SourceObject;
    // ...
}


text:
Q: What is the difference between concurrent.futures and asyncio.futures? To clarify the reason for this question:

*

*It is confusing to use two modules with the same name. What do they represent that makes them distinct?

*What task(s) can one solve that the other can't and vice-versa?

A: From the docs:

[asyncio provides a] Future class that mimics the one in the concurrent.futures module, but adapted for use with the event loop;

A: The asyncio documentation covers the differences:

class asyncio.Future(*, loop=None)
This class is almost compatible with concurrent.futures.Future.
Differences:

*

*result() and exception() do not take a timeout argument and raise an exception when the future isn't done yet.

*Callbacks registered with add_done_callback() are always called via the event loop's call_soon_threadsafe().

*This class is not compatible with the wait() and as_completed() functions in the concurrent.futures package.

  This class is not thread safe.

Basically, if you're using ThreadPoolExecutor or ProcessPoolExecutor, or want to use a Future directly for thread-based or process-based concurrency, use concurrent.futures.Future. If you're using asyncio, use asyncio.Future.


text:
Q: Barracuda not delivering external email I have a Barracuda 300, sometime yesterday afternoon, roughly 5:30, the Barracuda stopped delivering external emails to our exchange users and instead, it began marking all those messages as 'deferred' and a reason as 'Invalid Recipient.'
We have had issues with this Barracuda in the past, and normally, just a little reboot and it would eventually start delivering the mail that is in the queue, as of 9:44AM, the mail/log storage is at 75%. The System Load is under <1%, and the firmware storage is at 37%.
I'm looking for other things that I can check, I've exhausted my knowledge on differing things to try, while, not a lot, I've covered the aspects of what I know to check, I'm just not that familiar with the Barracuda prodcuts:

*

*I can ping our exchange server from the Barracuda

*I've rebooted the Barracuda several times

*A Dig/NsLookup against our exchange server is successful

A part of me just thinks that since the mail/log storage is so large, that it will just take some time before everything is back to normal, but, it's been about three hours so far, and the mail/log storage is slowly growing larger.
The firmware is ridiculously out of date, 4.0.1.009, the powers that be, just don't want to spend the money to update it.
Any help, even if it's just 'be patient, let it do it's thing', would be greatly appreciated.
Thanks.

A: Well, you have a few odd issues. Given the old firmware, you're subject to a massive bug related to the Spamassassin filter used by the Barracuda. This bug basically bricks all appliances that have a firmware older than January 2012. Anyone with an older firmware is referred to the Barracuda renewals department.
The current firmware is 5.1.1.xxx. Your vitals are fine in terms of CPU usage and disk utilization. The storage on a busy unit plateaus at 75% and logs/etc are rotated to keep things at that level.
You should check to see if you have LDAP integration enabled on your Barracuda.
That should be Domains -> Domain Manager -> yourdomain.com -> Users -> LDAP Configuration
For the time being, change Exchange Accelerator/LDAP Verification: to NO if it's enabled. If you did have it enabled, check your LDAP bind username and password.
If that's not the case, then check the main system configuration.
Basic -> IP Configuration -> Destination Mail Server TCP/IP Configuration.
Change that field to the IP of your Exchange system and input a test address on your network. Run the SMTP test. The output should end with:
From: <smtptest@barracudanetworks.com>
Date: Wed Apr 4 08:19:55 2012
Subject: Test message

This is a test message from your Barracuda Spam & Virus Firewall.
.
250 2.6.0 <f2d75f7d-25d1-4834-ba73-0ca126d0e3fd@abcd.booty.net> [InternalId=466] Queued mail for delivery

Do you have a VMware environment? If so, I would suggest dumping the hardware unit at this point and picking up an evaluation of the Barracuda VX300 virtual appliance. It's far cheaper and faster than the hardware and you can run it for 30 days while "the powers that be" decide on whether they value spam filtering. You won't get support from Barracuda on your existing hardware without paying back to the date that the initial contract ended. It's their policy.
Also see: What to do with an out-of-warranty Barracuda Spam/Web filter?


text:
Q: Add a lookup fild by the bottom Click, not from Adding Item Hello how to add to the value by bottom click not from the Adding Item. Only from code:
          protected void Button2_Click(object sender, EventArgs e)
            {
                using (SPWeb witryna = SPContext.Current.Web)
                {
                    SPListItemCollection listItems = witryna.Lists["Szczegoly"].Items;

                    SPListItem item = listItems.Add();
                    item["Kontrakt"] = TextBox1.Text;
                    item["Pracownik"] = TextBox2.Text;
                    item["Dzien"] = TextBox3.Text;
                    item["Procenty"] = TextBox4.Text;
                    item.Update();
                }
            }

Here is My code. How can I choise and add a Value to item["Procenty"] = TextBox4.Text; When I debug it show me that Value is no-writable.

A: You have to create a SPFieldLookupValue object,
SPFieldLookupValue splkup=new SPFieldLookupValue(TextBox4.Text);
item["Procenty"] = splkup;

A: What's the internal name of this field? Is it custom?
Assuming that item["Procenty"] is the same as item["PercentComplete"] you could set it with something like this (Note that TextBox.Text returns a string)
//Set item to 10% completet
item["PercentComplete"] = .10;


text:
Q: Font not correctly displaying in Internet Explorer using the css property @font-face I'm trying to render a font using the css property @font-face , in Firefox, Chrome and Opera it works fine, but within Internet Explorer is just does not want to display correctly, and reverts back to another standard font.
My code looks as follows
@font-face {

                font-family: "swatch";

        src: url("../../fonts/swatch.eot"); /* IE */

                src: url("../../fonts/swatch.ttf") format("truetype");

}

.header_text1{

    font-family: "swatch";

    font-size: 78px;

    text-align:center;

    color: #ffffff;

    padding-top: 50px;

}

Am I doing something wrong here?

A: Try without the quotes when you are using the font, font-family:swatch;

A: I have an answer, I developed this site on my local host and then it did not work, I then moved the site to the live server and that solved the problem. It probably was a caching issue. Thanks to all who tried to help!!!


text:
Q: How to use Agda from the command line / from another language? Most interaction with Agda is done with EMACS, but is there a way to do it programmatically? I.e., is it possible to do everything from the command line, or from some API? The main goal is to build a thin wrapper so we could call Agda from another language, ex:
var Agda = require("agda");

var code = `
    data Bool: Set where
        true: Bool
        false: Bool

    not : Bool -> Bool
    not true = false
    not false = true

    val : Bool
    val = not true
`;

console.log(Agda.infer(code, "true")); // prints "Bool"
console.log(Agda.normalize(code, "val")); // prints "false"

I've previously asked how to use Agda as a library, but that obviously only cover Haskell. I've tried looking Agda's VIM extension to see how it does it, and it seems like it is sending commands to Agda, but I'm not sure exactly how. Pointers to the relevant documentation would be highly appreciated!

A: As far as I know, currently (on the master branch) there are two ways of interacting with Agda from the command line:

*

*The original backend for Emacs agda --interaction

*The new JSON-based backend agda --interaction-json

The Emacs backend

*

*Emacs would send messages formatted as Haskell datatypes to Agda (easy)

*Agda would reply in the form of Emacs Lisp for Emacs consumption (hard)
As you can see, this backend was exclusively designed for Emacs.
It would take some reverse-engineering to figure out what they are talking with each other.
I've made some notes about the Emacs protocol when I was implementing agda-mode on Atom. But I'm afraid that it has deviated from the actual implementation at the time of writing.
Here are some relevant part of the Agda source code that you may find useful, if you want to interact with the Emacs backend:

*

*Encoding Response as Emacs Lisp

*The datatype of Request

The JSON backend
Needless to say, it's painful to work with the Emacs protocol.
So I've managed to replace Emacs Lisp with JSON in the new backend.

*

*You would still need to send messages formatted as Haskell datatypes to Agda as you would in Emacs

*Agda would reply in JSON
Now, you wouldn't have to deal with the S-expressions of Emacs Lisp.
This is how responses are encoded as JSON

However, the payloads are still serialized as strings, making it difficult to extract useful information from Agda. So I'm still working on the json branch, trying to encode the payload in JSON.


text:
Q: Cannot open Bashrc in Ubuntu 16.04 LTS I'm unable to open bashrc file in ubuntu. I tried using gedit ~/.bashrc and vi commands but its not opening.
When I open a terminal everytime, its displaying the problem like
bash: export: `/opt/grads-2.1.0.oga.1/Contents/Resources/SampleDatasets :/usr/local/ferret/bin:/home/user/bin:/home/user/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin': not a valid identifier

After running the .profile, I'm getting the issues like
user@revathi:~$ . ~/.profile
bash: lesspipe: No such file or directory
bash: dircolors: No such file or directory
bash: ls: No such file or directory
bash: grep: No such file or directory
bash: export: `/opt/grads-2.1.0.oga.1/Contents/Resources/SampleDatasets :/usr/local/ferret/bin:': not a valid identifier

Could anyone please help me to fix the path?

A: You changed your PATH variable and included a space which hinders the system to find crucial programs. Call gedit with the full path with
/usr/bin/gedit ~/.bashrc

and correct the error. I suspect the faulty line looks like this in your case:
PATH="/opt/grads-2.1.0.oga.1/Contents/Resources/SampleDatasets :$PATH"

while it should be
PATH="/opt/grads-2.1.0.oga.1/Contents/Resources/SampleDatasets:$PATH"

instead. Then save the file, source it with . ~/.bashrc or just open a new terminal and your terminal should be back to normal.


text:
Q: Check if palindrome while ignoring special characters I'm failing the last test case, which is the one with the spaces and single quotation mark.
I used s.strip, but the error still persists.
Is there another way to go about this?
Thank you.
from test import testEqual
def removeWhite(s):
    s.strip()
    s.strip("'")
    return s

def isPal(s):

    if s == "" or len(s) == 1:
        return True
    if removeWhite(s[0]) != removeWhite(s[-1]):
        return False
    return isPal(removeWhite(s[1:-1]))

testEqual(isPal(removeWhite("x")),True)
testEqual(isPal(removeWhite("radar")),True)
testEqual(isPal(removeWhite("hello")),False)
testEqual(isPal(removeWhite("")),True)
testEqual(isPal(removeWhite("hannah")),True)
testEqual(isPal(removeWhite("madam i'm adam")),True)

A: At first your removeWhite function doesn't return all spaces because strip only removes from the end and the beginning of a string. See:
>>> "   a   ".strip()
'a'
>>> "   a a   ".strip()
'a a'

So i suggest this approach:
def removeWhite(s):
    return ''.join(filter(lambda x: x not in " '", s))

Please note that I use join because filter returns an iterator which needs to be converted back to a string.
For finding the palindromes i would suggest this function:
def isPal(s):
    if len(s) <= 1:                       # Special case to prevent KeyError later
        return True
    stripped = removeWhite(s)             # Strip off all whitespaces
    first = stripped[:len(stripped) // 2] # First half of the string
    if len(stripped) % 2:                 # Length of string is even?
        second = stripped[len(stripped) // 2 + 1:] # Drop the middle character
    else:
        second = stripped[len(stripped) // 2:] # Else keep it
    secondrev = ''.join(reversed(second)) # Reverse the second half
    return first == secondrev             # And return wether they're equal.

This holds for all your examples. But it think your isPal function should work too if you fix your removeWhite function


text:
Q: Designing a parametrized structure in c++ I have a number of features of different basic types, that are parametrized say by numbers from 0 to 9, like
    int a[10];
    double b[10];
    char c[10];

So it makes sense to organize them in a structure:
Struct Features {
    int a;
    double b;
    char c;
};
Features f[10];

However, I'm required to read these features one by one. E.g. first a[0]...a[9], then b[0]...b[9] etc from an input like "a_features=1,2,3,4,5,6,7,8,9,10", "b_features=0.5,...12.4" etc. For such input it's much easier to read the input into
int a[10]

than into
Features f[10]

What's the standard design in a situation like that?
UPDATE:
Thanks to all for prompt responses - my main goal is to have a clean design, performance-wise it's not critical. What strikes me as somewhat ugly, is that without the Features structure, I'll have almost the same code, repeated many times. Like
parse_features(a, "a_features, src_a);
parse_features(b, "b_features", src_b);

If the containers are vectors and the size(10) comes from the user, I'd have to resize each vector separately and things like that.

A: Is the integer a[3] related to the double b[3] and the char c[3] ? If yes, then it does make sense to group them into a structure.
If you have to read all the ints, then the doubles and then the chars, so be it.
"read an int into f[3].a" is just as easy as "read an int into a[3]".
If your input is structured like that, there's no way to avoid three loops. Three loops over the same array may look less elegant, but the rest of the program (the important part!) will be easier to understand if the data is grouped logically.


text:
Q: duvida com download de arquivos tenho um pasta na nuvem, e quero gerar um list na paginal html, com todos esses arquivo, para que quando o usuario clicar, abrir o downlaod do arquivo, estou tentando da seguinte forma(esse codigo é só de teste):

no chrome funciona, abre a janela para download, porem no firefox e no IE, o browser tentar abrir arquivo, ao inves de abrir a tela de download, como posso melhorar esse codigo?

A:  var files = Directory.GetFiles("C:\\path", "*.*",
    SearchOption.AllDirectories)

List<string> imageFiles = new List<string>();
  foreach (string filename in files)
 {
  if (Regex.IsMatch(filename, @".jpg|.png|.gif$"))
    imageFiles.Add(filename);
 }

EM asp MVC ou C#,net
em asp
VEJA O LINK ve c te ajuda!
https://stackoverflow.com/questions/6047228/listing-folders-in-a-directory-using-asp-net-and-c-sharp


text:
Q: google chrome does not want to open and cannot uninstall it completely I found an update for chrome and I updated the system, and the next time I restarted chrome it did not want to open. Nothing was updated except chrome.
When I opened chrome from the terminal nothing appeared to happen until I tried
1
sudo google-chrome --no-sandbox
this method opened chrome so I tried to change the file:
/usr/share/google-chrome.desktop
and switched those lines:
"Exec=/usr/bin/google-chrome-stable"
"Exec=/usr/bin/google-chrome-stable %U"

to
"Exec=sudo /usr/bin/google-chrome-stable --no-sandbox"

saved and yet nothing got resolved.
2
sudo apt-get purge google-chrome-stable
It got uninstalled but the .config files remained in their place and the .cache also, so I had to delete them myself and then I reinstalled chrome to find that it was not just installed, but actually it signed in to everything I was signed into before I uninstall it; as if I did nothing. I
tried my best for 2 pages of google with nearly the same answer, but to no avail.
3
sudo apt-get install libnss3 tried this one as nearly all solutions was regarding that firefox has updated a file the chrome rely on which is "libnss3" but also this did not help
Is there any solution to completely uninstall chrome from the entire system not just "purge" that did not uninstall and delete all files?
is there any solution to this particular issue?


text:
Q: Value not being passed properly to controller from view I have an MVC application that when a link is clicked a page needs to be displayed based on the same values on another page. I can't figure out why what's getting passed is null instead of the string. My code is below.
Controller:
public string searchQ
    {
        get { return (string)Session["searchQ"]; }
        set { Session["searchQ"] = value; }
    }

    public ActionResult Index()
    {
        Session["InitialLoad"] = "Yes";
        return View();
    }

    [HttpPost]
    public ActionResult Index(string heatSearch)
    {
        ViewBag.SearchKey = heatSearch;
        searchQ = heatSearch;
        return View();
    }

    public ActionResult Index_Perm()
    {
        ViewBag.SearchKey = searchQ;

        return View();
    }

    public ActionResult PartialMainLim(string heatSearch)
    {
        HomeModel C = new HomeModel();
        ChemViewModel D = new ChemViewModel();
        D = C.QueryResults(heatSearch);

        return PartialView(D);
    }

    public ActionResult PartialMain(string heatSearch)
    {
        HomeModel C = new HomeModel();
        ChemViewModel D = new ChemViewModel();
        D = C.QueryResults(heatSearch);

        return PartialView(D);
    }

The code in the index view looks like this (this one works):
@if (ViewBag.SearchKey != null)
{

    @Html.Action("PartialMainLim", "Home", (string)ViewBag.SearchKey)

 }

And in the index_perm view:
@if(ViewBag.SearchKey != null)
{

    @Html.Action("PartialMain", "Home", (string)ViewBag.SearchKey)

 }

When I check the value of SearchKey in both views it is correct. However for the method "PartialMain" null gets passed instead of the string, despite SearchKey being correct. This all works for the other view though. What am I doing wrong?

A: When passing values back to controller you have basically two options:

*

*Make a form

*Pass it as part of the url
Get methods only accept url attributes while Post methods are able to handle form content as well.
From what you are trying to do I'd say you could use something like:
@Html.Action("PartialMain", "Home", new {heatSearch = (string)ViewBag.SearchKey})

this should create url looking like /Home/PartialMain?heatSearch=[content of SearchKey]
EDIT:
That will only pass the value given it is present in the ViewBag. You are getting it from the Session which is imho a terrible idea in MVC (which should be session-less). Please consider if you really need it there. Usually there are other ways to implement this.

A: There is no HttpPost handler in the controller when you click the index_perm view.

A: I think that problem is your session that would be null. One of principles of framework ASP.NET MVC is stateless. Using session in ASP.NET MVC quite horrible.
At the moment, I think you can quickly fixed it by using TempData that default using Session under the hood. You could have a look an outdated article for further digging up ViewData vs TempData


text:
Q: When is the generic point of an integral noetherian scheme open (reference)? Let $X$ be an integral noetherian scheme, let $\xi$ be its generic point. Then it is not so hard to show that $\{ \xi\}$ is open in $X$ if and only if $X$ is a finite set. In termes of algebra, it says the following:

Let $A$ be a noetherian integral domain. Suppose there exists $f\in A$ non-zero such that the localization $A_f$ is a field. Then $A$ is semi-local of Krull dimension at most $1$.

Question: What is the name of this result ? I am sure I saw it once somewhere.
The motivation comes from a construction of non-discrete zero-dimensional schemes  here.

A: This result is attributed to Artin and Tate: see Theorem 2.13, pg. 281.