text:
Q: CUDA reduce non-contiguous sub-arrays I am writing a function for a library which accepts a large array (in GPU memory) of a power-of-2 number of elements. This function must sum non-contiguous sub-arrays (of equal length, also a power-of-2), to produce a smaller (or rarely, equally sized) array. This is a GPU version of the OpenMP function described here.
For example,
in[8] = { ... }
out = { in[0]+in[2],  in[1]+in[3],  in[4]+in[6],  in[5]+in[7] }

The elements of the reduced sub-arrays are determined by a user-given list of bit indices, bitInds. They inform how the index (imagined as a bitstring) of an elemement of in is mapped to an index of out.
For example, if
bits = { 0, 2 }

then in index 0 = 000 maps to out[0], and in index 4 = 100 maps to out[2].
The length of bits can range from 1 to log2(length(in)). The length of out is pow(2, length(bits)). This means out can be just as large as in, or half as large, or a quarter as large, etc.
Preparing the device memory for this function, and performing well structured reductions within CUDA kernels seems challenging, and I'm unsure how to start. Since in is gauranteed very large, it is important threads access in locally and sequentially. How can I perform pow(2,length(bits)) reductions of possibly non-contiguous sub-arrays of in efficiently?

A: I tried three implementations and compared their performance.

*

*A: As per @RobertCrovella's example, using atomics on per-block exclusive global memory, and reducing between blocks thereafter.

*B: Having each thread directly atomically write to global memory.

*C: Having threads write to block-local shared memory, and finally atomically reducing them to global memory.

The best solution in both performance and size constraints was surprisingly the simplest, B. I present pseudocode and describe the trade-offs for these solutions in order of their complexity.
B
This method has each thread atomically write to global memory, directly to the final output. Besides fitting out and in in global memory, it imposes no additional constraints on their sizes.
__global__ void myfunc_kernel(double* in, inLen, double* out, ...) {

    // each thread handles one element of 'in'
    int inInd = blockIdx.x*blockDim.x + threadIdx.x;
    if (inInd >= inLen)
        return;

    // determine 'outInd' from other args
    int outInd = ...

    // atomically add directly to out global memory (vs all threads)
    atomicAdd(&out[outInd], in[inInd]);
}

void myfunc(double* in, int inLen, double* out,  ...) {

    // copy unspecified additional args into device memory (shared, if fits)
    double d_in = ...

    // create global memory for final output (initialised to zero)
    double d_out = ...
    cudaMemset(d_out, 0, ...);

    // allocate one thread per element of 'in'
    int numThreadsPerBlock = 128;
    int numBlocks = ceil(inLen / (double) numThreadsPerBlock);

    myfunc_kernel<<numBlocks, numThreadsPerBlock>>(d_in, inLen, d_out, ...);

    // copy output to host, and clean up
    cudaMemcpy(out, d_out, ...);
    cudaFree(...);
}

C
This method assigns each block shared memory, into which threads in a block locally reduce, via atomics. Thereafter, the shared memory is reduced between blocks into the output global memory, via atomics. Having to fit a local out into shared memory constrains outLen to at most (e.g.) 4096 (depending on the compute capability).
__global__ void myfunc_kernel(double* in, int inLen, double* out, ...) {

    // each thread handles one element of 'in'
    int inInd = blockIdx.x*blockDim.x + threadIdx.x;
    if (inInd >= inLen)
        return;

    // each block has a local copy of 'out', in shared memory
    extern __shared__ double outBlock[];

    // efficiently initialise shared memory to zero
    // (looped in case fewer threads than outLen)
    for (int i=threadIdx.x; i<outLen; i+=blockDim.x)
        outBlock[i] = 0;
    __syncthreads();

    // determine 'outInd' from other args
    int outInd = ...

    // atomically contribute thread's 'in' value to block shared memory
    // (vs other threads in block)
    atomicAdd(&outBlock[outInd], in[inInd]);
    __syncthreads();

    // keep one (or fewer) thread(s) per output element alive in each block
    if (threadIdx.x >= outLen)
        return;

    // remaining threads atomically reduced shared memory into global
    // (looped in-case fewer threads than 'outLen')
    for (int i=threadIdx.x; i<outLen; i+=blockDim.x)
        // (vs all surviving threads)
        atomicAdd(&out[i], outBlock[i]);

    /* This final reduction may be possible in parallel/tiers,
     * though documentation & examples about reducing shared memory
     * between blocks is disappointingly scarce
     */
}

void myFunc(double* in, int inLen, double* out, int outLen, ...) {

    // if 'out' cannot fit in each block's shared memory, error and quit
    if (outLen > 4096)
        ...

    // copy unspecified additional args into device memory
    double d_in = ...

    // create global memory for final output (initialised to zero)
    double d_out = ...
    cudaMemset(d_out, 0, ...);

    // allocate one thread per element of 'in'
    int numThreadsPerBlock = 128;
    int numBlocks = ceil(inLen / (double) numThreadsPerBlock);

    // allocate shared memory to fit 'out' in each block
    size_t mem = outLen * sizeof(double);
    myfunc_kernel<<numBlocks, numThreadsPerBlock, mem>>(d_in, inLen, d_out, ...);

    // copy output to host, and clean up
    cudaMemcpy(out, d_out, ...);
    cudaFree(...);
}

Note that all reductions were ultimately performed atomically. This should not be necessary, since after the shared memory is finalised, the reduction into global memory has strict structure. Yet, I am unable to find documentation or a single demonstration online of how to collectively reduce shared memory arrays into global memory.
A
This method uses the same paradigm as this histogram example. It creates #numBlocks copies of out in global memory, so that each block writes to exclusive memory. Threads within a block write atomically to their block's global memory partition. Thereafter, a second kernel reduces these partitions into the final out array. This significantly constrains outLen, to be smaller than deviceGlobalMem/numBlocks.
__global__ void myfunc_populate_kernel(double* in, int inLen, double* outs, int outLen, ...) {

    // each thread handles one element of 'in'
    int inInd = blockIdx.x*blockDim.x + threadIdx.x;
    if (inInd >= inLen)
        return;

    // determine 'outInd' from other args
    int outInd = ...

    // map to this block's exclusive subarray in global memory
    int blockOutInd = blockIdx.x*outLen + outInd;

    // atomically contribute thread's 'in' value to block's global memory
    // (vs threads in same block)
    atomicAdd(&outs[outInd], in[inInd]);
}

__global__ void myfunc_reduce_kernel(double* out, double* outs, int outLen, int numOuts) {

    // each thread handles one element of 'out'
    int outInd = blockIdx.x*blockDim.x + threadIdx.x;
    if (outInd >= outLen)
        return;

    // and determines it by reducing previous per-block partitions
    double total = 0;
    for (int n=0; n<numOuts; n++)
        total += outs[outInd + n*outLen];

    out[outInd] = total;
}

void myfunc(double* in, int inLen, double* outs, int outLen, ...) {

    int numThreadsPerBlock = 128;
    int numPopBlocks = ceil(inLen / (double) numThreadsPerBlock);

    // if #numPopBlocks copies of 'out' cannot fit in global memory, error and exit
    if (outLen * numPopBlocks > ...)
        ...

    // copy unspecified additional args into device memory (shared, if fits)
    double d_in = ...

    // create a working 'out' for each block, in global memory (init to zero)
    size_t mem = outLen * numPopBlocks * sizeof(double);
    double d_outs = ...
    cudaMalloc(&d_outs, mem);
    cudaMemset(d_out, 0, mem);

    // populate each blocks partition of global memory 'd_outs'
    myfunc_populate_kernel<<numPopBlocks, numThreadsPerBlock>>(d_in, inLen, d_outs, outLen, ...);

    // create global memory for final output
    double d_out = ...

    // reduce each blocks partition of global memory into output 'd_out'
    int numReduceBlocks = ceil(outLen / (double) numThreadsPerBlock);
    myfunc_reduce_kernel<<numReduceBlocks, numThreadsPerBlock>>(d_out, d_outs, outLen, numPopBolocks);

    //copy output to host, and clean up
    cudaMemcpy(out, d_out, ...);
    cudaFree(...);
}

Comparison
I tested these methods with a Quadro P6000 (24GB, 6.1 CC), with inLen = 2^5, 2^10, 2^15, 2^20, 2^25 and (for all values) outLen = m2^5, 2^10, 2^15 (outLen <= inLen). Here is a table of the runtimes:
╔══════════╦═════════╦══════════╦══════════╦══════════╗
║  inLen   ║ outLen  ║  A       ║  B       ║  C       ║
╠══════════╬═════════╬══════════╬══════════╬══════════╣
║       32 ║      32 ║ 0.000067 ║ 0.000071 ║ 0.000039 ║
║     1024 ║      32 ║ 0.000244 ║ 0.000044 ║ 0.000071 ║
║     1024 ║    1024 ║ 0.000265 ║ 0.000043 ║ 0.000064 ║
║    32768 ║      32 ║ 0.000290 ║ 0.000077 ║ 0.000080 ║
║    32768 ║    1024 ║ 0.000287 ║ 0.000059 ║ 0.000096 ║
║    32768 ║   32768 ║ 0.000762 ║ 0.000111 ║ N/A      ║
║  1048576 ║      32 ║ 0.000984 ║ 0.000793 ║ 0.000254 ║
║  1048576 ║    1024 ║ 0.001381 ║ 0.000343 ║ 0.002302 ║
║  1048576 ║   32768 ║ 0.017547 ║ 0.000899 ║ N/A      ║
║  1048576 ║ 1048576 ║ N/A      ║ 0.006092 ║ N/A      ║
║ 33554432 ║      32 ║ 0.021068 ║ 0.022684 ║ 0.008079 ║
║ 33554432 ║    1024 ║ 0.032839 ║ 0.008190 ║ 0.014071 ║
║ 33554432 ║   32768 ║ 0.013734 ║ 0.011915 ║ N/A      ║
╚══════════╩═════════╩══════════╩══════════╩══════════╝

Even despite having fewer limitations, method B is a clear winner, as more clearly illustrated here:
╔══════════════╦══════╦═════╗
║ outLen/inLen ║ A/B  ║ C/B ║
╠══════════════╬══════╬═════╣
║            1 ║ 0.9  ║ 0.5 ║
║           32 ║ 5.5  ║ 1.6 ║
║            1 ║ 6.2  ║ 1.5 ║
║         1024 ║ 3.8  ║ 1.0 ║
║           32 ║ 4.9  ║ 1.6 ║
║            1 ║ 6.9  ║     ║
║        32768 ║ 1.2  ║ 0.3 ║
║         1024 ║ 4.0  ║ 6.7 ║
║           32 ║ 19.5 ║     ║
║            1 ║      ║     ║
║      1048576 ║ 0.9  ║ 0.4 ║
║        32768 ║ 4.0  ║ 1.7 ║
║         1024 ║ 1.2  ║     ║
╚══════════════╩══════╩═════╝

