text:
Q: How to have an empty column label in pgfplots I have created the following heatmap using pgfplots:

Currently I need the x to make it compile. Without it, I get an error referring to the MH value below the x:
! Package PGF Math Error: Could not parse input 'MH' as a floating point number, sorry. The unreadable part was near 'MH'..'

For other places in the table it's fine for the entry to be empty, but not here. How can I remove that x?
\documentclass{standalone}
\usepackage{colortbl}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\pgfplotstableset{
    /color cells/min/.initial=0,
    /color cells/max/.initial=1000,
    /color cells/textcolor/.initial=,
    %
    % Usage: 'color cells={min=<value which is mapped to lowest color>,
    %   max = <value which is mapped to largest>}
    color cells/.code={%
        \pgfqkeys{/color cells}{#1}%
        \pgfkeysalso{%
            postproc cell content/.code={%
                %
                \begingroup
                %
                % acquire the value before any number printer changed
                % it:
                \pgfkeysgetvalue{/pgfplots/table/@preprocessed cell content}\value
\ifx\value\empty
\endgroup
\else
                \pgfmathfloatparsenumber{\value}%
                \pgfmathfloattofixed{\pgfmathresult}%
                \let\value=\pgfmathresult
                %
                % map that value:
                \pgfplotscolormapaccess
                    [\pgfkeysvalueof{/color cells/min}:\pgfkeysvalueof{/color cells/max}]%
                    {\value}%
                    {\pgfkeysvalueof{/pgfplots/colormap name}}%
                % now, \pgfmathresult contains {<R>,<G>,<B>}
                %
                % acquire the value AFTER any preprocessor or
                % typesetter (like number printer) worked on it:
                \pgfkeysgetvalue{/pgfplots/table/@cell content}\typesetvalue
                \pgfkeysgetvalue{/color cells/textcolor}\textcolorvalue
                %
                % tex-expansion control
                % see http://tex.stackexchange.com/questions/12668/where-do-i-start-latex-programming/27589#27589
                \toks0=\expandafter{\typesetvalue}%
                \xdef\temp{%
                    \noexpand\pgfkeysalso{%
                        @cell content={%
                            \noexpand\cellcolor[rgb]{\pgfmathresult}%
                            \noexpand\definecolor{mapped color}{rgb}{\pgfmathresult}%
                            \ifx\textcolorvalue\empty
                            \else
                                \noexpand\color{\textcolorvalue}%
                            \fi
                            \the\toks0 %
                        }%
                    }%
                }%
                \endgroup
                \temp
\fi
            }%
        }%
    }
}

\begin{document}

\pgfplotstabletypeset[%
     color cells={min=0,max=210,textcolor=black},
    %/pgfplots/colormap={orangewhiteorange}{rgb255=(255,170,0) color=(white) rgb255=(255,170,0)},
    /pgfplots/colormap/greenyellow,
    /pgf/number format/fixed,
    /pgf/number format/precision=3,
    col sep=comma,
    columns/x/.style={reset styles,string type}%
]{%%%%%%%
% fbankpitch2joint
x,MH,LH,L,H,M
MH,0,3,15,12,32
LH,7,0,16,10,30
L,8,9,0,37,210
H,5,10,25,0,89
M,16,8,168,67,0
}

\end{document}

A: In the line
columns/x/.style={reset styles,string type}%

you tell TeX that row headers are in a column named x. When TeX does not see it, it complains. Let us rename the column to \space:
\pgfplotstabletypeset[%
     color cells={min=0,max=210,textcolor=black},
    %/pgfplots/colormap={orangewhiteorange}{rgb255=(255,170,0) color=(white) rgb255=(255,170,0)},
    /pgfplots/colormap/greenyellow,
    /pgf/number format/fixed,
    /pgf/number format/precision=3,
    col sep=comma,
    columns/\space/.style={reset styles,string type}%
]{%%%%%%%
% fbankpitch2joint
\space,MH,LH,L,H,M
MH,0,3,15,12,32
LH,7,0,16,10,30
L,8,9,0,37,210
H,5,10,25,0,89
M,16,8,168,67,0
}

Result:


text:
Q: getting the gps position not working I dont know why, but i am unable to get the GPS Position...
lm.getLastKnownLocation always returns null and onLocationChanged is never called.
But i can see the gps icon on my system tray.
any ideas?
package com.localfotos;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

/*
 * This animated wallpaper draws a rotating wireframe cube.
 */
public class MyWallpaperService extends WallpaperService implements LocationListener{

    private final String TAG = "WallpaperService============================";
    private LocationManager lm;
    private final Handler mHandler = new Handler();

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "got location!");

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCreate() {
        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
        super.onCreate();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lm.removeUpdates(this);
    }

    @Override
    public Engine onCreateEngine() {
        return new CubeEngine(this);
    }

    class CubeEngine extends Engine{

        MyWallpaperService mws;

        private final Runnable mDrawCube = new Runnable() {
            public void run() {
                drawFrame();
            }
        };
        private boolean mVisible;
        private double lat = -1;
        private double lon = -1;

        CubeEngine(MyWallpaperService mymws) {
            mws = mymws;
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mHandler.removeCallbacks(mDrawCube);
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            mVisible = visible;
            if (visible) {
                drawFrame();
            } else {
                mHandler.removeCallbacks(mDrawCube);
            }
        }

        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);
            drawFrame();
        }

        @Override
        public void onSurfaceCreated(SurfaceHolder holder) {
            super.onSurfaceCreated(holder);
        }

        @Override
        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
            mVisible = false;
            mHandler.removeCallbacks(mDrawCube);
        }

        @Override
        public void onOffsetsChanged(float xOffset, float yOffset,
                float xStep, float yStep, int xPixels, int yPixels) {
            drawFrame();
        }

        /*
         * Store the position of the touch event so we can use it for drawing later
         */
        @Override
        public void onTouchEvent(MotionEvent event) {
            super.onTouchEvent(event);
        }

        /*
         * Draw one frame of the animation. This method gets called repeatedly
         * by posting a delayed Runnable. You can do any drawing you want in
         * here. This example draws a wireframe cube.
         */
        void drawFrame() {
            final SurfaceHolder holder = getSurfaceHolder();

            Canvas c = null;
            try {
                c = holder.lockCanvas();
                if (c != null) {
                    // draw something
                    drawCube(c);
                }
            } finally {
                if (c != null) holder.unlockCanvasAndPost(c);
            }

            // Reschedule the next redraw
            mHandler.removeCallbacks(mDrawCube);
            if (mVisible) {
                mHandler.postDelayed(mDrawCube, 1000 * 10);
            }
        }

        /*
         * Draw a wireframe cube by drawing 12 3 dimensional lines between
         * adjacent corners of the cube
         */

        //taken from http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
        private JSONObject getJSONfromURL(String url){

            //initialize
            InputStream is = null;
            String result = "";
            JSONObject jArray = null;

            //http post
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
            }

            //convert response to string
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
            }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
            }

            //try parse the string to a JSON object
            try{
                    jArray = new JSONObject(result);
            }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
            }

            return jArray;
        }

        String getPanoramioUrl(double minx, double maxx, double maxy, double miny){
            return "http://www.panoramio.com" +
                    "/map/get_panoramas.php?" +
                    "set=public&from=0&to=1&minx="+minx+"&miny="+miny+"&maxx="+maxx+"&maxy="+maxy;
        }

        void drawCube(Canvas canvas) {
            //canvas.save();
            //canvas.translate(0, 0);
            //c.drawColor(0xff00aa00);

            Location loc = mws.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            try{
                if (lat == loc.getLatitude() && lon == loc.getLongitude()){
                    return;
                }
            }catch(NullPointerException exc){
                Log.d(TAG, "gps not ready");
                return;
            }
            lat = loc.getLatitude();
            lon = loc.getLongitude();

        }

    }
}

<application android:icon="@drawable/icon" android:label="@string/app_name">

    <service android:name=".MyWallpaperService"
        android:label="@string/app_name"
        android:icon="@drawable/icon"
        android:permission="android.permission.BIND_WALLPAPER">

        <intent-filter>
            <action android:name="android.service.wallpaper.WallpaperService" />
        </intent-filter>
        <meta-data android:name="android.service.wallpaper"
            android:resource="@xml/livewallpaper" />

    </service>

</application>

A: You need to add
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

to use the GPS. To use network location, use:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

I think this will work for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set data values on a vtkStructuredGrid I'm trying to fill in a structured grid with an analytical field, but despite reading the vtk docs, I haven't found out how to actually set scalar values at the grid points or the set the spacing/origin info of the grid.  Starting from the code below, how do I

*

*associate spatial information with the grid (ie cell 0,0,0 is at coordinates 0,0,0, the spacing is dx in every direction)

*associate scalar values with each grid point.  To start, I just need one, but eventually I'd like to store 3 pieces of data at each point (not a vector, 3 distinct scalars).

grid = vtk.vtkStructuredGrid()
numPoints = int((maxGrid - minGrid)/dx)
grid.SetDimensions(numPoints, numPoints, numPoints)

A: In VTK there are 3 types of "structured" grids, vtkImageData (vtkUniformGrid derives from this), vtkRectilinearGrid, and vtkStructuredGrid.  They are all structured in the sense that the topology is set.  vtkImageData has constant spacing between points and is axis aligned, vtkRectilinearGrid is axis aligned but can vary the spacing in each axis direction, and vtkStructuredGrid has arbitrarily located points (cells may not be valid though).
For what you want to do you should do:
from vtk import *
dx = 2.0
grid = vtkImageData()
grid.SetOrigin(0, 0, 0) # default values
grid.SetSpacing(dx, dx, dx)
grid.SetDimensions(5, 8, 10) # number of points in each direction
# print grid.GetNumberOfPoints()
# print grid.GetNumberOfCells()
array = vtkDoubleArray()
array.SetNumberOfComponents(1) # this is 3 for a vector
array.SetNumberOfTuples(grid.GetNumberOfPoints())
for i in range(grid.GetNumberOfPoints()):
    array.SetValue(i, 1)

grid.GetPointData().AddArray(array)
# print grid.GetPointData().GetNumberOfArrays()
array.SetName("unit array")


text:
Q: Two measurable space - how to check Is it true that

*

*$\left( \mathbb{N}, \mathcal{P}(\mathbb{N}), \mu(M) = \sum_{n \in M} 2^{-n} \right)$ is measurable space?

*$\left( \mathbb{N}, \mathcal{P}(\mathbb{N}), \mu(M) = |M| \right)$ is measurable space?

The first condition is $\mu(\emptyset)=0$. And in these two case it is obviously. But how can I prove the second condition: $$\mu \left( \bigcup_{n=1}^{\infty}A_n \right) = \sum_{n=1}^{\infty} \mu \left( A_n \right)$$
where of course for any $m,n$ such that $n \not= m$ we have $A_n \cap A_m = \emptyset$.
Intuitively it is also obviously but how prove it more formal?

