text:
Q: Mixing UTF8 and latin1_bin fields in MySQL with PHP On a database I'll have to store names and such in UTF8, and hashes in latin1_bin. I called SET NAMES utf8, but I noticed that it corrupted the latin1 fields when I tried to read them (I was able to write them just fine). Which is odd, since if I understood correctly that query is only about sending data to the server, not receiving it.
phpMyAdmin displays broken data too.
Any clue about what I might be doing wrong?
(using MAMP 1.9.6)
edit: this answer specifies this is also the charset used to send data back to the client. I'm getting confused: what's the point of specifying the charset of a column if that will be ignored anyway?
edit:
excerpt from the column definition:
  `tok` char(64) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
  `sal` char(16) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
...
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_roman_ci ;

excerpt from queries:
SELECT tok,sal FROM user WHERE id=4 LIMIT 1

.
INSERT INTO user (tok, sal) VALUES (x'1387ea0c22277d3000bd23241c357e3a9ba45a2e28f50581d63a73bf785a7458a95cca4de27d0a86588f5bdfa94415d6a255c2c0379ebc2f00dacba03ae6b866', x'8fca28a592c29f245ff0a3ba5f97420c')

A: You should change your table definition to use MySql's BINARY type, which is the perfect fit for this kind of data:

The BINARY and VARBINARY types are similar to CHAR and VARCHAR, except
  that they contain binary strings rather than nonbinary strings. That
  is, they contain byte strings rather than character strings. This
  means that they have no character set, and sorting and comparison are
  based on the numeric values of the bytes in the values.

The column definitions would become:
`tok` binary(64) NOT NULL,
`sal` binary(16) NOT NULL,

A: set names ... only sets the character set of the connection (of the client side only!) for both sending and receiving the data. It is not related to the encoding of the fields in the database! It is only related to the encoding which you use as a client to the database, e.g. in PHP. The database engine will always convert the encoding between the encoding in tables to the encoding specified in set names ... query.
So in table definition you just specify encoding for each field as you need, and you don't change anything in the way how you used the set names ... command - it just remains the same as before.

A: Leaving SET NAMES on, and the INSERT query intact, I changed the SELECT query to:
SELECT BINARY(tok) AS tok, BINARY(sal) AS sal FROM user WHERE id=4 LIMIT 1

i.e. I casted the hash fields to binary.
While this worked, I'll leave this open in case someone provides a (perhaps more correct?) alternative.


text:
Q: Got more ylabels than specified by set_yticklabel() I got more ticklables in the y direction than I expected. My Y-ticklabel should have only 6 labels [100.,  70.,  50.,  30.,  20.,  10.], yet the plot show 8 labels and some in formate different from what I set. I do have more label ticks than I expected, yet not every tick is associated with  a label. Here is a link for the data file that I am using  https://app.box.com/s/8tp8r9fcb3owv7gqljqcehg5kj4zawtk
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt

#%%
myfile            = xr.open_dataset("all_daily_00_01.nc")
varnamePP         = myfile["u"]

timeP     = myfile['time']
lonP      = myfile['lon']
latPP     = myfile['lat']
levelPP   = myfile['level']
latP      = latPP[::-1]
levelP    = levelPP[::-1]

dti       = timeP.to_index()
periods   = dti.to_period(freq='D')

lat0=np.where(latP == 0)[0][0]

uwind=myfile['u'][:,::-1,::-1,:]

#%%
plt.figure(figsize=(15,6))
ax1=plt.subplot(1,1,1)
plt.contourf(dti[:],levelP.data,uwind[:,:,lat0,30].T,\
             np.arange(-60,60+6,6),cmap='bwr')
plt.yscale('log')
ax1.set_yticks(levelP.data)
pre_list1 = np.array(["{:4d}".format(int(x)) for x in levelP.data])
ax1.set_yticklabels(pre_list1)
plt.gca().invert_yaxis()

plt.colorbar()
plt.show()

I exptected to see only 6 labels in the y direction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 9 images shrinking together in a 3x3 grid in HTML & CSS? I have 9 images in a 3x3 grid shape on my web page.  At the moment it looks fine when I am viewing on my widescreen laptop, but when I view it on a smaller device the images stack on top of each other because it is responsive.  I would like the images to shrink down together (and remain in their 3x3 grid) instead of stacking.  I don't even know where to start.
Thanks in advance!
Sorry there isn't much to the code.  My section is 940px wide and each image is 300px wide and tall.

A: The best way is by using display:inline-block, max-widths and percentages
DEMO http://jsfiddle.net/kevinPHPkevin/Ptqde/
section {
    max-width:300px;
}
img {
    max-width:80px;
    display:inline-block;
    width:30%;
}

A: I've whipped up a sample of how to implement this.
The HTML code is a simple unordered list with 9 empty li elements inside a ul. The CSS is a percentage based set of rules within their fixed size parent:
li {
    width:33%;
    height:33%;
    top:33%;
    list-style:none;
    position:absolute;
}
li:nth-child(-n+3) {
    top:0;
}
li:nth-child(n+7) {
    top:66%;
}
li:nth-child(3n+2) {
    left:33%;
}
li:nth-child(3n+3) {
    left:66%;
}

In my example I used a fixed background with background-size:cover to put the images on there - it speaks for itself that you can put anything in the li elements since this approach ensures they always have the correct size.


text:
Q: filtering data in a text file using awk I am trying to filter rows based on one column in a big text file. here is a small example:
example:
-3261   1
777 1
-45574  1
1017    1
-2802   1
969 1
1800    1
-128768 1
-7614   1
-136751 1
-64104  1
134844  1

I want to filter based on the first column. if the numbers in the 1st column are smaller than 4000 or larger than -4000 keep the row and filter out the rest. here is the expected output:
expected output:
-3261   1
777 1
1017    1
-2802   1
969 1
1800    1

I am using awk using this code:
awk -F "\t" '{ if($1 >= -4000 || $1 <= 4000) { print } }' infile.txt > outfile.txt

using this code output is the same as input file. do you know how to fix it?

A: first of all, you should know that

smaller than 4000 or larger than -4000

and

smaller than 4000 AND larger than -4000

are different.
-80000 is valid for the OR condition, however not for the 2nd. I hope you meant the right thing. For your requirement, (the OR one), you can do (following your "or" requirement ):
awk '$1>=-4000 || $1<=4000'   file

Note, this will first check >=-4000,  that is, a row with value 99999999 will be valid, in output.
If you meant the AND condition, you need:
awk '$1<4000 && $1>-4000' file

A: another way to write this
$ awk '$1^2 <= 4000^2' input_file

A: Could you please try following.
awk '$1<4000 && $1>-4000'   Input_file

Where is your code going wrong, you need to put && condition since you want to check both conditions to be TRUE. || conditions will print those elements also where anyone of the conditions is TRUE too.
More information on && and || operators from man awk page:

   The &&, ||, and !  operators are logical AND, logical OR, and logical NOT, respectively, as in C.  They do short-circuit evaluation,

also as  in
         C,  and are used for combining more primitive pattern expressions.  As in most languages, parentheses may be used to change
  the order of evalua-
         tion.


text:
Q: Creating index with alias Sorry for the rudimentary question.I'm developing PHP small test class that manipulates AWS Elasticsearch Service.
<?php
namespace MyCompany\Aws;

use Elasticsearch\ClientBuilder;

class ElasticsearchApi {
    private $client;

    function __construct(string $hosts='', string $username='', string $password=''){
        ... //configure $this->client
    }
    /**
     * Create index
     * @param string $index
     * @param array $body
     * @return bool
     */
    public function createIndex(string $index, array $body = []):bool{
        $request = array(
            'index' => $index,
            'body' => $body
        );
        $ret = $this->client->indices()->create($request);
        return $ret['acknowledged'];
    }
}

And call createIndex function specifying alias as described at:
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html
<?php
require 'vendor/autoload.php';
use MyCompany\Aws\ElasticsearchApi as ES;

$es = new ES();

$body = array('aliases'=>array(
                'actions'=>array(
                    'add'=>array(
                        'alias'=>'sample-alias',
                        'index'=>'test-index'
                    )
                )
        ));
$ret = $es->createIndex('test-index',$body);
var_dump($ret);

This operation normally ends:
PS D:\My_Documents\Proj\Elasticsearch\index-gen> php es-lib-test.php
bool(true)
PS D:\My_Documents\Proj\Elasticsearch\index-gen>

However the generated index does not seem to have alias.

What is wrong with createIndex parameter? I'm using version 7.8 of Elasticsearch on AWS.
Addendum
Based on the @Val 's suggestion, I changed the code as follows:
$body = array(
    'aliases'=>array(
        'sample-alias'=>array()
    )
);
$ret = $es->createIndex('test-index',$body);
var_dump($ret);