Pitfalls
It is difficult to be polite about the state of CUDA documentation and the examples online. So I won't comment, but offer up these warnings of pitfalls to the puzzled reader:

*

*Beware that while shared memory seems to be initialised to zero at the first execution of the kernel, it is not re-initialised in subsequent executions. Hence you must re-initialise manually within a kernel (there is no convenient CUDA function).

*atomicAdd is missing an overload for double types. The doc claims this is true only for compute capabilities < 60, but my code would not compile with my 62 CC GPU with no manual overload. Furthermore, the doc's code-snippet of #if __CUDA_ARCH__ < 600 is wrong, since newer arch precompilers don't define __CUDA_ARCH__. View a correct macro here

*Beware that the popular parallel reduction paradigms you view online will assume all data is in the global memory, or in a single block's shared memory. Reducing shared memory into a global structure seems esoteric.

Determining bitInd
For the interested reader to better understand the out access pattern, here is how bitInd is determined from each thread, of which (between all blocks combined) there are inLen. Note the actual index types are long long int, since inLen and outLen can both be as big as 2^30 = 1073741824
__global__ void myfunc_kernel(
    double* in, int inLen, double* out, int* bitInds, int numBits
) {

    long long int inInd = blockIdx.x*blockDim.x + threadIdx.x;
    if (inInd >= inLen)
        return;

    // determine the number encoded by bits {bitInds} of inInd
    long long int outInd = 0;
    for (int b=0; b<numBits; b++) {
        int bit = (inInd >> bitInds[b]) & 1;
        outInd += bit * (1LL << b);
    }

    ...
}

For some possible inputs of bitInds, the access pattern is simple. For example:

*

*If bitInds = {0, 1, ..., n-1} (contiguous increasing from 0), then outInd = inInd % 2^n, and our kernel is (sub-optimally) performing reductions of contiguous partitions of in.

*If bitInds = {n, n+1, n+2, ...,  log2(inLen)-1}, then outInd = floor(inInd / 2^(log2(inLen) - n)), or simply outInd = floor(inInd 2^n / inLen).

However, if bitInds is an arbitrarily ordered subset of indices {0, ..., log2(inLen)-1}, then outInd must be determined from each bit as performed above.


text:
Q: No owin.Environment item was found in the context in asp mvc This is my code for register in identity :
[AllowAnonymous]
public ActionResult Register()
{
    var roles = db.Roles.Select(r => new { RoleID = r.Id, RoleName = r.Name }).ToList();
    ViewBag.Roles = new SelectList(roles, "RoleID", "RoleName");

    return View();
}

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase UserPhoto)
{
    if (ModelState.IsValid)
    {
        model.DateRegister = DateTime.Now;
        var user = new ApplicationUser
        {
            UserName = model.UserName,
            Name = model.Name,
            Family = model.Family,
            PhoneNumber = model.PhoneNumber,
            Gender = model.Gender,
            BirthDay = model.BirthDay,
            DateRegister = model.DateRegister,
            IsActive = false,
            Email = model.Email
        };

        if (UserPhoto != null)
        {
            UserPhoto = Request.Files[0];
            var ext = System.IO.Path.GetExtension(UserPhoto.FileName);
            if (ext == ".jpeg" || ext == ".jpg" || ext == ".png")
            {

                string filename = model.PhoneNumber + ext;
                UserPhoto.SaveAs(Server.MapPath(@"~/Image/" + filename));
                user.UserPhoto = filename;
            }
        }

        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {

            await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
            await UserManager.AddToRoleAsync(user.Id,model.UserRoles);
            return RedirectToAction("Index", "Home");
        }
        AddErrors(result);
    }

    return View(model);
}

WebConf :
<appSettings>
  <add key="webpages:Version" value="3.0.0.0" />
  <add key="webpages:Enabled" value="false" />
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  <add key="owin:AutomaticAppStartup" value="false" />
  <add key="owin:AppStartup" value="Identity_Work.Startup" />
</appSettings>

But I get this error:

What is the problem and how can I fix it?

A: Based on previous conversation you confirmed that
[assembly: OwinStartup(typeof(Identity_Work.Startup))]

already exists in Startup.cs.
Which means that there is no longer a need for owin:AppStartup in the web.config.
Therefore your appSettings should look like this.
<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="owin:AutomaticAppStartup" value="true" /> <!-- This should be true -->
</appSettings>

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL Very Slow for REALLY Simple Operations Something appears to be wrong with my MySQL even with very, very simple operations on almost empty (~100) tables
E.g. DROP TABLE IF EXISTS hookup_gender takes 10+ seconds
mysql> show processlist;
+----+---------------+---------------------+---------------+---------+------+----------------------+--------------------------------------+
| Id | User          | Host                | db            | Command | Time | State                | Info                                 |
+----+---------------+---------------------+---------------+---------+------+----------------------+--------------------------------------+
|  2 | pegpro_hookup | 130.88.149.86:51593 | pegpro_hookup | Sleep   |   43 |                      | NULL                                 |
| 92 | root          | localhost           | NULL          | Query   |    0 | NULL                 | show processlist                     |
| 93 | pegpro_hookup | localhost           | pegpro_hookup | Query   |    7 | checking permissions | DROP TABLE IF EXISTS `hookup_gender` |
+----+---------------+---------------------+---------------+---------+------+----------------------+--------------------------------------+

Whereas a basic table create takes 30+ seconds
mysql> show processlist;
+----+---------------+---------------------+---------------+---------+------+----------------+------------------------------------------------------------------------------------------------------+
| Id | User          | Host                | db            | Command | Time | State          | Info                                                                                |
+----+---------------+---------------------+---------------+---------+------+----------------+------------------------------------------------------------------------------------------------------+
|  2 | pegpro_hookup | 130.88.149.86:51593 | pegpro_hookup | Sleep   |   24 |                | NULL                                                                                |
| 92 | root          | localhost           | NULL          | Query   |    0 | NULL           | show processlist                                                                                |
| 93 | pegpro_hookup | localhost           | pegpro_hookup | Query   |   25 | creating table | CREATE TABLE `hookup_message`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `related_post_id` INTEGER NO |
+----+---------------+---------------------+---------------+---------+------+----------------+------------------------------------------------------------------------------------------------------+

What might be causing this slowdown?
What further information can I provide?
Thanks for your time,

Info:
top - 02:44:33 up  1:15,  2 users,  load average: 1.59, 1.57, 1.05
Tasks:  86 total,   1 running,  85 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:   2097152k total,   398904k used,  1698248k free,        0k buffers
Swap:        0k total,        0k used,        0k free,        0k cached

Error log
root@tent:~$ tail -f /var/lib/mysql/mysql-bin.err
111107  1:29:00 [Note] Event Scheduler: Purging the queue. 0 events
111107  1:29:01  InnoDB: Starting shutdown...
111107 01:29:41 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
111107  1:29:41 [Note] Plugin 'FEDERATED' is disabled.
111107  1:29:41  InnoDB: Initializing buffer pool, size = 8.0M
111107  1:29:41  InnoDB: Completed initialization of buffer pool
111107  1:29:55  InnoDB: Started; log sequence number 0 2618946
111107  1:30:06 [Note] Event Scheduler: Loaded 0 events
111107  1:30:06 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.1.59-log'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Community Server (GPL)

iostat:
root@tent:~$ iostat
Linux 2.6.18-274.3.1.el5.028stab094.3   07/11/11

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           0.15    0.05    0.08    2.45    0.00   97.28

Device:            tps   Blk_read/s   Blk_wrtn/s   Blk_read   Blk_wrtn

Thanks for your time,

A: It appears you are using innodb. During a table drop, the innodb engine locks the entire buffer pool and wipes out any references to the tables, and then drops the tables. This takes a fair bit of time when you have a large buffer pool.
One option is to switch to using the Percona builds of mysql. They have a specific feature to help this out
http://www.percona.com/docs/wiki/percona-server:features:misc_system_variables

When innodb_file_per_table is set to 1, doing a DROP TABLE can take a
long time on servers with a large buffer pool, even on an empty InnoDB
table. This is because InnoDB has to scan through the buffer pool to
purge pages that belong to the corresponding tablespace. Furthermore,
no other queries can start while that scan is in progress.
When innodb_lazy_drop_table is ON, XtraDB optimizes that process by only marking the pages corresponding to the tablespace being
deleted. It defers the actual work of evicting those pages until it
needs to find some free pages in the buffer pool.
When innodb_lazy_drop_table is OFF, the usual behavior for dropping tables is in effect.


text:
Q: What is an interior of a domain of a function? When explaining the continuity of convex functions, it says

Let $f: E \rightarrow (-\infty, +\infty)$ be convex. Then $f$ is
   continuous on the interior of its domain and, in fact, for any $x \in
 int\ dom(f)$, there exists an open neighborhood $U$ of $x$ and $L>0$
   such that for any $u,v\in U$, $f(u) - f(v) \le L ||u-v||_2$

Initially I thought $int\ dom(f)$ was the epigraph of $f$ but an epigraph isn't exactly a $dom(f)$. In addition, an interior point of a set is a point where it has an open neighborhood that is also in a set. But what is interior of a domain?

A: The domain of $f$ is a particular set, and the interior of the domain of $f$ is just the interior of that set.  The rest of this answer explains what the interior of a set is, for completeness.
A picture from Wikipedia:

Let $S \subset \mathbb R^n$.  Then the interior of $S$ is the set of all points $x \in S$ such that $B(x,\epsilon) \subset S$ for some $\epsilon > 0$.  Here $B(x,\epsilon)$ is the ball of radius $\epsilon$ at $x$:
$$
B(x,\epsilon) = \{ y \in \mathbb R^n \mid \| x - y \| < \epsilon \}.
$$
So, in other words, $x$ is in the interior of $S$ if and only if there exists a number $\epsilon > 0$ such that all points within $\epsilon$ of $x$ also belong to $S$.


text:
Q: How does stealth work in Grand Theft Auto Online? I have a level 41 character in GTA online with 100 in Shooting and something low ("Clumsy") in Stealth.
When playing job missions I like to soften up the AI opposition by sniping them from a good vantage point as far away as possible. This means I'm often on top of a building/ crane/ boat/ hill and hiding behind a billboard/ low wall/ box/ rock at the edge of sniper visibility - in the middle of the night.
I'm using the standard sniper with suppressor, advanced scope etc. At the moment I'm lucky to get more than two (head)shots off before the AI identify exactly where I'm hiding and come at me. I'm guessing that the reason for my detection is my low Stealth points.
You would think that shooting people 2 blocks away in the middle of the night while hidden behind a billboard on the top of a build would count as "stealthy" but my Stealth stays stubbornly on "Clumsy".
Switching into "stealth" mode by clicking the left stick (PS3) only changes my characters standing position and causes them to move slowly. I know from playing the storyline that I could perform "stealth" kills like this - if I wasn't 2 blocks from my protagonists.
Going into cover and sniping seems to cancel "stealth" mode. Standing up in "stealth" mode when I could be hiding behind something seems foolish, counter-intuitive and bad for my health.
So what is the purpose of Stealth and how does it work?