A: In both cases, the power sets are sigma algebras, so all that remains is to check that the 3rd coordinates of your triples are measures.  To check countable additivity, let $A_i$ be a countable disjoint collection of subsets of $\mathbb{N}$.  Then for the first one, you know that
$\mu(\bigcup_{i=1}^\infty A_i)=\sum_{k \in \bigcup_{i=1}^\infty A_i} 2^{-k}$ which in particular means that the right side converges. (Which actually should've been checked before even defining $\mu$ but I leave that to you.)  Also, $\mu$ is a finite-valued nonnegative set function, which is also clear by comparison test.  Coming from the other side you wonder if $\sum_{i=1}^\infty \sum_{k \in A_i} 2^{-k}$ converges to the same value.  The inside sum always makes sense as a corollary again of checking that $\mu$ is even well-defined, and the outer sum is still fine because actually its convergence and value is a subsequence of the limit of partial sums that you know to exist when computing $\sum_{k \in \bigcup_{i=1}^\infty A_i} 2^{-k}$.
I hope this has helped, and perhaps you can do the second one now.  I'm having some issues determining exactly what I can use since probably Tonelli's theorem is out of the question.  But Rudin, for example, proves a theorem about interchanging infinite sums without even discussing measure theory.  If you find that relative to your current understanding my proof is slightly circular or lacking detail, you may want to look into that.


text:
Q: Detect undefinded variable for msvc compiler for c++14 Consider the following C++14 (it's important) code:
struct B {
    static constexpr int a = 1;
};

int main() {
    auto p = &B::a;
}

Being compiled with gcc it leads to "undefined reference" since B::a is not defined (just declared). To fix the issue we just have to define B::a outside the struct:
constexpr int B::a;

But I have a problem with msvc compiler. Even without definition of B::a the first code excerpt just compiled well (without an "undefined reference" issue).
Is there a way (I think a compiler option) to say msvc to detect such an issue being compiled for C++14 standard, i.e. when /std:c++14 option is used?
Here is the link to godbolt where I've tested the issue: https://godbolt.org/z/G8BnFY


text:
Q: sql query selecting birthday today from number format Let say i have identification card number in this format
 720901155172

we can convert the number to birthday by using this code
        $data = '720901155172';
        $head = substr($data, 0, 6);

        $year = (int) substr($head, 0, 2);
        $currentYear = date('Y');

        $max = (int) substr($currentYear, 2, 4);

        $byear = $year + ($year > $max ? 1900 : 2000);
        $bmth = (int) substr($head, 2, 2);
        $bday = (int) substr($head, 4, 2);

        $bdate = date('Y-m-d', strtotime(sprintf('%s-%s-%s', $byear, $bmth, $bday)));
        echo $bdate;//output : 1972-09-01

how do i select all user that is having birthday today ?
is this possible ?
$sql="SELECT ic FROM users";

A: Since the birthday that you need to look at is on positions 2-5 in the ic string you can use REGEX to match it with today's date.
SELECT * FROM users WHERE ic REGEXP '^[0-9]{2}0901[0-9]{6}$';

Assuming each ic is a fixed length of 12 numbers this will match a string that:

*

*starts with 2 numbers between 0-9

*matches input date exactly

*ends with 6 numbers between 0-9

Today's date part of the REGEX you will have to insert into the query dynamically with PHP, so the code would look (depending on what framework you are using) something like:
$db->get_results("SELECT * FROM users WHERE ic REGEXP '^[0-9]{2}%d[0-9]{6}$'", $date);

A: What I understand is first 6 digits of your ic is YYMMDD. If this is not the case please ignore.
Accordingly you need this conversion in sql.
    select ic,
    case when substring(ic,1,2) <Substring(YEAR(NOW()),-2)
    then Concat('20',substring(ic,1,2),'-'  ,substring(ic,3,2),'-', substring(ic,5,2))
    else
     Concat('19',substring(ic,1,2),'-'  ,substring(ic,3,2),'-', substring(ic,5,2))
    end as derived_date
    from Users

please update 'Substring(YEAR(NOW()),-2)' with your $max, 2 digit year.


text:
Q: Swift - Increase speed of a moving Node using SpriteKit I am working on a game similar to pong, while starting the game I apply impulse to the ball in random direction, which is at the centre of the screen e.g.
func impulse(){
    let randomNum:UInt32 = arc4random_uniform(200)
    let someInt:Int = Int(randomNum)

    //Ball Impulse
    if someInt<49{
    ball.physicsBody?.applyImpulse(CGVector(dx: ballSpeed+3, dy: ballSpeed-5))
    }else if someInt<99{
        ball.physicsBody?.applyImpulse(CGVector(dx: ballSpeed+5, dy: -ballSpeed+5))
    }else if someInt<149{
        ball.physicsBody?.applyImpulse(CGVector(dx: -ballSpeed-5, dy: -ballSpeed+5))
    }else if someInt<200{
        ball.physicsBody?.applyImpulse(CGVector(dx: -ballSpeed-3, dy: ballSpeed-5))
    }

}

Where ballSpeed is the preset speed of ball.
So is there any way I can gradually increase the velocity of ball with duration while it is in motion? As ball will keep on bouncing around the screen so it is difficult to apply force to it using dx and dy.
EDIT -
I am using above method just to assign a random quadrant/direction to ball at start of the game.
Start, when impulse method is implemented e.g.
Game start image
And I want to increase speed of the ball by a predefined unit over time during gameplay e.g.
Gameplay

A: Ok, here you go! The ball CONSTANTLY gets faster, no matter what!!! Adjust amount to determine how much the ball gains speed each frame.
class GameScene: SKScene, SKPhysicsContactDelegate {

  let ball = SKShapeNode(circleOfRadius: 20)
  var initialDY = CGFloat(0)
  var initialDX = CGFloat(0)

  override func didMove(to view: SKView) {
    self.physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
    self.physicsWorld.gravity = CGVector.zero

    // Configure ball pb:
    let pb = SKPhysicsBody(circleOfRadius: 20)
    ball.physicsBody = pb
    addChild(ball)

    pb.applyImpulse(CGVector(dx: 10, dy: 10))
  }

  override func update(_ currentTime: TimeInterval) {
    initialDX = abs(ball.physicsBody!.velocity.dx)
    initialDY = abs(ball.physicsBody!.velocity.dy)
  }

  override func didSimulatePhysics() {
    guard let pb = ball.physicsBody else { fatalError() }

    // decrease this to adjust the amount of speed gained each frame :)
    let amount = CGFloat(5)

    // When bouncing off a wall, speed decreases... this corrects that to _increase speed_ off bounces.
    if abs(pb.velocity.dx) < abs(initialDX) {
      if      pb.velocity.dx < 0 { pb.velocity.dx = -initialDX - amount }
      else if pb.velocity.dx > 0 { pb.velocity.dx =  initialDX + amount }
    }

    if abs(pb.velocity.dy) < abs(initialDY) {
      if      pb.velocity.dy < 0 { pb.velocity.dy = -initialDY - amount }
      else if pb.velocity.dy > 0 { pb.velocity.dy =  initialDY + amount }
    }
  }
}

you can modify this to only increase speed every 5 seconds with an SKAction.repeatForever(.sequence([.wait(forDuration: TimeInterval, .run( { code } ))) but IMO having it constantly gain speed is a bit more awesome and easier to implement.


text:
Q: How to get the current working directory in Rust if it is a symlink If there is a directory /tmp/foo/bar and a directory /tmp/bar which is a link to /tmp/foo/bar made with ln -s /tmp/foo/bar /tmp/bar, then if the current working directory is /tmp/bar, Rust's std::env::current_dir will return /tmp/foo/bar instead of /tmp/bar?
Is there a way to get the current working directory in Rust without resolving symbolic links?

A: As per this GitHub issue, this is not really possible.

For UNIX Rust just calls getcwd() and that behavior is documented in the POSIX spec, so it will be the same on all conforming implementations.

From the linked spec:

The pathname shall contain no components that are dot or dot-dot, or are symbolic links.

A possible workaround is to look at the PWD environment variable, but it's dependent on the shell to set this, and it's not a requirement that shells do so.  The executable may not have been invoked from a shell, either.


text:
Q: Extreme values for a vector equation For a question on physics.stackexchange about Does the Ampère-Maxwell law fail for the field of a uniformly moving point charge? with
$$ \vec B(P) = \dfrac{\mu_0 q}{4 \pi} \dfrac{1 - v^2/c^2}{[1 - (v^2/c^2) sin^2 \phi]^{3/2}} \dfrac{\vec v \times \hat r}{r^2} $$
for this sketch

I want to know the extreme value for $v \rightarrow c$ and have doubts about my thoughts:
A possible case is $\phi =0°$. For this angle the equation gives
$$ \vec B(P) = \dfrac{\mu_0 q}{4 \pi} \dfrac{1 - v^2/c^2}{1} \dfrac{\vec v \times \hat r}{r^2} $$
But what is about the term $\dfrac{\vec v \times \hat r}{r^2}$? It is a vector product and for 0° it is zero and $ \vec B(P)$ equals zero?
Taking $\phi =90°$ I'm lost because I don't know what is the solution for  $v \rightarrow c$ of
$$ \dfrac{1 - v^2/c^2}{[1 - (v^2/c^2)]^{3/2}} $$

A: From the picture we have $0\le y=r\sin(\pi-\phi)$, so $\sin\phi=-\frac yr$. Put $A=\frac{\mu_0qc^2}{4\pi}$, $\vec u=\frac {\vec v}{c}$. I assume that $\mu_0\ne 0$, $r\ne 0$, and $\hat r=\frac {\vec r}{r}$.  Then
$$\vec B(P)=A\cdot\frac{1-u^2}{\left(1-u^2\frac {y^2}{r^2}\right)^{3/2}}\cdot \frac{\vec u\times\vec r}{r^3}.$$
Assume first that the charge needs to go a long way to be accelerated to $c$, so $r$ tends to infinity. Then   $\vec B(P)$ tend to zero because $A$ is constant, $ u^2\frac {y^2}{r^2}$ tends to zero, $1-u^2$ is bounded, and $|\vec u\times\vec r |=O(r)=o(r^3)$.
As an opposite case from now I assume that $\vec r$ is constant.
Assume first that $x\ne 0$. Then $y<r$, so the denominator $1-u^2\frac {y^2}{r^2}\ne 0$ and $B(\vec P)$ is a continuous function of $u$. Therefore $\lim_{u\to 1} \vec B(P)=\vec B(P)|_{u=1}=0$, because when $u=1$ we have $1-u^2=0$.
Assume now that $x=0$. Then $y=r$. Since $\vec u=(u,0,0)$ and $\vec r=(0,r,0)$, we have
$$\frac{\vec u\times\vec r}{r^3}=\frac 1{r^3} \cdot \begin{vmatrix}
\mathbf{i} & \mathbf{j} & \mathbf{k}\\
u & 0 & 0 \\
0 &  r  & 0
\end{vmatrix}=\frac{u\mathbf{k}}{r^2}.$$
For $v=c$ the value of $\vec B(P)$ is undefined, because the denominator $\left(1-u^2\frac {y^2}{r^2}\right)^{3/2}=0$. For $v<c$ we have
$$\vec B(P)=A\cdot\frac{1-u^2}{\left(1-u^2\right)^{3/2}}\cdot \frac{\vec u\times\vec r}{r^3}= \frac{Au\mathbf{k}}{\left(1-u^2\right)^{1/2}r^2}.$$
$$\lim_{u\to 1, u\ne 1} \vec B(P)= \lim_{u\to 1, u\ne 1} \frac{Au\mathbf{k}}{\left(1-u^2\right)^{1/2}r^2}=\infty.$$
Now about the growth of $\vec B(P)$ when $v$ tends to $c$, that is $u$ tends to $1$. We have
$$|\vec B(P)|=\left|A\cdot\frac{1-u^2}{\left(1-u^2\frac {y^2}{r^2}\right)^{3/2}}\cdot \frac{\vec u\times\vec r}{r^3}\right|=\frac{C(1-u^2)u}{\left(1-a u^2\right)^{3/2}},$$ where $C=\left|A\cdot \frac{(1,0,0)\times\vec r}{r^3}\right|$ and $a=\frac {y^2}{r^2}\le 1$.
If  $x\ne 0$ then $0\le a<1$, and the derivative $\left(\frac{(1-u^2)u}{\left(1-a u^2\right)^{3/2}}\right)'$ is $\frac{1-(3-2a)u^2}{(1-au^2)^{5/2}}$, so  $|\vec B(P)|$  monotonically grows when $u$ grows from $0$ to $\frac{1}{\sqrt{3-2a}}$ and then monotonically decreases to $0$ when $u$ grows to $1$.
If $x=0$ then $a=1$  and $|\vec B(P)|=\frac{Cu}{\left(1-u^2\right)^{1/2}}$. This value monotonically grows to the infinity when $u$ monotonically tends to $1$.

A:
In terms of my answer here :Does the Ampère-Maxwell law fail for the field of a uniformly moving point charge?,
 the electric field intensity vector $\:\mathbf{E}\:$ and the magnetic-flux density vector $\:\mathbf{B}\:$  at the field point $\:\mathrm P(\mathbf{r})=\mathrm P(x,y,z) \:$ are :
\begin{equation}
\mathbf{E}\left(\mathbf{r},t\right)=\dfrac{q}{4\pi \epsilon_{0}\gamma^{2}}\dfrac{1}{\left(1\!-\!\beta^{2}\sin^{2}\!\phi\right)^{\frac32}}\dfrac{\mathbf{r}_{\bf o}}{\:\:\Vert\mathbf{r}_{\bf o}\Vert^{3}}
\tag{01}
\end{equation}
and
\begin{equation}
\mathbf{B}\left(\mathbf{r},t\right)=\dfrac{1}{c^{2}}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}\right)=\dfrac{\mu_{0}q}{4\pi \gamma^{2}}\dfrac{1}{\left(1\!-\!\beta^{2}\sin^{2}\!\phi\right)^{\frac32}}\dfrac{\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{r}_{\bf o}}{\:\:\Vert\mathbf{r}_{\bf o}\Vert^{3}}
\tag{02}
\end{equation}
where
\begin{equation}
\beta=\dfrac{\upsilon}{\:c\:}\,,\quad \gamma=\left(1-\beta^{2}\right)^{-\frac12}
\tag{03}
\end{equation}
Note that $\:\mathbf{r}_{\bf o}\:$ is the position vector of the field point $\:\mathrm P(x,y,z)\:$ with respect to the present position $\:\mathbf{x}(t)\:$ of the charge $\:q\:$ on the $\:x-$axis
\begin{equation}
\mathbf{r}_{\bf o}=\mathbf{r}-\mathbf{x}
\tag{04}
\end{equation}
In terms of the symbols in the question :
\begin{equation}
r\equiv\Vert\mathbf{r}_{\bf o}\Vert\,,\quad \hat r \equiv \dfrac{\mathbf{r}_{\bf o}}{\Vert\mathbf{r}_{\bf o}\Vert}
\tag{05}
\end{equation}
that is $\:\hat r \:$ is the unit vector along $\:\mathbf{r}_{\bf o}\:$. The angle $\:\phi\:$ is that of $\:\mathbf{r}_{\bf o}\:$ with respect to the constant velocity vector of the charge $\:\boldsymbol{\upsilon}\:$ along the $\:x-$axis.
Equation (02) in full analysis is
\begin{equation}
\mathbf{B}\left(\mathbf{r},t\right)=\dfrac{\mu_{0}q}{4\pi}\dfrac{1-\dfrac{\upsilon^{2}}{c^{2}}}{\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\sin^{2}\!\phi\right)^{\frac32}}\dfrac{\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{r}_{\bf o}}{\:\:\Vert\mathbf{r}_{\bf o}\Vert^{3}}
\tag{06}
\end{equation}
We have the following limits for $\:\phi\;\longrightarrow\;0\:$
\begin{align}
 \lim_{\phi\rightarrow 0}\dfrac{\mathbf{r}_{\bf o}}{\Vert\mathbf{r}_{\bf o}\Vert} & =\mathbf{i}=\text{unit vector along the }x\!-\!\text{axis, so}
\tag{07a}\\
\lim_{\phi\rightarrow 0}\dfrac{\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{r}_{\bf o}}{\Vert\mathbf{r}_{\bf o}\Vert} & =\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{i}=\boldsymbol{0}
\tag{07b}\\
\lim_{\phi\rightarrow 0}\Vert\mathbf{r}_{\bf o}\Vert^{2} & = \boldsymbol{+}\infty\Longrightarrow \lim_{\phi\rightarrow 0}\left(\dfrac{1}{\Vert\mathbf{r}_{\bf o}\Vert^{2}}\right)=0
\tag{07c}
\end{align}
so
\begin{equation}
\lim_{\phi\rightarrow 0}\mathbf{B}\left(\mathbf{r},t\right)=\dfrac{\mu_{0}q}{4\pi}\dfrac{1-\dfrac{\upsilon^{2}}{c^{2}}}{\left[1\!-\!\dfrac{\upsilon^{2}}{c^{2}}   \underbrace{\lim_{\phi\rightarrow 0}(\sin^{2}\!\phi)}_{0}   \right]^{\frac32}}\underbrace{\lim_{\phi\rightarrow 0}\left(\dfrac{\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{r}_{\bf o}}{\:\:\Vert\mathbf{r}_{\bf o}\Vert}\right)}_{\boldsymbol{0}}\underbrace{  \lim_{\phi\rightarrow 0}\left(\dfrac{1}{\Vert\mathbf{r}_{\bf o}\Vert^{2}}\right)}_{0}=\boldsymbol{0}
\tag{08}
\end{equation}
as expected since for $\:\phi\;\longrightarrow\;0\:$ the charge tends to be at $\:\boldsymbol{-}\infty\:$ of the $\:x-$axis, see Figure above.
For $\:\phi =90^{\rm o}\:$ the vector $\:\mathbf{r}_{\bf o}\:$ is the projection of the position vector $\:\mathbf{r}=(x,y,z)\:$ of the field point $\:\mathrm P\:$  on the $\:yz-$plane
\begin{equation}
(\mathbf{r}_{\bf o})_{\phi =90^{\rm o}}=y\mathbf{j}+z\mathbf{k}\,, \quad \Vert\mathbf{r}_{\bf o}\Vert_{\phi =90^{\rm o}}=\sqrt{y^{2}+z^{2}}
\tag{09}
\end{equation}
and
\begin{equation}
\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{r}_{\bf o}=
\begin{vmatrix}
\:\:\mathbf{i} & \mathbf{j} & \mathbf{k}\:\: \vphantom{\tfrac12}\\
\:\:\upsilon & 0 & 0  \:\:\vphantom{\tfrac12}\\
\:\: 0 &  y  & z \:\: \vphantom{\tfrac12}
\end{vmatrix}
=\upsilon(-z\mathbf{j}+y\mathbf{k})
\tag{10}
\end{equation}
so
\begin{equation}
\left[\mathbf{B}\left(\mathbf{r},t\right)\right]_{\phi =90^{\rm o}}=\dfrac{\mu_{0}q}{4\pi}\dfrac{\upsilon}{\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)^{\frac12}}\dfrac{(-z\mathbf{j}+y\mathbf{k})}{\left(y^{2}+z^{2}\right)^{\frac32}}
\tag{11}
\end{equation}
and
\begin{equation}
\lim_{\upsilon\rightarrow c}\left[\mathbf{B}\left(\mathbf{r},t\right)\right]_{\phi =90^{\rm o}}=\dfrac{\mu_{0}q}{4\pi}\dfrac{(-z\mathbf{j}+y\mathbf{k})}{\left(y^{2}+z^{2}\right)^{\frac32}} \underbrace{\lim_{\upsilon\rightarrow c}\left[\dfrac{\upsilon}{\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)^{\frac12}}\right]}_{\boldsymbol{+}\infty}=\boldsymbol{\infty}
\tag{12}
\end{equation}

