text:
Q: angularjs defining values with different functions I have this small issue where I am calling a service method in one function, and then trying to use the values from that function in another function (Both functions are in the same controller).
But when calling the values it says they are undefined.
the bottom coding is basically what I want to achieve not my real coding.
app.controller('Ctrl', function($scope)
{
     $scope.a = function()            // a function calling service data
     {
       $scope.value1 = array[];       //array[] list of all data called
       console.log(value[0].item1);   // value is defined
     }

     $scope.b = funtion(value1)
     {
       console.log(value1[0].item1);  // returns undefined
     }
)};

As shown in function a the value is defined but not in function b how do I keep the same value of item1 when calling it from another function?

A: Do  $scope.value[0].item1
since the array value is in the $scope


text:
Q: FastCGI sent in stderr primary script unknown while reading response header from upstream I have in nginx.conf
upstream php-fpm7.0
{
    server unix:/run/php-fpm/php7.sock;
}

I have in conf.d/default.conf
location ~ \.php$ {
    include php-fpm;
}

I have in php-fpm
fastcgi_pass    php-fpm7.0;
include fastcgi_params;
fastcgi_param   SCRIPT_FILENAME         $document_root$fastcgi_script_name;
set             $path_info              $fastcgi_path_info;
fastcgi_param   PATH_INFO               $path_info;
# Additional variables
fastcgi_index   index.php;

But i get error 404.
When i comment
#location ~ \.php$ {
#    include php-fpm;
#}

files are available
Error even if
location ~ \.php$ {
    fastcgi_pass unix:/run/php-fpm/php7.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

FastCGI sent in stderr: "Primary script unknown" while reading
  response header from upstream

The same error if not using socket:
fastcgi_pass 127.0.0.1:9000;

Centos 7
Update 1.
After i used:
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_param SCRIPT $fastcgi_script_name;
fastcgi_param FOLDER $document_root;
fastcgi_param FOLDER_SCRIPT $document_root$fastcgi_script_name;

I got $_SERVER['SCRIPT'] /index.php
and $_SERVER['FOLDER'] /home/www/m-a-x/www
and $_SERVER['FOLDER_SCRIPT'] /home/www/m-a-x/www/index.php
When i back
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

all works.
Mystery.

A: You can always check nginx variables by adding them to return statement, for example:
location / {
    return 200 $document_root$fastcgi_script_name;
}

*

*Open the URL, a file will be downloaded, file will contain variables
returned by nginx. For example /srv/www/index.php

*Check that nginx/php-fpm user group has access to the file:
sudo -u www stat /srv/www/index.php

*Set permissions to read and execute the files for the www user group all along the path.
chmod g+x /srv
chmod g+x /srv/www
chmod g+x /srv/www/index.php

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the purpose of ccall and cwarp functions in Emscripten? I'm following the instructions from the Emscripten documentation here, and I want to practice with minimal examples. My final goal is to create a C++ library, compile it to a single wasm binary file and then use these compiled methods in pure-frontend web application.
I do not understand what is the purpose of calling C++ methods with "ccall" when you can just instatiate them directly from "Module". For example, I can use Module._doubleNumber(9);, which is shorter than Module.ccall('doubleNumber','number', ['number'], [9]);.
Whats the difference between calling one or another?
Here is the complete code:
extern "C" {
    int doubleNumber( int x ) {
        int res = 2*x;
        return res;
    }
}

Compiled with
emcc main.cpp -o main.js -sEXPORTED_FUNCTIONS=_doubleNumber -sEXPORTED_RUNTIME_METHODS=ccall

I'm using a simple html document to test results:
<html>
<head>
    <meta charset="utf-8">
    <title>WASM Demo</title>
</head>
<body>
    <script type="text/javascript" src="main.js"></script>
    <script type="text/javascript">
        Module.ccall('doubleNumber','number', ['number'], [9]); // 18
        Module._doubleNumber(9); // 18
    </script>
</body>
</html>

A: There is no difference in such the tiny example. There might be issues in big projects.

*

*Less important. Module.ccall can perform async call with the parameter async=true, whereas call to the exported function Module._doubleNumber is always sync.

*More important. At higher optimisation levels (-O2 and above), the closure compiler runs and minifies (changes) function names. A minified name for _doubleNumber will be changed to another name, usually unpredictable one, and Module._doubleNumber will be undefined.

*-sEXPORTED_FUNCTIONS=_doubleNumber prevents name minifying and can be used for small C libraries. A big C library would require a ton of items listed in EXPORTED_FUNCTIONS, and you shall take into account the limited command line length.


text:
Q: Using wildcard in Gradle Files then copy if it exists In very brief, I want to find all files that ends with *.sql and copy them if they exist.
There might be 0 or more files in etc directory.
    File sqlfiles = file('etc/' + '*.sql')
    logger.info("Looking for SQL files: " + sqlfiles);
    if (sqlfiles.exists())
    {
        logger.info("Found log SQL file: " + sqlfiles);

        copy
                {
                    from sqlfiles
                    into "$rpmStoredir"
                }
    }
    else
    {
        logger.warn("No SQL file found - skipping");
    }

With my code, the wildcard is not working here.
So adding "include" to the copy as in the below is working but I just want to figure how to add a logger if the file does not exist
copy
{
    from "etc/"
    include "*.sql"
    into "$rpmStoredir"
}

A: file(...) is the wrong method to use as this returns a single java.io.File
You could do something like
FileTree myTree = fileTree('etc') {
   include '*.sql'
}
if (myTree.empty) {
  ...
} else {
   copy {
      from myTree
      ...
   }
}

See Project.fileTree(Object, Closure) and FileTree


text:
Q: Watch xml sent to jasper report I'm using JasperReports and iReport to constructing some reports.
I'm trying to see what parameters are sent so I could use them in order to make the report more dynamic.
For example,  if a report is produced to Excel (and I'm sure there's a parameter in the xml for that) I will create a print expression not to show pages' numbers,  and if produced to pdf, it will print page numbers.
Any help?  Thanks in advance
PS:  I tried debugging to see what xml is produced but it's made on a web service which I cant see.

A: I would say that there isn't anything in the XML file generated regarding the format you want to export to. The difference is that when you export to one format or another you use different classes/methods.
Anyway, if you want to show content depending on the output format, why don't you create your own parameter telling the report which output format will you be using?

A: I don't think you can change report options after the report filling is done and the jasperprint object is made. The parameters are set before filling the report.

For example, if a report is produced to Excel (and I'm sure there's a
  parameter in the xml for that) I will create a print expression not to
  show pages' numbers, and if produced to pdf, it will print page
  numbers.

If you add another text/static field over your page number text field. That is if they overlap .Then the page number won't appear when you export to xls or any grid based export .But it will appear in pdf or in any non-grid based export .


text:
Q: Как изменить пример ответа в Swagger UI? Как изменить пример ответа для поля типа Decimal с 0 на 0,00 в Swagger UI? Пробовал вот это решение, но не получилось. Также отображает 0.

A: Сформировал ответ на основании помощи @EvgeniyZ (накидываем ему респектов выше):
public class DecimalSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (context.Type == typeof(decimal))
            schema.Example = new OpenApiDouble(0.01d);
    }
}

И в настройке свагера добавляем:
services.AddSwaggerGen(c =>
{
    c.SchemaFilter<DecimalSchemaFilter>();
});


text:
Q: Pass another control as property value in XAML Consider a XAML snippet like this:
<Grid>
    <Button x:Name="myButton"/>
    <m:MyControl Button="myButton"/>
</Grid>

Of course this doesn't work. But what I need is to pass the Button control instance named "myButton" as value to the other control's Button property. I've also tried it with {StaticResource myButton} but it fails telling me that the resource cannot be found.
What's the correct XAML syntax for that?

A: If MyControl.Button is a DependencyProperty you can do it so
<m:MyControl Button="{Binding ElementName=myButton}" />


text:
Q: Sparseness for a matrix I would like to define a function $f$ whose range is $[0,1]$ such that it takes a matrix $C \in R_+$ of dimension $m \times n$. The entries in the matrices are also in the range $[0,1]$. In addition, each row of $C$ sums to $1$.
The function $f$ should produce $0$ when all the entries in the matrix $C$ are same and produce $1$ when there is only one $1$ entry in each row.
For example,when
C = [1 0 0 0
     0 0 1 0
     0 0 0 1
     0 1 0 0]

$f(C) = 1$
In other case, when
C = [0.25 0.25 0.25 0.25
     0.25 0.25 0.25 0.25
     0.25 0.25 0.25 0.25
     0.25 0.25 0.25 0.25]

$f(C) = 0$
Can anyone help me out in contructing such a function?

A: Let $R_i$ be the maximum value in row $i$ less the minimum value in that row, and put $f = (R_1 + ..R_n)/n$.

A: Let the matrix have the form
$$
\begin{pmatrix}
  p_{1,1} & \ldots & p_{1,n}  \\
  \vdots & \ddots & \vdots  \\
  p_{n,1} & \ldots & p_{n,n}
\end{pmatrix}
.
$$
I would approach this problem in the following way:
Since $\sum_{i=1}^np_{k,i}=1$ for all $k$, each of the matrix rows can be thought of as a probability distribution.
The almost canonical characterisation of a probability distribution is its Shannon entropy
$$
  H_k = -\sum_ip_{k,i}\cdot\ln(p_{k,i})
$$
where summands with $p_{k,i}=0$ are left out.
This is known to be highest when $p_{k,i}=p_{k,j}\equiv p_k=\tfrac1n$, and lowest when $p_{k,i}=0$ save for one $i$. Namely,
$$
  \bigl.H_k\bigr|_{p_{k,i}=p_{k,j}}
  = -\sum_ip_{k}\cdot\ln(p_{k})
  = -n\cdot p_{k}\cdot\ln(p_{k})
  = -n\cdot \tfrac1n\cdot\ln(\tfrac1n)
  = -\ln(\tfrac1n)
  = \ln(n)
$$
and
$$
  \bigl.H_k\bigr|_{p_{k,i}=0\ \forall i\neq j}
  = -0 - \ldots - p_{k,j}\ln (p_{k,j}) - \ldots -0
  = -1\cdot \ln(1)
  = 0
$$
We can now define a "total entropy" of the matrix,
$$
  H := -\sum_{k}\sum_{i}p_{k,i}\cdot\ln(p_{k,i})
$$
This will now be $n\ln(n)$ for the matrix with all-equal entries, and $0$ for a matrix with only-$0$-and-$1$-entries. To get a value in your desired range, just do an affine transformation
$$
  f:= 1-\frac{H}{n\ln(n)}
  = 1 + \sum_{k,i}\frac{p_{k,i}\ln(p_{k,i})}{n\cdot\ln(n)}
$$


text:
Q: memory consumption in deb9 vs deb10 In the below c++ program I am trying to divide a bigger memory block into smaller subblock by moving pointers by 1 page. While creating a subblock I am initializing the variable of a structure which is of 64 bits. I tried to run this code on debian10 and debian9. What I observed is in deb9 only 64 bits memory is consumed but  deb10 consumes the entire page which is off 4K.
Can someone help me understand what causes this difference? Can this be related to the way the kernel handles the memory? Thanks for your help in advance.
#include <vector>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