A: purpose of stealth is to sneak up on enemies and use the one hit kill attack.. stealth skill is gained by staying in stealth mode in-game (walking in stealth) and it seems to serve little purpose compared to single player because as you said, GTAonline seems to group a bunch of enemies together rendering stealth almost impossible, as one shoot one and the rest become terminators ready to kill with vision scopes of thousands of miles away knowing your exact location. Therefore your style of stealth, while being theoretically very smart, doesn't work in this game. You might have a better chance sneaking up on human players or using it during death match
source : level 87 in gta online and the experience that comes with time.

A: As said in the previous answer there is no purpose in online (that i have found). You can gain it by using suppressors on your guns (very slowly) or walk in stealth mode takes 20 minutes per bar
From what I have seen after leveling my stealth the only affects I have seen are on AI when walking stealthily behind them.
Perhaps it is something they are still in the works with.
Thats all I have

A: From what I have observed is that some players are off the radar when in close proximity to another player, but it is only when you have achieved the Ninja level of stealth and sneak. True Story, I was once in a public session fighting 5 new people which were armed with pistols and shotguns while I had assault rifles and explosives, one of them tried sneaking up on me with a clumsy level of stealth and..... lets just say it wasn't pretty on their side


text:
Q: How to prevent copy of URL in Parent Window In my application I am opening my application page in a Child Window. When I look these in IE, It doesnt show any URL this is great but When I check it in Firefox and Chrome I shows me URL.
My Question is Can I hide address bar in Child Window for Firefox and chrome.
I want to prevent User to copy paste URL in Parent window and access the page.
I m using form Authentication
<authentication mode="Forms">
        <forms loginUrl="~/login.aspx" protection="All" timeout="3600" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" cookieless="UseUri" enableCrossAppRedirects="false"/>
    </authentication>

I have tried using Authorization="?"
I have tried using a javascript to check whether this is a parent window or child window.
<script type="text/javascript">
        if (typeof window.opener != "undefined")
            alert("I was opened from within " + window.opener.location.href);
        else if (window != top)
            alert("You came here from " + document.referrer);
</script>

But the 2nd part is not working.
Kindly Help me and let me know what I m doing wrong

A: Instead of preventing user to copy paste url what u can do is u can put some script, that can runs only when a request is made else it will do the action that you want.
 string referer = Request.ServerVariables["HTTP_REFERER"];
        if (string.IsNullOrEmpty(referer))
        {
            Response.Redirect("../Index.htm");
        }

Use runs page only if request is coming from a page else it will redirect to the desired page

A: No You cannot hide the url if you open a new window.
If the page is from the same domain, you can instead AJAX the result into a popup DIV on your current page.
That said - anyone with a tiny bit of web savvy, can find the URL anyway.
For example in Chrome I do not even have to install anything, just click "Inspect Element" hit the NET tab and see the url as it is loaded from whereever.

A: If I understood what you want right, the only way is after the use logs in, (since you have a login form), save a boolean in the session state that indicates that the user is authenticated, then in the page you want to hide it's url, at the page_load event, check if this boolean is true, this way you can limit access to this url without needing to hide the url.


text:
Q: Firebase,Swift : Not able to retrieve Data I'm trying to do a simple task, to get a value from Firebase.
I added the image below with the relevant screens. At least one of the print commands should print a message to the console, but it's not working. I've been trying to fix it for 1,5 days now and I still have no idea why it is not working.
Code:
import UIKit
import Firebase

class MainVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let ref = FIRDatabase.database().reference()

        ref.child("zonneschijn").observeSingleEventOfType(.Value, withBlock: { snapshot in
            if snapshot.value is NSNull {
                print("Does not exist currently")
            } else {
                print("Exists currently")
            }

        })
    }
}

I've also tried to use viewDidAppear, also with no succes.

A: If you are not authenticating your user's.
Go to Rules tab in Realtime Database in Firebase console.
Default Security rules of firebase are something like this :-
{
 "rules": {
    ".read": "auth != null",
    ".write": "auth != null"

   }
}

Which means only authenticated users(Those user's who have been signed in either with gmail, Facebook, gitter, email..etc) can read or write data...
Clearly you are not authenticating your user that's why you can not retrieve any data with these default Security Rules .
This is a good practice to only allow authenticated users to have access to the DB, as it is more secure.If you want to read data anyways , Modify your security rules to this:-
Warning :- Not Recommended if you are making app that has some private DB.
   // These rules give anyone, even people who are not users of your app,
    // read and write access to your database

    {
      "rules": {
        ".read": true,
        ".write": true
      }
    }

A better alternative :-

*

*Sign in your user(start with email-password : Firebase EMAIL- Password Auth)

*Then access your DB

Do read :  Security Rule's


text:
Q: Restoring dependency via nuget in VS2017 I created a project of Windows Runtime Component (Universal) type using VS2017. Project file includes package reference:
 <ItemGroup>
    <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
      <Version>5.2.3</Version>
    </PackageReference>
  </ItemGroup>

Everything works fine if this option is enabled: Automatically check for missing packages during build in Visual Studio

But I have some cases (this option is disabled, build via CLI, server CI build) when this dependency is not being restored automatically during build and project.assets.json is missing in the obj folder after build. It causes a lot of errors like this: error CS0518: Predefined type 'System.String' is not defined or imported
Is it possible to make auto restoring of package reference via project file (.csproj)?
Thanks

A: Execute msbuild -t:restore your.sln before building the solution to restore all packages and make sure your CI uses MSBuild 15.x.


text:
Q: Best way to extract the tld and domain, but not subdomain? php What is the best way to extract from a url just the domain (like example.com), taking into account of some tlds like .co.uk?
Is it just with a manual list of the .xx.xx? or do they follow a pattern?
I would say just filter out any domain part under 3 characters, but there are things like .org.xx which are 3 characters

A: Yes, you will need a per-TLD (or even per-domain) list. It doesn't have to be "manual" per se; in fact, I would strongly recommend you to use the one from http://publicsuffix.org/


text:
Q: Intermec printer stopped printing after sending IPL commands I tried printing a label to an Intermec printer from php using the following code:
    $cmds .= "<STX><ESC>C<ETX>";
    $cmds .= "<STX><ESC>P<ETX>";
    $cmds .= "<STX>E4;F4;<ETX>";
    $cmds .= "<STX>H0;o102,51;f0;c25;h20;w20;d0,30;<ETX>";
    $cmds .= "<STX>L1;o102,102;f0;l575;w5;<ETX>";
    $cmds .= "<STX>B2;o203,153;c0,0;h100;w2;i1;d0,10;<ETX>";
    $cmds .= "<STX>I2;h1;w1;c20;<ETX>";
    $cmds .= "<STX>R;<ETX>";
    $cmds .= "<STX><ESC>E4<ETX>";
    $cmds .= "<STX><CAN><ETX>";
    $cmds .= "<STX>RO503C001IP0722RZ001-050<CR><ETX>";
    $cmds .= "<STX>RO503C001IP0722RZ001-050<ETX>";
    $cmds .= "<STX><ETB><ETX>";
$handle = printer_open("Intermec");
printer_set_option($handle, PRINTER_MODE, "raw");
printer_write($handle,$cmds);
printer_close($handle);

This is the site from which I copied the Intermec Programming Language commands.
The script connected to the printer successfully but after running it, the printer won't print anything, anything at all. The Printer Monitor keeps showing Syntax Error.
Did I do something really wrong? Is there a way to make it print again?
I didn't have the inspiration to note down the printer type (I won't have access to it until tomorrow), but it looks exactly like the one in the picture below:

Please help me, I have no idea what to do...

A: Did you get an answer elsewhere?
For me, I use the following in place of your first 3 lines
<STX><ESC>P;E2;F2<ETX>

And for lines 8 to 10 I use
<STX>R<ESC>E2<CAN><ETX>

And in your last line I include <FF> after the <ETB>


text:
Q: I don't know exactly if it's a bug from the API or axios I had a problem is that when I type **console.log(response.data) **It should show me an object Containing many arrays, but its place shows me an error: Uncaught (in promise) => I get this error in the console
Knowing that there is no error in my API because when I try it in postman it brings the correct parameters.
this is my code :
const baseUrl = "https://....";

function getStandings() {
  const url = `${baseUrl}/standings`

  axios.get(url, {
    headers: {
      "X-Auth-Token": `${token}`
    }
  })
  .then((response) => {
    console.log(response.data)
  });

}

getStandings();

⚠ note : token and baseUrl they correct.
It goes in the error and I log it to the console. This is what I get::
message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …

A: I found the solution, only the problem was with CORS I had to enter from a browser that does not support it to show me the result of the API.
This site helped me a lot => Run Chrome browser without CORS


text:
Q: strftime is always showing am for times (even for "pm" time also) for every datetime entry in rails iam saving current date and time in database as checkin time in db. by using Time.now. and when i query the database like this iam always getting the time in "am" only even for time in "pm" also.
 @curr_emp_attendace = current_employee.punch_in_outs.where("YEAR(check_in) = ? and MONTH(check_in) = ?",Time.now.strftime("%Y") ,Time.now.strftime("%m") )

and in view iam displaying like this
<%= attendace.check_in.strftime("%a %d, %H:%M %P") when i display like this iam always getting the "am" only for the time (for times in "pm") also. what might be the reason iam not understanding.

A: Try this:
@curr_emp_attendace = current_employee.punch_in_outs.where(:check_in => Time.now)


text:
Q: How do the electrical characteristics of an ADC degrade over lifetime? How do the electrical characteristics of an ADC typically degrade over lifetime?
And is there a way to do a somewhat realistic worst-case estimate for that before doing aging tests over a big batch?
Example data, probably for begin of life, taken from the PIC16(L)F1855/75 data sheet is:

There are also application notes available what can be compensated away and what is remaining, for the case one does not already know.
However, I never see any information about degradation due to aging.
Also no information how much the characteristics worst-case change over the operational temperature range.