EDIT
In my answer here :Does the Ampère-Maxwell law fail for the field of a uniformly moving point charge?,
there are given the following alternative expressions for the electric field intensity vector $\:\mathbf{E}\:$ and the magnetic-flux density vector $\:\mathbf{B}\:$  at the field point $\:\mathrm P(\mathbf{r})=\mathrm P(x,y,z) \:$ :
\begin{equation}
\mathbf{E}\left(x,y,z,t\right)=\dfrac{q}{4\pi \epsilon_{0}}\dfrac{\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)}{\left[\left(x\!-\!\upsilon\,t\right)^{2}\!+\!\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)\left(y^{2}+z^{2}\right)\right]^{\frac32}}
\begin{bmatrix}
x\!-\!\upsilon\,t \vphantom{\dfrac12}\\
y  \vphantom{\dfrac12}\\
z \vphantom{\dfrac12}
\end{bmatrix}
\tag{13}
\end{equation}
\begin{equation}
\mathbf{B}\left(x,y,z,t\right) =\dfrac{\mu_{0}q}{4\pi }\dfrac{\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)}{\left[\left(x\!-\!\upsilon\,t\right)^{2}\!+\!\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)\left(y^{2}+z^{2}\right)\right]^{\frac32}}
\begin{bmatrix}
\hphantom{-} 0 \vphantom{\dfrac{\partial}{\partial x}}\\
-\upsilon\,z  \vphantom{\dfrac{\partial}{\partial x}}\\
\hphantom{-}\upsilon\,y \vphantom{\dfrac{\partial}{\partial x}}
\end{bmatrix}
\tag{14}
\end{equation}
For the magnitudes we have
\begin{equation}
\Vert\mathbf{E}\Vert=\dfrac{q}{4\pi \epsilon_{0}}\dfrac{\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)\left[\left(x\!-\!\upsilon\,t\right)^{2}\!+\!R^{2}\right]^{\frac12}}{\left[\left(x\!-\!\upsilon\,t\right)^{2}\!+\!\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)R^{2}\right]^{\frac32}}
\tag{15}
\end{equation}
\begin{equation}
\Vert\mathbf{B}\Vert =\dfrac{\mu_{0}q}{4\pi }\dfrac{\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)\,\upsilon\,R}{\left[\left(x\!-\!\upsilon\,t\right)^{2}\!+\!\left(1\!-\!\dfrac{\upsilon^{2}}{c^{2}}\right)R^{2}\right]^{\frac32}}
\tag{16}
\end{equation}
where $\:R=\sqrt{y^{2}+z^{2}}\:$ the distance of the observer $\:\mathrm P\:$ from the $\:x-$axis (see Figure).
Now, in (16) take $\:\upsilon/c\:$ as close to $\:1\:$ you want and R as close to $\:0\:$ you want. In any case $\:\Vert\mathbf{B}\Vert\:$ goes closer and closer to $\:0$.

Video here : Electric field of a uniformly moving point charge


