text:
Q: SENDER_ID_MISMATCH error when trying send notification to some devices I'm getting SENDER_ID_MISMATCH error when trying to send fcm notification.
Follwing is the error message i am gettin

Caused by: com.google.api.client.http.HttpResponseException: 403 Forbidden
      {
        "error": {
          "code": 403,
          "message": "SenderId mismatch",
          "status": "PERMISSION_DENIED",
          "details": [
            {
              "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
              "errorCode": "SENDER_ID_MISMATCH"
            }
          ]
        }
      }


text:
Q: How do I insert some data into an Sqlite 3 database Through the following code I am retrieving data from a Db, however I need to insert some data into a Sqlite3 database with this code before select statement. Can any one tell me where I need to put the insert query and how can I execute it.
I am selecting the datas through the following code:
sqlite3* database;

- (void)initializeDatabase
{
    list=[[NSMutableArray alloc] init];
    BOOL success;
    NSFileManager *filemanager=[NSFileManager defaultManager];
    NSError *error;
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory= [paths objectAtIndex:0];
    NSString *writablePath=[documentsDirectory stringByAppendingPathComponent:@"SymbolTalk.sqlite"];
    success=[filemanager fileExistsAtPath:writablePath];
    if(!success)
    {
        NSString *defaultDBPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SymbolTalk.sqlite"];
        success=[filemanager copyItemAtPath:defaultDBPath toPath:writablePath error:&error];
        if(!success)
        {
            NSAssert1(0,@"Failed to create writable databasefile withw message %@.",[error localizedDescription]);
        }
    }

    //Specify where to get the database from
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory= [paths objectAtIndex:0];
    NSString *path=[documentsDirectory stringByAppendingPathComponent:@"SymbolTalk.sqlite"];

    //Open the database
    //might have to make database as property
    if(sqlite3_open([path UTF8String], &dataBase) ==SQLITE_OK)
    {
        const char *sql="select filename from scenes";
        sqlite3_stmt *statement;

        if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                //NSLog(@"%@",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
                [list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
            }
        }
    }
}

A: sqlite3_stmt *insert_statement = nil;

