text:
Q: A unique 'code' to represent a 2d array I've made a game that randomly generates mazes, the maze is stored in a 2d array.
each integer in the array represents the number of walls that cell has.
It's based on the java example here: http://rosettacode.org/wiki/Maze
To allow people to share a unique maze i'm trying to find a way to convert the array into a string or an integer that can be generated by one user, copied and then pasted into another game which will then load the same maze.
The user can select the size of the maze up to 25x25 so simply printing each value (2|16|4|20...) would be incredibly long.
If converting it to a 'code' isn't possible are there any other ways it can be done without using a file?

A: Store the seed for the random number generator. The seed fully determines the output of the random number generator.
Assuming you are using java.util.Random to generate the random numbers, instead of using the default constructor new Random() use
long seed = System.currentTimeMillis();
// store the seed somewhere
// so you can generate the same sequence of random numbers again
Random rng = new Random(seed);

To make a short "code" that can be given to users for sharing, you can convert the number to hex or base 36:
String code = Long.toString(seed, 36); // codes like heeho82h

A: If you're randomly creating the values for that array, you only need the state of the PRNG that produced those values to re-generate them. That's at the same time the biggest weakness and strength of all pseudo-random number generators.
As most PRNGs don't allow retrieving and setting the state, or have a pretty huge state (a Mersenne Twister has a few kilobyte of state internally), you may want to use the seed instead. Of course, then you must create a new PRNG (or reset an existing one) for level generation.
To make the number human-readable, you should just render it in some number base. Base 10 makes it obvious it's a number and is easiest to generate and parse. Base 16 (hexadecimal) and base 64 yield shorter, more obscure "codes". Padding it to be fixed-length regardless of the actual value is probably a good idea.

A: You could use Serialization concept to save the state of 2-D array and then retrieve it back using deserialization. Here is the simple Demo to save a 2-D array state and then read it back . I hope it would be of your help:
import java.io.*;
class ArraySerialization
{
    ByteArrayOutputStream baos;
    ByteArrayInputStream bins;
    public void saveState(Object obj)throws Exception
    {
        baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        oos.close();
    }
    public int[][] readState()throws Exception
    {
        bins = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream oins = new ObjectInputStream(bins);
        Object obj = oins.readObject();
        oins.close();
        return (int[][])obj;
    }
    public static void main(String[] args) throws Exception
    {
        int arr[][]= {
                        {1,2,3},
                        {4,5,7}
                    };
        ArraySerialization ars = new ArraySerialization();
        System.out.println("Saving state...");
        ars.saveState(arr);
        System.out.println("State saved..");
        System.out.println("Retrieving state..");
        int j[][] = ars.readState();
        System.out.println("State retrieved..And the retrieved array is:");
        for (int i =0 ; i < j.length ; i++ )
        {
            for (int k = 0 ; k < j[i].length ; k++)
            {
                System.out.print(j[i][k]+"\t");
            }
            System.out.print("\n");
        }

    }
}

A: Although it uses a random generator, it is in fact a deterministic process. You can repeat it by knowing the random seed. Just share the random seed, as mentioned by Joni. Anyway, if you want to share the data: a NxN mesh has NxN inner walls, and considering it takes 1 bit to store presence/absence of a wall, you will need NxN bits to store the maze. In this way you can store a 90x90 maze in 1kb.


text:
Q: Cloud Firestore with Authentication I have been looking for a way to use Authentication with Firebase's new Cloud Firestore. I know it's possible, but there is no good guide both in the Documentation and other places.
Could someone please explain how to provide an Authentication UID when get()ing data from Cloud Firestore?
Here are my security rules:
service cloud.firestore {
  match /users/{userID} {
    allow read, write: if request.auth.uid == userID;
  }
}

And here is my current code:

var db = firebase.firestore();
var docRef = db.collection("users").doc(uid); //lets say "uid" var is already defined
docRef.get().then(function(doc) {
  if (doc.exists) {
      console.log("Document data:", doc.data());
  } else {
      console.log("No such document!");
  }
}).catch(function(error) {
  console.log("Error getting document:", error);
});

The structure of my database is just a "users" collection at root, then a document for each user (named after the UID). I want to get the document with the user's UID.
Of course, this gives the error "Missing or insufficient permissions," which is expected, because of the security rules.
This question may seem simple, but if anyone can find some good documentation on this, that would be great!

A: Your rule should be inside match /databases/{database}/documents
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userID} {
        allow read, write: if request.auth.uid == userID;
   }
  }
}

