text:
Q: Cross thread problem?  My error

Cross-thread operation not
  valid: Control 'MailTree' accessed
  from a thread other than the thread it
  was created on.

with my code
My idea is when SaveMail method has finish store 1 mes then add this mes to listview.
private delegate int SaveMailDelegate(ImapX.Message mes);

public int SaveMail(ImapX.Message mess)
{
    if (!File.Exists("D:\\" + Username + "\\" + MailTree.SelectedNode.Text + "\\" + mes.MessageUid.ToString() + ".eml"))
    {
        mess.Process();
        mess.SaveAsEmlToFile("D:\\" + Username + "\\" + MailTree.SelectedNode.Text + "\\", mes.MessageUid.ToString());   //Store messages to a Location

    }
    // mes.MessageUid=mess.MessageUid;
    return 1;
}
Mime EncodingMail(string NodeName,string focusitem)
{
    Mime m = new Mime();
    m=Mime.Parse("D:\\" + Username+ "\\"+NodeName+"\\"+focusitem+".eml");
    return m;
}
private void AddMesToMailList()
{
    ListViewItem item = new ListViewItem();
    Mime m = EncodingMail(MailTree.SelectedNode.Text, mes);
    item.Text = mes.MessageUid.ToString();
    item.SubItems.Add(m.MainEntity.Subject);
    ReturnMime(m);
    if (mailfromname != null)
        item.SubItems.Add(mailfromname);
    else item.SubItems.Add(mailfrom);
        item.SubItems.Add(m.MainEntity.Date.ToString());
    item.SubItems.Add(mailfrom);
    MailList.Items.Add(item);
}
private void SaveMailDone(IAsyncResult iar)
{
    SaveMailDelegate del = iar.AsyncState as SaveMailDelegate;
    if (del != null)
    {
        int result = del.EndInvoke(iar);
        AddMesToMailList();
    }
}

private void MailTree_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
    MailList.Items.Clear();
    for (int i = 0; i < client.Folders.Count; i++)
    {
        (ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems[i].Click += new EventHandler(MainForm_Click);
    }
    if (MailTree.SelectedNode.Text == Username)
    {
        webBrowser1.Visible = false;//webBrowser1.DocumentText = "Hello Baby";
        AttachmentList.Visible = false;
        groupBox1.Visible = false;
    }
    else
    {
        webBrowser1.Visible = true;
        groupBox1.Visible = true;

        try
        {
            messages = client.Folders[MailTree.SelectedNode.Text].Search("ALL", false); // Search mail in your choossen Folder
            AmoutOfMail = messages.Count(); //Amout of Mail in this Folder
            for (int i = 0; i < AmoutOfMail; i++)
            {
                mes=messages[i];
                SaveMailDelegate del = new SaveMailDelegate(this.SaveMail);
                del.BeginInvoke(mes, new AsyncCallback(this.SaveMailDone), del);
            }
        }
        catch (Exception)
        { }
    }
}

A: You cannot directly access a control from another thread, you will have to invoke it.
private delegate void ControlCallback(string s);

public void CallControlMethod(string text)
{
    if (control.InvokeRequired)
    {
        ControlCallback call = new ControlCallback((s) =>
        {
            // do control stuff
        });
        control.Invoke(call, new object[] { text });
    }
    else
    {
        // do control stuff
    }
}

A: I think AddMesToMailList() is trying to modify the view elements but it is on a wrong thread.
Try something like this
void AddMesToMailList()
{
    if (this.InvokeRequired)
    {
         this.BeginInvoke(new Action(AddMesToMailList));
         return;
    }

    // do stuff that original  AddMesToMailList() did.
}

EDIT:
       SaveMail is a little complicated as it has a return value but you can try this