text:
Q: Will using a Cloud PaaS automatically solve scalability issues? I'm currently looking for a Cloud PaaS that will allow me to scale an application to handle anything between 1 user and 10 Million+ users ... I've never worked on anything this big and the big question that I can't seem to get a clear answer for is that if you develop, let's say a standard application with a relational database and soap-webservices, will this application scale automatically when deployed on a Paas solution or do you still need to build the application with fall-over, redundancy and all those things in mind?
Let's say I deploy a Spring Hibernate application to Amazon EC2 and I create single instance of Ubuntu Server with Tomcat installed, will this application just scale indefinitely or do I need more Ubuntu instances? If more than one Ubuntu instance is needed, does Amazon take care of running the application over both instances or is this the developer's responsibility? What about database storage, can I install a database on EC2 that will scale as the database grow or do I need to use one of their APIs instead if I want it to scale indefinitely?
CloudFoundry allows you to build locally and just deploy straight to their PaaS, but since it's in beta, there's a limit on the amount of resources you can use and databases are limited to 128MB if I remember correctly, so this a no-go for now. Some have suggested installing CloudFoundry on Amazon EC2, how does it scale and how is the database layer handled then?
GAE (Google App Engine), will this allow me to just deploy an app and not have to worry about how it scales and implements redundancy? There appears to be some limitations one what you can and can't run on GAE and their price increase recently upset quite a large number of developers, is it really that expensive compared to other providers?
So basically, will it scale and what needs to be done to make it scale?

A: That's a lot of questions for one post. Anyway:

*

*Amazon EC2 does not scale automatically with load. EC2 is basically just a virtual machine. You can achieve scaling of EC2 instances with Auto Scaling and Elastic Load Balancing.

*SQL databases scale poorly. That's why people started using NoSQL databases in the first place. It's best to see which database your cloud provider offers as a managed service: Datastore on GAE and DynamoDB on Amazon.

*Installing your own database on EC2 instances is very impractical as EC2 has ephemeral storage (it looses all data on "disk" when it reboots).

*GAE Datastore is actually a one big database for all applications running on it. So it's pretty scalable - your million of users should not be a problem for it.
http://highscalability.com/blog/2011/1/11/google-megastore-3-billion-writes-and-20-billion-read-transa.html

*Yes App Engine scales automatically, both frontend instances and database. There is nothing special you need to do to make it scale, just use their API.

*There are limitations what you can do with AppEngine:
A. No local storage (filesystem) - you need to use Datastore or Blobstore.
B. Comet is only supported via their proprietary Channels API
C. Datastore is a NoSQL database: no JOINs, limited queries, limited transactions.

*Cost of GAE is not bad. We do 1M requests a day for about 5 dollars a day. The biggest saving comes from the fact that you do not need a system admin on GAE ( but you do need one for EC2). Compared to the cost of manpower GAE is incredibly cheap.
Some hints to save money (an speed up) GAE:
A. Use get instead of query in Datastore (requires carefully crafting natiral keys).
B. Use memcache to cache data you got form datastore. This can be done automatically with objectify and it's @Cached annotation.
C. Denormalize data. Meaning you write data redundantly in various places in order to get to it in as few operations as possible.
D. If you have a lot of REST requests from devices, where you do not use cookies, then switch off session support ( or roll your own as we did). Sessions use datastore under the hood and for every request it does get and put.
E. Read about adjusting app settings. Try different settings (depending how tolerant your app is to request delay and your traffic patterns/spikes). We were able to cut down frontend instances by 70%.


text:
Q: How to extract numbers after string using regexp? I need to extract the number/numbers that come after the last letter in a given string,  using regexp or any other possible function.
For example, if the string is 'a23kfj879lp999', I need only 999 since the last letter in the string is p.

A: Use the REGEX_SUBSTR function:
SELECT REGEXP_SUBSTR('a23kfj879lp999', '([0-9]+)$') FROM dual

Explanation:
REGEX_SUBSTR simply extracts the first substring from the source string that matches the respective pattern.
Syntax:
REGEXP_SUBSTR( string, pattern [, start_position [, nth_appearance [, match_parameter [, sub_expression ] ] ] ] )


text:
Q: Partially Checking-in changes in TFS/VSTS2010 Is there a way to easily facilitate checking-in in chunks rather than as a whole?
It becomes too much work to create shelvesets for each chunk of check-in. Plus, this is especially a problem with csproj files which are hard to modify manually for each changeset I want to check in. PS: I don't live in an ideal world where I only work on one problem at a time.
Optimally, I would like to be given the option to use the conflict-resolution tool with each check-in, but I couldn't find a way to do this.  Am I the only one with this issue? Any ideas?

A: In Dev11, we have introduced a new concept of My Work, where you can easily switch to different tasks. When you start working, just do as you are used to do with editing files. When you want to work on something else, you can just suspend the work (which will create a shelveset on the background) and you can work on the other problem. Once you are done with the other task, you can resume your suspended work. It will unshelve the changes and even reloads the settings (open windows / breakpoints).
To learn more about My Work see \\BUILD\ session of Jamie Cool


text:
Q: Convert GTK RecordMyDesktop OGV video for OpenShot editing I make some screencasts with my laptop. The software that I use in Ubuntu is GTK RecordMyDesktop which gives me an OGV file.
The quality is perfect and I am happy with it.
For publishing or giving it to other people though I need to do some minor video editing which I like to do it in OpenShot which gives me 1080p HD video hassle free. The problem is that is you import OGV to OpenShot the audio and video won't be in sync after the conversion and there are other compatibility problems with OGV in OpenShot as mentioned in other forums.
So, I need to convert it to a usable format in between. This conversion should be fast and lossless in order to import it in OpenShot and continue the workflow there.

A: I looked a little into the specifications and found that …

recordMyDesktop produces files using only open formats. These are theora for video and vorbis for audio, using the ogg container.

So, it's very likely that OpenShot has troubles parsing that container or either of these codecs. I would try and report a bug with OpenShot nonetheless, but if you want to try another container or video/audio codecs, you might succeed in parsing the videos without synchronization issues.
OpenShot uses FFmpeg's libraries for decoding, so chances are high it'll be able to parse anything you encoded using FFmpeg itself.
Your requirement was for the conversion to be lossless. This leaves two options:

*

*Change the container and keep the codecs, e.g. from OGV to MKV. I believe MKV is the only container that accepts both codecs you have.
If you install a recent copy of FFmpeg (e.g. using a static build from here) — and please don't use the outdated version Ubuntu provides — then all you need to do is:
 ffmpeg -i input.ogv -c copy output.mkv

Maybe that solves a problem related to OGV in OpenShot.

*Transcode the video and audio streams to lossless codecs, e.g. from Theora to lossless h.264 video and Vorbis to PCM audio.
Again, using FFmpeg, this would be the following for lossless h.264 and PCM audio to a MKV container. Note that h.264 usually is not lossless, but -qp 0 will achieve that:
 ffmpeg -i input.ogv -c:v libx264 -qp 0 -c:a pcm_s16le out.mkv

Or, using an MP4 container, which doesn't support PCM audio out of the box. We'll need to re-encode audio to AAC here and supply a little higher bitrate so as not to reduce quality too much:
 ffmpeg -i input.ogv -c:v libx264 -qp 0 -c:a aac -strict -2 -b:a 192k out.mp4

Hopefully, that'll solve your issues. If not, filing a bug report with OpenShot would probably be the best solution.
If you get confused by the termini used here, please check out the following question: What is a Codec (e.g. DivX?), and how does it differ from a File Format (e.g. MPG)?, and for FFmpeg usage, read our related blog entry.


text:
Q: Move Assignment incompatible with Standard Copy and Swap Testing out the new Move Semantics.
I just asked about an issues I was having with the Move Constructor. But as it turns out in the comments the problem is really that the "Move Assignment" operator and  "Standard Assignment" operator clash when you use the standard "Copy and Swap" idiom.
This is the class I am using:
#include <string.h>
#include <utility>

class String
{
    int         len;
    char*       data;

    public:
        // Default constructor
        // In Terms of C-String constructor
        String()
            : String("")
        {}

        // Normal constructor that takes a C-String
        String(char const* cString)
            : len(strlen(cString))
            , data(new char[len+1]()) // Allocate and zero memory
        {
            memcpy(data, cString, len);
        }

        // Standard Rule of three
        String(String const& cpy)
            : len(cpy.len)
            , data(new char[len+1]())
        {
            memcpy(data, cpy.data, len);
        }
        String& operator=(String rhs)
        {
            rhs.swap(*this);
            return *this;
        }
        ~String()
        {
            delete [] data;
        }
        // Standard Swap to facilitate rule of three
        void swap(String& other) throw ()
        {
            std::swap(len,  other.len);
            std::swap(data, other.data);
        }

        // New Stuff
        // Move Operators
        String(String&& rhs) throw()
            : len(0)
            , data(null)
        {
            rhs.swap(*this);
        }
        String& operator=(String&& rhs) throw()
        {
            rhs.swap(*this);
            return *this;
        }
};

Pretty bog standard I think.
Then I tested my code like this:
int main()
{
    String  a("Hi");
    a   = String("Test Move Assignment");
}

Here the assignment to a should use the "Move Assignment" operator. But there is a clash with the "Standard Assignment" operator (which is written as your standard copy and swap).
> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/c++/4.2.1
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix

> g++ -std=c++11 String.cpp
String.cpp:64:9: error: use of overloaded operator '=' is ambiguous (with operand types 'String' and 'String')
    a   = String("Test Move Assignment");
    ~   ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String.cpp:32:17: note: candidate function
        String& operator=(String rhs)
                ^
String.cpp:54:17: note: candidate function
        String& operator=(String&& rhs)
                ^

Now I can fix this by modifying the "Standard Assignment" operator to:
    String& operator=(String const& rhs)
    {
        String copy(rhs);
        copy.swap(*this);
        return *this;
    }

But this is not good as it messes with the compiler's ability to optimize the copy and swap. See What is the copy-and-swap idiom? here and here
Am I missing something not so obvious?

A: All you need for copy and assignment is this:
    // As before
    String(const String& rhs);

    String(String&& rhs)
    :   len(0), data(0)
    {
        rhs.swap(*this);
    }

    String& operator = (String rhs)
    {
        rhs.swap(*this);
        return *this;
    }

   void swap(String& other) noexcept {
       // As before
   }

A: If you define the assignment operator to take a value, you should not (need not and cannot) define the assignment operator taking an rvalue-reference. There is no point to it.
In general, you only need to provide an overload taking an rvalue-reference when you need to differentiate an lvalue from an rvalue, but in this case your choice of implementation means that you don't need to make that distinction. Whether you have an lvalue or an rvalue you are going to create the argument and swap the contents.
String f();
String a;
a = f();   // with String& operator=(String)

In this case, the compiler will resolve the call to be a.operator=(f()); it will realize that the only reason for the return value is being the argument to operator= and will elide any copy --this is the point of making the function take a value in the first place!

A: Other answers suggest to have just one overload operator =(String rhs) taking the argument by value but this is not the most efficient implementation.
It's true that in this example by David Rodríguez - dribeas
String f();
String a;
a = f();   // with String& operator=(String)

no copy is made. However, assume just operator =(String rhs) is provided and consider this example:
String a("Hello"), b("World");
a = b;

What happens is

*

*b is copied to rhs (memory allocation + memcpy);

*a and rhs are swapped;

*rhs is destroyed.