However I got the following exception. Are there any mistakes?
PS D:\My_Documents\Proj\Elasticsearch\index-gen> php es-lib-test.php
PHP Fatal error:  Uncaught Elasticsearch\Common\Exceptions\BadRequest400Exception: {"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"No alias is specified"}],"type":"illegal_argument_exception","reason":"No alias is specified"},"status":400} in D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php:641
Stack trace:
#0 D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php(328): Elasticsearch\Connections\Connection->process4xxError(Array, Array, Array)
#2 D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\ezimuel\ringphp\src\Future\CompletedFutureValue.php(55): React\Promise\FulfilledPromise->then(Object(Closure), NULL, NULL)
#3 D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\ezimuel\ring in D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php on line 641

A: Your body should simply look like this:
$body = array('aliases' => array('sample-alias' => array()));

The syntax you're using is for the _aliases endpoint not for the index creation one.


text:
Q: How to get SqlParamter replaced in SELECT SqlCommand? In an existing codebase there is hardcoded SQL and I want to avoid SQL injection.
The below code uses SqlCommand together with SqlParameters. The query does not return any data. However, when I remove the parameters the query returns the correct results.
How can I use SqlParameters with a SELECT statement?
        string atUsername = "@username"; //does not work
        //string atUsername = "Demo1"; //THIS WORKS
        string atPassword = "@password"; //does not work
        //string atPassword = "222"; //THIS WORKS
        string sql = @"SELECT userId, userName, password, status, roleId, vendorId
        FROM users
        WHERE username = '" + atUsername + "' AND password = '" + atPassword + "'";

        SqlCommand cmd = new SqlCommand(sql);

        cmd.Parameters.Add(atUsername, SqlDbType.NVarChar, 20);
        cmd.Parameters[atUsername].Value = "Demo1";
        //cmd.Parameters.AddWithValue //also does not work

        cmd.Parameters.Add(atPassword, SqlDbType.NVarChar, 20);
        cmd.Parameters[atPassword].Value = "222";
        //cmd.Parameters.AddWithValue //also does not work

        SqlConnection conn = new SqlConnection(connStr);
        cmd.Connection = conn;
        conn.Open();

        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        Console.WriteLine(dt.Rows != null);
        if (dt.Rows != null)
        {
            Console.WriteLine(dt.Rows.Count);
        }

        conn.Close();
        conn.Dispose();

I have also unsuccessfully tried alternatives using

*

*SqlCommand.ExecuteReader and SqlDataReader

*IDisposable pattern

*Replace cmd.Parameters.Add(atUsername with
SqlParameter pUsername = new SqlParameter();
            pUsername.ParameterName = atUsername;
            pUsername.Value = "Demo1";
            cmd.Parameters.Add(pUsername);"
PS. I've heard of EntityFramework but I cannot use EF in this case (long story).

A: The root of your problem is that you use variable names inside string literal:
 WHERE username = '@username' AND password = '@password'

So they are not treated as variable names by sql server. Instead you are searching for user with name "@username" and password "@password". Correct way is:
WHERE username = @username AND password = @password


text: Q: Kafka streams application high memory usage after scaling broker We noticed a high memory usage of our kafka streams applications after scaling our brokers from 3 to 6 brokers. Is there a link between memory usage of client applications and broker count?


text:
Q: How to determine change points in data? I have a data which consists of multiple measurements for proportion of cells for controls and patients. As you can see from the figures, the proportions increase with age and this increase starts at the earlier ages for patients.
So, is there a way that I can determine such a change point and quantify its significance?
I have checked some time-series packages but as far as I can see they require one measurement per time point.
Any help is appreciated. Thank you!
Controls

Patients

Edit: You can reach the data with the following link

A:
the proportions increase with age and this increase starts at the earlier ages for patients.

*

*I wager these data are highly amenable to log transformation. I am distrustful of the scatterplot due to the long positive skew of the response. Nevertheless, the hypothesis is well framed as the above

*The natural test for the hypothesis as above is to fit the linear and quadratic terms of age with an interaction by "case"-status, whatever the disease is. You can test the hypothesis about the inflection point using linear combinations of the coefficients

*If this is a retrospective analysis, be cautious of lead time bias. That is, "cases" were more likely to be identified as "cases" because surveillance of "proportion" (whatever that is) was performed sooner and more frequently

Edit: illustrating code below
with(df, plot(age, lproportion, type='n'))
by(df, df$group, function(df) {
  Col <- unique(df$group)
  points(df$age, df$lproportion, col=Col)
  # if any interest in the smoothing spline result
  # lines(with(na.omit(df), smooth.spline(age, lproportion)), col=Col)
  qfit <- lm(lproportion ~ age + I(age^2), data=df)
  uage <- sort(unique(df$age))
  lines(uage, predict(qfit, newdata = data.frame('age'=uage)), lty=2, col=Col)
})
legend('topleft', pch=1, col=unique(df$group), legend = unique(df$group))

library(lmtest)
fit0 <- lm(lproportion ~ group + (age + I(age^2)), data=df)
fit1 <- lm(lproportion ~ group*(age + I(age^2)), data=df)
lrtest(fit1, fit0)

The log transform of the response was taken and is plotted in the figure below, with the black points representing the proportions of "CD8+ RO+ CCR7- d0" in controls and the red points the "CD8+ RO+ CCR7- d0" in patients. Quadratic trendlines were estimated using least squares regression. We remark that the estimated concavity differs. That is, cases and controls have the same estimated proportion at age 20 and at age 60, however, at age 40 the cases have a predicted proportion of 20 whereas controls have a predicted proportion of about 12 (confirm this).

To test the hypothesis that quadratic curves differ between the two samples we fit age and the square of age along with an effect for group in a linear model, and then further adjusted for the interaction between group and age and its square. The 2-degree of freedom Likelihood Ratio Test was not statistically significant ($p = 0.1981$).


text:
Q: Are there differences in loot quality between the different Lost Eternia Shards levels on survival? If there is a difference, does the quality increase in the order they fall in the story?

A: Loot quality actually increases with release date:

*

*Mistymire -> Moraggo/Karathiki -> Aquanos -> Sky City (when released)

What wave you're on, difficulty, and hardcore mode also contribute to loot quality. Note that these are for random drops only; reward qualities are more consistent between levels, but are widely random in quality (i.e. you are just as likely in getting an awesome monkey in Karathiki survival as you are getting an awesome Seahorse in Aquanos).


text:
Q: Merge function in C with pointers I've been given an assignment to create function which merges 2 increasingly sorted lists, without creating additional one, only with pointers. It would be lovely if someone would give me a hint or a reasoning why my code is failing to do so:(
node_t *merge(node_t *l1, node_t *l2) {
    node_t *i;
    node_t dummy;
    i = &dummy;
    if (l1->value < l2->value) {
        dummy.next = l1;
        l1 = l1->next;
    } else {
        dummy.next = l2;
        l2 = l2->next;
    }
    while (i->next != NULL) {
        if (l1->value < l2->value && l1->next != NULL) {
            i->next = l1;
            l1 = l1->next;
        }
        if (l1->value >= l2->value && l2->next != NULL) {
            i->next = l2;
            l2 = l2->next;
        }
    }
    return dummy.next;
}

A: Don't use a dummy node, you have all necessary nodes... Just change the links...
First determine which list contains the lower element:
node *finalList;
if (l1->value<l2->value) {
    finalList = l1;
    l1 = l1->next;
} else {
    finalList = l1;
    l1 = l1->next;
}

then use a pointer to move through the final list:
node *current = finalList;

Now loop over the lists:
while(true) {
    if (l1->value<l2->value) {
        current->next = l1;
        current = current->next; // one more in the final list from l1
        l1 = l1->next;           // move in l1
        if (l1==NULL) {          // l1 empty, everything remains in l2
            current = l2;
            break;
        }
    } else {
        current->next = l2;
        current = current->next;
        l2 = l2->next;
        if (l2==NULL) {
            current = l1;
            break;
        }
    }
}

You just have to tackle empty lists at start...

A: Your function has some problems:

*

*it will have undefined behavior if either argument list is empty,

*the test for the ends of lists are incorrect: once the sublist with the lower element is reduced to a single element, the loop runs forever without any effect.

Using a dummy node to simplify the code is not a problem, here is how to fix your function:
node_t *merge(node_t *l1, node_t *l2) {
    node_t dummy;
    node_t *i = &dummy;
    for (;;) {
        if (l1 == NULL) {
            // list 1 exhausted: link in the rest of list 2
            i->next = l2;
            break;
        }
        if (l2 == NULL) {
            // list 2 exhausted: link in the rest of list 1
            i->next = l1;
            break;
        }
        if (l1->value <= l2->value) {
            // list 1 element comes before: link it in and skip to the next
            i = i->next = l1;
            l1 = l1->next;
        } else {
            // list 2 element comes before: link it in and skip to the next
            i = i->next = l2;
            l2 = l2->next;
        }
    }
    // return the combined list head
    return dummy.next;
}

A more typical C implementation would use a pointer to the list link:
node_t *merge(node_t *l1, node_t *l2) {
    node_t *head;
    node_t **pp = &head;
    for (;;) {
        if (l1 == NULL) {
            // list 1 exhausted: link in the rest of list 2
            *pp = l2;
            break;
        }
        if (l2 == NULL) {
            // list 2 exhausted: link in the rest of list 1
            *pp = l1;
            break;
        }
        if (l1->value <= l2->value) {
            // list 1 element comes before: link it in and skip to the next
            *pp = l1;
            pp = &l1->next;
            l1 = l1->next;
        } else {
            // list 2 element comes before: link it in and skip to the next
            *pp = l2;
            pp = &l2->next;
            l2 = l2->next;
        }
    }
    // return the combined list head
    return head;
}

Here is a much simpler function to merge the lists without a dummy node or a double pointer. Note however that this recursive function does not use tail recursion: it will recurse many times using stack space proportional to the combined lengths of the argument lists, potentially causing a stack overflow.
node_t *merge(node_t *l1, node_t *l2) {
    if (l1 == NULL)
        return l2;
    if (l2 == NULL)
        return l1;
    if (l1->value <= l2->value) {
        l1->next = merge(l1->next, l2);
        return l1;
    } else {
        l2->next = merge(l1, l2->next);
        return l2;
    }
}


text:
Q: HTML5 canvas animation not showing background image I'm trying to do a simple animation where a bubble rises in a beer bottle and struggling with the background image. The beer image is not showing up. I only see the bubble rising.
My code:
<!DOCTYPE html>

<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Bieranimation</title>

<canvas id="bier" width="400" height="520" style="border:solid 1px">
 </canvas>

I tried to do something with the z-index but it doesn't seem to work:
body{text-align: center;}
.img{position:absolute;z-index:-1;}

#container{
    display:inline-block;
    width: 400px;
    height:520px;
    margin: 0 auto;

    position:relative;
   }

#gameCanvas{
    position:relative;
z-index:20;
}

I'd appreciate any kind of help.

A: (I'm not sure why I habitually try to answer questions in comments. Correcting that now.)
Canvases are transparent by default, but currently you're erasing your canvas each loop by filling it with white:
context.fillRect(0,0,width,heigth);

If you instead erase it (technically, fill it with a transparent color), you'll be able to see the elements stacked behind the canvas:
context.clearRect(0,0,width,heigth);


text:
Q: How can I reduce the size of .wav audio files for iPhone apps? I have some music that loops.  The .wav file size is about 8 meg.  I load this and just loop it... everything was working fine until I added another 4 meg .wav file.  Now the game crashes... removing the additional audio file fixed the crashing.
So how can I reduce the size of these .wav files?  I thought about releasing the memory after I'm done with the 4 meg file but what I tried didn't work (and I'd rather the game itself be a smaller file size so it's easier to download).
Thanks!

A: If you're only playing one sound file at a time, just use mp3 or aac.  That way you also get hardware decoding, for improved performance and battery life.
Unfortunately, the iPhone can only play one hardware decoded sound file at a time.  So if you're looking to ever play more than one at once, you'll need to do your own decoding of the second file; IMA 4:1 is recommended, though you'll have to find or implement your own decoder, Apple doesn't give you one.
This is all based off of this blog post, which goes into a bit more detail.

A: Actually .WAV is a container. The contents can be compressed or uncompressed, it all depends on the WAVEFORMATEX structure contained in the first "fmt " tag in the .WAV file.
For instance, in Windows 7 all of the built-in sounds are .WAV files that contain MP3 data.
You can just author your .WAV files as MP3 files and (assuming that the iPhone correctly handles the .WAV container) they should work.

A: Wav in a uncompressed format will inevitably take up tons of space. 8 Megs is not really big for an uncompressed wav.
You should consider an alternate, compressed format such as mp3 or aac. You might need to link in a decoding library though.
Check out this link on including mp3 files in your iphone app:

A: If your WAV files are stereo, you could try making them mono. This would basically half the file size. The disadvantage would obviously be that your sound is now mono.

A: I wouldn't use WAV. Take a look at ffmpegx. It's free, runs on the mac and will convert your waves files to MP3 or a host of other formats.


text:
Q: Implement multiple library versions with Gradle I have two libraries, which both include by themself a different version of com.android.billingclient:billing; 1.2.2 and 2.0.3
I need to use both libraries in my project, and if I force the use of one, one of both libraries won't compile anymore.
How can I use both versions of com.android.billingclient:billing in my project, so that they don't conflict with each other?

A: The key phrase to finding the solution to your problem is: transitive dependency. If you have 2 dependencies in your project that each have a sub-dependency (transitive dependency) on the same library but each uses different versions of that library then you'll need to tell one of them not to import that dependency.
Check out the discussion of this question in the Gradle Forums, I think it addresses your problem. It describes how to tell a dependency you declare not to automatically import a dependency it needs and will instead rely on you to explicitly declare the dependency or rely on the dependency being imported transitively:
How do I exclude transitive dependencies of something I depend on


text:
Q: Azure Functions and queues I want to create an app that supports multiple users. Every user can upload multiple files and each file uploaded needs to be processed by a pipeline (for example processing1.exe -> processing2.py -> processing3.exe). The results must be made available to the user after processing.
The backend is in Laravel.
I have the following questions:

*

*I tried running the processing1.exe binary on Azure Functions but I got "access denied". I guess this is because the default Windows image does not have the necessary dependencies installed (Windows SDK). From what I read there are other offerings of "serverless" in Azure like Logic Apps, Custom containers etc. Is there a way to use "serverless"/Azure Functions with that binary? What are my options?

*Everytime a new file upload is detected (by Laravel), how should I trigger Azure to start processing it? Should I Azure Storage Queues, Azure Service Bus, Event Hub or Event Grid (or something else)?
Ideally the system shouldn't process all the files from users in a FIFO manner but instead use round-robin (that way if user1 uploads 1000 files and user2 uploads 3 files, user2 wouldn't have to wait for all of user1 files to finish).