A: I'm not aware of any ADCs that degrade, nor what mechanisms would lead to such (while meeting abs. max. ratings).  (But then, ADCs are usually super-secret sauce, and I'm hardly expert in VLSI to begin with.)  This is a question for the manufacturer, not random people from the internet.
This may be relevant: http://ww1.microchip.com/downloads/en/DeviceDoc/00000169J.pdf
Offhand, the only indications I know of, regarding reliability, are made explicit: to wit, I've been using the AVR64DA64 lately, and errata show a lower than expected Flash lifetime (100k --> 10k erase cycles), and "The offset of the DAC output buffer can drift over lifetime if the device is powered with the DAC output buffer disabled".  No such notes about the ADC.
If you need guaranteed device lifetime, expect to pay for it.  Perhaps you can obtain some MIL/aerospace rated parts with more extensive testing, proven operation, and a paper trail to prove it?  I'm sure an FAE can help figure something out.

A: It'll either cost real money to get parts where this is known, or you can use some intrinsically accurate self-calibration process. A ramp from an integrator is an excellent way to check ADCs for static linearity errors. As far as scaling goes - try for ratiometric operation if at all possible, then you only deal with resistor drift, if any.
The best way to "deal" with such problems is to design them out.


text:
Q: Regular expression - Get specific part of string I have the following sentence:

b.g The big bag of bits was bugged.

How can I exclude the b.g from it by using a regular expression?
I am sure I need a negative lookahead but I cannot get it right yet.
Something like
^(?!b\.g)

A: sed 's/^...//' strips the first 3 characters, "b.g", but I doubt that's what you're really asking. Your ^ anchor appears to be a red herring.
You already have correct escaping for . period, just stick with that:
sed 's/b\.g//'

Python's positive lookbehind ?<= may be what you are trying to find words to express:
>>> m = re.search(r'(?<=b\.g)(.*)', 'b.g The big bag of bits was bugged.')
>>> print(m.group(1))
 The big bag of bits was bugged.

A: I would do it this way:
[^\S].*

What [^\S] does is basically skip any character until it reaches the first space. then start capturing. No need in this case for negative or positing Lookbehind.
Demo: regex101
If you prefer to do it with positive Lookbehind, you can do it this way
(?<=b\.g).*

Demo: regex101

A: In python you could do something like this:
import re
w = 'b.g The big bag of bits was bugged.'
print w

d = re.compile(r'^b.g\s')
a = re.sub(d, '', w)
print a


text:
Q: How to fix 'microsoft.maintainability' build error? I have a controller which contains a few private read only interface properties which it needs in order to get data by calling a service which is then used to populate models etc
private readonly ISomeInterface _someObject;

Which gets set in the Controllers constructor:
public ... (ISomeInterface someInterface, ...) {
...
_someObject = someObject
}

_someObject is then used in a call to the service layer to get data.
I had to add another property to the controller but now when I build the soloution I get the following error:
CA1506 : Microsoft.Maintainability : 'ControllerName' is coupled with 87 different types from 30 different namespaces. Rewrite or refactor this class's methods to decrease its class coupling, or consider moving some of the class's methods to some of the other types it is tightly coupled with.

It asks me to reduce the coupling of the class, I understand that one way of doing this is to code against interfaces (abstractions) - which I'm already doing by adding the interface property? It seems by adding one more property it takes it past the threshold for flagging up this error.
If I remove it, I can't get the data I need? What do I need to modify?

A: How many actions does your controller have?  Do you have a view model for each action?  Do you have an input model for each action?  Are you interacting with different classes for each controller action?  You may need to split  your controller up into multiple controllers to make it do less giving it fewer reasons to change and also fewer dependencies.  Although using an interface would decouple the controller from the specific implementation of ISomeInterface it doesn't do anything in terms of that warning.  Changing to using the Interface didn't reduce the number of types... it just changed from concrete type to an interface type.
The problem is warning against having one class that does many many things.  Having many dependencies suggests the class is doing too much and should be divided up.  For example if this controller has say an action for "Bake Pie" and "Eat Pie" and "Make Ice Cream" and "Deliver food" you could move "deliver food" to a brand new class... you could break out the Make Ice Cream as well and then you would evaluate if Bake Pie and Eat Pie should stay together in the same class or be put in separate classes.  The pies debate opens a can of worms which folks would debate.
see: SOLID (object-oriented design)
Do you have code that has to call 2 or more different data access classes that then calls another class to  to create a view model.  You could move that whole operation to a new class thus reducing your dependency on 3 classes down to 1.


text:
Q: Sorting results of UNION query combining two tables by the table of origin I'm using the UNION operator to select results from two different tables. I want results from the first table result to come before those from the second table.
For example: I have the tables customer_coupons and segment_coupons. Both tables have a column named coupon_id. When I run a query involving a UNION of these two tables, it returns the correct records, but they are not the order I want: It gives me the coupon_ids of both tables mixed in ascending order, but I want to show ALL coupon_ids of the first table and then ALL coupon_ids of the second table.
Here's the query as it currently exists:
SELECT coupon_id
FROM   customer_coupons
UNION
SELECT coupon_id
FROM   segment_coupons;
How can I change this so that all results from the first half of the query come before all results of the second half?

A: Put in a fixed table-identifying field:
(SELECT 1 AS source_table, coupon_id
FROM customer_coupons)

UNION ALL

(SELECT 2 AS sourcE_table, coupon_id
FROM segment_coupons)

ORDER BY source_table, coupon_id

Note the brackets around the individual queries. This forces MySQL to apply the order by to the result of the union, not to the 2 sub-query.

A: SELECT * FROM (
SELECT coupon_id, 1 as myorder
FROM   customer_coupons
UNION
SELECT coupon_id 2 as myorder
FROM   segment_coupons)
Order by myorder


text:
Q: React: how to initiate a variable with API call response I am trying to create a table that uses an api to access data from a database.
import { COLUMNS } from './ActivityColumns.js'
import { getTable } from "./ApiCall.js"

export const SortingTable = () => {

    const columns = useMemo(() => COLUMNS, [])
    const [aaa, setData] = useState([])

    const getData = () => {
        getTable('activity').then(result => {
            console.log('returning result')
            return result;
        })
    }

    const tableInstance = useTable({
        columns: COLUMNS,
        data: getData()
    },
    useSortBy)
}

The result in getData() is the expected one, an array of Object dicts [ {..}, {..}, ..., {..}]. The problem is that when tableInstance tries to set the data as the result of getData(), I get the following error: useTable.js:591 Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')
The exact line that causes the error is from useTable.js:
  data.forEach((originalRow, rowIndex) =>
    accessRow(originalRow, rowIndex, 0, undefined, rows)
  )

Before using an API I used a json file that has the same structure as the API's response: [{..}, {..}, {..}]. This one worked.
What goes wrong when trying to initiate with an API and how can I fix this error?
Edit 1: I tried to declare getData inside the hook
export const SortingTable = () => {

    const columns = useMemo(() => COLUMNS, [])

    const getData = () => {
        const [data, setData] = useState(null);

       const getData = () => {
         getTable('activity').then(result => {
           console.log('returning result')
           console.log(result)
           setData(result);
         })
       }

       getData();

       return data;
    }

    const tableInstance = useTable({
        columns: COLUMNS,
        data: getData
    },
    useSortBy)

    const { getTableProps, getTableBodyProps, headerGroups, footerGroups, rows, prepareRow } = tableInstance
}

A: Your getData function does not have a return. This means calling getData() would give you undefined.
Is useTable OK to work with an asynchronous function?
If so, just return something from getData.
If it expects its synchronous data you might need to put the results of getData into state so that it gets populated once available which in turn causes a rerender of your component and calling useTable again.
import { COLUMNS } from './ActivityColumns.js'
import { getTable } from "./ApiCall.js"

export const SortingTable = () => {

    const columns = useMemo(() => COLUMNS, [])
    const [aaa, setData] = useState([])

    useEffect(() => {
            getData(); // <-----
    }, []);

    const getData = () => {
        getTable('activity').then(result => {
            setData(result); // <-----
        })
    }

    const tableInstance = useTable({
        columns: COLUMNS,
        data: aaa // <-----
    },
    useSortBy)
}

The reason why your JSON was loaded without issue and your fetching is problematic is probably because you just imported/required the JSON which is synchronous while getTable obviously returns a thenable/Promise.

A: getData doesn't return anything. So effectively you're passing useTable an object {columns: COLUMNS, data: undefined}.
One way to fix this is to declare getData inside your hook, and use state to save the result of the API call:
const useTable = () => {
  const [data, setData] = useState(null);

  const getData = () => {
    getTable('activity').then(result => {
      console.log('returning result')
      setData(result);
    })
  }

  getData();

  // do whatever you want to do here with COLUMNS

  return data;
}


text:
Q: move images in a line with timed effect the idea is that I have a div with some images ( in a horizontal line) you only see the first image within the div.
For now there are 5 images.
I want to move the images from right to left leaving the div (and screen) and after the last images has moved the first image will be in front  (that is 1 entire loop)
to start the animation, you click a button.
now the trick of this, at every uneven numbered image the animation has to stop a few moments. so the starting image is 1, then pass number 2 and stop at 3 for a few seconds then pass numver 4 and stop at number 5 after that the image continues to the first one again and stops until start button is clicked again.
I want to be able to expand the amount of images fairly easy.
what I have so far in CSS / HTMl is

and css
body{
padding:0px;
margin:0px;
background-image:url(afb_stuk/background.jpg);
background-repeat:no-repeat;
background-size:cover;}

#container{
position:relative;
margin-left:50px;
margin-top:25px;
height:600px;
width:1250px;
border:solid thin red;
z-index:1;
/*overflow:hidden;*/}

#fotos{
position:relative;
height:80%;
width:12000px;}

.image{
height:600px;
width:1250px;
float: left;

.image img{
height:600px;
width:auto;}

#start{
position:relative;
margin:auto;
margin-top:-10px;
height:10px;
width:60px;

border-radius: 25px;
border: 2px solid #8AC007;
padding: 20px; }

.text{
margin-top:-10px;}

A:

    <button onclick="start()" id="new">Click to start!</button>

your image names should be in form of 1,2,3,4.jpg etc.
and try to accumulate the delay between images.

A: i have found a very good youtube tutorial including a fiddle.
I just changed some of the effects (and image width) to giv it the effect I liked and wanted.
Thnx to all who have helped me :)
[1]http://jsfiddle.net/EjZzs/15/
$(function() {

//settings for slider
var width = 720;
var animationSpeed = 1000;
var pause = 3000;
var currentSlide = 1;

//cache DOM elements
var $slider = $('#slider');
var $slideContainer = $('.slides', $slider);
var $slides = $('.slide', $slider);

var interval;

function startSlider() {
    interval = setInterval(function() {
        $slideContainer.animate({'margin-left': '-='+width}, animationSpeed, function() {
            if (++currentSlide === $slides.length) {
                currentSlide = 1;
                $slideContainer.css('margin-left', 0);
            }
        });
    }, pause);
}
function pauseSlider() {
    clearInterval(interval);
}

$slideContainer
    .on('mouseenter', pauseSlider)
    .on('mouseleave', startSlider);

startSlider();

});
[2]https://youtu.be/KkzVFB3Ba_o