A: I was just confused about how UIDs work. I was under the impression that you have to supply a UID and an auth token to database operation.
You don't actually pass in a UID to database operations. The firebase object stores authentication state. You can simply sign in (check the Firebase docs to read how to do this), and after the action is completed (use a .then promise statement) you can simply do your operation.
Additionally, to have users not sign in every time they visit your app, you can have the `firebase object's authentication state persistent.

redpajama_set_name: RedPajamaStackExchange


text:
Q: .NET : Get property name in attribute [MyAttribute()]
public string Name { get; set; }

In MyAttribute I need to know the name of associated property, is it possible?
EDIT:
I need to use it in text formatting.

A: No, this is not possible. Usually you would use reflection to read attributes applied on a given property, so you already know the property. Example:
var properties = typeof(SomeType).GetProperties();
foreach (var property in properties)
{
    var attributes = property.GetCustomAttributes(typeof(MyAttribute), true);
    if (attributes.Count > 0)
    {
        // look at property.Name here
    }
}

A: You can use a PostSharp aspect to do the job. I had a similar question a while back, which was almost the same thing. You can see comments on the answer for more info about some of the implications that you might encounter.


text:
Q: Do i keep foreign passports after i confiscate them? I want to escape with my family to Obristan, but I need Obristan passports for forgeries. I've read other answers, and they say the same, confiscate Obristan passports. Should I confiscate only two passports? I have the passport jorji gave, I adopted my niece and my wife is still alive.

A: If you have two family members left, you will need to steal two more passports. You also need one for yourself, which Jorji will give you.


text:
Q: Graphics Memory info with CMD Starting from the beginning, I've created an installer (game installer) with command prompt.. I want to set a variable for the available graphics memory on the PC which it is currently running ... Something like this ---
set gfxmem=[code here]
if %gfxmem% leq 1000[mb or value] ( echo Low Graphics memory ) else echo Supported

What might be in place of code here?

A: I searched the world wide web, found quickly How To Identify Your Computer Video Card (The Manual Way) and downloaded the batch file containing the lines:
@echo off
wmic PATH Win32_videocontroller GET description
wmic PATH Win32_videocontroller GET adapterram
wmic PATH Win32_videocontroller GET driverversion
wmic PATH Win32_videocontroller GET pnpdeviceid
pause

I executed the batch file to see what the line with adapterram outputs and could see a line with AdapterRAM and two lines with a byte value because there are two video adapters installed in my computer.
Next I developed following batch code with using coding techniques described in detail in answer on How to get the % of memory utilization using WMIC in batch script? and in the comments of the batch code itself.
@echo off
goto :GetVideoMemorySize

rem Note: MB = MiB and GB = GiB in this batch file, see
rem       https://en.wikipedia.org/wiki/Byte for details on GiB.

rem The command WMIC with the parameters PATH Win32_videocontroller GET
rem AdapterRAM outputs one line per video adapter. The output of WMIC is
rem in UTF-16 LE with BOM. The output is redirected to a temporary file
rem which is printed by command TYPE to STDOUT which makes a better job
rem on UNICODE to ASCII conversion as command FOR.

rem Memory of a video adapter is in bytes which can be greater 2^31 (= 2 GB).
rem Windows command processor performs arithmetic operations always with
rem 32-bit signed integer. Therefore 2 GB or more installed video memory
rem exceeds the bit width of a 32-bit signed integer and arithmetic
rem calculations are wrong on 2 GB or more installed video memory. To
rem avoid the integer overflow, a subroutine is called which makes the
rem calculation depending on string value length, i.e. number of bits.

rem Create a copy of current environment variables. Enabling additionally
rem delayed environment variable expansion is not required for this task.
rem Command extensions are enabled by default, but nevertheless enable it.

:GetVideoMemorySize
setlocal EnableExtensions
set "VideoTotalMemory=0"
set "VideoAdapterCount=0"

%SystemRoot%\System32\wbem\wmic.exe PATH Win32_videocontroller GET AdapterRAM >"%TEMP%\AdapterRam.tmp"

for /F "skip=1" %%M in ('type "%TEMP%\AdapterRam.tmp"') do (
    set /A VideoAdapterCount+=1
    set "VideoAdapterMemory=%%M"
    call :AddVideoMemory
)
del "%TEMP%\AdapterRam.tmp"

if "%VideoAdapterCount%" == "1" (
    set "AdapterInfo="
) else (
    set "AdapterInfo= of %VideoAdapterCount% video adapters"
)

echo Total video memory is: %VideoTotalMemory% MB%AdapterInfo%
echo.
if %VideoTotalMemory% LEQ 1024 (
    echo Low Graphics memory
) else (
    echo Supported
)

endlocal
goto :EOF

rem This subroutine calculates the total video adapter memory correct
rem only for video adapter memory sizes being either less than 1 GB or
rem an exact multiple of 1 GB. The calculation is wrong for values like
rem 1.5 GB, 2.5 GB and similar values.

rem For a value with not more than 9 characters the memory size in MB
rem can be directly calculated with a division by 1024 * 1024 = 1048576.

rem To avoid an integer overflow on video memory sizes of 1 GB and more,
rem the last 6 characters are removed from bytes value and the remaining
rem characters are divided by 1073 to get the number of GB which is next
rem multiplied with 1024 to get the value in MB.

rem  1 GB =  1.073.741.824 bytes = 2^30
rem  2 GB =  2.147.483.648 bytes = 2^31
rem  4 GB =  4.294.967.296 bytes = 2^32
rem  8 GB =  8.589.934.592 bytes = 2^33
rem 16 GB = 17.179.869.184 bytes = 2^34
rem 32 GB = 34.359.738.368 bytes = 2^35

:AddVideoMemory
if not "%VideoAdapterMemory:~9,1%" == "" goto AtLeast1GB
set /A VideoTotalMemory+=VideoAdapterMemory/1048576
goto :EOF

:AtLeast1GB
set "VideoAdapterMemory=%VideoAdapterMemory:~0,-6%"
set /A VideoTotalMemory+=(VideoAdapterMemory/1073)*1024
goto :EOF

I tested the batch file on Windows XP SP3 x86 and Windows 7 SP1 x64 with administrator privileges and it worked fine on both computers.
See also User Account Control and WMI and Win32_VideoController class. Interesting to read for me was uint32 AdapterRAM on second web page. This would mean that more than 4 GB are not possible for video adapter RAM.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*call /?

*del /?

*echo /?

*endlocal /?

*for /?

*goto /?

*rem /?

*setlocal /?

*set /?

*type /?

*wmic /?

*wmic PATH /?

*wmic PATH Win32_videocontroller GET /?
And read also the Microsoft article Using command redirection operators for an explanation of redirection operator >.


text:
Q: Coordinates that cancel the 64 affine connection components at a point Consider an arbitrary connection $\Gamma$, compatible with the metric, in 4 dimensional spacetime:
$$\nabla_{\lambda} \, g_{\mu \nu} \equiv \partial_{\lambda} \, g_{\mu \nu} - \Gamma_{\lambda \mu}^{\kappa}\, g_{\kappa \nu} - \Gamma_{\lambda \nu}^{\kappa} \, g_{\mu \kappa} = 0. \tag{1}$$
I don't assume symetry of that connection (torsion may be present): $\Gamma_{\mu \nu}^{\kappa} \ne \Gamma_{\nu \mu}^{\kappa}$.
For a long time, I was believing that it was possible to find a special coordinates system such that we could cancel all the $4 \times 4 \times 4 = 64$ connection components, at any given point $\mathcal{P}$ in spacetime (but only for that point):
$$\tilde{\Gamma}_{\mu \nu}^{\lambda}(\tilde{x}_{\mathcal{P}}) = a_{\mu}^{\; \rho} \: a_{\nu}^{\; \sigma} \: a^{\lambda}_{\; \kappa} \: \Gamma_{\rho \sigma}^{\kappa}(x_{\mathcal{P}}) - a_{\mu}^{\; \rho} \: a_{\nu}^{\; \sigma} \: \partial_{\rho} \, a^{\lambda}_{\; \sigma} = 0, \tag{2}$$
where
\begin{align}
a^{\mu}_{\; \nu} &= \frac{\partial \tilde{x}^{\mu}}{\partial x^{\nu}} \, \bigg|_{\mathcal{P}},
&a^{\; \nu}_{\mu} &= \frac{\partial x^{\nu}}{\partial \tilde{x}^{\mu}} \, \bigg|_{\mathcal{P}}. \tag{3}
\end{align}
But then, recently I had to re-read my old personnal notes on this subject and I'm now confused (I must have forgotten something important here, which I didn't described in my notes).  Consider the following coordinates transformation (for simplicity, I assume cartesian-like coordinates $x^{\mu}$ such that the metric is Minkowskian at point $\mathcal{P}$ of coordinates $x_{\mathcal{P}}^{\mu}$ : $g_{\mu \nu}(x_{\mathcal{P}}) = \eta_{\mu \nu}$):
$$\tilde{x}^{\mu} = x_0^{\mu} + \Lambda^{\mu}_{\: \nu} \, x^{\nu} + \frac{1}{2} \, \Lambda^{\mu}_{\: \nu} \: \Gamma_{\rho \sigma}^{\nu}(x_{\mathcal{P}}) (x^{\rho} - x^{\rho}_{\mathcal{P}})(x^{\sigma} - x^{\sigma}_{\mathcal{P}}), \tag{4}$$
where $x_0^{\mu}$ and $\Lambda^{\mu}_{\: \nu}$ are arbitrary constants (translation and Lorentz transformations), such that $a^{\mu}_{\: \nu} = \Lambda^{\mu}_{\: \nu}$.  Then, (2) gives
$$\tilde{\Gamma}_{\mu \nu}^{\lambda} = \Lambda_{\mu}^{\; \rho} \, \Lambda_{\nu}^{\; \sigma} \, \Lambda^{\lambda}_{\; \kappa} \, (\, \Gamma_{\rho \sigma}^{\kappa} - \Gamma_{\sigma \rho}^{\kappa}) = 0. \tag{5}$$
This equation then implies that the connection need to be symetric (no torsion), which implies 40 components instead of 64.
So I have two questions:

*

*Is there another - more general - coordinates transformation (in place of (4) above) that could cancel all 64 components of the arbitrary connection (evaluated at a given point)?  Or is that impossible to cancel all of the 64 components (evaluated at a point) with any coordinates transformation (4 functions)?

*In the special case of the symetric connection (AKA Levi-Civita connection), how is it possible that transformation (4) of four coordinates is able to cancel at once all 40 components of the symetric Levi-Civita connection, evaluated at a given point?

A: Both questions are easily answered once we realize that $\partial_\mu a^\lambda_{\ \nu}=\partial_\mu \partial_\nu \tilde{x}^\lambda = \partial_\nu \partial_\mu \tilde{x}^\lambda = \partial_\nu a^\lambda_{\ \mu}$.

*

*The antisymmetric part of $\Gamma^{\lambda}_{\mu \nu}$, which we denote as $\Gamma^\lambda_{[\mu\nu]}$ (where $[\mu,\nu]\equiv \frac{1}{2}(\mu\nu-\nu\mu)$), transforms as a tensor. The part of the transformation of $\Gamma^{\lambda}_{\mu\nu}$ which does not transform as a tensor is symmetric under the exchange of $\mu$ and $\nu$, which can be shown using the property above. Therefore, it is not possible to find coordinates where $\Gamma^\lambda_{\mu\nu}=0$ in general. If it were possible, then $\Gamma^\lambda_{[\mu\nu]}$ would vanish, and then by properties of tensors, $\Gamma^\lambda_{[\mu\nu]}=0$ would be zero in every coordinate system. Indeed, the antisymmetric part of $\Gamma^\lambda_{\mu \nu}$ is a way to measure the torsion -- so coordinate invariance by itself is not enough to set $\Gamma^\lambda_{[\mu\nu]}=0$, you need an additional assumption that the torsion vanishes. This assumption is made in GR, but logically speaking this is an extra assumption you need to make.

*As we established above, $\partial_\mu a^\lambda_{\ \nu}$ is symmetric under exchanging $\mu$ and $\nu$. It therefore has 40 components (4 possibilities $\lambda$ times 10 possibilities for the symmetric pair ($\mu,\nu$). This gives enough freedom to cancel the freedom in the symmetric part of $\Gamma^{\lambda}_{\mu \nu}$.

A: If the connection has torsion, the answer is negative. Indeed, if you found a coordinate system around a point where all connection coefficients vanish at that point, then also their antisymmetric part would vanish, and this is not possible because the torsion is a tensor so that, if it vanishes in a coordinate system, then it has to vanish in every coordinate system.
Hence, let us  assume that the connection is symmetric without assuming that it is metric. What follows does not need a metric, just an affine symmetric connection on a manifold with generic dimension $n$.
Consider a point $p$. In that case you can define the local diffeomorphism known as the exponential map at $p$.
The map identifies an open neighborhood of the tangent space at $p$ with a neighborhood of $p$.
$$\exp_p{v} = \gamma(1,p, v)$$
Where $t \mapsto \gamma(t,p,v)$ is the geodesic with initial point $p$ and initial tangent vector $v$.
(Actually there are a few mathematical subtleties. First, one has to prove that it is always possible to include $1$ in every maximal parameter domain of all geodetics emanated from $p$ if $v$ stays in a suitable small neighborhood of the origin of $T_pM$. Secondly, one has to prove that the map written above is in fact a diffeomorphism, i.e., smooth, bijective with inverse smooth, by possibly shrinking the said neighborhood. All that can be fixed with a little effort.)
Fixing a basis in the tangent space at $p$, the components of $v$ are coordinates of the corresponding point on the manifold. Such a coordinate system is known as a normal coordinates system centered on $p$.
The geodesics emanated by $p$ are straight lines exiting the origin in that coordinate system,
$$v^a(s) = sv_0^a\tag{1}$$
This is an immediate consequence of the identity arising from the geodesic equation (and the uniqueness theorem for that differential equation)
$$\gamma(s,p,v_0) = \gamma(1,p, sv_0)$$
Eventually, (1) easily implies from the geodesic equation that the connection coefficients must  vanish at $p$ in the said coordinate system.
In fact, it must hold at $s=0$
$$\Gamma(0)_{ab}^cv^av^b=- \frac{d^2sv^c}{dt^2}|_0=0$$
for every choice of the coefficients $v^a$. Using the fact that the connection is symmetric, replacing $v$ for $u\pm w$, you find $$\Gamma(0)_{ab}^c=0.$$
If the connection is metric (Levi-Civita), we also have for free that
$$\frac{\partial g_{ab}}{\partial x^c}|_{p}=0$$
in the said coordinate system. It arises by just writing the above derivative in terms of connection coefficients (using the metricity condition).
ADDENDUM. Actually the exponential map is defined also when the connection has torsion (I did not use that hypothesis in defining the exponential map). In that case, the reasoning above proves that the symmetric part of the connection coefficients vanishes at the center of a normal system of coordinates. The antisymmetric part cannot be cancelled in any cases as said at the beginning of this answer.

A: Also, to close the loop, let's prove this by controposition.  Let's assume that, for some torsion-having metric, we HAVE produced a transformation that makes all $\Gamma$ zero at some point.  Then, at this point, we have:
$$\nabla_{a}v^{b} = \partial_{a}v^{b}$$
Now, transform to some other coordinate system.  This will require that we multiply $v^{b}$ by the transformation matrix $P^{a}{}_{b} = \frac{\partial y^{a}}{\partial{x^{b}}}$
Now, we have, in this new coordinate system (suppressing multiplication on the left by two factors of $P$ on both sides to transform the basis components:
$$\nabla_{a}v^{b} = \partial_{a}\left(P^{b}{}_{c}v^{c}\right) = P^{b}{}_{c}\partial_{a}v^{c} + v^{c}\partial_{a}P^{b}{}_{c}$$
The first term becomes just the partial derivative term again, because the factors of P that we suppressed satisfy the identity $P^{a}_{b}P^{b}{}_{c} = P^{a}{}_{c}$ by the chain rule.  That second term must be the Christoffel symbol in our new frame with nonzero Christoffel symbols, so:
$$\Gamma_{ab}{}^{c} = \partial_{a}P^{c}{}_{b} = \frac{\partial^{2}y^{c}}{\partial x^{a} \partial x^{b}}$$
This cannot have any torsion associated with it, because it is symmetric in a and b.

A: The OP is not the only person who has wondered about this.
And even a textbook can be mistaken, or at least misleading, about this.
I have in my possession a textbook which assigns this as an exercise.  It says that for any point $P$ of a manifold and any connexion on any neighbourhood of it $U$, there exist coordinates (in a neighbourhood of $P$ which is possibly smaller than $U$) such that all $\Gamma_{ij}^k$ are zero at $P$.  Part of the exercise is to construct the coordinates using the geodesics of $\Gamma$ which begin at $P$.
Not every textbook is error-free, and Doubrovine, Novikov, and Fomenko, is certainly not.
But there it is, on p. 285, of Geometrie Contemporaine, Methodes et Applications, Premier Partie, Geometrie des surfaces, des groupes de transformations et des champs, Moscow, 1982, tranlated from the Russian edition of 1979.  I understand that the new revised Russian edition is freely available on the web.  Also, I have read this theorem elsewhere for the special case of connexions which are torsion free and compatible with the metric.  But neither of those assumptions are made here.
One can not trust one exercise posed in one textbook, and Moretti has solved their exercise under the hypothesis that there is no torsion.
So the same question that the OP wanted clarified is actually the subject of a mistake in a reputable textbook.


text:
Q: resizing div after AJAX call jQuery I am attempting to resize a div after I load in new HTML content via AJAX. I have a hashbang linking system that loads up particular HTML snippets if certain hashes are present in the URL. The div height resizes correctly when links are pressed to load in the content, but the computed height of the loaded content is consistently 20px less when the page is navigated to directly.
HTML:

Need some help with searches?

Recommendations

What's Hot

History

Additional Features

Select a help topic above!

 ...

jQuery:
$(document).ready(function(){
  if(window.location.hash)
  {
    loadContent(window.location.hash)
  }

  $(".docs_link").click(function(e){
    $(".help_page_content").html("")
    var fragment = this.hash
    loadContent(fragment)
  });

  function loadContent(fragment)
  {
    fragment = fragment.slice(1).replace(/!\//g, "");
    $(".help_page_content").load("./"+fragment+".html", function(){
      var height = $("#ajax_page_wrap").outerHeight();
      $(".help_page_content").animate({height: height}, 500);
    });
  }
});

An example to clarify:
If I navigate to www.homepage.com/docs/ directly, and then click one of the help links to load content, the height is computed fine. However, if I navigate to www.homepage.com/docs/#!/history, the computed height is always about 20px less than it should be.

A: Is there an image inside the #ajax_page_wrap div that is not yet loaded when you navigate directly there (and the AJAX call is completing before it's loaded)?
What about using $(window).load (which waits for all the images to load) instead of $(document).ready (which does not).  See this answer.
Hope the helps! Lemme know if that's not the issue and I'll keep brainstorming :)


text:
Q: Apache worker mpm, one process and many threads: understanding performance Got a mod_perl-written serverside program.
Im using shared apache worker mpm memory with one process only, and ~ 60 threads.
Im using locks to temporary secure the access to the shared memory, just 0.1s out of 1.7s are locked time though.
The problem is that i get the same speed on 10 sequential requests compared to 10 concurrent requests.
my stress-script fire up n number of heavy URL process-requests with 0.1s delay between each. The number in brackets is the request number.
perl stressTestServer.pl n=1
DONE  ( 0 ) > 1.778257 sek

perl stressTestServer.pl n=5
DONE  ( 3 ) > 8.71926 sek
DONE  ( 0 ) > 8.85207 sek
DONE  ( 1 ) > 8.976061 sek
DONE  ( 4 ) > 9.119936 sek
DONE  ( 2 ) > 9.218552 sek

perl stressTestServer.pl n=10
DONE  ( 9 ) > 8.840539 sek
DONE  ( 7 ) > 9.130133 sek
DONE  ( 8 ) > 9.271598 sek
DONE  ( 6 ) > 9.873936 sek
DONE  ( 5 ) > 10.02668 sek
DONE  ( 4 ) > 18.169001 sek
DONE  ( 3 ) > 18.432776 sek
DONE  ( 2 ) > 18.617186 sek
DONE  ( 1 ) > 18.775277 sek
DONE  ( 0 ) > 18.821972 sek

is this normal for this setup?
this is tested on a dual-core. moving to a quad core, what performance difference can i expect with this setup?
I have a hard time believing more cores will help here..
feels like serialized execution could be more efficient than concurrent threads.
tx for input!


text:
Q: Left join in pandas without the creation of left and right variables I'm missing something in the syntax of merging in pandas.
I have the following 2 data frames:
>>> dfA
  s_name  geo    zip  date value
0  A002X  zip  60601  2010  None
1  A002Y  zip  60601  2010  None
2  A003X  zip  60601  2010  None
3  A003Y  zip  60601  2010  None

(or potentially some values exist which will not overlap with dfB:
>>> dfA_alternate
  s_name  geo    zip  date value
0  A002X  zip  60601  2010   NaN
1  A002Y  zip  60601  2010   2.0
2  A003X  zip  60601  2010   NaN
3  A003Y  zip  60601  2010   NaN

)
And
>>> dfB
  s_name  geo    zip  date  value
0  A002X  zip  60601  2010    1.0
1  A002Y  zip  60601  2010    NaN
3  A003Y  zip  60601  2010    4.0

I'd like to join the data present in dfB onto dfA, like so:
>>> new
  s_name  geo    zip  date value
0  A002X  zip  60601  2010   1.0
1  A002Y  zip  60601  2010   NaN
2  A003X  zip  60601  2010   NaN
3  A003Y  zip  60601  2010   4.0

(or
>>> new_alternate
  s_name  geo    zip  date value
0  A002X  zip  60601  2010   1.0
1  A002Y  zip  60601  2010   2.0
2  A003X  zip  60601  2010   NaN
3  A003Y  zip  60601  2010   4.0

)
However, what seems like natural syntax actually makes extra columns:
>>> pd.merge(dfA,dfB,on=["s_name","geo","zip","date"],how="left")
  s_name  geo    zip  date value_x  value_y
0  A002X  zip  60601  2010    None      1.0
1  A002Y  zip  60601  2010    None      NaN
2  A003X  zip  60601  2010    None      NaN
3  A003Y  zip  60601  2010    None      4.0

(
>>> # alternate
>>> pd.merge(dfA_alterate,dfB,on=["s_name","geo","zip","date"],how="left")
  s_name  geo    zip  date value_x  value_y
0  A002X  zip  60601  2010     NaN      1.0
1  A002Y  zip  60601  2010     2.0      NaN
2  A003X  zip  60601  2010     NaN      NaN
3  A003Y  zip  60601  2010     NaN      4.0

)
There's value_x and value_y when I'd rather just have value.
I get that I can clean this up after the fact with:
new["value"] = new.apply(lambda r: r.value_x or r.value_y, axis=1)
new.drop(["value_x", "value_y"], axis=1, inplace=True)

But I imagine there's just merge syntax I need to change to get it right without post-processing.  What am I missing?

A: I think you need combine_first with MultiIndex created by set_index:
cols = ["s_name","geo","zip","date"]

df = dfA.set_index(cols).combine_first(dfB.set_index(cols)).reset_index()
print (df)
  s_name  geo    zip  date  value
0  A002X  zip  60601  2010    1.0
1  A002Y  zip  60601  2010    2.0
2  A003X  zip  60601  2010    NaN
3  A003Y  zip  60601  2010    4.0

Or update:
df = dfA.set_index(cols)
df.update(dfB.set_index(cols))
df = df.reset_index()


text:
Q: Drag and drop cells on CSS Grid only works properly when moving a cell to the right, and does not work when moving a cell to the left I have a CSS Grid and I'm trying to implement a drag and drop (or drag and swap) feature. It's getting close to working as desired but as the title says, the dragged cell will not drop properly into a cell to the left of its original position. The feature only works when the cell being dragged is moved to the right. Can anyone see what the problem is?

var dragSrcEl = null;
function handleDragStart(e) {
  this.style.opacity = "0.4";
  dragSrcEl = this;
  e.dataTransfer.effectAllowed = "move";
}

function handleDragOver(e) {
  if (e.preventDefault) {
    e.preventDefault();
  }
  e.dataTransfer.dropEffect = "move";
  return false;
}

function handleDragEnter(e) {
    this.classList.add("over");
}

function handleDragLeave(e) {
  this.classList.remove("over");
}

function handleDrop(e) {
  if (e.stopPropagation) {
    e.stopPropagation();
  }

  if (dragSrcEl != this) {
    this.replaceWith(this, dragSrcEl);
  }
  return false;
}

function handleDragEnd(e) {
  this.style.opacity = "1";
  items.forEach(function (item) {
    item.classList.remove("over");
  });
}
  let items = document.querySelectorAll(".grid-container .grid-item");
  items.forEach(function (item) {
    item.addEventListener("dragstart", handleDragStart, false);
    item.addEventListener("dragenter", handleDragEnter, false);
    item.addEventListener("dragover", handleDragOver, false);
    item.addEventListener("dragleave", handleDragLeave, false);
    item.addEventListener("drop", handleDrop, false);
    item.addEventListener("dragend", handleDragEnd, false);
  });
.grid-container {
       display: grid;
       grid-template-columns: repeat(3, 40px);
       grid-template-rows: repeat(4, 30px);
       margin: auto;
     }
        .grid-item {
          border: 1px solid #666;
          background-color: #ddd;
          cursor: move;
        }
          .grid-item.over {
            border: 3px dotted #666;
          }

          [draggable] {
            user-select: none;
          }
<!DOCTYPE html>

1

2

3

A: I have added six more grid items to your code, so in my sample code the grid is three by three.
Now, when you drag a grid item, you can clearly see that no swapping is taking place in either direction. For example, drag item 9 and drop it on 2. The new order will be:
1 2 9  3 4 5  6 7 8  and not  1 9 3  4 5 6  7 8 2  as expected if swapping took place

Your code is inserting the dragged item to a new position and shuffling the rest of the items.
Please have a look at the answer to the following question for a drag and drop swap implementation

var dragSrcEl = null;

function handleDragStart(e) {
  this.style.opacity = "0.4";
  dragSrcEl = this;
  e.dataTransfer.effectAllowed = "move";
}

function handleDragOver(e) {
  if (e.preventDefault) {
    e.preventDefault();
  }
  e.dataTransfer.dropEffect = "move";
  return false;
}

function handleDragEnter(e) {
  this.classList.add("over");
}

function handleDragLeave(e) {
  this.classList.remove("over");
}

function handleDrop(e) {
  if (e.stopPropagation) {
    e.stopPropagation();
  }

  if (dragSrcEl != this) {
    this.replaceWith(this, dragSrcEl);
  }
  return false;
}

function handleDragEnd(e) {
  this.style.opacity = "1";
  items.forEach(function(item) {
    item.classList.remove("over");
  });
}
let items = document.querySelectorAll(".grid-container .grid-item");
items.forEach(function(item) {
  item.addEventListener("dragstart", handleDragStart, false);
  item.addEventListener("dragenter", handleDragEnter, false);
  item.addEventListener("dragover", handleDragOver, false);
  item.addEventListener("dragleave", handleDragLeave, false);
  item.addEventListener("drop", handleDrop, false);
  item.addEventListener("dragend", handleDragEnd, false);
});
.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 40px);
  grid-template-rows: repeat(4, 30px);
  margin: auto;
}

.grid-item {
  border: 1px solid #666;
  background-color: #ddd;
  cursor: move;
}

.grid-item.over {
  border: 3px dotted #666;
}

[draggable] {
  user-select: none;
}
<!DOCTYPE html>

1

2

3

4

5

6

7

8

9


text:
Q: Working with a JSON on a third-part server I'm developing an Android application with cordova, I need to read the json file from this address: Dati.venezia.it and put it into a json variable. i have tried using jQuery getJson but i had problems with CORS i have also tried the same think with JSONP but i havent got how it works.
Any help would be appreciated.
console.log("start");
var url = 'http://dati.venezia.it/sites/default/files/dataset/opendata/livello.json?callback=?';
this.risultato= $.getJSON(url, function(data){

});
console.log("end");

and this was the attempt with getJson
$.getJSON('http://dati.venezia.it/sites/default/files/dataset/opendata/livello.json', function (data) {
  console.log(data);

  var items = data.items.map(function (item) {
    return item.key + ': ' + item.value;
  });

  showData.empty();

  if (items.length) {
    var content = '
' + items.join('

') + '
';
    var list = $('
').html(content);
    showData.append(list);
  }
});

A: You are correct that you can use jsonp as a workaround.  Looking at Dati.venezia.it , it doesn't look like it currently supports jsonp.  You'll need to have the endpoint Dati.venezia.it provide a callback for jsonp to work.
Additionally, the endpoint is missing the response header Access-Control-Allow-Origin, which won't allow other sites to pull data from it without that header.  This is why you're running into CORS issues.  If you have control of that website, you'll need to add Access-Control-Allow-Origin to it's response headers.


text:
Q: JDBC ResultSet with SQL Server When query using JDBC createStatement and getting ResultSet of millions of rows (from SQL Server), what SQL queries are really executed, where do the rows are stored and how many rows? Does it use SQL Server cursor?
I know that only a limited number of rows are kept in the client-side memory (where the Java code), so where are the rest of the rows kept, or maybe they are not yet queried from the SQL Server)?
When I looked at SQL Server profiler, it just shows the normal query (it didn't add cursor or TOP X of something else)

A: Taken from the SQL Server documentation on Adaptive Buffering:

Normally, when the Microsoft JDBC Driver for SQL Server executes a query, the driver retrieves all of the results from the server into application memory. Although this approach minimizes resource consumption on the SQL Server, it can throw an OutOfMemoryError in the JDBC application for the queries that produce very large results.

There's a way around that, what SQL Server calls Adaptive Buffering and which seems to be enabled by default for JDBC driver version 2+ and you might want to read up on it in the documentation. Here's the gist:

In order to allow applications to handle very large results, the Microsoft JDBC Driver for SQL Server provides adaptive buffering. With adaptive buffering, the driver retrieves statement execution results from the SQL Server as the application needs them, rather than all at once.


text:
Q: Is it possible to use structured bindings to assign class members? I'd like to use C++ 17 structured bindings to assign a value to a class member variable, like this:
#include <cmath>
#include <iostream>

struct Result {
  double value;
  bool error;
};

Result square_root(double input) { return {std::sqrt(input), input < 0}; }

struct Calculator {
  double result_;
  bool error_;

 public:
  void ComputeSquareRoot(double input) {
    [ result_, error_ ] = square_root(input);
  }

  void DisplayResult() {
    if (error_)
      std::cout << "Cannot take the square root of a negative number.\n";
    else
      std::cout << "The square root is " << result_ << ".\n";
  }
};

int main(int argc, char* argv[]) {
  Calculator calc;
  calc.ComputeSquareRoot(64);
  calc.DisplayResult();
}

But this code fails to compile with the following error (using clang 5.0):
> clang++ structured_bindings.cpp -std=c++17 -o structured_bindings
structured_bindings.cpp:20:7: error: 'result_' in capture list does not name a variable
    [ result_, error_ ] = square_root(input);
      ^
structured_bindings.cpp:20:16: error: 'error_' in capture list does not name a variable
    [ result_, error_ ] = square_root(input);
               ^
structured_bindings.cpp:20:25: error: expected body of lambda expression
    [ result_, error_ ] = square_root(input);
                        ^
3 errors generated.

There seems to be some confusion with lambda capture. Certainly this will work:
auto[result, error] = square_root(input);
result_ = result;
error_ = error;

But I would like to avoid the need to use new local variables. Is this possible with structured bindings?

A: Use std::tie to assign values to existing objects:
std::tie(result_, error_) = square_root(input);

That's why it was added to C++11. Of course, you'd need to forego using Result in favor of a std::tuple. Which IMO is better for such ad-hoc "return multiple things" scenarios.
Structured bindings are exclusively for declaring new names.
Another approach, which could be even better, since C++1z is on the table, is to not re-invent the wheel. Return a std::optional
auto square_root(double input) {
   return input < 0 ? std::nullopt : std::optional{std::sqrt(input)};
}

This has the clear semantics of "there may be a value, or not".

By the way, unconditionally calling std::sqrt with a negative input is a bad idea. Especially if you don't configure your floating point environment in any special way prior.


text:
Q: Is soundness implies consistency in all logical systems? I am a physics student and I don't have a formal education in set theory and logic but I am interested.
Is soundness equivalent to consistency in any logical system?
When a theory is sound and we have a model, I know that consistency is a consequence of soundness.
Is consistency implies existence of a model in all logical systems?(I know that the converse is true)
Is there a sound theory where the consistency is not a consequence of the soundness?


text:
Q: MTImageMapView EXC_BAD_ACCESS I am using MTImageMapView for my project
https://github.com/stkim1/MTImageMapView
It's a great view and I find it very useful for my purposes.
Unfortunately sometime I encounter EXC_BAD_ACCESS error.
During profiling with Instruments XCode I found our a Zombie object
On stack trace there are two lines which probably cause this error
MTImageMapView.m line 82, which is property declaration
MTImageMapView.m line 183, which is assignment
I tried to contact the author but I didn't get any response from him.
Unfortunately my experience does not allow me to easily fix this.
Can anybody help me, this is very important.
Kind regards


text:
Q: Remove hash id from url I have a menu header and when you click one of the menu links it directs to another page half way down (which i want) as it finds the relevant div id name. I was wondering if there is a way to clean the url back up again so it doesn't include the #id in my url? Tried window.location hash and this breaks it from scrolling and leaves the # in the url. Here is what i have:
In my menu:
<a href="about#scroll-to" ....
And on the about page, it scrolls down to a div called #scroll-to..

Any suggestions would be great. Thanks!

A: Using jquery, you can make a POST call to the target page when menu is clicked.
The POST data will contain the id of the div where you want to slide to.
On your target page, use your server language (php, asp) to output that id in a js variable and on document ready slide using jquery to that id.
Then you will have a clean url, and the page scrolling to your div.
---- edit: here comes the code!
Lets use jquery to make a POST to the target page, when a menu item is clicked. We will add a class, lets say, "mymenuitem". We will add this class to our link in the menu. So we will have

Information about us

(the onClick stops link from redirecting manually)
and an empty form (put it after the )
<form id="slidinganchorform" method="post" action="YOURTARGETPAGE.HTML"></form>

then we will create the neccessary jquery so when the  tag with class "mymenuitem" is clicked, we will make a POST to the target page.

then in our YOURTARGETPAGE.HTML we will have something like (let's assume we use php)

<?php
if($_POST['anchorid']!='')
{
?>

<?php
}
?>

be sure the correct id must exist ;)
Information about us or whatever...

(remove your old code because i changed some variable names and it will be difficult to debug if there are parts from the previous version. write everything from the start )

A: You can do this when the new page loads
history.pushState("", document.title, window.location.pathname);

However it will also remove the query string. Although, you could play with it a little bit to keep it


text:
Q: bash enable autocomplete for PATH names In bash, if I were to type which pyth<tab> it would autocomplete to which python. I have my own program, limitcpu, and if I type limitcpu pyth<tab> nothing happens.
Tab completion still works for files where I provide the path, but I would like it to work with files (programs) in the PATH environment variable as it does with which.

A: The bash configuration option complete -c <list of commands> will allow each command in <list of commands> to autocomplete with other commands.
In this case, put complete -c limitcpu in ~/.bashrc or any other place it can be sourced.


text:
Q: how to consume ws security header in soap web service c# I need some help.Firstly I wrote one soap web service with basic authentication.But I have to change with wssecurity in soap.How can I consume coming ws security header I have to read username and password and I have to compare my username and password in my webconfig file inside service.  I write this code but I m not sure :  I done this way.But how can I configure in webconfig.file
         public class QuantityService : Microsoft.Web.Services3.WebServicesClientProtocol, IQuantityService
{

    private OperationResult AuthCheck()
    {
        OperationResult retVal = new OperationResult()
        {
            ReturnCode = 0,
            ReturnMessage = "OK"
        };

        string userName = ConfigurationManager.AppSettings["username"].ToString();
        string password = ConfigurationManager.AppSettings["password"].ToString();

        //UsernameToken token = new UsernameToken(userName,password,PasswordOption.SendPlainText);
        QuantityService serviceProxy = new QuantityService();
        SoapContext requestContext = serviceProxy.RequestSoapContext;

        //requestContext.Security.Tokens.Add(token);

        if (requestContext == null)
        {
            throw new ApplicationException("Non-SOAP request.");
        }

        foreach (SecurityToken tok in requestContext.Security.Tokens)
        {
            if (tok is UsernameToken)
            {
                if (userName == ((UsernameToken)tok).Username && password == ((UsernameToken)tok).Password)
                {
                    retVal.ReturnCode = 0;
                    retVal.ReturnMessage = "OK";
                }
                else
                {
                    retVal.ReturnCode = -2;
                    retVal.ReturnMessage = "Unauthorized.";
                }
            }
        }

        return retVal;
    }


text:
Q: Is there a Mechanism to Take AAD Auth & Make SharePoint Online Auth I have an application that is successfully logging into the Microsoft Graph, with correct Scopes, and querying SharePoint Online resources: Lists, Files etc, with the Microsoft Graph SDK (3.18.xxx)
I would like to access CSOM specific features using the Microsoft SharePoint CSOM (16.1.xxx)
These features include LoadClientSidePage, and all the associated nice things you can do with ClientSidePage
(note, if I "re-auth" the user, everything works perfectly well)
Rather than having the user log in twice (once for Graph, once for SharePoint CSOM) -- is there a feature of SharePoint CSOM Auth where I can exchange my Bearer: Access Token for the SharePoint CSOM equivalent ? (I may be wrong, but I think it is a WSFed Token)?
Thanks

A: I think it's possible. You can attach access token to csom as below:
public ClientContext GetContext(Uri web, string userPrincipalName, SecureString userPassword)
{
 var context = new ClientContext(web);

 context.ExecutingWebRequest += (sender, e) =>
 {
     //get access token
     e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;
 };

 return context;
}

How to exchange the token?
Generally one access token only against one resource. However Refresh tokens are valid for all permissions that your client has already received consent for - thus, a refresh token issued on a request for scope=mail.read can be used to request a new access token for scope=api://contoso.com/api/UseResource.

*

*https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token
Another possible method is to use OAuth 2.0 On-Behalf-Of flow. The OAuth 2.0 On-Behalf-Of flow (OBO) serves the use case where an application invokes a service/web API, which in turn needs to call another service/web API

*

*https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow
The token that CSOM required is the same as SharePoint rest API
If you're using V1.0 author endpoint, please refer to https://learn.microsoft.com/en-us/azure/active-directory/azuread-dev/v1-protocols-oauth-code#refreshing-the-access-tokens.


text:
Q: How to write Rspec Testing for devise authenticate methods  def self.find_for_database_authentication(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    else
      where(conditions).first
    end
  end

Above is the method for authenticate and that code is from Model.
I unable to understand how to pass warden_conditions as parameter in this method for testing.
Can you please help me how to pass warden_condition as parameter for Rspec (Unit) Testiong?
Thanks

A: That seems to be a class method, and warden_conditions seems to be just a hash, so you can use something like this
let(:email) { "foo@bar.com" }
let(:warden_conditions) { { login: email } }

it "finds user by email" do
  user = User.create(email: email)
  authenticated = User.find_for_database_authentication(opts)
  expect(authenticated).to eql user
end

it "finds user by username" do
  user = User.create(username: email)
  authenticated = User.find_for_database_authentication(opts)
  expect(authenticated).to eql user
end


text:
Q: Splitting up elements into groups of n child elements (follow-up from 69940580) Follow-up from insert page-break after all elements except the last, when position() is not reliable.
How would I achieve the following result (more info below):
<pages>
    <page title="Manchuria">
        <edit version="2"/>
        <edit version="3"/>
    </page>
    <page-break/>
    <page title="Manchuria">
        <edit version="4"/>
        <edit version="5"/>
    </page>
    <page-break/>
    <page title="Manchuria">
        <edit version="6"/>
        <edit version="7"/>
    </page>
    <page-break/>
    <page title="Perfect the first time"/>
    <page-break/>
    <page title="Zombie Librarian">
        <edit version="2"/>
    </page>
</pages>

From the following input:
<articles>

        <original>

        </original>
        <edits>

        </edits>

        <original>

        </original>
        <edits/>

        <original>

        </original>
        <edits>

        </edits>

</articles>

starting from the following xslt:
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:exsl="http://exslt.org/common"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match="/">
        <pages>
            <xsl:variable name="pages">
                <xsl:apply-templates select="/articles/article[@publishable='true']" mode="subfilter"/>
            </xsl:variable>

            <xsl:apply-templates select="msxsl:node-set($pages)/article" mode="layout"/>
        </pages>
    </xsl:template>

    <xsl:template match="article" mode="subfilter">
        <xsl:variable name="id_of_latest_edit">
            <xsl:for-each select="edits/article">
                <xsl:sort data-type="number" select="@version"/>
                <xsl:if test="position()=last()">
                    <xsl:value-of select="@id"/>
                </xsl:if>
            </xsl:for-each>
        </xsl:variable>
        <xsl:if test="@id = $id_of_latest_edit or not(edits/article)">
            <xsl:copy-of select="."/>
        </xsl:if>
    </xsl:template>

    <xsl:template match="article" mode="layout">
        <page title="{@title}">
            <xsl:apply-templates select="edits/article" mode="editdetails"/>
        </page>
        <xsl:if test="position()!=last()">
            <page-break/>
        </xsl:if>
    </xsl:template>

    <xsl:template match="article" mode="editdetails">
        <xsl:param name="editPos"/>
        <edit version="{@version}"/>
    </xsl:template>

</xsl:stylesheet>

The problem
A page can have maximum n edit elements (n=2 in this example), and the edits need to be sorted by version.
What I tried
Before the linked question was solved, I tried something along the lines of:
    <xsl:template match="article" mode="subfilter">
        <xsl:variable name="currentnode" select="."/>

        <xsl:apply-templates select="." mode="layout"/>

        <xsl:if test="count(edits/article) > 2">
            <xsl:for-each select="edits/article[(position() mod 2) = 0]">
                <xsl:apply-templates select="$currentnode" mode="layout"/>
            </xsl:for-each>
        </xsl:if>
    </xsl:template>

which gets me the multiple pages and I would still need to filter and sort the edit elements. However, the new code (to get the page-breaks) uses the node-set() function and I can't seem to figure out how to merge this approach (if it is even a good idea to try). Is maybe muenchian grouping needed?

A: I suppose this is one way you could look at it:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/articles">
    <pages>
        <xsl:variable name="pages">
            <xsl:apply-templates select="article[@publishable='true']" mode="preprocess"/>
        </xsl:variable>
        <xsl:apply-templates select="exsl:node-set($pages)/page"/>
    </pages>
</xsl:template>

<xsl:template match="article[not(edits/article)]" mode="preprocess">
    <page title="{@title}"/>
</xsl:template>

<xsl:template match="article" mode="preprocess">
    <xsl:variable name="title" select="@title" />
    <xsl:for-each select="edits/article">
        <xsl:sort select="@version" data-type="number" order="ascending"/>
        <xsl:if test="position() mod 2 = 1">
            <page title="{$title}">
                <edit version="{@version}"/>
                <xsl:if test="position()!=last()">
                    <edit version="{@version + 1}"/>
                </xsl:if>
            </page>
        </xsl:if>
    </xsl:for-each>
</xsl:template>

<xsl:template match="page">
    <xsl:copy-of select="."/>
    <xsl:if test="position()!=last()">
        <page-break/>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

Note that this assumes versions are numbered consecutively.


text:
Q: Using Tesseract for handwriting recognition I was just wondering how accurate can tesseract be for handwriting recognition if used with capital letters all in their own little boxes in a form.
I know you can train it to recognise your own handwriting somewhat but the problem in my case is I need to use it across multiple handwritings. Can anyone point me in the right direction?
Thanks a lot.

A: In short, you would have to train the Tesseract engine to recognize the handwriting. Take a look at this link:
Tesseract handwriting with dictionary training
This is what the linked post says:

It's possible to train tesseract to recognize handwriting. Here are
the instructions:
https://tesseract-ocr.github.io/tessdoc/Training-Tesseract
But don't expect very good results. Academics have typically gotten
accuracy results topping out about 90%. Here are a couple references
for words and numbers. So if your use case can deal with at least 1/10
errors, this might work for you.

Also here is a good academic article written on this subject:
Recognition of Handwritten Textual Annotations using Tesseract
Open Source OCR Engine for information Just In Time (iJIT)


text:
Q: BrainTreePayments create new payment method I am going through the BrainTreePayments documentation page and I came across the Payment Methods. The documentation says "To create a new payment method for an existing customer, the only required attributes are the customer ID and payment method nonce."
gateway.paymentMethod.create({
  customerId: "12345",
  paymentMethodNonce: nonceFromTheClient
}, function (err, result) { });

The question is
1) How do we create a new payment method for a new customer without payment method nonce?
2) How do we verify the validity of an existing payment method?

A:  Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
1) A payment method is like a container to store payment information in your Vault, whereas the payment method nonce is a way to deliver payment information to Braintree. You use a payment method nonce to deliver payment information to create payment methods, transactions, etc. A payment method can be referenced to generate a payment method nonce from stored payment information, but the payment method must store something. You can't create an empty payment method.
2) To verify an existing payment method, use 'PaymentMethod.update()' and include 'verify_card' in your options. If you have enabled fraud tools in your control panel, newly created payment methods for credit cards will be verified before they are stored in the Vault. Cards that are not valid will not be stored and you will receive an error response.


text:
Q: ExecuteSqlRawAsync returns -1 in Entity Framework 3.1 In my ASP.NET Core 3.1  web application, I am mostly using stored procedures. When using ExecuteSqlRawAsync in Entity Framework Core it always returns -1. Below given is my generalized method to execute stored procedures.
  public async Task<int> ExecuteSqlNonQuery(string StoredProcName, params object[] parameters)
  {
        int iTotalRecordsAffected = 0;

        List<TEntity> listOfObject = null;

        try
        {
            if (!string.IsNullOrEmpty(StoredProcName))
            {
                StringBuilder sbStoredProc = new StringBuilder();
                sbStoredProc.Append("Exec ");
                sbStoredProc.Append(StoredProcName);

                if (parameters != null)
                {
                    foreach (SqlParameter item in parameters)
                    {
                        if (listOfObject == null)
                        {
                            sbStoredProc.Append(" @");
                            listOfObject = new List<TEntity>();
                        }
                        else
                        {
                            sbStoredProc.Append(", @");
                        }
                        sbStoredProc.Append(item.ParameterName.Replace("@", ""));
                        if (item.Direction == System.Data.ParameterDirection.Output)
                        {
                            sbStoredProc.Append(" OUT");
                        }
                    }
                }

                iTotalRecordsAffected = await _DBContext.Database.ExecuteSqlRawAsync(sbStoredProc.ToString(), parameters);
            }
        }
        catch (Exception ex)
        {

        }
        finally
        {
            if (_DBContext.Database.GetDbConnection().State == System.Data.ConnectionState.Open)
            {
                _DBContext.Database.GetDbConnection().Close();
            }
        }

        return iTotalRecordsAffected;
 }

Here is my controller method that calls a SP to update data.
   public async Task<int> UpdateCustomerData(EditCustomerDetail editCustomerDetail)
    {
        int iTotalRecordsEffected = 0;

        try
        {
            List<SqlParameter> sqlParamList = new List<SqlParameter>()
            {
                new SqlParameter("@CustomerID",editCustomerDetail.CorporateID),
                new SqlParameter("@CustomerName",editCustomerDetail.CorporateName),
                new SqlParameter("@CustomerAddress",editCustomerDetail.Address),
                new SqlParameter("@City",editCustomerDetail.City),
                new SqlParameter("@CountryID",editCustomerDetail.CountryID),
                new SqlParameter("@StateID",editCustomerDetail.StateID),
                new SqlParameter("@Description",editCustomerDetail.Description),
                new SqlParameter("@Phone",editCustomerDetail.Phone),
                new SqlParameter("@Fax",editCustomerDetail.Fax),
                new SqlParameter("@ModifiedBy",editCustomerDetail.UserID)
            };

            iTotalRecordsEffected = await _unitOfWork.GetRepository<EditCustomerDetail>().ExecuteSqlNonQuery("UpdateCustomerDetails", sqlParamList.ToArray());
        }
        catch (Exception ex)
        {

        }
        finally
        {

        }
        return iTotalRecordsEffected;
    }

Any suggestion what I am doing wrong?


text:
Q: How to customize right click with already existing instance of a program? I need to customize right click so that I can scan a directory with my anti-virus. I know how to do that using registry keys, but the problem is that I don't want to start a new instance of my program every time I want to scan a directory. My anti-virus needs to load some signature databases so it will take around 15 seconds for the program to load those. I need to use the instance of the program which I have already opened and is running for scanning the directory. How can I do that?
I am using C++Builder.
Thanks.

A: Considering you already know how to add the item to the right click contextual menu, I suggest implementing a client/server set of applications:

*

*A server that loads up when you turn your computer on and does the scanning, and

*The client that tells it what to do using IPC - inter-process communication.

You then add the client application to various contextual menus, passing it arguments that indicate what it should get the server to do depending on what you right-clicked on.
IPC is a bit of a pain in the butt, the easiest way is to use TCP/IP to and do local networking using a network library. There are many out there, however given you'll likely want to have other features such as UI elements and a tray icon, I suggest you look at Qt, namely the following components:

*

*QtNetwork: For performing communication between the client and the server executable.

*QSystemTrayIcon: For displaying a small icon on the tray.
There are quite a few other little bits of Qt you'll no doubt encounter (like all the fabulous UI stuff), and fortunately Qt is well documented and help is always available here, and from the Qt Developer Network. You can get started with Qt by downloading and installing the SDK:
http://qt.nokia.com/downloads/
Best of luck :).

A: Implement a DDE server in your anti-virus, and then add a ddeexec subkey to your Registry key. Alternatively, add an OLE Automation object to your app that implements the IDropTarget interface, and then add a DropTarget subkey to your Registry key that specifies the object's CLSID.
Either way, whenever your menu item is then invoked, Windows will call into your existing app instance if it is already running, otherwise it will launch a new instance and then call into it.  Either way, Windows is handling all of that for you.  All you are doing is providing an entry point for Windows to call into.
I would suggest the IDropTarget method, because DDE is deprecated, and because IDropTarget is more flexible.  While your app is running, you could re-use the same IDropTarget object to handle OLE Drag&Drop operations on your app's UI window and Taskbar button, and support automated invokations of your scanner by other apps.


text:
Q: Main function with three arguments I ran into a function like this earlier:
int main(int argc, char **argv, char **argw){

}

Why is there a need for three arguments, and how does this actually work?

A: The third argument to main is normally called envp.
int main(int argc, char **argv, char **envp) {

Many compilers provide a third argument to main, but it is not specified in the C standard, so using it is undefined behaviour. If you try to port the code to a platform that doesn't provide a third parameter the program will most likely fail.
Is char *envp[] as a third argument to main() portable

A: I've seen these arguments before. My compiler places them there as well when starting in C++ code. I can tell you for a fact that they are not necessary in C++, although I can't say for sure in C. They look to be slots for a variables to be passed in to the function int main. One of type int, and two of type char. These variables would be passed in, generally by the user at the time the program is executed.


text:
Q: SQL Server Cross Permutations from a single table Quite a tricky scenario. I have a table as below. Basically I want to get all combinations of ranges from each RangeSet in SQL Server 2012.
Best I show an example of structure and desired output. The problem is the number of RangeSetID's can be dynamic and the number of RangeID's can be dynamic in each range set
RangeID RangeSetID
------------------
1          4
2          4
3          4
4          4
5          2
6          2
7          2
8          2
9          2
10         2
11         1
12         1
13         1
14         1
15         1
16         1
17         3
18         3
19         3
20         3

I need the output to recursively create the below dataset of rates:
1 5 11 17  (first from range4, first from range2, first from range1, first from range3)
1 5 11 18 (first from range4, first from range2, first from range1, second from range3)
1 5 11 19 (first from range4, first from range2, first from range1, third from range3)
1 5 11 20 (first from range4, first from range2, first from range1, fourth from range3)
1 5 12 17 (first from range4, first from range2, second from range1, first from range3)
1 5 12 18 (first from range4, first from range2, second from range1, second from range3)
1 5 12 19
1 5 12 20

And so on until I reach the last RangeID from each RangeSetID and result in
4 10 16 20 (last from range4, last from range2, last from range1, last from range3)

Which will ultimately result in the below where RateID 1 is showing the first result vertically to allow for the dynamic number of RangeSetID's
RateID    RangeID
------------------
  1         1
  1         5
  1         11
  1         17
  2         1
  2         5
  2         11
  2         18

This should result in 11,000 rows (approx). I have tried CROSS JOIN's etc but I cannot get this working at all.
Any geniuses out there please?
Thanks

A: If you know that you have four groups, then the logic would be:
select t1.rangeid, t2.rangeid, t3.rangeid, t4.rangeid
from t t1 cross join
     t t2 cross join
     t t3 cross join
     t t4
where t1.rangesetid = 1 and
      t2.rangesetid = 2 and
      t3.rangesetid = 3 and
      t4.rangesetid = 4;

If you do not know the number of values of rangesetid, then you will need to use dynamic SQL.  A SQL SELECT statement returns a fixed set of columns -- so you cannot have a variable number based on the number of values of a column.

A: Try this dynamic SQL query.
 declare @i int = 1;
 declare @count int = 0;
 declare @cols varchar(max) = '';
 declare @select varchar(max) = 'select ';
 declare @join varchar(max);
 declare @where varchar(max);
 declare @query varchar(max);

 declare @range varchar(100);
 declare @prevrange varchar(100);
 declare @rangeid varchar(100);

 select @count =count(distinct RangeSetID) from [Range];

 while @count > 0
 begin

     set @range = 'Range' + cast(@i as varchar(max));
     set @rangeid = 'RangeID' + cast(@i as varchar(max));

     set @cols = @cols + @rangeid + ', ';
     set @select = @select + @range + '.RangeID as '+@rangeid + ', ';

      if @i = 1
        begin
            set @join = ' from [Range] as ' + @range;
            set @where = 'where ' + @range + '.RangeSetID <> ';
        end
      else
        begin
            set @prevrange = 'Range' + cast((@i - 1) as varchar(max));
            set @join = @join + ' inner join [Range] as ' + @range + ' on (' + @prevrange + '.RangeID <= ' + @range + '.RangeID)';
            if(@count = 1)
                set @where = @where + @range+ '.RangeSetID';
            else
                set @where = @where + @range+ '.RangeSetID and '+ @range+ '.RangeSetID <> ';
        end

     set @i = @i + 1;
     set @count = @count - 1;
 end

 set @query = '
;WITH CTE
AS
  (
  SELECT * FROM (
  SELECT ROW_NUMBER() over (order by '+ SUBSTRING(@cols, 0, LEN(@cols)) + ') as ''RateID'', '+ SUBSTRING(@cols, 0, LEN(@cols)) +'  FROM
  (
    ' + SUBSTRING(@select, 0, LEN(@select)) + char(13) + @join + char(13) + @where + '
  ) as A) T
  UNPIVOT ( RangeID FOR N IN ('+(SUBSTRING(@cols, 0, LEN(@cols))) +' ))P
  )
 SELECT RateID, RangeID
 FROM CTE
 ';

 exec (@query);

A: For the sake of simplicity, RangeSetID is assumed to start from 1 and increase by 1 (no gaps between RangeSetID's).
Create a recursive function
create function dbo.Permutation(@n as int) returns @tbl table (RateID int,RangeID int)
as
begin
declare @Temp1 table (RateID int identity, RangeID int)
insert @Temp1 select RangeID from tbl where RangeSetID = @n
if @n = (select max(RangeSetID) from tbl)
    insert @tbl select * from @Temp1
else
    begin
        declare @Temp2 table  (RateID int, RangeID int)
        insert @Temp2 select * from dbo.Permutation(@n+1)
        declare @count int
        select @count = count(*) from @Temp1
        insert @tbl select (a.RateID - 1) * @count + b.RateID, a.RangeID
        from @Temp2 a cross join @Temp1 b
        insert @tbl select (a.RateID - 1) * @count + b.RateID, b.RangeID
        from (select distinct RateID from @Temp2) a cross join @Temp1 b
    end
return
end

Then issue the following statement
select * from dbo.Permutation(1)


text:
Q: compare jquery datepicker with date in database in asp.net I am newbie. I am working on asp.net website. I have added datepicker and it works fine. Now I want to get that date and compare it with date in my database. But I have no idea of how to do it. I also goggled but couldn't find any solution.
    <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="reserve" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
 <input type="text" id="popupDatepicker"  />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

           <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

</asp:Content>

A: Use DateTime.Compare(Date1, Date2) in code behind.
it'll give you differnce between the datetimes. Is this what you looking for


text:
Q: Automatically open applications at start up in Xubuntu 14.04 LTS I have ubuntu 14.04 LTS installed on my pi 2 with Xubuntu as my GUI and I am trying to figure out how to start application automatically after login. I have tried several different methods (listed below) and non have worked.
I am trying to start Xastir and Direwolf for now and plan on doing more in the future.
The first thing I tried was adding X-GNOME-Autostart-enabled=true at the bottom of my direwolf.desktop and xastir.desktop files using nano. direwolf.desktop and xastir.desktop are short scripts that launch the two programs from the desktop. Modifying these files yielded no success.
For my second attempt, I typed gnome-session-properties into terminal which opened the startup application program. I then clicked "add" once for direwolf and once for xastir. From here I entered in the applications' respective names into the "name" space and entered lxterm-hold-title "Dire Wolf" -bg white -e "/usr/local/bin/direwolf" in the command section for direwolf and gnome-terminal -t Xastir_Terminal --geometry=160x48 -x for xastir. I pulled direwolf's command from the Exec= part of the direwolf.desktop file. The Xastir command was pulled from the Exec= from here. On reboot, neither application opens.
What am I doing wrong, and how can I open more applications automatically at startup in the future? Thank you

A: Did you try it this way ?

Add Application to startup

*

*Open 'Settings Manager'

*Select 'Session and Startup'

*On the 'Application Autostart' click on the 'Add' button


text:
Q: How to add in a Count in the sub Query I have to count in the sub query. I want to add this to the subquery.
I am getting a fail when I add this line to the sub query:
   SELECT COUNT(DISTINCT v.Department_descr), v.Patient_Number, b.patient_name FROM vwGenVouchInfo v) as pat_dept

SELECT *
FROM vwGenVouchInfo v
WHERE v.Patient_Number=b.Patient_Number
  AND v.Voucher_Primary_Diagnosis_Code  IN ('Z00.129', 'Z00.00') )
ORDER BY voucher_primary_diagnosis_code

I want to get a result that will have the patient which department they went to the most times. I am not sure how to add this in. I want pat_dept to hold the dept the patient went to the most times besides the dental dept.
SELECT distinct
    a.voucher_primary_diagnosis_code,
   a.Patient_Number
,   b.Patient_Name, b.patient_home_phone, patient_age
FROM vwGenVouchInfo a
LEFT JOIN vwGenPatInfo b ON a.Patient_Number=b.Patient_Number
WHERE
    a.Department_Descr = 'Dental'
and a.Voucher_Service_Date >= '2015-01-01'
AND NOT EXISTS (
    -- This subquery looks at other vouchers of the same patient.

    --
    SELECT *
    FROM vwGenVouchInfo v
    WHERE v.Patient_Number=b.Patient_Number
      AND v.Voucher_Primary_Diagnosis_Code  IN ('Z00.129', 'Z00.00') )
ORDER BY voucher_primary_diagnosis_code

A: If you need this in the subquery, you will have to put all the necessary columns one by one along with the count and then group by the same columns.


text:
Q: PHP $_GET with Ajax/Jquery Request I am trying to set a variable $id=$_GET["categoryID"]. I cannot get it to work. I believe it has to do with the the Ajax request. But I don't know how I have to format it so that it will work in conjunction with that request. I need the variable for a mysql query. Any help is greatly appreciated. This is over my head and have been struggling with it for days. I have tried both GET and POST. Thanks.
I have distilled the page down to this...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test $_GET</title>

<?php
        if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

        $id = $_GET["categoryID"];
        //$id=3;
        }
?>
  print_r($_GET) = <?php print_r($_GET); ?>

  print_r($id) = <?php print_r($id); ?>

Here is the resulting page....
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test $_GET</title>

          print_r($_GET) = Array
(
    [categoryID] => 1001
)

      print_r($id) =

Here is the whole page....
<?php
if (@$_REQUEST['ajax']) {
    $link = $nm33;
    if ($link == false)
        trigger_error('Connect failed - ' . mysql_error(), E_USER_ERROR);
    $connected = mysql_select_db('nm', $link);
    if ($connected) {

    //How do I set $id = $_GET["categoryID"] It fails to set the variable.

        $id =$_GET["categoryID"];
    //  $id=1;
    // It will work as $id=1

        $results = mysql_query('select * from selectMenu where categoryID= \'' . $id . '\' AND category="' . strtolower(mysql_real_escape_string(strip_tags($_REQUEST['category']))) . '"');

    //////////

        $json = array();
        while (is_resource($results) && $row = mysql_fetch_object($results)) {
            //$json[] = '{"id" : "' . $row->id . '", "label" : "' . $row->label . '"}';
            $json[] = '"' . $row->label . '"';
        }
        echo '[' . implode(',', $json) . ']';
        die(); // filthy exit, but does fine for our example.
    } else {
        user_error("Failed to select the database");
    }
}
?>

<link href="selectMenu.css" rel="stylesheet" type="text/css" />
<form action="performance-models.php" method="get">
  <select name="category" class="dropdown" id="categorySelect">
    <option selected="selected">Select Your Vehicle</option>
    <?php do { ?>
    <option> <?php echo $row_rsMake['make']; ?></option>
    <?php } while ($row_rsMake = mysql_fetch_assoc($rsMake)); ?>
  </select>
  <select name="model" class="dropdown" id="elementSelect">
    <option selected="selected">Select Model</option>
    <option>[none selected]</option>
  </select>
  <select name="appYear" class="dropdown" id="attributeSelect" >
    <option selected="selected"> </option>
    <option>[none selected]</option>
  </select>
  <input  type="submit" value="Go">
</form>

  print_r($_GET) = <?php print_r($_GET); ?>

  print_r($_REQUEST) = <?php print_r($_REQUEST); ?>

  echo $_REQUEST['categoryID']  <?php  echo $_REQUEST['categoryID'];?>

Here is select-chain.js
(function ($) {
    $.fn.selectChain = function (options) {
        var defaults = {
            key: "id",
            value: "label"
        };

                var settings = $.extend({}, defaults, options);

        if (!(settings.target instanceof $)) settings.target = $(settings.target);

        return this.each(function () {
            var $$ = $(this);

            $$.change(function () {
                var data = null;
                if (typeof settings.data == 'string') {
                    data = settings.data + '&' + this.name + '=' + $$.val();
                } else if (typeof settings.data == 'object') {
                    data = settings.data;
                    data['category'] = $$.val();
                    data['model'] = $$.val();
                    data['year'] = $$.val();
                }

                settings.target.empty();

                $.ajax({
                    url: settings.url,
                    data: data,
                    type: (settings.type || 'get'),
                    dataType: 'json',
                    success: function (j) {
                        var options = [], i = 0, o = null;

                        for (i = 0; i < j.length; i++) {
                            // required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
                            o = document.createElement("OPTION");
                            o.value = typeof j[i] == 'object' ? j[i][settings.key] : j[i];
                            o.text = typeof j[i] == 'object' ? j[i][settings.value] : j[i];
                            settings.target.get(0).options[i] = o;
                        }

            // hand control back to browser for a moment
            setTimeout(function () {
                settings.target
                                .find('option:first')
                                .attr('selected', 'selected')
                                .parent('select')
                                .trigger('change');
            }, 0);
                    },
                    error: function (xhr, desc, er) {
                        // add whatever debug you want here.
            alert("an error occurred here");
                    }
                });
            });
        });
    };
})(jQuery);

A: A $_GET parameter is passed in the URL so for this;

http://www.google.com/?q=search

The parameter $_GET['q'] would be equal to 'search'
So when you perform your AJAX request you need to specify the parameters in the URL.
EDIT:
Try getting rid of your HTTP_X_REQUESTED_WITH statements. The request is probably safe enough without those kind of checks. Just simplify it to:
if ( isset( $_GET["categoryID"] ) ) {
  $id = $_GET["categoryID"];
}

A: There is no need for:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')

You can just use:
$id = isset($_GET["categoryID"]) ? intval($_GET["categoryID"]) : 0;

Which is the same as (but shorter...):
if (isset($_GET["categoryID"]))
{
  $id =  intval($_GET["categoryID"]);
}
else
{
  $id =  0;
}

If you want to check if a request was made via ajax, you would have to rewrite your script as the whole header section would not be needed. Instead you could call this script from your page, set a variable in the page itself and if that variable is not set in the script, it's an ajax call. Obviously this is just a simple example.
Edit: The plugin does not mention what the default type of the request is, but that could very well be POST so you could try to add type: "post" to the options of selectChain.
And to make sure that your response is well-formed json (when you get there...) I would also recommend you use json_encode, so:
    echo json_encode($json);
    die(); // filthy exit, but does fine for our example.

Edit 2: I just noticed another problem: Nowhere is the categoryID being added to the data section in the ajax:

*

*You are requesting / posting to (???) : select-menu.php (notice, no query string!)

*The data you are sending is: { ajax: true, anotherval: "anotherAction" } or { ajax: true}
So there is no way that categoryID is ever going to show up in select-menu.php.
The most logical thing to do, would be to add the selected category to the data section:
data: { "ajax": true, "anotherval": "anotherAction", "categoryID": cat }

and:
data: { "ajax": true, "categoryID": cat }

A: With jQuery you can use jQuery.get() or add a type='GET' parameter to jQuery.ajax(). Some example:
jQuery(function($) {
    $.ajax({
        url : 'your-page.php',
        type : 'GET',
        data : {
            'paramName' => 'paramValue',
            'foo' => 'bar'
        },
        success : function(data) {
             // do something in the callback function
        }
    });
});

A: You need to pass the value in the jQuery.get():
$.get('yourphppage.php', { categoryID : 1234 }, function(data) {
    alert(data);
});

In your php just echo right back your cateogryId to see if it is working
<?php echo $_GET['categorID'] ?>


text:
Q: Mode of a dataset having distinct numbers I am actually a bit confused... about the definition of a mode.

According to the definition I read, it came to my notice that the number with highest frequency has to be a mode for a given data set, but then what if I have all the numbers as distinct... In that scenario we won't have a particular number having a frequency more than other elements in the data set...
  Now if I consider a case when we have 2 numbers in a dataset with same max number of occurrences like:
  $$2,3,4,5,3,2$$
  Here 2, 3 both happen to have same maximum frequency and thus we say there are 2 modes...
  The above is stated similar in case we have 3 modes or multi modes ...
  So if there are all distinct numbers then we would have each number having the same maximum frequency as 1 ..so we can say all the numbers are modes...for that dataset...But then I have seen on some websites claiming that such data sets have  "NO MODE".

So again my thought process is contradicting...what claims I am seeing on websites...
So plz some one help me get this basic concept resolved ...

A: We have three cases: unimodal, multimodal and no mode
$\underline{\textrm{unimodal}}$: A statistical distribution of values with one peak.
Example: $5667$. The mode is obviously $6$.
$\underline{\textrm{multimodal}}$: A statistical distribution of values with multiple peaks.
Example: $55677$. The frequencies of 5 and 7 are 2. And we have a lower frequency of 6, which is 1.  Thus the modes are $5$ and $7$.
$\underline{\textrm{no mode}}$: A statistical distribution of values with no peaks. All values have the same frequency.
Example: $556677$


text:
Q: Wrong values with np.mean()? I'm quite new to programming (in Python) and so I don't understand what is going on here. I have an image (35x64) as a 3D-array and with np.mean(), I attempted to extract the mean of one color channel of one row:
print(np.mean(img[30][:][0]))

For comparison, I also wrote a for-loop to append the exact same values in a list and calculating the mean with that:
for i in range(64):
    img_list.append(img[30][i][0])
print(np.mean(img_list))

Now, for a strange reason, it gives different values:
First output: 117.1
Second output: 65.7

By looking at the list, I discovered that the second one is correct. Can somebody with more experience explain to me why this is exactly happening and how to fix that? I don't want to use the second, longer code chunk in my programs but am searching for a 1-line solution that gives a correct value.

A: There's a subtle difference between img[30][:][0] and img[30,:,0] (the one you were expecting).
Let's see with an example:
img = np.arange(35*64*3).reshape(35,64,3)
img[30][:][0]
# array([5760, 5761, 5762])
img[30,:,0]
# array([5760, 5763, ... 5946, 5949])

So you simply need to:
print(np.mean(img[30,:,0]))

(which is more efficient anyways).
Some details: in your original syntax, the [:] is actually just triggering a copy of the array:
xx = img[30]
yy = img[30][:]
print (xx is yy, xx.shape, yy.shape, np.all(xx==yy))
# False (64, 3) (64, 3) True # i.e. both array are equal

So when you take img[30][:][0], you're actually getting the 3 colors of the first pixel of row 30.


text:
Q: How can i randomize delay of moving object Recently i added that enemy shoots but unfortunately i cannot randomize delay of Shooting for every object.
Project 60 times in second  :

*

*update (all code here is connected to this part)

*draw

*sleep

Fragment of code :
Fragment of code.
    public void createNewEnemyBullet(){
    for(Enemy enemy: enemies){
        EnemyBullet enemyBullet = new EnemyBullet(getResources());
        randomShot = random.nextInt(60-40)+40;

        System.out.println("Randomowy shot :"+ randomShot);
        enemyBullet.x = (int) (((enemy.x+enemy.widthEnemy/2)-18)*screenRatioX);
        enemyBullet.y= enemy.y+20;

        enemyBullets.add(enemyBullet);
    }

    System.out.println("\n\n");
}

Screenshot of my result
enter image description here

A: Use Math.random(). It'll be your friend here. Compare (Math.random() <= epsilon) the output of random() with some number epsilon you want as your threshold for making an enemy shooting decision.
If enemyBullets is what the UI code uses to draw bullets, you may want to add a Thread.sleep(Math.random()) to add variable delay in adding them.

A: Solution for generating random delay of bullet is to change this delay when a enemy starship is shot.


text:
Q: how to redirect https requests to http I have a site on my machine (localy).
Users used to access it using both HTTP and HTTPS. Now there is a problem with HTTPS configuration.[ It is not working]
Is it possible to redirect HTTPS requests to the HTTP port temporarly?

A: in your .htaccess file paste this code:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


text:
Q: how to hide label in bottom tab navigator react navigation v5 im trying to hide the Label. and showLabel: false is not working.
import React, {useLayoutEffect} from 'react';
import {createStackNavigator} from '@react-navigation/stack';
import {useNavigation} from '@react-navigation/native';

import HomeTopTabNavigator from '../routes/home.top.tab';
import {NAVIGATOR} from '../constants/screen.constants';
import THEME from '../constants/theme.constants';
import Icon from '../components/atoms/Icon';

const HomeStack = createStackNavigator();

function HomeStackNavigator() {
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      showLabel: false,
      tabBarIcon: () => (
        <Icon
          type="MaterialCommunityIcons"
          name="home"
          size={24}
          color={THEME.PRIMARY}
        />
      ),
    });
  }, [navigation]);

  return (
    <HomeStack.Navigator
      screenOptions={{headerStyle: {elevation: 0, shadowOpacity: 0}}}>
      <HomeStack.Screen
        name={NAVIGATOR.HomeTopTab}
        component={HomeTopTabNavigator}
      />
    </HomeStack.Navigator>
  );
}

export default HomeStackNavigator;

A: For Tab bar pass like the ,
tabBarOptions={{
        showLabel: false,

}
}

A: If you use https://reactnavigation.org/docs/bottom-tab-navigator
please kindly check out this one instead
https://reactnavigation.org/docs/material-bottom-tab-navigator/
Something like
import React from 'react';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';

import FeedScreen from './Feed';
import AddScreen from './Add';
import ProfileScreen from './Profile';

const Tab = createMaterialBottomTabNavigator();

const MainScreen = () => {
  return (
    <Tab.Navigator labeled={false}>
      <Tab.Screen
        name='FeedTab'
        component={FeedScreen}
        options={{
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name='home' color={color} size={26} />
          ),
        }}

      />
      <Tab.Screen
        name='AddTab'
        component={AddScreen}
        options={{
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name='plus-box' color={color} size={26} />
          ),
        }}
      />
      <Tab.Screen
        name='ProfileTab'
        component={ProfileScreen}
        options={{
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons
              name='account-circle'
              color={color}
              size={26}
            />
          ),
        }}
      />
    </Tab.Navigator>
  );
};

export default MainScreen;


text:
Q: Transform DateTime into simple Date from mysql when rendering page in Rails I am developing a datatable in Ruby on Rails, but I don't understand how to translate mysql datetime into normal date notation within the datatable when rending the view.
Roughly, I have my table view that imports the columns.

    <table id="customer-grid" data-grid-name="Customers List" data-available-columns='[<%=raw(@grid_fields.map{|fieldcaption,fieldname| '"'<<fieldcaption<<'"'}.join(",") )%>]' data-column_scaling='<%=raw(@grid_fields_scaling.map{|fieldcaption,scale| scale}.join(",") )%>' >

                <% @grid_fields_visible.each do |fieldcaption,fieldname|%>
                    <%=fieldcaption%>
                <%end%>

The columns list is given by the controller of the page.
@grid_fields=@grid_service.get_grid_fields
@grid_fields_visible =@grid_service.get_grid_fields_visible

that brings to the actual list in the service folder.
def get_grid_fields
    return {
        "Company Name"      =>"name",
        "Contact Name"      =>"contact_name",
        "Address"           =>"address_1",
        "Post Code"         =>"postcode",
        "Telephone"         =>"tel",
        "Primary Email"     =>"email",
        "WWW"               =>"www",
        "Created by"        =>"created_by",
        "Date Created"      =>"created_at",
        "Modified by"       =>"modified_by",
        "Date modified"     =>"modified_at"
    }
end

The mysql connection is given by a module:
module CustomerLegacyShim extend ActiveSupport::Concern
  included do
    self.table_name = "tblcustomers"

    ...
    alias_attribute :created_by,       :tblCustomer_CreatedBy
    alias_attribute :created_at,       :tblCustomer_CreatedAt
    alias_attribute :modified_by,      :tblCustomer_ModifiedBy
    alias_attribute :modified_at,      :tblCustomer_ModifiedAt

    ...
  end
end

To go to the point, everything works great. The only problem is that I have a really incomprehensible DateTime, and I don't understand what to change to make it %d/%m/%Y within the table.
The fact is that I completely have no idea where to put .strftime() or .strptime(), as I can only give the "column name" to the datatable and I don't know how to change the format of the retrieved data.
Can anybody teach me?
Luca

A: You can use to_s(:db) to convert into a database friendly format.
Time.now.to_s(:db)

However, timezone specified in Rails because the time will be stored in UTC in the database. You'll need to specify that to do proper comparisons.
Time.now.to_s(:db)

A: You can simply use to_date to get a Date object.
time = Time.now
date = time.to_date

Then you can use strftime to get the output you need:
date.strftime('%a %d %b %Y')    #=> "Sun 04 Feb 2001"

Or in the format that you need:
date.strftime('%d/%m/%Y') #=> "02/06/2016"

Here is the doc for the Date class: link
And more info on strftime format: link
Now let say I have this in a controller:
@my_objects = MyObject.all

In the views you can do something like:

    Title
    Create at

  <% @my_objects.each do |0| %>

      <%= o.title%>
      <%= o.created_at.to_date.strftime('%d/%m/%Y') %>

  <% end %>

A: In the end I had to hard code the datatable column and create a dedicated function within the *.dataTable method in JS:
"columnDefs": [
    {
        "sClass": "date-long filterdaterangedatetime",
        "targets": getColumnIndexFromName('#sage-customers-grid',['Date Created','Date modified']),
        "mRender": function (data, type, full) {
            if (data != "") {
                var date = data.substring(0,10);
                var dateParts = date.split("-");
                var createDataFormat = dateParts[2] + "/" + dateParts[1] + "/" + dateParts[0];
                return createDataFormat;
            } else {
                return "";
            }
        }
    }
]


text:
Q: Getting a return value from Lambda python I'm trying to check if my lambda function is correctly working
rule_defs = {
'and': lambda r: (lambda d, r1, r2: match_rule(r1, d) and match_rule(r2, d),
                  [compile_rule(r[1]), compile_rule(r[2])])}

But when I try to run it

('and', 'a', 'a')

it just shows me something similiar of this
<function <lambda> at 0x023C68F0>, ['a', 'a']

Which as I understand is that i send in ['a'.'a'] into lambda d from which I would like a return value similar to True
Am I misunderstanding something basic?
EDIT:
The calling itself is not the problem but the return value being:

function  at 0x023C68F0>, ['a', 'a']

instead of a value (i.e. True) and I'm not sure if that is the fault of my calling or the function itself
The call is done with a "help function"
calling(input)
    return rule_defs[input[0]](input)

(Python 2.7.X)

A: Firstly, if you want your inner function to produce a tuple, you should also add another '(' after starting the inner lambda and close it just before.
Example -
rule_defs = {
'and': lambda r: (lambda d, r1, r2: (match_rule(r1, d) and match_rule(r2, d), [compile_rule(r[1]), compile_rule(r[2])]))}

Or if you were doing it correctly, and outer lambda intended to return a tuple of (lambda, list) , then to call the inner lambda use rule_defs['and'](<parameter>)[0](<parameters>)
When defining lambda within a lambda , you have to call first lambda with () and then again the second lambda with () .
So in your case , you would call your function with -
rule_defs['and'](r)(d, r1, r2)

Or you can assign it to a variable and then call that variable with the double paranthesis.
Example I tested with -
>>> rule_defs = { 'and': lambda r: (lambda d ,r1: print(d))}
>>> rule_defs['and'](1)(2,3)
2

A: You have to get your lamba expression and then call it:
l = rule_defs['and']
l(d, r1, r2)

Replace the arguments with the value of your choice, then you will get the return value of the lambda function.
You can also do it at once:
rule_defs['and'](d, r1, r2)

A: Here is your code:
rule_defs = { # define a dict
    'and': lambda r: ( # `lambda r` return a tuple: (lambda, list)
        lambda d, r1, r2: match_rule(r1, d) and match_rule(r2, d),
        [compile_rule(r[1]), compile_rule(r[2])]
    )
}

You should call your function by rule_defs['and'](r)[0](d, r1, r2)
In your case, it would be rule_defs['and'](r)[0]('and', 'a', 'a')
rule_defs['and'] will get the function object lambda r: (...)
rule_def['and'](r) will call the lambda r function, and get the returned tuple
rule_def['and'](r)[0] get the index(0) of the returned tuple, e.g. function object lambda d, r1, r2
rule_defs['and'](r)[0](d, r1, r2) will call the lambda d, r1, r2 function


text:
Q: Using HTTP Client to download a file from MVC causes "(System.AggregateException) One or more errors occurred" I have had this code in production for a very long time and this issue just started. Basically it is downloading a file from an MVC controller. These files are around 5 to 20 megabytes. And this is a PCL library running on iOS. Users are getting an error when they go to download the file from the server. I am assuming it is a timeout, but I am not 100% sure. We are unable to re-create this issue in house, but we see the errors in the logs AND users have reported this.
Anything I can do on the server side to improve this? Nothing has changed on the client, and it has become a pervasive issue for our customer base.
Server Code
    public virtual FileResult BuildDatabaseForSite(Guid organizationId, Guid siteId) {
        var basePath = RESTContext.Config.DBPath;
        var filePath = basePath + @"\" + fileId + ".db";
        byte[] existingDbBytes = null;

        using (new Impersonator(RESTContext.Config.VideoPathUsername, RESTContext.Config.VideoPathDomain,
            RESTContext.Config.VideoPathPassword)) {

            if (System.IO.File.Exists(filePath))
                existingDbBytes = System.IO.File.ReadAllBytes(filePath);
        }
        return File(existingDbBytes, "application/octet-stream", "CompassLocal.db");
    }

Client Code
       public void DownloadDatabase(Guid organizationId, Guid siteId) {
            Platform.FileSystem.DeleteFile(Paths.LocalDatabase);
            var url = string.Format("organizations/{0}/Sites/{1}/InitialDatabaseCompressed", organizationId, siteId);
            var webClient = new HttpClient();
            webClient.Timeout = new TimeSpan(0,0,5,0);
            webClient.DefaultRequestHeaders.Add("Authorization", authHeader);
            var stream = webClient.GetStreamAsync(url).Result;
            using (Stream file = File.OpenWrite(Paths.LocalDatabase)) {
                          stream.CopyTo(file);
            }
        }

Stack Trace
System.AggregateException: One or more errors occurred
  at System.Threading.Tasks.Task.Wait (Int32 millisecondsTimeout, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0
  at System.Threading.Tasks.Task.Wait () [0x00000] in <filename unknown>:0
  at System.Threading.Tasks.Task`1[TResult].get_Result () [0x00000] in <filename unknown>:0
  at DataFinch.Mobile.Core.Network.RemoteAPI.DownloadDatabase (Guid organizationId, Guid siteId) [0x00000] in <filename unknown>:0
  at DataFinch.Mobile.Core.Services.Registration.RegistrationService.RegisterDeviceAndDownloadDatabase (System.String username, System.String password, Guid siteId) [0x00000] in <filename unknown>:0

A: Obviously this is caused by a timeout - after all, the stack trace indicates that the exception happened in Task.Wait(...) - which is internally called by the Task's Result property further down the call stack.
Because this happens on the client side, there's nothing that you can do on the server side. You could try and make the server somehow faster. But I doubt that this would really help, because there still will be limited bandwidth available for the mobile clients - and what's more: this is depending on each single customer's data plan.
Anyway, and because you can (and you will) always have customers with very poor bandwith, the file sizes are generally way too large for targeting mobile clients. All you can do is to schedule a refactoring of the download logic for the next version of your app, splitting your downloads into much smaller chunks and and make your client code handle these kinds of problems as good as possible...
Also, blocking the entire thread, even if it is a working thread, while waiting for such a large download is a bad idea (especially on a mobile client where you have no indication of the available bandwidth). This causes the thread to be unresponsive for a very long time. You should consider changing this logic as well.