using namespace std;

typedef unsigned char u8;
typedef unsigned int u32;
typedef unsigned long long u64;

struct e{
   u8* f;
   u64* s;
};
struct se{
   u64 cid;
   void* np;
};
const u64 a = -1;
u32 subchunk = 2878;
u32 subchunkperchunk = 140;
u32 chunksize = 1028096;   //in bytes
u32 TSize = 4096;
u32 eleOfChunk = 50;
u32 eSize = 4096;
u64 x;
vector<e> v;
int it=0;

u64& add(const void* ep)
{
    void* subChunkPtr = (void*) (((u64)ep) / chunksize * chunksize);
    u64 firstElementLocation = ((u64)subChunkPtr) + TSize;
    u32 indexInsideSubChunk = (((u64)ep)-firstElementLocation) / eSize;
    se* elePtr = ((se*)subChunkPtr) + indexInsideSubChunk;
    return elePtr->cid;
}

int main()
{
    int file = open("Result", O_CREAT|O_WRONLY, S_IRWXU);
    dup2(file, 1);
    for (u32 i=0; i<= subchunk/subchunkperchunk; i++)
    {
      u32 eleInCurrChunk;
      if (i != subchunk/subchunkperchunk)
      {
         eleInCurrChunk = subchunkperchunk;
      }
      else
      {
         eleInCurrChunk = subchunk % subchunkperchunk;
         if (eleInCurrChunk == 0)
         {
            break;
         }
      }
      u32 CSize = (eleInCurrChunk+1) * chunksize;
      u8* sp;
      sp = new u8[CSize];
      u8* ssp = sp + (chunksize - ((u64)sp % chunksize));
      for (u32 j = 0; j < eleInCurrChunk; ++j)    //creat block
      {
         u8* scp = ssp + j * chunksize;
         u8* ep = scp + TSize;
         for (u32 k=0; k < eleOfChunk ; ++k)   //creat subblock
         {
             v.push_back(e());
             v[it].f = ep;
             v[it].s = &add(ep);
             add(ep)= a;               //set the 64 bits to high
             ep += eSize;
             ++it;
        }
        system("free -m");
      }
    }
  return 0;
}

Below is the output of the code on deb10
              total        used        free      shared  buff/cache   available
Mem:    7914        1789        4306           0        1819        5826
Swap:         0           0           0
              total        used        free      shared  buff/cache   available
Mem:    7914        1789        4306           0        1819        5826
Swap:         0           0           0
              total        used        free      shared  buff/cache   available
Mem:    7914        1791        4304           0        1819        5824
Swap:         0           0           0
              total        used        free      shared  buff/cache   available
Mem:   7914        1791        4304           0        1819        5824
Swap:        0           0           0
              total        used        free      shared  buff/cache   available
Mem:     7914        1793        4302           0        1819        5822
Swap:         0           0           0
              total        used        free      shared  buff/cache   available
Mem:    7914        1793        4302           0        1819        5822
Swap:         0           0           0
              total        used        free      shared  buff/cache   available
Mem:   7914        1795        4300           0        1819        5820
Swap:         0           0           0
.
.
.
Mem:       7914        4592        1502           0        1819        3022
Swap:           0           0           0
              total        used        free      shared  buff/cache   available
Mem:   7914        4594        1500           0        1819        3020
Swap:       0           0           0
              total        used        free      shared  buff/cache   available
Mem:    7914        4594        1501           0        1819        3021
Swap:        0           0           0
              total        used        free      shared  buff/cache   available
Mem:    7914        4596        1499           0        1819        3019
Swap:        0           0           0
              total        used        free      shared  buff/cache   available
Mem:     7914        4596        1499           0        1819        3019
Swap:           0           0           0
              total        used        free      shared  buff/cache   available
Mem:    7914        4598        1497           0        1819        3017
Swap:         0           0           0

If you check the memory usage on "used"  it is consuming ~4.5G by the end of the iteration.

Below is the output of the code on deb9.
              total        used        free      shared  buff/cache   available
Mem:   7923        1843        4128           4        1951        5776
Swap:       0           0           0
              total        used        free      shared  buff/cache   available
Mem:   7923        1843        4128           4        1951        5776
Swap:       0           0           0
              total        used        free      shared  buff/cache   available
Mem:   7923        1843        4128           4        1951        5776
Swap:        0           0           0
              total        used        free      shared  buff/cache   available
Mem:    7923        1843        4128           4        1951        5776
Swap:         0           0           0
              total        used        free      shared  buff/cache   available
Mem:     7923        1843        4128           4        1951        5776
Swap:          0           0           0
.
.
.

              total        used        free      shared  buff/cache   available
Mem:    7923        1870        4101           4        1952        5750
Swap:         0           0           0
              total        used        free      shared  buff/cache   available
Mem:    7923        1870        4101           4        1952        5750
Swap:         0           0           0
              total        used        free      shared  buff/cache   available
Mem:   7923        1870        4100           4        1952        5750
Swap:        0           0           0
              total        used        free      shared  buff/cache   available
Mem:     7923        1870        4100           4        1952        5750
Swap:         0           0           0
              total        used        free      shared  buff/cache   available
Mem:    7923        1870        4101           4        1952        5750
Swap:       0           0           0
              total        used        free      shared  buff/cache   available
Mem:     7923        1870        4100           4        1952        5750
Swap:         0           0           0

By the end of the iteration it is consuming ~1.8G
As we see from the output  there is a huge memory consumption difference between deb9 and deb10. I would like to know why this is different, when the same code runs on different Debian machines (i.e. deb9 and deb10).


text:
Q: Model Schema for vertices and edges How to validate graph (vertices and edges) data like what happens in OrientDB?
For example,
If my graph has vertices/edges of format
{
    "name": :any_name,
    "age" : 13
}

How can I associate it with a well defined schema (with validations)?
In OrientDB, there is feature of storing data in vertices and edges also and each of the schemas are well defined. How can I do this in arangoDB?

A: "Out-of-the-box" ArangoDB does not support schema enforcement. Clearly that is potentially a signficant drawback in some use-cases.
However, Max Neunhöffer of ArangoDB argues that with a bit of work, one can switch off the standard database API, leaving an ArangoDB-based system that does enforce schemas:

Therefore, ArangoDB can then be turned into a strict schema-enforcing persistence engine, because its HTTP API can be extended by user code written in JavaScript that is executed in the database server with direct access to the data. One can gradually evolve the way the data store is used by client code and move it slowly over to special, user defined routes that enforce the by now stable database schema, in particular for the write operations. As a consequence, a lot of client code can be simplified, because suddenly one can rely on a strict schema that is enforced by the API, once all write operations are covered.
In the end, when one has customized the whole API for the app, one can even switch off the standard database API, which further increases security and cleanliness. With this final step one has arrived at a software architecture that implements data-centric microservices in an application-specific way directly in the database server, which is good against bugs, good for performance (complex queries can be run close to the data), good for the simplicity of the application design and good for maintainability. Even the devops like this because the microservices can be deployed and updated independently.

https://www.arangodb.com/2015/03/agile-development-vs-schema-enforcement


text:
Q: Application getting VERY slow only in the morning: tools to track the culprit? I have two Ubuntu Servers: one acting as db server (mysql) and file server and the application server.
Using this three service an application has been working flawlessly for months.
Now we've found out that around 7:45 EVERY morning it really slows down.
After an hour everything becomes fast again and usable without human intervention.
I'm trying to track down the problem...
Is there any kind of tool to monitor and log cpu, ram, disk, network usage?
How should I proceed to find the problem quickly?

A:
Is there any kind of tool to monitor and log cpu, ram, disk, network usage?

You would not believe the number of tools available. The ones I use are Nagios, sar, iotop, top, ps, mrtg, and a load of custom scripts. But they are just going to tell you how slow the system is - not why it is slow.
There are all sorts of reasons it could be slow - both stuff happening on the machine (e.g. backups causing a cache flush, batch processing stealing CPU cycles...), stuff happenning elsewhere (network congestion, shift in the majority of traffic from local to overseas) not to mention an absence of stuff which happens when the system is running quickly (low levels of traffic can cause things like loss of caching, early evacuation of connections from badly configured stateful firewalls).

A: Quick fix would be to isolate the problem and find the culprit.
Check what cronjobs are running at that time and reschedule them to the different time.
If you can afford it, disable networking during that time.
If issue still persists, shutdown all services that are not needed.
Proper way would be to look at the data that you have already collected as part of the process.As said already, there is a myriad of option on how to do it.We use Cacti graphing system as this gives nice visual representation and you can graph virtually anything.

A: I find sar is good at pointing out likely causes of slowness.  Install the atsar package on both systems.  After it has been running for a day you should have data to see which resources are being used heavily when the system is slow.  Data will be collected in /var/log/atsar which will eventually have 31 daily files.  This is a great tool for examining load issues.
I find munin to be a good tool for overall monitoring of servers.  I try not to run the munin server on a system which might get overloaded.  In your case you would want a third host to act as the server.  munin gathers data from each client every five minutes.  This data is then transformed into graphs.   It is fairly easy to see from the graphs which resource has the heaviest load.  That can help speed up then investigation with sar.
For a quick test, just log on to each server and run top during the problem period.  It helps to have run it earlier to know what the normal load looks like.  If your load average exceeds the number of cores on the server for a long period of time, you have likely identified the server which is causing the slow down.   The top lines can be used to identify if it is CPU (high user%) or some other resource (high system% or high wait%).  You also get a view of memory utilization.
The process accounting package acct can tell you which process(es) are completing during the period.  You will need to run accton on to enable process accounting.  The command dump-acct can be run to dump the data in a readable format.  man dump-acct includes information on the format of the output.  You likely want processes that start around 7:45.