const char *sql = "INSERT INTO scenes (filename) VALUES(?)";
if (sqlite3_prepare_v2(database, sql, -1, &insert_statement, NULL) != SQLITE_OK) {
    NSAssert1(NO, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}

sqlite3_bind_text(insert_statement, 1, [newFilename UTF8String], -1, SQLITE_TRANSIENT);

if (sqlite3_step(insert_statement) == SQLITE_DONE) {
    // code if all ok
} else {
    NSAssert1(NO, @"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(database));
}

sqlite3_reset(insert_statement);
sqlite3_finalize(insert_statement);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Diagonally Transition Background Color on Hover From Bottom Left to Top Right I'm using the technique in the answer from this question, except that I'm wondering if it's possible to slide a background color change from left to right diagonally - specifically, from bottom-left to top-right?
I have this CSS and HTML for a menu, for example:

.menu {
background: #1481C3;
color: white;
border-right: 1px solid #666666;
}

.menu ul.links {
list-style: none;
padding: 0;
}

.menu ul.links li {
border-bottom: 1px solid #0E99ED;
height: 64px;
line-height: 67px;
padding: 0 25px;
font-size: 15px;
background: linear-gradient(to right, #0E99ED 50%, #1481C3 50%);
background-size: 200% 100%;
background-position: right bottom;
transition: all 0.2s ease;
}

.menu ul.links li:hover {
background-position: left bottom;
cursor: pointer;
}

          Home

          Assignments

          Proctoring

          Reports

          Administration

And, to make it horizontal, I tried to change the styles of this class
.menu ul.links li {
    background: linear-gradient(to top right, #0E99ED 50%, #1481C3 50%);
}

But that is not quite working as expected: link to jsFiddle
I need the li to be 100% #0E99ED (light blue) initially and then 100% #1481C3 (dark blue) on hover. Currently that ^ is initially taking up about 25% of the bottom left with #0E99ED and only about 75% of the total li on hover. It needs to be 0% initially and 100% on hover.
Any suggestions for how to fix this?

A: If I understand you correctly all that is necessary is to increase the starting background-size so that no gradient is seen initially.

div {
  height: 100px;
  background-image: linear-gradient(45deg, blue 50%, lightblue 50%);
  background-size: 250% 100%;
  background-position: right bottom;
  transition: background-position .5s ease;
}

div:hover {
  background-position: left top;
}


text:
Q: How can I set up configuration variables in XSLT for different environments? We have a site that uses XSLT. There is a config.xslt file that declares a few global variables and it's included in a bunch of other stylesheets. The issue is that we host the site in a few different places and we tweak some of these variables depending on the environment.
Usually, we would create both a main config file and a local config file to keep the local changes out of version control. The local config file can override any of the variables that it needs to without modifying the main config file. However, it is my understanding that this would not be possible within XSLT since XSLT variables can only be declared once and you can't check if they've been declared already.
My question then is: Is it possible to implement such a thing in XSLT?
If not, what would be a better way of managing our configuration?
Edit:
Thanks to Martin Honnen for suggesting xsl:import. I've looked up how to use import and it does what I want. However, it leaves me with another issue where the local config file must always exist or else the whole application breaks. Since I want to remove the local config file from version control it's not completely ideal. I found this answer but it's for xslt-2.0 and I'm unfortunately stuck with xslt-1.0.

A: I can suggest two options.

*

*Add your config as a parameter to your XSL transformer, prior to doing the transformation. How you do that depends on what transformer you are using. The config could be XML or a set of name=value pairs.

or

*Use a config.xml file to populate an xsl:param at the top of your XSLT. Read the values using document(). Something like this:

<xsl:param name="config">
  <xsl:choose>
    <xsl:when test="document('C:\config\config.xml')">
      <xsl:value-of select="document('C:\config\config.xml)/config" />
    </xsl:when>
    <xsl:otherwise><config/></xsl:otherwise>
  </xsl:choose>
</xsl:param>

(If you do this, the config will always be at least <config />)


text:
Q: Accessing Two dimensional fixed byte array I am struggling with two dimensonal fixed byte array use.I have to Convert A pascal Char type with the similiar size in C# .I have to have some character values in this array.
I am declaring this like public fixed byte C10VAFT[14*20];
I dont know whether this array is simply a one D array of size 280 or it is a two dimensional array reason being I am not able to get my intensional values becoz I get series of Byte.
Thanks
Ashok
here the the code.
this is a pascal structure
CREC10 = RECORD
         C0RT    : INTEGER;
         C0KEY1  : INTEGER;
         C10VAFT : ARRAY [0..13] OF PACKED ARRAY [0..19] OF CHAR;
         C10VH1H : PACKED ARRAY [0..19] OF CHAR;
         C10VH2H : PACKED ARRAY [0..19] OF CHAR;
         C10VH3H : PACKED ARRAY [0..19] OF CHAR;
         C10MPE1 : PACKED ARRAY [0..14] OF CHAR;
         C10MPE2 : PACKED ARRAY [0..14] OF CHAR;
         C10MPE3 : PACKED ARRAY [0..14] OF CHAR;
         C10MPR1 : PACKED ARRAY [0..14] OF CHAR;
         C10MPR2 : PACKED ARRAY [0..14] OF CHAR;
         C10MPR3 : PACKED ARRAY [0..14] OF CHAR;
         SPARE2  : PACKED ARRAY [0..61] OF CHAR;
         C10CP   : INTEGER[4];
         C0BRRP  : INTEGER[8];
         END;

blow is the replica struct in C#. i am stuck with the ** element
public unsafe struct CREC10
    {
        public short C0RT;
        public short C0KEY1;
        **public fixed byte C10VAFT[14*20];**
        public fixed byte C10VH1H[20];
        public fixed byte C10VH2H[20];
        public fixed byte C10VH3H[20];
        public fixed byte C10MPE1[15];
        public fixed byte C10MPE2[15];
        public fixed byte C10MPE3[15];
        public fixed byte SPARE2[62];
        public UcsdInt4 C0CP;
        public UcsdInt4 C0BRRP;

    }

A: By using this decalaration C10VAFT[14*20]  you are getting an array  of   3920 and you are  getting  an  array of byte because the difference between char and byte in  .net is that
byte=8bits and  char =2bytes (16bits) which is different from  PASCAL where  A byte and a char are the same thing
in C# a Multidimensional array is declared like  this
 char[,] array = new char[14, 20]

or A jagged array
 char[][] array = new char[14][] ;

A: The native answer to your question is that you cannot make a two-dimensional fixed array. The compiler does not let you. The documentation says:

Unsafe buffers are always vectors, or one-dimensional arrays.

If you are to continue to use unsafe and fixed then you would need to either:

*

*Declare 14 separate fixed byte arrays.

*Declare a single fixed byte array of length 14*20 and then index into it manually.

The indexing would be something like this:
int arrIndex(int elementIndex, int charIndex)
{
    return (elementIndex*20) + charIndex;
}

This does illustrate the syntactical hurdles that you have to jump over to use fixed size buffers.

I think that what you are actually doing is taking a byte stream laid out as per your Pascal record, and wanting to transfer that into a C# structure. And possibly back again. In my opinion it is a mistake to try to use the same layout in C#. The compiler does not want you to do so. Don't fight it. Use a natural C# layout for the structure and provide mappings between the natural C# layout, and the on-disk layout.
The first point I want to make is that you categorically do not need nor want to use unsafe or fixed here. Both of those just make your life harder than it needs to be.
First of all I'm going to assume that you have your raw data in a C# Stream instance. If it comes from a byte stream then you would make a MemoryStream:
MemoryStream stream = new MemoryStream(bytes);

But it doesn't really matter. It can be a file stream. It just wants to be in a stream.
Then you define a C# structure to receive the data. This does not need to match the rigid layout of the Pascal data structure. Use native C# types. For instance:
public struct CREC10
{
    public int C0RT;
    public int C0KEY1;
    public string[] C10VAFT;
    public string C10VH1H;

    public static CREC10 FromStream(Stream stream)
    {
        ....
    }
}

I've not defined all the fields. Just enough to give you a flavour. And I've also added a static method that can make a new one from a stream. That would be implemented like this:
    public static CREC10 FromStream(Stream stream)
    {
        CREC10 result;
        using (BinaryReader reader = new BinaryReader(stream))
        {
            result.C0RT = reader.ReadInt32();
            result.C0KEY1 = reader.ReadInt32();
            result.C10VAFT = new string[14];
            for (int i=0; i<result.C10VAFT.Length; i++)
            {
                result.C10VAFT[i] = Encoding.ASCII.GetString(reader.ReadBytes(20));
            }
            result.C10VH1H = Encoding.ASCII.GetString(reader.ReadBytes(20));
        }
        return result;
    }

This does assume that there is no packing in your structure. It does look as though that would be the case. And I'm also assuming that your integers are 4 bytes wide, but perhaps for this somewhat elderly Pascal compiler that is not the case. In any case, I believe that you know the binary layout of the data structure and can iron out these details.
And you can write a matching function to copy the struct to a stream using the same format.
If you try to stick with your rigid Pascal layout in C# you will find it excruciatingly difficult to actually work with your data in C# code.


text:
Q: gccgo build can not find custom pakage when use the gccgo build one single go file is ok, but whn I build a large multi custom pacage go mod project, the project have some sub package(such as app/ app/core/server etc) not build success.
how to fix this? anyhelp? I build with -x and see some debug info.
go build -x  -gccgoflags -Wl,-R,/opt/gccgo/lib64/ -compiler gccgo -o bin/app main.go

the error is:
WORK=/tmp/go-build1609005358
mkdir -p $WORK/b001/
cd $WORK
/opt/gccgo/bin/gccgo -fgo-importcfg=/dev/null -c -x c - -o /dev/null || true
mkdir -p $WORK/b001/_importcfgroot_/github.com/gin-gonic
ln -s /home/liangqi1/.cache/go-build/8a/8ae3d6bb3097698b7be6547599d7a61c9c5c54cca0be55c007ca1c8386d1188c-d $WORK/b001/_importcfgroot_/github.com/gin-gonic/libgin.a
mkdir -p $WORK/b001/_importcfgroot_/github.com/logrusorgru
ln -s /home/liangqi1/.cache/go-build/6f/6fb602f3c990310188a3e921909d152810f07d50f1ab4c621ab71b87afd4942d-d $WORK/b001/_importcfgroot_/github.com/logrusorgru/libaurora.a
mkdir -p $WORK/b001/_importcfgroot_/go.uber.org
ln -s /home/liangqi1/.cache/go-build/c0/c0ac9f2f0ebb74e0997bfa1d72d21a79ce906ed736197f83402365203094c3a9-d $WORK/b001/_importcfgroot_/go.uber.org/libautomaxprocs.a
/opt/gccgo/bin/gccgo -ffile-prefix-map=a=b -c -x c - -o /dev/null || true
cd /home/liangqi1/gccgo_demo
/opt/gccgo/bin/gccgo -c -g -m64 -fdebug-prefix-map=$WORK=/tmp/go-build -gno-record-gcc-switches -fgo-relative-import-path=_/home/liangqi1/gccgo_demo -o $WORK/b001/_go_.o -I $WORK/b001/_importcfgroot_ -Wl,-R,/opt/gccgo/lib64/ ./main.go
# command-line-arguments
./main.go:7:23: 错误:import file 'gccgo_demo/app' not found
    7 |         "gccgo_demo/app"
      |                       ^
./main.go:8:35: 错误:import file 'gccgo_demo/app/core/server' not found
    8 |         "gccgo_demo/app/core/server"
      |                                   ^
./main.go:24:19: 错误:reference to undefined name 'app'
   24 |         if err := app.Init(prjHome); err != nil {
      |                   ^
./main.go:29:12: 错误:reference to undefined name 'app'
   29 |         if app.IsProd() {
      |            ^
./main.go:35:9: 错误:reference to undefined name 'server'
   35 |         server.Run()
      |         ^

the gccgo just clone from gcc git:
gccgo (GCC) 12.0.1 20220217

go version is 1.16.4

my project struct like flow:
gccgo_demo
├── app
│   ├── app.go
│   ...
├── go.mod
├── go.sum
├── main.go
 ... other code

the go mod name is gccgo_demo so , the app/app.go has some import like gccgo_demo/app path.

A: I don't see your code but I guess the problem that you do not pass the include path.

The cgo tool will always invoke the C compiler with the source file's directory in the include path; i.e. -I${SRCDIR} is always implied. This means that if a header file foo/bar.h exists both in the source directory and also in the system include directory (or some other place specified by a -I flag), then "#include <foo/bar.h>" will always find the local version in preference to any other version.

So just do smth like
go build -x  -gccgoflags -I/path/to/your/file -Wl,-R,/opt/gccgo/lib64/ -compiler gccgo -o bin/app main.go

More details https://pkg.go.dev/cmd/cgo


text:
Q: How to show names in tableview as in iphone contact list with sections A to Z I have dictionary with keys A to Z  and sorted array with contact name and phone numbers.
var names = [Entry]()
var sortedphoneResult = NSArray()
var names = [(A, [Anna Haro]), (D, [Daniel Higgins Jr., Daniel Higgins Jr., Daniel Higgins Jr., David Taylor]), (H, [Hank M. Zakroff, Hank M. Zakroff]), (J, [John Appleseed, John Appleseed]), (K, [Kate Bell, Kate Bell])]

how i can show this names under A To Z Sections alphabetically in tableview???

A: You should store more info inside the array from which it would be easy to get numberofrows and numberofsections in the tableview.
For more info you can refer to this image i m attaching with comment.


text:
Q: Where to get ubuntu linux kernel source package? Where to get Ubuntu Linux kernel source package from? Not a Debian package.
Is there any repository which has tar/bz2 package of complete kernel sources of every version release.

A: There is a git repository for Ubuntu kernels.
It is http://kernel.ubuntu.com/git/ubuntu/
To get sources using git run
git clone git://kernel.ubuntu.com/ubuntu/ubuntu-xenial.git

For instance you can get Ubuntu 16.04 kernel sources from http://kernel.ubuntu.com/git/ubuntu/ubuntu-xenial.git
17.04 sources are at http://kernel.ubuntu.com/git/ubuntu/ubuntu-zesty.git

A: The answer to your question, you can find the Linux Kernel Archives at the following site.
https://www.kernel.org/
You can download the tarball.


text:
Q: Calling a Java Function from within a Superpowered SDK callback I'm defining a callback to process audio in Android using Superpowered SDK. I'm passing the JNIEnv using the clientData pointer in the callback. Is there anyway I can call a simple Java function to update some text on the main screen inside the callback?
My code is built on the FrequencyDomain example for Superpowered SDK.

A: This question is not related to Superpowered, but JNI: Java Native Interface.
You can call Java from native code, but it's quite complex (and ugly).
Check "Calling Java code from C/C++ programs" in this article by IBM: http://www.ibm.com/developerworks/java/tutorials/j-jni/j-jni.html


text:
Q: Gddrescue asks for a mapfile but refuses to create one I'm using Example 3 from gddrescue's documentation here to zero-write a disk and force pending bad sectors on it to be reallocated.
The same documentation states elsewhere that:

If mapfile does not exist, ddrescue will create it.

But when I run Example 3 near-verbatim:
ddrescue -vvvv --fill-mode=- -f --synchronous /dev/zero /dev/sdc mapfile.txt

...I get the error:

ddrescue: Mapfile 'mapfile.txt' does not exist or is not readable.

If I run:
ddrescue -vvvv --fill-mode=- -f --synchronous /dev/zero /dev/sdc -m /cygdrive/b/users/user/desktop/mapfile.txt

...I get a truncated version of the same error:

ddrescue: Mapfile '/cygdrive/b/users/user/desktop/mapfile.txt' does not exist or is not

I'm using gddrescue on Windows 7, via Cygwin.
Is this a bug with the Cygwin implementation of dd, or am I missing something?

A: Not a bug. It's the same on my Kubuntu. I think it's because of --fill-mode option you used. This mode has its own chapter of the documentation. What you are missing is this part [emphasis mine]:

When ddrescue is invoked with the --fill-mode option it operates in "fill mode", which is different from the default "rescue mode". That is, if you use the --fill-mode option, ddrescue does not rescue anything. It only fills with data read from infile the blocks of outfile whose status character from mapfile coincides with one of the type characters specified as argument to the --fill-mode option.

This means --fill-mode needs an already existing mapfile.

What are status characters and type characters here?

The phrase "status character from mapfile" should be understood according to this fragment:

The status character is one of these:
Character Meaning
'?'   non-tried block
'*'   failed block non-trimmed
'/'   failed block non-scraped
'-'   failed block bad-sector(s)
'+'   finished block
And here is an example mapfile:
# Mapfile. Created by GNU ddrescue version 1.23
# Command line: ddrescue -d -c18 /dev/fd0 fdimage mapfile
# Start time:   2015-07-21 09:37:44
# Current time: 2015-07-21 09:38:19
# Copying non-tried blocks... Pass 1 (forwards)
# current_pos  current_status  current_pass
0x00120000     ?               1
#      pos        size  status
0x00000000  0x00117000  +
0x00117000  0x00000200  -
0x00117200  0x00001000  /
0x00118200  0x00007E00  *
0x00120000  0x00048000  ?

Now "type characters specified as argument to the --fill-mode option" are characters that appear just after --fill-mode=.
So if the mapfile is like the above example and you use

*

*--fill-mode=-, then ddrescue will only fill 0x00000200 blocks starting at the position 0x00117000;

*--fill-mode=?-* (beware of shell globbing, unlikely but still), then ddrescue will fill fragments marked with ?, - or *.


text:
Q: Normal form(s) for the elements of hyperbolic triangle groups I'm seeking a reference or a sketch for any sort of normal form that would enable rapid enumeration without redundancies of the elements of hyperbolic triangle groups and/or von Dyck groups.

A: This thesis contains a complete rewriting system for every triangle group (see Section C at the end of the thesis). Then normal forms are just words that do not contain left parts of the rewriting rules (which is just a finite set of words). This gives enumeration of all elements without redundancies.

A: The general reference for this topic is "Word processing in groups", Epstein et. al., MR1161694 (93i:20036). Your groups all have automatic structures, and that book gives an enumeration method as you ask for, which applies to any automatic structure on a group.


text:
Q: UICollectionView CellForItemAtIndexPath not getting called I have two UICollectionViews in my UIViewController.
Let's say they are A and B, A and B are positioned at the same place in UIViewcontroller in the nib file, they have exact same sizes.
Now I set
A.delegate = self;
A.dataSource = self;

B.delegate = self;
B.dataSource = self;

[A registerNib:nib forCellWithReuseIdentifier:CELL_A];

[B registerNib:nib forCellWithReuseIdentifier:CELL_B];

in ViewDidLoad
then in CellForItemAtIndexPath,
I use a switch statement to show different cells.
then I use a segment control to control displaying a correct UICollectionViewcontroller on my selected segment.
In segment control value changed code. I use:
- (IBAction)sectionSelected:(id)sender {
    if (choosing A) {
        B.hidden = YES;
        A.hidden = NO;
        A.backgroundColor = [UIColor blackColor];
        [self getAData];
        [A reloadData];
    }
    else if (choosing B) {
        A.hidden = YES;
        B.hidden = NO;
        B.backgroundColor = [UIColor orangeColor];
        [self getBData];
        [B reloadData];
    }
}

A is displayed correctly when I set default selected segment as A. but when I switch to B, I can see B is load but the data is not loaded to B so I couldn't see anything except for the orange background. I put the NSLog in CellForItemAtIndexPath and find that the method is not being called after reloadData.
Here is some logging I get for A.collectionViewLayout.collectionViewContentSize; and B.collectionViewLayout.collectionViewContentSize;
content size of B = 768.000000, 24.000000
content size of A = 768.000000, 880.000000

When I set default selected segment as B, B is displayed correctly. I switch back to A which is also displayed correctly. However when I switch back to B again it shows an empty orange screen. Any idea what have gone wrong with my code?

A: From this answer
Change
  [A reloadData]/ [B reloadData]

to:
  [self.collectionView reloadItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]];
  [self.collectionView reloadData];

A: Probably you have lost the data of items in your array object, which you using for reloading/creating the collection view cells. Double check on array/data.

A: Is your getAData/getBData an asynchronous call? You may be hitting a race condition where the data isn't ready, so when you call reloadData the number of cells the collection view is creating is 0. This would also explain the small height in the content size.


text:
Q: Proving the surjective property in Chinese Remainder Theorem If $\textrm{R}$ is a commutative ring and $\left\{\textrm{I}_i\right\}_{i=1}^n$ are proper ideals of $\textrm{R}$ with $\textrm{I}_i+\textrm{I}_j = \textrm{R}$ for all $1 \leq i \neq j \leq n$, then the map $\phi$ from $\textrm{R}$ to $\displaystyle\frac{\textrm{R}}{\textrm{I}_1}\oplus\displaystyle\frac{\textrm{R}}{\textrm{I}_2}\oplus\cdots\oplus \displaystyle\frac{\textrm{R}}{\textrm{I}_n}$ given by
\begin{align*}
\phi(r) = (r+\textrm{I}_1, r+\textrm{I}_2,\ldots,r+\textrm{I}_n)
\end{align*}
is an onto ring homomorphism with
\begin{align*}
Ker(\phi) = \bigcap\limits^n_{i=1}\textrm{I}_i
\end{align*}
I have proven that $\phi$ is a ring homomorphism with kernel as given above. But I have proven that the map $\phi$ is onto, only when the ring $\textrm{R}$ has unity. What about the case when $\textrm{R}$ does not have a unity ? Would the theorem still be valid ? I have checked that this would be true if $n=2$. But for any $n\geq 3$, the proof become cumbersome. Most book that I've come across mentions that the ring in the Chinese Remainder Theorem should be a commutative ring with unity. If the theorem doesn't hold for $n \geq 3$ and a commutative ring with no unity, is their any counter-example?


text:
Q: What is the equivalent of the following sql statement in postgresql? I have the following SQL statement that is executed in a MySql database and it works successfully
cursor.execute("""SELECT COUNT(*), `deleted` FROM `tweets` WHERE `id` = %s""", (tweet['id'],))

What is the equivalent in postgres database?
Trying the following
cursor.execute("""SELECT COUNT(*), deleted FROM tweets WHERE id = %s""", (tweet['id'],))

Fails with error
 ERROR: ERROR:  column "tweets.deleted" must appear in the GROUP BY clause or be used in an aggregate function

I'm not sure where I should add the GROUP BY Clause.
Any help will be appreciated.

A: This statement:
SELECT COUNT(*), `deleted`
FROM `tweets`
WHERE `id` = %s

is malformed in any database, including MySQL, because the SELECT columns mix an aggregation function and a non-aggregation function and there is no GROUP BY.
Older versions of MySQL accept this syntax (an oversight that has happily been fixed!).  The value of deleted comes from an arbitrary row.  So, you can use any value of deleted to match the functionality.  So, use an aggregation function:
SELECT COUNT(*), MAX(deleted) as deleted
FROM `tweets`
WHERE `id` = %s


text:
Q: What switch should we use for PCoIP?
*

*We have a small lab space that seats 10 people and has 20 machines.

*Each machine is set to 1920x1200 resolution because the user apps are best used at that resolution.

*Currently the machines are all located close enough to montors that a DisplayPort cable will reach, but the pending lab remodel positions them around 80 feet or more away in racks.

*Our proposed solution is to use PCoIP.

*We purchased 10 PCoIP portals and 20 PCoIP host cards.

*We plan to set up a dedicated network to handle just the PCoIP traffic.

After testing just one portal and one host card with a cheap 1G switch from a local office supply store, we were left with less than good impressions about the usefulness in our lab.  The framerates were not spectacular and the mouse seemed jerky. Our concern is that we can't get away with the cheap 1G stuff from the store because adding more machines to the switch will just make the user experience worse.
What switch would be recommended to best support our PCoIP situation?  We will need to plug in at least 30 cables based on just those machines.  Is there a particular feature to search for that makes a difference?  Is there a switch that works best with PCoIP?
Added Info:
The reporting webapp for the host card shows maximum bandwidth usage to be 220000 kbps.  The average appears to be around 180000 kbps.  The reverse direction is much lower, like 15000 kbps.

A: What's the approximate bandwidth consumed? Both "in total" (with all "displayed" displays active, I take it that's roughly 10) and "for a single machine/display"?
I suspect the crucial point would be the backplane capacity of the switch, as that'll limit the total amount of traffic you're pushing through.
EDIT So, 220 Mbps, roughly. From your description, that looks to be a per-display value. I would expect that to work fine in any Gig-capable switch, once you're out of the "intended for consumer usage" tranche. You'll probably still be limited by the backplane of the switch, as you go to more displays. I can't really recommend any specific model, but any switch that provides a console port, telnet/ssh interface and SNMP, with 20-odd Gbps ports should work fine.

A: First update the firmware on the Portals and the card to version 3.3
Then start testing again...

A: Most switches (even the somewhat cheaper ones) have full switching fabric (meaning they can send and receive on all ports simultaneously, or close thereto). Just look at the switching fabric (sometimes also called throughput) of the device, it should be 2Gbps per port.


text:
Q: In kubernetes can ```service.spec.sessionAffinityConfig.clientIP.timeoutSeconds``` be set to infinity? As described in the title, can service.spec.sessionAffinityConfig.clientIP.timeoutSeconds be specified to infinity? I want the sessions never to change pod.

A: From the api docs timeoutSeconds specifies the seconds of ClientIP type session sticky time. The value must be >0 && <=86400(for 1 day) if ServiceAffinity == "ClientIP". Default value is 10800(for 3 hours).
So it can not be infinity.


text:
Q: Reading out decimal numbers in English
Possible Duplicate:
How to write decimal values in words

How do you read numbers like these?
0.12 "oh point twelve", "zero point one two", "zero and twelve hundreds"
And these ones?
0.345, 12.45

A: *

*0.12: "zero point one two" or "nought point one two"

*0.345: "zero point three four five" or "nought point three four five"

*12.45: "twelve point four five" for the number, "twelve forty-five" for the time and perhaps for money with implicit pennies or cents.

"point twelve" is not acceptable for a decimal, as it leads to confusion as to whether "point one" means .1 or .01.  After the decimal point you read each digit individually, though with times you can adjust as there may be an implicit minutes for the later digits.
You can use oh for nought or zero if you think there will be no confusion between O and 0 and o; there might be with say a password.

A: The treatment of numbers in language is an interesting topic.  In base 10, we have terms for numbers to the left of the decimal, according to the powers of 10 they represent: e.g., 496 is four hundred ninety-six.  For numbers to the right of the decimal, however--and also for numbers in bases other than 10--there isn't special terminology, and we simply speak each digit individually.
Having said that, it may be worth noting that certain common decimal values can be conveniently represented as fractions, presenting an alternative for pronunciation.  Here, the rule is to state the numerator as a standard integer but the denominator as an ordinal number--singular if the numerator is 1; plural otherwise.  So one-third, two-fifths, etc.
In the case of the fourths, we have options: it's common to refer to 1/4 and 3/4 as one quarter, and three quarters, while one-fourth and three-fourths are equally acceptable.  With 1/2, however, we have the maverick:  the only acceptable term for this fraction is one-half, which does not use the ordinal number or anything else that remotely sounds like the word two.


text:
Q: Spring Cloud Ilford (2020.0.3) WebClient DataBufferLimitException: Exceeded limit on max bytes to buffer Spring boot 2.5.3
Spring Cloud 2020.0.3
My understanding is this was fixed in Hoxton SR7?
    public byte[] findImage(String guid) {
        return webClient
            .get()
            .uri(sUrl + "/findImage/" + guid )
            .header(AUTHORIZATION_PROPERTY, AUTHENTICATION_SCHEME + clientToken)
            .retrieve()
            .onStatus(
                (HttpStatus::isError),
                it -> handleError(it.statusCode().getReasonPhrase()))
            .bodyToMono(FileResponse.class)
            .block(Duration.of(6000, ChronoUnit.MILLIS))
            .getContent();
    }

nested exception is org.springframework.core.io.buffer.DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144
        at org.springframework.web.reactive.function.client.WebClientResponseException.create(WebClientResponseException.java:229)

A: https://github.com/spring-projects/spring-framework/issues/23961
https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-client-builder-maxinmemorysize
@Slf4j
@Configuration
public class WebClientConfig implements WebFluxConfigurer {

    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        configurer.defaultCodecs().maxInMemorySize(16 * 1024 * 1024);
    }
}


text:
Q: Comprehensive security solution for ASP.NET MVC app If you were planning and preparing for a big ASP.NET MVC project how would you approach it to design and build comprehensive, extensible and maintainable security solution that requires

*

*users,

*roles,

*controller-level and action-level security,

*item-level security (applying users or roles to items),

*security trimming (hiding some menu options based on the above settings).

If you were to estimate the time and effort to produce this and would have to issue a qoute to the client, what would it be? You don't have to give a number in money, only billable hours.

A:
You don't have to give a number in money, only billable hours.

You want someone to do your work for free? Come on...
Authorization
Anyway, I would use Code Access Security and impersonation to implement security in all my services. Check the PrinicpalPermission attribute.
Controller/Action level
As for MVC, simply use the Authorize attribute to provide authorization. Derive it to provide a more finegrained control.
Security trimming
if (System.Thread.Threading.CurrentThread.CurrentPricinpal.IsInRole("Administrator"))
   //show menu item

Item level
Not possible with default MVC implementation. You need to do a manual check in your actions.
if (!System.Thread.Threading.CurrentThread.CurrentPricinpal.IsInRole(item.RequiredRole))
  return View("AccessDenied", null); //return accessdenied view.

Authentication
I don't know what kind of users you got. Are all registered in a AD domain? Then use Windows Authentication to authenticate your users. It's just a IIS setting..


text:
Q: Why does my function, that fills a textarea, only work the first time? Javascript:
function editQuestion() {
  $("body").on("click", ".edit_question", function(event) {
    $(this).closest("form").find("textarea").text("sample text");
    event.preventDefault();
  });
}

$(document).ready(function() {
  editQuestion();
});

HTML:
<form>
  <textarea>ormar</textarea>

    Cancel

</form>

When firing off the function by clicking the .edit_question link, everything is working as expected the first time.
But clicking more times (after manually removing the textarea content) doesn't do anything, why is this?

A: .text() only changes the initial value of the textarea, since the initial value is read from the element's content (<textarea>Initial value</textarea>).
Once you modified the value, the current value is stored in the value property of the DOM element. Changing the initial value after the textarea was modified doesn't have any effect.
That's why you should use .val() intead of .text().

A: Updated Demo  compare with Original Demo
Use .val() instead of .text() in case of inputs.
Check this,
$(document).ready(function () {
    $(document).on("click", ".edit_question", function (event) {

        $(this).closest("form").find("textarea").val('sample text');
        event.preventDefault();
    });
});

Note: The .text() method cannot be used on form inputs or scripts.

A: Try using the .val() method rather than .text() method for textarea
From documentation page:
The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.
link: http://api.jquery.com/text/


text:
Q: FB.Event.subscribe not registering status:true in Internet Explorer and Firefox I would like my my FB app to automatically get information about the user if they are already logged in to FB. In chrome the following code works perfectly and gets the requested information. In Internet Explorer and Firefox, however, the following code only works if I add FB.login(); into the window.fbAsyncInit function. This causes a pop-up to load everytime the page is accessed which I do not want. By using an alert to test my code I have determined that the FB.Event.subscribe function is not even even being called in IE and FF, but works fine in Chrome. Why is this behaving differently in IE and FF and how can I get it to work correctly?
 (function(d){
       var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
       if (d.getElementById(id)) {return;}
       js = d.createElement('script'); js.id = id; js.async = true;
       js.src = "//connect.facebook.net/en_US/all.js";
       ref.parentNode.insertBefore(js, ref);
     }(document));

// Init the SDK upon load
window.fbAsyncInit = function() {
   FB.init({
      appId      : 'ID', // App ID
      channelUrl : 'Channel Path', // Path to your Channel File
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true,  // parse XFBML
      oauth      : true,
      frictionlessRequests: true
   });

  // listen for and handle auth.statusChange events
   FB.Event.subscribe('auth.statusChange', function(response){
      console.log(response);
      if (response.authResponse) {
        // user has auth'd your app and is logged into Facebook
         FB.api('/me', function(me){
            if (me.name) {
               userID = me.id;
            }
         });
         document.getElementById('auth-loggedout').style.display = 'none';
         document.getElementById('auth-loggedin').style.display = 'block';
      }else {
         // user has not auth'd your app, or is not logged into Facebook
         $('#auth-displayname').html('');
         document.getElementById('auth-loggedout').style.display = 'block';
         document.getElementById('auth-loggedin').style.display = 'none';
      }
   });
}

A: auth.statusChange only gets called when you are already logged into facebook.
I beleave you are testing on chrome, so you are most likely logged in. but when you go to firefox or IE and you are not logged in auth.statusChange nevers gets called
Test by login out of facebook on chrome, and youll see it doesnt work there either.
So you have to make an explicit call to FB.getLoginStatus() to init stuff as soon as the page loads, and listen on statusChange for changes in the future:
FB.getLoginStatus(function(response){
  if (response.authResponse) {
    // user has auth'd your app and is logged into Facebook
     FB.api('/me', function(me){
        if (me.name) {
           userID = me.id;
        }
     })
    }
 });

// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response){
  if (response.authResponse) {
     document.getElementById('auth-loggedout').style.display = 'none';
     document.getElementById('auth-loggedin').style.display = 'block';
  }else {
     // user has not auth'd your app, or is not logged into Facebook
     $('#auth-displayname').html('');
     document.getElementById('auth-loggedout').style.display = 'block';
     document.getElementById('auth-loggedin').style.display = 'none';
  }

});


text:
Q: jQuery UI Sortable with React.js buggy I have a sortable list in React which is powered by jQuery UI. When I drag and drop an item in the list, I want to update the array so that the new order of the list is stored there. Then re-render the page with the updated array. i.e. this.setState({data: _todoList});
Currently, when you drag and drop an item, jQuery UI DnD works, but the position of the item in the UI does not change, even though the page re-renders with the updated array. i.e. in the UI, the item reverts to where it used to be in the list, even though the array that defines its placement has updated successfully.
If you drag and drop the item twice, then it moves to the correct position.
    // Enable jQuery UI Sortable functionality
    $(function() {
      $('.bank-entries').sortable({
        axis: "y",
        containment: "parent",
        tolerance: "pointer",
        revert: 150,
        start: function (event, ui) {
            ui.item.indexAtStart = ui.item.index();
        },
        stop: function (event, ui) {
            var data = {
                indexStart: ui.item.indexAtStart,
                indexStop: ui.item.index(),
                accountType: "bank"
            };
            AppActions.sortIndexes(data);
        },
      });
    });

    // This is the array that holds the positions of the list items
    var _todoItems = {bank: []};

    var AppStore = assign({}, EventEmitter.prototype, {
      getTodoItems: function() {
        return _todoItems;
      },
      emitChange: function(change) {
        this.emit(change);
      },
      addChangeListener: function(callback) {
        this.on(AppConstants.CHANGE_EVENT, callback);
      },
      sortTodo: function(todo) {
        // Dynamically choose which Account to target
        targetClass = '.' + todo.accountType + '-entries';

        // Define the account type
        var accountType = todo.accountType;

        // Loop through the list in the UI and update the arrayIndexes
        // of items that have been dragged and dropped to a new location
        // newIndex is 0-based, but arrayIndex isn't, hence the crazy math
        $(targetClass).children('form').each(function(newIndex) {
          var arrayIndex = Number($(this).attr('data-array-index'));
          if (newIndex + 1 !== arrayIndex) {
            // Update the arrayIndex of the element
            _todoItems[accountType][arrayIndex-1].accountData.arrayIndex = newIndex + 1;
          }
        });

        // Sort the array so that updated array items move to their correct positions
        _todoItems[accountType].sort(function(a, b){
          if (a.accountData.arrayIndex > b.accountData.arrayIndex) {
            return 1;
          }
          if (a.accountData.arrayIndex < b.accountData.arrayIndex) {
            return -1;
          }
          // a must be equal to b
          return 0;
        });

        // Fire an event that re-renders the UI with the new array
        AppStore.emitChange(AppConstants.CHANGE_EVENT);
      },
    }

  function getAccounts() {
    return { data: AppStore.getTodoItems() }
  }

  var Account = React.createClass({
      getInitialState: function(){
          return getAccounts();
      },
      componentWillMount: function(){
          AppStore.addChangeListener(this._onChange);

          // Fires action that triggers the initial load
          AppActions.loadComponentData();
      },
      _onChange: function() {
          console.log('change event fired');
          this.setState(getAccounts());
      },
      render: function(){
          return (
              <div className="component-wrapper">
                  <Bank data={this.state.data} />
              </div>
          )
      }
  });

A: The reason jQuery UI Sortable doesn't work with React is because it directly mutates the DOM, which is a big no no in React.
To make it work, you would have to modify jQuery UI Sortable so that you keep the DnD functionality, but when you drop the element, it does not modify the DOM. Instead, it could fire an event which triggers a React render with the new position of the elements.

A: Since React uses a Virtual DOM, you have to use the function React.findDOMNode() to access an actual DOM element.
I would call the jQuery UI function inside the componentDidMount method of your component because your element has to be already rendered to be accessible.
// You have to add a ref attribute to the element with the '.bank-entries' class
$( React.findDOMNode( this.refs.bank_entries_ref ) ).sortable( /.../ );

Documentation - Working with the browser (everything you need to know is here)
Hope that makes sense and resolves your issue

A: The trick is to call sortable('cancel') in the stop event of the Sortable, then let React update the DOM.
componentDidMount() {
    this.domItems = jQuery(React.findDOMNode(this.refs["items"]))
    this.domItems.sortable({
        stop: (event, ui) => {
            // get the array of new index (http://api.jqueryui.com/sortable/#method-toArray)
            const reorderedIndexes = this.domItems.sortable('toArray', {attribute: 'data-sortable'})
            // cancel the sort so the DOM is untouched
            this.domItems.sortable('cancel')
            // Update the store and let React update (here, using Flux)
            Actions.updateItems(Immutable.List(reorderedIndexes.map( idx => this.state.items.get(Number(idx)))))
        }
    })
}


text:
Q: TooManyRedirects Error with requests module Currently trying to get html for url and am encountering an error raised by the requests module in python.
What's the preferred method for handling the TooManyRedirects Error raised by requests? How do access the html for the site?
site = requests.get("http://www.hortonworks.com/blog/data-science-apacheh-hadoop-predicting-airline-delays")

A: Normal way to disallow redirects is to use allow_redirects=False
For eg.,
site = requests.get(url,allow_redirects=False)

But that is NOT the solution to your problem,
Adding a user-agent solves the redirect issue and gets the page-source successfully.
Try this,
headers={"User-Agent":"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}

url="http://www.hortonworks.com/blog/data-science-apacheh-hadoop-predicting-airline-delays"

site = requests.get(url,headers=headers)
print site.url

-
Out[]: 'http://hortonworks.com/blog/data-science-apacheh-hadoop-predicting-airline-delays/'


text:
Q: Sitecore Show Time in 24 Hours Format in the Content Editor In an Item there is a field type "DateTime". For this field in the content editor the options to enter time is in 12 Hours Format (AM,PM). As shown below:

How Can I show the time in 24 Hours format to the content editor.
Thanks!

A: You can override the default time format by extending Sitecore.Shell.Applications.ContentEditor.DateTime class, finding the TimePicker inside that control and changing the Format property (which is set to t by default, which means that standard locale of Content Editor User will be used). Just to be completely honest, I don't think that changing this should be recommended for any Sitecore solution, but it's doable if required.
First of all, create your custom class inheriting from Sitecore.Shell.Applications.ContentEditor.DateTime, e.g.:
namespace My.Assembly.Namespace.ContentEditor
{
    public class CustomDateTime : Sitecore.Shell.Applications.ContentEditor.DateTime
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            TimePicker timePicker = FindTimePicker(this);
            if (timePicker != null)
            {
                timePicker.Format = "HH:mm";
            }
        }

        private TimePicker FindTimePicker(Control control)
        {
            if (control != null)
            {
                var timePicker = control as TimePicker;

                if (timePicker != null)
                {
                    return timePicker;
                }

                foreach (Control childControl in control.Controls)
                {
                    if ((timePicker = FindTimePicker(childControl)) != null)
                    {
                        return timePicker;
                    }
                }
            }
            return null;
        }
    }
}

Now in web.config find <controlSources> tag, and add following line inside that tag:
  <source mode="on" namespace="My.Assembly.Namespace.ContentEditor" assembly="My.Assembly" prefix="customcontent"/>

Now go to Sitecore Desktop, switch to core database, find /sitecore/system/Field types/Simple Types/Datetime item and change value of the Control field to customcontent:CustomDateTime:

Switch back to master database and check any Date Time field, e.g.:

A: @Marek Musielak Answer is great but as he wrote that its really not recommended to change the default settings of Sitecore Solution.
So I searched a little bit more and found another way, on per-user basis. In Sitecore shell xx/sitecore/shell A user can also change it by going to Control Panel > Preferences > Set Your Regional and Language Options.


text:
Q: python django_tables2 filtering and pagination issue I am trying to render a web page with a table of filtered data. The filtering should be based on a date submitted by the user. For the initial GET request I have tried setting an initial_date of '01 01 2015' and when a POST request is submitted, the date is extracted form the POST query-set.
The issue I am having appears to be related to  django_tables2 pagination.
The initial table data is successfully rendered after the user submits the date form in the POST request, however when I click the "Next" button on the bottom of the table I receive "Exception Value: That page contains no results".
Clicking the Next button appears to call the GetCustomData() function as a GET request, which then uses the "initial_time" rather than the filtered data.
How do I format my function so that subsequent GET requests return the filtered data from the initial POST request?
views.py
from django.shortcuts import render
from .models import TestResult
import datetime
import django_tables2 as tables
from .forms import DateForm

class SimpleTable(tables.Table):
    class Meta:
        model = TestResult
        attrs = {"class": "paleblue"}

def GetCustomData(request):

    form = DateForm()

    if request.method == 'POST':
        request_time = datetime.datetime.strptime((request.POST['custom_date_day']+' '+request.POST['custom_date_month']+' '+request.POST['custom_date_year']), '%d %m %Y')
        time_min = datetime.datetime.combine(request_time, datetime.time.min)
        time_max = datetime.datetime.combine(request_time, datetime.time.max)
        custom_query = TestResult.objects.filter(timestamp__range=(time_min, time_max))
        table = SimpleTable(custom_query)
        table.paginate(page=request.GET.get('page', 1), per_page=30)

        return render(request, 'custom_results.html', {'table_results': table,
                                                       'form': form})

    elif request.method == 'GET':
        initial_time = datetime.datetime.strptime('01 01 2015', '%d %m %Y')
        time_min = datetime.datetime.combine(initial_time, datetime.time.min)
        time_max = datetime.datetime.combine(initial_time, datetime.time.max)
        custom_query = TestResult.objects.filter(timestamp__range=(time_min, time_max))
        table = SimpleTable(custom_query)
        table.paginate(page=request.GET.get('page', 1), per_page=30)

        return render(request, 'custom_results.html', {'table_results': table,
                                                       'form': form})

A: Probably not the cleanest approach, but I managed to get it working by referencing and updating a list outside the GetCustomData() function.


text:
Q: iOS looking for new shared files Where's the best place in an iOS application to look wether or not the user has added new files to the shared files from his app? In the awakeFromNib method? Or somewhere else?

A: The awakeFromNib: method is fine, but you can also do this in one of the initialization (-initWith...) methods, or when the application delegate is being instantiated by UIKit, in the application:didFinishLaunchingWithOptions: method. Also make sure to check for new files in th e applicationDidBecomeActive: method, and you may also want to add a Refresh button or Pull-to-Refresh to your app for ergonomical reasons.


text:
Q: Make PHP Working in Many Ports Is there any possible way to make PHP run on both ports 80 and 8800? If yes please tell me instructions how to do it. I am using apache2 as my HTTP server.
EDIT: I am actually trying to make PHP work into tornado framework which runs on port 8800.

A: I think you are talking more about having apache run on multiple ports. If this is the case you should simply have to edit your apache config to have the following:
Listen 80
Listen 8080

You will likely need to add virtual hosts for both of these ports ie:
NameVirtualHost *:80
NameVirtualHost *:8080

<VirtualHost *:80>
    DocumentRoot "C:\WWW\test.com\public_html"
</VirtualHost>

<VirtualHost *:8080>
    DocumentRoot "C:\WWW\test.com\public_html"
</VirtualHost>

Once this has been done you need to restart the apache service.


text:
Q: Steganography in android with native Java library support issue I am developing a multi-platform application which will use the "F5 Steganography" to hide a message inside a JPG image captured from the device's camera.
Currently my objectives are to make an android application and desktop Java application.
I have found the jar file of "F5 Steganography" from here
I have successfully implemented the library in Java desktop application but the problem is coming in android implementation.
I have imported the jar file in the android project but in the embedding and extraction of the message, I am facing issues on android.

*

*Extract issue
On Extract, the issue I am facing now is that the imported library is using "sun.security.provider.SecureRandom" but android is unable to find it.
here is log-cat error:
10-06 22:25:44.324: E/dalvikvm(32150): Could not find class 'sun.security.provider.SecureRandom', referenced from method crypt.F5Random.<init>

Now I am guessing that android is not supporting the "sun.security.provider.SecureRandom" library, if it is so, the what should I do? Can I import the library manually? P.S I don't want to change anything in "F5 Steganography" library code due to the fact it is being used as it is on Java platform. Here is the code for reference:
public void clk1(View v){
    EditText eto=(EditText) findViewById(R.id.editText2);
    EditText ett=(EditText) findViewById(R.id.editText3);
    Extract e=new Extract();
    String information[] = new String[5];
    information[0]="-p";
    information[1]="123";
    information[2]="-e";
    information[3]=ett.getText().toString();
    information[4]=eto.getText().toString();
    e.main(information);
}

*

*Embed Issue
On Embed, I am facing an issue similar to before. Error is saying that it could not find the "james.JpegEncoder" class in the library, yet it is present there as seen in the attached image.
Here is log-cat trace:
10-06 23:00:39.678: E/dalvikvm(410): Could not find class 'james.JpegEncoder', referenced from method main.Embed.main

Here is the code for reference:
public void clk0(View v){
    EditText eto=(EditText) findViewById(R.id.editText2);
    EditText ett=(EditText) findViewById(R.id.editText3);
    EditText eti=(EditText) findViewById(R.id.editText1);
    Embed e=new Embed();
    String information[] = new String[8];
    information[0]="-e";
    information[1]=ett.getText().toString();
    information[2]="-p";
    information[3]="123";
    information[4]="-q";
    information[5]="100";
    information[6]=eti.getText().toString();
    information[7]=eto.getText().toString();
    e.main(information);
}

What should I do to counter this problem? I have reached here after solving many issues but got stuck here. I have searched through the Internet and could not find a proper solution even remotely relating to my issue.

A: If you would like to use in Android the tool you referred (https://code.google.com/p/f5-steganography), you have to import some libraries from sun or include in your project the following classes from sun.security.provider:

*

*NativePRNG.java

*NativeSeedGenerator.java

*SecureRandom.java

*SeedGenerator.java

*SunEntries.java
This post is a bit old but might help others in the futre... I just tried myself and works like charm :)


text:
Q: What purpose does counts serve? Line 7 I am wondering what purpose does the counts variable serve, the one right before the last end?
# Pick axe page 51, chapter 4

# Count frequency method
def count_frequency(word_list)
    counts = Hash.new(0)
    for word in word_list
        counts[word] += 1
    end
    counts    #what does this variable actually do?
end

puts count_frequency(["sparky", "the", "cat", "sat", "on", "the", "mat"])

A: The last expression in any Ruby method is the return value for that method. If counts were not at the end of the method, the return value would be the result of the for loop; in this case, that's the word_list array itself:
irb(main):001:0> def count(words)
irb(main):002:1>   counts = Hash.new(0)
irb(main):003:1>   for word in words
irb(main):004:2>     counts[word] += 1
irb(main):005:2>   end
irb(main):006:1> end
#=> nil
irb(main):007:0> count %w[ sparky the cat sat on the mat ]
#=> ["sparky", "the", "cat", "sat", "on", "the", "mat"]

Another way someone might write the same method in 1.9:
def count_frequency(word_list)
  Hash.new(0).tap do |counts|
    word_list.each{ |word| counts[word]+=1 }
  end
end

Though some people consider using tap like this to be an abuse. :)
And, for fun, here's a slightly-slower-but-purely-functional version:
def count_frequency(word_list)
  Hash[ word_list.group_by(&:to_s).map{ |word,array| [word,array.length] } ]