text:
Q: How do I store a random integer in a local variable in Python? I have some code here for a basic game I'm making in Python 3.x. As you can see, the local variable 'code1' creates a random two digit number between my values, for the first part of my vault's unlock code (later in game). What I want to do is store the random integer somehow so if the specific room is re-visited it will display the first outputted random number from this function and not keep changing as this would defeat the object of clue collecting.
def corridorOptions():
    code1 = random.randint(30,60)
    corridorChoice = input('> ')
    if corridorChoice == "loose":
        delayedPrint("You lift the loose floorboard up out its place." + '\n')
        delayedPrint("It shifts with hardly any resistance." + '\n')
        delayedPrint("There is a number etched. It reads " + "'" + str(code1) + "'")

Cheers guys.

A: I suggest you add an attribute to the corridorOptions function that is only initialised once when it is created on the first call of the function
from random import randint

def corridorOptions():
    if not hasattr(corridorOptions, 'code'):
        corridorOptions.code = randint(30, 60)
    print("There is a number etched. It reads '{0:02d}'".format(corridorOptions.code))

corridorOptions()
corridorOptions()
corridorOptions()
corridorOptions()
corridorOptions()

output
There is a number etched. It reads '58'
There is a number etched. It reads '58'
There is a number etched. It reads '58'
There is a number etched. It reads '58'
There is a number etched. It reads '58'


text:
Q: SAML identity provider interoperability with remote Active Directory domain We have a SaaS system based on SAML 2.0 authentication using an Identity Provider and we want to provide several ways of logging in, Form Authentication, Facebook, etc. Is it possible to connect the SAML system to a remote application using Active-Directory, ideally to gain access to the API also but most importantly to be able to use their authentication with the remote active directory as a means of logging in to the SaaS system?

A: Check out PingFederate and PingOne from Ping Identity (note: I work for Ping).  We have complete IDP and SP support (SAML1.1, 2.0, WS-Fed (Passive)) as well as support for LDAP, SFDC, OpenID and other Cloud Identity providers (LinkedIn, Facebook, etc). We also have support for Web Services security via Oauth2 and WS-Trust.


text:
Q: visual studio 2012 asp.net HTTPpost data to db error When using following code:
@{
    ViewBag.Title = "Insert";
    Layout = "../_Insert.cshtml";
    model Namespace.GoogleCalendarModel
}

Kies een evenement
<select>
    @foreach (var e in ViewBag.allEvents)
    {
        <option value="@e.Id">@e.Titel</option>
    }
</select>
@using (Html.BeginForm("Insert","GoogleCalendar", FormMethod.Post, new {enctype="multipart/form-data"}))
{

            Formuleer werksfeer
            @Html.TextBoxFor(model => model.txtModus);

            Formuleer de opdrachten
            @Html.TextBoxFor(model => model.txtOpdrachten);

            Formuleer mededeling
            @Html.TextBoxFor(model => model.txtMededeling);

    @Html.ValidationSummary(true);
   @Html.TextBoxFor(model => model.toevoegen);
}

i get following error on model Namespace.GoogleCalendarModel:
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
anybody an idea of how to fix this? Or a working example for an httppost for writing data to db in MVC asp.net visual studio 2012?

A: The model must be specified using @model:
@model Namespace.GoogleCalendarModel  //notice there's no semicolon at the end

@{
    ViewBag.Title = "Insert";
    Layout = "../_Insert.cshtml";
}

You are not assigning anything since model (notice lowercase first letter) is not a variable. You can consider it as a construct similar to the using keyword for adding namespaces.


text:
Q: ASP.NET Identity 2 and Anonymous Users In our developing e-commerce solution we are using AspNet Identity 2.2.1 and it is required that any guest (anonymous) users should complete checkout without prior registration to the website. In order to fullfill this requirement have written an ActionFilter named UserMigrationAttribute which obtains SessionTrackId (string GUID) from cookie -which we set from a HttpModule for every request if SessionTrackId is not found along with request cookies- and creates and actual IdentityUser in database with the username something like SessionTrackId@mydomain.com.
We have decorated our BaseController class with this UserMigration attribute in order to utilize its functions throughout the site.
Everything up to this point works as expected with single downside issue, which is when the page is being loaded for the first time for any user, if we try to make an Jquery Ajax Call to a Method which have [ValidateAntiForgeryToken] attribute, the call fails with the 'The provided anti-forgery token was meant for a different claims-based user than the current user.' error, even though we are sending __RequestVerificationToken parameter with every ajax call.
But if user opens another page by clicking link and/or reloads/refreshes current page, all the subsequent ajax calls complete successfully.
In our understanding UserMigrationAttribute creates user on OnActionExecuting method, but after we signIn user in the process @Html.AntiForgeryToken() is not being updated with the right values.
You may find the UserMigrationAttribute code below;
    [AttributeUsage(AttributeTargets.Class)]
    public class UserMigrationAttribute : ActionFilterAttribute
    {
        public ApplicationSignInManager SignInManager(ActionExecutingContext filterContext)
        {
            return filterContext.HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }

        public UserManager UserManager(ActionExecutingContext filterContext)
        {
            return filterContext.HttpContext.GetOwinContext().GetUserManager<UserManager>();
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            CreateMigrateCurrentUser(filterContext);
            base.OnActionExecuting(filterContext);
        }

        private static readonly object LockThis = new object();

        private void CreateMigrateCurrentUser(ActionExecutingContext filterContext)
        {
            lock (LockThis)
            {
                var signInManager = SignInManager(filterContext);
                var userManager = UserManager(filterContext);

                var sessionTrackId = GetSessionTrackId(filterContext);

                if (!filterContext.HttpContext.Request.IsAuthenticated)
                {
                    if (!string.IsNullOrEmpty(sessionTrackId))
                    {
                        var username = string.Format("{0}@mydomain.com", sessionTrackId);
                        var user = userManager.FindByName(username);

                        if (user == null)
                        {
                            user = new User() {UserName = username, Email = username};
                            var result = userManager.Create(user);
                            userManager.AddToRole(user.Id, StringResources.AnonymousVisitorsGroup);
                        }

                        signInManager.SignIn(user, true, true);
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(sessionTrackId))
                    {
                        var username = string.Format("{0}@mydomain.com", sessionTrackId);
                        var user = userManager.FindByName(username);

                        if (user != null)
                        {
                            if (!HttpContext.Current.User.IsInRole(StringResources.AnonymousVisitorsGroup))
                            {
                                var targetUserId = HttpContext.Current.User.Identity.GetUserId<int>();

                                var service = new Service();
                                service.Users.MigrateUser(user.Id, targetUserId);
                            }
                        }
                    }
                }

            }

        }

        private string GetSessionTrackId(ActionExecutingContext filterContext)
        {
            var retVal = string.Empty;
            if (filterContext.HttpContext.Request.Cookies["stid"] != null)
            {
                retVal = filterContext.HttpContext.Request.Cookies["stid"].Value;
            }

            return retVal;

        }

    }

Any help or suggestions are highly appreciated.
Thank you,

A: This is happening because the anti-forgery token is set in a cookie, which will not be updated until the next request. If you're manually signing a user in, you should also issue a redirect (even if to the same page they were already headed to), simply to ensure that the cookie data is correct. This normally happens naturally, as the sign in form will redirect to the URL that needed authorization after the user is signed in, thus negating the problem. Since you're not redirecting currently, the data is out of sync.
However, I have to say that this seems like a very poor solution to this particular use case. Creating some sort of temporary-type user and signing that user in to handle guest checkout creates an unnecessary glut of useless data in your database, at best, and leads to bugs and other issues like this one you're experiencing, at worst.
I also run an ecommerce site, and the way we handled guest checkout is incredibly simplistic. The checkout data is just stored in the session (email, shipping/billing address, etc.). We build a view model to handle the actual checkout where the data necessary for submitting the sale comes either from the user object, if they're logged in, or these session variables, if they aren't. If the user is neither logged in, nor has the requisite session variables set, then they are redirected to the onboarding form where billing/shipping, etc. is collected.
For other aspects like maintaining an anonymous cart, we use a permanent cookie with the cart identifier. If the user ends up creating an account, we associate the anonymous cart with their user, and then remove the cookie. This ensures that their cart survives past the session timeout and things like closing the browser, even if they're anonymous.
In other words, in all these things, no user object is actually needed. If it's there (user is logged in), great, we'll use it. Otherwise, we collect and persist the requisite information for checkout via other means.


text:
Q: Returning Values through HTTP Post within Infusionsoft Campaign API The specific objective here is as follows -
Using Infusionsoft API (iSDK),
I need to create and host a file instructing infusionsoft to return the value of a 'Name / Value' pair from an HTTP Post to a contact specific Custom Field.
This is become increasing challenging as most of my experience revolves around HTML, CSS and basic Javascript and I am completely at a loss.
My HTTP Post url points to the following php file.
<?php require("isdk.php");
$app = new iSDK;
$connInfo = array(
"appname:appname:i:myapikey:appname.infusionsoft.com"
);

$returnFields = array('numberId');
$conDat = $app->loadCon('numberId', $returnFields);

$returnId = $conDat['numberId'];
$update = array('_customField' => 'numberId');
$conID = $app->updateCon($contactId, $update);

/*
And some additional code I don't know how to apply
$app->updateCustomField($, $numberId)
    {
        $carray = array(
            php_xmlrpc_encode((int)$fieldId),
            php_xmlrpc_encode($fieldValues));
        return $this->methodCaller("DataService.updateCustomField", $carray);
    }

*/


text:
Q: How to make casts work in this way? I'm working with forms where the checkboxes are present, but the target model's fields must be in boolean type, since they are defined in my migrations as boolean. For example:
$table->boolean('is_active')->default(true);

The Model's values are filled in this way:
    foreach (static::getFillableFields() as $field) {
        $entry->$field = $request->input($field);
    }

So I added the cast to make this field boolean:
class Entry extends Model
{