text:
Q: Visual Studio tool for managing Entity Framework migrations? Is there a Visual Studio tool or GUI extension for managing Entity Framework migrations, rather than having to type repetitive commands into the Package Manager console.
I'm looking for something that will save me time, and save me from having to remember all of the commands and their options.
(Example of the commands I'm referring to:
http://msdn.microsoft.com/en-gb/data/jj591621.aspx)


text:
Q: Function declaration as if statement condition Several days ago I was trying to declare a function inside an if() statement, and I tried doing it in many ways but did not manage to achieve this.
Is it possible to do something like this?
if(!function() { return false; }) {
    console.log("False");
} else {
    console.log("True");
}

A: You can... you just need to execute it as well.  Lookup IIFE for more information on this.

if (!(function() { return false;}())) {
  console.log("False");
} else {
  console.log("True");
}

The form a function expression takes is function(){}.  To invoke the expression when its declared you must change the format to (function(){}())

A: NOTE: This solution don't work!
This will work:

if((function() { return false; }) !== true) {
  console.log("False");
} else {
  console.log("True");
}


text:
Q: LIS on two arrays I feel lost on how to approach this question,
Given two integer array of size
,
, I want to merge these two arrays into one such that order of element in each array doesn't change and size of their Longest Increasing Subsequence become maximum.
Once we choose an element of A or B, we cannot choose an earlier element of that sequence
My goal is to find maximum possible length of longest increasing subsequence.
This is what I have so far:
def sequences(a, b, start_index=0, min_val=None):
    limits = a[start_index], b[start_index]
    lower = min(limits)
    higher = max(limits)
    if min_val is not None and min_val > lower:
        lower = min_val
    options = range(lower, higher + 1)
    is_last = start_index == len(a) - 1
    for val in options:
        if is_last:
            yield [val]
        else:
            for seq in sequences(a, b, start_index+1, min_val=val+1):
                yield [val, *seq]

for seq in sequences([1,3,1,6], [6,5,4,4]):
    print(seq)

However, this results in: [1, 3, 4, 5], [1, 3, 4, 6], [2, 3, 4, 5], [2, 3, 4, 6].
The expected output should be:
array1: [1,3,1,6]
array2: [6,5,4,4]
We take 1(from array1), 3(from array1), 4(from array2), 6(from array1)

Giving us LIS: [1,3,4,6].
We got this by not choosing an earlier element from a sequence once we are at a certain value.

How do I stop it from unwanted recursion?


text:
Q: What tools are out there for an Intranet search engine across a diverse toolset? Basic requirements:

*

*Should be able to index things like MediaWiki, Confluence, Sharepoint, GitHub:Enterprise, Askbot

*Should be reasonably smart about de-duping results (one reason Confluence search is so painful).

*Should definitely incorporate heuristics like how many pages link to a document, whether the search terms are in the title of the document, etc.  If there's a way for users to downrank particular results, that might be a bonus.

*Should be somewhat tunable (e.g., prefer Confluence over Sharepoint, blacklist certain paths).

Are there off-the-shelf products that can do the above?  FOSS projects?  Are there FOSS projects that can provide the basics for the above and are easy to extend or build a frontend for?

A: You can try Apache Solr, it's a great tool.
According to the website:

Solr is the popular, blazing fast open source enterprise search
  platform from the Apache Lucene project. Its major features include
  powerful full-text search, hit highlighting, faceted search, near
  real-time indexing, dynamic clustering, database integration, rich
  document (e.g., Word, PDF) handling, and geospatial search. Solr is
  highly reliable, scalable and fault tolerant, providing distributed
  indexing, replication and load-balanced querying, automated failover
  and recovery, centralized configuration and more. Solr powers the
  search and navigation features of many of the world's largest internet
  sites.

A: You could try a bundled version of Solr and other tools such as OpenESP or Constellio. Expect to spend some time tuning the sources and imports. ManifoldCF which is bundled with OpenESP is an open source connector/crawler framework for plugging in connectors to various systems like those you describe, and several connectors come out of the box.

A: You can try Moogle. It is open source easily employable in windows with IIS. just  having look as google so you feel bit familiar with it. Try http://techstuff.smsjuju.com/intranet-search-engine/


text:
Q: Flash AS3: saving/loading the positions of all the children of a MovieClip I would like to know how to save and load the X and Y position of all the children of a MovieClip.
I have a project with a save and load button.
They save and load the X and Y position of the MovieClip's child.
save.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler3);

function fl_MouseClickHandler3(event:MouseEvent):void
{

var mySo:SharedObject = SharedObject.getLocal("SaveData");

mySo.data.my_x = mc2.x;
mySo.data.my_y = mc2.y;
mySo.flush();

}

loader.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler_2);

function fl_MouseClickHandler_2(event:MouseEvent):void
{

var mySo:SharedObject = SharedObject.getLocal("SaveData");

mc2.x = mySo.data.my_x;
mc2.y = mySo.data.my_y;

}

This however only saves and loads the last clicked MovieClip child.
How can I change it from only saving and loading the last clicked MovieClip child,
to saving and loading all the MovieClip children?

A: That will always save "mc2" positions, you will need to run a loop on numchildrens of the movieclip and put their positions in an array, and then access them in the same way. Here is a code example
import flash.display.MovieClip;

var mySo:SharedObject = SharedObject.getLocal("SaveData");
save.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler3);
loader.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler_2);

function fl_MouseClickHandler3(event:MouseEvent):void
{
    var clippositions:Array = new Array();
    var child:MovieClip;
    for(var i:uint=0; i<this.numChildren; i++)
    {
        if( this.getChildAt(i) is MovieClip )
        {
            child = this.getChildAt(i) as MovieClip;
            if(child)
            {
                clippositions.push( { clipname:child.name, my_x:child.x,my_y:child.y } );
            }
        }
    }
    mySo.data.clippositions = clippositions
    mySo.flush();
}

function fl_MouseClickHandler_2(event:MouseEvent):void
{
    var clippositions:Array = mySo.data.clippositions;
    if( clippositions != null )
    {
        var child:MovieClip;
        for(var i:uint=0; i<clippositions.length; i++)
        {
            if( this.getChildByName( clippositions[i].clipname ) is MovieClip )
            {
                child = this.getChildByName( clippositions[i].clipname ) as MovieClip;
                if(child)
                {
                    child.x = clippositions[i].my_x;
                    child.y = clippositions[i].my_y;
                }
            }
        }
   }
}


text:
Q: To change Browser's settings with c# code I m trying to do following with c# code.
1) Open Firefox Browser --->Tools--->Options--->In General Tab--->Downloads--->Always ask me where to save file.
I want to do this whole process in my application with c# code. I want that when download window opens , the radio button in "Always ask me where to save file" option gets checked automatically.
  I got the code from this site ..but that works only when firefox in not running. I m using the code in application and running that application in Firefox browser.
I have tried from various links , but all is in vain. Any help will be greatly rewarded. Thanxxx in advance..!!

A: If by "and running that application in Firefox browser" you mean you've written an ASP.NET web app, I highly doubt you're going to be able to do this. It would probably be considered a security flaw in Firefox if it allowed a web page to change this setting.

A: You could try modifying the code here. But that code will only run on your machine or in your own program that you can distribute. Like said in the other answer you will not be able to run this from the browser. This sounds like something that was done with ActiveX but that´s no longer supported by Firefox.


text:
Q: Oracle Employee constraint I'm still new in SQL and I'm kinda stuck. Here's my script :
CREATE TABLE Employee
         (SSN                 NUMBER          NOT NULL,
          FNAME               VARCHAR(8)     ,
          MINIT               VARCHAR(1)     ,
          LNAME               VARCHAR(7)     ,
          BDATE               DATE           ,
          SEX                 VARCHAR(1)     ,
          SALARY              NUMBER(8,2)    ,
          SUPERSSN            NUMBER         ,
          DNO                 NUMBER(2)      ,
CONSTRAINT Employee_PK PRIMARY KEY (SSN),
CONSTRAINT Employee_FK1 FOREIGN KEY (SUPERSSN) REFERENCES Employee(SSN));

INSERT INTO Employee  (SSN, FNAME, MINIT, LNAME, BDATE, SEX, SALARY, SUPERSSN, DNO)
VALUES  (123456789, 'John', 'B', 'Smith', '09-JAN-55', 'M', '30000', '333445555', '5');

COMMIT;
DESC Employee

As you can see, I'm trying to create a constraint for SUPERSSN > SSN but it always gives me  integrity constraint violated - parent key not found
When i remove CONSTRAINT Employee_FK1 FOREIGN KEY (SUPERSSN) REFERENCES Employee(SSN), it works perfectly.
But, if I keep it and remove the insert into employee script instead, it also works fine. So I'm not sure what I'm doing wrong.
I use Oracle.

A: When you want to add data on column that its a foreign key you have to make sure it is parent has data, for example the table SUPERSSN doesn't contain SSN 123456789 .
Insert a rescord where SSN = 123456789 and it will work.
I'll give you an example about 2 tables.

table FoodMarket contain Id and employer
And table sandwich contains column Id , Name and DateCreated

Now logically you cannot have a sandwich if it doesn't exist in the market, correct ? So we create on this table a foreign key on one column id
  alter table Sandwish add CONSTRAINT fk_column
    FOREIGN KEY (id)
    REFERENCES FoodMarket(id)

So if you want to insert a new sandwich, let's say hamburger, its id should exist in the market, if you insert in the sandwich table an in id = 10 but this value = 10 doesn't exist in the market, it will raise error, you should add first id 10 in the market to let you insert id =10 in table sandwiches.


text:
Q: Is it OK to ask an old question again? I need to ask something that has been asked before (not by me), but the answer was negative or there was no answer. The last question was 3 years ago, and it doesn't have an accepted answer.
After 3 years it is possible that a negative answer could become positive. But unless someone is actively looking for old no longer correct-answers those will remain outdated.
Would it be OK if I ask my question today although, technically speaking, there are existing duplicate questions already?
If not, is there a way to boost the attention on those old questions to see If I can get a new answer?


text:
Q: Implicit twirl parameter: Unspecified value parameter messages I am trying to use internationalization in twirl templates. I followed this guide: https://stackoverflow.com/a/30800825/1567737
I am having issues with the implicit messages: Messages. I have reduced my setup to the bare minimum on which the error occurs:

TestController

import javax.inject.Inject
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{Action, Controller}

class TestController @Inject()(val messagesApi: MessagesApi)
    extends Controller with I18nSupport {

  def index = Action {
    Ok(views.html.test.render())
  }

}

test.scala.html

@()(implicit messages: Messages)

I have also added routesGenerator := InjectedRoutesGenerator to my build.sbt.
This should be sufficient according to the docs and the guide I linked above. Still I get the following compile time error:
[error] app/controllers/TestController.scala:11: not enough arguments for method render: (messages: play.api.i18n.Messages)play.twirl.api.HtmlFormat.Appendable.
[error] Unspecified value parameter messages.
[error]     Ok(views.html.test.render())

*

*Play Version: 2.5.9

*SBT version: 0.13.11

*Scala version: 2.11.7

A: Well, apparently implicit parameters only work on the apply method. And not when you explicitly call render.
Ok(views.html.test.render())
Must be
Ok(views.html.test())


text:
Q: What is the difference between assign(x), eval(parse(text = "x")), get(x), and deparse(substitute(x))? In R, are the following sets of expressions functionally similar to one another?

*

*assign(x,y), and  eval(parse(text = "x"))  and  x=as.name("string")

*get(x), and   deparse(substitute(x))  and     ____ (x=as.string(object))?

*do.call("<-",list(x, y))
For example, can each of them be used in the following batch process?
## example data tables (requires data.table package I believe)
(dt1 <- data.table(urlteststatus = letters[1:24], urltest = letters[1:24], istest = letters[23:24] ) )
(dt2 <- data.table(istest = letters[2:2], urlteststatus = letters[1:10], urltest = paste0(letters[3:3], letters[1:10]) ) )

# list of variables to iterate over
tlist <- list("dt1","dt2")

# Batch process: This creates a new variable "x.2" which concatenates the the variables "urltest", "istest", and "urlteststatus".
for (x in tlist) {
  assign(paste0(x,".2"), mutate(assign(x, get(x)),
                            r_teststatus = paste(urltest,
                                                 istest,
                                                 urlteststatus)))
}