end

A: Ruby doesn't require you to use the return statement to return a value in a method.  The last line evaluated in the method will be returned if an explicit return statement is omitted.

A: It provides the return value for the function; it's how the result (which is stored in that variable) is transmitted back to the caller (i.e., the line of code at the end.) The last expression evaluated in a Ruby function is used as the return value.

A: Counts is a dictionary, i.e. it is an associative map of keys to values.
In this case, the words are the keys, the values are the number of occurrences.
The dictionary is returned from the function count_frequency


text:
Q: nodejs async.parallel recursion I am test async.parallel behaviour with nodejs.

var async = require("async");

function makeSleepFunction(i) {
 return function(callback) {
   setTimeout(function() {
     console.log('   + sleep '+i);
     callback(null, i);
   }, i);
 }
}

function parallel(i, callback) {
 // console.log('----parallel '+i+'-----')
 return async.parallel([makeSleepFunction(i), makeSleepFunction(i+10)], callback);
}

// Expected result OK: 100 before 10
parallel(100, function(err, results) {
 console.log('async.parallel 1 done: '+results.toString());
 parallel(10, function(err, results) {
  console.log('async.parallel 2 done: '+results.toString());
 });
});

// Expected result KO: 100 after 10
setTimeout(function() { // Wait the 1st test is finished
 console.log('\n\n***** The followig test des not give the expected result:')
 parallel(100,
  parallel(10, function(err, results) {
   console.log('async.parallel 2 done: '+results.toString());
  })
 );
}, 300);