    protected $casts = [
        'is_active' => 'boolean',
    ];

But now what I see: when the form's checkbox is checked and I have '1' string in the request, it works well - '1' gives 'true' when I access $entry->is_active then. But when checkbox isn't checked, it gives the 'null' value, and - I don't know why - when the model's field is set to null, then it returns null (not 'false', as I expected).
Why is it so? This makes casts useless in my case. Can I change this behavior?
I'm not too inspired with idea of adding this (accessors/mutators) for every boolean field (but in fact this results in what I need):
public function setIsActiveAttribute($value)
{
    $this->attributes['is_active'] = (bool)$value;
}

public function getIsActiveAttribute(bool $value): bool
{
    return $value;
}

A: As @Devon mentioned, checkboxes that are not checked are not included in the request data sent to the controller. The HTML spec deems unchecked checkboxes as unsuccessful, and therefore does not submit them.
One trick that is used to get around this "limitation", however, is to add a hidden input to your HTML that has the same name as your checkbox, but contains the false value. This hidden input must come before your checkbox input.
This will allow you to continue to use your mass-assignment functionality.
So, your form should look something like:
<input type="hidden" name="is_active" value="0" />
<input type="checkbox" name="is_active" value="1" />

Now, when the form is submitted with an unchecked checkbox, the hidden input will ensure the input value exists in the request data with the false value (0).
When the form is submitted with a checked checkbox, both inputs will submit successfully with the same name, but the server side will only take the last value it sees. This is why the checkbox must come after the hidden input field, so that the last value the server sees is the successful value defined on the checkbox (1).
As a side note, this is also how the Ruby on Rails form helper handles checkboxes. From their documentation.

The HTML specification says unchecked check boxes are not successful, and thus web browsers do not send them. Unfortunately this introduces a gotcha: if an Invoice model has a paid flag, and in the form that edits a paid invoice the user unchecks its check box, no paid parameter is sent. So, any mass-assignment idiom like
@invoice.update(params[:invoice])
wouldn't update the flag.
To prevent this the helper generates an auxiliary hidden field before the very check box. The hidden field has the same name and its attributes mimic an unchecked check box.
This way, the client either sends only the hidden field (representing the check box is unchecked), or both fields. Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.

A: This is a controller issue, not a model issue.  HTML checkboxes will not have a value if they are unchecked, this is how they work.
Therefore, when retrieving the value from your Request object in the controller, you should set the default value as false.
Example in controller method:
$model->is_active = $request->input('is_active', false);

If you leave the second argument of input() empty, it will default to null.

A: Suddenly: casts don't work for Model::save() method.
laravel eloquent model casts on save?
So all that's left for me is to use accessors/mutators..


text:
Q: Emacs: как вызвать Лисп функцию из консоли не открывая редактора? Как вызвать свою функцию из командной строки через редактор Emacs уже знаю, это написано тут, но при этом сам редактор так же открывается и в своем буфере выводит результат функции,
Мне же нужно, чтобы редактор не открывался, а выводил результат прямо в консоль.

A: Есть ключи  --eval и --batch
emacs --batch --eval "(+ 1 1)"
emacs --batch --eval "(print (+ 1 1))"

Ссылки

*

*https://www.gnu.org/software/emacs/manual/html_node/elisp/Batch-Mode.html


text:
Q: Creating a connection to a subscription site in python I am looking to open a connection with python to http://www.horseandcountry.tv which takes my login parameters via the POST method. I would like to open a connection to this website in order to scrape the site for all video links (this, I also don't know how to do yet but am using the project to learn).
My question is how do I pass my credentials to the individual pages of the website? For example if all I wanted to do was use python code to open a browser window pointing to http://play.horseandcountry.tv/live/ and have it open with me already logged in, how do I go about this?

A: As far as I know you have two options depending how you want to crawl and what you need to crawl:
1) Use urllib. You can do your POST request with the necessary login credentials. This is the low level solution, which means that this is fast, but doesn't handle high level stuff like javascript codes.
2) Use selenium. Whith that you can simulate a browser (Chrome, Firefox, other..), and run actions via your python code. Then it is much slower but works well with too "sophisticated" websites.
What I usually do: I try the first option and if a encounter a problem like a javascript security layer on the website, then go for option 2. Moreover, selenium can open a real web browser from your desktop and give you a visual of your scrapping.
In any case, just goolge "urllib/selenium login to website" and you'll find what you need.

A: If you want to avoid using Selenium (opening web browsers), you can go for requests, it can login the website and grab anything you need in the background.
Here is how you can login to that website with requests.
import requests
from bs4 import BeautifulSoup

#Login Form Data
payload = {
    'account_email': 'your_email',
    'account_password': 'your_passowrd',
    'submit':   'Sign In'
}

with requests.Session() as s:
    #Login to the website.
    response = s.post('https://play.horseandcountry.tv/login/', data=payload)

    #Check if logged in successfully
    soup = BeautifulSoup(response.text, 'lxml')
    logged_in = soup.find('p', attrs={'class': 'navbar-text pull-right'})
    print s.cookies
    print response.status_code
    if logged_in.text.startswith('Logged in as'):
        print 'Logged In Successfully!'

If you need explanations for this, you can check this answer, or requests documentation

A: You could also use the requests module.  It is one of the most popular.  Here are some questions that relate to what you would like to do.
Log in to website using Python Requests module
logging in to website using requests