These examples are from: Convert string to a variable name, Adding data frames as list elements (using for loop), and
How to convert string to a dataframe name pandas/python.
PS: Frequently in the response, I see comments like "that's not a good way to do it, a more R-like way would be to. . ." but they usually don't have a link to what the more R-like way would be. Please explain or link to what the "right" way is, and why.

A: 1) assign is used to dynamically assign to a variable whose name is passed as a character string and get is used to dynamically retrieve a variable whose name is passed as a character string.
assign("x", 3)
x
## [1] 3

get("x")
## [1] 3

Thus if you have a character vector of strings representing variables we can iterate over them and produce derived variables containing the dimensions like this:
nms <- c("mtcars", "iris")
for(nm in nms) assign(paste0(nm, ".dims"), dim(get(nm)))
mtcars.dims
## [1] 32 11
iris.dims
##[1] 150 5

although normally we would create a list (or possibly a matrix in this case) rather than leaving them loose.
Map(function(nm) dim(get(nm)), nms)
## $mtcars
## [1] 32 11
##
## $iris
## [1] 150   5

or the following which gives the same result
Map(dim, mget(nms, inherits = TRUE))

2) deparse and substitute operate on expressions rather than character strings. deparse converts an expression to a character string.  substitute substitutes values into an expression.
deparse(quote(1+2))
## [1] "1 + 2"

substitute(y * y, list(y = 3))
3 * 3

3) do.call executes a function whose name is passed as a character string (or passed as a function object) and whose arguments are passed in a list.
do.call("sqrt", list(4))
## [1] 2


text:
Q: Is variable allocated on stack if i return before its declaration? Assume i have a function whose rough structure looks like this:
int aRecursiveFunction(const SomeLargeStructure *a, int x) {
    if (end recursion)
        return 0;
    // ...
    if (something that is mostly true)
        return aRecursiveFunction(a, x+1)+1;
    // ...
    SomeLargeStructure copy = *a;
    alter(&copy);
    return aRecursiveFunction(&copy, x);
}

What i need to know is, for performance reasons, whether the space for copy (which is a large structure) will be created on the stack in the 90 % of cases where the function ends before this point. Or does it actually not even matter? Does it depend on the compiler? Is it better to separate this part as another function?
Thanks.
EDIT: To clarify, sizeof(SomeLargeStructure) is around 500, it only has basic types and arrays (no special constructors or assignment operators etc.).
EDIT 2: Alright, the conclusion seems to be that the stack space probably will be allocated every time but it doesn't impact performance. Stack overflow is not an issue here, so case closed.

A: On most platforms, the maximum stack space that might be needed is allocated on function entry. But usually allocating stack space is just addition, so the amount of space allocated has no effect on performance.
Your question reads like premature optimization to me though. This isn't an algorithmic issue and you don't have a measured performance issue. So why are you even thinking about micro-optimizations?

A: Some compilers might optimize your tail-recursive call. When they do optimize, the call stack frame is reused so won't grow (so a tail-call is optimized as a "goto with arguments"). IIRC, for recent GCC, you are in the case where tail-call is not optimized (but I may be wrong, and GCC is progressing in that area).
You may want to compile to assembler code, e.g. with g++ -fverbose-asm -S -Wall -O and look into the generated assembler code to find out.
You certainly should not expect every C++ compiler to optimize tail calls like yours.
If it is so important for you, and if portability is less a concern, you might use alloca(3) and then a placement new operator.
  SomeLargeStructure* copyptr =
    new (alloca(sizeof(SomeLargeStructure))) SomeLargeStructure;
  *copyptr = *a;
  alter(copyptr);
  return aRecursiveFunction(copyptr, x);

If you have a copy constructor, use new (alloca(sizeof(SomeLargeStructure))) SomeLargeStructure(*a); instead.
BTW, I'm not sure it is worth the effort, for a call frame size of half a kilobyte, on modern desktops or servers (where stack space is often a bit more than a megabyte), unless you believe that your recursion is really deep (e.g. more than a thousand levels of recursion).
With recent GCC, you might be interested by compiler options like -fstack-usage or -Wstack-usage=