If we implement operator =(const String& rhs) and operator =(String&& rhs) then we can avoid the memory allocation in step 1 when the target has a length bigger than source's. For instance, this is a simple implementation (not perfect: could be better if String had a capacity member):
String& operator=(const String& rhs) {
    if (len < rhs.len) {
        String tmp(rhs);
        swap(tmp);
    else {
        len = rhs.len;
        memcpy(data, rhs.data, len);
        data[len] = 0;
    }
    return *this;
}

String& operator =(String&& rhs) {
    swap(rhs);
}

In addition to the performance point if swap is noexcept, then operator =(String&&) can be noexcept as well. (Which is not the case if memory allocation is "potentially" performed.)
See more details in this excellent explanation by Howard Hinnant.


text:
Q: setTimeout performing before a task in micro task queue (Job queue) I'm having trouble understanding why my code below logs the following in order:
"end"
"timeout done"
"promise"
I assumed that "promise" would log before "timeout done" since it has a priority over callback queue task (setTimeout).
My assumption after this observation is that until .then is called, the promise does not enqueue its task since it's not ready yet, and thus allows setTimeout to perform in the callback queue to be performed first. Is this correct?
const sampleFunction = function(e) {
  setTimeout(() => console.log('timeout done'), 0)
  const data = fetch(`https://jsonplaceholder.typicode.com/comments/1`)
  .then(response => {
    return response.json();
  })
  .then(json => {
    /*doSomething*/
    console.log('promise')
  });
  console.log('end')
}

A: Your console.log('promise') has to wait until your fetch().then() is done which involves a networking operation to another host (and thus non-zero time).
Your setTimeout() only has to wait until sampleFunction() returns and you get back to the event queue.  So, since the fetch().then() is non-blocking and takes non-zero amount of time, when you first get back to the event queue, only the setTimeout() is ready to go.  The networking operation will still be in process in the background.
So, this isn't a matter of prioritization.  It's a matter of completion order.  The setTimeout() inserts its completion event into the event queue long before the fetch() promise is resolved.
Perhaps you didn't realize that fetch() is non-blocking and calling it just initiates the operation and then your code execution continues after that?
In the console, you should see:
end
timeout done
promise

As long as your fetch() doesn't have any errors.


text:
Q: Prove that $m \mapsto zm$ for $z$ in the center of a ring $R$ is an $R$-module homomorphism and that $R \rightarrow \text{End}_R(M)$ is homomorphism Question:
Let $R$ be a ring with 1 and let $M$ be a left $R$-module.  Let $z$ be a fixed element of the center of $R$.  Prove that the map $m \mapsto zm$ is an $R$-module homomorphism from $M$ to itself.  Show that for a commutative ring $R$ the map from $R$ to $\text{End}(M)$ given by $r \mapsto rI$ is a ring homomorphism (where $I$ is the identity endomorphism).
My Attempt:
A mapping $\varphi: M \rightarrow M$ is an $R$-module homomorphism if and only if $\varphi(rx + y) = r\varphi(x) + \varphi(y)$ for all $r \in R$ and for all $x,y \in M$.  So, let $r \in R$, let $x$ and $y$ be any elements in the $R$-module $M$ and let $\varphi_z$ denote the map $m \mapsto zm$.  Then
\begin{equation*}
    \begin{split}
        \varphi_z(rx + y) &= z(rx + y)
        &= zrx + zy
        &= rzx + zy \quad
        &= r\varphi_z(x) + \varphi_z(y),
    \end{split}
\end{equation*}
so indeed $\varphi_z$ is an $R$-module homomorphism from $M$ to itself.  Now, let $\psi$ be defined
$$
\psi:R \rightarrow \text{End}(M), \quad r \mapsto rI.
$$
The resulting $rI$ is in fact an element in $\text{End}(M)$, since for any $m \in M$ one has $(rI)(m) = r(I(m)) = rm$, and since $R$ is commutative (every $r \in R$ is an element in the center of $R$) the mapping $(rI)(m) = rm$ is equivalent to $\varphi(m)$ where $r$ is taking the place of the fixed value $z$.  Thus $rI \in \text{End}(M)$.  To show that $\psi$ is a ring homomorphism, let $s,t \in R$.  Then $\psi(s+t)$ is an element of $\text{End}(M)$, and
\begin{equation*}
    \begin{split}
        \psi(s+t)(m) &= ((s+t))I)(m)
        &= (s + t)(I(m))
        &= (s + t)m
        &= sm + tm
        &= s(I(m)) + t(I(m))
        &= (sI)(m) + (tI)m
        &= (\psi(s))(m) + (\psi(t))(m).
    \end{split}
\end{equation*}
Similarly, $\psi(st)$ is an element of $\text{End}(M)$ and
\begin{equation*}
    \begin{split}
    \psi(st)(m) &= (stI)(m)
    &= st(I(m))
    &= stm
    &= \varphi_{st}(m)
    &= \varphi_s(m) \circ \varphi_t(m)
    &= (sI)(m) \circ (tI)(m)
    &= \psi(s)(m) \circ \psi(t)(m),
    \end{split}
\end{equation*}
thereby proving that $\psi: R \rightarrow \text{End}(M)$ is indeed a ring homomorphism.


text:
Q: ImportError: cannot import name 'App' from partially initialized module guizero most likely due to a circular import Querio hacer un proyecto con la libreria guizero y me sale este erorr ImportError: cannot import name 'App' from partially initialized module 'guizero' (most likely due to a circular import) (c:\POO\guizero.py)
from guizero import App, Text
app = App()
text_1 = Text(app, text="on top")
text_2 = Text(app, text="below")
app.display()


text:
Q: Converting HTML to sentences I was wondering if there was a way to convert HTML to sentences, for example, using JSoup. What I am looking for is something like:
List<String> convertToSentences(String html);

Sometimes sentences are separated by dots, question and exclamation marks, and sometimes by HTML structures, like
's and
's
For example, given the following HTML:

Hello World. What a great day.
    // [Hello world, What a great day]

One

Two

        // [One, Two]

Today is great</great>
    // [Today is great]

Is there any library out there which does such a thing?


text:
Q: for some or for all The following text is from Velleman's How to Prove book from the reflexive closure section:

According to the definition we gave in the last section, the relation $L =
\{(x, y) \in R × R \mid x ≤ y\}$ is a total order on $R$, but the relation $M = \{(x, y) ∈
R × R | x < y\}$ is not because it is not reflexive. Of course, these relations are
  closely related. It's clear that $M \subseteq L$, and the only ordered pairs in $L$ that are
  not in M are pairs of the form (x, x), for some x ∈ R.

My doubt is with respect to the last sentence. Isn't the only ordered pairs in $L$ which are not in M is $\forall x \in R((x,x) \in L)$. Then why is it said for some $x \in R$ rather than forall $x \in R$ ?

A: Somehow its both: The ordered pairs in $L\setminus M$ are all pairs for which there exists an $x$ such that the pair is $(x,x)$. The "all" is dropped in the original formulation from "(all) pairs of the form" and the "exists" is contained in "for some $x$".

A: You are correct in saying that it concerns all $x\in R$. The author is using "for some" in the context of "are of the form $(x,x)$...".


text:
Q: How to make the main div tag get a higher height if content is added in the two floating divs (#content and #sidebar)? Please look here to see the problem I've got:
http://jsfiddle.net/M8aV5/
#main {
width: 940px;
padding: 20px;
background-color: #ffffff;
}