text:
Q: Allow cmd+` to toggle between most recent windows in TextMate In OS X if you press CMD + TAB you switch to your most recent application. If you press it again you switch to the application you were just using (because it becomes the most-recent).
In Textmate, if you press CMD + `, release, and then press it again it continues cycling through windows and does not go back to the most recently used window.
I understand that I can use CMD+SHIFT+` to achieve the desired affect, but it would be better if there was a setting to change the default behavior.

A: This is how it works for all applications. But note that when you click inside the window, it switches directions. So as long as you click first, it will do what you want.


text:
Q: I've two computers.. But which one I keep? which one is better? HP vs Asus I've two computers Asus and Hp:
HP EliteBook 8560w has this configuration:
Intel® Core™ i7-2630QM CPU @ 2.00GHz × 8
DDR3 8GiB
NVIDIA Quadro 1000M avec 2 GB
Asus G553V gamer has:
Intel Core i5-6300HQ CPU @ 2.3 - 3.2 GHz
DDR4 8GiB
NVIDIA GeForce GTX 960M
I don't play games or video editing..etc
My job is mainly image processing using C++ which uses lot of math and geometry..etc.
About multithreading, I believe that compilers are very intelligent that they can use threads automatically if that is possible.. So I think it will useful in my case
What do you think? which machine is suitable for me?

A: Right.. After your edit added some useful information...
The Asus is the newer, more modern machine. The HP is already 5 year old or so.
The i5 in the Asus has more cache, a higher clock-speed and faster RAM than the i7 in the HP. There is no hyper-threading.
The i7 has 4 cores + hyper-threading (which amounts to 8 cores if used effectively by your software), but is slower in all aspects. The i7 is only interesting if you are heavily into multi-threaded applications using more than 4 threads. (Probably only really noticeable until you go beyond 8 threads.)
The Quadro in the HP only makes sense if you have software that insists on (or is heavily optimized for) a Quadro card (some specialist 3D CAD software falls in that category).
For everything else the GTX960 will be the faster/better video-card.
In short: The Asus is the better machine, except for the rare case if you really need a Quadro GPU or are using heavily multi-threaded software most of the time.

A: I'd recommend the Asus G553V. If you don't require 4C/8T, than the processor gives you 4C at higher speed than the i7-2630QM. The speed is very similar and the architecture is also 5 years newer.
It also uses DDR4 memory with lower consumption than DDR3.
The graphics isn't important for you, despite that the 960M has lower consumption and gives you more functions like acceleration of video content and so on.
So from the future usability perspective, it's better option. And also, it's much younger HW, so there is lower chance, that some HW part fails.
You didn't specified the display parameters and disk type (HDD/SSD). It can be also significant decision factor...


text:
Q: C++ operator overloading issue: expected initializer before '<<' token I am trying to overload the insertion operator '<<' to simplify some syntax required to use a specific piece of software. That software implements a hash object which holds a variety of types of data, so type checking cannot be done at compile-time because the type of the RHS of a given expression is not known until run-time. This hash is very similar in spirit to Boost Property Trees.
I am trying to write this as a template function to extract data from the hash. This works just fine as long as the receiving variable already exists (is initialized). It fails to compile if this is used during variable initialization.
So, this compiles and works fine.
int value;
value << data;

But this does not compile at all.
int value << data;

The real code is quite large and complex so I have written the following simplified program to exhibit the same behaviors.
I am using gcc version 4.3.4. A different compiler is not an option.
Any and all help is appreciated.
#include <iostream>

/**
  * Simple class to use with the templates.
  */
class Data
  {
public:
    Data ()
      {
        m_value = 0;
      }
    Data (int val)
      {
        m_value = val;
      }
    ~Data ()
      {
      }
    int value ()
      {
        return (m_value);
      }
    int value (int val)
      {
        m_value = val;
        return (value ());
      }
private:
    int m_value;
  };

/**
  * Assign data from RHS to LHS.
  */
template <class T>
void operator<< (T &data, Data &node)
  {
    data = node.value ();
  }

/**
  * Simple test program.
  */
int main (int argc, char *argv[])
  {
    // initialize the data
    Data data (123);
    std::cout << data.value () << std::endl;

    // extract the data and assign to integer AFTER initialization
    int value;
    value << data;
    std::cout << value << std::endl;

    // extract the data and assign to integer DURING initialization
    // *** problem is here ***
    int other << data; // <-- this fails to compile with...
    // expected initializer before '<<' token
    std::cout << other << std::endl;

    return (0);
  }

A: int value << data; does not make grammatical sense.
Think of << as being like any other operator, rather like +=. Yes, << is overloaded but it still has to obey the same semantics as its natural incarnation as a bitwise shift.
int value += 3; for example, makes no sense either.

A: int value << data; is not valid C++.


text:
Q: Delete row mysql php Using the following code:
if (isset($_POST['delete']) && isset($_POST['id']))
{
    $first = get_post('first');
    $query = "DELETE FROM user_master WHERE id='$id'";
    if(!mysql_query($query, $db_server))
        echo "DELETE failed: $query
" .
        mysql_error() . "

";
}

$query="SELECT * FROM user_master";
$result= mysql_query($query);

if(!result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);

for ($j=0 ; $j<$rows ; ++$j)
{
    $row = mysql_fetch_row($result);
    echo <<<_END

    ID      $row[0]
    First   $row[1]
    Last    $row[2]
    Email   $row[3]
    User    $row[4]

    <form action="willingLog.html" method="post">
    <input type="hidden" name="delete" value="yes" />
    <input type="hidden" name="id" value="$row[0]" />
    <input type="submit" value="DELETE RECORD" /></form>
_END;

I'm unable to delete a record form the table.
All the records form the table are printing on the screen, including the "DELETE RECORD" button.  When I hit the button, however, nothing happens.  I've checked the actual table on phpmyadmin, and the table is unaffected as well.
I'm pulling this stuff from a book, so I don't understand why it's not working.

A: I do not see where you set the $id variable.
if (isset($_POST['delete']) && isset($_POST['id']))
{
    //$first = get_post('first');   #not sure what this does
    $id = sanitize($_POST['id'], 'int');  //protect from sql injection
    $query = "DELETE FROM user_master WHERE id=$id";
    if(!mysql_query($query, $db_server))
        echo "DELETE failed: $query
" .
        mysql_error() . "

";
}

Please be sure to sanitize any data sent across the network, i.e. $_POST. Also, if id is of a number type, do not surround the value in quotes or mysql will interpret it as a string.
Lastly, look into using MySqli or PDO, as MySql API has been deprecated.

A: Here i defined a variable from that variable i delete the values
$id = 2;
    $query = mysql_query("DELETE FROM table_name WHERE id="'.$id.'"");

note: Delete query id is important otherwise it delete whole rows defaulty.

A: $query = mysql_query("DELETE FROM table_name WHERE id=1");

A: $query = "DELETE FROM user_master WHERE id='$id'";

This should probably be:
$query = "DELETE FROM user_master WHERE id='" . $_POST['id'] "'";

But please do some research into SQL injection, and why you should never pass information directly from the user into the database.

A: code should read:
$id = get_post('id');

in the first line of the curly braces under the first "if" statement.


text:
Q: I don't understand the string to byte aspect of computing/javascript After two years coming back to this/another topic where I see people discussing the same; I still don't understand what is going on.
following this SO post:
String length in bytes in JavaScript

I want to understand this part of javascript! I am also interested in calculating the kb size of a bitcoin transaction before I push it to the blockchain. The more important of the two though is that I finally understand what these users are doing because its come up more than once and I just don't get it!

I've tried three of the functions outlined as answers but they all seem to do nothing more than return the string.length whereas I would expect them to return a different value (the overhead of the string in bytes/kilobytes/megabytes)
function byteCount(s) {
    return encodeURI(s).split(/%..|./).length - 1;
    }

console.log(byteCount('hello'),'hello'.length);//5,5

function getLengthInBytes(str) {
    var b = str.match(/[^\x00-\xff]/g);
    return (str.length + (!b ? 0: b.length));
    }

console.log(getLengthInBytes('hello'),'hello'.length);//5,5

console.log((new TextEncoder('utf-8').encode('hello')).length,'hello'.length);//5,5

It's annoying that this makes no sense to me! Clearly these people would not be talking about how to get something that they can easily get with string.length so what are they trying and succeeding in returning?
Should the string instead be binary? (like so: How to convert text to binary code in JavaScript?)

A: You are testing with the base ascii characters (well, they are utf8, but you can think of them a little like ascii and these characters work very similarly in both encodings).  Try with an extended character.

console.log((new TextEncoder('utf-8').encode('')).length, ''.length);

A: There are a lot of different signs in the world.
They dont fit in one byte of data. Thats why some chars use more than one byte of data.
Some examples: "Äüöôś"


text:
Q: Implications of a model of ZFC By the completeness theorem ZFC is consistent if there is a model where ZFC is true.
What would happen if we found a model for ZFC? Would we be able to stop worrying if ZFC is inconsistent?
Are people trying to find such a model?
Or is there a proof that no such model exists?
My model theory and set theory is weak in general, but I understand basic ideas.

A: Gödel's second incompleteness theorem tells us that ZFC (if it is consistent) cannot prove that ZFC is consistent. Therefore, ZFC (if it is consistent) cannot prove that there is a model of ZFC, either. Thus we do not have a proof that no model exists, but we do have a proof that trying to find such a model is a pointless pursuit.
If you make stronger assumptions, such as assuming the existence of large cardinals, then you can prove that models of ZFC exist, and you can study them.

A: The question is always what are you willing to take "on faith". This is a source of tension between "minimal hypotheses" and "convenient hypotheses".
On the one hand, if you're willing to assume that set theory (by which I mean $\sf ZFC$ or one of its close relatives) is your meta-theory, you might as well assume that it is consistent. Because why would you work in a meta-theory which isn't consistent? And so you might as well assume that $\sf ZFC+\operatorname{Con}(ZFC)$ is also consistent, and so on.
Now since you've already made these "oh well" assumptions, you can indeed use Gödel's completeness theorem and see that $\sf ZFC$ has a model, and in fact it has a model in which $\sf ZFC$ is internally consistent, and so on.
But now, since we've made all of these "oh well" assumptions, since for "any reasonable iteration of the consistency operator" we assume the consistency statement, we must have gone through $\omega_1^{CK}$, so our meta-theory is not computable anymore. And that's not nice, and we don't want that.
So in order to salvage this, we need to set a recursive upper bound on the consistency operator. Call this new theory $T$. So now we're working in $T$ but we are not assuming $\operatorname{Con}(T)$. But it doesn't really change a lot from assuming just $T=\sf ZFC$. So we might as well do just that. The key observation here is that there is a bound which we can compute on how many times we are guaranteed that the consistency operator is iterable.

Now what about large cardinal axioms? Well, indeed even the statement "There is a well-founded model of $\sf ZFC$" already gives us a lot of consistency power relative to the above, and of course this statement is a consequence of all large cardinal axioms, you can now apply the above argument to the theory $\sf ZFC+\varphi$, where $\varphi$ is your large cardinal axiom(s).
So at the end of the day, you're not gaining a whole lot.
Now, what does it matter if we make these assumptions or not? At the end, it matters very little in terms of results. We need to have some agreed upon meta-theory in mathematics, and even if it's not $\sf ZFC$ per se, it is something which can be easily interpreted in $\sf ZFC$ (or its close relatives, or arguably an even weaker theory) in the most cases, perhaps much to the dismay of some people.
But we need to have some common denominator. And due to historic reasons that is "more or less $\sf ZFC$". So by adding new axioms we are deviating from this norm. It's not necessarily a bad things, these axioms can—and often do—simplify many arguments in mathematics, but we have some ways of stripping them from the proofs in most cases.
(For example forcing can be developed by working over a countable transitive model of $\sf ZFC$, but in fact we can develop forcing in arithmetical meta-theories, and there's no need to assume anything beyond that. It just that these additional assumptions illuminate and clarify the arguments, the proofs, and the results.)


text:
Q: Retrofit: add runtime parameter to interface? I would like to always add a parameter to my Retrofit calls. For values that I can hard code I can simply use
@POST("/myApi?myParam=myValue")

but what if I want to append android.os.Build.MODEL?
@POST("/myApi?machineName="+ Build.MODEL)

doesn't work. It would be useful to be able to abstract this part of the network call away from the implementing code.
EDIT
I can add Build.MODEL to all of my api calls by using a RequestInterceptor. However it still eludes me how to add it selectively to only some of my api calls while still using the same RestAdapter.
EDIT 2
Fixed the title which was all sorts of wrong.
EDIT 3
Current implementation:
RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("myapi")
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestInterceptor.RequestFacade request) {
                    request.addQueryParam("machineName", Build.MODEL);
                }
            })
            .build();
    API_SERVICE = restAdapter.create(ApiService.class);

A: Build.MODEL is not available for use in an annotation because it cannot be resolved at compile time. It's only available at runtime (because it loads from a property).
There are two ways to accomplish this. The first is using a RequestInterceptor which you mention in the question.
The second is using a @Query parameter on the method.
@POST("/myApi")
Response doSomething(@Query("machineName") String machineName);

This requires you to pass Build.MODEL when invoking the API. If you want, you can wrap the Retrofit interface in an API that's more friendly to the application layer that does this for you.


text:
Q: Defining methods in const and then using them in an order I have a page where i have written
const cc2= this.authService.getRoles().subscribe((data:PortalUserRoleModel[]) => {
       this.roles=data;

  });

and based on the data i have to call another service and fetch pages accessible
const cc3= this.authService.getMenu(this.role).subscribe((data:PortalMenuModel[]) => {
       this.menu=data;

  });

in page init i need to call both of them in order so i am using this :=
concat(cc2,cc3);
but it doesnt seem to work. It says concat does not work on subscription. What am i doing wrong and what is the correct way for this.
Thanks for the help

A: Given that both service methods are asynchronous, you will have better luck in calling both of them in order using RxJS pipeable operators:, such as switchMap:
this.authService.getRoles()
  .pipe(
    switchMap((data) => {
      this.roles=data;
      return this.authService.getMenu(this.role)
    })
  ).subscribe((data) => {
     this.menu=data;
  });

This will ensure that the observables from getRoles() is returned, before getMenu() is triggered.

A: just use forJoin:
import { delay } from 'rxjs/operators';
import {forkJoin,of} from 'rxjs';
const example = forkJoin(
  of('Hello'),
  of('World').pipe(delay(1000))
);
const subscribe = example.subscribe(val => console.log(val));

learn more about rxjs and Subscriptions


text:
Q: OR criteria Grails nested objects I'm trying to use createCriteria with OR on two nested objects.
This is the code I'm working with:
or {
  ordersSecondaryReceptionSystem {
    eq('code', params.receptionSystemCode)
  }
  ordersReceptionSystem {
    eq('code', params.receptionSystemCode)
  }
}

Only one of the two are being taken into account, the secondary one.
Is there something I'm missing?

A: I was able to fix it by creating an Alias:
createAlias('ordersReceptionSystem', 'ordersReceptionSystem', Criteria.LEFT_JOIN)
                    createAlias('ordersSecondaryReceptionSystem', 'ordersSecondaryReceptionSystem', Criteria.LEFT_JOIN)
                    or {
                        eq('ordersReceptionSystem.code', params.receptionSystemCode)
                        eq('ordersSecondaryReceptionSystem.code', params.receptionSystemCode)
                    }


text:
Q: Android SDK IDE configuration (cannot highlight all instances of a variable) In the Android SDK IDE, in the code view, if we bring the typing pointer at the location of a  variable, all the other references to that variable gets highlighted, as shown

For some reason, this has stopped happening in my computer. It was enabled by default before, but suddenly it stopped happing, and I have no idea what caused it. If I hover the mouse pointer over a variable or class name it just shows the tooltip window, and if I bring the typing pointer at the variable's location then nothing happens. What is the name for this highlighting feature, and how do I re-enable it?
Incidentally, how do I view my android sdk version? The About ADT button says Build v22.0.1-685705, but the question tags here only show sdk2.1, 2.2 and 2.3, so i'm sure it hasn't reached version 22 yet. Or does this mean I have version 2.2?

A: In Eclipse, you can turn this (search highlighting) on or off by using the "Toggle Mark Occurrences (Alt + Shift + O). Visually, the control button for this looks like a yellow highlighter.
As for "SDK Version"... in Eclipse, go to Window > Android SDK Manager.
This opens up a window with several details related to your SDK version and supported libraries, files, etc. Near the top, you should see Tools > Android SDK Tools. Your version might be 22.0.5 (as an example). This is the SDK Tools revision number. You should keep it up-to-date periodically throughout the year (check monthly if you wish).
The SDK Tools version number (22.0.5) does not mean "2.2" - this 2.2 number refers to the Android API version..
Please see this google link for a correlation between SDK Version and API version. The AndroidManifest calls it "minSdkVersion" so i can see where this can be confusing.


text:
Q: SubstringIndex::$value undefined property - can't use in DATEADD The following query works
SELECT
   DATE_ADD(CURRENT_TIMESTAMP(), 1, 'DAY')
FROM table;

/* */
SELECT
   DATE_ADD(CURRENT_TIMESTAMP(), SUBSTRING_INDEX(column, ' ', 1), 'DAY')
FROM table;

However, this one not:
SELECT
   DATE_ADD(CURRENT_TIMESTAMP(), 1, SUBSTRING_INDEX(column, ' ', -1))
FROM table;

Column property contains 1 MONTH which should be passed to DATE_ADD to modify the date, but the third argument of DATE_ADD SUBSTRING_INDEX(column, ' ', -1) throws the following error in Doctrine:
Notice: Undefined property: DoctrineExtensions\Query\Mysql\SubstringIndex::$value
The code above is plain SQL so here's how I have it in Doctrine:
->andWhere("createdAt > DATE_ADD(CURRENT_TIMESTAMP(), SUBSTRING_INDEX(column, ' ', 1), SUBSTRING_INDEX(column, ' ', -1))")

Does it mean it cannot be written like this?


text:
Q: Check which deno "allow" flags are enabled / disabled from within script Deno.args gives access to all the args ($@) after the executed file.
Is it possible to get the flags passed into Deno before that? I am interested in detecting within the script if something like --allow-run is true or false and depending on that give a better err message to the user.

A: You have to use Deno.permissions which is currently an unstable API. So the --unstable flag is required.
const { state } = await Deno.permissions.query({ name: "env" });

if(state !== 'granted')
  console.log(`Can't access env variables`)