Can somebody explain with the second test does not give the expected result?
Thanks for help.

A: The async parallel waits for every task done. Your tasks are timed i and i+10. The first call the parallel waits for the longest sleep which is 110 ms.
The second call for same reason waits for 20 ms.
Your code waits minimum 110 + 20 = 130 ms before writes a message: "async.parallel 2 done"
In the second test you not pass a callback, but you call imediately a new parallel function.
try this way:
setTimeout(function() { // Wait the 1st test is finished
    console.log('\n\n***** The followig test des not give the expected result:')
    parallel(100,function(){ //not call, but only declare a function
        parallel(10, function(err, results) {
            console.log('async.parallel 2 done: '+results.toString());
        })
    });
}, 300);

or you can use bind, of course


text:
Q: How does instagram fixed and change the bar when scroll up in android? Notice: I cannot provide pictures due to my reputation.
When we scroll down from the feed in instagram the action bar is actually hide and a white bar that indicate the user name and time is fixed at the top. When we scrolling down again the previous white bar will scroll up and next bar will fixed at the top again. I want to make something like that for my school project.
So my first question is how can I hide the action bar while scrolling up and show it again while i scrolling down?
Second question is how can I make the white bar just like how instagram did it?
Any help will be highly apperciate!!

A: I am not a 100% sure what to do to accomplish the movable action-bar, but you may want to look into "toolbar" which may provide more manipulation potential.
http://www.google.com/design/spec/layout/structure.html#structure-toolbars
http://developer.android.com/reference/android/widget/Toolbar.html
http://cyrilmottier.com/2013/05/24/pushing-the-actionbar-to-the-next-level/
Also, if you are looking for the white part that has to do with usernames and such inside instagram, you should look for an effect called sticky-headers.
Awesome library to quickly add list view animations, such as sticky-headers
https://github.com/nhaarman/ListViewAnimations