A: It really boils down to how much information the compiler can gain during its analysis on how your code will be executed at runtime. In the worst-case (i.e. a compiler can't infer if that data is ever going to be executed) the compiler necessarily has to allocate stack space for every function call:
struct SomeLargeStructure {
    double arr[20];
};

int aRecursiveFunction(const SomeLargeStructure *a, int x) {
    int val;
    cin >> val; // User input isn't foresee-able
    if (val == 29)
        return 0;
    // ...

    if (val)
        return aRecursiveFunction(a, x + 1) + 1;
    // ...
    SomeLargeStructure copy = *a;
    if (val == 22)
      copy.arr[0] = 2.0; // whatever
    return aRecursiveFunction(&copy, x);
}

int main(int argc, char *argv[]) {
    SomeLargeStructure obj;
    aRecursiveFunction(&obj, 2);
}

the above will require a full stack allocation at every call (-O3):
aRecursiveFunction(SomeLargeStructure const*, int):
    pushq   %r15
    pushq   %r14
    pushq   %rbx
    subq    $176, %rsp // stack alloc
    movl    %esi, %ebx
    movq    %rdi, %r14
    leaq    172(%rsp), %rsi

Also in cases where human deduction might think "this is definitely not needed" a compiler might still choose to allocate stack space.
It is impossible to answer this question properly without seeing the full code and/or studying the compiler's behavior in that case. You should compile your code and look at the generated and optimized assembly yourself. Just allocating stack space isn't usually a performance concern (unless you have a stack overflow).
A word of advice though: this is usually a premature optimization as others have noted, you shouldn't worry for these low-level issue but rather concentrate on your algorithm and how your data is being used, especially because if your stack space consumption doesn't prove/seem to be a problem, it is the profiling phase that will hint you on the red areas where optimization is most needed.


text:
Q: Generic interface for type I'm trying to create a generic function that returns a configuration, given an enum.
In my packages I'd like to create a getConfiguration method that would return me all the env variables that I need.
So for example :
enum PackageAEnvs {
   API_KEY = "API_KEY"
}

enum PackageBEnvs {
   ADMIN_URL = "ADMIN_URL"
}

Ideally, I would like to do something like this :
const getConfiguration = <T extends string[]> (conf: T): Record<T, string>{

  return conf.reduce( (acc, val) => {

    const env = process.env[val];

    if(! env) throw new Error()

    return { ...acc, [val]: env}

  }, {})

}

I would then like to have typescript raising errors if the key does not exist :
const { randomKey} = getConfiguration<PackageAEnvs>() <-- typescript should throw error

I found a way using a type :
type Conf = "K1" | "K2"

type Config =  {[Property in  Conf]: string}

const getConfig = (): Config  => {

  return {
    K1: "2",
    K2: "2"
  }

}
const { someKey } = getConf() // <-- error

However how can I make this getConfig function generic so it could accept any type ?  Is it possible ?

A: You would want to change your function to this:
const getConfiguration = <T extends object>(conf: T): Record<keyof T, string> => {
  return Object.keys(conf).reduce( (acc, val) => {
    const env = process.env[val];
    if(! env) throw new Error()
    return { ...acc, [val]: env}
  }, {}) as any
}

The function now takes the enum directly as an argument and constructs a Record where the keys are the enum keys. We also use Object.keys(conf) to get those keys at runtime.
const { API_KEY } = getConfiguration(PackageAEnvs)
const { ADMIN_URL } = getConfiguration(PackageBEnvs)

Playground


text:
Q: Simple database table comparison using DataTable.Merge and DataTable.GetChanges We are converting our application from using Sql Server Express (let's call this version 3) to Sql Server Compact Edition (let's call this version 4). I am trying to make sure that upgrades from previous versions (versions 1 and 2) are the same in the new product (version 4) as the old (version 3). The upgrade code had to be rewritten for various reasons.
I'm creating a quick test application that will compare a version 3 Sql Server Express database and a version 4 Sql CE database. If the conversion logic is good, the databases should be exactly equivalent--same tables, same columns, same row values.
It would seem to me that there should be an easy way to do this using DataTable.Merge and DataTable.GetChanges, but I'm not having success. If rows exist in the version 3 database and not in the version 4 database, the GetChanges still returns null. If there are changes to the same rows (based on the primary key, which is a Guid), GetChanges still returns null.
string selectSql = String.Format("SELECT {0} FROM {1}", String.Join(", ", columns.ToArray()), tableName);

var expressAdapter = new SqlDataAdapter(selectSql, expressConnection);
DataTable expressTable = new DataTable();
expressAdapter.Fill(expressTable);
expressTable.PrimaryKey = new DataColumn[] { expressTable.Columns[tableName + "ID"] };

SqlCeConnection ceConnection = new SqlCeConnection(this.SqlServerCeConnectionString);
var ceAdapter = new SqlCeDataAdapter(selectSql, ceConnection);
DataTable ceTable = expressTable.Clone();
ceAdapter.Fill(ceTable);

expressTable.Merge(ceTable);
return expressTable.GetChanges(); // this is null even when the expressTable has rows that do not exist in ceTable.

Am I using Merge and GetChanges in a way too far removed from their intended use? If so, other options would be welcome.

A: I'm pretty sure Merge doesn't do what you want it to.
If you check the expressTable.Rows.Count before and after the merge, you'll see what I mean.
Of course there are a lot of obvious ways to do this and they require a lot of work on your part. If you can you might want to consider a product like Red Gate Data compare
http://www.red-gate.com/products/SQL_Data_Compare/index.htm

A: I tried to do something similar sometime ago, but eventually it didn't work, because AcceptChanges was called on rows added by Merge, so they were all in unmodified state, so GetChanges returned null...

A: I don't think you're using this staff in an intended way.
In case you need to compare you'd better think in terms of having two data sources and keeping them in 'sync'. In case you want/need to do this automatically (via some code) you might want to take a look at Microsoft Sync Framework which was specially developed for finding/resolving differences between data sources. In you case 'resolution' could be trivial (i.e. 'no action, report only'). In case this is a 'once-in-a-while' activity and you're OK with doing it manually, you can use some tool (RedGate Data Compare which was mentioned is quite OK for that, but I'm not 100% sure if it supports SQL Server CE).


text:
Q: Can collection be used a verb? Eg. the activity of data collection over the activity of data collecting I am writing a research paper about data collectors, but there is no existent terminology for the activity of such collectors. Would it be data collecting? Or data collection?
Example from my paper:
Data collecting/collection is defined as the large accumulation of data with a cohesive theme with the aim of enriching a personal collection.


text:
Q: Rounding a specific Hour in LINQ to Entities I wonder how the following SQL code can be converted to LINQ.
declare @t table( hour datetime )

insert into @t select '19000101 14:38:12' union select '19000101 09:21:55'

select
  hour,
  case
    when DATEPART( MINUTE, hour ) >= 30
    then LEFT(convert(varchar, dateadd( HOUR, 1, hour ) , 108),2)+':00:00'
    else LEFT(convert(varchar, hour , 108),2)+':00:00'
  end
from @t

My current query is:
List<RegistroVehiculo> listaRegistroVehiculoCompleta =
  (from r in db.RegistroVehiculo
   where r.idPersona == oPersona.id
      && r.tipoRegistro == "S"
      && (
           (oHoraExtraGeneral.fechaDesde <= r.fechaRegistro && r.fechaRegistro <= oHoraExtraGeneral.fechaHasta)
           ||
           (oHoraExtraGeneral.fechaDesde <= r.fechaEntrada && r.fechaEntrada <= oHoraExtraGeneral.fechaHasta)
         )
    orderby r.fechaRegistro
    select r).ToList<RegistroVehiculo>();

How I can make the list with rounded hours work?

A: Have you tried using Let clause inside your LINQ query?
Look, it would be something like this:
var xx = (from r in li
          let RoundHour = r.fechaRegistro.Minute >= 30 ?
                          TimeSpan.FromHours(r.fechaRegistro.Hour + 1) :
                          TimeSpan.FromHours(r.fechaRegistro.Hour)
          where r.tipoRegistro == "S" //whatever else goes here Just for the sake of brevity
          orderby r.fechaRegistro
          select new { rounded = RoundHour,
                       registro = r}).ToList();

Please note that instead retrieving a list of RegistroVehiculo, we return an anonymous type, so, for every occurrence, you'll receive 2 things:

*

*the rounded hour

*the RegistroVehiculo object

I hope this approach helps you!
regards


text:
Q: Unpermitted parameter when trying to allow only one option with a collection_select in Rails I got my event categories to work without an unpermitted parameter error if I use the following setup:
class Event
     has_many :event_category_joins
     has_many :event_categories, through: :event_category_joins
     accepts_nested_attributes_for :event_categories

class EventCategoryJoin
     belongs_to :event
     belongs_to :event_category

class EventCategory
     has_many :event_category_joins
     has_many :events, through: event_category_joins

class EventsController
     private

     def event_params
          params.require(:event).permit(:title, :start, :end, :description, :cover_img, :cover_img_alt, event_category_ids: [])
     end

in the view:

= f.collection_select(:event_category_ids, EventCategory.all, :id, :category, {}, {class: "form-select border border-dark", multiple: true})

Now, the above works.  But if I don't define multiple: true, it returns a unpermitted parameter: event_category_ids.
If I use multiple: false, it returns unpermitted.
Right now, I only want the user to be able to select ONE category from a dropdown collection of categories that I define with the categories controller.
Is there a way I can get this drop down to work properly?  I have other fields that need to do the same.  Yet at the same time I want the code set up so I can offer multiple selections later if needed.
The other problem I'm having is in the edit view with the multiple: true, it doesn't even show which ones are currently saved in the database.  I can see the array when I go to Rails Console, but it doesn't show it on the edit view.
UPDATE:
Based on the comments given below, I was able to remove the array and now it works as I want it to for a single selection for now.
def event_params
    params.require(:event).permit(:title, :cover_img, :cover_img_alt, :start, :end, :description, :registration_required, :event_category_ids)
  end

A: *

*Check your log and you should see the difference between multiple: true and the otherwise:
Parameters: {"authenticity_token"=>"[FILTERED]", "event"=>{"title"=>"...", "event_category_ids"=>["", "1"]}, "commit"=>"Save"}

event_category_ids in parameters sent is array, VS string in:
Parameters: {"authenticity_token"=>"[FILTERED]", "event"=>{"title"=>"...", "event_category_ids"=>"1"}, "commit"=>"Save"}

It simply doesn't work because you only accept array in your event_params event_category_ids: []

*Without any builder like simple form you'll have to define selected value(s) manually.
= f.collection_select(:event_category_ids, EventCategory.all, :id, :category, { selected: @event.event_category_ids }, {class: "form-select border border-dark", multiple: false})


text:
Q: How to greyout a Fragment My application have a viewpager with the following fragment
1 Login 2 Measure 3 View Data
After the user login and swipe to the measure fragment my app will automatically measure some parameters.
As the viewpager is swipe-able . Is is possible to greyout/disable a fragment in the case where the user want to measure without login.
Thanks.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageButton
        android:id="@+id/qt_deleteButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/qt_testtype"
        android:layout_marginLeft="28dp"
        android:layout_marginTop="18dp"
        android:layout_toRightOf="@+id/qt_saveButton"
        android:background="@drawable/border_button"
        android:src="@drawable/delete" />

    <ImageButton
        android:id="@+id/qt_saveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/qt_deleteButton"
        android:layout_toRightOf="@+id/maintxt_measure"
        android:background="@drawable/border_button"
        android:src="@drawable/save" />

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/main_unknown" />

    </FrameLayout>

</RelativeLayout>

I have edit my layout file to the above however the layer below is still clickable. Is there any thing i missed ?
Thanks

A: Sorry but no, this is how it should probably look like:
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- You may change this to your relative layout, just make sure it is fill_parent -->
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center">

        <!-- Everything related to your main activity goes here -->

    </LinearLayout>

    <LinearLayout
        android:id="@+id/faderLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center">

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#E0000000"
            android:onClick="faderClicked" />

    </LinearLayout>

</FrameLayout>

So, in your activity, you will have a function public void faderClicked(View v) where it does nothing at all, and you control the view by changing faderLayout's visibility.


text:
Q: GET requests via Python Requests always returns reponse data as Content-Type text/html I am using Python package Requests to perform a GET request to a server which returns json data in the response. However I can't seem to get the response to form as application/json instead of text/html as the Content-Type.
>>> headers = {'Content-type': 'application/json','Accept': 'application/json'}
>>> resp = requests.get("http://192.168.1.180/api/enodeb", headers=headers)
>>> resp.headers
{'Transfer-Encoding': 'chunked', 'Date': 'Wed, 08 Mar 2017 15:36:16 GMT', 'Content-Type': 'text/html; charset=UTF-8'}
>>> resp.text
u'<!DOCTYPE html> \n \n     \n        <title>Raemis Enterprise</title> \n        <link rel="stylesheet" href="/javascript/jquery.mobile-1.2.0/jquery.mobile-1.2.0.min.css" />\n        <link rel="stylesheet" href="/css/jqm-docs.css"/>\n        <link rel="stylesheet" href="/css/omc.css"/>\n        \n        \n        \n        \n\n        \n\n        \n    \n\n     \n\n     \n        \n
\n
\n
Raemis Enterprise Login
\n            \n            <form action="#" id="form_login">\n

\n
\n                    Username:\n                    <input type="text" name="username" id="form_login_username" />\n
\n
\n                    Password:\n                    <input type="password" name="password" id="form_login_password" />\n
\n
\n                    <button type="submit" id="submit_login">Login\n
\n            </form>\n
\n
\n
Raemis Enterprise vRev. 21820
\n
  \n\n\n\n
\n\n    \n\n\n\n'

Performing the same actions using Postman, a http request tool, returns the correct data without having to set any headers at all.
The data should be:
[{
"id": 1,
"enb_id": 1,
"oper_state": 2,
"admin_state": 2,
"name": "Airspan eNB",
"tac": 1,
"cell_id": 257,
"location": "site",
"mac": "",
"downlink_bandwidth": 25000,
"uplink_bandwidth": 12500,
"downlink_earfcn": 0,
"uplink_earfcn": 0,
"mimo_group": 0
}]

How can I ensure the response data is in application/json Content-Type?


text:
Q: Python Return text between two markers for a CSV file File:
abcaddress\nCity\nCA\n92384
abcaddress\nCity\nTX\n75661
abcaddress\nCity\nNC\n28079
[877 rows x1 columns]
Please advise how I can return something like the following:
CA
TX
NC
...
I am thinking if there is a code that allows me to
find all the data between \n and \n
and if it is two characters, it will be returned
Many thanks!

A: Sure, you can use regex to find these. The findall will find all non-overlapping text that matches. The () in the second argument to findall specifies what to return. And the re.MULTILINE will allow the matches to happen accross lines.
import re

text="abcaddress\nCity\nCA\n92384 abcaddress\nCity\nTX\n75661 abcaddress\nCity\nNC\n28079"

matches = re.findall( '\n(..)\n', text, re.MULTILINE )

for match in matches:
    print (match)


text:
Q: Replicate image in CSS and HTML only For a code quiz I am trying to replicate the attached image using CSS and HTML only. The gradients and borders seem to be working out fine, but I am having trouble getting the ribbon edges to look curved.
Here is my markup:

AWESOME!

And here is my CSS:
    .container {
    width:300px;
    height:300px;
    margin-left:auto;
    margin-right:auto;
    margin-top:10px;
    position:relative;
    border:#CCC 1px solid;
    background-color:#EBEBEB;
    box-shadow:1px 1px 1px #CCC;
}

.ribbon-wrapper-green {
    width: 290px;
    height: 290px;
    overflow: hidden;
    position: absolute;
    top: -3px;
    right: -3px;
}

.ribbon-green {
    font: 25px Arial;
    text-align: center;
    text-shadow:0px 0px 6px #000;
    -webkit-transform: rotate(45deg);
    -moz-transform:    rotate(45deg);
    -ms-transform:     rotate(45deg);
    -o-transform:      rotate(45deg);
    position: relative;
    padding: 20px 0;
    left: 7px;
    top: 66px;
    width: 363px;
    background-color: #BFDC7A;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#BFDC7A), to(#8EBF45));
    background-image: -webkit-linear-gradient(top, #BFDC7A, #8EBF45);
    background-image:    -moz-linear-gradient(top, #BFDC7A, #8EBF45);
    background-image:     -ms-linear-gradient(top, #BFDC7A, #8EBF45);
    background-image:      -o-linear-gradient(top, #BFDC7A, #8EBF45);
    color: #FFF;
    -webkit-box-shadow: 0px 8px 20px rgba(0,0,0,0.3);
    -moz-box-shadow:    0px 8px 20px rgba(0,0,0,0.3);
    box-shadow:         0px 8px 20px rgba(0,0,0,0.3);
}

.ribbon-green:before, .ribbon-green:after {
    content: "";
    border-top:   4px solid #6e8900;
    border-left:  4px solid transparent;
    border-right: 4px solid transparent;
    position:absolute;
    bottom: -4px;
}

.ribbon-green:before {
    left: 0;
}

.ribbon-green:after {
    right: 0;
}

.ribbon-bottom-left {
    width: 0px;
    height: 0px;
    border-style: solid;
    border-width: 250px 0 0 250px;
    border-color: transparent transparent transparent #D32023;
    position:absolute;
    bottom:-5px;
    left:-5px;
    border-top-left-radius:10px;
    border-bottom-right-radius:10px;
    -moz-border-radius-topleft:10px;
    -moz-border-radius-bottomright:10px;
    z-index:1;
}

.bottom-left-gradient {
    position:absolute;
    bottom:-8px;
    left:-8px;
    z-index:100;
    height:245px;
    width:245px;
    opacity:0.4;
    filter:alpha(opacity=40);
    background: -moz-linear-gradient(45deg,  rgba(255,255,255,1) 0%, rgba(255,255,255,0.92) 4%, rgba(255,255,255,0) 51%); /* FF3.6+ */
    background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,rgba(255,255,255,1)), color-stop(4%,rgba(255,255,255,0.92)), color-stop(51%,rgba(255,255,255,0))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(45deg,  rgba(255,255,255,1) 0%,rgba(255,255,255,0.92) 4%,rgba(255,255,255,0) 51%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(45deg,  rgba(255,255,255,1) 0%,rgba(255,255,255,0.92) 4%,rgba(255,255,255,0) 51%); /* Opera 11.10+ */
    background: -ms-linear-gradient(45deg,  rgba(255,255,255,1) 0%,rgba(255,255,255,0.92) 4%,rgba(255,255,255,0) 51%); /* IE10+ */
    background: linear-gradient(45deg,  rgba(255,255,255,1) 0%,rgba(255,255,255,0.92) 4%,rgba(255,255,255,0) 51%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#00ffffff',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
    border-style:solid;
    border-width:0 0 5px 5px;
    border-radius:10px;
    -moz-border-radius:10px;
    border-color:#E41316;
}

The image is coming out like this example here: http://arunsood.me/code-quizzes/placebo-effect/.
The original I need to copy is below. How can I achieve the edge bending effect via CSS alone?


text:
Q: Why must a manifold be orientable to be able to induce a specific statistical manifold? Let $M$ be a manifold, $g$ a Riemannian metric, $\nabla$ be an affine connection on $M$, and $\nabla^{*}$ the unique dual affine connection of $\nabla$ on $M$, i.e. for all vector fields $X,Y,Z$ on $M$, we have
$$Zg(X,Y)=g(\nabla_{Z} X,Y)+g(X,\nabla_Z^{*} Y)$$
If both $\nabla$ and $\nabla^{*}$ are torsion-free, then we call $(M,g,\nabla,\nabla^{*})$ a statistical manifold.
On the following Wikipedia article, it is stated that if you have a probability space $(M,\mathcal{F},\mu)$, where $M$ is an orientable manifold, then you can induce an infinite-dimensional statistical manifold $S(M)$ defined to be the space of all probability measures on $M$ (with $\mathcal{F}$ held fixed).

My question is why should $M$ be orientable to be able to induce this statistical manifold?

I can see why one can induce such a statistical manifold if we are considering the probability space $(\mathbb{R},\mathcal{B},\mu)$, because in that space any probability measure $\mu$ on the Borel $\sigma$-algebra $\mathcal{B}$ is a probability distribution of the random variable $Y:\mathbb{R}\to \mathbb{R}$ defined by $Y(x)=x$. Additionally, a family of probability distributions is a special case of a statistical manifold with the Fisher information matrix as the Riemannian metric, with an affine connection called the $\alpha$-connection (so the definition of a statistical manifold I gave above is a more general definition than Wikipedia's). But in this case $\mathbb{R}$ is orientable so that does not help.

A: Orientability is merely a convenience, because then positive densities can be identified with volume forms. For a discussion on the non-orientable case in one of the major models of infinite-dimensional statistical manifolds, see the first pages of
Bauer, Martin, Martins Bruveris, and Peter W. Michor. "Uniqueness of the Fisher–Rao metric on the space of smooth densities." Bulletin of the London Mathematical Society 48.3 (2016): 499-506.


text:
Q: MvvmCross Plugin Network and Cookie I'm tring to make a rest request that require an embedded cookie. I've do that using System.Net reference in that way
Reference to System.net on PCL and MVVMCross
but i've problem to port that PCL library (System.Net) on VS2012. That code infact works fine on Xamarin Studio on Mac.
Referred to that question i've tried to use Network Plugin of MVVMCross in that way:
var url = "http://api.myaddress.com/api";
var json = new Cirrious.MvvmCross.Plugins.Json.MvxJsonConverter();
var client = new Cirrious.MvvmCross.Plugins.Network.Rest.MvxJsonRestClient
{
JsonConverterProvider = () => json
};
var request = new MvxRestRequest(url);
MvxDecodedRestResponse<SearchItem> theResponse = null;
    Exception exception = null;
CookieCollection cc = new CookieCollection ();
cc.Add(new Cookie("mycookiename","mycookievalue","/","api.myaddress.com"));

request.CookieContainer = new CookieContainer();

request.CookieContainer.Add(cc);
client.MakeRequestFor<SearchItem>(request,
                                                    (result) => { theResponse = result; },
                                                (error) => { exception = error; });

I've this error "The requested feature is not implemented."

at System.Net.HttpWebRequest.get_SupportsCookieContainer () [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:553
    at (wrapper remoting-invoke-with-check) System.Net.HttpWebRequest:get_SupportsCookieContainer ()
    at Cirrious.MvvmCross.Plugins.Network.Rest.MvxRestClient.SetCookieContainer (Cirrious.MvvmCross.Plugins.Network.Rest.MvxRestRequest restRequest, System.Net.HttpWebRequest httpRequest) [0x00000] in /Users/stuartlodge/Documents/GitHub/Mvx/MvvmCross/Plugins/Cirrious/Network/Cirrious.MvvmCross.Plugins.Network/Rest/MvxRestClient.cs:128
    at Cirrious.MvvmCross.Plugins.Network.Rest.MvxRestClient.BuildHttpRequest (Cirrious.MvvmCross.Plugins.Network.Rest.MvxRestRequest restRequest) [0x00028] in /Users/stuartlodge/Documents/GitHub/Mvx/MvvmCross/Plugins/Cirrious/Network/Cirrious.MvvmCross.Plugins.Network/Rest/MvxRestClient.cs:100
    at Cirrious.MvvmCross.Plugins.Network.Rest.MvxRestClient+c__AnonStorey2.<>m__4 () [0x0000d] in /Users/stuartlodge/Documents/GitHub/Mvx/MvvmCross/Plugins/Cirrious/Network/Cirrious.MvvmCross.Plugins.Network/Rest/MvxRestClient.cs:60
    at Cirrious.MvvmCross.Plugins.Network.Rest.MvxRestClient.TryCatch (System.Action toTry, System.Action`1 errorAction) [0x00000] in /Users/stuartlodge/Documents/GitHub/Mvx/MvvmCross/Plugins/Cirrious/Network/Cirrious.MvvmCross.Plugins.Network/Rest/MvxRestClient.cs:20

That is the code that works on Mac and that i'd like to port using MvvMCross Network Plugin
HttpWebRequest request = WebRequest.Create("http://api.myaddress.com/api") as HttpWebRequest;
        request.Method = "GET";
        request.Accept = "application/json";
        request.Headers.Add(HttpRequestHeader.Cookie, "mycookievalue");

        // Get response

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
            // Get the response stream
            StreamReader reader = new StreamReader (response.GetResponseStream());
            content = reader.ReadToEnd();

        }

        SearchItem itemssr = jsonConvert.DeserializeObject<SearchItem>(content);

A: That particular part of the Network plugin is currently under development - see GitHub Issue for REST plugin
It looks as though the cookie feature isn't going to work on the platform you are testing (which I guess from the stacktrace is xamarin.ios)
In this one case, this might be down to temporary issues in Xamarin.iOS - see:

*

*http://forums.xamarin.com/discussion/comment/14628/#Comment_14628

More generally for Plugin development, where a feature doesn't work, then whoever is writing the plugin will have to either override that functionality on that particular platform or will have to mark that feature is NotImplemented on that platform.
Note that marking features as not implemented is perfectly normal - there are always somethings that will not be implemented on some platforms.
Assuming the feature can be implemented then whoever is contributing to the network plugin might:

*

*implement an MvxTouchJsonRestClient somewhere in: https://github.com/slodge/MvvmCross/tree/v3/Plugins/Cirrious/Network/Cirrious.MvvmCross.Plugins.Network.Touch

*

*this implementation would inherit from the PCL core

*this implementation would have to override SetCookieContainer somehow - https://github.com/slodge/MvvmCross/blob/v3/Plugins/Cirrious/Network/Cirrious.MvvmCross.Plugins.Network/Rest/MvxRestClient.cs#L126

*this implementation would then be registered with IoC for Touch in the Plugin.cs file - in https://github.com/slodge/MvvmCross/blob/v3/Plugins/Cirrious/Network/Cirrious.MvvmCross.Plugins.Network.Touch/Plugin.cs#L21
If this isn't a temporary Xamarin.iOS issue, then I expect that someone will add cookie support in this way at some point soon. If you want that support sooner, then:

*

*ask on the GitHub issue, giving the contributors a use case (someone might prioritise it)

*contribute the code yourself

If working with this existing Network plugin is too large an initial leap, then maybe start by looking at a simpler plugin - see the much simpler Vibrate example in https://speakerdeck.com/cirrious/plugins-in-mvvmcross

If you don't want to mess around with plugins, then just find some other way of moving forwards - e.g. using your own native non-PCL library for that part of the functionality.

Side note:

That code infact works fine on Xamarin Studio on Mac.

As I tried to explain in the other question, currently XS has 'fake' PCL support - so PCLs built in XS are just normal assemblies and are not portable.


text:
Q: Liblog adapter for wix custom action Currently I am logging Wix Custom Action log messages to a file using Session.Log(). My application uses Liblog with Serilog for logging.
Is there a way to have an adapter class for Liblog that writes log messages to Custom Action Session?
The reason for trying to write installer log messages using Liblog is that dependent libraries of Custom Action assembly writes several log messages to Liblog and I do not want to have two different log files for installer.


text:
Q: message authentication negotiate login and password connect in browser login.teamviewer.com (managment console) Good afternoon,
when connecting to a computer using login.teamviewer.com (management console)
I get the message:
enter image description here
login.teamviewer.com (managment console)
message authentication: 'negotiate'
requires login and password connect
What is it? What do I do to connect?

A: You can have a teamviewer account and attach computers to that account. on login.teamviewer.com yo have to login with your account, then, you're going to be able to see the computers attached to your account and manage them


text:
Q: Use directive or ng-click to change preview in AngularJS So I'm very new to angularjs and have written a function in js that I would like to figure out how to convert to I guess a directive.
I have an image library using ng-repeat to load a series of images. To the right of the images I have a preview block that shows a larger version of the image and updates the information according to the image that is clicked on.
My question is what is the best method to update the preview area when an image is clicked - should I create a directive or use a ng-click on the image to call a function?
Note - all of the data and image are a part of a single object.
This is a smippet of how I was updating it just using js.
$('.box').on('click','.mainbox',function(){
    var imgid = this.id;
    $('#preview-img').attr('src', collection[imgid].smImg);
    $('#preview-title').text(collection[imgid].title);
    $('#preview-year').text(collection[imgid].years);
    $('#preview-desc').text(collection[imgid].description);
});

A: I don't know how your html looks like, but say it looks like this:

{{ selectedImage.title }}

{{ selectedImage.years }}

{{ selectedImage.description }}

And your controller code could look like this:
function myCtrl($scope) {
    $scope.images = [
        { url: "urlOfFirst.png", title: "Image1" .. },
        { url: "urlOfSecond.png", title: "Image2" .. }
    ];

    $scope.setSelectedImage = function(image) {
        $scope.selectedImage = image;
    }
}

See this jsfiddle as example


text:
Q: Regex for finding names after number I have string which contains names:
"1. Sachin Deshpande 2. K. Chandra Shekar 3. B. Rupesh 1. Prabhakar Rao 2. Venkata Chary 3. B. Gangadhar"

I need list of names from above string. I have tried (?:[0-9][).])+(\D*) this regex but it gives false results as well. Any help would be appreciated.
above regex also matches with raj sharma 4) mirror ship
I am looking for regex which checks the sequence for number
Output should look like this :
["Sachin Deshpande","K. Chandra Shekar","B. Rupesh","Prabhakar Rao",...]

A: With:
\d+\.\s+(\D+)(?:\s+|$)

Demo
Python demo:
>>> import re
>>> s="1. Sachin Deshpande 2. K. Chandra Shekar 3. B. Rupesh 1. Prabhakar Rao 2. Venkata Chary 3. B. Gangadhar"
>>> re.findall(r'\d+\.\s+(\D+)(?:\s+|$)', s)
['Sachin Deshpande', 'K. Chandra Shekar', 'B. Rupesh', 'Prabhakar Rao', 'Venkata Chary', 'B. Gangadhar']

If you have
"1) Sachin Deshpande 2) K. Chandra Shekar 3) B. Rupesh 1) Prabhakar Rao 2) Venkata Chary 3) B. Gangadhar"

You can use:
\d+[.)]\s+(\D+)(?:\s+|$)

Demo

A: import re
x="1. Sachin Deshpande 2. K. Chandra Shekar 3. B. Rupesh 1. Prabhakar Rao 2. Venkata Chary 3. B. Gangadhar"
res=(re.split('\d+\.\s', x)[1:-1])
print(res) #has spaces at end of names
res=[i.rstrip() for i in res]
print(res) #removes trailing spaces

A: /(?<=[0-9]\)|\. )+(\D*)/gm
There will be a space after it, but I tried my best :P

A: You can use the capture group, and if you also want to able to match digits in between:
\d[).]\s+(\S.*?)\s*(?=\d+[).]|$)

Explanation

*

*\d[).] Match a digit and either ) or .

*\s+ Match 1+ whitespace chars

*(\S.*?) capture group 1, Match at least a single non whitespace char, and then any char af few as possible

*\s* Match optional whitespace chars

*(?=\d+[).]|$) Positive lookahead, assert the starting pattern to the right or the end of the string

Regex demo


text:
Q: Pandas MultiIndex from regex on column I have a pandas dataframe that looks
df = pd.DataFrame(
    [
        ['JoeSmith', 5],
        ['CathySmith', 3],
        ['BrianSmith', 12],
        ['MarySmith', 67],
        ['JoeJones', 23],
        ['CathyJones', 98],
        ['BrianJones', 438],
        ['MaryJones', 75],
        ['JoeCollins', 56],
        ['CathyCollins', 125],
        ['BrianCollins', 900],
        ['MaryCollins', 321],
    ], columns = ['Name', 'Value']
)

print df

            Name  Value
0       JoeSmith      5
1     CathySmith      3
2     BrianSmith     12
3      MarySmith     67
4       JoeJones     23
5     CathyJones     98
6     BrianJones    438
7      MaryJones     75
8     JoeCollins     56
9   CathyCollins    125
10  BrianCollins    900
11   MaryCollins    321

The first column 'Name' needs to be split into First and Last names and put into a MultiIndex.
               Value
Joe   Smith        5
Cathy Smith        3
Brian Smith       12
Mary  Smith       67
Joe   Jones       23
Cathy Jones       98
Brian Jones      438
Mary  Jones       75
Joe   Collins     56
Cathy Collins    125
Brian Collins    900
Mary  Collins    321

A: I think you can use extract for extracting Names and surname, then set_index and last drop column Name:
df[['name','surname']] = df.Name.str.extract(r'([A-Z][a-z]*)([A-Z][a-z]*)', expand=True)
df = df.set_index(['name','surname']).drop('Name', axis=1)
print df
               Value
name  surname
Joe   Smith        5
Cathy Smith        3
Brian Smith       12
Mary  Smith       67
Joe   Jones       23
Cathy Jones       98
Brian Jones      438
Mary  Jones       75
Joe   Collins     56
Cathy Collins    125
Brian Collins    900
Mary  Collins    321

A: Solution
import pandas as pd

pattern = r'.*\b([A-Z][a-z]*)([A-Z][a-z]*)\b.*'
names = df.Name.str.extract(pattern, expand=True)
midx = pd.MultiIndex.from_tuples(names.values.tolist())
df.index = midx
df[['Value']]

Explanation
pattern grabs a group of letters that starts with a capital A-Z followed by any number of lower-case a-z followed by another capital A-Z and any number of lower-case a-z.  Then it splits it into two.
pd.MultiIndex.from_tuples creates the MultiIndex.
names.values.tolist() turns the converted DataFrame into a list of lists that will be interpreted as tuples.


text:
Q: How do I (can I?) get the exit status from a command? Using twisted.conch, I'm working with the following SSHChannel implementation, which is fed a command to run when instantiated:
class CommandChannel(channel.SSHChannel):
    name = 'session'

    def __init__(self, command, *args, **kwargs):
        channel.SSHChannel.__init__(self, *args, **kwargs)
        self.command = command

    def channelOpen(self, data):
        d = self.conn.sendRequest(
            self, 'exec', common.NS(self.command), wantReply=True)
        d.addCallback(self._gotResponse)

    def _gotResponse(self, _):
        self.conn.sendEOF(self)
        self.loseConnection()

    def dataReceived(self, data):
        log.msg('dataReceived: data=%r' % data)

    def extReceived(self, dataType, data):
        log.msg('extReceived: dataType=%r, data=%r' % (dataType, data))

    def closed(self):
        reactor.stop()

To this I'm feeding a shell command that should be returning some sort of exit status.  Can I read what that exit status is?  I had hoped extReceived might be my way in, but it doesn't look like it.
In my logs I see this, which seems like it should be a hint where to look, but I'm not sure how to follow said hint:
2013-04-05 10:39:37-0400 [SSHChannel session (0) on SSHService ssh-connection
    on CommandTransport,client] unhandled request for exit-status

A: There are two extra callbacks you might want to implement for this.  These are callbacks on the channel, so you're pretty close already.
The first is request_exit_status.  Once you implement this, Conch will no longer log that the exit-status request is unhandled.  Here's an example implementation:
def request_exit_status(self, data):
    """
    When the server sends the command's exit status, record it for later
    delivery to the protocol.

    @param data: The network-order four byte representation of the exit
        status of the command.
    @type data: L{bytes}
    """
    (status,) = unpack('>L', data)
    if status != 0:
        self._reason = ProcessTerminated(status, None, None)

The second is request_exit_signal.  exit-signal is sent instead of exit-status if the command is terminated by a signal.  Here's an example implementation:
def request_exit_signal(self, data):
    """
    When the server sends the command's exit status, record it for later
    delivery to the protocol.

    @param data: The network-order four byte representation of the exit
        signal of the command.
    @type data: L{bytes}
    """
    (signal,) = unpack('>L', data)
    self._reason = ProcessTerminated(None, signal, None)

The general pattern here is that when SSHChannel receives a request for foo it will try to call request_foo with the bytes making up the request.


text:
Q: Converting any colored PPM image into a colored image with only 8 colors I need an algorithm for converting any colored image of ppm format to only 8 color in C++. I tried this code and I keep facing an error with the >> and << operators:
    #include "stdafx.h"
    #include<iostream>
    #include<fstream>
    using namespace std;

    int main()
    {
ifstream in;
in.open("football.ppm");
ofstream out("football8color.ppm");

string header;
int cols, rows,colors;
int r, g, b;

in >> header >> cols >> rows >> colors;
out << header << endl;
out<< cols<< " " << rows <<endl;
out<< colors<< endl;

for ( int i=0; i<rows; i++)
{
    for (int j=0; j<cols; j++){
        in>> r >> g >> b;
}
out <<endl;
    }
    in.close();
    out.close();
    return 0 ;
    }

I get these errors:
    4   IntelliSense: no operator "<<" matches these operands   c:\users\atiyeh\documents\visual studio 2010\projects\mm ass 2\mm ass 2\mm ass 2.cpp    18
    3   IntelliSense: no operator ">>" matches these operands   c:\users\atiyeh\documents\visual studio 2010\projects\mm ass 2\mm ass 2\mm ass 2.cpp    17
Error   2   error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)  c:\users\atiyeh\documents\visual studio 2010\projects\mm ass 2\mm ass 2\mm ass 2.cpp    16
Error   1   error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::ifstream' (or there is no acceptable conversion) c:\users\atiyeh\documents\visual studio 2010\projects\mm ass 2\mm ass 2\mm ass 2.cpp    15

A: For the algorithm, you should look up Color Quantization. If you want to make it look nice, you should look up dithering techniques such as Floyd-Stienberg dithering.


text:
Q: Recursion Friends Confusion My program takes data from an outside text file and puts this data into a list of names as well as numbers. The numbers represent the friendships (i.e. if at index 2 there is a 1 for a person. This means this person is friends with the person of names[1].) From here it is supposed to take a name and display who the person's direct friends are and then display the indirect friends (Indirect friends are the friends of a person's friends.) My current problem is that my program displays the indirect but I am unsure of how to send it into my base if statement to print the direct friend. If anyone could shed some light that would be greatly appreciated.
Th data in the names array(String): ["Smith","Adams","Steward","Stein","Mankell","Yorst"]
The data in the numbers array(String):
["000010","001001","01000","000010","100100","010000"]
I called the method on smith (directFriends("Smith", names,numbers,1)
I Am getting this for out put:
Indirect Friends of Smith:
Mankell is Friends with Smith
Mankell is friends with Stein
My desired output is:
Smith is friends with Mankell
Indirect Friends of Smith:
Mankell is Friends with Smith
Mankell is friends with Stein
public class AllFriends {

public static void directFriends(String name,String[]names,String[]numbers, int num){
ArrayList<String> indirect = new ArrayList<String>();

if (num==0){
    for (int i=0;i<names.length;i++){
        if(names[i].equalsIgnoreCase(name)){
            for(int j=0;j<numbers[i].length();j++){
                if(numbers[i].charAt(j)=='1'){
                    System.out.println(name+" is friends with "+names[j]);
                }
            }
        }
    }
}
else
    //Go through names array
    for (int i=0;i<names.length;i++){
        //To see if name entered is the same as a name from the list
        if(names[i].equalsIgnoreCase(name)){
            //For each character in the individual number String
            for(int j=0;j<numbers[i].length();j++){
                //Check if it's a 1(Friends)
                if(numbers[i].charAt(j)=='1'){
                    //Then add this friend to the group of people needed to be friend searched
                    indirect.add(names[j]);
                    //If
                    if(j==numbers[i].lastIndexOf("1") ) {

                        for(int f=0;f<indirect.size();f++){
                            System.out.println("Indirect Friends of "+name+":");
                            num--;
                            directFriends(indirect.get(f),names,numbers,num);

                        }
                    }

                }
            }
        }
    }
}

A: I actually got it to work for anyone who was curious here is my solution All I had to do was re order and add a line in my final for loop in the else statement:
public class AllFriends {

public static void directFriends(String name,String[]names,String[]numbers, int num){
ArrayList<String> indirect = new ArrayList<String>();

if (num==0){
    for (int i=0;i<names.length;i++){
        if(names[i].equalsIgnoreCase(name)){
            for(int j=0;j<numbers[i].length();j++){
                if(numbers[i].charAt(j)=='1'){
                    System.out.println(name+" is friends with "+names[j]);
                }
            }
        }
    }
}
else
    //Go through names array
    for (int i=0;i<names.length;i++){
        //To see if name entered is the same as a name from the list
        if(names[i].equalsIgnoreCase(name)){
            //For each character in the individual number String
            for(int j=0;j<numbers[i].length();j++){
                //Check if it's a 1(Friends)
                if(numbers[i].charAt(j)=='1'){
                    //Then add this friend to the group of people needed to be friend searched
                    indirect.add(names[j]);//New stuff
                    //If
                    if(j==numbers[i].lastIndexOf("1") ) {

                        for(int f=0;f<indirect.size();f++){
                            num--;
                            **directFriends(name,names,numbers,num);
                            System.out.println("Indirect Friends of "+name+":");
                            directFriends(indirect.get(f),names,numbers,num);**

                        }
                    }

                }
            }
        }
    }
}


text:
Q: VLC 2.0.1 Adjust Subtitle Tming How can i adjust subtitle timing on VLC 2.0.1
My Subtitle late 2 minutes.
Already tried google, most of tutorial written for version 1, and version 2 has different configuration interface which it is more confusing for me.

A: In windows, Go to   Tools --> Track Synchronization
or Click on the button   from the VLC skin to open the extended settings
In Mac, Go to Window --> Track Synchronization


text:
Q: How to concat, find duplicates and display result after joining mulitple tables(9-10) I want to concat one column each from multiple tables , after concatenation find if there are duplicates in the concatenation , display duplicates with a ID column from one of first tables.
I am able to do this but query which I have done looks very long and is bad from a performance perspective.
Here is the logic which is working -
SELECT ID , concatcolumn where concat column in (
(select concat
join all tables
group by concatcolumn
having count(id)>1) a
JOIN
(select id, concat
join all tables) b
on a.concatcolumn = b.concatcolumn )

This gives me what I want but I am no happy with it as
concatcolumn is a concatenation of 10 columns atleast , and wherever i have mentioned it will be replaced by that code.
Is there any other easier way ?


text:
Q: geoip_record_by_name returns nothing? I tried this tutorial http://tech.cibul.net/install-maxminds-geoip-ip-database-on-ubuntu-for-php/ and did everything from it. Compiled the geoip module and also the php extension on my Ubuntu 11.10 installation.
I also tried this more simpler terminal command
(sudo) apt-get install php5-geoip

And it showed successful installation but when I try
geoip_record_by_name('127.0.0.1')

and it still gives nothing, i.e. no array at all.

A: Try a different IP address - for example 111.111.111.111 as you are checking your localhost (127.0.0.1) - it may not run locally anyway.
See geoip_record_by_nameDocs:

Returns the associative array on success, or FALSE if the address cannot be found in the database.

You get back FALSE because the address was not found in the database.

A: There is important discussion on this subject at https://bugs.php.net/bug.php?id=59753
The problem with this function is that it returns a "PHP Notice" when a address can not be found.
In plain the behavior this function take on normal internal address that is not expected to return location ( record ) from its database is to return "false" that is good and expected, but additional it send "PHP Notice" that is normally used to report real coding or library problems, but not expected results.


text:
Q: .NET Core and type equality This test:
[Fact]
public void X()
{
    Assert.IsType<Expression<Func<int>>>(Expression.Lambda<Func<int>>(Expression.Constant(1)));
}

Runs on .NET Framework, but fails on .NET Core (3.1 in my case) with the following error:
Expected: System.Linq.Expressions.Expression`1[[System.Func`1[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]
Actual:   System.Linq.Expressions.Expression0`1[[System.Func`1[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]

Why is this? And can I do something to compare the types properly?

A: Incorrect version of my answer before:

Assuming the behavior for .Net Core is the same or similar to framework, here is my reasoning.
Looking at the reference source code Expression.Lambda<T> creates a runtime type of Expression<T>, see typeof(Expression<>).MakeGenericType.
typeof(Expression<T>) however is the compile time type.

Using the following LINQPad script you see the difference in the output
var exp = Expression.Lambda<Func<Int32>>(Expression.Constant(1));
exp.GetType().BaseType.Dump();
// System.Linq.Expressions.Expression`1[System.Func`1[System.Int32]]
typeof(Expression<Func<Int32>>).BaseType.Dump();
// System.Linq.Expressions.LambdaExpression

For .Net Framework an instance of Expression<T> is returned from Expression.Lambda<T>(Expression exp) as expected.
But for .Net Core the behavior was changed!
For .Net Core either Expression<TDelegate>.Create or ExpressionCreator<TDelegate>.CreateExpressionFunc is called along the way but in both cases - for this example here - a new instance of Expression0{T} : Expression{T} is returned! Which are obviously not of the same type.
to assert your type you may use
var expression = Expression.Lambda<Func<int>>(Expression.Constant(1));
// extract the type of used generics
var genericArgs = expression.GetType().GetGenericArguments();
// TODO: assert that we DO have exactly one argument here
Assert.IsType<Func<int>>(genericArgs[0]);

// another assert:
// unverified, but `(expression is Expression<Func<int>> _).Dump();` returns `true` in LINQPad
Assert.True(expression is Expression<Func<int>>);


text:
Q: Show or Hide SlickGrid "header" (filter) row at runtime I'm trying to control the visibility of the HeaderRow at runtime.
[Note:  To clear any confusion: I'm not talking about the row with the column names;  I'm talking about the row that's made visible with grid option "showHeaderRow:true";  i.e., what might be better termed the "Filter Row"].
I'm trying to use:
grid.setOptions({ showHeaderRow: true/false });
grid.invalidate();

This seems to have no effect on the grid or the display of the HeaderRow.
Any thoughts on what I'm missing?

A: this worked for me:
if(grid.getOptions().showHeaderRow){
    grid.setHeaderRowVisibility(false);
}else{
    grid.setHeaderRowVisibility(true);
}

A: Yes this one should be simple enough, I use these 2 pieces of code to hide/show dynamically after the grid is already created.grid.hideHeaderRowColumns(); grid.showHeaderRowColumns();
Give it a try, hope it helps...

A: I'm using SlickGrid version 2.1 at the time of writing, and I have a similar requirement as yours. After digging some depth into the source code, I assume that option showHeaderRow has no effect on the display of the resulting grid unless co-work with the grid.setHeaderRowVisibility(visibility).
Anyway, I managed to work around with simple jquery technique after the grid is created, simply by using the code below, if you don't want any animation:
$(".slick-header").hide();

Although this is an old question asked 2 years ago, and Slick Grid hasn't got any progress for quite some time, I still believe it's quite a useful lib. Hope this complements the thread and be of a little help for the up-coming users.


text:
Q: When creating a node pool (multi-zone) with gcloud, the nodes do not register on the kubernetes master When running the following gcloud command on my existing GKE cluster
SCOPES=(
https://www.googleapis.com/auth/compute
https://www.googleapis.com/auth/devstorage.read_write
https://www.googleapis.com/auth/monitoring.write
https://www.googleapis.com/auth/logging.write
https://www.googleapis.com/auth/monitoring
https://www.googleapis.com/auth/pubsub
https://www.googleapis.com/auth/servicecontrol
https://www.googleapis.com/auth/service.management
https://www.googleapis.com/auth/sqlservice.admin
https://www.googleapis.com/auth/trace.append
https://www.googleapis.com/auth/cloud_debugger
https://www.googleapis.com/auth/cloud-platform
)

gcloud beta container node-pools create $POOL_NAME \
--machine-type $MACHINE_TYPE \
--disk-size $DISK_SIZE \
--enable-autorepair \
--enable-autoscaling \
--min-nodes 1 --max-nodes 4 \
--cluster $CLUSTER \
--zone $ZONE \
--num-nodes 1 \
--scopes $(printf ",%s" "${SCOPES[@]}")

(Note this is regional, so using the beta command - I suspect this doesn't happen with non-regional clusters)
I get the following error:
    Creating node pool pool-alpha...done.
ERROR: (gcloud.beta.container.node-pools.create) Operation [<Operation
 endTime: u'2018-03-29T08:56:14.989660264Z'
 name: u'operation-1522311735033-87b12027'
 operationType: OperationTypeValueValuesEnum(CREATE_NODE_POOL, 7)
 selfLink: u'https://container.googleapis.com/v1beta1/projects/xxxxxxxxx/zones/europe-west1-d/operations/operation-1522311735033-87b12027'
 startTime: u'2018-03-29T08:22:15.03391313Z'
 status: StatusValueValuesEnum(DONE, 3)
 statusMessage: u'All cluster resources were brought up, but the cluster API is reporting that only 0 nodes out of 3 have registered. Cluster may be unhealthy.'
 targetLink: u'https://container.googleapis.com/v1beta1/projects/xxxxxxxxxx/zones/europe-west1-d/clusters/digibet-prod/nodePools/pool-alpha'
 zone: u'europe-west1-d'>] finished with error: All cluster resources were brought up, but the cluster API is reporting that only 0 nodes out of 3 have registered. Cluster may be unhealthy.

And indeed, the nodes are created but aren't registered on the cluster. A bug with GKE?

A: I reproduced your situation but looks like that is not a GKE issue.
I think the problem is in the $(printf ",%s" "${SCOPES[@]}") function, which creates a list starting from a comma, and it somehow affects available scopes.
I also found that https://www.googleapis.com/auth/cloud_debugger is not in the list of available scopes for node-pools create command. But, based on Cloud Debugger documentation, you can use cloud-platform scope instead of cloud_debugger, and everything will be OK.
So, I checked the command with manually added scopes, it works fine:
gcloud beta container node-pools create $POOL_NAME \
--machine-type $MACHINE_TYPE \
--disk-size $DISK_SIZE \
--enable-autorepair \
--enable-autoscaling \
--min-nodes 1 --max-nodes 4 \
--cluster $CLUSTER \
--zone $ZONE \
--num-nodes 1 \
--scopes logging-write,monitoring-write,service-management,compute-rw,storage-rw,monitoring,pubsub,service-acontrol,service-management,sql-admin,trace,cloud-platform


text:
Q: Set Report Size on Crystal report i am using windows 10.
i am trying to create a report for continuous form (Half Of A4), i set manually from device and printer, so i set printer server like this.

then i change page setup on CR to vpc (name of paper where i create on printer server)  like this..

then i tried it with different way :

*

*i preview the report, than print.

with out run my application. the print result was great. just like i want.

*i run my application, preview my report with Crystal REport viewer tools, but my report become landscape. not protrait.

see...
what must i do?

A: yes, after a week,finally i found the answer, we need to set default paper to our customer paper.
just that.