For checking whether --allow-run is on or not you'll have to use:
const { state } = await Deno.permissions.query({ name: 'run' });

console.log(state);

name can be one of:

*

*run

*read

*write

*net

*env

*plugin

*hrtime


text:
Q: Xamarin Image usage for iOS , Android and PCL I am confused about the usage of images in Xamarin. For iOS images I am using sampleimage@2x.png. How does the image sizes relate to Android? I know Android doesn't like @2x in the image name. If I am skipping @2x and use sampleimage.png for Android then what common image name should I be using in PCL project.

A: If you have an image named as icon_detail.
In resources file of ios project you should add three different sizes of this icon_detail image.
For example
first icon: 25*25 sizes => icon_detail.png
second icon: 50*50 sizes => icon_detail@2x.png
third icon: 75*75 sizes => icon_detail@3x.png
In android it is a little bit different
You should add icons with same name but different sizes.
For example
first icon : 25*25 sizes => icon_detail.png to drawable-hdpi file under resources
second icon : 50*50 sizes => icon_detail.png to drawable-xhdpi file under resources
third icon : 75*75 sizes => icon_detail.png to drawable-xxhdpi file under resources


text:
Q: Cannot save scikit-learn model using joblib? I have the Ensemble model that combines both tensorflow and scikit-learn. And I would like to save this Ensemble model as a box to feed data in and generate the output. My code is as below
def model_base_LSTM(***):
   ***
model = model_base_LSTM(***)
ensem_model = BaggingRegressor(base_estimator=model, n_estimators=15)
ensem_model.fit(x_train, y_train)
bag_mod_pred = ensem_model.predict(x_test_bag)

from joblib import dump, load
dump(ensem_model, 'LSTM_Ensemble.joblib')

TypeError: can't pickle _thread._local objects

So, how to solve this problem??

A: You can save your TensorFlow (and even PyTorch) models with Scikit-Learn, but only if you use Neuraxle and its saving mechanics.
Neuraxle is an extension of Scikit-Learn to make it more compatible with all deep learning libraries.

The trick is performed by using Neuraxle-TensorFlow or Neuraxle-PyTorch.

Why so?
Using one of Neuraxle-TensorFlow or Neuraxle-PyTorch will provide you with a saver to allow your thing to be serialized correctly. You want it to be serialized correctly to be able to ensure compatibility between scikit-learn and your Deep Learning framework when it comes time to save or parallelize things and so forth. You can read how Neuraxle solves this with savers here.
Code Examples
Here is a full project example from A to Z where TensorFlow is used with Neuraxle as if it was used with Scikit-Learn.
Here is another practical example where TensorFlow is used within a scikit-learn-like pipeline


text:
Q: Aptana Studio 3 as plugin fails to startup on Ubuntu 12.04 I have installed Eclipse 3.7.2 via PPA and subsequently I have clicked on Add New Software and the link to 64Bit Aptana studio 3.
It found the plugin and installed it correctly.
Now when I startup the Eclipse I get this error:
An internal error has occurred.
No more handlesNative code library failed to load. (java.lang.UnsatisfiedLinkError: /home/xxx/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/com.aptana.swt.webkitbrowser.linux.x86_64_1.0.0.1295409059/os/linux/x86_64/libcefjni.so: libjpeg.so.62: cannot open shared object file: No such file or directory)

Any idea please?
Update:
Seems to be the Java version:
!SESSION 2012-04-30 07:48:06.985 -----------------------------------------------
eclipse.buildId=I20110613-1736
java.version=1.7.0_04
java.vendor=Oracle Corporation
BootLoader constants: OS=linux, ARCH=x86_64, WS=gtk, NL=en_GB
Command-line arguments:  -os linux -ws gtk -arch x86_64

!ENTRY org.eclipse.osgi 4 0 2012-04-30 07:48:07.951
!MESSAGE Application error
!STACK 1
java.lang.UnsatisfiedLinkError: Could not load SWT library. Reasons:
        no swt-gtk-3740 in java.library.path
        no swt-gtk in java.library.path
        Can't load library: /home/xxx/.swt/lib/linux/x86_64/libswt-gtk-3740.so
        Can't load library: /home/xxx/.swt/lib/linux/x86_64/libswt-gtk.so

        at org.eclipse.swt.internal.Library.loadLibrary(Library.java:285)
        at org.eclipse.swt.internal.Library.loadLibrary(Library.java:194)
        at org.eclipse.swt.internal.C.<clinit>(C.java:21)
        at org.eclipse.swt.internal.Converter.wcsToMbcs(Converter.java:63)
        at org.eclipse.swt.internal.Converter.wcsToMbcs(Converter.java:54)
        at org.eclipse.swt.widgets.Display.<clinit>(Display.java:132)
        at org.eclipse.ui.internal.Workbench.createDisplay(Workbench.java:695)
        at org.eclipse.ui.PlatformUI.createDisplay(PlatformUI.java:161)

A: I found the solution here:
http://www.samclarke.com/2012/04/how-to-install-aptana-studio-3-on-ubuntu-12-04-lts-precise-pangolin/

A: Have you consider using aptana as standalone version? I Use aptana every day and there's no conflict at all with my Ubuntu 12.04.
Consider asking in the official Support page:
Aptana | Support
Or see if is that is a current bug.
I hope you find a solution (:

A: This might be the same problem: https://stackoverflow.com/a/10482634/207791

I had same problem with Oracle Java 7 and Eclipse on 32-bit system.
libswt-gtk-3.6-java and libswt-gtk-3.6-jni were already installed.
  What helped:
cd ~/.swt/lib/linux/x86
ln -s /usr/lib/jni/* .

Maybe this can be done reconfiguring Java alternatives or what.


text:
Q: How to get total items count in specific index of List? I have used retrofit 2 for request data from API and have some JSON response format like below.
{
     result: [
        {
           kolom1: "PI 0",
           kolom2: "PV 0",
           kolom3: "TP 0",
           kolom4: "10",
           kolom5: "20",
           kolom6: "30",
           kolom7: "FK 0",
           kolom8: "CA 0"
        },
        {
           kolom1: "PI 1",
           kolom2: "PV 1",
           kolom3: "TP 1",
           kolom4: "10",
           kolom5: "20",
    }

This is my model class.
public class DetailKPIModel {
    private String kolom1, kolom2, kolom3, kolom4, kolom5, kolom6, kolom7, kolom8;

    public String getKolom1() {
        return kolom1;
    }
}

This is my response model class.
public class ResponseModel {
    private List<DetailKPIModel> resultDetail;

    public List<DetailKPIModel> getResultDetail() {
        return resultDetail;
    }
}

This is my onResponse method.
@Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
   //get total items in result index 0
}

I want to know size of

response.body().getResultDetail().get(0)

How to get total of items in every index of result?
My expected results are like these:

*

*Total result index 0 is 8

*Total result index 1 is 5

A: try this way on your model class
    public class DetailKPIModel {
            private String kolom1, kolom2, kolom3, kolom4, kolom5, kolom6, kolom7, kolom8;

            public String getKolom1() {
                return kolom1;
            }

            public int getCount(String value){
                int count =0;
                if(value.equalsIgnoreCase(kolom1.substring(kolom1.length()-1))){
                    count++;
                }
                .
                .
                .

                if(value.equalsIgnoreCase(kolom8.substring(kolom8.length()-1))){
                    count++;
                }
return count;
            }
        }

pass the value 0 or 1 in getCount() method


text:
Q: JavaScript / jQuery problem on Internet Explorer 7 I have a simple HTML page that looks like this:
...

    Click here!

...

I have a piece of jQuery JavaScript in the header that looks like this:

When I click the HTML link in FireFox then I get an alert that says 'Hello!'. Why does this not work in IE7/8?
When I look at the (dynamically) build DOM in IE then I can see the onmouseup is present but it is never called. I have tried replacing onmouseup with onclick - same problem...

A: You shouldn't be using the JavaScript pseudo protocol for anything.
This should work:
function DoHello()
{
    $("div#main a")
        .text("Click here!")
        .mouseup(function(){
             alert('Hello!');
        });
}

A: Don't use expando events, use jQuery!
$("div#main a").mouseup(function(){ alert('Hello!') });

A: instead of adding the onmouseup event like that why dont you just use the jQuery method like so:
$("div#main a").mouseup(function() {
   alert("hello");
});

should work :) for more info check out - http://docs.jquery.com/Events/mouseup

A: You should use the bind function like this:
function DoHello(){
$("div#main a").bind("mouseup", function(e){
    alert("Hello!");
});
}


text:
Q: What is the relationship between OpenId Connect and IdentityServer and Identity? I am confused with AspNetCore Identity,OpenId Connect and IdentityServer4. What is the relationship between them,and what is the suitable occasion for each of them?

A: *

*OpenID Connect is a specification (an authentication protocol).

*IdentityServer4 is an implementation of an OpenID Connect provider (server-side)

*ASP.NET Core Identity is a user-management library (over a database). It can be used by an ASP.NET Core application to create users, verify password etc.

OpenID Connect providers using IdentityServer4 are ASP.NET Core applications, so they can use ASP.NET Core Identity to authenticate users on the login page.