text:
Q: Magento 1.9 join table issue I'm having an issue with Magento 1.9.2.4 trying to  make a join on my collection, here's the problem:
Actually I've got a custom table named product_banner which I'm getting by:
$collection = Mage::getModel('mymodule_productbanner/productbanner')->getCollection();

But I need to join this table with catalog_category_entity_varchar, I've tried solution:
    $catalogTable = Mage::getSingleton('core/resource')->getTableName('catalog/category');

    $collection = Mage::getModel('exablack_productbanner/productbanner')->getCollection()->getSelect()->join(array('category' => $catalogTable),
        'main_table.category_id = category.entity_id AND category.attribute_id = 41');

But for no avail...
The pure sql query I need to run to get my desired result would be:
    select catalog_category_entity_varchar.value, product_banner.banner_url,
    product_banner.text from product_banner inner join catalog_category_entity_varchar
    on product_banner.category_id = catalog_category_entity_varchar.entity_id and
    catalog_category_entity_varchar.attribute_id = 41;

How can I achieve this with magento collections?

A: Please try with below code as I haven't run a query on MySQL because I have no any custom module table include with category id field but I build it based on your collection
$collection =
Mage::getModel('mymodule_productbanner/productbanner')->getCollection()
->addFieldToSelect('banner_url');