(you do best by looking at the jsfiddle as I'm not completely sure which code is affecting this problem)
As you can see when more content is added to sidebar the #main div tag doesn't stretch down which makes everything look bad.
For quite a while I have just put a standard height on the #main div tag but right now it feels like I want the content to be able to stretch out how much it want to without it being ugly.
I'd really appreciate some help on this since I've got absolutely no idea where to look for an answer on this.

A: You need to clear the floats. There are a number of different ways to achieve this. The method I would recommend is called a clearfix. See it in action on your code here: http://jsfiddle.net/M8aV5/1/
.cf:before,
.cf:after {
  content: " "; /* 1 */
  display: table; /* 2 */
 }

.cf:after {
  clear: both;
}

Then just add the .cf class to your container #main. Details about this can be found here: http://nicolasgallagher.com/micro-clearfix-hack/
Another option would be to add overflow:auto property to the #main. See http://jsfiddle.net/M8aV5/2/ for a working example.
This a fairly popular option as well. There is a pretty good discussion between the two options here: ClearFix vs Overflow


text:
Q: on the day of the deadline I have term 31.3. and sentence "Teams are only allowed to have maximum of three games remaining on the day of the deadline."
I have question.
Deadline is 31.3 00:01 or 31.3 23:59?

A: The day of the deadline is March 31st.  You can't deduce the time from that.
But it doesn't matter for the statement you provided.
Starting 12:01am on March 31st, you can only have 3 games remaining.  There is probably an additional requirement that at some time on that day, you stop playing or something similar.


text:
Q: Handling Login on Multiple Devices using Parse iOS I have a problem with this login scenario in current game project:

*

*User logs in using their account details (previously registered PFUser on Parse backend)

*They play the game for a while, then leave the game (still logged in)

*They log in on another device and play

I would like to somehow log the other device out since there shouldn't be TWO or more logged in devices AT THE SAME time because it's a multiplayer game.
How can I detect whether the user is logged in somewhere else? What is the best approach to handle same user logged in in many places? I want to prevent overwriting data and inconsistency. Thanks in advance.

A: You can generate a unique identifier for each installation of your game (just a UUID stored in user defaults). Each time a use logs in, update the identifier into your user information stored on the server. When you upload any edit to the server you can send the identifier and check it with cloud code (or check the identifier first) to decide if the login is still valid. How you check depends on what you want to do if you find the login to be invalid. The more efficient route is to use cloud code and send back an error response that the app handles to alert the user and action the logout.


text:
Q: Duplicate method Meeting(String) in type Meeting - Error Hi Guys I'm having error regarding Duplicate Constructors, but according to my Assignment i need a another constructor but different field.
Specifications:

*

*Meeting – Location, Subject, list of attendees as a String array, Notes , addAttendee(String name) method.

*Constructor to set a single attendee to the attendee array.

*Constructor to accept an array of strings assign to the list of attendees.

*Two more constructors that are the same as the previous two but allow setting the note field as a String.
Here is part of code
public Meeting(String name) {
    this.name = name;
    listofAttendees[count] = name;
    count++;
    // blank constructor for no parameter super constructor

}

// Constructor to accept an array of strings assign to the list of Attendees
public Meeting(String[] listofAttendees) {
    this.listofAttendees = listofAttendees;

}

// CONStructors for note field

public Meeting(String notes) {    // Error here!
    this.notes = notes;

}

A: You are getting Duplicate Constructor error because if you will look at these two Constructors

*

*Meeting(String name)

*Meeting(String notes)

they basically have the same method signature. You need to think of something else to get around it.
Your specification is basically asking you to add 'notes' field in addition the fields present in your previous constructors. That way it won't conflict with your method signatures.

A: you can not have more than one method with the same name and the same type of parameters.
Make only one constructor with name and notes, and if you want to assign only i.e name pass a null parameter as notes.
public Meeting(String names, String notes);

A: "names" and "notes" is just a local variables, your functions from the outside look exactly the same, therefore the ambiguity. You should probably have a constructor with both parameters. How do you tell which constructor you call from outside for like new MyClass(myString)


text:
Q: How to eliminate the flicker on the right edge of TPaintBox (for example when resizing) Summarization:
Say that I have a TForm and two panels. The panels are aligned alTop and alClient. The alClient panel contains a TPaintBox, whose OnPaint involve drawing codes.
The default value of DoubleBuffered on the components are false.
During the drawing process, flicker is obvious because the form, the panels all paint their background.
Because the form is covered by the panels, it is probably fine to intercept its WM_ERASEBKGND message. If not, one could see flickering on the panels, and flickering on the right edge of the panels when the form is resized, because form paints its background.
Secondly, because the alTop panel is intended to be a container for some buttons, it is probably fine to set its DoubleBuffered to true to let Delphi ensure there is no flicker on it. It probably won't introduce much performance burden.
Thirdly, because the alClient panel is intended only to be a container for another drawing component, this panel is most likely not involved in composing the final drawing. In this respect, it's probably good to use a TPanel descendant instead of a standard TPanel. In this TPanel descendant, override the protected procedure Paint and do nothing inside the procedure, especially not the inherited call to avoid the FillRect call in the base class TCustomPanel.Paint. Furthermore, intercept the WM_ERASEBKGND message and also do nothing inside. This is because when the TPanel.ParentBackground is False, Delphi is responsible for repainting the background, and when it is True, ThemeService is responsible.
Lastly, to paint without flicker in the TPaintBox:
(1) Using VCL built-in drawing routines, it is probably better that...
(2) Using OpenGL, with OpenGL's double buffer enabled.
(3) ...
===Q: How to eliminate the flicker on the right edge of TPaintBox?===
Suppose that for one TForm, I have two panels on it. The top one is aligned alTop relative to the form and considered as a container for buttons. The other one is aligned alClient relative to the form and considered as a container for drawing components (such as TPaintBox from VCL, or TPaintBox32 from Graphics32). For the latter panel, its WM_ERASEBKGND message is intercepted.
Now, I use a TPaintBox instance in the following sample code. In its OnPaint handler, I have two choices to draw a drawing that I would expect to be flicker-free. Choice 1 is drawing after filling the rect. Because its parent panel should not erase the background, the drawing should be flicker-free. Choice 2 is drawing onto a TBitmap, whose Canvas is then copied back to the paintbox.
However, both choices are flickering, and the 2nd choice is especially flickering. My main concern is regarding choice 1. If you resize the form, you could see the main part of the flickering occurs on the right edge. Why does this happen? Could some one help to comment on the reason and possible solution? (Note, if I use TPaintBox32 instead of TPaintBox here, the right edge will not flicker at all.)
My secondary concern is that when using choice 1, the minor part of the flickering occurs on the paintbox randomly. It is not very obvious but still observable if you rapidly resize the form. Furthermore, when using choice 2, this kind of flickering becomes much more severe. I didn't find the reason of this. Could some one help to comment on the possible reason and solution?
Any suggestion is appreciated!!
    unit uMainForm;

    interface

    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      ExtCtrls, Dialogs;

    type
      TMainForm = class(TForm)
        procedure FormCreate(Sender: TObject);
      private
        { Private declarations }
        FPnlCtrl, FPnlScene: TPanel;
        FPbScene: TPaintBox;

        OldPnlWndProc: TWndMethod;

        procedure PnlWndProc(var Message: TMessage);
        procedure OnScenePaint(Sender: TObject);
      public
        { Public declarations }
      end;

    var
      MainForm: TMainForm;

    implementation

    {$R *.dfm}

    procedure TMainForm.FormCreate(Sender: TObject);
    begin
      Self.Color := clYellow;
      Self.DoubleBuffered := False;

      FPnlCtrl := TPanel.Create(Self);
      FPnlCtrl.Parent := Self;
      FPnlCtrl.Align := alTop;
      FPnlCtrl.Color := clPurple;
      FPnlCtrl.ParentColor := False;
      FPnlCtrl.ParentBackground := False;
      FPnlCtrl.FullRepaint := False;
      FPnlCtrl.DoubleBuffered := False;

      FPnlScene := TPanel.Create(Self);
      FPnlScene.Parent := Self;
      FPnlScene.Align := alClient;
      FPnlScene.Color := clBlue;
      FPnlScene.ParentColor := False;
      FPnlScene.ParentBackground := False;
      FPnlScene.FullRepaint := False;
      FPnlScene.DoubleBuffered := False;

      FPbScene := TPaintBox.Create(Self);
      FPbScene.Parent := FPnlScene;
      FPbScene.Align := alClient;
      FPbScene.Color := clRed;
      FPbScene.ParentColor := False;

      //
      OldPnlWndProc := Self.FPnlScene.WindowProc;
      Self.FPnlScene.WindowProc := Self.PnlWndProc;

      FPbScene.OnPaint := Self.OnScenePaint;

    end;

    procedure TMainForm.PnlWndProc(var Message: TMessage);
    begin
      if (Message.Msg = WM_ERASEBKGND) then
        Message.Result := 1
      else
        OldPnlWndProc(Message);
    end;

    procedure TMainForm.OnScenePaint(Sender: TObject);
    var
      tmpSceneBMP: TBitmap;
    begin
      // Choice 1
       FPbScene.Canvas.FillRect(FPbScene.ClientRect);
       FPbScene.Canvas.Ellipse(50, 50, 150, 150);

      // Choice 2
    //  tmpSceneBMP := TBitmap.Create;
    //  tmpSceneBMP.Width := FPbScene.ClientWidth;
    //  tmpSceneBMP.Height := FPbScene.ClientHeight;
    //  tmpSceneBMP.Canvas.Brush.Color := FPbScene.Color;
    //  tmpSceneBMP.Canvas.FillRect(FPbScene.ClientRect);
    //  tmpSceneBMP.Canvas.Ellipse(50, 50, 150, 150);
    //  FPbScene.Canvas.CopyRect(FPbScene.ClientRect, tmpSceneBMP.Canvas,
    //    FPbScene.ClientRect);

    end;

    end.

===Q: How to intercept the panel's repainting its background correctly? ===
(If I should ask this in a separate question, just say so and I will delete this.)
New a VCL application, pasting the sample code in, attach the FormCreate, run debug. Now hover the mouse over the form, you could see the panel is clearly repainting its background. However, as shown in the sample code, I should already intercepted this behaviour by intercepting the WM_ERASEBKGND message.
Note, if I comment out this three lines,
FPnlScene.Color := clBlue;
FPnlScene.ParentColor := False;
FPnlScene.ParentBackground := False;

then the WM_ERASEBKGND message can be captured. I have no clue about this difference.
Could some one help to comment on the reason of this behavior, and how to intercept WM_ERASEBKGND message correctly (when ParentBackground := False)?
    unit Unit1;

    interface

    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      ExtCtrls, Dialogs;

    type
      TForm1 = class(TForm)
        procedure FormCreate(Sender: TObject);
      private
        { Private declarations }
        FPnlScene: TPanel;
        FPbScene: TPaintBox;

        FOldPnlWndProc: TWndMethod;

        procedure PnlWndProc(var Message: TMessage);

        procedure OnSceneMouseMove(Sender: TObject; Shift: TShiftState;
          X, Y: Integer);
        procedure OnScenePaint(Sender: TObject);
      public
        { Public declarations }
      end;

    var
      Form1: TForm1;

    implementation

    {$R *.dfm}

    procedure TForm1.FormCreate(Sender: TObject);
    begin
      Self.Color := clYellow;
      Self.DoubleBuffered := False;

      FPnlScene := TPanel.Create(Self);
      FPnlScene.Parent := Self;
      FPnlScene.Align := alClient;
      FPnlScene.Color := clBlue;
      FPnlScene.ParentColor := False;
      FPnlScene.ParentBackground := False;
      FPnlScene.FullRepaint := False;
      FPnlScene.DoubleBuffered := False;

      FPbScene := TPaintBox.Create(Self);
      FPbScene.Parent := FPnlScene;
      FPbScene.Align := alClient;
      FPbScene.Color := clRed;
      FPbScene.ParentColor := False;

      //
      FOldPnlWndProc := Self.FPnlScene.WindowProc;
      Self.FPnlScene.WindowProc := Self.PnlWndProc;

      Self.FPbScene.OnMouseMove := Self.OnSceneMouseMove;
      Self.FPbScene.OnPaint := Self.OnScenePaint;

    end;

    procedure TForm1.PnlWndProc(var Message: TMessage);
    begin
      if Message.Msg = WM_ERASEBKGND then
      begin
        OutputDebugStringW('WM_ERASEBKGND');
        Message.Result := 1;
      end
      else
        FOldPnlWndProc(Message);
    end;

    procedure TForm1.OnSceneMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    begin
      FPbScene.Repaint;
    end;

    procedure TForm1.OnScenePaint(Sender: TObject);
    begin
      FPbScene.Canvas.FillRect(FPbScene.ClientRect);
      FPbScene.Canvas.Ellipse(50, 50, 150, 150);
    end;

    end.

A: The usual technique is to play with form.DoubleBuffered, which I see you are already doing in code, so if it was that easy, I would think you would have solved it already.
I think one could also perhaps avoid any operation in the OnPaint other than a stretch-draw directly onto your paintbox.Canvas, from your offscreen bitmap. Anything else in OnPaint is a potentially flicker-inducing mistake.  That means, no modification of the TBitmap from within the OnPaint.  Let me say that a third time; Don't change state in paint events. Paint events should contain a "bitmap-blit" operation, GDI rectangle and line calls, etc, but nothing else.
I hesitate to recommend to anyone that they experiment with WM_SETREDRAW, but it is one technique people use. You can catch the move/resize window events or messages, and turn WM_SETREDRAW on/off, but this is SO fraught with complications and problems, that I don't recommend it. You can also call various Win32 functions to lock a window, and these are all highly dangerous and not recommended.

A: For what it's worth, the following is flicker-free for me:
unit uMainForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, ExtCtrls, Dialogs;

type
  TMainForm = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    FPnlCtrl, FPnlScene: TPanel;
    FPbScene: TPaintBox;
    procedure OnScenePaint(Sender: TObject);
  end;

implementation

{$R *.dfm}

procedure TMainForm.FormCreate(Sender: TObject);
begin
  Self.Color := clYellow;

  FPnlCtrl := TPanel.Create(Self);
  FPnlCtrl.Parent := Self;
  FPnlCtrl.Align := alTop;
  FPnlCtrl.Color := clPurple;

  FPnlScene := TPanel.Create(Self);
  FPnlScene.Parent := Self;
  FPnlScene.Align := alClient;
  FPnlScene.Color := clBlue;

  FPbScene := TPaintBox.Create(Self);
  FPbScene.Parent := FPnlScene;
  FPbScene.Align := alClient;
  FPbScene.Color := clRed;

  FPbScene.OnPaint := Self.OnScenePaint;
end;

procedure TMainForm.OnScenePaint(Sender: TObject);
begin
  FPbScene.Canvas.FillRect(FPbScene.ClientRect);
  FPbScene.Canvas.Ellipse(50, 50, 150, 150);
end;

end.


text:
Q: Google static maps with encoded paths don't show when posting HTML page to OneNote REST API I am POSTing an HTML page to the OneNote REST API, to:
https://www.onenote.com/api/v1.0/pages

I am doing this from Google App engine (Java), and it all works fine, except that I am having problems with the static Google maps that are linked within the HTML.
Specifically a static map WITHOUT an encoded path is working and showing up fine, e.g.:
http://maps.googleapis.com/maps/api/staticmap?key=<KEY>&sensor=false&
center=<LAT,LON>&scale=1&zoom=17&markers=<LAT,LON>&size=150x150

However, when I post including an encoded polyline, the images doesn't show up on the OneNote page that is created (it looks a broken link on the page), e.g.:
http://maps.googleapis.com/maps/api/staticmap?sensor=false&size=150x150&
scale=1&path=enc:<PATH>&markers=<BLAH>&key=<KEY>

My first thought was that it wouldn't work because the google maps key can only be used from my own domain (although that wouldn't explain why the maps without encoded polylines worked already), so I added
https://www.onenote.com/*