public int SaveMail(ImapX.Message mess)
{
     if(this.InvokeRequired)
     {
            return (int) this.Invoke(
                   new Func<ImapX.Message, int>( m => SaveMail(mess)) );
     }
     else
     {

        if (!File.Exists(@"D:\" + Username + "\\" + MailTree.SelectedNode.Text + "\\" + mes.MessageUid.ToString() + ".eml"))
        {
            mess.Process();
            mess.SaveAsEmlToFile(@"D:\" + Username + "\\" + MailTree.SelectedNode.Text + "\\", mes.MessageUid.ToString());   //Store messages to a Location

        }
       // mes.MessageUid=mess.MessageUid;
        return 1;

     }

}

A: you can't access the UI on a different thread than what it was created on. From inside your secondary thread (the one that runs your callback handler) you will need to call Form.BeginInvoke to register a method that will be run on the UI thread. From that method you can update your UI controls


text:
Q: IIS behaviour with JS files, transfer paused This is a tough one, in all my years I've never seen it. The setup is windows 2003 r2, running IIS, MVC 1, asp.net 3.5. I have a website, which is viewable on the server itself and renders correctly. However, when you access it remotely the site transfers roughly half it's contents and then gets stuck downloading some javascript files. Browser stays in "transferring data". I'm mystified. Anyone got any pointers to help me from pulling out all my hair?

A: Use Fiddler to watch the requests come out of the browser.
http://www.fiddler2.com/fiddler2/
Also sometimes the content type is not set correctly, but really it sounds like the app itself is broken or needs IIS 7.x to run correctly.

A: Try turning off TCP Checksum Task Offloading:
http://support.microsoft.com/kb/904946
I had problems similar to this on a 2003 instance under XenServer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wrapping up cfiles and related dependences to implement them in C++/Windows? I have an assignment to write a program to implement i2c communication between a temp sensor and the Adafruit FT232H Breakout board (https://learn.adafruit.com/adafruit-ft232h-breakout/overview).
The end result is this running on a Linux computer, and they did not want it implemented in python like the examples, so I decided on using the suggested C library, libmpsse,(https://code.google.com/p/libmpsse/).
after installing the libftdi library that it needs, as well as the libpmpsse code. I was able to get the .c code working, using the make provided.
There Make
LDFLAGS= -lmpsse

all: spiflash spiflashfast i2ceeprom ds1305 gpio bitbang

spiflash:

spiflashfast:

i2ceeprom :
           $(CC) $(CFlags) i2ceeprom.c -o i2ceeprom $(LDFLAGS)

ds1305:

clean:
           rm -f* .dsym
           rm -f spiflash spiflashfast i2ceeprom ds1305 gpio bitbang

distclean: clean

What I am hoping to be able to do, is take all the required library's and wrap it all together in one package (cmake?) With the end result being single functions in a c++ file that will be able to run the functions in my .c code.
What I've tried:
Using CMake, I tried to use the add_libraycommand to tie the lmpsse.c together.
I cant post any more links but it looks like:
cmake_minimum_required(VERSION 2.8)
project(i2c)

add_library(i2cFunctions, lmpsse.c)
include_directories("${PROJECT_SOURCE_DIR}/i2cFunctions")
add_subdirectory(i2cFunctions)

add_executable(i2c i2ceeprom.c)
target_link_libraries(i2c i2cFunctions)

I then run it, with the files I want in the dir above, but it produces
Linking C executable i2c
CMakeFiles/i2c.dir/i2ceeprom.c.o: In function `main':
i2ceeprom.c:(.text+0x73): undefined reference to `MPSSE'
i2ceeprom.c:(.text+0xa0): undefined reference to `Start'
i2ceeprom.c:(.text+0xb6): undefined reference to `Write'
i2ceeprom.c:(.text+0xcc): undefined reference to `Write'
i2ceeprom.c:(.text+0xd8): undefined reference to `GetAck'
i2ceeprom.c:(.text+0xec): undefined reference to `Stop'
i2ceeprom.c:(.text+0xf8): undefined reference to `Start'
i2ceeprom.c:(.text+0x10e): undefined reference to `Write'
i2ceeprom.c:(.text+0x11a): undefined reference to `GetAck'
i2ceeprom.c:(.text+0x133): undefined reference to `Read'
i2ceeprom.c:(.text+0x15b): undefined reference to `Stop'
i2ceeprom.c:(.text+0x18c): undefined reference to `Start'
i2ceeprom.c:(.text+0x1a2): undefined reference to `Write'
i2ceeprom.c:(.text+0x1b8): undefined reference to `Write'
i2ceeprom.c:(.text+0x1c4): undefined reference to `Stop'
i2ceeprom.c:(.text+0x1d0): undefined reference to `Start'
i2ceeprom.c:(.text+0x1e6): undefined reference to `Write'
i2ceeprom.c:(.text+0x1f2): undefined reference to `SendAcks'
i2ceeprom.c:(.text+0x203): undefined reference to `Read'
i2ceeprom.c:(.text+0x213): undefined reference to `SendNacks'
i2ceeprom.c:(.text+0x224): undefined reference to `Read'
i2ceeprom.c:(.text+0x234): undefined reference to `Stop'
i2ceeprom.c:(.text+0x6fc): undefined reference to `Stop'
i2ceeprom.c:(.text+0x716): undefined reference to `ErrorString'
collect2: error: ld returned 1 exit status
make[2]: *** [i2c] Error 1
make[1]: *** [CMakeFiles/i2c.dir/all] Error 2
make: *** [all] Error 2

Thanks for any ideas or help you might have,
If my explanation is a little weird I would be happy to explain better.


text:
Q: Application appears to run multiple times depending on input size I have 2 python scripts https://gist.github.com/2233477.

*

*rsgen.py generates "random" inputs for use in simulate.py

*simulate.py does the actual simulation

Thing is, when I start to increase the input size from rsgen.py with the --numReferences param, I get different outputs
# ./rsgen.py --numReferences 1000 > rs.txt; cat rs.txt | xargs ./simulate.py
Number of page faults : 59

# ./rsgen.py --numReferences 100000 > rs.txt; cat rs.txt | xargs ./simulate.py
Number of page faults : 873
Number of page faults : 848
Number of page faults : 823
Number of page faults : 103

./rsgen.py --numReferences 1000000 > rs.txt; cat rs.txt | xargs ./simulate.py
Number of page faults : 866
Number of page faults : 869
Number of page faults : 876
Number of page faults : 907
Number of page faults : 910
Number of page faults : 1001
Number of page faults : 845
...

Notice as I increase numReferences, the python script simulate appears to run more times. Why is that? I am expecting just 1 line of "Number of page faults: ..."

A: This probably has something to do with xargs' ARG_MAX which defines a batch size for how many args to send to an executable; hence why multiple invocations of your script since it is splitting up the args across multiple calls.
Try the -n (or --max-args) flag of xargs .
A better way alltogether would be to have simulate.py accept a file argument so you could do something like this:
./rsgen.py --numReferences N > rs.txt;
./simulate.py -f rs.txt

It would probably be a lot faster since it avoids the xargs overhead


text:
Q: json.serializeArray, not including arrayed elements I am getting a really wired issue while using the serializeArray on form submit via ajax.
Here is any example of my code:

console.log($('form').serializeArray());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<form action="..." method="post">
  <input type="text" name="title" value="input value">

  <select name="select_one" id="select_one">
    <option value="1">Select 1 - 1</option>
    <option value="2" selected>Select 1 - 2</option>
    <option value="3">Select 1 - 3</option>
  </select>

  <select name="select_two[]" id="select_two[]" multiple="multiple">
    <option value="1" selected>Select 2 - 1</option>
    <option value="2" selected>Select 2 - 2</option>
    <option value="3">Select 2 - 3</option>
  </select>

  <select name="select_three[]" id="select_three[]" multiple="multiple">
    <option value="1" selected>Select 3 - 1</option>
    <option value="2" selected>Select 3 - 2</option>
    <option value="3">Select 3 - 3</option>
  </select>

  <input type="text" name="mobile" value="1234567890">
</form>

Output
{
    "title": "input value",
    "select_one": 2,
    "mobile": 1234567890
}

Whereas it should have been
{
    "title": "input value",
    "select_one": 2,
    "select_two": [1, 2],
    "select_three": [1, 2],
    "mobile": 1234567890
}

All the elements except the arrayed ones are collected.
I have tried googling this issue but could not find any solution.

A: If the output shown in the question is your goal, then serializeArray() is not the correct method to achieve it. That returns an array of objects with each object containing one value per field. It doesn't return not a single object containing string/array values as your goal requires.
To do what you need you will have to build the object manually:

$('form').on('submit', e => {
  e.preventDefault();

  const output = {};
  $(e.target).find(':input[name]').each((i, el) => output[el.name] = $(el).val());

  console.log(output);

  // ajax request here...
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<form action="..." method="post">
  <input type="text" name="title" value="input value">

  <select name="select_one" id="select_one">
    <option value="1">Select 1 - 1</option>
    <option value="2" selected>Select 1 - 2</option>
    <option value="3">Select 1 - 3</option>
  </select>

  <select name="select_two[]" id="select_two[]" multiple="multiple">
    <option value="1" selected>Select 2 - 1</option>
    <option value="2" selected>Select 2 - 2</option>
    <option value="3">Select 2 - 3</option>
  </select>

  <select name="select_three[]" id="select_three[]" multiple="multiple">
    <option value="1" selected>Select 3 - 1</option>
    <option value="2" selected>Select 3 - 2</option>
    <option value="3">Select 3 - 3</option>
  </select>

  <input type="text" name="mobile" value="1234567890">

  <button type="submit">Submit</button>
</form>


text:
Q: append same element into two places I have the following html....

jquery:
$('#clickto').click(function(){
   $('
hi
').appendTo('#test div:nth-child(1)');
   $('
hi
').appendTo('#test div:nth-child(2)');
});

The same element I have to append since I appended two times. I think there is an easy way.
I tried this but appends to only one div:
$('
hi
').appendTo('#test div');

A: Working DEMO
This will do it
:lt documentation
div:lt(2) will select first two elements
$('
hi
').appendTo('#test div:lt(2)');

A: You can turn it around
$('#test div').append($('
hi
'));

A:

 $('
hi
').appendTo('#test div.select_me');


text:
Q: Python elegant way for many conditional statements in if statement Is there a better more elegant / professional way to code the following
if A > 1 and B > 1 and C > 1 and A < 100 and B < 100 and C < 100:
    do something

?

A: Use the all() function, as well as chained comparisons
if all(1 < x < 100 for x in (A, B, C)):
    # do something

A: Use all() rather than listing out each condition. This will make it easier to add new variables to check, if necessary:
if all(1 < item < 100 for item in [A, B, C]):
    do something


text:
Q: Should I use flash card Or USB pen drive with eBoostr (ReadyBoost) I have 1GiB of RAM and would like to know what kind of memory device will be best for use with eBoostr (something like ReadyBoost).
I have heard that flash cards are faster than USB flash drives. What I want to know is if flash cards have wear leveling feature and support ReadyBoost. Wear leveling feature is important to prolong the life of flash memory. Also what is no less important is high-speed random read and write of small chunks of data. One person's benchmarking experience showed that SLC flash memory performs better than MLC.
What would be better?

A: Don't bother using ReadyBoost. It's almost never a good idea. Not only does it wear out extremely quickly, flash drives have nowhere near both the raw bandwidth and latency as internal RAM for several reasons including the limitations of both flash memory and the USB protocol.
tl;dr: If you want more RAM, buy more RAM.


text:
Q: Run CNTK on machine with multiple GPUs I'm running CNTK on an Azure VM with 2 x K80 GPUs.
Do I need to do anything special in my Python (Jupyter Notebook) code in order to take advantage of the multiple GPUs or will CNTK automatically take advantage of both GPUs?

A: Currently automatic multi-GPU training in CNTK is supported via MPI. Launching multi-GPU training in Notebook is possible using multiprocessing.
Here is more details on how to run CNTK with multiple GPUs.


text:
Q: How to connect to oracle apex environment from my android browser I am working with oracle apex 5.1 on my Laptop at: http://192.168.1.6:8181/APEX/ at a local network and every thing is working correctly, I want to open the same at my mobile web browser.
When I navigate to
https://apex.oracle.com/pls/apex/f?p=4550:1:16230997599016: from mobile; the login page appears normally, But when I navigate to: http://192.168.1.6:8181/APEX/ I face unable to connect message in browser.


text:
Q: Failed to attach debug in python tool visual studio I have a problem with "attach to process" in python tool in vs.
If I attach to process before the next line:"import clr" , everything is ok and I can debug.
If I attach after this line I failed to debug and get "... No symbols have been loaded..."
I don't know why,
(If I use regular debug, everything is OK)
Thanks,
Code:
in this case I failed to attach in line 4
1. import sys
2. import clr
3. while True:
4.     print "Hello"

In this case I succeeded to attach in line 2 (also can continue debug all the code):
1. import sys
2. for i in range(1000):
3.     print "Hello"
4. import clr
5. while True:
6.     print "Hello"


text:
Q: How to "stack" and "unstack" in R, for summary statistics with 2 factors I'm attempting to calculate two summary statistics (mean and standard error) from the following data set, where both Location and Adult should be factors.
 Location    Adult    OverComp
 F           1        7
 P           1        8
 P           0        10
 F           1        3
 F           0        11

I would like the output to appear as follows:
Location    Adult     OverComp.m    OverComp.se
F           1         (mean)        (standard error)
F           0         (mean)        (standard error)
P           1         (mean)        (standard error)
P           0         (mean)        (standard error)

Where OverComp.m is the calculated mean for each combination of Location x Adult, and OverComp.se is standard error for each of those combinations. I want this format because I want to then use this with ggplot2, to make a bar plot of the four means & se's, color-coded for Location.
I've gotten this far:
 summary.OverComp <-data.frame(
 + Location=levels(as.factor(data$FLocation)),
 + MeanOverComp=tapply(data$OverComp, list(data$FLocation,data$Adult), mean),
 + se=tapply(data$OverComp, list(data$FLocation,data$Adult),std.error))

Which produces the statistics I want, but not the format that I need for plotting in ggplot2 (as far as I can tell):
summary.OverComp
       Location   MeanOverComp.0 MeanOverComp.1   se.0      se.1
 F     Fiji       7.238095       8.454545         0.3792062 0.3023071
 P     Peru       6.893617       5.395833         0.4544304 0.3076155

I am now a bit clueless - not sure whether to pursue a different method for plotting, or a transformation to the above output, or to figure out how to incorporate Adult as a factor in my summary coding. I have an inkling that reshape2 may be involved, but not sure how to approach that. Your help would be much appreciated!

A: You could try data.table (if dat is the dataset)
 library(plotrix)
 library(data.table)

 setDT(dat)[,list(OverComp.m=mean(OverComp),
                Overcomp.se=std.error(OverComp)), by=list(Location, Adult)]
     Location Adult OverComp.m Overcomp.se
 #1:        F     1          5           2
 #2:        P     1          8          NA
 #3:        P     0         10          NA
 #4:        F     0         11          NA

A: This is a typical use for aggregate, a base (actually stats-pkg)  function:
> aggregate(dat$OverComp, # the values being aggregated
            dat[-3],   # the grouping factors
            function(Ov) c(mean=mean(Ov), sd=sd(Ov) ) #aggregation function(s)
            )
  Location Adult    x.mean      x.sd
1        F     0 11.000000        NA
2        P     0 10.000000        NA
3        F     1  5.000000  2.828427
4        P     1  8.000000        NA

If you had more than one item in the three categories where you see NA's then a more ayttractive ouput would have occurred.


text:
Q: SSE mean filter in c++ and OpenCV I would like to modify the code for an OpenCV mean filter to use Intel intrinsics. I'm an SSE newbie and I really don't know where to start from. I checked a lot of resources on the web, but I didn't have a lot of success.
This is the program:
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;
using namespace std;

int main()
{
    int A[3][3] = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } };
    int c = 0;
    int d = 0;
    Mat var1 = imread("images.jpg", 1);
    Mat var2(var1.rows, var1.cols, CV_8UC3, Scalar(0, 0, 0));
    for (int i = 0; i < var1.rows; i++)
    {
        var2.at<Vec3b>(i, 0) = var1.at<Vec3b>(i, 0);
        var2.at<Vec3b>(i, var1.cols - 1) = var1.at<Vec3b>(i, var1.cols - 1);

    }
    for (int i = 0; i < var1.cols; i++)
    {
        var2.at<Vec3b>(0, i) = var1.at<Vec3b>(0, i);
        var2.at<Vec3b>(var1.rows - 1, i) = var1.at<Vec3b>(var1.rows - 1, i);

    }
    for (int i = 0; i < var1.rows; i++) {
        for (int j = 0; j < var1.cols; j++)
        {
            c = 0;
            for (int m = i; m < var1.rows; m++, c++)
            {
                if (c < 3)
                {
                    d = 0;
                    for (int n = j; n < var1.cols; n++, d++)
                    {
                        if (d < 3)
                        {
                            if ((i + 1) < var1.rows && (j + 1) < var1.cols)
                            {
                                var2.at<Vec3b>(i + 1, j + 1)[0] += var1.at<Vec3b>(m, n)[0] * A[m - i][n - j] / 9;
                                var2.at<Vec3b>(i + 1, j + 1)[1] += var1.at<Vec3b>(m, n)[1] * A[m - i][n - j] / 9;
                                var2.at<Vec3b>(i + 1, j + 1)[2] += var1.at<Vec3b>(m, n)[2] * A[m - i][n - j] / 9;
                            }
                        }
                    }
                }
            }
        }
    }
    imshow("window1", var1);
    imshow("window2", var2);
    waitKey(0);
    return(0);
}

The part that I find difficult is understanding how to convert the innermost 2 loops, where the mean value is computed. Any help will be greatly appreciated.

A: Just for fun, I thought it might be interesting to start with a naive implementation of a 3x3 mean filter and then optimise this incrementally, ending up with a SIMD (SSE) implementation, measuring the throughput improvement at each stage.
1 - Mean_3_3_ref - reference implementation
This is just a simple scalar implementation which we'll use as a baseline for throughput and for validating further implementations:
void Mean_3_3_ref(const Mat &image_in, Mat &image_out)
{
    for (int y = 1; y < image_in.rows - 1; ++y)
    {
        for (int x = 1; x < image_in.cols - 1; ++x)
        {
            for (int c = 0; c < 3; ++c)
            {
                image_out.at<Vec3b>(y, x)[c] = (image_in.at<Vec3b>(y - 1, x - 1)[c] +
                                                image_in.at<Vec3b>(y - 1, x    )[c] +
                                                image_in.at<Vec3b>(y - 1, x + 1)[c] +
                                                image_in.at<Vec3b>(y    , x - 1)[c] +
                                                image_in.at<Vec3b>(y    , x    )[c] +
                                                image_in.at<Vec3b>(y    , x + 1)[c] +
                                                image_in.at<Vec3b>(y + 1, x - 1)[c] +
                                                image_in.at<Vec3b>(y + 1, x    )[c] +
                                                image_in.at<Vec3b>(y + 1, x + 1)[c] + 4) / 9;
            }
        }
    }
}

2 - Mean_3_3_scalar - somewhat optimised scalar implementation
Exploit the redundancy in summing successive columns - we save the last two column sums so that we only need to calculate one new column sum (per channel) on each iteration:
void Mean_3_3_scalar(const Mat &image_in, Mat &image_out)
{
    for (int y = 1; y < image_in.rows - 1; ++y)
    {
        int r_1, g_1, b_1;
        int r0, g0, b0;
        int r1, g1, b1;

        r_1 = g_1 = b_1 = 0;
        r0 = g0 = b0 = 0;

        for (int yy = y - 1; yy <= y + 1; ++yy)
        {
            r_1 += image_in.at<Vec3b>(yy, 0)[0];
            g_1 += image_in.at<Vec3b>(yy, 0)[1];
            b_1 += image_in.at<Vec3b>(yy, 0)[2];
            r0 += image_in.at<Vec3b>(yy, 1)[0];
            g0 += image_in.at<Vec3b>(yy, 1)[1];
            b0 += image_in.at<Vec3b>(yy, 1)[2];
        }

        for (int x = 1; x < image_in.cols - 1; ++x)
        {
            r1 = g1 = b1 = 0;

            for (int yy = y - 1; yy <= y + 1; ++yy)
            {
                r1 += image_in.at<Vec3b>(yy, x + 1)[0];
                g1 += image_in.at<Vec3b>(yy, x + 1)[1];
                b1 += image_in.at<Vec3b>(yy, x + 1)[2];
            }

            image_out.at<Vec3b>(y, x)[0] = (r_1 + r0 + r1 + 4) / 9;
            image_out.at<Vec3b>(y, x)[1] = (g_1 + g0 + g1 + 4) / 9;
            image_out.at<Vec3b>(y, x)[2] = (b_1 + b0 + b1 + 4) / 9;

            r_1 = r0;
            g_1 = g0;
            b_1 = b0;
            r0 = r1;
            g0 = g1;
            b0 = b1;
        }
    }
}

3 - Mean_3_3_scalar_opt - further optimised scalar implementation
As per Mean_3_3_scalar, but also remove OpenCV overheads by caching pointers to each row that we are working on:
void Mean_3_3_scalar_opt(const Mat &image_in, Mat &image_out)
{
    for (int y = 1; y < image_in.rows - 1; ++y)
    {
        const uint8_t * const input_1 = image_in.ptr(y - 1);
        const uint8_t * const input0 = image_in.ptr(y);
        const uint8_t * const input1 = image_in.ptr(y + 1);
        uint8_t * const output = image_out.ptr(y);

        int r_1 = input_1[0] + input0[0] + input1[0];
        int g_1 = input_1[1] + input0[1] + input1[1];
        int b_1 = input_1[2] + input0[2] + input1[2];
        int r0 = input_1[3] + input0[3] + input1[3];
        int g0 = input_1[4] + input0[4] + input1[4];
        int b0 = input_1[5] + input0[5] + input1[5];

        for (int x = 1; x < image_in.cols - 1; ++x)
        {
            int r1 = input_1[x * 3 + 3] + input0[x * 3 + 3] + input1[x * 3 + 3];
            int g1 = input_1[x * 3 + 4] + input0[x * 3 + 4] + input1[x * 3 + 4];
            int b1 = input_1[x * 3 + 5] + input0[x * 3 + 5] + input1[x * 3 + 5];

            output[x * 3    ] = (r_1 + r0 + r1 + 4) / 9;
            output[x * 3 + 1] = (g_1 + g0 + g1 + 4) / 9;
            output[x * 3 + 2] = (b_1 + b0 + b1 + 4) / 9;

            r_1 = r0;
            g_1 = g0;
            b_1 = b0;
            r0 = r1;
            g0 = g1;
            b0 = b1;
        }
    }
}

4 - Mean_3_3_blur - leverage OpenCV's blur function
OpenCV has a function called blur, which is based on the function boxFilter, which is just another name for a mean filter. Since OpenCV code has been quite heavily optimised over the years (using SIMD in many cases), let's see if this makes a big improvement over our scalar code:
void Mean_3_3_blur(const Mat &image_in, Mat &image_out)
{
    blur(image_in, image_out, Size(3, 3));
}

5 - Mean_3_3_SSE - SSE implementation
This a reasonably efficient SIMD implementation. It uses the same techniques as the scalar code above in order to eliminate redundancy in processing successive pixels:
#include <tmmintrin.h>  // Note: requires SSSE3 (aka MNI)

inline void Load2(const ssize_t offset, const uint8_t* const src, __m128i& vh, __m128i& vl)
{
    const __m128i v = _mm_loadu_si128((__m128i *)(src + offset));
    vh = _mm_unpacklo_epi8(v, _mm_setzero_si128());
    vl = _mm_unpackhi_epi8(v, _mm_setzero_si128());
}

inline void Store2(const ssize_t offset, uint8_t* const dest, const __m128i vh, const __m128i vl)
{
    __m128i v = _mm_packus_epi16(vh, vl);
    _mm_storeu_si128((__m128i *)(dest + offset), v);
}

template <int SHIFT> __m128i ShiftL(const __m128i v0, const __m128i v1) { return _mm_alignr_epi8(v1, v0, SHIFT * sizeof(short)); }
template <int SHIFT> __m128i ShiftR(const __m128i v0, const __m128i v1) { return _mm_alignr_epi8(v1, v0, 16 - SHIFT * sizeof(short)); }

template <int CHANNELS> void Mean_3_3_SSE_Impl(const Mat &image_in, Mat &image_out)
{
    const int nx = image_in.cols;
    const int ny = image_in.rows;
    const int kx = 3 / 2;                               // x, y borders
    const int ky = 3 / 2;
    const int kScale = 3 * 3;                           // scale factor = total number of pixels in sum
    const __m128i vkScale = _mm_set1_epi16((32768 + kScale / 2) / kScale);
    const int nx0 = ((nx + kx) * CHANNELS + 15) & ~15;  // round up total width to multiple of 16
    int x, y;

    for (y = ky; y < ny - ky; ++y)
    {
        const uint8_t * const input_1 = image_in.ptr(y - 1);
        const uint8_t * const input0 = image_in.ptr(y);
        const uint8_t * const input1 = image_in.ptr(y + 1);
        uint8_t * const output = image_out.ptr(y);

        __m128i vsuml_1, vsumh0, vsuml0;
        __m128i vh, vl;

        vsuml_1 = _mm_set1_epi16(0);

        Load2(0, input_1, vsumh0, vsuml0);
        Load2(0, input0, vh, vl);
        vsumh0 = _mm_add_epi16(vsumh0, vh);
        vsuml0 = _mm_add_epi16(vsuml0, vl);
        Load2(0, input1, vh, vl);
        vsumh0 = _mm_add_epi16(vsumh0, vh);
        vsuml0 = _mm_add_epi16(vsuml0, vl);

        for (x = 0; x < nx0; x += 16)
        {
            __m128i vsumh1, vsuml1, vsumh, vsuml;

            Load2((x + 16), input_1, vsumh1, vsuml1);
            Load2((x + 16), input0, vh, vl);
            vsumh1 = _mm_add_epi16(vsumh1, vh);
            vsuml1 = _mm_add_epi16(vsuml1, vl);
            Load2((x + 16), input1, vh, vl);
            vsumh1 = _mm_add_epi16(vsumh1, vh);
            vsuml1 = _mm_add_epi16(vsuml1, vl);

            vsumh = _mm_add_epi16(vsumh0, ShiftR<CHANNELS>(vsuml_1, vsumh0));
            vsuml = _mm_add_epi16(vsuml0, ShiftR<CHANNELS>(vsumh0, vsuml0));
            vsumh = _mm_add_epi16(vsumh, ShiftL<CHANNELS>(vsumh0, vsuml0));
            vsuml = _mm_add_epi16(vsuml, ShiftL<CHANNELS>(vsuml0, vsumh1));

            // round mean
            vsumh = _mm_mulhrs_epi16(vsumh, vkScale);
            vsuml = _mm_mulhrs_epi16(vsuml, vkScale);

            Store2(x, output, vsumh, vsuml);

            vsuml_1 = vsuml0;
            vsumh0 = vsumh1;
            vsuml0 = vsuml1;
        }
    }
}

void Mean_3_3_SSE(const Mat &image_in, Mat &image_out)
{
    const int channels = image_in.channels();

    switch (channels)
    {
        case 1:
            Mean_3_3_SSE_Impl<1>(image_in, image_out);
            break;
        case 3:
            Mean_3_3_SSE_Impl<3>(image_in, image_out);
            break;
        default:
            throw("Unsupported format.");
            break;
    }
}

Results
I benchmarked all of the above implementations on an 8th gen Core i9 (MacBook Pro 16,1) at 2.4 GHz, with an image size of 2337 rows x 3180 cols. The compiler was Apple clang version 12.0.5 (clang-1205.0.22.9) and the only optimisation switch was -O3. OpenCV version was 4.5.0 (via Homebrew). (Note: I verified that for Mean_3_3_blur the cv::blur function was dispatched to an AVX2 implementation.) The results:
Mean_3_3_ref         62153 µs
Mean_3_3_scalar      41144 µs =  1.51062x
Mean_3_3_scalar_opt  26238 µs =  2.36882x
Mean_3_3_blur        20121 µs =  3.08896x
Mean_3_3_SSE          4838 µs = 12.84680x

Notes

*

*I have ignored the border pixels in all implementations - if required these can either be filled with pixels from the original image or using some other form of edge pixel processing.

*The code is not "industrial strength" - it was only written for benchmarking purposes.

*There are a few further possible optimisations, e.g. use wider SIMD (AVX2, AVX512), exploit the redundancy between successive rows, etc - these are left as an exercise for the reader.

*The SSE implementation is fastest, but this comes at the cost of increased complexity, decreased mantainability and reduced portability.

*The OpenCV blur function gives the second best performance, and should probably be the preferred solution if it meets throughput requirements - it's the simplest solution, and simple is good.


text:
Q: Migrate local timezone dates into new Rails application I am migrating a Perl-based web application to Rails. The old application stores dates in a MySql database in local (Pacific) time. For example, there is a created field that might have the value 06/06/2008 14:00:00 representing 2:00 PM June 6, 2008 (PDT) whereas 02/02/2002 06:30:00 represents 6:00 AM February 2, 2002 (PST).
I have written a rake task to take all the old data and import it into the new database. The date in the new database still looks like 06/06/2008 14:00:00 but, of course, my Rails application interprets this as UTC.
The migrating task looks like this:
# Migrating old events in Perl application to new events in Rails
oldevents = OldEvent.all
oldevents.each do |oldevent|
  newevent = Event.convert_old_event_to_newevent(oldevent)
  newevent.save!
end

The interesting code is in the static method Event.convert_old_event_to_newevent:
def Event.convert_old_event_to_newevent(oldevent)
  ...
  # If the "created" field in the old db contains '06/06/2008 14:00:00' (meaning
  # 2:00 PM PDT (since June is during daylight savings time) then the
  # "created_at" field in the new database will contain the same string which
  # Rails interprets as 2:00 PM GMT.
  newevent.created_at = oldevent.created
  ...
  return newevent
end

So, in the migration process, before storing the dates in the new database I need to read the date/times from the old database, convert them to UTC, and then store that in the new database.
How can that be done?

A: >> Time.local(*'06/06/2008 14:00:00'.split(/[:\/ ]/).values_at(2,0,1,3..5)).utc
=> Fri Jun 06 21:00:00 UTC 2008

This obviously returns a Ruby core library Time object that can be formatted any way you like.
If your time zone is not already Pacific, run your rake import task like:
$ TZ=PST rake initdb:import # whatever

Now, Rails defines a type called DateTime which you may need, and it wants real integer parameters, so:
DateTime.civil_from_format :local, *'06/06/2008 14:00:00'.split(/[:\/ ]/).map(&:to_i).values_at(2,0,1,3..5)


text:
Q: Excel VBA - Getting values from dynamic array - does not show real number Here is some code which shows the problem I am having:
Sub main()
    Dim V() As Long, x As Integer, temp As Long

    x = 5

    ReDim V(1 To x)

    V(4) = 0.65
    temp = V(4)

    MsgBox (temp) ' Returns value of 1
End Sub

I would like the variable temp to take in value: 0.65, but it always shows a value of 1. I am not sure what I am missing. Any help is greatly appreciated.

A: You have declared Dim V() As Long. This means it takes in only integers. Change it to Double.

A: temp & V are Long integers so cannot represent floating point numbers like 0.65, simply change their type to Double which can.


text:
Q: hook a functions to change wp-config from functions.php is there a way to hook / filter or add action that would be printed in the wp-config file? lets say i want to add some simple command like "empty the trash" aka
define('EMPTY_TRASH_DAYS', 1 );

This should be changes in the wp-config but i want it to go with theme..
Any way to do that?

A: You can just redefine it in your functions.php file (call define with the key/value you want).  Since it loads later, it's going to be replaced with your value.  I just tried this with a plugin, it generated some unexpected output errors, but it worked.
That said, if this is a theme for public consumption, it is definitely not your job to change site wide configuration options without consulting your users.  If it's for a client, you should be able to edit their wp-config directly.
You're better off to use xref (or something like ack-grep) to search for where the constant is used and how.  Are there hooks in those functions/whatever that you could used to accomplish the same thing as redefining the variable?

A: There is, as far as I know, no way to hook into wp-config.php from a Theme. For one, wp-config.php shouldn't be writeable; for another, wp-config.php is executed well-before a Theme's functions.php file is parsed. For a great overview of how WordPress boots, have a look at this two-part post by Theme.FM (part 1, part 2) or this Explanation with a flowchart by @Rarst.
You might want to look into removing the define() from wp-config.php, and moving it into the Theme? I'll have to look to see where it gets used, but there's a good chance that WordPress won't have looked for it before functions.php gets parsed.
EDIT
As per @ChristopherDavis' comment below, EMPTY_TRASH_DAYS gets defined at wp-settings.php, via default-constants.php. So, you have to define it in wp-config.php, if you want to override the default.
p.s. why would you want to define the number of trash days in a Theme, anyway?


text:
Q: write a program to test numbers whether its prime or perfect public class assignmentno7
{
    public static void main(String[] args)
    {
        long i,c1=1,n;
        for(n=1;n<20;n++)
        {
            for(i=1;i<(n+1);i++)
                if(n%i==0)
                    c1+=i;
            if(c1==1)
                System.out.println(n+"is prime");
            else if(c1==n)
                System.out.println(n+"is perfect");
            else
                System.out.println(n+"its a regular number");
        }
    }
}

I want to write a program that test number whether its prime or perfect
I have no errors is my program
but im not getting the right solutions
this is my output :
----jGRASP exec: java assignmentno7

1its a regular number
2its a regular number
3its a regular number
4its a regular number
5its a regular number
6its a regular number
7its a regular number
8its a regular number
9its a regular number
10its a regular number
11its a regular number
12its a regular number
13its a regular number
14its a regular number
15its a regular number
16its a regular number
17its a regular number
18its a regular number
19its a regular number

 ----jGRASP: operation complete.

any suggestions ?

A: You are getting this because c1 becomes 2 on your first loop and increases from there.  You never have a case where c is less than 1.
Reconsider how you are tracking if a number is prime or not.

A: I would suggest your real problem here is not the domain problem at hand, but an lack of understanding about how to discern what your code is actually doing. You're not going to get anywhere if you look at the output, see that it's not correct, and go straight to Stackoverflow for help.
A couple of suggestions.

*

*Add System.out.println calls to your code so that you can watch it execute. This is a primitive form of "logging", and it's alright to start out without a full blown framework like log4j.

*Turn on your debugger. Your jgrasp IDE has a debugger built in so that you can watch the code values as it executes. http://www.jgrasp.org/tutorials187/06_Debugger.pdf

*Write out an example number that should be prime, and then trace through your code with pencil and paper to find the solution.

A:
any suggestions ?

Yea.  Check the definition of a prime number ... and compare it to what your inner loop is actually doing.
And if that isn't sufficient, ask yourself what the value of N % 1 is, for any N greater or equal to zero.

A: The problem stems from 'c1' never being 'c1 == 1' or 'c1 == n'. It seems you've forgotten to wrap your second loop in brackets. This could be the issue because you're trying to increment 'c1' n times before checking it.
Then try to 'println(c1)' to see what's going on with it during your loop.


text:
Q: Which database should I use for my flutter app using lots of images? I want to build a flutter app which focuses on learning plant names with the help of a lot of pictures. In total there will be 600-800 pictures.

*

*question: Do I store these pictures all in the app or in a database?

From what I read so far I guess the app would be too big if I store all these pictures in the app.

*question: Which database should I use for storing such an amount of pictures?

I want to give the possibility to store a lection/course (containing 30-40 pictures) locally on the phone to be able to learn without internet connection.

*question: Which database should I use for that?

A:
Question #1: Do I store these pictures all in the app or in a
database?

You should not store all the images in your app. Use the Cloud Storage for Firebase service to store your pictures and download them to your app as desired.

Question #2: Which database should I use for storing such an amount of pictures?

You should use Cloud Storage for Firebase to store your pictures: "Cloud Storage for Firebase is built for app developers who need to store and serve user-generated content, such as photos or videos."

Question #3: I want to give the possibility to store a section/course (containing 30-40 pictures) locally on the phone to be
able to learn without internet connection. Which database should I use
for that?

You can save these pictures locally as explained here in the Firebase doc: "The writeToFile() method downloads a file directly to a local device. Use this if your users want to have access to the file while offline."

A: *

*If in a database, get pic to many times, and much more than the free limit of database , we will prefer pic in app than in database.
But in app will never consider the cost, just keep the develop account. Maybe, a pic could compress down to 50kb each, and the app will not too big to download.

*mongodb google-could amazon ... all database on the market can serve you.

*above dbs are good. the more resourses on net, the better envirnment we like.


text:
Q: Efficient group substring search in Python? Lets say I've loaded some information from a file into a Python3 dict and the result looks like this.
d = {
    'hello' : ['hello', 'hi', 'greetings'],
    'goodbye': ['bye', 'goodbye', 'adios'],
    'lolwut': ['++$(@$(@%$(@#*', 'ASDF #!@# TOW']
}

Let's say I'm going to analyze a bunch, I mean an absolute ton, of strings. If a string contains any of the values for a given key of d, then I want to categorize it as being in that key.
For example...
'My name is DDP, greetings' => 'hello'

Obviously I can loop through the keys and values like this...
def classify(s, d):
    for k, v in d.items():
        if any([x in s for x in v]):
            return k

    return ''

But I want to know if there's a more efficient algorithm for this kind of bulk searching; more efficient than my naive loop. Is anyone aware of such an algorithm?

A: You can use regex to avoid extra operations. Here all you need is to join the words with a pip character and pass it to re.search(). Since the order or the exact word is not important to you this way you can find out if there's any intersection between any of those values and the given string.
import re

def classify(s, d):
    for k, v in d.items():
        regex = re.compile(re.escape(r'|'.join(v)))
        if regex.search(s):
            return k

Also note that you can, instead of returning k yield it to get an iterator of all occurrences or use a dictionary to store them, etc.


text:
Q: AJAX GET request successful; Django View updated but HTML does not get updated This has completely stumped me and I have stared at the screen for a long time now.
It is about a mail app that I am trying to develop. I have an HTML page that is divided in three parts. Left side has the ability to check/uncheck folders from which to view emails. Middle page "should" show all the mails (depending upon what is selected on the left column). The right most column is expanded view of individual mail in the middle.
I added AJAX GET request feature to pass to view which folders have been selected or unselected. The view gets the AJAX request all right (in the code below I print out args and it is right what I want it to be). However the HTML page/template never responds to the changing args!! I don't know why? Please help me locate the bug in my program.
urls.py
from django.conf.urls import url
from . import views

app_name="Home"
urlpatterns = [
    url(r'^$', views.Home_View.as_view(),name="Home"),
    url(r'^RightBody/$', views.RightBody, name="RightBody"),
    url(r'^RulePopUp/$', views.RulePopUp_View.as_view(), name="RulePopUp"),
    ]

views.py
class Home_View(View):

    def get(self, request):
        ExcludedFolder = request.GET.getlist('UncheckedFolder[]')
        LeftSide_FolderHandle = FolderTree("/SomePath/")
        LeftSide_Folder = LeftSide_FolderHandle.CreateFolderNames()
        LeftSide_Folder = LeftSide_FolderHandle.MakeAJSONtree()
        CompleteMailBox_Handle = MailLogger("/SomePath/",FoldersToExclude=ExcludedFolder)
        CompleteMailBox = CompleteMailBox_Handle.RecreateMailBox()
        # RightMail = FullMailInTheRight()
        args = {"CompleteMailBox":CompleteMailBox,
                "LeftSide_FolderStructure":LeftSide_Folder}
        print(args) ##This works
        return render(request,'Home_Query.html',args)

Home_Query.html
<!DOCTYPE html>
{% load static %}

    <meta charset="utf-8">
    <title>Main Page</title>

    <link rel="stylesheet" href="{% static 'css/HomePageMain.css' %}" type="text/css">

 Mail checking app

      Select folders to display messages

{% include "Home_Query_LeftSide.html" with LeftSide_FolderStructure=LeftSide_FolderStructure %}

      Select Message to show complete mail on the right

      {% for eachMail in CompleteMailBox %}

             Sender:  {{eachMail.0.Sender}}, Time:  {{eachMail.0.Time}}

            Subject:  {{eachMail.0.Subject}}

             Mail: {{eachMail.1}}

Click here for rules

    {% endfor %}

      This column shows the complete email when selected in the middle column

main.js
var Unchecked = [];

$(function () {
    $("input:checkbox").click(function(){
      $(this).parent().find("input[type='checkbox']").prop('checked',$(this).is(':checked'));
      if ($(".left-column").find("input:checkbox:not(:checked)").length != 0){
        var UncheckedFolder = "";
        $(this).parent().find("input:checkbox:not(:checked)").each(function(){
          UncheckedFolder += "/"+String($(this).prop("id"));
        });
        if ($.inArray(UncheckedFolder, Unchecked) === -1) {Unchecked.push(UncheckedFolder)}
        var CheckedFolder = "";
        $(this).parent().find("input:checkbox:checked").each(function(){
          CheckedFolder += "/"+String($(this).prop("id"));
        });
        if ($.inArray(CheckedFolder, Unchecked) != -1) {Unchecked.splice($.inArray(CheckedFolder,Unchecked),1);}
        UncheckedFolder = "";
      }
      else {
        Unchecked = [];
      }
      console.log(Unchecked);
      $.ajax({
        type: 'get',
        url: "/Home/",
        datatype: "json",
        data: {
          'UncheckedFolder':Unchecked,
        },
        success: PrintMessage,
      });
    });
});

function PrintMessage(data,textStatus,jqXHR){
  console.log("Success To Exclude");
}

Many thanks!

A: You are close. Return a JsonResponse instead of render:
from django.http import JsonResponse

class Home_View(View):

    def get(self, request):
        ...
        print(args) ##This works
        return JsonResponse(args)

The javascript call is expecting a response in json format. With render you are returning an HTML template.


text:
Q: C pipe: Bad file descriptor I have the simple producer consumer program in C try to solve it with fork
I get error exactly when producer tries to write on pipe:
I have wrote another program with the same logic but this one does not give me any clue to know why?
Producer failed to write item on pipe: Bad file descriptor
Anyone have idea why I get this error?
Thanks
#define READ 0
#define WRITE 1
int mutex = 1, full = 0, empty = BUFFER_SIZE, x = 0;

void consumer();

void producer();

int wait_(int);

int signal_(int);

int pipefd[2];

int main() {
    printf("Starting producer-consumer problem!\n");
    //We intend to run the producer in parent process and the consumer in the child process
    if (pipe(pipefd) == -1) {       /* An error has occurred. */
        fprintf(stderr, "%s", "The call to pipe() has failed.\n");
        exit(EXIT_FAILURE);
    }
    for (int j = 0; j < sizeof(pipefd); j++) {
        if (pipe(&pipefd[j]) < 0) { //Initialize each pipe appropriately
            perror("Error in making pipe...");
        }
    }
    pid_t pid = fork();
    if (pid < 0) {
        perror("**********Error in creating fork()!**************\n");
        exit(STDERR_FILENO);
    } else if (pid == 0) {
        consumer();//We intend to run the consumer in child
    } else {
        producer();//We intend to run the producer in parent
    }
    return 0;
}

int wait_(int s) {
    return (--s);
}

int signal_(int s) {
    return (++s);
}

void producer() {
    printf("Starting Producer\n");
    //while (1) {
    //sleep(1);
    if (close(pipefd[READ]) != 0) {
        perror("Error in closing reading pipe");
    }
    if (write(pipefd[WRITE], &full, 1) < 0) {
        perror("Producer failed to write item on pipe");
    }
    if ((mutex == 1) && (empty != 0)) {
        mutex = wait_(mutex);
        full = signal_(full);
        empty = wait_(empty);
        x++;
        printf("Producer produces the item %d\n", x);
        mutex = signal_(mutex);
    }
    if (close(pipefd[WRITE]) != 0) {
        perror("Error in closing writing pipe");
    }
    //}
}

void consumer() {
    printf("Starting Consumer\n");
    //while (1) {
    //sleep(1);
    int status = 0;
    wait(&status);              /* wait for all children to return back the result */
    if (close(pipefd[WRITE]) != 0) {
        perror("Error in closing reading pipe");
    }
    if (read(pipefd[READ], &full, 1) > 0) {
        printf("Consumer\t%d\n", full);
    }
    if ((mutex == 1) && (full != 0)) {
        mutex = wait_(mutex);
        full = wait_(full);
        empty = signal_(empty);
        printf("Consumer consumes item %d\n", x);
        x--;
        mutex = signal_(mutex);
    }
    if (close(pipefd[READ]) != 0) {
        perror("Error in closing reading pipe");
    }
    //}
}

A: The sizeof operator returns the size in bytes. So on a typical system where an int is four bytes, sizeof(pipefd) would result in the value 8. Which is not the correct number of elements for your loop.
Also, pipe(&pipefd[j]) is not correct either. The two pipes in pipefd are already initialized "appropriately". There's no need for any more initialization. Especially since in both this and the previous case you will have undefined behavior.


text:
Q: собрать данные из DIV в JSON Есть динамически сформированная корзина заказа (условно):

...

...

...

наименование_товар_1

количество_товар_1

цена_товар_1

...

...

...

Количество, тип и цена этих товаров заранее неизвестны.
Подскажите, как собрать все это в JSON для последующей передачи на email.
Предположение:
подсчитать количество дочерних элементов .bin_item: $(".bin_item").length, а затем обращаться к каждому .bin_item[] и собирать информацию о значениях в  по заранее известным class'ам тупо пихать в JSON-строку:
{товар:наименование_товар_1, количество:количество_товар_1, цена:цена_товар_1 },
{товар:наименование_товар_2, количество:количество_товар_2, цена:цена_товар_2 },
{товар:наименование_товар_3, количество:количество_товар_3, цена:цена_товар_3 }

Вопрос: как получить данные из .bin_item[1], а затем .bin_item[1].type ?
Или, очень может быть, есть другой способ решения этой задачи - пока я для себя определил только такой ...

A: Просто пробегаемся в цикле по всем bin_item. Так же не называйте классы с точкой иначе не сможете потом использовать в селекторе.

var data = [];

$('.bin_item').each(function() {
  $el = $(this);
  data.push({
    type: $el.find('.type').text(),
    count: $el.find('.count').text(),
    total_price: $el.find('.total_price').text(),
  })
});

console.log(data);

...

...

...

наименование_товар_1

количество_товар_1

цена_товар_1

...

...

...


text:
Q: MySQL - Find the largest time difference between consecutive datetimes I have a table that contains a list of datetimes.
I'd like to find the longest amount of time between consecutive datetimes ie., find the largest distance between any two datetime entries that fall next to each other on a timeline. Think about it like a "longest streak" - the longest time from one reset to the next one chronologically.
For exmaple:
mysql> select * from resets order by datetime asc;
+----+---------------------+-------------+---------------------+---------------------+
| id | datetime            | activity_id | created_at          | updated_at          |
+----+---------------------+-------------+---------------------+---------------------+
|  7 | 2014-12-30 20:38:22 |           1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 |
|  3 | 2014-12-31 20:38:22 |           1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 |
|  5 | 2015-01-01 20:38:22 |           1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 |
|  4 | 2015-01-02 20:38:22 |           1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 |
|  6 | 2015-01-03 20:38:22 |           1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 |
|  1 | 2015-01-04 20:38:22 |           1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 |
|  2 | 2015-01-05 20:38:22 |           1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 |

 etc...

From the sample dataset above, I want to know which of the following time differences is greater:

*

*between rows 7 and 3

*between rows 3 and 5

*between rows 5 and 4

*etc...

(Obviously, they are all exactly 24 hours apart. I'm looking for a general solution.)
This is easily done with a normal programming language by iterating over the ordered array, storing the differences between consecutive values, and selecting the greatest one.
Is there a neat way to do this using only SQL?
Update:
The query that worked for me was
SELECT MAX(DATEDIFF(r.next_datetime, r.datetime))
    FROM (

    # finds each datetime and the next consecutive one in the table
    SELECT r1.datetime as datetime, (

        # finds the next consecutive datetime
        SELECT datetime
        FROM resets r2
        WHERE r2.datetime > r1.datetime
        ORDER BY datetime ASC
        LIMIT 1
    ) as next_datetime

    FROM resets as r1
    ORDER BY r1.datetime

) as r;

The innermost query SELECT datetime FROM resets r2... is responsible for finding the next datetime in the list that's greater than the current one. Notice that this query is ordered and has a limit of 1. This was the toughest part for me.
The rest is pretty straightforward. For each row in the table, we select the datetime value and the next consecutive datetime in the table. The outermost query finds the greatest difference between any of the datetime pairs we just created - the "winning streak".
I chose the answer that @OllieJones gave because it was the neatest and best explained, even if I prefer the "pure SQL" solution.

A: This query will compute time differences between successive rows and display the largest one -- the length of the winning streak. If you need the whole row, you'll need Gordon's query.
SELECT MAX(diff)
  FROM (
          SELECT TIMEDIFF(datetime,@prev) AS diff,
                 (@prev:=datetime) AS datetime
            FROM resets,
                 (SELECT @prev:=(SELECT MIN(datetime) FROM resets)) AS init
           ORDER BY datetime
       ) AS diffs

How does this work?
First of all, it's a cross-join between a one-row query and your table. The one-row query is this:
       (SELECT @prev:=(SELECT MIN(datetime) FROM resets))

It sets the user-defined value @prev to the lowest/earliest datetime in the table.  This is a MySQL trick to initialize a user-defined variable at the beginning of the query.
Then, the SELECT clause has two columns in it:
          SELECT TIMEDIFF(datetime,@prev) AS diff,
                 (@prev:=datetime) AS datetime

The first one takes the time difference between the present row's datetime and the value of @prev.  The second one updates the value of @prev to the present row's datetime.
So the inner query spits out a list of the timestamps and the difference to the preceding timestamp in ORDER BY datetime.
The outer query SELECT MAX(diff) grabs the largest value of diff -- the longest winning streak -- from the inner query.
Let's be clear: This is MySQL-specific monkey business. Pure SQL is supposed to be declarative, not procedural. But this trick with the user-defined @prev variable lets us mix declarative and procedural code in a useful way, even if it's somewhat obscure.

A: You can calculate the next datetime using a correlated subquery and then find the biggest by sorting:
select r.*
from (select r.*,
             (select datetime
              from resets r2
              where r2.datetime > r.datetime
              order by datetime
              limit 1
             ) as next_datetime
      from resets r
     ) r
order by timestampdiff(second, datetime, next_datetime) desc
limit 1;

A: Unfortunately MySQL doesn't support lag to get the previous row's datetime but you can emulate it using variables.
select max(timediff(datetime,prevDate)) from (
    select *, @prevDate prevDate, @prevDate := datetime
    from resets
    order by datetime
) t1

or if you want to select the whole row
select * from (
    select *, @prevDate prevDate, @prevDate := datetime
    from resets
    order by datetime
) t1 order by timediff(datetime,prevDate) desc limit 1


text:
Q: OrientDB compatibility with Java17 We are using OrientDB 3.0.10 version and we are planning to migrate our application from Java11 to Java17. But application is stopped working due to OrientDB exception. On the latest version of OrientDB also same issue exists.
    22-Mar-2022 12:35:15.140 ERROR [Catalina-utility-1] o.a.catalina.core.StandardContext.listenerStart - Exception sending context initialized event to listener instance of class [com.progress.fathom.servlet.FathomContextInitializer]
java.lang.ExceptionInInitializerError: null
    at javassist.util.proxy.DefineClassHelper.<clinit>(DefineClassHelper.java:216)
    at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:128)
    at javassist.util.proxy.ProxyFactory.createClass3(ProxyFactory.java:552)
    at javassist.util.proxy.ProxyFactory.createClass2(ProxyFactory.java:537)
    at javassist.util.proxy.ProxyFactory.createClass1(ProxyFactory.java:473)
    at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:444)
    at com.orientechnologies.orient.object.enhancement.OObjectEntityEnhancer.getProxiedInstance(OObjectEntityEnhancer.java:97)
    at com.orientechnologies.orient.object.db.OObjectDatabaseTx.newInstance(OObjectDatabaseTx.java:211)
    at com.orientechnologies.orient.object.db.OObjectDatabaseTx.newInstance(OObjectDatabaseTx.java:115)
    at com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer.serializeObject(OObjectEntitySerializer.java:146)
    at com.orientechnologies.orient.object.db.OObjectDatabaseTx.save(OObjectDatabaseTx.java:499)
    at com.orientechnologies.orient.object.db.OObjectDatabaseTx.save(OObjectDatabaseTx.java:444)
    at com.progress.isq.ipqos.AbstractDatabase.updateDatabaseSchemaVersion(AbstractDatabase.java:455)
    at com.progress.isq.ipqos.AbstractDatabase.checkAndUpdateSchema(AbstractDatabase.java:481)
    at com.progress.isq.ipqos.AbstractDatabase.applySchema(AbstractDatabase.java:399)
    at com.progress.isq.ipqos.AbstractDatabase.openDatabase(AbstractDatabase.java:374)
    at com.progress.isq.ipqos.AbstractDatabase.open(AbstractDatabase.java:296)
    at com.progress.isq.ipqos.Probe.loadProject(Probe.java:1817)
    at com.progress.isq.ipqos.Probe.loadAndInitializeProjectResources(Probe.java:1195)
    at com.progress.isq.ipqos.Probe.createAndInitializeBaselineResources(Probe.java:678)
    at com.progress.isq.ipqos.Probe.start(Probe.java:391)
    at com.progress.fathom.servlet.FathomContextInitializer.contextInitialized(FathomContextInitializer.java:298)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4768)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5230)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:698)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:696)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1024)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1911)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:123)
    at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:825)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:475)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1618)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:319)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
    at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:423)
    at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:366)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:946)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @46762e3e
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
    at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:199)
    at java.base/java.lang.reflect.Method.setAccessible(Method.java:193)
    at javassist.util.proxy.SecurityActions$3.run(SecurityActions.java:94)
    at javassist.util.proxy.SecurityActions$3.run(SecurityActions.java:90)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:569)
    at javassist.util.proxy.SecurityActions.getMethodHandle(SecurityActions.java:89)
    at javassist.util.proxy.DefineClassHelper$SecuredPrivileged$2.getDefineClassMethodHandle(DefineClassHelper.java:143)
    at javassist.util.proxy.DefineClassHelper$SecuredPrivileged$2.<init>(DefineClassHelper.java:136)
    at javassist.util.proxy.DefineClassHelper$SecuredPrivileged.<clinit>(DefineClassHelper.java:134)
    ... 52 common frames omitted

To fix this we have added --add-opens=java.base/java.lang=ALL-UNNAMED to our application as mitigation but we know that this is not the valid fix for the issue. OrientDB needs to come up with a fix i think.
Another thing is OrientDB already added other java packages to Add-Opens in orient jar manifest file
Manifest-Version: 1.0
Implementation-Title: OrientDB Object
Implementation-Version: 3.2.5
Built-By: tglman
Specification-Vendor: Orient Technologies
Specification-Title: OrientDB Object
Implementation-Vendor-Id: com.orientechnologies
Implementation-Vendor: Orient Technologies
Implementation-Build-Date: 2022-02-14 18:19:43+0000
Add-Opens: jdk.unsupported/sun.misc=ALL-UNNAMED java.base/sun.security
 .x509=ALL-UNNAMED
X-Compile-Target-JDK: 8
Implementation-Build: c4298657c01683192ba0b7bfffdf82226c164506
X-Compile-Source-JDK: 8
Created-By: Apache Maven 3.6.3
Build-Jdk: 1.8.0_312
Specification-Version: 3.2
Implementation-URL: http://www.orientechnologies.com

Is OrientDB officially supporting Java17 and is there any plan to fix this issue?


text:
Q: Can a 3rd party js script write cookies? Is it possible for a 3rd party script to write cookies to the user's computer?
For example, if affiliate.example.org includes:
<script type="text/javascript" src="http://me.example.com/cookiemonster.js"></script>

I want to provide an affiliate with a script, to hopefully write a cookie on their clients' machines; ideally we would want to control the script ourselves. However, before trying this, I just thought I would see if it is even possible.
Of course, the other option would be for us to provide the actual script for the affiliate to put directly onto their site.

A: Yes, third party scripts can write cookies, and they will appear to belong to the domain of the page itself.
You can see this if you examine the cookies of any site using Google Analytics - the content comes from a third party (Google) but the _utm prefix cookies will be on the hosting site's domain.
To write third-party cookies (i.e. where the cookie is on the domain of the third party) requires that the cookies be sent in the headers of a download from that third party, and not written by JS code.

A: What happenned when you tested it?
(yes, if the browser/user permits, it will record a cookie - but the domain of the cookie is determined by the domain the script was loaded from).


text:
Q: Merged code from repo not updating in production server after push I have a post-receive hook in my server.
I also have a remote repo(origin) (branch:stage) where another developer pushes to.
I pull the commits and push them to production from my local computer.
I recently created a new branch(feature) from the latest head of the existing branch(stage), added some code and pushed the feature branch to remote repo. I merged the new features from feature branch to stage branch.
Then I pulled from the remote repo to local.
Now, I pushed the stage branch to production.
My post-receive file consists:
    git --work-tree=/path/to/project --git-dir=/path/to/project.git checkout -
    f stage

My head in the remote repo after merge is currently at ae228b9.
And, at the remote production hook's latest logs also points to ae228b9.
The problem is that the code from the merge are not seen in the production server.
Do I have to do something else to get the merged code to production?
After I pulled from origin and pushed to production, I tried changing the new files locally, committed them and push to the server. But, the changes are not reflected in the server.
Edit:
Also, I uninstalled apache php mysql and installed them again. Before the unistallation/installation, the home page was showing in server but the routes were not working(404 error) but the git hook was working. After the unistallation/installation, the git hook stopped working
Update:
I created a new hook with the same code as above. Now during the push I get:

remote: error: unable to unlink old '.gitignore' (Permission denied)
  remote: error: unable to unlink old '.htaccess' (Permission denied)
  remote: fatal: cannot create directory at '.idea': Permission denied

I tried the following code inside my project folder and project.git(hook) folder:
sudo chmod -R ug+w .;

unable to link
after which the push is a success but the changes are not reflecting.

A: I solved this by deleting the contents of the project folder and pushing again with some new changes.

A: I faced the same issue(Azure deployment)
There are two ways to ways to handle this -

*

*Increase timeout setting (but deployment may stuck some times)

*Push new changes (redeployment)

I prefer 2nd option.


text:
Q: Как сделать фильтр по свойствам и обработать на php Здравствуйте! не как не могу понят как сделать фильтр по свойствам в интернет магазине делаю так:
Размер
<input type="checkbox" name="value[20509][28315]" value="">
<input type="checkbox" name="value[20509][28316]" value="">

*

*[20509] = Размер [28315] = m

*[20509] = Размер [28316] = l

Стиль
    <input type="checkbox" name="value[412][800000067]" value="">
    <input type="checkbox" name="value[412][1000003]" value="">

*

*[412] = Стиль [28315] = Ретро

*[412] = Стиль [28316] = Случайный

как перебрать это что бы вышло так:
<Configurator Pid="20509" Vid="28315"/>
<Configurator Pid="20509" Vid="28316"/>
<Configurator Pid="412" Vid="800000067"/>
<Configurator Pid="412" Vid="1000003"/>

A: foreach ($_POST['value'] as $k => $v) {
    foreach ($v as $value) {
        echo '<Configurator Pid="' . $k . '" Vid="' . $v . '"/>';
    }
}


text:
Q: Initializing useState by modifying (mapping through) values of redux state I'm trying to initialize my state with the redux state that I have stored. However, when I try to map through one of the lists stored in the state it just resets the values that I have inside the list instead of returning their substring values (which I want). The thing is if I print mail.substring(0, mail.length -10) I see the value that I would like to assign to the variable but after assigning the value is empty.
Here comes the strange part: if I were to assign "hello" instead of mail.substring(0, mail.length-10) then it works which could make you assume that the substring would return an empty value but as I mentioned above it does not.
I guess this might be because I create a shallow copy of the redux state but I'm not sure. Could you help me resolve this, please?
const membershipData = useSelector(getCompanyMembershipDetails);

function getInitState() {
if (membershipData !== null && membershipData !== undefined) {
  const newState = { ...membershipData };
  newState.members.map((m) => {
    const mail = m.contact.countersignEmail;
    const newVal = mail.substring(0, mail.length - 10);
    m.contact.countersignEmail = newVal;
    return m;
  });
  return newState;
} else
  return {
    members: [getEmptyMemberStateForId(0), getEmptyMemberStateForId(1)],
    membershipRates: [
      getEmptyPropertyContributionForId(0),
      getEmptyPropertyContributionForId(1),
    ],
    registrationPermissions: [],
  };
}

const [membersData, setMembersData] = useState(getInitState());

A: It was because of the shallow copy as I thought. Using cloneDeep from lodash I made a working version:
const membershipData = useSelector(getCompanyMembershipDetails);

  function getInitState() {
    if (membershipData !== null && membershipData !== undefined) {
      const newState = _.cloneDeep(membershipData);
      newState.members.map((m) => {
        const mail = m.contact.countersignEmail;
        const newVal = mail.substring(0, mail.length - 10);
        m.contact.countersignEmail = newVal;
        return m;
      });
      return newState;
    } else
      return {
        members: [getEmptyMemberStateForId(0), getEmptyMemberStateForId(1)],
        membershipRates: [
          getEmptyPropertyContributionForId(0),
          getEmptyPropertyContributionForId(1),
        ],
        registrationPermissions: [],
      };
  }

  const [membersData, setMembersData] = useState(getInitState());

If you use lodash the way I did above make sure to import it the following way:
import _ from "lodash";


text:
Q: How can I import my Ubuntu terminal's color scheme for a different computers? I did a reinstall on my computer presently, and I want to restore my previous terminal settings. While exporting my settings, I ran the command
 gconftool-2 --dump '/apps/gnome-terminal' > gnome-terminal-conf.xml

Now running the following restore command on my Ubuntu 15.04 machine does nothing. Can anyone give me any pointers how to overcome this?
gconftool-2 --load terminal-color-scheme.xml

My gnome-terminal version is 3.14.2 and I am running zsh over it, using the very popular oh-my-zsh. Also, is there a tool that I can use to export and import without all this hassle in the future?


text:
Q: JDO Java Data Objects example can someone help me to find a step-by-step example for developing JDO in a gwt project?
I really want to know and learn the jdo and differences between that and jpa
RGDS

A: I have used both jdo and jpa. I find it much easier using jpa for my work. If you are using datanucleus then you should look at the documentation on app engine located below.
JDO
https://developers.google.com/appengine/docs/java/datastore/jdo/overview-dn2
JPA
https://developers.google.com/appengine/docs/java/datastore/jpa/overview-dn2
These are the newer specs for app engine and if you are not using these then just about any database should be fairly straight forward.
I personally use jpa, request factory, service locators and a Dao pattern for accessing my objects. Here is something I posted earlier that has some code samples that may help. If you are not using app engine then a normal Long key should be easier.
GAE Datastore with GWT, making more friendly/smaller keys
You should also look at using a Servlet Filter for handling your EntityManager so that requestfactory can handle fetching your object graph using the .with("childGetterMethod") clause. This will save you quite a bit of coding to fetch child entities while the servlet filter handles opening and closing your entity manager.


text:
Q: How do I test my team site before I share it? I might not be asking this correctly as I am still very new at SharePoint. I am trying to figure out if it is possible to view my team site as if I was a visitor? This way I can see exactly what they do? Also, I would be able to test all links etc. Am I completely missing this?
Thank you.

A: There isn't a built-in feature which would allow you to do so. For a developer, tester or an administrator it should be quite ideal to have a separate test account for purposes like this. Then it's only a matter of assigning the corresponding permission for this user.


text:
Q: As I see There isn't Any way to pass data from Activity to a BroadCastReceiver today I spent whole my time to find a way to pass some Integer data to my BroadCastReceiver from my MainActivity but I didn't find any way to do that and I'm totally depress, what I want to do is that I get some integer data like hour and minute and date from user and save them on SharedPreferences and til now all codes work right then I want to define a BroadCastreceiver for when the phone reboot this BroadCast  implements and get my data that I save on SharedPreferences
but I didn't find any way to do that!
I try all the way like using Intent or making constructor that didn't work because the BroadCast can not have a constructor
please help me if you know how can I do this?
below is my codes
Manifest codes:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example9.kavoshrayan.org.alarm">

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:name=".G"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Ring"></activity>

        <receiver android:name=".BroadCast">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

MainActivity codes:
 //In this Activity I define 3 button, one for set TimePicker and another one for
 //set DatePicker and the last one for Save data and pass them To My instance BroadCast
 //so that when phone reboot, data save on SharedPreferences in My instance BroadCast
 //and after the phone turned on the data set and alarm work
 public class MainActivity extends AppCompatActivity {
 Button setBtn, dateBtn, saveBtn;
 public int sec = 0;
 public int min = 16;
 public int hour = 3;
 public int year = 2018;
 public int month = 8;
 public int day = 26;
 PendingIntent pendingIntent;
 Intent intent;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     intent = new Intent(this, Ring.class);
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     pendingIntent = PendingIntent.getActivities(G.context, 0, new Intent[]  {intent}, PendingIntent.FLAG_UPDATE_CURRENT);
     setBtn = (Button) findViewById(R.id.setBtn);
     setBtn.setOnClickListener(new View.OnClickListener() {
         @Override
          public void onClick(View view) {
            TimePickerDialog dialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int Hour, int Min) {
                    hour = Hour;
                    min = Min;
                    Toast.makeText(MainActivity.this, Hour + " : " + Min + " : " + sec, Toast.LENGTH_SHORT).show();

                }
            }, 12, 0, true);
            dialog.show();
        }
    });
    dateBtn = (Button) findViewById(R.id.dateBtn);
    dateBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DatePickerDialog dialog1 = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int Year, int Month, int Day) {
                    year = Year;
                    month = Month;
                    day = Day;
                    Toast.makeText(MainActivity.this, Year + " / " + Month + " / " + Day, Toast.LENGTH_SHORT).show();

                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.HOUR, hour);
                    calendar.set(Calendar.MINUTE, min);
                    calendar.set(Calendar.SECOND, sec);
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, month);
                    calendar.set(Calendar.DAY_OF_MONTH, day);
                    Log.i("LOG", hour + " : " + min + " : " + sec + "\n" + year + "//" + month + "//" + day);
                    G.alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                }
            }, 2018, 6, 12);
            dialog1.show();
        }
    });

    saveBtn = (Button) findViewById(R.id.saveBtn);
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            passData();
        }
    });
}

public void passData() {
    Intent intent2 = new Intent(this, BroadCast.class);
    intent2.putExtra("HOUR", hour);
    intent2.putExtra("MIN", min);
    intent2.putExtra("YEAR", year);
    intent2.putExtra("MONTH", month);
    intent2.putExtra("DAY", day);
    sendBroadcast(intent2);
}

My G Application Class:
public class G extends Application {
    public static Context context;
    public static AlarmManager alarmManager;
    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    }
}

My Instance BroadCast codes:
public class BroadCast extends BroadcastReceiver {
PendingIntent pendingIntent;
SharedPreferences sharedPreferences;

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(G.context, "Reboot!", Toast.LENGTH_SHORT).show();
    Intent intent1 = new Intent(G.context, Ring.class);
    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    pendingIntent = PendingIntent.getActivities(G.context, 0, new Intent[]{intent1}, PendingIntent.FLAG_UPDATE_CURRENT);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(G.context);

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("HOUR", intent.getExtras().getInt("HOUR"));
    editor.putInt("MIN", intent.getExtras().getInt("MIN"));
    editor.putInt("YEAR", intent.getExtras().getInt("YEAR"));
    editor.putInt("MONTH", intent.getExtras().getInt("MONTH"));
    editor.putInt("DAY", intent.getExtras().getInt("DAY"));
    editor.commit();

//Here I log data and it works right and shows user's input data but after rebooring,
//Log shows 0 and alarm works a while after that
    Log.i("LOG1", sharedPreferences.getInt("HOUR", 0)
            + " : " + sharedPreferences.getInt("MIN", 0)
            + " : " + 0 + "\n" + sharedPreferences.getInt("YEAR", 0)
            + "." + sharedPreferences.getInt("MONTH", 0)
            + "." + sharedPreferences.getInt("DAY", 0));
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR, sharedPreferences.getInt("HOUR", 0));
    calendar.set(Calendar.MINUTE, sharedPreferences.getInt("MIN", 0));
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.YEAR, sharedPreferences.getInt("YEAR", 0));
    calendar.set(Calendar.MONTH, sharedPreferences.getInt("MONTH", 0));
    calendar.set(Calendar.DAY_OF_MONTH, sharedPreferences.getInt("DAY", 0));
    G.alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}

A: The onReceive of the broadcast receiver has Context object as parameter, You can use this to get your shared preference:
context.getSharedPreferences("MY_PREF",MODE_PRIVATE);

A: You can add extras to the Intent when you send the broadcast like:
Intent intent = new Intent(context,Receiver.class);
intent.putExtra("data",data);  //Here add your int as Extra
sendBroadcast(intent);

And then in your Receiver:
void onReceive(Context context, Intent intent){
    int data = intent.getIntExtra("data");  //Get the data from extras
}


text:
Q: Not able to create a table locally, getting Hive support is required Getting error even after setting configuration
config("spark.sql.catalogImplementation","hive")

override def beforeAll(): Unit = {
  super[SharedSparkContext].beforeAll()
  SparkSessionProvider._sparkSession = SparkSession.builder()
    .master("local[*]")
    .config("spark.sql.catalogImplementation","hive")
    .getOrCreate()
}

Edited:
This is how am setting up my local db and tables for testing.
val stgDb = "test_stagingDB"
val stgTbl_exp ="test_stagingDB_expected"
val stgTbl_result="test_stg_table_result"

val trgtDb = "test_activeDB"
val trgtTbl_exp ="test_activeDB_expected"
val trgtTbl_result ="test_activeDB_results"

def setUpDb ={
  println("Set up DB started")
  val localPath="file:/C:/Users/vmurthyms/Code-prdb/prdb/com.rxcorp.prdb"
  spark.sql(s"CREATE DATABASE IF NOT EXISTS test_stagingDB LOCATION '$localPath/test_stagingDB.db'")
  spark.sql(s"CREATE DATABASE IF NOT EXISTS test_activeDB LOCATION '$localPath/test_sctiveDB.db'")
  spark.sql(s"CREATE TABLE IF NOT EXISTS $trgtDb.${trgtTbl_exp}_ina (Id String, Name String)")
  println("Set up DB done")
}
setUpDb

While running spark.sql("CREATE TABLE.., ") cmd , am getting below error:
Error:
Hive support is required to CREATE Hive TABLE (AS SELECT);;
'CreateTable test_activeDB.test_activeDB_expected_ina, org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe, Ignore
org.apache.spark.sql.AnalysisException: Hive support is required to CREATE Hive TABLE (AS SELECT);;
'CreateTable test_activeDB.test_activeDB_expected_ina, org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe, Ignore
at org.apache.spark.sql.execution.datasources.HiveOnlyCheck$$anonfun$apply$12.apply(rules.scala:392)
at org.apache.spark.sql.execution.datasources.HiveOnlyCheck$$anonfun$apply$12.apply(rules.scala:390)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreach(TreeNode.scala:117)
at org.apache.spark.sql.execution.datasources.HiveOnlyCheck$.apply(rules.scala:390)
at org.apache.spark.sql.execution.datasources.HiveOnlyCheck$.apply(rules.scala:388)
at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$2.apply(CheckAnalysis.scala:349)
at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$2.apply(CheckAnalysis.scala:349)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$class.checkAnalysis(CheckAnalysis.scala:349)
at org.apache.spark.sql.catalyst.analysis.Analyzer.checkAnalysis(Analyzer.scala:92)
at org.apache.spark.sql.catalyst.analysis.Analyzer.executeAndCheck(Analyzer.scala:105)
at org.apache.spark.sql.execution.QueryExecution.analyzed$lzycompute(QueryExecution.scala:57)
at org.apache.spark.sql.execution.QueryExecution.analyzed(QueryExecution.scala:55)
at org.apache.spark.sql.execution.QueryExecution.assertAnalyzed(QueryExecution.scala:47)
at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:74)
at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:641)
at com.rxcorp.prdb.exe.SitecoreAPIExtractTest$$anonfun$2.setUpDb$1(SitecoreAPIExtractTest.scala:127)
at com.rxcorp.prdb.exe.SitecoreAPIExtractTest$$anonfun$2.apply$mcV$sp(SitecoreAPIExtractTest.scala:130)

A: It seems you are almost there(your error message is also giving you the clue), you need to call enableHiveSupport() when you are creating spark session. Eg.
SparkSession.builder()
         .master("local[*]")
         .config("spark.sql.catalogImplementation","hive")
         .enableHiveSupport()
         .getOrCreate()

And also when using enableHiveSupport(), setting config("spark.sql.catalogImplementation","hive") looks redundant. I think you can safely comment out that part.


text:
Q: The remote server returned an error: (401) Unauthorized - Provider hosted App I am trying to access an web application through provider hosted App. In the webapplication, at clientContext.ExecuteQuery(); I am getting 'The remote server returned an error: (401) Unauthorized'.
Following unxpected error is recorded in uls logs
SPApplicationAuthenticationModule: Failed to authenticate request, unknown error. Exception details: System.IdentityModel.Tokens.SecurityTokenException: The issuer claim of the user identity doesn't match the nameid (name identifier) claim of the delegated identity (actor identity). It is expected that these two claims match and hence this token is rejected.     at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityBaseTokenHandler.ValidateActorIsSelfIssuer(SecurityToken token, ClaimsIdentityCollection result)     at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityBaseTokenHandler.ValidateToken(SecurityToken token)     at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityTokenHandler.ValidateToken(SecurityToken token)     at Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule.TryExtractAndValidateToken(HttpContext httpContext, SPIncomingTokenContext& tokenContext)     at Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule.ConstructIClaimsPrincipalAndSetThreadIdentity(HttpApplication httpApplication, HttpContext httpContext, SPFederationAuthenticationModule fam)     at Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule.AuthenticateRequest(Object sender, EventArgs e)
Any help would be greatful.

A: I restarted my box & started the whole configuration again. This time it worked. Steps that are redone -

*

*Created new self signed certificate.

*Registered it with SharePoint using the following PS Commands

$publicCertPath = "c:\certificates\SampleCert.cer"
$issuerId = [System.Guid]::NewGuid().ToString()
$issuerId
$spurl ="http://hostname/sites/sitecoll"
$spweb = Get-SPWeb $spurl
$realm = Get-SPAuthenticationRealm -ServiceContext $spweb.Site
$certificate = ***New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($publicCertPath)***
New-SPTrustedRootAuthority -Name "SampleCert" -Certificate $certificate
$fullIssuerIdentifier = $issuerId + '@' + $realm
New-SPTrustedSecurityTokenIssuer -Name $issuerId -Certificate $certificate -RegisteredIssuerName $fullIssuerIdentifier -IsTrustBroker

*Used http://hostname/_layouts/15/appregnew.aspx to register the App with SharePoint

*Used the generated Appid as ClientId, AppSecret as ClientSecret and IssuerId from 2nd step.

I guess restarting the box has fixed my issue as I haven't done anthing different.
View at Microsoft Docs: https://docs.microsoft.com/pt-br/sharepoint/dev/sp-add-ins/create-high-trust-sharepoint-add-ins


text:
Q: C# WebClient DownloadString and DownloadFile giving different results I am attempting to retrieve some information from a website, parse out a specific item, and then move on with my life.
I noticed that when I check "view source" on the website, the results match with what I see when I use the WebClient class' method of DownloadFile. On the other hand, when I use the DownloadString method, the contents of that string are different from both view source and DownloadFile.
I need DownloadString to return similar contents to view source and DownloadFile. Any suggestions? My relevant code is below:
string criticalPathUrl = "http://blahblahblah&sessionId=" + sessionId;

WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;

//this is different
string urlContentsString = wc.DownloadString(criticalPathUrl);

//than this
wc.DownloadFile(criticalPathUrl, "rawDlTxt2.txt");

Edit: Please ignore this question as I just didn't scroll up far enough. Ugh. One of those days.

A: use download data instead of downloadstring and use suitable encoding  to convert the string then save the file!
watch details: https://www.pavey.me/2016/04/aspnet-c-downloadstring-vs-downloaddata.html


text:
Q: getting error when trying to use dolphin instead of Nautilus I am getting the following error while trying to use dolphin instead of Nautilus.
"Failed to execute child process "/usr/share/applications/kde4/dolphin.desktop" (Permission denied)"

I used the soultion of this to get Dolphin as the default file manager. Please guide me what next to do.
PS : tried to change permissions as well and it did not work.
Using Ubuntu 12.04

A: Although this is an old question, the same happened to me recently.
The solution I found:
On command line:
$exo-preferred-applications -c
In Preferred Applications dialog that opens:
Utilities tab --> File Manager
Change:
/usr/share/applications/kde4/dolphin.desktop"%s"
to just:
dolphin "%s"
An alternative solution may be to completely remove the exo-utils package
(Note: I am running KDE, but the Default Applications section in KDE System Settings had no effect (was already set to Dolphin). The application exo-preferred-applications appears to be from the xfce desktop environment.)


text:
Q: How to Fix Error In SQL Query Error
SQL query: Documentation
SELECT *
FROM tbl_vehicle_details
INNER JOIN tbl_user, tbl_ride
ON `tbl_vehicle_details`.`v_u_id` = `tbl_user`.`u_id` AND
   `tbl_ride`.`r_v_id` =`tbl_vehicle_details`.`v_id`
LIMIT 0, 25

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
  near 'ON tbl_vehicle_details.v_u_id = tbl_user.u_id AND
  tbl_ride.r_v_id =    ' at line 1

A: You are mixing implicit with explicit join syntax. Try this instead:
SELECT *
FROM tbl_vehicle_details
INNER JOIN tbl_user
ON `tbl_vehicle_details`.`v_u_id` = `tbl_user`.`u_id`
INNER JOIN tbl_ride
ON `tbl_ride`.`r_v_id` =`tbl_vehicle_details`.`v_id`
LIMIT 0, 25

Note: Usage of LIMIT without an ORDER BY clause results in an arbitrary selection of records as there is no inherent order in an SQL table.


text:
Q: Customs binding cross views in mvvmcross I need a custom binding and I know when and where but I don't know how I can do it. This is the relation of the view in my custom binding. Think about the *Views like controls.

I have the connections from ViewModel->ContainerView->FirstView but I can't connect it with the TableView. To connect the ContainerView to FirstView I did a custom binding (in one direction for now). And in the setvalue method I call the firstview's method SetBinding (where I want to do the binding)
I tried a few option but nothing happens, the last one looks like this:
public GolferList CurrentGolferList { get; set; }
    public void SetBinding(GolferList golferList){
        this.CurrentGolferList = golferList;

        TableSource = new TableSourcePlayers(TableViewPlayers);
        var bindingDescription = new[]{
            new MvxBindingDescription {TargetName = "ItemsSource",SourcePropertyPath = "CurrentGolferList"} ,
        };

        Binder.Bind(this,TableSource, bindingDescription);

        TableViewPlayers.Source = TableSource;
        TableViewPlayers.ReloadData();

    }

I would be grateful if you could tell me another way to handle it.
Update:
I followed Stuart's link and now it works fine, thanks a lot Stuart!
Actually, in my scheme the TableView is a MvxSimpleBindableTableViewSource and I want to bind the data there. So in order to make it work, I used the code below (SetBinding needs some external refactor):
    private List<IMvxUpdateableBinding> bindings;
    private string BindingText = "{'ItemsSource':{'Path':'CurrentGolfers'}}";
   public object DataContext {
        get { return dataContext; }
        set { dataContext = value;
            if (bindings == null)
                bindings = this.GetService<IMvxBinder>().Bind(dataContext, TableSource, BindingText).ToList();
            else
                bindings.ForEach(b => b.DataContext = dataContext);
           }
        }
    public void SetBinding(GolferList golferList){
        this.DataContext = PlayViewModel;
        tableView.Source = TableSource;
        tableView.ReloadData();
   }

Note that BindingText points to the table, not to the view itself.
Update 2
Now in V3 it's a bit different. First, the view must implement IMvxBindable and this members:
    public object DataContext
    {
        get { return BindingContext.DataContext; }
        set { BindingContext.DataContext = value; }
    }

    public IMvxBindingContext BindingContext { get; set; }

(Don't forget dispose calling BindingContext.ClearAllBindings() and also call to CreateBindingContext() in the viewload )
And then you'll be able to bind in your class. In my case:
    var set = this.CreateBindingSet<FirstPlayViewController, PlayViewModel>();
    set.Bind(source).To(vm => vm.CurrentGolfers).Apply(); //I love the new fluent api :)

A: I think what you want to do is actual a data-bound View, rather than a custom binding.
This is covered in this question - Custom bindable control in a MvvmCross Touch project
Basically what you need to do is to add a collection of 'Bindings' and the 'DataContext' property to your FirstView.
If you do that then you should be able to databind (to DataContext) within FirstView just like you do within any normal MvvmCross view.
Note - this will be much easier to do in v3 as we've added a 'BindingContext' object to assist with exactly this type of operation