A: Few of the workarounds for running the .exe file on Azure Functions:
Workaround 1:
There is one of my practical workarounds on running and getting .exe output in Azure Functions, please refer this SO Thread.

Workaround 2:
My .exe file contains SQL database query that insert record into database using Azure Function App:
cmd.CommandText = "insert into [dbo].[debug]([Name]) values('test')";

run.csx:
using System;

public static void Run(TimerInfo myTimer, TraceWriter log)
{
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    process.StartInfo.FileName = @"D:\home\site\wwwroot\TimerTriggerclass1\demofunction.exe";
    process.StartInfo.Arguments = "";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.Start();
    string output = process.StandardOutput.ReadToEnd();
    string err = process.StandardError.ReadToEnd();
    process.WaitForExit();

    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
}

Before running the Function App in Azure, we need to upload the .exe file in the Azure Functions App > Functions (TimerTriggerclass1) > Upload File option.

Workaround 3:
using System;
using System.Diagnostics;
using System.Threading;

public static void Run(TimerInfo myTimer, TraceWriter log)
{

    System.Diagnostics.Process process = new System.Diagnostics.Process();
    string WorkingDirectoryInfo =@"D:\home\site\wwwroot\TimerTriggerClass1";
    string ExeLocation = @"D:\home\site\wwwroot\TimerTriggerClass1\MyApplication.exe";
    Process proc = new Process();
    ProcessStartInfo info = new ProcessStartInfo();

    try
    {
    info.WorkingDirectory = WorkingDirectoryInfo;
    info.FileName = ExeLocation;
    info.Arguments = "";
    info.WindowStyle = ProcessWindowStyle.Minimized;
    info.UseShellExecute = false;
    info.CreateNoWindow = true;
    proc.StartInfo = info;
    proc.Refresh();
    proc.Start();
    proc.WaitForInputIdle();
    proc.WaitForExit();
    }
    catch
    {
    }
    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
}

Everytime a new file upload is detected (by Laravel), how should I trigger Azure to start processing it? Should I Azure Storage Queues, Azure Service Bus, Event Hub or Event Grid (or something else)? Ideally the system shouldn't process all the files from users in a FIFO manner but instead use round-robin (that way if user1 uploads 1000 files and user2 uploads 3 files, user2 wouldn't have to wait for all of user1 files to finish).

For this process, the pure serverless approach like Azure Functions with Blob Storage Trigger or Azure Logic Apps with Blob Storage Trigger is better.
Whenever the new file is uploaded, then the Blob Storage will trigger the Azure Function to process the files immediately.
It will not make wait of the user 2 until the user1 finishes all files processing. User 2 can get the processed result at the same time when files are uploaded.
In Comparison, Logic Apps also does the same functionality whenever the files are added or modified but Logic Apps has built-in processing methods and connectors like after processing, share or save it to some other storages or mails whereas if you need customized functionality before/on/after processing the files uploaded on Azure Storage, Azure functions is the best approach to write the custom optimized code.


text:
Q: enabled IPv6 but [::1] is not working Windows XP with IE 7
http://localhost works.
http://127.0.0.1 works.
http://[machinename] works.
http://[::1] does not work.
A separate W2K3 machine works with all four addresses.
I did the same IPv6 installation on both machines (Network properties>Install IPv6)

A: Check the bindings is IIS or which ever web server you are using locally.  Otherwise the port isn't going to be listened to.
If you're using IIS 5.1, it doesn't support IPv6, so it won't bind to the IPv6 addresses and ports.  MS added the support in 6.0.