$attribute =
Mage::getSingleton('catalog/config')->getAttribute('catalog_category',
'name');

$collection->getSelect()
     ->join(array('category_varchar' => $attribute->getBackendTable()),'category_varchar.entity_id=
 main_table.category_id',array('value'))
     ->where('category_varchar.attribute_id = ?',$attribute->getId());

echo $collection->getSelect();
die;

and run this query on MySQL.Hope it will work for you.


text:
Q: Alfanumerico determinato por un new Date() Quiero hacer un generador de ID "aleatorio" que sea un Alfanumérico de 24 carácteres.
Para "evitar" colisiones, quiero que el ID esté formado por:

*

*Los primeros X cáracteres vegan determinados por la fecha.

*Los restantes un simple random alphanumerical (esta parte no tiene misterio).

Cuál es la mejor aproximación para la primera parte?
Entiendo que el objetivo inicial es tener un long/int en plan new Date().getTime() % <caparlo a un determinado rango> , pero luego este long/int no tengo claro cuál es la manera óptima para pasarlo a una cadena alfanumérica.
Gracias!
PD: Si hay una alternativa conocida ya existente para generar dichos ID (alfanuméricos de 24 óptimos para evitar colisiones), también lo valoro!

A: Espero te sirva,puedes agregar o disminuir los caracteres del id generado
import java.security.SecureRandom;
import java.time.LocalDate;

public class gokuPass {
public static String generadorDePasword() {
        String fecha=String.valueOf(LocalDate.now()).replaceAll("-", "");
        int diferecial=24-fecha.length();//diferencia de los 24 caracteres con la cantidad de digitos de la fecha
        String alfaMin = "abcdefghijklmnopqrstuvwxyz";
        String alfaMay = alfaMin.toUpperCase();
        String numeros = "0123456789";

        String datosToString = alfaMin + alfaMay + numeros;
        SecureRandom random = new SecureRandom();

        if (diferecial < 1) throw new IllegalArgumentException();

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < diferencial; i++) {
            // 0-62 (exclusivo), retorno aleatorio 0-61
            int rndCharAt = random.nextInt(datosToString.length());
            char rndChar = datosToString.charAt(rndCharAt);

            sb.append(rndChar);
        }

        return fecha+sb.toString();
    }

    public static void main(String args[]) {

    for (int i = 0; i < 5; i++) {
            System.out.println("Id de 24 carcateres Aleatorio: " + generadorDePasword());
            System.out.println("\n");
        }

    }
}


text:
Q: This OFFSET FETCH command passes validation but produces no results? I have to connect accounts to users, and in doing so I have ensure I'm selecting the right account to ensure eligibility and do this with multiple accounts.  The following code passes validation but yields no results.
I already have a list of the CustomerNumbers on the table that are the PK.

SELECT
x.CustomerNumber,
a.ACC_AccountId

FROM Eligibles x

LEFT JOIN
    ACCOUNTS a
    ON x.CustomerNumber = a.ACC_CustomerNumber
    ORDER BY a.ACC_LIVEcode ASC,
         a.ACC_Limit DESC,
         a.ACC_Amount DESC
    OFFSET 0 ROWS
    FETCH FIRST 1 ROWS ONLY

I am not getting any Account ID's to populate, whereas nearly everyone should have one.

A: In an ascending sort, NULLs are first.  So, you get the mismatches first.  Instead, add an expression so the matches are first:
SELECT x.CustomerNumber, a.ACC_AccountId
FROM Eligibles x LEFT JOIN
     ACCOUNTS a
     ON x.CustomerNumber = a.ACC_CustomerNumber
ORDER BY (CASE WHEN ACC_CustomerNumber IS NOT NULL THEN 1 ELSE 0 END),
         aa.ACC_LIVEcode ASC, a.ACC_Limit DESC, a.ACC_Amount DESC
OFFSET 0 ROWS
FETCH FIRST 1 ROWS ONLY


text:
Q: add filter to change specific part of function I am trying to remove a class from a button in woocommerce that is in the wc_cart_functions.php file. There is a string in the wc_add_to_cart_message function which inserts this string:
%s %s
function wc_add_to_cart_message( $products, $show_qty = false ) {
$titles = array();
$count  = 0;

if ( ! is_array( $products ) ) {
    $products = array( $products );
    $show_qty = false;
}

if ( ! $show_qty ) {
    $products = array_fill_keys( array_keys( $products ), 1 );
}

foreach ( $products as $product_id => $qty ) {
    $titles[] = ( $qty > 1 ? absint( $qty ) . ' × ' : '' ) . sprintf( _x( '“%s”', 'Item name in quotes', 'woocommerce' ), strip_tags( get_the_title( $product_id ) ) );
    $count += $qty;
}

$titles     = array_filter( $titles );
$added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', $count, 'woocommerce' ), wc_format_list_of_items( $titles ) );

// Output success messages
if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
    $return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wc_get_raw_referer() ? wp_validate_redirect( wc_get_raw_referer(), false ) : wc_get_page_permalink( 'shop' ) );
    $message   = sprintf( '%s %s', esc_url( $return_to ), esc_html__( 'Continue Shopping', 'woocommerce' ), esc_html( $added_text ) );
} else {
    $message   = sprintf( '%s %s', esc_url( wc_get_page_permalink( 'cart' ) ), esc_html__( 'View Cart', 'woocommerce' ), esc_html( $added_text ) );
}

wc_add_notice( apply_filters( 'wc_add_to_cart_message', $message, $product_id ) );
}

I tried to create a filter which would just replace that specific string, since it appears twice and in both instances I want the class removed. This does not seem to work though:
add_filter( 'wc_add_to_cart_message', 'add_to_cart_mod');
 function add_to_cart_mod($message) {
    $message = str_replace ( '%s %s' , '%s %s', $message );
 return $message;
}

With this filter set as it is, I still see the button with the same unchanged class. Any thoughts?

A: Your filter expects to find %s, but that was replaced by the previous call to sprintf: these  %s are not there any more.
You could try with a regular expression:
$message = preg_replace ('/(]+ )class="button wc-forward"/',
                         '$1class="button"', $message );

The [^>]+ part means: any sequence of characters that does not contain a > (end of a tag).
$1 means: whatever was matched between the parentheses. It could be something like <a href="http://example.com".

A: You can try this:
add_filter( 'wc_add_to_cart_message', 'add_to_cart_mod');

function add_to_cart_mod( $message ) {
    // Output success messages
    if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
        $return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wc_get_raw_referer() ? wp_validate_redirect( wc_get_raw_referer(), false ) : wc_get_page_permalink( 'shop' ) );
        $message   = sprintf( '%s %s', esc_url( $return_to ), esc_html__( 'Continue Shopping', 'woocommerce' ), esc_html( $added_text ) );
    } else {
        $message   = sprintf( '%s %s', esc_url( wc_get_page_permalink( 'cart' ) ), esc_html__( 'View Cart', 'woocommerce' ), esc_html( $added_text ) );
    }

    return $message;
}


text:
Q: Photodiode connection to ADC I am designing a product where an ambient light sensor is used to adjust the LCD's brightness.
The following circuit is implemented to read the light sensor. The LIGHT_SENSE pin is connected directly to an ADC input of an MCU.

Later on I chose the SFH-203-P photodiode, which is connected directly to the pins 5 & 6 of the above connector.
Unfortunately, this diode combined with this circuit do not play well. The whole circuit is extremely insensitive to light. A very high luminance is needed to produce any readings at the ADC, much greater than typical room light.
Even worse, the PCBs have been manufactured in large quantities already, so a change in the PCBs is not possible. I am stuck with only changing components.
I tried to change R644. I found out that at 5.6 M ohms, the circuit behaves exactly as needed, and I am about to propose this change.
However I am not confident on using such a high-value resistor for this purpose. I am afraid that such a great impedance may cause problems that I cannot see now, like noise, instability of the circuit etc.
Is it safe to use such a big value for the photodiode biasing?
What problems may arise from such a change?

A: I guess it would be redundant to suggest that you should have breadboarded this portion of the circuit if you couldn't predict the current from the PD specs. That's a relatively small very fast PIN photodiode.
I would suggest you replace the photodiode with either a much larger one or a phototransistor. There are phototransistors available in a two-lead package.
Using such a high value resistor can cause issues with leakage and other factors (often there is a very significant loading depending on reading rate for typical MCU ADCs) so you would need to study the datasheet for whatever MCU you are using and maybe do some testing.

A: A very quick examination of the data sheet shows:

Photocurrent     (EV = 1000 lx, Std. Light A, VR = 5 V)
  (typ (min))
  IP 9.5 (≥ 5) µA

So at 1000 lux (a very bright indoor level), you'll get about 5 to 10 uA of current.
Then the voltage across R644 will (of course) be about 0.05 to 0.1 volt under the equivalent of TV studio lighting. For normal office lighting more like 0.015 to 0.025 volts. Bump the resistor up to 1 M and the voltage will probably be about 1 - 3 volts.
In your case, it takes 5.6 M to get what you want, which suggest that the lighting level is even lower than "normal office lighting". This rather makes sense since you're adjusting an LCD backlight.
I would not expect any real issues with using a larger resistor, except the ones Spehro has already suggested. If your pcb fab and assembly are doing their jobs properly the boards are cleaned of flux after soldering. You ARE using a reputable shop, right? Not necessarily the cheapest you can find? This should take care of leakage. 5.6 M is not all that big a resistor in the normal scheme of things. Noise should not be an issue, especially with R641/C611 in place. You might want to check the data sheet for C611 and look at the expected leakage there.