to list of referrers. (I don't know that's the right referrer - just a guess based on the API URL). That didn't solve the problem.
Then I thought maybe it's because MS doesn't allow google maps on OneNote (or Google doesn't allow Google maps on OneNote). So I tried serving the google maps via my own website. That didn't work either. But what I could see from my server logs is that OneNote didn't even called the URL on my website of the maps with encoded polylines - which is weird!
The final idea I had is that maybe it's because the URL with encoded polyline is too long for the OneNote API to handle. So one thing I could try is to create short URLs to put in the HTML. Before I try that final step, thought I would ask for advice in case I am still headed the wrong way...
Thanks.
Edit: Here's an example of a URL that didn't work (excluding the key only):
http://maps.googleapis.com/maps/api/staticmap?sensor=false&size=150x150&scale=1&
path=enc:obblHzpwnVY?QEmBqA@qEzDT|JeAtD{Qn@yQhD_CMeIZ}BeCO@A@A?H
&markers=label:S|49.331765,-123.169574|&markers=label:F|49.328255,-123.158863&
key=<KEY>

Note that the key is approx 40 characters long

A: This appears to have been a length of URL problem. I tried serving the maps from my own website with a very short URL...
http://MY_DOMAIN/mapwrapper/SHORT_KEY

....and they worked fine.


text:
Q: Checkbox select filter jQuery not working in wordpress but works in codepen I am using DataTables in WordPress. I have created a checkbox and dropdown select filter. You can see it below. It works well in a Codepen and exported HTML from the Codepen, but when I apply this to the WordPress page, only the dropdown function is working. I have changed $ to jQuery and added noConflict() in the JS code, but it did not work.
Can anyone please help me to solve this.

$(document).ready(function() {
  dataTable = $("#example").DataTable({
    "columnDefs": [{
      "targets": [3],
      "visible": false
    }]
  });

  /*
    $('.filter-checkbox').on('change', function(e){
        var searchTerms = []
        $.each($('.filter-checkbox'), function(i,elem){
          if($(elem).prop('checked')){
            searchTerms.push("^" + $(this).val() + "$")
          }
        })
        dataTable.column(2).search(searchTerms.join('|'), true, false, true).draw();
      });
    */

  $('input:checkbox').on('change', function() {
    //build a regex filter string with an or(|) condition
    var positions = $('input:checkbox[name="pos"]:checked').map(function() {
      return '^' + this.value + '$';
    }).get().join('|');

    //filter in column 1, with an regex, no smart filtering, not case sensitive
    dataTable.column(2).search(positions, true, false, false).draw(false);
  });

  $('.status-dropdown').on('change', function(e) {
    var status = $(this).val();
    $('.status-dropdown').val(status)
    console.log(status)
    //dataTable.column(6).search('\\s' + status + '\\s', true, false, true).draw();
    dataTable.column(3).search(status).draw();
  })
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

          <input type="checkbox" name="pos" value="Wholesalers">Wholesalers
          <input type="checkbox" name="pos" value="GDS">GDS

          <select class="form-control status-dropdown">
            <option value="">Region</option>
            <option value="Global">Global</option>
            <option value="Australia">Australia</option>
            <option value="United Kingdom">United Kingdom</option>
          </select>

        Name
        Region
        Industry
        Hidden

        HaoQiao
<p>About HaoQiao</p>
<span class="desc"></span>
        China
        Wholesalers
        China

        STGlobe
<p>About STGlobe</p>
<span class="desc"></span>
        Global
        Wholesalers
        Global

        Broadway Travel
<p>About Broadway Travel</p>
<span class="desc"></span>
        United Kingdom
        Wholesalers
        United Kingdom

        Abreu Online
<p>About Abreu Online</p>
<span class="desc"></span>
        Global
        Wholesalers
        Global

        Across Australia
        Australia
        Wholesalers
        Australia

        Galileo
        Global
        GDS
        Global

        WorldSpan
        Global
        GDS
        Global

        Apollo
        Global
        GDS
        Global


text:
Q: How to format decimal in c# asp-format tag to 2 decimal points and without trailing zeros if it is an int? How to format decimal in c# asp-format tag to 2 decimal points and without trailing zeros if it is an int?
<input asp-for="X" asp-format="{0:0.00}" />

I need:
123.456 => 123.46
123.45  => 123.45
123.4   => 123.40
123     => 123

thanks

A: Try this
asp-format="{0:0.##}"

A: Your asp-format is correct. Change the format syntax:
asp-format="{0:n2}"


text:
Q: Play Game Services (Real time games) with Parse.com security How can I provide security for the game from hackers? I'm making the game with Google Game Services (sign in and real time multiplayer 1vs1) and with Parse.com for data storage.
developers.google.com notify:

Warning: Data that is sent using Game services is unencrypted. Since messages can originate from any peer client connected to the room, you should treat this data as untrusted. We recommend that you implement your own security checking to verify that inbound data does not compromise your app.

And how can I safely  write player level progress to parse.com, for example?
I cannot write something like:
if (expirianceUp) {
  WriteToServer(newExpirianceVal);
}

I think it is no safely.

A: You can hash the value with a key like hmac-md5. Using same key on parse.com, decrypt hashed value and parse to int or whatever your data type. Use cloud code to dcrypt.


text:
Q: WindowLess WinForm or Console app to launch .bat files? I want to launch a .bat file through a scheduler. The .bat file calls a third party command line tool. What's the difference between doing this through a console app vs a windowless winform application? I am using .NET. I prefer the app not show a DOS window.

A: This sounds like a job for a windows scheduled task.  I assume that you're using the ProcessStart classes to launch the program from .NET?  If so then I think the only difference would be the overhead involved in the WinForm assemblies being loaded vs not loading in the console app.


text:
Q: Error with implicitly typed variables When assigning a linq selection to an implicitly typed local variable "var" i receive the
following error.
Error :Cannot assign method group to an implicitly-typed local variable
at
root : var mailgroup = emails.Where(p =>IsValidFormat(p.Value)).Select;

Dictionary of elements
        Dictionary<int, string> emails = new Dictionary<int, string>();
        emails.Add(1, "Marry@yahoo.com");
        emails.Add(2, "Helan@gmail.com");
        emails.Add(3, "Rose");
        emails.Add(4, "Ana");
        emails.Add(5, "Dhia@yahoo.com");
        Dictionary<int, string> dc = new Dictionary<int, string>();

How to correct it ?

A: You're missing () after Select. As a result, what's being assigned to the variable is a reference to the Select method, which the compiler refers to as a 'method group'.
Incidentally, based on the code that you've posted I don't think that you need the trailing .Select() at all.

A: What are you expecting it to do? You probably want to make an actual method call there, such as:
var mailgroup = emails.Where(p =>IsValidFormat(p.Value))
                      .Select(p => p.Value);

Or if you just want the key/value pairs, you can just use:
var mailgroup = emails.Where(p =>IsValidFormat(p.Value));

and remove the "Select" entirely.
If you do just want the values (as per the first code snippet) I'd suggest using:
var mailgroup = emails.Values.Where(p =>IsValidFormat(p));

Without any brackets, your reference to "Select" is a method group - the kind of thing you'd convert to a delegate, e.g.
Func<int> x = SomeMethod; // Where SomeMethod is declared as "int SomeMethod()"

It doesn't really make sense to use Select as method group in this case, although it is just about feasible...


text:
Q: Secret from Gogs hook (failing to get on python3) I'm configuring a gogs hook, I have an API that receives this POST from push
e.g.
secret: myS3cr3t
it's supposed that " Secret will be sent as SHA256 HMAC hex digest of payload via  X-Gogs-Signature  header."
then in python3 I got it like this:
message is the payload (json body) from the request and the key i set it on env var
import hashlib
import hmac

def get_secret_signature(message, secret):
   signature = hmac.new(bytes(key, 'utf-8'), bytes(message, 'utf-8'), hashlib.sha256).hexdigest()
   return signature

but when checking the hook is failing cause the signature sent in X-Gogs-Signature never match with the signature generated on python
even comparing the logic with jenkins gogs plugin:
public static String encode(String data, String key) throws Exception {
        final Charset asciiCs = Charset.forName("UTF-8");
        final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(asciiCs.encode(key).array(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}

I think it's the same logic in python, obviously shorter in python ;)

A: It seems that the variable that had the payload was not escaping some characters, since I'm using the python framework Bottle this is the right way to get the payload:
payload = request._get_body_string()
gogs_signature = request.get_header('X-Gogs-Signature')

signature = get_secret_signature(payload, secret)
.
.
.
if gogs_signature != signature:
   print("Signature error")

def get_secret_signature(message, secret):
   signature = hmac.new(bytes(key, 'utf-8'), message, hashlib.sha256).hexdigest()
   return signature


text:
Q: How can I beautify all files using Python script or some other ways? I have a lot of unindented C/C++ source files.I want to beautify all of them programmatically. How can I achieve that?

A: Write a python script that calls a C++ beautifier like Artistic Style.
http://astyle.sourceforge.net/
Here's how your python script would look:
# Collect all the files you need to beautify in "files"

#Loop through each C/C++ file
for file in files:
    command = "astyle " + file
    import subprocess
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()

Example usage of Artistic Style is:
astyle example.cpp

or
astyle --style=ansi --indent=tab example.cpp


text:
Q: Authentication api twitter by documentation (https://dev.twitter.com/docs/auth/application-only-auth) I need to implement an Ajax call to make an app only authentication. I've tried but twitter server respond me ever error 403 forbidden. Can anyone suggest me an Ajax implementation to do this?

A: Make manually an Ajax call to request an authentication for Twitter is a bit complicate because Twitter needs some parameters in the request header. Plus this parameters needs to be encoded.
To resolve this problem I've found a good library: codebird.js.
Below code to make an authentication and use all twitter api.:
var cb = new Codebird;
cb.setConsumerKey("Yourkey","Yoursecret");
cb.setToken("Access token", "Access token secret");

Yourkey,Yoursecret,Access token,Access token secret are your personal number you can get by your twitter app management.


text:
Q: Не могу Datagrid связать с ObservableCollection<> Есть Datagrid по имени list
<DataGrid Width="300" Height="300" VerticalScrollBarVisibility="Visible" x:Name="list">   </DataGrid>
В коде wpf я создал ObservableCollection<>
ObservableCollection<Ourdata> carlist = new ObservableCollection<Ourdata>();

Класс Ourdata выглядит следующим образом.
    public class Ourdata
{
    public string A {get;set; }
    public string B { get; set; }
    public string C { get; set; }
}

При выполнении list.ItemsSource = carlist; выбивается ошибка.

"Exception has been thrown by the target of an invocation"

Коллекция carlist не пустая объекты добавляются и сохраняется там без проблем.В чём может быть ошибка?
В Inner exception следующая ошибка "object reference not set to an instance of an object"

A: В конструкторе MainWindow я не прописал InitializeComponent();.


text:
Q: Update requests send no longer all fields to the SAP S/4HANA system Since the update to the Cloud SDK version 2.0.0 we now have problems to add fields to the request. It is mainly about the process step "Count Physical Inventory Document Item". Here the manually set properties for the items are not sent into the request.
These are the properties we actually set and send to S/4 System:

These are the properties that are embedded in the query:

A: Quick answer
Call the method includingFields(PhysInventoryDocItem.MATERIAL, ...) on the update fluent helper.
Longer explanation
Version 1.11.1 of the SAP S/4HANA Cloud SDK slightly changed the behavior of the Java Virtual Data Model (VDM) during update requests. The release notes state:

Update requests with the Java Virtual Data Model (VDM) no longer send all non-null fields to the SAP S/4HANA system, but only changed fields. You may need to adapt the logic in your code to explicitly change fields by using the setters of the entity classes, or use the includingFields method to manually specify fields to include.

So in your case, by default only fields will be sent that have a different value compared to the result returned by the get-by-key OData request, as typically expected for PATCH requests. For example, the value of the field material likely didn't change, because it was "MAT_KONSI_APP1" before.
Because there are cases that require some mandatory fields to be always sent, the SAP S/4HANA Cloud SDK allows you to control which fields to always send. Use the includingFields method on the update fluent helper of the VDM to specify the fields that shall be sent in any case, also if their value has not changed.
In your case, if you want to send the material and unit of entry fields, which may be mandatory properties, you need the following code:
service.updatePhysInventoryDocItem(itemToUpdate)
    .includingFields(PhysInventoryDocItem.MATERIAL,
                     PhysInventoryDocItem.UNIT_OF_ENTRY)
    .execute()


text:
Q: How to check if an email address in valid in PHP? I need a php program to check mail id
$txt="swatimishra298@gmail.com";

and I need to find whether its a valid mail id or not. @ should not be repeated and only A-za-z _ . @ are allowed
My program:
 <?php

 echo "Hello world!<br>";
 $txt="swatimishra298gmail.com";
 $i = strlen("swatimishra298gmail.com");

 for ($j = 0; $j <= $i; $j++) {

 $name=substr( $txt ,0, $j);

 do
 {
   $j++;
 }while( $j == '@' );
   echo "Its a mail id!";
 }
 ?>

A: Use filter_var. Try with -
filter_var($txt, FILTER_VALIDATE_EMAIL);

It will return false if fails.


text:
Q: How to load 32/64 bit library changing the compiler kit in Qt Creator? How can I load different compiler kit depending on the 32/64 bit compiler chosen when changing the kit.
I tried like this. But this always loads x64 library. I have MSVC2017-x64 and MSVC2015-x32 bit compilers.
win32:contains(QMAKE_HOST.arch, x86_64) {
  LIBS += -L"$$PWD/lib/x64" -lftd2xx

} else {
  LIBS += -L"$$PWD/lib/x86" -lftd2xx
}

A: Here is what I am doing in my project. If I use MSVC 2017 64 bits it links to myLib_64. Otherwise it links to myLib_32. You can adapt it for your situation.
MAKE_SPEC = $$split(QMAKESPEC, /)
contains(MAKE_SPEC, msvc2017_64):{
    LIB_SUFFIX = _64
} else {
    LIB_SUFFIX = _32
}

LIBS += -lMyLib$$LIB_SUFFIX


text:
Q: Random maps/graphs and OSM just wondering if you have any suggestions here. I need a lot of sample maps/graphs to test my shortest path search solution (I was told I should have >100 of them). My code is supposed to work in a simulator, which uses OpenStreetMap maps of urban setting, limiting the total number of junctions to a few thousand. the problem is, there are only two or three maps provided with the simulator. The way I see it, I have a few choices here:

*

*Write my own random graph generator. Possibly lots of work (do you think? --I've never done it before) and reinventing the wheel.

*Use off-the-shelf solution. I'm not aware of any that would generate me map-like graphs (well, at least I didn't find it in JUNG :-) )

*In some automated way grab them from OSM. I don't really intend to myself go and pick out a 100+ urban maps that would satisfy <15000 nodes requirement. I don't think that would be easy to automate either, though.

I would assume that 3 would be tough to do. Any advice on some off-the-shelf solution? or comments about writing my own? I'm not an experienced programmer by any measure, but given a few days.

A: The first thought:
You have a known problem and you need to test its solution. Generate lots of test data, find correct solutions with verified algorithm, then run your algorithm against generated data set and compare results. (or just download verified dijkstra algorithm implementation, I believe that implementing this algorithm is your task)
The second thought:
Random-generated data set is not the best way to test algorithms. You need to think about cases when your algorithm can fail and create correspondent tests. For example, graph with 1 node, graph with cycles, linear graph i.e. N1---N2---N3-...-Nn, complete graph with maximum nodes number. I think if you create these 4 tests and 2-3 small random tests it'll be enough to be sure that your algorithm is implemented correctly.


text:
Q: Вывод данных на TForm Сама я техник и в программировании ни черта не разбираюсь, а сделать надо. По этому если у кого будет возможность помогите, пожалуйста!
У меня ни как не получается реализовать интерфейс для ввода элемента двухмерного массива и организовать нахождение суммы введенных элементов и вывод НА TForm! Вот что у меня поучилось с кодом, но я не могу разобраться с выводом на форму… Да какое там, я на столько чайник в программировании, что не уверена что код правильно написан и проверить не знаю как… Тупо по учебнику подбирала, да еще чел один рядом сидел подсказывал, а еще и крин-шот нужен:
#include <iostream>
int main()
{
int m, n;
std::cout << «Введите размер матрицы: »;
std::cin >> m >> n;
int mat[m][n], sum = 0;
std::cout << «Введите элементы матрицы: » << std::endl;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
std::cin >> mat[j];
}
}
for(int i = 0; i < m; i++)
{
for(int j = 0 ; j < n; j++)
{
sum += mat[j];
}
}
std::cout << «Сумма всех элементов равна » << sum << std::endl;
return 0;
}

Тут даже не главное сам код, главное создание  TForm, а для этого надо хотя бы ИМЕТЬ среду разработки, коей у меня нема, и скачать ни как.(ну и знание КАК это все делатся).
Пробовала сама что то накрутить, но не получается как бы мне обьясняли!!!


text:
Q: convergence of series of subsequence, when original sequence converges There is a sequence {a1, a2, a3, ...}.
Suppose that a series of this sequence converges to a constant C.
My question is,
For any subsequence {b1, b2, b3, ... } of {a1, a2, a3, ... },
Does the series of {bn} converges?

A: Consider the serie $\sum_{n\geq 0} (-1)^n/n$, it converges since it is an alternating serie, but $\sum (-1)^{2n}/(2n)=\sum_{n\geq 0}{1\over{2n}}$ does not converge.

A: Yes if the convergence is absolute: if $\sum_{n=1}^{\infty}|a_n|<\infty$ then also $\sum_{n=1}^{\infty}|b_n|<\infty$.
No if the convergence is not absolute: see the counterexample given in the answer of Tsemo Aristide.


text:
Q: Autodesk InventorApprentice API print .iam or .ipt to PDF Using examples for the Autodesk Inventor Aprentice API I can print a 2d .IDW file to PDF
But I cannot get a model (.IAM/.IPT) to do so
InventorView can print to the MS Print to PDF from the app, so it is possible
Any ideas or guidance appreciated
    public void PrintModelToPdf(string iam, string outputFolder)
    {
        string logFileName = Path.Combine(outputFolder, "PrintPDFlog.txt");
        string modelName = Path.GetFileNameWithoutExtension(iam);
        string pdfFileName = Path.Combine(outputFolder, $"{modelName}.pdf");

        try
        {
            InventorApprentice.ApprenticeServerComponent apprentice = new ApprenticeServerComponent();
            apprentice.Open(iam);

            InventorApprentice.ApprenticeServerDocument model;
            model = apprentice.Document;

            model.PrintManager.Printer = "Microsoft Print to PDF";
            model.PrintManager.Orientation = PrintOrientationEnum.kDefaultOrientation;
            model.PrintManager.PaperSize = PaperSizeEnum.kPaperSizeESheet;
            model.PrintManager.NumberOfCopies = 1;
            model.PrintManager.ColorMode = PrintColorModeEnum.kPrintDefaultColorMode;

            //Throws with "Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))"
            model.PrintManager.PrintToFile(pdfFileName);

        }
        catch (Exception ex)
        {
            System.IO.File.AppendAllText(logFileName, $"{ex.Message}\n{ex.StackTrace}");
        }
    }


text:
Q: Writing and running tests. ImportError: No module named generic I'm new to tests in Django. And I need to write a couple.
Django version 1.9.7.
OS: Linux version 4.2.0-42-generic (buildd@lgw01-54) (gcc version 5.2.1 20151010 (Ubuntu 5.2.1-22ubuntu2) ) #49-Ubuntu SMP Tue Jun 28 21:26:26 UTC 2016
My simple test code is:
cat animal/tests.py

from django.test import TestCase
from animal.models import Animal

class AnimalTestCase(TestCase):
    def say_hello(self):
        print('Hello, World!')

I execute it in this way ./manage.py test animal
And the following error arise:
Traceback (most recent call last):
  File "./manage.py", line 13, in <module>
    execute_from_command_line(sys.argv)
  File "/path-to-venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/path-to-venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute
    django.setup()
  File "/path-to-venv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/path-to-venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/path-to-venv/local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create
    module = import_module(entry)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/path-to-venv/local/lib/python2.7/site-packages/autofixture/__init__.py", line 5, in <module>
    from autofixture.base import AutoFixture
  File "/path-to-venv/local/lib/python2.7/site-packages/autofixture/base.py", line 7, in <module>
    from django.contrib.contenttypes.generic import GenericRelation
ImportError: No module named generic

What am I doing wrong?

A: You have the wrong import, the correct import is from
django.contrib.contenttypes.fields import GenericRelation

But that seems to actually come from django auto-fixtures rather than from your own code. The good news is that you don't need auto-fixtures for this sort of simple tests. Just say good bye to it.

A: Your installed version of django-autofixture does not support Django 1.9, because it has out of date imports for GenericRelation.
Try upgrading to the latest version. The project's changelist says that Django 1.9 support was added in version 0.11.0.
In order for Django to run your method in your AnimalTestCase, you need to rename it so that it begins with test_:
class AnimalTestCase(TestCase):
    def test_say_hello(self):
        print('Hello, World!')


text:
Q: Are my half siblings related to my half brother? My parents Bianca and Ivan are currently married and have always been since before I was born. Both of my parents have had previous relationships in the past. Bianca had a previous relationship with Henry and have a son named John, making John my half brother. Ivan had a previous relationship with Alicia, and have two sons named Frank and Ernest, making Frank and Ernst my half brothers. After that, Ivan met Katy and have a daughter named Pamela, making Pamela my half sister. So basically, I have one brother from my mom's side and two brothers and one sister from my dad's side. John knows who my other half siblings are but he doesn't know them at all and he barely sees them. Is he related to them?Is there a term for this relationship?  I suspect he really isn't but I'm just curious.

A: According to today's standards, they're not truly related.
However, they are members of the same clan.
Also, less than 500 years ago, if John and Pamela had a relationship, it would have been considered incestuous: a sibling was a true sibling once he or she had been recognized as such. This had to do with the Christian view of the family as a concept, I think (which is why, for instance, Shakespeare's Hamlet views his mother's marriage to his uncle as incestuous).

A: The answer to your question depends on your understanding of the word related.
Oxford defintes related as:

related -
  adjective - Belonging to the same family, group, or type; connected.

In that sense you are absolutely related, but in another sense you might not be.  Some people use the term related to refer to primary familial connections (father, mother, sister, brother, cousin.)  In the eyes of such a person, you wouldn't be related unless you shared familial DNA.
In my opinion that definition is too narrow.  Ultimately, all humans are related, and we are genetically related to other mammals.  The important thing is, are you family?