text:
Q: symfony & apache friendly url I am writing because after searching&reading i still have doubts about if i can make an url like this:
(a) http://www.balancextreme.es/tiendaweb/tienda/nuestrosProductos?culture=es
to show like this in search engines:
(b) http://www.balancextreme.es/pulseras-y-zapatillas-famosos.html
Doubts involved (and i hope this are usefull for others too!) are:
If i do it in htaccess (rewrite) will (i.e. google) show this one (even when url_for in the template is the (a) link)?
Or, if that`s not the case, can i achieve this in the routing.yml? (the examples i studied doesnt show this kind of change and i couldnt figure out how to do it)
well, that s it!
Someone can help on this?
thank

A: If you're using Symfony, you should use the Symfony routing system...
There you could create a route like this:
#/apps/frontend/routing.yml:
show_product:
  url: /product/:slug
  params: { module: products, action: show }

Then, in your view, use <?php echo link_to($product->name, 'show_product', array('slug' => $product->slug); ?>.
If you solve your problem with mod_rewrite, which is possible, you miss the flexibility of referring to routes in your frontend. And if you change an URL, you'll have to manually change all references to that URL.
But this is the really compact explanation... You should really look into this tutorial, which explains everything very good: http://www.symfony-project.org/jobeet/1_4/Doctrine/en/05


text:
Q: Use thread with shared memory I have an exe that writes data to shared memory than i read data from shared memory, i want to use std::thread when copy shared memory to different memory because writer exe does not stop writing.
When i use std::thread for copying shared memory,i pass memory structure as parameter than memory structure will be null in thread function, but when use the function normally, function memory structure will be as i expect. am i missed something or std::thread not useable for shared memory ?
struct Foo {
imgHeader imgHeader;
uint8_t imgBuf[12441600];
}

void memCpyFunc(uint8_t buf[12441600], std::list<uint8_t*>& bufferList) {

    uint8_t* ImgBuffer = new uint8_t[12441600];
    memcpy(ImgBuffer, buf, 12441600);
    bufferList.push_back(ImgBuffer);

}

int main(){
    Foo* foo;
    shmid = shmget(SHM_KEY, sizeof(Foo), 0666 | IPC_CREAT);
    foo = (Foo*)shmat(shmid, NULL, 0);
    std::list<uint8_t*> bufferList;
    memCpyFunc(foo->imgBuf, bufferList); //It works
    std::thread thread(&memCpyFunc, foo->imgBuf, std::ref(bufferList)); //Segmantation Fault
    //foo->imgBuf error: Cannot access memory at address 0x7ffff03b3078
    thread.detach();
    if (shmdt(foo) == -1) {
        perror("shmdt");

    }
}

I simply want to copy data from shared memory to different memory with thread.

A: Okay, there are some problems with your code as written. First, main is almost certainly going to quit before the thread gets a chance to run. But even if this isn't main but is something else (and thus your program isn't trying to quit), then bufferList is going out of scope before your thread runs.
This is a time when Francois might be right about using thread->join(), although I normally disagree with him about that. There are times to detach and times to use join.
Are you sure the error is about the shared memory and not about bufferList?
I'd do this. First, I'd change the detach to a join, and then I'd stick debug statements in the function you're calling. The code should work as long as main doesn't return too fast.


text:
Q: Value of array in structure still changing I have a problem. I written the some values to my array and i want to send handle to inicialize frame to connecting with my device, but when i pick up the structure my data from struct overvrite the another value than i want.
There are my foo:
int handlePackets (struct _PacketData * outputPacket, uint8_t command){
    outputPacket->addr = SERIAL;
    outputPacket->length = 0;
    outputPacket->cmd = command;

    switch (outputPacket->cmd)
    {
        case CMD_SET_OUTPUT:
            outputPacket->length = 0x06;

            outputPacket->data[0] = 0x80;
            outputPacket->data[1] = 0x3F;
            outputPacket->data[2] = 0x10;
            outputPacket->data[3] = 0x40;
            outputPacket->data[4] = 0x30;
            return COMM_FRAME_OK;
    }
    return COMM_FRAME_OK;
}
int sendPacket (struct _PacketData * outputPacket, uint8_t * buffer){
int cntr = 0, x;

buffer[cntr++] = STX;
buffer[cntr++] = outputPacket->addr >> 24;
buffer[cntr++] = outputPacket->addr >> 16;
buffer[cntr++] = outputPacket->addr >> 8;
buffer[cntr++] = outputPacket->addr & 0xff;

buffer[cntr++] = outputPacket->length >> 8;
buffer[cntr++] = outputPacket->length & 0xff;

buffer[cntr++] = outputPacket->cmd;

for (x = 0; x < outputPacket->length -1 ; x++)
{
    buffer[cntr++] = outputPacket->data[x];
}
crc = calcCrcBuffer (buffer + 1, cntr - 1);

buffer[cntr++] = (unsigned char) (crc >> 8);        //crc high byte
buffer[cntr++] = (unsigned char) (crc & 0xff);      //crc low byte

buffer[cntr++] = ETX;
return cntr;
}

structure
struct _PacketData{
uint32_t addr;
uint16_t length;
uint8_t cmd;
uint8_t data[256];};

main.c
int main(void) {
struct _PacketData  * outputOutPack;

uint8_t tab[256];
int i;

    uint8_t *buffer = tab;

  handlePackets(&outputOutPack,CMD_SET_OUTPUT );

  result = sendPacket(&outputOutPack, buffer);}

The output of my frame is not like i need. Data overvrite the values from buffer[cntr] but i dont know why.
Output:
[0] = 0x82
[1] = 00
[2] = 0x18
[3] = 0xb0
[4] = 0xa5
[5] = 00
[6] = 0x6
[7] = 0x78
[8] = 0x82
[9] = 00
[10] = 0x18
[11] = 0xb0
[12] = 0xa5
[13] = 0x64
[14] = 0xfe
[15] = 0x83

Position 7 is output->cmd and next is output->data, [8-12], but its not my array :)
Any suggestion?
Thanks

A: When you compile the code you would see the following warnings.
warning: passing argument 1 of 'handlePackets' from incompatible pointer type
note: expected 'struct _PacketData *' but argument is of type 'struct _PacketData **'

The reason for the problem is that your functions(handlePackets and sendPacket) takes a pointer to the struct _PacketData not pointer to a pointer.
You need to change struct _PacketData * outputOutPack; to struct _PacketData outputOutPack;
What you are essentially doing when you provide the functions with a pointer to a pointer, is dereferencing the memory you allocated to the pointer type on the stack this leads to undefined behavior and potentially corrupting your stack.


text:
Q: Como definir o SET CLIENT_ENCODING = UTF8 de forma permanente? Estou usando o PostgreSQL no meu DATABASE
As informações com acento estão sendo gravadas com problemas no acento.
Ex:
ã grava como ã
Tubarão grava como Tubarão
A codificação do meu DATABASE e do meu servidor estão utilizando o UTF8 como ENCODING. Só que o PostgreSQL possui uma variável de ambiente chamada CLIENT_ENCODING que é responsável por controlar a codificação utilizada pelo cliente que está conectado ao servidor de banco de dados.
Quando eu mando o comando SHOW
SHOW CLIENT_ENCODING;
Aparece que meu ENCODING é o UNICODE
Então, toda vez, eu tenho que usar o comando SET, em cada janela de query tool, para poder alterar seu valor e corrigir os acentos. Por exemplo:
SET CLIENT_ENCODING = 'LATIN1';
OBS.: se eu coloco 'UTF8', ele não reconhece os caracteres especiais. Não sei o porquê disso, já que meu banco está em 'UTF8'. Ele deveria reconhecer e mostrar os acentos, quando eu coloco em set UTF8.
A MINHA PERGUNTA É:
Por favor, como posso deixar o meu cliente encoding de acordo com o banco (UTF8), para que não aconteça esses erros com o acento?

A: Você pode adicionar o comando SET client_encoding = 'UTF8'; ao arquivo ~/.psqlrc (ou %APPDATA%\postgresql\psqlrc.conf no Windows)
Para mais detalhes, veja o manual: http://www.postgresql.org/docs/current/static/app-psql.html#AEN88713
Resposta similhar em inglês:
https://dba.stackexchange.com/questions/71597/postgresql-set-default-psql-client-encoding

A: Você pode setar variáveis de ambiente diretamente na ROLE responsável pela sessão/conexão, por exemplo:
ALTER ROLE foobar SET CLIENT_ENCODING = 'UTF8';


text:
Q: Set dropdown menu as main menu item I have a problems with adding a dropdown as a menu item.
This is my main menu:
Ext.define('ECR.view.main.Main', {
    extend: 'Ext.tab.Panel',
    xtype: 'app-main',

    requires: [
        'Ext.plugin.Viewport',
        'Ext.window.MessageBox',

        'ECR.view.main.MainController',
        'ECR.view.main.MainModel',
        'ECR.view.main.List'
    ],

    controller: 'main',
    viewModel: 'main',

    ui: 'navigation',
    tabBar: {
        layout: {
            pack: 'center'
        },
        border: false
    },

    defaults: {
        iconAlign: 'top',
        bodyPadding: 15
    },

    items: [{
            title: 'Home',
            iconCls: 'fa-home',
            bind: {
                html: 'Test'
            }

        },
        {   title: 'DROPDOWN',
            iconCls: 'fa-cogs',
            bind: {
                html: 'Test'
            },
            xtype: 'dropdownButton'
        },

        {
            title: 'Administration',
            iconCls: 'fa-cogs',
            bind: {
                html: '{loremIpsum}'
            }
        }, {
            title: 'Reporting',
            iconCls: 'fa-calendar',
            bind: {
                html: '{loremIpsum}'
            }
        },
        {
            title: 'Help',
            iconCls: 'fa-question',
            bind: {
                html: '{loremIpsum}'
            }
        },
        {
            title: 'Account',
            iconCls: 'fa-user',
            bind: {
                html: '{loremIpsum}'
            }
        }
    ]
});

And here I am trying to add the dropdown where I previously defined:
{   title: 'DROPDOWN',
            iconCls: 'fa-cogs',
            bind: {
                html: 'Test'
            },
            xtype: 'dropdownButton'
        },

This is the definition of dropdown:
Ext.define('My.harun.Button', {
    extend: 'Ext.menu.Menu',
    alias: ['widget.dropdownButton'],

    text: 'Menu button',

    arrowAlign: 'bottom',
    menu: [
        { text: 'Item 1' },
        { text: 'Item 2' },
        { text: 'Item 3' },
        { text: 'Item 4' }
    ],
    listeners: {
        mouseover: function() {
            this.showMenu();
        }
    }
});

But this does not work. However I tried to create it manually using Ext.create() :
Ext.create('Ext.Button', {
    text: 'Menu button',
    renderTo: Ext.getBody(),
    arrowAlign: 'bottom',
    menu: [
        { text: 'Item 1' },
        { text: 'Item 2' },
        { text: 'Item 3' },
        { text: 'Item 4' }
    ],
    listeners: {
        mouseover: function() {
            this.showMenu();
        }
    }
})

So far I am getting only this:

I managed to put the item in main menu but it is still not a dropdown one. And when I click on that item it shows really big button in the main screen (here where "Test" is written).
Is there a way to fix this or I must use Toolbar?

A: Solved it with tabConfig. If anyone needs dropdown item in your menu, include this in your items list:
{
    tabConfig:
    {
        title: 'Dropdown menu',
        iconCls: 'fa-home',
        menu: Ext.create('Ext.menu.Menu',
        {
            width: 100,
            plain: true,
            items: [
            {
                text: 'Dropdown Item 1'
            },
            {
                text: 'Dropdown Item 2'
            },
            {
                text: 'Dropdown Item 3'
            }]
        })
    }
},


text:
Q: setstate is not working properly in react-native so here i have 3 TouchableOpacities , for each press the backgroundColor changes its self and it works fine , so i tried adding in my changeColor() function a setState that returns a size (M,L or XL) of each TouchableOpacity pressed
here is my code :

    constructor(props) {
        super(props)
            colorId: 0,
            size:""
        };
    }
        changeColor = (id) => {
        this.setState({ colorId: id });
        if (id == 1) {
            this.setState({ size: 'M' })
        }
        else if (id == 2) {
            this.setState({ size: 'XL' })
        }
        else {
            this.setState({ size: 'L' })
        }
        console.log("Button id:", id ,"size :", this.state.size)
    }
     render() {

        return (

<TouchableOpacity style={this.state.colorId === 2 ? styles.button_XL_Colored : styles.button_XL} onPress={() => this.changeColor(2)} ><Text style={{ color: '#000000', alignSelf: 'center', marginTop: normalize(12), fontSize: normalize(20) }}>XL</Text></TouchableOpacity>
<TouchableOpacity style={this.state.colorId === 3 ? styles.button_L_Colored : styles.button_L}   onPress={() => this.changeColor(3)}><Text style={{ color: '#000000', alignSelf: 'center', marginTop: normalize(12), fontSize: normalize(20) }}>L</Text></TouchableOpacity>
<TouchableOpacity style={this.state.colorId === 1 ? styles.button_M_Colored : styles.button_M} onPress={() => this.changeColor(1)} ><Text style={{ color: '#000000', alignSelf: 'center', marginTop: normalize(12), fontSize: normalize(20) }}>M</Text></TouchableOpacity>

        );
    }
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F5F8',
    },

    button_M: {
        backgroundColor: '#FFFDFD',
        borderRadius: 10,
        width: normalize(50),
        height: normalize(50),
        alignSelf: 'center',
        marginLeft: 0,
        marginTop: normalize(-10)
    },
    button_L: {
        backgroundColor: '#FFFDFD',
        borderRadius: 10,
        width: normalize(50),
        height: normalize(50),
        alignSelf: 'center',
        marginLeft: normalize(140),
    },
    button_XL: {
        backgroundColor: '#FFFDFD',
        borderRadius: 10,
        width: normalize(50),
        height: normalize(50),
        alignSelf: 'center',
    },
    button_M_Colored: {
        backgroundColor: '#D05A0B',
        borderRadius: 10,
        width: normalize(50),
        height: normalize(50),
        alignSelf: 'center',
        marginLeft: 0,
        marginTop: normalize(-10)
    },

    button_XL_Colored: {
        backgroundColor: '#D05A0B',
        borderRadius: 10,
        width: normalize(50),
        height: normalize(50),
        alignSelf: 'center',
    },
    button_L_Colored: {
        backgroundColor: '#D05A0B',
        borderRadius: 10,
        width: normalize(50),
        height: normalize(50),
        alignSelf: 'center',
        marginLeft: normalize(140),
    },

The problem is i cannot get the size value that i wanted at first press

it should return size="M" when i press the TouchableOpacity thats has the M letter
its only working if it press twice :

the same case for other touchableOpacities :

Is there any solution for this ?

A: You're using console.log right after setState, above results are expected because setState is asynchronous. So console.log is executed with old state instead of new state (new state has not been assigned yet).
You need to use the callback form of setState to get the right state.
this.setState({ size: 'L' }, (state) => console.log("Button id:", id ,"size :",state.size))

You can read more about it here: https://reactjs.org/docs/react-component.html#setstate
// Added (I don't have enough rep to comment)
I saw John Lim's answer that suggests to use await, but setState does not return a Promise, so await won't work here. https://github.com/facebook/react/blob/0e100ed00fb52cfd107db1d1081ef18fe4b9167f/packages/react/src/ReactBaseClasses.js#L57-L66

A: console.log() does not show things immediately after useState().
One alternative might be putting console.log inside useEffect().
Another solution might be using setTimeOut() by calling the method after a certain moment.


text:
Q: How to create a rounded scrollbar with style in tkinter python I'm looking for how to create a rounded scrollbar with style method in tkinter.
Also, is it possible to set trough color when our mouse enter scrollbar trough?
This is a example about the scrollbar which I'm taking about.
https://i.stack.imgur.com/OHpm7.jpg
Thanks in advance for your helps!


text:
Q: Polling with sqlplus and logging result to a file forces in lineshifts I am trying to make a, what I thought to be, simple bash-script that regularly polls a remote database and logs the following elements to a log-file, where only the last two elements are row-elements from the sql-query:
Readable timestamp, timestamp, string, Request Duration

Example result should look something like this:
Mon Sep 5 13:28:30 CEST 2016,1473074940127,text content, 4
Mon Sep 5 13:28:40 CEST 2016,1473074940127,text content, 3
Mon Sep 5 13:28:50 CEST 2016,1473074940127,text content, 2

The purpose of this script is to actively monitor and log response times from our local environment to the remote database, so that we can correspond errors in our local application while testing, with eventual database connection issues or similar. For this reason, we want the script to output any eventual error-messages as well. Formatting of these are not important, but we would like to see the standard output to be "comfortable" one-liners.
I have written the following quite simple script for the occasion, but it has a few eccentricities that I can't seem to remove no matter how I tune it:
sleep_duration=10
while true; do

SECONDS=0
timestamp="$(date),"
echo -n $timestamp >> $LOG_PATH

sqlplus -s $database << EOF >> $LOG_PATH
    whenever sqlerror exit sql.sqlcode

    set echo off
    set heading off
    set linesize 1000
    set pagesize 0
    set numformat 9999999999999
    set colsep ,
    set null null

    SELECT COLUMN1, COLUMN2 FROM TABLE1;
    exit;
EOF

echo ', '$SECONDS >> $LOG_PATH

sleep $sleep_duration
done

The query we send to the database always returns exactly one row with two elements, and the two elements (INTEGER, VARCHAR2) are always of the same fixed width. They can both be null if something in our application breaks locally.
I am aware of the existance of the SPOOL and TIMING commands, but have tested and opted out of using both. Spooling the query does not output any eventual surprise errors to the log-file, at least not without tricking around with error terminal outputs, so I just went with the pipe-solution in the first place. Seemed simpler. TIMING did not seem to correctly display the elapsed time of the query in the case of database downtime, so I went with the SECONDS-approach. I know this is not as precise in regards to all the sqlplus overhead that is included, but we're not interested in precise metrics anyway, we're generally just interested in seeing whether the process takes less than one second, or several minutes. Milliseconds are essentially irrelevant.
This has one big problem however, as the log ends up looking like this:
Mon Sep 5 14:50:47 CEST 2016, 1473079873483,text output

, 0
Mon Sep 5 14:50:57 CEST 2016, 1473079883483,text output

, 0
Mon Sep 5 14:51:07 CEST 2016, 1473079893489,text output

, 0

I would expect the set pagesize 0 to remove all such trailing lineshifts from the result, but there seems to be two lineshifts after each query regardless, and I can't seem to get rid of it no matter what I try. Spooling the query gives the same results.
I considered looping inside the sqlplus-session instead, but as the script will have to run on a more or less permanent basis, I fear this would permanently reserve a connection-slot for an otherwise functionally meaningless purpose, which is undesirable. Opening and closing it as necessary seems more sensible. I have not tested this approach at all, mainly for that reason.
I am hoping to avoid having to do post-processing of the log, as I have no idea what kind of error-entries might pop up in there, so prettifying it later feels like an unneccesary regex-nightmare.
Does anyone have any suggestions on how to make the output cleanly line up on a single line, without unneccessary lineshifts and whitespace, while also ensuring that any eventual errors are not lost?

A: This is a bit of a work-around, as it hasn't actually solved the lineshifts which I still haven't been able to explain, but a very simple solution to this was to simply store the sqlplus output directly to a bash variable instead of trying to print to the log from sqlplus directly, and echo it as any other variable.
Essentially, all I had to change in the script above, was wrap the sqlplus command in a variable QUERY_OUTPUT=$() and remove piping of the output:
while true; do

SECONDS=0
timestamp=$(date)
echo -n "$timestamp, " >> $LOG_PATH

QUERY_RESULT=$(sqlplus -s $database << EOF
    whenever sqlerror exit sql.sqlcode

    set echo off
    set heading off
    set linesize 1000
    set pagesize 0
    set numformat 9999999999999
    set colsep ', '
    set null null

    SELECT TIME, BROKER_NAME FROM ACTIVEMQ_LOCK;
    exit;
EOF
)

echo $QUERY_RESULT, $SECONDS seconds elapsed >> $LOG_PATH

sleep $sleep_duration
done

Stumbled across this solution on my own while spending a few hours attempting to document and verify what I had tried and not tried in the question above in the first place, and after some testing it appears to be working great. Everything is cleanly and controllably printed on one line, and any eventual errors seem to be printed cleanly on that one line as well. Spot on exactly what I were looking for.
Considered just not asking the question in the first place since I found the solution, but I figured someone else might see some value in this as well, I have not been able to find any glaringly obvious duplicates at least. Might as well share!


text:
Q: An element not in a field extension
Possible Duplicate:
Is $\mathbb{Q}(\sqrt{2}) \cong \mathbb{Q}(\sqrt{3})$?

Consider the field extension $\mathbb{Q}(\sqrt2)$. I want to show that $\sqrt5 \notin \mathbb{Q}(\sqrt2)$. If this were not the case, then we could write $\sqrt5 = a + b\sqrt2$ for $a,b\in\mathbb{Q}$. However, I do not see the contradiction here. Is there a better/easier way to prove this?

A: HINT $\ $ Since $\sqrt{2},\sqrt{5},\sqrt{10}\not\in\mathbb Q,\:$ it is an immediate consequence of this
LEMMA $\rm\ \ [K(\sqrt{a},\sqrt{b}) : K] = 4\ $ if  $\rm\ \sqrt{a},\ \sqrt{b},\ \sqrt{a\:b}\ $  all are not in $\rm\:K\:$ and $\rm\: 2 \ne 0\:$ in $\rm\:K\:.$
Proof $\ \ $  Let  $\rm\ L = K(\sqrt{b})\:.\:$ Then $\rm\:  [L:K] = 2\:$  via  $\rm\:\sqrt{b}  \not\in K\:,\:$  therefore it is sufficient to prove $\rm\: [L(\sqrt{a}):L] = 2\:.\:$ But this fails only if  $\rm\:\sqrt{a} \in L = K(\sqrt{b})\ $ and then $\rm\ \sqrt{a}\ =\  r + s\ \sqrt{b}\ $  for $\rm\ r,s\in K\:.\:$ That's impossible: squaring yields $\rm(1):\ \ a\ =\ r^2 + b\ s^2 + 2\:r\:s\  \sqrt{b}\:,\: $ contra hypotheses as follows:
$\rm\quad\quad\quad\quad\quad\quad\quad\quad rs \ne 0\ \ \Rightarrow\ \  \sqrt{b}\ \in\  K\ \ $ by solving $(1)$ for $\rm\sqrt{b}\:,\:$ using  $\rm\:2 \ne 0$
$\rm\quad\quad\quad\quad\quad\quad\quad\quad\  s = 0\ \ \Rightarrow\ \  \ \sqrt{a}\ \in\  K\ \ $  via  $\rm\ \sqrt{a}\ =\ r \in K$
$\rm\quad\quad\quad\quad\quad\quad\quad\quad\  r = 0\ \ \Rightarrow\ \  \sqrt{a\:b}\in K\ \ $  via  $\rm\ \sqrt{a}\ =\ s\ \sqrt{b}\:,\: \ $times $\rm\:\sqrt{b}\quad\quad$ QED
Using the above as the inductive step one easily proves the following result of Besicovic.
THEOREM $\ $  Let $\rm\:Q\:$ be a field with $2 \ne 0\:,\:$ and $\rm\ L = Q(S)\ $ be an extension of $\rm\:Q\:$ generated by $\rm\: n\:$  square roots  $\rm\ S = \{ \sqrt{a}, \sqrt{b},\ldots \}$ of elts  $\rm\ a,\:b,\:\ldots \in  Q\:.\:$
If every nonempty subset of $\rm\:S\:$ has product not in $\rm\:Q\:$ then each successive
adjunction  $\rm\ Q(\sqrt{a}),\  Q(\sqrt{a},\:\sqrt{b}),\:\ldots$ doubles the degree over $\rm\:Q\:,\:$ so, in total, $\rm\: [L:Q] \ =\ 2^n\:.\:$  Hence the $\rm\:2^n\:$ subproducts of the product of $\rm\:S\:$ form a basis of $\rm\:L\:$ over $\rm\:Q\:.$

A: Squaring both sides of $\sqrt5 = a + b\sqrt2$ will imply that $\sqrt2$ is rational, which it is not.
(Actually, you also need to consider the case $b=0$, which would imply $\sqrt5$ is rational, and the case $a=0$, which would imply $\sqrt{\dfrac52}$ is rational.)


text:
Q: Add validation method to "jquery validation plugin" Hello im using jquery validation plugin to validate my form.
I want to add one more rule to the validation, but cant get it to work.
Input value should be less or equal previous element value.
It is possible to do it ?
Here is the code -
<input type='text' value='<?php echo $count; ?>' class='input_in_stock' readonly="readonly" />
<input type='text' name='amount[]' id='<?php echo rand(0,99).$id; ?>' size='1' value='<?php echo $count; ?>' class='required input_count' />

$(document).ready(function(){

    $.validator.addMethod('positiveint', function (value) {
        return (value > 0) && (value != 0) && (value == parseInt(value, 10));
    }, 'Enter a positive integer value.');

    $.validator.addMethod('notmorethan', function (value) {
        return (value <= $(this).prev().val());
    }, 'abc.');

    $("#cartform").validate({
        rules: {
            "amount[]": {
                required: true,
                positiveint: true,
                notmorethan: true
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next());
        }
    });

});

p.s. I used this jquery validation plugin fix to make it work with names like this[]
http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements
EDIT: found the solution
$.validator.addMethod('notmorethan', function (value, element) {
    return (value <= $(element).prev().val() );
}, 'abc');

A: See if this fiddle helps- http://jsfiddle.net/alokswain/LSuMA/11/ . I am not sure about the customizations that you are using to use names like amount[], but I guess this approach should pretty much work.
The custom validation methods are just functions, if you use this inside the function body then it would refer to the owner of the function. Now assuming you want to get the previously valid value from the input field, you could store it somewhere in the DOM whenever the whole form is valid, say the previously stored value is called as previousAmountVal. When the value in the field is changed, in the function notmorethan you can access the current value using value parameter and the previously stored value and the previous value using previousAmountVal, thus deciding whether the current value is valid or not. Also, if you do this remember to always update the previousAmountVal when the form is valid.

A: found the solution
$.validator.addMethod('notmorethan', function (value, element) {
    return (value <= $(element).prev().val() );
}, 'abc');


text:
Q: config.h: No such file or directory in ssh_client from libssh's example When I compile ssh_client code from example folder of libssh source directory( I have wrote about building process of this library in this link : libssh's functions couldn't be found on qt):
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/select.h>
#include <sys/time.h>

#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_PTY_H
#include <pty.h>
#endif

#include <sys/ioctl.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>

#include <libssh/callbacks.h>
#include <libssh/libssh.h>
#include <libssh/sftp.h>

#include "examples_common.h"
#define MAXCMD 10

static char *host = NULL;
static char *user = NULL;
static char *cmds[MAXCMD];
static char *config_file = NULL;
static struct termios terminal;

static char *pcap_file = NULL;

static char *proxycommand;

static int auth_callback(const char *prompt,
                         char *buf,
                         size_t len,
                         int echo,
                         int verify,
                         void *userdata)
{
    (void) verify;
    (void) userdata;

    return ssh_getpass(prompt, buf, len, echo, verify);
}

struct ssh_callbacks_struct cb = {
    .auth_function = auth_callback,
    .userdata = NULL,
};

static void add_cmd(char *cmd)
{
    int n;

    for (n = 0; (n < MAXCMD) && cmds[n] != NULL; n++);

    if (n == MAXCMD) {
        return;
    }

    cmds[n] = strdup(cmd);
}

static void usage(void)
{
    fprintf(stderr,
            "Usage : ssh [options] [login@]hostname\n"
            "sample client - libssh-%s\n"
            "Options :\n"
            "  -l user : log in as user\n"
            "  -p port : connect to port\n"
            "  -d : use DSS to verify host public key\n"
            "  -r : use RSA to verify host public key\n"
            "  -F file : parse configuration file instead of default one\n"
#ifdef WITH_PCAP
            "  -P file : create a pcap debugging file\n"
#endif
#ifndef _WIN32
            "  -T proxycommand : command to execute as a socket proxy\n"
#endif
            "\n",
            ssh_version(0));

    exit(0);
}

static int opts(int argc, char **argv)
{
    int i;

    while((i = getopt(argc,argv,"T:P:F:")) != -1) {
        switch(i){
        case 'P':
            pcap_file = optarg;
            break;
        case 'F':
            config_file = optarg;
            break;
#ifndef _WIN32
        case 'T':
            proxycommand = optarg;
            break;
#endif
        default:
            fprintf(stderr, "Unknown option %c\n", optopt);
            usage();
        }
    }
    if (optind < argc) {
        host = argv[optind++];
    }

    while(optind < argc) {
        add_cmd(argv[optind++]);
    }

    if (host == NULL) {
        usage();
    }

    return 0;
}

#ifndef HAVE_CFMAKERAW
static void cfmakeraw(struct termios *termios_p)
{
    termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
    termios_p->c_oflag &= ~OPOST;
    termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
    termios_p->c_cflag &= ~(CSIZE|PARENB);
    termios_p->c_cflag |= CS8;
}
#endif

static void do_cleanup(int i)
{
  /* unused variable */
  (void) i;

  tcsetattr(0, TCSANOW, &terminal);
}

static void do_exit(int i)
{
    /* unused variable */
    (void) i;

    do_cleanup(0);
    exit(0);
}

static ssh_channel chan;
static int signal_delayed = 0;

static void sigwindowchanged(int i)
{
    (void) i;
    signal_delayed = 1;
}

static void setsignal(void)
{
    signal(SIGWINCH, sigwindowchanged);
    signal_delayed = 0;
}

static void sizechanged(void)
{
    struct winsize win = {
        .ws_row = 0,
    };

    ioctl(1, TIOCGWINSZ, &win);
    ssh_channel_change_pty_size(chan,win.ws_col, win.ws_row);
    setsignal();
}

static void select_loop(ssh_session session,ssh_channel channel)
{
    ssh_connector connector_in, connector_out, connector_err;
    int rc;

    ssh_event event = ssh_event_new();

    /* stdin */
    connector_in = ssh_connector_new(session);
    ssh_connector_set_out_channel(connector_in, channel, SSH_CONNECTOR_STDINOUT);
    ssh_connector_set_in_fd(connector_in, 0);
    ssh_event_add_connector(event, connector_in);

    /* stdout */
    connector_out = ssh_connector_new(session);
    ssh_connector_set_out_fd(connector_out, 1);
    ssh_connector_set_in_channel(connector_out, channel, SSH_CONNECTOR_STDINOUT);
    ssh_event_add_connector(event, connector_out);

    /* stderr */
    connector_err = ssh_connector_new(session);
    ssh_connector_set_out_fd(connector_err, 2);
    ssh_connector_set_in_channel(connector_err, channel, SSH_CONNECTOR_STDERR);
    ssh_event_add_connector(event, connector_err);

    while (ssh_channel_is_open(channel)) {
        if (signal_delayed) {
            sizechanged();
        }
        rc = ssh_event_dopoll(event, 60000);
        if (rc == SSH_ERROR) {
            fprintf(stderr, "Error in ssh_event_dopoll()\n");
            break;
        }
    }
    ssh_event_remove_connector(event, connector_in);
    ssh_event_remove_connector(event, connector_out);
    ssh_event_remove_connector(event, connector_err);

    ssh_connector_free(connector_in);
    ssh_connector_free(connector_out);
    ssh_connector_free(connector_err);

    ssh_event_free(event);
}

static void shell(ssh_session session)
{
    ssh_channel channel;
    struct termios terminal_local;
    int interactive=isatty(0);

    channel = ssh_channel_new(session);
    if (channel == NULL) {
        return;
    }

    if (interactive) {
        tcgetattr(0, &terminal_local);
        memcpy(&terminal, &terminal_local, sizeof(struct termios));
    }

    if (ssh_channel_open_session(channel)) {
        printf("Error opening channel : %s\n", ssh_get_error(session));
        ssh_channel_free(channel);
        return;
    }
    chan = channel;
    if (interactive) {
        ssh_channel_request_pty(channel);
        sizechanged();
    }

    if (ssh_channel_request_shell(channel)) {
        printf("Requesting shell : %s\n", ssh_get_error(session));
        ssh_channel_free(channel);
        return;
    }

    if (interactive) {
        cfmakeraw(&terminal_local);
        tcsetattr(0, TCSANOW, &terminal_local);
        setsignal();
    }
    signal(SIGTERM, do_cleanup);
    select_loop(session, channel);
    if (interactive) {
        do_cleanup(0);
    }
    ssh_channel_free(channel);
}

static void batch_shell(ssh_session session)
{
    ssh_channel channel;
    char buffer[1024];
    size_t i;
    int s = 0;

    for (i = 0; i < MAXCMD && cmds[i]; ++i) {
        s += snprintf(buffer + s, sizeof(buffer) - s, "%s ", cmds[i]);
        free(cmds[i]);
        cmds[i] = NULL;
    }

    channel = ssh_channel_new(session);
    if (channel == NULL) {
        return;
    }

    ssh_channel_open_session(channel);
    if (ssh_channel_request_exec(channel, buffer)) {
        printf("Error executing '%s' : %s\n", buffer, ssh_get_error(session));
        ssh_channel_free(channel);
        return;
    }
    select_loop(session, channel);
    ssh_channel_free(channel);
}

static int client(ssh_session session)
{
    int auth = 0;
    char *banner;
    int state;

    if (user) {
        if (ssh_options_set(session, SSH_OPTIONS_USER, user) < 0) {
            return -1;
        }
    }
    if (ssh_options_set(session, SSH_OPTIONS_HOST, host) < 0) {
        return -1;
    }
    if (proxycommand != NULL) {
        if (ssh_options_set(session, SSH_OPTIONS_PROXYCOMMAND, proxycommand)) {
            return -1;
        }
    }
    /* Parse configuration file if specified: The command-line options will
     * overwrite items loaded from configuration file */
    if (config_file != NULL) {
        ssh_options_parse_config(session, config_file);
    } else {
        ssh_options_parse_config(session, NULL);
    }

    if (ssh_connect(session)) {
        fprintf(stderr, "Connection failed : %s\n", ssh_get_error(session));
        return -1;
    }

    state = verify_knownhost(session);
    if (state != 0) {
        return -1;
    }

    ssh_userauth_none(session, NULL);
    banner = ssh_get_issue_banner(session);
    if (banner) {
        printf("%s\n", banner);
        free(banner);
    }
    auth = authenticate_console(session);
    if (auth != SSH_AUTH_SUCCESS) {
        return -1;
    }
    if (cmds[0] == NULL) {
        shell(session);
    } else {
        batch_shell(session);
    }

    return 0;
}

static ssh_pcap_file pcap;
static void set_pcap(ssh_session session)
{
    if (pcap_file == NULL) {
        return;
    }

    pcap = ssh_pcap_file_new();
    if (pcap == NULL) {
        return;
    }

    if (ssh_pcap_file_open(pcap, pcap_file) == SSH_ERROR) {
        printf("Error opening pcap file\n");
        ssh_pcap_file_free(pcap);
        pcap = NULL;
        return;
    }
    ssh_set_pcap_file(session, pcap);
}

static void cleanup_pcap(void)
{
    if (pcap != NULL) {
        ssh_pcap_file_free(pcap);
    }
    pcap = NULL;
}

int main(int argc, char **argv)
{
    ssh_session session;

    session = ssh_new();

    ssh_callbacks_init(&cb);
    ssh_set_callbacks(session,&cb);

    if (ssh_options_getopt(session, &argc, argv)) {
        fprintf(stderr,
                "Error parsing command line: %s\n",
                ssh_get_error(session));
        usage();
    }
    opts(argc, argv);
    signal(SIGTERM, do_exit);

    set_pcap(session);
    client(session);

    ssh_disconnect(session);
    ssh_free(session);
    cleanup_pcap();

    ssh_finalize();

    return 0;
}

I got the following error:
/home/heydari.f/projects/ssh_client/ssh_client/main.c:100: error: config.h: No such file or directory
 #include "config.h"
          ^~~~~~~~~~

Is there anything to do with configure or what?
I use Qt and my os is ubuntu 18.04.

A: Config headers as config.h normally aren't needed to compile a program against a library. Those are generated to compile the library, not the programs that link against them. If not, there will be lot of trouble as lots of software use them and there would be lots of collisions between them.
Being an example, it may be that it uses the config.h, but in that case I'm pretty sure you should compile with the system libssh uses to compile. (You may need to specify an option to compile examples when calling configure or specify something in DefineOptions.cmake or something in the same line.)
If you copied the sources (as it seems as the error states projects/ssh_client/) to build with Qt, you probably can remove that include unless it is a config from Qt itself.
Also, if you are compiling with Qt you surely need to install the lib and follow @Dmitry advice about -I, -L and -l flags to compiler.


text:
Q: How to make an object go to alpha 0,5 and back to 1 during one transition? I'd like to have smooth effect of fading out and going back to being fully visible. I can set alpha to 0.5 at the beginning and make it go back to 1 during the transition, but that's not the effect that I want. And it has to be done using one transition effect.
Btw, how can I add params to existing transition. Would just mytransition.params={someparam=2} work?

A: You can use the easing library to change how the animations works with transitions, so you can manage how the animation works between 2 values. I think you need to use easing.continuousLoop
Try to add this to your transition.
Check the easing functions in easing.* library

A: Use the easing.continuousLoop it's set the alpha to desired value and returns to the previous:
transition.to( object, { time=1000, alpha=0, transition=easing.continuousLoop } )


text:
Q: RxSwift TestScheduler don't work if subscribeOn background I have mock interactor and router for unit tests on presenter
presenter method:

private func presenterMethod(_ isOn: Bool) -> Driver<Bool> {
    return interactor.interactorMethod(isOn)
        .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
        .observeOn(MainScheduler.instance)
        .do(onError: { [weak self] error in
            self?.view.showError(error)
        })
        .asDriver(onErrorJustReturn: !isOn)
}

And test

func testPresenterMethod() {
    let trigger = self.scheduler.createHotObservable([
        next(100, (false)),
        next(200, (true)),
        next(300, (false))
        ]).asDriverOnErrorJustComplete()

    let observer = scheduler.createObserver(Bool.self)
    let input = createInput(presenterTrigger: trigger)
    let output = presenter.transform(input)

    scheduler.scheduleAt(0, action: {
        output.presenterMethodOutput.asObservable()
            .subscribe(observer)
            .disposed(by: self.disposeBag)
    })

    scheduler.start()

    let results = observer.events.map {
        $0.value.element
    }

    XCTAssertEqual(results, [false, true, false])
}

And results are empty,
This test work correctly only when I remove these lines from presenterMethod

    .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
    .observeOn(MainScheduler.instance)

I tried with XCTestExpectation and fulfill in do(onNext:{}) block and get the same results, work only without subscribeOn background.
Method work correct on device and simulator, presenterMethod is treggered on switch and emit correct events. How this test should be written to work with SubscribeOn background?

A: You'll actually want the schedulers passed to subscribeOn to be a configurable variable on the presenter.
Because tests are better ran synchronously, passing the test scheduler in will ensure there's no need to wait for an asynchronous execution.
struct Presenter {
  let mainScheduler: SchedulerType
  let backgroundScheduler: SchedulerType

  init(backgroundScheduler: SchedulerType = ConcurrentDispatchQueueScheduler(qos: .background), mainScheduler: SchedulerType = MainScheduler.instance) {
    self.mainScheduler = mainScheduler
    self.backgroundScheduler = backgroundScheduler
  }

  private func presenterMethod(_ isOn: Bool) -> Driver<Bool> {
    return interactor.interactorMethod(isOn)
        .subscribeOn(backgroundScheduler)
        .observeOn(mainScheduler)
        .do(onError: { [weak self] error in
            self?.view.showError(error)
        })
        .asDriver(onErrorJustReturn: !isOn)
    }
}

And then, when creating the presenter whithin the tests
let presenter = Presenter(backgroundScheduler: self.scheduler, mainScheduler: self.scheduler)


text:
Q: Showing that this particular sequence is Cauchy using the definition This is the following information that I've been given;
$$a_{1}=1,\, a_{2}=4,\, a_{n+2}=\frac{2a_{n+1}+a_{n}}{3}$$
I need to show that $|a_{m}-a_{n}|<\epsilon \,,\forall n\geq n_{0}, m>n$
I deconstructed the general sequence to the following
$$|a_{m}-a_{m-1}|+|a_{m-1}-a_{m-2}|+...+|a_{n+2}-a_{n+1}|+|a_{n+1}-a_{n}|$$
The above method was what our tutor showed us when basically telling what we would need to know to solve this, although I'm having difficulty getting from that back to the inequality to show that this sequence is or isn't Cauchy.

A: Observe that your recursive relation implies
$$
|a_{n+2}-a_{n+1}|= \frac 1{3}|a_{n+1}-a_{n}|
$$
So the differences are decreasing geometrically with ratio $1/3$. That is, for $m\le n$
$$
S_{mn}=|a_m-a_{m-1}|+|a_{m-1}-a_{m-2}|+\dots |a_{n+1}-a_{n}|=(1+1/3+1/9+\dots +1/3^{n-m})|a_{n+1}-a_{n}|.
$$
Now, given $\epsilon$ choose $n$ large such that $|a_{n+1}-a_{n}|<2\epsilon/3$ (this is possible because the sequence of the differences is geometric and decreasing to zero). Then we conclude
$$
S_{mn}\le 2(1+1/3+1/9+\dots +1/3^{n-m})\epsilon/3\le \epsilon.
$$
for all $m>n$ since
$$
1+1/3+1/9+\dots +1/3^{n-m}\le \sum_{i=0}^\infty 3^{-i}=3/2.
$$
Finally, just observe that
$$
|a_m-a_n|\le S_{mn}
$$
by the triangle inequality.

A: More generally, if
$a_{n+2} = ca_{n+1}+(1-c)a_n$
where $0 < c < 1$ then
$a_{n+2}-a_{n+1}
=ca_{n+1}+(1-c)a_n-a_{n+1}
=(c-1)a_{n+1}+(1-c)a_n
=(c-1)(a_{n+1}-a_n)
$ so
$|a_{n+1}-a_n|$
decreases in absolute value and alternates in sign.
$a_n$ then converges in the same way as shown in the other answer.

A: $$3(a_{n+2}-a_{n+1})=a_n-a_{n+1}.$$
Let $b_n=a_{n+1}-a_n.$
Thus, $$b_{n+1}=-\frac{1}{3}b_n,$$ which says
$$a_{n+1}-a_n=b_n=b_1\left(-\frac{1}{3}\right)^{n-1}=3\left(-\frac{1}{3}\right)^{n-1}=-\frac{1}{(-3)^{n-2}}.$$
Now, $$|a_m-a_n|=\left|\sum_{k=m-1}^n(a_{k+1}-a_k)\right|=\left|\sum_{k=m-1}^n\frac{1}{(-3)^{k-2}}\right|<\frac{1}{3^{n-2}}.$$
Can you end it now?


text:
Q: Css calc is not working on Safari I have this css rule:
#SideBar{
height: calc(100vh, -82px);
overflow: auto;
/*Something more*/
}

The problem is that, in all the other browser like: IExplorer, Chrome, Opera, Firefox, but in Safari is not working this rule? Exist an alternative rule to set the height?

A: The proper syntax of CSS calc() function  is -
calc(expression)
Where the expression can be built using +, -, * or / operators.
The comma , is not a valid operator to use inside calc(). Thus you are having an invalid property value of height inside the #SideBar.
Even you have to add space between operators and values.
You are having no space between - sign and 82px
So, your final code should looks like this -
#SideBar{
    height: calc(100vh - 82px);
    overflow: auto;
    /*Something more*/
}

Also safari still has some issue with viewport units, see here. You might want to use percentage value instead of viewport units. In this case the code will be -
#SideBar{
    height: calc(100% - 82px); /* Fallback for safari */
    height: calc(100vh - 82px); /* Supports for Chrome, FireFox, IE10+ */
    overflow: auto;
    /*Something more*/
}

A: Try without comma there or with -webkit-calc () prefix


text:
Q: Disable admin bar reload in wordpress When users navigate the site I do not want the WordPress admin bar to reload. I want it to be a permanent fixture. Everything else may reload.
How can I achieve this?
For all the confusion I am clarifying that I do NOT want to disable the admin bar. I want it not to refesh as user navigated the site so it down not have to reload but be as a permanent feature. Go example, in gmail the only the main contents reload but the header and sidebars do not reload

A: Hope it helps, removes admin bar other than administrator
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar()
{

    if (!current_user_can('administrator') && !is_admin())
    {
    show_admin_bar(false);
    }

}


text:
Q: CKEditor in a ajax form I try to use the same ckeditor replace several time in a ajax form:
 ... <textarea id="textareaId"></textarea> ...

And a javascript code
CKEDITOR.replace('textareaId');
$('#textareaId').val("first");
CKEDITOR.replace('textareaId');
$('#textareaId').val("second");

Can somepody know why id does not show "second" instead of "first" in the textarea with ckeditor? And how to get the correct value $('#textareaId').val()?
Thank you

A: Ids should be unique, so (I don't use CKEditor btw so no clue what this is trying to achieve but am explaining how ids should be used):
<textarea id="textareaId"></textarea>
<textarea id="textareaId2"></textarea> <!-- changed id -->

CKEDITOR.replace('textareaId');
$('#textareaId').val("first");
CKEDITOR.replace('textareaId2'); /* new id for text area */
$('#textareaId2').val("second");

A: I think you should force destroying instance before replace again.
var editor = CKEDITOR.instances['textareaId'];
if (editor) {
    editor.destroy(true);
}
CKEDITOR.replace('textareaId');


text:
Q: Product last modified date & who modified it I would like to know is there a way where I could get last modified date & who modified the product in magento backend?

A: This is not available in Community Edition 'default install'.
The data is not stored. Obviously you can look at the Apache log files to see things at an IP address level if you need some forensics, however, what you are after cannot be done out-the-box with Community Edition.
In the world of extensions there are plenty of options, generally paid for. However, if you want to roll your own then this article is a good place to start:
http://inchoo.net/magento/logging-user-customer-actions-in-magento/

A: You can get the last modified date by calling $product->getUpdatedAt(). unfortunately you cannot know who modified it. That information is not logged.
But the getUpdatedAt method might not help you 100% of the cases either.
The value of update_at is changed only when calling specifically $product->save(). This happens when the product is saved from the backend or if you call it from a script.
updated_at is not changed if you use the update attributes mass action. See more about this bug/feature/inconsistency in here: Change updated_at date on mass action

A: Credits : Fabian Blechschmidt
link : https://github.com/firegento/firegento-adminmonitoring
class FireGento_AdminMonitoring_Adminhtml_HistoryController extends Mage_Adminhtml_Controller_Action
{
    /**
     * Inits the layout, the active menu tab and the breadcrumbs
     *
     * @return FireGento_AdminMonitoring_Adminhtml_HistoryController
     */
    protected function _initAction()
    {
        $this->loadLayout();
        $this->_setActiveMenu('system/history');
        $this->_addBreadcrumb(
            $this->getMonitoringHelper()->__('Admin Monitoring'),
            $this->getMonitoringHelper()->__('History')
        );

        $this->_title($this->getMonitoringHelper()->__('Admin Monitoring'))
            ->_title($this->getMonitoringHelper()->__('History'));

        return $this;
    }

    /**
     * Shows the history grid
     */
    public function indexAction()
    {
        $this->_initAction();
        $this->renderLayout();
    }

    /**
     * Reload the adminhtml history grid, for
     */
    public function gridAction()
    {
        $block = $this->getLayout()->createBlock('firegento_adminmonitoring/adminhtml_history_grid');
        $this->getResponse()->setBody($block->toHtml());
    }

    /**
     * View a single history grid
     */
    public function viewAction()
    {
        /* @var $history FireGento_AdminMonitoring_Model_History */
        $history = Mage::getModel('firegento_adminmonitoring/history')->load($this->getRequest()->getParam('id'));
        if (!$history->getId()) {
            $this->_redirect('*/*');

            return;
        }

        Mage::register('current_history', $history, true);

        $this->_initAction();
        $this->renderLayout();
    }

    /**
     * Reverts a history entry
     */
    public function revertAction()
    {
        /* @var $history FireGento_AdminMonitoring_Model_History */
        $history = Mage::getModel('firegento_adminmonitoring/history')->load($this->getRequest()->getParam('id'));
        if ($history->getId()) {
            $model = $history->getOriginalModel();
            $model->addData($history->getDecodedContentDiff());
            $model->save();
            Mage::getSingleton('adminhtml/session')->addSuccess(
                $this->getMonitoringHelper()->__(
                    'Revert of %1$s with id %2$d successful',
                    $history->getObjectType(),
                    $history->getObjectId()
                )
            );
        }

        $this->_redirect('*/*');
    }

    /**
     * Retrieve the adminmonitoring helper
     *
     * @return FireGento_AdminMonitoring_Helper_Data
     */
    public function getMonitoringHelper()
    {
        return Mage::helper('firegento_adminmonitoring');
    }

    /**
     * Check is allowed access to action - needed afer security patch SUPEE-6285
     *
     * @return bool
     */
    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('system/history');
    }
}


text:
Q: BlackBerry - Programmatically create new exception in profile? Actually i trying how to read the profile status but i am not getting that.
....
If anyone have an idea how to create new exception in profile programmatically,
will really helpful for me.
Thanks


text:
Q: Setting Public Property in msi Custom Action Is it possible to set a public property (say MYPROPERTY) from a C# custom action? I can read properties with Context.Parameters["MYPROPERTY"] that I pass into the custom action data but is there a way to set them too?
Thanks.

A: I don't know of a way to do it.  In most cases, it would be impossible.  Visual Studio's setup and deployment projects set their .net custom actions to run "deferred", meaning they run after the msi installation objects have been disposed.  Here's the list of the possible operations in that context.
To verify that your .net custom actions are running deferred, use Orca to open the msi file and go to the CustomAction table.  If the InstallUtil (VS's utility library that is placed in the "Binary" table of the MSI by VS and exposes a 'C' entry point to MSI that calls into a .NET installer assembly's installation entry points) actions have "3073" as their "Type", that means that they are running as deferred execution (3073 is msidbCustomActionTypeInScript + msidbCustomActionTypeNoImpersonate + msidbCustomActionTypeDll.)
If you create a 'C' custom action in a DLL and put it in your MSI it with a Type of "1" you can execute it during the install sequence and change properties.  Unfortunately, VS's install project doesn't support that; it runs every custom action deferred as far as I can tell.


text:
Q: throttle functions return(...args),return function(...args) Hello i'm trying to learn the concept of throttling,i've read some articles and "kinda" got the hang of it (the concept at least) but there is one thing i can't figure out when reading these functions and is the part where u return a function with the "arguments" for example in these functions i found:
  const throttleFunction = (func, delay) => {
        let prev = 0;
        return (...args) => {
            let now = new Date().getTime();
            if (now - prev > delay) {
                prev = now;
                return func(...args);
            }
        }
    }

    const throttle = (func, limit) => {
        let inThrottle
        return function() {
          const args = arguments
          const context = this
          if (!inThrottle) {
            func.apply(context, args)
            inThrottle = true
            setTimeout(() => inThrottle = false, limit)
          }
        }
      }

i don't get what the
return (...args) => {

            return func(...args);
        }

does
same in the other one
 const args = arguments
   func.apply(context, args)

in fact i'm having some troubles tryng to use them some times i get them to work some times i don't especially when i have to pass parameters to the function i want to throttle
when i have a single button i usually do
<button onclick="throttleFunction(some_function,1500)">Click me</button>

and it works
but when i have to pass something like the "this" i can't get it
let's say i have some divs
i do
const func = (thhis) => {
 console.log(thhis);
}
const x = throttleFunction(func,2500);

 something

 something

 something

and it doesn't work the function gets called every time i click on the div...
can someone explain me ?

A: The concept of throttling is literally to avoid subsequent function calls to be executed for a limited amount of time.

*

*Say hello

*suppress any further function call for x amount of time

*make function callable again.

You can really think about it as rate limiting for function calls...

const throttle = (ms, fn) => {
  let scheduler;

  return (...args) => {
    if (scheduler) {
      return null;
    }

    fn(...args);

    scheduler = setTimeout(
      () => {
        scheduler = null;
      },
      ms
    );
  }
}

const logger = throttle(
  500,
  console.log,
);

logger('Ciao');

// this is not called
logger('Bello');
logger('Bello');
logger('Bello');
logger('Bello');
logger('Bello');
logger('Bello');

setTimeout(() => logger('Ciao Bello'), 600, 'Ciao Bello');

*

*You can learn about the arguments variable at this link, it's a variable that is created and old the function's call... it is largely not recommended anymore since you can use the array spread operator instead.

*You might also want to learn about debouncing


text:
Q: Databinding textbox Well I'm a bit of a newbie with MVVM so please any tips ans suggestions are welcome :)
I want to keep track of a username and password and the user can set this on a Settings view.
In the SettingsViewModel I have 2 properties for these 2 fields that are bound to the text boxes on the view.
I added a Save button on the app bar and through a RelayCommand it executes a method on the ViewModel when the user clicks it.
Now what goes wrong:

*

*When the user is typing in a textbox and doesn't exit it, but presses the save directly, the value is not databinded yet. So how do you solve this? Is the only way using the coding4fun:TextBoxBinding.UpdateSourceOnChange="True" feature from the coding4fun library?

*When a user enters data in a textbox and it is databound, leaving the settings page and returning to it will still keep this data. How do I clear this as long as the user hasn't pressed the save button? Kinda weird that you keep data on the page when it hasn't been saved yet... But because I use MVVMLight the page is statically created in the ViewModelLocator and stays 'active' as long as the program is running.
Well like I said, any hints, tips, suggestions are welcome :)

A: Re 1: This is a known issue where if the last control that had focus was a textbox, and you click on an app-bar button, its latest value is not databound properly.  In my appbar click event handlers, I invoke the following method to force a databind if the last control to have focus was a textbox or passwordbox.
private static void UpdateBoundText()
{
    var focusObj = FocusManager.GetFocusedElement();
    if (focusObj == null) return;
    var binding = focusObj is TextBox ? ((TextBox)focusObj).GetBindingExpression(TextBox.TextProperty)
                : focusObj is PasswordBox ? ((PasswordBox)focusObj).GetBindingExpression(PasswordBox.PasswordProperty)
                : null;
    if (binding != null)
    {
        binding.UpdateSource();
    }
}

A: 1 - Set the UpdateSourceTrigger value on the TextBox binding to PropertyChanged
<TextBox Text="{Binding MyProperty, UpdateSourceTrigger=PropertyChanged}" />

2 - I haven't used the MVVM Light Toolkit, but presumably it has the concept of a view model being activated, where you could reset the properties to their default values in your view model.  If it doesn't, then have a look at Caliburn.Micro which does support this concept.


text:
Q: mongodb GEO2D Index - kilometers? I have a geospatial index in my database.  MongoDB's documentation says that the $near operator takes an argument in meters to find matches.  For example:
db.data.find({'coordinates': SON([('$near', [20.450550042732765, 80.52327036857605]), ('$maxDistance', 100)])}).count()

should return matches within 100 meters of that location.  But too many are returned, about 3,000.  When I rewrite the query as
db.data.find({'coordinates': SON([('$near', [20.450550042732765, 80.52327036857605]), ('$maxDistance', 1)])}).count()

I receive 364 results.  I do not think my database has 364 matches within a 1 meter radius of the point I query.  Finally, if I query
db.data.find({'coordinates': SON([('$near', [20.450550042732765, 80.52327036857605]), ('$maxDistance', .1)])}).count()

I receive 330 matches.  There are definitely not 330 results within 10 centimeters of that point.
I think mongodb interprets distance as kilometers, not meters.  Can anyone confirm or explain what is going on?

A: If you are using the legacy 2d index, and it looks like that's what you're doing, then $maxDistance is in radians, as per the documentation you linked to.


text:
Q: Backbone collection only renders on page load but not when coming from a different route I'm trying to use Backbone with requirejs, which is working just fine so far and I used a very clean boilerplate, but now I also want to start using Backbone's way of handling views and models, which I haven't before, and my lobby table view renders just fine on page load, but as soon as I change page and come back to it, it won't render anything. No error's given and the collection seems to fetch the new data just fine. Could it have anything to do with rendering the basic table structure in the main.js and then afterwards creating a child view in views/play.js without telling the parent view?
Backbone router (main.js)
play: function() {
    var view = new app.Views.Play();
    app.instance.changePage(view);
    require(['controllers/play'], function(PlayController) {
        PlayController.init();
    });
},

…

app.Views.App = app.Extensions.View.extend({

  el: 'body',

  changePage: function(view) {

    var previous = this.currentPage || null;
    var next = view;

    if(previous) {
      if(AppLib.transitions === "notransitions") previous.remove();
      previous.transitionOut(function() {
        previous.remove();
      });
    }

    next.render({ page: true });
    this.$el.append(next.$el);

    next.transitionIn();
    this.currentPage = next;

    // Change page title
    var title = app.lang.get(next.className + ".title");
    if(title === next.className + ".title") title = next.className;
    document.title = (!_.isEmpty(Backbone.history.getFragment()) ? title.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}) : AppLib.name);

  }

});

…

app.Views.Play = app.Extensions.View.extend({

  className: 'play',
  addHeader: function() {
    var options = { className: "gl-header", fixed: true, elements: ['BackButton', 'LoginButton'] };
    var n = new app.Views.Header({ el: "." + this.className, parentView: this, options: options });
    this.$el.prepend(n.render());
  },

  render: function() {
    var template = _.template($('script[name=play]').html());
    this.$el.html(template());
    this.addHeader();
    return app.Extensions.View.prototype.render.apply(this, arguments);
  }

});

The play controller (controllers/play.js)
define(['jquery', 'backbone', 'models/play', 'views/play'], function($, Backbone, Model, View) {
    return {
        init: function() {
            var LobbyCollection = new Model.LobbyCollection();
                LobbyCollection.getMatches();

            var LobbyView = new View.Lobby({ collection: LobbyCollection });
        }
    }
});

The play model (models/play.js)
define(['jquery', 'backbone', 'persist', 'AppLib'], function($, Backbone, Persist, AppLib) {
var Match = Backbone.Model.extend({});

  var LobbyCollection = Backbone.Collection.extend({
    model: Match,
    url: "/api/v1/play/lobby-updates",
    initialize: function() {

    },
    getMatches: function(callback) {
      var self = this;
      this.fetch({
        reset: true,
        success: function(collection, response, options) {
          self.trigger('successOnFetch');
        },
        error: function(collection, response, options) {
          self.trigger('errorOnFetch');
        }
      });
    },
    parse: function(response) {
      var obj = response["lobby_matches"];
      this.RandomLobbyName = response["random_name"];
      return _.map(obj, function(value, key) {
        return obj[key];
      });
    }
  });

  return {
    LobbyCollection: LobbyCollection
  }
});

The play view (views/play.js)
define(['jquery', 'backbone', 'persist', 'AppLib', 'jquery_debounce'], function($, Backbone, Persist, AppLib) {

var LobbyView = Backbone.View.extend({
    el: **$(".play.page-container .table")** !!".play.page-container .table",
    initialize: function() {
      var self = this;

      this.listenTo(this.collection, 'reset', this.render);
      this.listenTo(this.collection, 'successOnFetch', this.handleSuccess);
      this.listenTo(this.collection, 'errorOnFetch', this.handleError);

      $(".play.page-container .table button.refresh-list").on("click", $.throttle(2000, function() {
        $(this).html($("<span\>", { "class": "opaque blue throbber small" })).addClass("selected").prop("disabled", true);
        self.collection.getMatches();
      }));
    },
    handleSuccess: function(options) {
      setTimeout(function() {
        $(".play.page-container .table button.refresh-list").removeClass("selected").removeAttr("disabled").html($("<span\>", { "class": "icon-spinner6" }));
  }, 2000);
    },
    handleError: function(options) {

    },
    render: function() {
      var template = _.template($('script[name=lobby-table]').html());
      var $tbody = this.$el.children("tbody");
          $tbody.children().not(".create-lobby").remove();
          $tbody.append(template({ collection: this.collection.toJSON() }));
      return this;
    }
});

return {
    Lobby: LobbyView
}

});

A: I solved it myself. The problem was I looked up how to make a view on here and they defined the element using jquery so: el: $("selector") and I followed that, but that's wrong. Backbone already puts it into jquery itself, so it's double that way. So I simply put my selector in quotation marks and now everything works.


text:
Q: Tkinter new window does not appear until the function is finished I have a long process to do and I want to notify the user to wait during the time of execution.
It looks like this:
class MainWindows(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Nmap Database")
        self.geometry("800x600")
        self.resizable(True, True)
        self.create_widgets()
    ....

   def refresh(self) :
      self.openWindows()
      long_operation()

   def openWindows(self):
      window = WaitingWindows(self)
      window.grab_set()

class WaitingWindows(tk.Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.title("Scan")
        self.geometry("100x50")
        self.resizable(True, True)
        self.create_widgets()

    def create_widgets(self):
        self.label = ttk.Label(self, text="Scanning... Please wait")
        self.label.pack(side=tk.TOP, expand=True)

But the windows appear at the end of the execution of 'long_operation()'.
Ps: I will add something to notify that the operation have finished.
Thank you


text:
Q: scale() and shape() in Processing UPDATE: I think I figured it out. The scaleMultiplier also applied to the translate that I was trying to do. I had a suspicion this was the case but couldn't figure out exactly how it got affected.
Anyone familiar with a spinoff of Java called Processing? I'm trying to do something simple, scale a shape and place it in the center of the sketch. This is my code in a nutshell:
pushMatrix();

float scaleX, scaleY, scaleMultiplier, resetX, resetY, transX, transY;

scaleX = 500 / (float)clickState.bounds.getWidth();
scaleY = 500 / (float)clickState.bounds.getHeight();
scaleMultiplier = min(scaleX,scaleY);
resetX = -(float)clickState.bounds.getX();
resetY = -(float)clickState.bounds.getY();

transX = resetX + ((800 - ((float)clickState.bounds.getWidth() * scaleMultiplier))/2);
transY = resetY + ((550 - ((float)clickState.bounds.getHeight() * scaleMultiplier))/2);

scale(scaleMultiplier);
shape(clickState.pshape, transX, transY);

popMatrix();

What I'm trying to do is scale a state on a US Map. clickState is the state that the user clicked on. clickState.bounds is a Rectangle that surrounds the shape of the state. getX() and getY() return the x and y coords of the upper left hand corner of said box. I want to scale the state so that it's no bigger than 500x500 pixels. After that, I want to translate it so that it's in the middle of the sketch, which is 800x550.
Here's where I run into trouble: When I do
shape(clickState.pshape, resetX, resetY);

It draws the state in the upper left hand corner of the sketch. That's exactly what it should do. Then from there I want to add the number of pixels that it would take to center the shape, which is what transX and transY are for. However, when I use transX and transY, the shape gets drawn almost completely off the canvas, depending on where the state is located (even if its only being moved 50 pixels to the right from 0,0). It doesn't make any sense to me whatsoever. I've tried all sorts of combinations of translate(), and even skipping scale() altogether and using a width and height in shape(). It's like Processing is trying to frustrate me on purpose. Any help is appreciated.

A: I'm not familiar with Processing, but matrix operations are not commutative—the order matters. Typically, operations are applied in an apparent last-specified-first-applied order, as shown in this example.

A: Vince, I think I was trying to do something very similar last week. Sounds like you figured it out, but check out the answers on this board:
http://forum.processing.org/topic/how-do-i-move-svg-child-shapes#25080000000689051