text:
Q: Creating a MATLAB program using Euler Explicit Method I want to solve following ODE using Euler explicit method.
$$S'(t)=\frac{b}{m}\bigg(u(t)+\frac{P(t)}{p}\bigg)$$
where $S(0)=\frac{q}{m}$.
We can have any value for the parameters. $P(t)$ should be a non-decreasing function. I don't understand how to introduce the function in the program. Suppose $P(t)=t$ then what will be the formula of Euler explicit method?
MATLAB Code:
T = 10;
N = 100;
h = T/N;
b = -1;
q = 1;
m = 1;
p = 1.5;

S(0) = q/m;
S(1)=s(0);

for j=1:N
   aj    =(j-1)*h;
   S(j+1)=(b*h/p*m)*t(j) + S(j);
end

I have written this code. I have taken the simplest case taking $u(t)=0$. But I am confused about $P(t)$. I have taken $P(t)=t$ as a non decreasing function. But how I have to introduced it? Do I have to give an initial value for t also?

A: For a step length of h = T/N (note that in this form $N$ does not count the initial time $t=0$) the Forward Euler update equation reads in general form
S(j + 1) = S(j) + h * b/m * (u(j) + P(j) / p)

and for $u(t) \equiv 0$ and $P(t) = t$
S(j + 1) = S(j) + h * b/m * (t_0 + j * h) / p


text:
Q: implement segmentUI android I am trying to implement the segmentUI found in the ios sdk in android. I have been able to determine that I need to use the radiogroup. My query is how to effectively implement this idea. Appreciate any help.

A: You need to create 9patch images corresponding to each individual segment, that is, left, center and right and then implement the radiobutton UI which you can position using xml.


text:
Q: unable to understand Null pointer in c I am working on singly linked list and unable to solve problem (I think the problem is in add function something with NULL pointer), the problem is it only adding first number to list and skipping rest of call to add function.
#include<stdlib.h>
#include<stdio.h>

struct node
{
  int i;
  struct node* next;
};

struct node* head = NULL;

int add(int val)
{
  if(head == NULL)
  {
    head = (struct node*)malloc(sizeof(struct node));
    head->i = val;
  }
  else
  {
    struct node* current = head;
    while(current != NULL)
    {
      current = current->next;
    }
    current = (struct node*)malloc(sizeof(struct node));
    current->i = val;
  }
}

int print(struct node* first)
{
  while(first != NULL)
  {
    printf("%d\n",first->i);
    first = first->next;
  }
}

int main()
{
  add(36);
  add(46);
  add(97);
  print(head);
  return 0;
}

A: You are never setting node->next to NULL (for both head->next and current->next paths). Allocating using malloc does not clear the allocated memory, so you need to do this yourself.
Also, when you are adding the second element, you are iterating until current reaches NULL, but you never set previous_node->next to point to new element, so you never actually "link" anything in your linked list.
Also, you shouldn't cast the result of malloc in C.

A: Two issues here.  First, when creating a new node you don't set next to NULL.  So when you iterate through the list, you end up reading garbage data, invoking undefined behavior.
Then next problem is that when you iterate through a non-empty list, you "fall off" the end of the list, so current is NULL at the end of the loop and there's no link to the end of the list.  You need to stop when current->next is null, then create the new node there.
void add(int val)     // change return type to void since nothing is being returned
{
  if(head == NULL)
  {
    head = malloc(sizeof(struct node));  // don't cast return value of malloc
    head->i = val;
    head->next = NULL;                   // terminate list
  }
  else
  {
    struct node* current = head;
    while(current->next != NULL)         // loop until you're on the last node
    {
      current = current->next;
    }
    current->next = malloc(sizeof(struct node));
    current->next->i = val;
    current->next->next = NULL;          // terminate list
  }
}

A: The main reason why you do not see the effects of adding the second and subsequent nodes is that when you allocate a new node that is not the head node, you store the pointer to it only in local variable current of function add().  You need to instead store it in the next pointer of the previous node.  Compare this with your original code:
    struct node* current = head;
    while (current->next != NULL) {
      current = current->next;
    }
    current->next = malloc(sizeof(*current->next));

Note also that, as @Lousy observed also, you fail to set the next pointers of new nodes to NULL.  You must do this, for until you assign some value to those fields, their contents are indeterminate.


text:
Q: Bootstrap Carousel / Preload images I've searched but haven't been able to find out a way to preload images using Bootstrap Carousel. I am building up a portfolio site with a lot of images and right now Bootstrap carousel works properly after all the images are loaded.
Any ideas?

A: I'm pretty sure that the images in the Bootstrap carousel aren't loaded dynamically, but loaded with the page. Therefore there isn't any reason for you to preload.
Preloading is used when images are loaded onto the page dynamically. When this happens, the page has to load this image separate from the page, causing an undesirable lag between dynamic addition and image downloading/appearing.
Because bootstrap's carousel has it's images included in the HTML and simply hidden with javascript, the images are loaded with the page, resulting in whatever preloading would achieve for you.
tl;dr: You can't it's already done for you.


text:
Q: ¿Por qué MongoDB 4.0.1 es mucho más lento que Mongodb 3.2 Había trabajado con mongodb 3.2 y Nodejs
Por probar, me instalé la última versión de mongo, la 4.0.1, ejecuté un test de escritura (documentos muy simples con _id, date, docset_id (numerical)) , y en 3.2 se demora 1 a 1.5 segundo insertando 10000 registros.
Con mongodb 4 se demora 10, 15, 20, 30 segundos y va subiendo cada vez que pruebo, insertar los mismos 10000.
Añado información de mi ambiente:
Intel core i7-4790k 8 core  4ghz
SSD storage
Wired tiger para los dos tests

Los tests fueron ejecutados en el mismo equipo
Pruebas realizadas (en el mismo equipo):

*

*XFS FileSystem

*WiredTiger

*Intel Xeon E3-1230 v3 - 3.3 GHz - 4 core(s)

*NodeJS 8

*mongodb driver nodejs v 3.1.3

*Insertar 10000 simples documentos: {nombre: 'xxxx', docset_id: Número}

Mongodb 3.2 Tests:

*

*1400 ms

*1215 ms

*1684 ms

*1020 ms

*2300 ms

*1230 ms

Mongodb 4.0.1 (lo mismo para 3.6.6) Tests:

*

*12234 ms

*16456 ms

*27567 ms

*24870 ms

*26560 ms

*42654 ms


text:
Q: Problems building wxwidgets in cygwin I followed all the instructions provided in the docs/msw/install.txt file for building wxWidgets 3.0.2 using cygwin with all the necessary tools installed.
And even after using the configure script with all the different possible options.
But still it doesn't build properly.The configure script executes correctly but when i use make it shows me this error.
Error:
cannot convert 'wxString' to 'const void*' for argument '2' to 'ssize_t cygwin_conv_path(cygwin_conv_path_t, const void*, void*, size_t)'
             cygwin_conv_path(CCP_POSIX_TO_WIN_W, strDir, windowsPath, MAX_PATH);
If any one can help me on this i will highly appreciate it.
Thank you.

A: First of all, are you absolutely sure that you really want to use the Cygwin port of wxWidgets? This is almost never a good idea and it's strongly recommended to use Cygwin as the build environment for building the native MSW port using MinGW (cross-)compiler as explained in this post.
If you really do need Cygwin, it looks like you need to insert .c_str() call here, i.e. write cygwin_conv_path(CCP_POSIX_TO_WIN_W, strDir.c_str(), windowsPath, MAX_PATH), as you're probably using --enable-stl and the implicit conversion is not available.


text:
Q: Why does Scala ignore exclamation points in command line arguments? If I write a Scala script (or App) that just prints out the command line arguments, I notice that it ignores all the '!' characters.  For example, if my script looks like:
println(args(0))

And I run it with:
scala MyScript "Hello!"

I get the output:
Hello

And if I run it with:
scala MyScript "Hello! World!"

I also get:
Hello

What's going on?  What is the purpose of the ! character in arguments that causes this behaviour?

A: ! is history substitution.
Try scala MyScript hello! with ! at EOL to see it work as if quoted.
http://www.gnu.org/software/bash/manual/bashref.html#Event-Designators
http://www.gnu.org/software/bash/manual/bashref.html#Single-Quotes
On windows, the "scala.bat" command script has delayed expansion enabled.
http://en.wikibooks.org/wiki/Windows_Batch_Scripting
http://en.wikibooks.org/wiki/Windows_Batch_Scripting#SETLOCAL
http://en.wikibooks.org/wiki/Windows_Batch_Scripting#Command-line_arguments
To disable interpretation of !myvar!:
C:\Users\you> scala greeting.script "hello^!"
hello!

C:\Users\you> set world= Bob

C:\Users\you> scala greeting.script "hello!world!"
hello Bob


text:
Q: How to add href to Wicket DataTable cells I have simple DataTable with ListDataProvider.
HTML markup is as simple as <table wicket:id="data"/>.
I need to open other page with query string to display form for single selected item.
How to add links (a href) to cells?

A: Actual answer I found at official doc https://cwiki.apache.org/confluence/display/WICKET/Adding+links+in+a+DefaultDataTable


text:
Q: What happens if I glue a Möbius strip to a sphere with a hole in it? For no appreciatable reason I've been trying to figure out 2-manifolds. Unfortunately, I've been struggling to find good enough sources on learning the basics, so it's pretty likely that my question will betray my lack of understanding of the basic topological concepts, which I believe to be a good thing.
Imagine we cut a circural hole in a sphere. It will have a single boundary. Let's also take a Möbius strip. It also has a single boundary. let's glue those boundaries together. What will be the resulting shape? What it will be homeomorphic to? It might be a cliché thing to say in the field, but I have hard times imagining the resulting object.
Might be a duplicate with Gluing a Möbius strip into a sphere. - I do not understand either the question nor an answer.
Okay, after getting some answers that cleared things up for me, and re-reading & re-analyzing the question above, I can confirm that indeed I posted a duplicate question. I'm sorry. :(


text:
Q: How to open current submenu? In Jquery I have this sample:
link
CODE HTML:

    Menu 1

    Menu 2

link1

link2

    Menu 3

link1

link2

CODE JS:
$('.menu a').click(function(){
   var subMenu  = $(this).closest("li").find("submenu-1");
   if(subMenu){
     alert("open current sub menu")
   }

 });

What I want to do it's the next thing...for example:
1.If you click on the "menu2" to open its submenu.
2.If you click on the "menu3" to hide submenu for "menu2" and open submmenu for "menu3"
You can send your a short example and tell me please how to solve this problem?
Thanks in advance!

A: Use jquery show()/toggle()
   $('.menu a').click(function(){
   var subMenu  = $(this).next(".submenu-1");
   if(subMenu.length >0){
     $(".submenu-1").not(subMenu).hide();
    $(subMenu).toggle();
   }

 });

http://codepen.io/anon/pen/jqmpqP

A: i think this will help you. much cleaner.
$('.menu a').click(function(){
  $(".submenu").hide();
  $(this).next().show();
});

http://codepen.io/airsakarya/pen/BKRPoE


text:
Q: How do I use WindowManager to overlay an Activity? How can I have an activty overlay like the one used in Facebook Messenger using the WindowManager?

This is what I want

This is what I have so far

first widnow manger thats who have chatheads bubble
 params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,

            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);

    params.gravity = Gravity.TOP | Gravity.LEFT;
    params.x = 0;
    params.y = 100;

This is the code I have for my activity dialog
WindowManager.LayoutParams params = getWindow().getAttributes();

    params.alpha = 1.0f;    // lower than one makes it more transparent
    params.dimAmount = 0f;  // set it higher if you want to dim behind the window
    params.type = WindowManager.LayoutParams.TYPE_PHONE;
    params.flags = WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON|              WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;

    params.x = 0;
    params.y = (int) (height - dpToPx(this,40));

    getWindow().setAttributes(params);

This is the activity in my manifest:
 <activity
        android:name=".activity.popup"
        android:configChanges="orientation|screenSize"
        android:excludeFromRecents="true"
        android:label="@string/app_name"
        android:launchMode="singleInstance"
        android:taskAffinity=""
        android:theme="@style/Theme.FloatingWindow.Popup"
        android:windowSoftInputMode="adjustPan|adjustResize"
        tools:ignore="ExportedActivity" >
    </activity>

Here is the @style/Theme.FloatingWindow.Popup style in style file I made:
 <style name="Theme.FloatingWindow.Popup" parent="@style/Theme.AppCompat.Light" >
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="android:windowIsFloating">false</item>
    <item name="android:windowSoftInputMode">adjustResize</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowActionModeOverlay">true</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowFrame">@null</item>
    <item name="android:windowCloseOnTouchOutside">false</item>
    <item name="android:windowAnimationStyle">@null</item>
    <item name="android:backgroundDimEnabled">false</item>

</style>

A: Use this it has worked for me.
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);

A: TYPE_SYSTEM_ALERT view is shown on top of all other applications and activities. Therefore, you can't make any activity appears on top of that view.
To achieve what you want you have to add your chat view to window manager the same way you added the chat bubbles instead of using an activity.
Example:-
WindowManager.LayoutParams dialogParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT);
LayoutInflater inflater = LayoutInflater.from(context);
View activityView = inflater.inflate(R.layout.activity_layout, null);
windowManager.addView(activityView, dialogParams);

Another solution:-
You can just remove the system alert view temporally when you show your chat activity and make that chat bubbles part of the activity's layout to make it looks like the first image above.
Then you can add the system alert view later when you need to use it (you can attach that to some events such as activity's onPause or when the user click something).


text:
Q: TypeError: 'DataFrame' object is not callable не могу найти в чем ошибка Есть такой код. Идея в том, чтобы ускорить обработку большого датафрейма мультипроцессингом.
class Get_data(object):

def __init__(self):

    self.data_path = '/../'
    self.t = "preAVL"
    self.num_cores = multiprocessing.cpu_count()
    self.num_partitions = 20

def getDF(self):
    df_preAVL = pd.DataFrame()
    search_string = self.data_path + "/*" + self.t + "*"
    for filename in glob.glob(search_string):
        try:
            df_preAVL = df_preAVL.append(pd.read_excel(filename))
        except:
            print "Problem file: {}".format(filename)
            raise
            df_preAVL = df_preAVL.reset_index(drop=True)
    del df_preAVL['trainUpTime']
    return df_preAVL

def setLossCarByIMEI(self, row):
    if not pd.isnull(row['car']):
        return row['car']
    if pd.isnull(row['dev_imei']):
        return np.NAN

    try:
        return map_imei2car_id[row['dev_imei']]
    except:
        pass

    return np.NAN

def parallelize_dataframe(self,df, func):
    df_split = np.array_split(df, self.num_partitions)
    pool = Pool(self.num_cores)
    df = pd.concat(pool.imap(func, df_split))
    pool.close()
    pool.join()
    return df

def pre_AVL(self,df):
    df['car'] = df.apply(s.setLossCarByIMEI, axis=1)
    return df

Вызываю таким образом
if __name__ == "__main__":
s = Get_data()
df_preAVL=s.getDF()
#df_preAVL = s.pre_avl(df_preAVL)

df_preAVL = s.parallelize_dataframe(df_preAVL, s.pre_AVL(df_preAVL))

print df_preAVL

Полный текст ошибки такой :
TypeError: 'DataFrame' object is not callable
Начинает ругаться на :
df = pd.concat(pool.imap(func, df_split))
Где у меня ошибка? Импорт необходимых модулей сделан-pandas,multiprocessing и тд

A: *

*мультипроцессинг скорее всего уже используется Pandas и Numpy, чтобы проверить np.__config__.show()

*если попытаться распараллелить самому, то с очень высокой вероятностью получится еще медленнее

*getDF можно немного оптимизировать:

def getDF(self):
    dfs = []
    search_string = self.data_path + "/*" + self.t + "*"
    for filename in glob.glob(search_string):
        try:
            dfs.append(pd.read_excel(filename).drop('trainUpTime', axis=1))
        except:
            print "Problem file: {}".format(filename)
            raise
            df_preAVL = df_preAVL.reset_index(drop=True) # почему в секции except ???
    return pd.concat(dfs, ignore_index=True)

*самое важное: df.apply(s.setLossCarByIMEI, axis=1) можно и нужно векторизировать (это даст самый большой прирост производительности).
Если map_imei2car_id - словарь вида {'IMEI':'car_id'}, то

df['car'] = df.apply(s.setLossCarByIMEI, axis=1)

можно заменить на:
mask = df['car'].isnull() & df['dev_imei'].notnull()
df.loc[mask, 'car'] = df.loc[mask, 'dev_imei'].map(map_imei2car_id)

Пример:
имеем следующий DF:
In [190]: df
Out[190]:
    car dev_imei
0   NaN    IMEI1
1  car2    IMEI2
2   NaN    IMEI3
3  car4    IMEI4
4   NaN      NaN
5   NaN    IMEIx

и словарь:
In [191]: map_imei2car_id
Out[191]: {'IMEI1': 'car1', 'IMEI2': 'car2', 'IMEI3': 'car3', 'IMEIx': 'carX'}

Замена:
In [192]: mask = df['car'].isnull() & df['dev_imei'].notnull()

In [193]: df.loc[mask, 'car'] = df.loc[mask, 'dev_imei'].map(map_imei2car_id)

Результат:
In [194]: df
Out[194]:
    car dev_imei
0  car1    IMEI1
1  car2    IMEI2
2  car3    IMEI3
3  car4    IMEI4
4   NaN      NaN
5  carX    IMEIx


text:
Q: Rest API Basic Authentication Is it okay if the server returns the API Key and Shared Secret Key when a client tries to login on the API using Basic Authentication? For example, if a user enter this link http://api.example.com/authorize?auth=some_encoded_Base64_string, the response will be:
Content-Type: application/xml
Date: Fri, 10 Nov 2006 20:04:45 GMT
Transfer-Encoding: chunked
Authorization: apiKey;secretKey

Will I have issues using this method? I wanted to be like this since the API core methods will only accept APIKey hashes and in order to obtain that they need to use the Basic Authentication as they're first step. I'm not gonna use OAuth here for now.
I'm trying out the new ASP.NET Web API for this project.

A: HTTP does not define an Authorization header in the response so if you need to define a custom header, use X- prefix.
Also from the design point, HTTP headers are to pass data which is orthogonal to the call. You seem to be trying to pass a piece of data which needs to be in the payload so I would refrain from using the headers.
I would pass this data in the payload.
If you use SSL and pass data in the URL, HTTP headers or payload it will be secure.


text:
Q: Bound on inverse operator Define
$X = {C^{2, \alpha}}(U \times [0,T])$ and
$Y = {C^{0, \alpha}}(U \times [0,T])$ where $U$ is some real interval.
Let $F:X \to Y$ be a map. Let $DF(g):X \to Y$ be a bounded linear operator for each $$g \in \{C^{2, \alpha}(U \times [0,T]) \} \cap \{g : |g(x,t)| < w\}.$$ Note that $DF(g)$ is the Frechet derivative of F at point $g$.
Suppose we have $$DF(g)h = \mathcal{L}(h) := h_t(x,t) - a(x,t)h_{xx}(x,t) + b(x,t)h_x(x,t) + c(x,t)h(x,t)\tag{1}$$ for $h \in X.$
where $a$, $b$ and $c$ depend on $g$ and are uniformly bounded in $Y$ provided the $g$'s are uniformly bounded in $X$ norm.
We also have the bound
$$\lVert h \rVert_{C^{2, \alpha}} \leq C\lVert \mathcal{L}(h)\rVert_{C^{0, \alpha}} + C\lVert h(\cdot, 0) \rVert_{C^{2, \alpha}}\tag{2}$$
where the constant $C$ doesn't depend on $T$ and depends only on norms of $g.$
I am told that this bound (2) is

a bound on the mapping norms of the inverses of the Frechet derivatives that doesn't depend on $T$

How does the bound (2) mean that the $DF[g]^{-1}$ are uniformly bounded? Applying the inverse of the Frechet derivative to (1) and using the bound gives
$$\lVert DF[g]^{-1}\mathcal{L}(h) \rVert \leq C\lVert \mathcal{L}(h)\rVert_{C^{0, \alpha}} + C\lVert h(\cdot, 0) \rVert_{C^{2, \alpha}}$$
but not sure how to extract the operator norm from here.
Can someone help me please?


text:
Q: How to calculate "scanLegth" param from Bitmap.getRGB565(...) I'm trying get bytes from bitmap in blackberry using the next method in Bitmap:
getRGB565(byte[] rgbData, int offset, int scanLength, int x, int y, int width, int height)

But i have read the params and i don't know how must i calculate scanLength:

scanLength - Width of a scanline (in bytes) within the data array.

Any idea?

A: Here scanLength is the full width of the original image, while width is the width of the rectangle you are copying from.
If you are copying the whole image it is the same, but if you are copying only a part of the image you'll have scanLength > width.
See also the Bitmap#getRGB565 javadoc

A: To get byte[] from Bitmap I used this: http://blackberry-digger.blogspot.com/2009/05/code-convert-bitmap-to-png-and-then.html and it worked fine.

A: Sorry it was too easy . In getARG is another example , it must be used usually with the same int width param