text:
Q: Continue For Next loop in separate cell I have a table of number and I want to create a macro that will loop through each one, and return any value higher than 0.
The table would look something like this:
    1   2   3   4   5   6   7   8   9   10  11  12  13  14
1   0   0   0   0   0   0   0   0   0   0   0   0   0   0
2   0   0   0   0   2   0   0   0   0   0   0   0   0   7
3   0   0   0   0   0   0   0   0   0   0   0   0   0   0

And I would want it to return the column headers. So in that example I would want it to return the values 5 and 14 for the 2nd row.
So far I have:
For j = 0 To 11
    For i = 0 To 91

        If Cells(2 + j, 2 + i) > 0 Then
        Cells(16 + j, 2) = Cells(1, 2 + i)
        End If

    Next i
Next j

The issue with this is that it will only return one value in cells(16 + j, 2), which is the last value that this corresponds to. What I need is, once the condition has been met, for it to continue from that point, but enter the value into cells(16 + j, 3).
I considered perhaps an "Exit For" once it had met the condition, but couldn't work out how to continue on the next cell from where it had left off.

A: According with what you said this should work:
Dim cont        As Integer

cont = 2

For j = 0 To 11
For i = 0 To 91

    If Cells(2 + j, 2 + i) > 0 Then
    Cells(16 + j, cont) = Cells(1, 2 + i)
    cont = cont + 1
    End If

Next i
Next j


text:
Q: How to display GIF's in laravel I'm using Firefox Browser, tried all PNG's, JPG's and all were working, except GIF.
Here's the thing, if I test http://localhost/pepsi.gif, the GIF is actually working and displaying. But when I tried it inside HTML img tag it does not displaying.
Here's the simple code below:

Somebody could help me how to do it? I'm really stucked with this one.
pepsi.gif

A: This is most likely to be caused by an ad-blocker or extension.
Try disabling them 1 by 1 and see if the image loads.
Or try an incognito browser.

A: Your gif should work in an img-tag. If you upload your code to a server you have to change the path from localhost to anything other, maybe this causes the problem.

img {
  height: 200px;
  width:auto;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: fetching data from mongodb in nodejs I use the below code for getting data from mongodb
But the userlist is undefined in the .jade file
var db = monk('mongodb://UserName:Password@ds047342.mongolab.com:ds047342/UsersDB');

router.get('/userlist', function (req, res) {
    var db = req.db;
    var collection = db.get('Users');

    collection.find({}, {}, function (e, docs) {
        res.render('userlist', {
            "userlist": docs
        });
    });
});

code in the jade file
extends layout

    block content
        h1.
            User List
        ul
            each user, i in userlist
                li
                    a(href="mailto:#{user.EmailId}")= "name"

A: I was unable to replicate your issue and successfully loaded users from my local collection, maybe you need to validate before rendering the page like
router.get('/userlist', function (req, res) {
    var db = req.db;
    var collection = db.get('Users');

    collection.find({}, {}, function (e, docs) {
        if (e){
            // something went wrong, render an error
        } else if (!docs) {
            // no users found, render a 404 maybe
        } else {
            // users found, render the list
            res.render('userlist', {
                "userlist": docs
            });
        }
    });
});


text:
Q: Switch fails to render component in react router Hey Guys im kinda stuck on a simple matter,
my routing doesn't work, no idea why
The Code:
  <BrowserRouter>

    <Switch>
      <Route component={Home}  exact path='/'></Route>
      <Route component={ToyApp} exact path='/app'></Route>
    </Switch>

  </BrowserRouter>

NavBar:

        <BrowserRouter>
        <NavLink to='/'>Home</NavLink>
        <NavLink to='/app'>App</NavLink>
        </BrowserRouter>

Only the Home Component Renders even if i go to /app, when i change their order only the app component appears.
Edit:
When i change the url by hand in browser it works, so problem must be with the nav

A: You don't need the BrowserRouter wrapping your NavLinks. BrowserRouter should be used once at the very root of your app.

A: Why Browser Router? If you are using a dynamic server that can handle dynamic URLs then you need to use the BrowserRouter component else  if you are using a server that only serves static files you can use HashRouter.
A Link component takes a to property which tells React Router the destination to navigate to. NavLink is a subclass of Link which adds styling information to the rendered element(s) (You can use any of the either.)
You can use your component inside BrowserRouter .Posting Just a reference:
class App extends Component {
      render() {
        return (
        <BrowserRouter>

<Link to={'/'} className="nav-link"> Home </Link>

<Link to={'/contact'} className="nav-link">Contact</Link>

              <Switch>
                  <Route exact path='/' component={Home} />
                  <Route path='/contact' component={Contact} />
              </Switch>

          </BrowserRouter>
        );
      }
    }

For More : https://www.techiediaries.com/react/react-router-5-4-tutorial-examples/


text:
Q: Can gcloud nodejs modules see each other? I'm developing a application that runs client js code inside the node server (not safe, i know).
I use node vm, although It seems safe, I want to isolate it in another module so even though some malicious code reads all my node server code and config, it don't see important files.
I was reading https://cloud.google.com/appengine/docs/flexible/nodejs/configuration-files but i'm not sure it serves my purpose.
Example:
Files:

*

*< app>/notsafemodule/app.yml

*< app>/notsafemodule/...

*< app>/safemodule/app.yml

*< app>/safemodule/secret.txt

Are (safemodule) and (notsafemodule) deployed in same container?
Is it possible that (notsafemodule) can read (< app>/safemodule/secret.txt)?
Thanks!

A: Modules/services are deployed in different instances with different URLs:

*

*safemodule-dot-< app>.appspot.com

*notsafemodule-dot-< app>.appspot.com

So it's not possible that they see each other..


text:
Q: Using subprocess to execute command while in a class python Hi I am working in Tkinter and have built a frame that asks for a file to open and then opens that file to run code with it,
import subprocess
import pandas as pd
import Tkinter as tk

class MonthlyMenu(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)
        self.controller = controller

        self.browsefile = tk.StringVar()

        self.fileentry = tk.Entry(self, textvariable = self.browsefile,).grid(row=1,column=1,sticky=tk.W+tk.E)
        self.submitFile = tk.Button(self,text="Ok",command=self.openFile).grid(row=1,column=2,sticky = tk.W+tk.E)

    def openFile(self):
        self.browsefile.get()
        filename = self.browsefile.get()

        df = pd.read_excel(filename, sheename="Sheet1",parse_col=0)
        titles = list(df.columns)

        for col in titles:
            sa_command = "C:\\X12\\x12a.exe %s" % (col)
            process = subprocess.Popen(sa_command,stdout=subprocess.PIPE)
            process.wait()

But the last part of that code running the executable with subprocess is not running. There is other code in that for loop that runs and builds the correct files to run that executable, but I didn't think it was necessary to show everything. I have tried breaking the subprocess code out of the for loop and manually passing the titles, but that hasn't worked either.
All the other files that I create in that for loop are working correctly, and I have run just the subprocess code on its own (in a .py file with just that code) with those files and it works correctly then. I am wondering if anyone knows if it is an issue with trying to run it within the class that is causing this issue, or if I am just missing something.

A: Ok, I am not sure how good it is to answer my own question, and I promise I had been trying to get this to work for a while before posting the question.
But all I did was add the directory to file in the command, which shouldn't have mattered since they are always in the same directory. So changing it to:
sa_command = "C:\\X12\\x12a.exe C:\\X12\\%s" % (col)

This code will work now (I also realized I copied my code in incorrectly before and had "col" inside the string which doesn't work).
EDIT: I realize now that because my .py file that I was running was not in the C:\X12 directory, the command was looking for the appropriate files in the directory of my .py file and not in the directory with the executable.


text:
Q: Good probability measues on $S^1$ reprented by a kernel I was looking for some good references for properties/theorems/characterizations of 'good/important' probability measures on the unit circle $S^1$ ( and/or on spheres $S^n$ ).In particular, I want some probability measures on $S^1$ which is obtained through a kernel, like Poisson kernel for the harmonic measures etc. Are there any theorems that the probabilty measures are generated by some kernel if they are 'good', i.e. they have no atoms, they may be absolutely continuous with respect to Lebesgue measure.
Please suggest me some references in this topic.
Also, are there good results regarding homeomorphisms of $S^1, S^n$ which are more explicit in nature/expression ?

A: Perhaps this is not exactly what you are expecting, but it is anyway interesting.
In topological dynamics, when you have a compact group $\Gamma$ acting on the circle with Haar measure $dg$, you define a $\Gamma$-invariant probability measure on $S^1$ by the formula
$$\mu(A):=\int_\Gamma Leb(gA)dg$$
where $A$ is any Borel subset of $S^1$ and $Leb$ denotes the Lebesgue measure on the circle.
This is an easy exercise, but if you want to find more, one possible reference is Navas' survey on Groups of circle diffeomorphisms

A: There are some results and further references in Section 7.15 of K. Ito and H.P. McKean, Diffusion Processes and their Sample Paths, Springer, 1965.


text:
Q: Python Beautiful Soup (HTML Parsing) I am a beginner in in Python3.6 using BeautifulSoup to perform "web-scraping."
Once I have ran a request.get() and prettyify the output I notice that the webpage does not return the values, it would seem to be storing code which would be related to the value.
Here is the link to the webpage in specific:
http://www.tennisabstract.com/cgi-bin/wplayer.cgi?p=AngeliqueKerber&f=r1
I am trying to extract the hand which the player uses in Tennis.  Highlighted Yellow from picture below:
Picture of what I am trying to obtain:

I would appreciate feedback concerning the outline of the question, if it is confusing (or non-standard) feedback such as this will help me in the future to ensure I am asking questions appropriately.

A: There are two options (mostly).
The first one is easier and slower - browser emulation. You just try to use the site as a normal user - with browser. There is a python module for this task - selenium. It uses specific webdriver to use browser. There are plenty of webdrivers available (for example chromedriver to use chrome). Also, there are headless solutions (PhantomJS for example).
The other way is smarter and faster - XMLHttpRequests (XHRs). Basically - site uses some hidden API to get info via JS, and you try to find out how exactly. In most cases you can use Inspect Element toolbox of your browser. Switch to the network tab of it, clear it an try to get results. Then sort it to see only XHRs. It usually returns JSON-based values that are easily converted into a python dictionary using json() method of Response object.

A: Here's a really great GitHub that someone made on this website, an API practically you can change/edit few things (fork it) and then use it the way you want to.
HERE
It uses Selenium webdriver but it's high quality.


text:
Q: is there a way to print a float input into a specified number of characters? printf("%40s", "%.2f", AMOUNT);
im trying to print the computed price lets say 100 as the value of the chicken but it only prints "%.2f"

A: printf("%.2f", AMOUNT); would be enough. Make sure AMOUNT is double though.
Or, if you use cout, you will have to #include <iomanip> and do the following code:
cout << fixed << setprecision(2) << AMOUNT;


text:
Q: C programming: Read lines of numbers from a file and store it in an array I'm kinda new to programming so sorry for a stupid question. I've been tasked to read first two lines (numbers) and store them as variable n, and the other one in m. Other numbers bellow those two lines need to be read and store it in a dynamic array (malloc to be exact). Each line has exactly one number. I'm having trouble trying to accomplish this.
Here's my code so far:
#include <stdio.h>
#define MAX_LINE 5

int main() {

    FILE* in;
    FILE* out;
    int n, m, list = (int*)malloc(9 * sizeof(int));

    in = fopen("ulazna.txt", "r");
    out = fopen("izlazna.txt","w");

    if ((in && out) == NULL)
    {
        printf("Error opening the file...");
        return -1;
    }

    while (fscanf(in, "%d\n", &m) != EOF)
    {
        fscanf(in, "%d\n", &n);
        fscanf(in, "%d\n", &m);
        printf("First two: %d %d", n, m);
    }

    //free(list);
    fclose(in);
    fclose(out);
    return 0;
}

File ulazna.txt has:
3
3

This works as intended but when I write:
3
3
1
2
3
4
5
6
7
8
9

My program prints random numbers from this file.
So, I need to read 3 and 3 into n and m. Then, from 1 to 9 into the array list.
Thanks for help in advance :)

A: Dynamic array size
If you want to dynamically allocate memory for the list, you would have to count the number of lines in the file first.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n, m;
    /* open the file for reading text using "r" */
    FILE *file_in = fopen("ulazna.txt", "r");

    if (!file_in) { /* same as `file_in == NULL` */
        printf("Failed to open file\n");
        return EXIT_FAILURE;
    }

    int lines = 0; /* number of lines */
    int c; /* return value of `fgetc` is of type `int` */

    /* go through each character in the file */
    while ((c = fgetc(file_in)) != EOF) {
       /* increment the number of lines after every line break */
       if(c == '\n')
           ++lines;
    }

    /* reset pointer to start of file */
    rewind(file_in);

    /* check the return value of `fscanf` */
    if (fscanf(file_in, "%d\n", &n) != 1 ||
            fscanf(file_in, "%d\n", &m) != 1) {
        printf("File contains invalid line\n");
        return EXIT_FAILURE;
    }
    printf("First two: %d %d\n", n, m);

    /* no need to cast `malloc`, because it returns `void *` */
    int *list = malloc(lines * sizeof(int));
    for (int i = 0; i < lines - 2; ++i) {
        /* check the return value of `fscanf` */
        if (fscanf(file_in, "%d\n", &list[i]) != 1) {
            printf("File contains invalid line\n");
            return EXIT_FAILURE;
        }
        printf("%d\n", list[i]);
    }

    free(list); /* always free memory allocated by malloc */
    fclose(file_in);
    return EXIT_SUCCESS;
}

Fixed array size
If you already know that the number of lines in the file is going to be 11, the array has a length of 9 and there is no need to dynamically allocate memory. But because your assignment requires it, I have implemented malloc.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n, m;
    /* open the file for reading text using "r" */
    FILE *file_in = fopen("ulazna.txt", "r");

    if (!file_in) { /* same as `file_in == NULL` */
        printf("Failed to open file\n");
        return EXIT_FAILURE;
    }

    /* check the return value of `fscanf` */
    if (fscanf(file_in, "%d\n", &n) != 1 ||
            fscanf(file_in, "%d\n", &m) != 1) {
        printf("File contains invalid line\n");
        return EXIT_FAILURE;
    }
    printf("First two: %d %d\n", n, m);

    /* the array has a fixed size of 9 */
    const int size = 9;
    int *list = malloc(size * sizeof(int));
    /*
     * If you do not have to use malloc, remove the
     * above line and uncomment the following line:
     *
     * int list[size];
     */
    for (int i = 0; i < size; ++i) {
        /* check the return value of `fscanf` */
        if (fscanf(file_in, "%d\n", &list[i]) != 1) {
            printf("File contains invalid line or has to few lines\n");
            return EXIT_FAILURE;
        }
        printf("%d\n", list[i]);
    }

    fclose(file_in);
    return EXIT_SUCCESS;
}


text:
Q: c# ASP MVC Parallel For loop, getting descendants, random errors I am working on an issue dealing with the speed of our intranet web application and a function that gets the descendants of all items in our database.
I do not have access to the code at home, but I can describe the issue and process:
We have a database table that stores items that can be linked to a parent item in the same table. We have logic that prevents circular references, so in theory the descendant link should never circle back (so far no such thing has happened).
When a user accesses a page on the web app, currently I have functions that get the list of descendants of that item and puts it into an object. This was originally done in a normal FOR loop, but the time it took to parse through 881 entities would take 12+ seconds, which needs to change. I looked into threading and implemented the Parallel FOR loop, and it took the time from 12+ seconds to 1-2 seconds, except I randomly get errors on the page.
Some of the errors include the drop down list not being populated, the connection state not being open and available, and connection being closed and not available.
The original code is something like:
var DS = _uow.locations.AllEager().FirstOrDefault( l => l.Zone == "DS");
var hwddl = new List<HWTXSelectItem>();
var HWinDS = _uow.hw.AllEager().Where(h => h.Locations_ID == DSS.Locations_ID).OrderBy(h => h.ID).ToArray();

var dataSet =_uow.hw.AllEager().Where(h => h.IsActive && h.Parent_ID != null).Select(h => new HierarchyObject() {id=h.HW_ID, parentId = Parent_ID}).ToList();
var assets = _uow.hw.AllEager();
var arrayCount = HWinDS.Length;
for(int i = 0; i < arrayCount; i++){
    var hw in HWinDS[i];
    var HWDescendants = Helpers.FindAllChildren(dataSet, new HierarchyObject() {id=hw.HWID, parendId=null}).ToList();
    var descendends = new List<int>();
descendends.AddRange(HWDescendants.Select(m => m.id);

    var allChildren = assets.Where(h => descendends.Contains(h.HW_ID) && IsActive).ToList();

    var direct = allChildren.Where(h => h.ParentID == hw.HW_ID).Select(h => new{hwid = h.HWID, id=h.HW_ID}).OrderBy(h => h.hwid).ToList();
    var sub = allChildren.Where(h => h.Parent_ID != hw.HW_ID).Select(h => new{hwid = h.HWID, id=h.HW_ID}).OrderBy(h => h.hwid).ToList();

    hwtxddl.Add(new HWTXSelectItem
    {
    ...
    ... <obj properties>
    ...
    });
}

HWFromDS = hwddl;

The parallelized is something like:
var DS = _uow.locations.AllEager().FirstOrDefault( l => l.Zone == "DS");
var hwddl = new List<HWSelectItem>();
var HWinDS = _uow.hw.AllEager().Where(h => h.Locations_ID == DS.Locations_ID).OrderBy(h => h.ID).ToArray();

var dataSet =_uow.hw.AllEager().Where(h => h.IsActive && h.Parent_ID != null).Select(h => new HierarchyObject() {id=h.HW_ID, parentId = Parent_ID}).ToList();
var items = _uow.hw.AllEager();
var arrayCount = HWinDS.Length;
Parallel.For(0, arrayCount,i =>
{
    var hw in HWinDS[i];
    var HWDescendants = Helpers.FindAllChildren(dataSet, new HierarchyObject() {id=hw.HW_ID, parendId=null}).ToList();
    var descendends = new List<int>();
descendends.AddRange(HWDescendants.Select(m => m.id);

    var allChildren = assets.Where(h => descendends.Contains(h.HWAssets_ID) && IsActive).ToList();

    var direct = allChildren.Where(h => h.Parent_ID == hw.HW_ID).Select(h => new{hwid = h.HWID, id=h.HW_ID}).OrderBy(h => h.hwid).ToList();
    var sub = allChildren.Where(h => h.Parent_ID != hw.HW_ID).Select(h => new{hwid = h.HWID, id=h.HW_ID}).OrderBy(h => h.hwid).ToList();

    hwddl.Add(new HWSelectItem
    {
    ...
    ... <obj properties>
    ...
    });
}

HWFromDS = hwddl;

I have some variations of parallel for loops that work and speed up the process, getting an overall time of  6 seconds with partial data returning and no errors and 1 second with all data returning with random errors. The one above seems to work with full data returning but gives the random errors at random points. Any tips?


text:
Q: How to return json string of arrays using rapidjson I have a json file which looks like this
{
    "ActivityId":"CB8FA1DA-DCB4-40B3-9D12-2786BD89B4D4",
    "AdditionalParams":{

    },

    "Extensions":[
        {
            "Id":"1234",
            "IsEnabled":false,
            "Name":"Name1"
        },
        {
            "Id":"4567",
            "IsEnabled":false,
            "Name":"Name2"
        },
        {
            "Id":"8910",
            "IsEnabled":true,
            "Name":"Name3"
        }
    ]
}

I see a lot of code online which tries to get the IsEnabled,Name fields(as an example). However, I am trying to use rapidjson to print out the array of extensions as is.
Here is the code that I have tried
 Document document;
    document.Parse(json);
   if (document.HasMember(L"Extensions")) {
        eventPayload = document[L"Extensions"].GetString();
    }

A: document[L"Extensions"] is not a string, it's an array, so you will have to first getArray, then iterate through it with a JSONIterator and then get the value of IsEnabled.
Also, you don't have to use L"", since they are normal strings and not wide strings.


text:
Q: IE Event is null I am trying to simulate blur event in IE using JXBrowser.
HTML code:
<input type="text" id="email" name="email" onblur="test()">

and the function "test"
function test(){
    alert("1");
   alert(event.srcElement);
}

when I try it manually in IE, I get it work perfectly, but when I run using JXBrowser it pop's up the first alert (alert("1")) but then says: "Unable to get value of the property 'srcElement': object is null or undefined".
Why when I run JXBrowser it simulates the event but then it says that the event is null?
Thanks

A: For the most part, event.srcElement is called event.target in other browsers. Generally you can write this:
var element = event.srcElement ? event.srcElement : event.target;


text:
Q: How to use parent template's properties in child template in EmberJS? I have a /newLicense route defined inside application route ('/') as :
App.Router.map(function() {
    this.route('newLicense', {path: '/newLicense'});
});

I have a property in application controller called is_admin which gets set properly every time the application controller is called. Now in newLicense template, I want to show a message based on whether logged in user is admin or not (which is stored in is_admin of application controller).
I tried
{{#if is_admin}}
    <p> You are logged in as Admin user. </p>
{{else}}
    <p> You are logged in as Read-Only user. </p>
{{/if}}

But it's not working. I also tried to provide application controller in newLicenseController as :
App.newLicenseController = Ember.ObjectController.extend({
    needs: ['application'],
});

But it's still not working. Then I tried {{#if application.is_admin}} still no luck.
Any help on this concept is much appreciated. Thanks.

A: Got it. It was a simple mistake. One should access the properties of controllers listed in needs as : {{controllers.controller_name.property_name}}.
So in this case, it would become :
{{#if controllers.application.is_admin}}
    <p> You are logged in as Admin user. </p>
{{else}}
    <p> You are logged in as Read-Only user. </p>
{{/if}}


text:
Q: Is my proof valid? I need to proof that if a deleted epsilon neighborhood contains at least one element, it must contain an infinite number of elements.
So, this is my proof. Am I doing things wrong?
I will try to reach a contradiction.
Consider an deleted epsilon neighborhood of $s_0$: $N_{\epsilon}^-(s_0)$ and define the set S to be the set containing all points of this neighborhood. Suppose, S contains not an infinite number of elements. So S would contain a finite number of elements. Define a new set: $D=\{|s-s_0| | s \in S\}$. Since S was finite, this set is finite and therefore we could pick the smallest element of it. So, there exists an $s^* \in S$ such that $|s^*-s_0|$ is the smallest element of D. Since we know the neighborhood contains at least one element, call it $s_1$, we now that for any $\epsilon$ holds that $$|s_0-s_1|<\epsilon.$$ Now, pick $\epsilon = \frac{1}{2}|s^*-s_0|$, then $$|s_0-s_1|\ge|s^*-s_0|>\frac{1}{2}|s^*-s_0|=\epsilon$$ which contradicts the fact that $|s_0-s_1|<\epsilon$. So the deleted epsilon neighborhood of $s_0$ must contain an infinite number of elements.
Regards,
Kevin


text:
Q: Возможно ли A-GPS переключить на GPS? GPS определяет координаты по спутнику и бесплатно. A-GPS -по вышкам оператора и это платно по трафику, особенно если пакет на мало мегабайт. У меня вопрос, если на телефоне написано a-gps, возможно ли отключить эту функцию и использовать gps, не платя за трафик или a-gps сама по себе, а gps в телефонах может не быть?
A: Скорее всего нет, т.к. это разные вещи.A-GPS нужен 3G без него он не работает + ему реально нужен трафик для работы, но определяет он местоположение быстро, но погрешность больше чем при приемнике GPS.GPS не нужен инет для определения, у него есть спутники, но он нагружает своими расчетами процессор на мобильном устройстве.1.A-GPS сводит к минимуму время с момента включения GPS-приемника до первой выдачи координат.2. A-GPS более правильно и быстро может просчитать координаты, если допустим GPS сейчас работает только с одним спутником, а у A-GPS есть возможность обратиться к соседним станциям и по времени отдачи инфы от них получить местонахождение.
A: В большинстве телефонов есть и то, и то. И есть возможность отключать ненужную в данный момент времени технологию.![alt text][1]  [1]: http://i.imgur.com/pSAuM.jpg


text:
Q: JTable not updating when model updates Ok, I have read up on this, but I'm still very confused. I have a JTable with a custom Table Model that stores data in an ArrayList. It displays just fine. However, when I want to add a row, I add an object to the ArrayList, then call fireTableRowsInserted(...). However, the table does not refresh.
public Main() {
        initComponents();
        current_map = new Map();
        current_map.authors.add(new Author("New Author"));
        author_model = new AuthorModel(current_map.authors);
        jTable1.setModel(new AuthorModel(current_map.authors)); <---This is the mistake
    }
...

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        author_model.authors.add(new Author("New Author"));
        author_model.fireTableRowsInserted(author_model.authors.size(), author_model.authors.size());
    }

The above code is from my main JFrame. Not sure where to go from here.
I'm lost right now.

A: The table is initialized with:
jTable1.setModel(new AuthorModel(current_map.authors));

But when the button is clicked, you modify the variable author_model:
author_model.authors.add(new Author("New Author"));

The initialization of the table should be
jTable1.setModel(author_model);

You should also respect the Java naming conventions, and choose better names for your variables.


text:
Q: Continue HTTP Video Live streaming In background mode Ios I am searching for an answer related to live streaming for a while but did not got any satisfying answer.
I am developing a HTTP live streaming (HLS) protocol  based ios app. I can live stream from my ios app  that not a problem . but when my  app goes in background by pressing home button The Mpmovieplayer get paused and after returning to the foreground when i resume the player it take some time for starting  to live streaming again. Thats normally its behaves.
But now my client wants that after returning to foreground from background the live streaming should not take time . that means in my understanding the continuous request of url should be done in background so that when app come to foreground the live streamjing should take very little time .
My question is how i can request  to live straming url in background mode so that that steaming goes smoothly after coming from  background . I have searched the documentation the closest think i got is audio live streaming in background.Anyone there who can enlighten me how other ios live streaming app solve this problem??

A: You can make a circular buffer for that for something like 10 secs and keep feeding the data in it and deleting it on other side so you will ways have say 10 secs of data. Whenever the player goes to background, even then you will keep filling the buffer. Whenever it comes back, fed the player with the buffer and after say 8-9 secs you can switch to normal streaming.
I am not sure if this will be feasible fro your application but its workable and people have implemented this kind of behavior.


text:
Q: How to encode string categorical data? So I have a dataset that is essentially the list of Windows API calls that a single program makes. Each row belongs to one program. Successive cells of the same row are the API calls made by the same program. My issue is not being able to figure out how to encode this categorical data so that I can make a regression-based ML model out of it.
I tried using the Pandas method, get_dummies() but that just seems to mess things up as there is an exponential increase in the number of columns that seems to be generated.
My dataset looks something like this -
ROW [9822] GetStartupInfoA LockResource GetCommandLineA GetModuleFileNameA ShowWindow EnableWindow DestroyWindow    lstrcpyW GetThreadLocale lstrcmpiW GlobalAlloc

I also have the list of unique APIs if that helps.
My goal is essentially to build a model that analyses the API calls and predicts if the program making these calls is benign or not.

A: This is integer encoding:
api_dict = {
'call_1': 1,
'call_2': 2,
'call_3': 3,
...}

#grab the corresponding value from the dictionary
`api_dict.get({api_name_here})`

I'm not sure how your data structure is arranged but assuming it is a list of lists:
for row in sheet:
    for cell in row:
       cell = api_dict.get(value)

One hot encoding is similar except the values will be converted to binary:
from keras.utils import to_categorical

data = ['cold', 'warm', 'hot'] # 3 possible values
encoded = to_categorical(data)

returns
[[1 0 0],[0 1 0],[0 0 1]]
~2000 different values will be converted to an 11-digit binary number, that means that in order to represent all different API calls, the function converts each value, 11 different columns of either 1, or 0. This is done to keep the data as neutral as possible.
If you use the algorithm I provided above, you will end up with a 1-1 replacement, but the value in the cell will be anywhere from 1-2000. This could affect the output of your model.
Alternatives:

*

*Reduce the amount of calls you want to allow the program to make, this will reduce the columns

*Reconsider what data you want your model to consider when making a prediction. You can remove any unneeded data or use a different approach to reduce it.

*Change the structure of your table, instead of logging all of the calls, you can log things like total runtime, # of API calls, or anything else you think might affect your output. It's up to you.


text:
Q: How to 're-run' the mainloop in Tkinter I've been asked to make a Chat program using Tkinter. For the final part, I'm supposed to have the Chat window open, which has one Entry field, one Button (SEND) and a Text Widget to display the chat log. This is my first week learning Tkinter, and I've been told in class that the mainloop() is an infinite loop as long as the user doesn't close the window or write root.quit(). So in the chat window, I'm supposed to check for new messages every 10 seconds. Is it possible to do that in the mainloop()? If yes, please let me know how, because I have no idea how that can happen since the stuff before the mainloop() is read only once. For example, something like a print statement is printed only once, even though the mainloop() is an infinite loop.

A: You can call the after method of the root window to call something in the future. If that function itself calls after, you can set it up so that your function runs every 10 seconds forever.
def check_for_messages():

    <your code here>

    root.after(10000, check_for_messages)

Call that function once before calling mainloop() and it will run every 10 seconds for as long as mainloop() is running.


text:
Q: How can I create an ArrayList of n elements in Kotlin? This should be trivial. Kotlin has an ArrayList with a constructor "initialCapacity"
If I have this test case;
class ArrayListTest : TestCase() {

  @Test
  fun testArrayList() {
      val test = ArrayList<Int>(12)
      test[3]=5
  }
}

I get the exception
java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 0
Running in debug confirms that although the ArrayList is created, its size is zero.
The docs say there's limited functionality for controlling capacity because the backing array is resizable itself, but this doesn't seem to be happening. Even if I use index 0 I get the out of bounds exception.
I tried running an update on the offchance. I'm running Android Studio Arctic Fox 2020.3.1 Patch 3, of Oct 1st 2021.
Has anyone else encountered and resolved this?
Edit: hmm. test.add(5) lets you append, which is fine for most cases. I'm leaving the question up because it seems the original approach should work.

A: The constructor that takes an initialCapacity parameter only uses the capacity as the size of the backing array under the hood. Note the parameter is called "capacity", not "size". This is useful if you know ahead of time that the list will likely not grow beyond a certain size, because then it doesn't use a bigger backing array than necessary, and it won't have to resize the array later if it started too small.
Unlike Array, ArrayList has no fixed size. Its size is dependent on what elements are currently in it. So it always starts with size zero unless you pass elements to its constructor.
You created an ArrayList with size zero and backing array capacity of 12. Since it has zero elements, you can't access an element with index bigger than its size.
You seem to want to create an ArrayList with a specific size, all filled with zeroes. There's no function or constructor for doing that exactly, but you can do it with MutableList like this:
val test = MutableList(12) { 0 }


text:
Q: My express js api cannot read my given property It does not read the res.body.signatureRequestId property for my Express js server.
How should I submit the property to avoid the error in type error? I shared my error log, json response, express js code with below.
Error log:
{
  account: {
    account_id: 'aaa',
    email_address: 'xxx@gmail.com',
    is_locked: false,
    is_paid_hs: false,
    is_paid_hf: false,
    quotas: {
      templates_left: 0,
      documents_left: 2,
      api_signature_requests_left: 0
    },
    callback_url: 'https://hellosigntest.info/api/callback',
    role_code: null
  },
  resHeaders: {
    'access-control-allow-headers': 'Authorization, Origin, X-Requested-With, Content-Type, Accept',
    'access-control-allow-methods': 'GET, POST, OPTIONS',
    'access-control-allow-origin': '*',
    'content-type': 'application/json',
    date: 'Fri, 10 Apr 2020 10:01:26 GMT',
    p3p: 'CP="NOP3PPOLICY"',
    server: 'Apache',
    'strict-transport-security': 'max-age=15768000',
    'user-agent': 'HelloSign API',
    vary: 'Accept-Encoding',
    'x-ratelimit-limit': '2000',
    'x-ratelimit-limit-remaining': '1999',
    'x-ratelimit-reset': '1586512887',
    'content-length': '329',
    connection: 'Close'
  },
  statusCode: 200,
  statusMessage: 'OK'
}
Hello API Event Received
TypeError: Cannot read property 'signature_request_id' of undefined
    at /Desktop/nodejs/helloSignDemo/routes/index.js:50:54
    at Layer.handle [as handle_request] (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/layer.js:95:5)
    at next (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/layer.js:95:5)
    at /Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/index.js:335:12)
    at next (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/index.js:174:3)
    at router (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/index.js:47:12)

Events posted to your callback url will be formatted as a JSON string contained in the json POST param. The complete detail for the event object can be found in the event section of the API reference page. Here is an example of an event that could be received:
{
    "account_guid": "aaa", // DEPRECATED: use reported_for_account_id instead
    "client_id": null,  // DEPRECATED: use reported_for_app_id instead
    "event": {
        "event_time": "1348177752",
        "event_type": "signature_request_sent",
        "event_hash": "aaa",
        "event_metadata": {
            "related_signature_id": "aaa",
            "reported_for_account_id": "aaa",
            "reported_for_app_id": null
        }
    },

 signature_request: {
    signature_request_id: 'aaaaa',
    test_mode: true,
    title: 'PDF Sign via Node Server',
    original_title: 'PDF Sign via Node Server',
    subject: 'PDF Sign via Node Server',
    message: 'Please sign this pdf.',
    metadata: {},
    created_at: 1586507276,
    is_complete: false,
    is_declined: false,
    has_error: false,
    custom_fields: [],
    response_data: [],
    signing_url: 'https://xxxcom/aaa',
    signing_redirect_url: null,
    final_copy_uri: '/v3/signature_request/final_copy/aaa',
    files_url: 'https://api.hellosign.com/v3/signature_request/files/aaa',
    details_url: 'https://app.hellosign.com/home/manage?guid=aaa',
    requester_email_address: 'xxx@gmail.com',
    signatures: [ [Object] ],
    cc_email_addresses: [],
    template_ids: null
  }
}

routes/ index js :
const express = require('express');
const router = express.Router();
const hellosign = require('hellosign-sdk')({ key: 'key' });
const fs = require('fs');

hellosign.account.update({
    callback_url: process.env.HOST_URL+'/api/callback'
}).then((res) => {
    // handle response
    console.log(res)
}).catch((err) => {
    // handle error
    console.log(err)
});

router.post('/sign',(req,res)=>{
    const opts = {
        test_mode: 1,
        title: 'PDF Sign via Node Server',
        subject: 'PDF Sign via Node Server',
        message: 'Please sign this pdf.',
        signers: [
            {
                email_address: 'xxx@gmail.com',
                name: 'xxx'
            }
        ],
        files: ['nda.pdf']
    };

    hellosign.signatureRequest.send(opts).then((res) => {
        // handle response
        console.log(res)
    }).catch((err) => {
        // handle error
        console.log(err)
    });
});

router.post('/callback',(req,res)=>{

    res.send('Hello API Event Received');

    res.send(res.body);

    try {
        hellosign.signatureRequest.download(res.body.signatureRequestId, { file_type: 'zip' }, (err, res) => {
            const file = fs.createWriteStream('files.zip');

            res.pipe(file);

            file.on('finish', () => {
                file.close();
            });
        });
    }catch (e) {
        console.log(e)
    }

});

router.get('/', (req, res) => {
    res.send("Server is listening...")
});

module.exports = router;

index.js
const express = require('express');
const app = express();

app.use(express.json());
app.use(express.urlencoded({extended:true}));

app.use('/api',require('./routes/index'));

app.listen(process.env.PORT,function(){
    console.log("Started on PORT "+process.env.PORT);
});

A: The res.body property is not populated by default.  To get it populated from your POST data, you need an appropriate middleware that will read the body of the request, parse it and place the parsed results into req.body.
Express has a few middleware functions built-in that you can use as shown below:
app.use(express.json());                           // for json body
app.use(express.urlencoded({extended:true}));      // for form encoded body
app.use(express.text());                           // for plain text body

You need to use middleware that matches the content-type of your POST request.  That middleware will then populate the req.body property.
From the Express documentation:

req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().

As you can see in the documentation, req.body is undefined unless you have an appropriate middleware that matches in the incoming content-type and runs before your request handler.


text:
Q: SailsJs add custom task in default.js I'm trying to add a custom task in a salsjs application.
This is what I've done so far:

*

*Added a new file in the task/config directory named cssminTemplates.js

*Modify the default.js file in the task/registerd directory.

My cssminTemplates.js is basically a copy of the cssmin.js standard file:
module.exports = function(grunt) {

 grunt.config.set('cssminTemplates', {
    dist: {
        src: ['asset/templates/above_the_fold.css'],
        dest: 'asset/templates/above_the_fold.min.css'
    }
 });
grunt.loadNpmTasks('grunt-contrib-cssmin');
};

default.js file as been modified as follow:
module.exports = function (grunt) {
 grunt.registerTask('default', [
  'compileAssets',
  'linkAssets',
  'cssminTemplates',
  'watch']);
};

But when I start the app with sails lift command I got this error:
Warning: Task "cssminTemplates" not found.

I try to change the 'cssminTemplates' with 'cssmin' and I've got no errors.

A: In Grunt.js (ref), cssminTemplates function is invoked instead of cssmin which is loaded via grunt.loadNpmTasks('grunt-contrib-cssmin');. This is where the function is invoked:
function invokeConfigFn(tasks) {
    for (var taskName in tasks) {
        if (tasks.hasOwnProperty(taskName)) {
            // Invoking the function....
            tasks[taskName](grunt);
        }
    }
}

In other words, you are setting the function (cssminTemplates) and invoking it from Grunt.js but Grunt loaded cssmin instead via loadNpmTasks(). I think that's why setting cssminTemplates does not work.


text:
Q: Accessing arrays using pointers I came across the below code snippet in a project and was not sure how value of variable "response" is computed. Here as we can see, pic_data holds two one dimensional arrays but "response" access both the single dimensional array as two dimensional array.
Can anyone please explain how this works?
Note: below code is not full fledged code snippet of a larger code block.
#define MAX 100
#define MAXBUF 100

u32 response;
u32 index;

typedef struct {
    u16         flag;
    u16         status;
} __attribute__ ((packed)) register;

typedef struct
{
    register      *rq[MAX];
    u64            buf[MAXBUF];

}Data;

Data *pic_data;

void getres(Data *pic_data) {
    response = *((u32*)&(pic_data->rq[index][pic_data->buf[index]]));
}

A: That line isn't accessing a 2D array, it's accessing a 1D array of pointers, and then dereferencing the pointer it gets out.
Let's break it down into steps.  Starting with:
response = *((u32*)&(pic_data->rq[index][pic_data->buf[index]]));

We can rewrite as:
register *r = pic_data->rq[index]; // figure out which element of 'rq' to use
u64 offset = pic_data->buf[index]; // figure out what offset to use from 'buf'
response = *(u32 *)&r[offset];     // get the right register and extract value
                                   // into a 32-bit word

Editorial note:  register is a reserved word, don't use it as a type name.  Your function paramater pic_data also shadows the global variable of the same name.  Be careful out there!


text:
Q: Como limitar el espacio de trabajo a una celda desbloqueda en google sheets? tengo un proyecto de lector de precios casi finalizado, solo se me presenta el problema de que es necesario que la única celda (A1) donde se ingresa el código de barras, una vez ingresado el valor, el cursor NO se desplace a otra celda, sino que siempre esté situado en dicha celda de manera inamovible.
No he encontrado información al respecto. en Excel funciona simplemente con la protección de hojas y libros bloqueando la hoja y seleccionando la celda desbloqueada.  Necesito lo mismo para Google sheets.
Desde ya muchas gracias !


text:
Q: get the last weeks date from given date I am trying to find the date of the of the last week. For instance lets say my date is '2021-01-02' in that specific date time format. How do i go about getting the date of the past week.
I originally tried but I get this error. I believe its because i have the date as a string but i need to have the dates in the yyyy-mm-dd format
x = '2021-01-02'
pervious_data =  datetime.date.x.shift(-7)

error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-09dc0b383193> in <module>
      1 x='2021-03-05'
----> 2 pervious_data =  datetime.date.x.shift(-7)

AttributeError: 'str' object has no attribute 'x'

A: The method datetime.datetime.strptime is able to convert the string into a special datetime object, which in turn can be turned into a date object.
After that, you need only create a datetime.timedelta instance of a single week and subtract it from your date.
import datetime

x = datetime.datetime.strptime("2021-01-02", "%Y-%m-%d").date()
previous_data = x - datetime.timedelta(weeks=1)


text:
Q: Pushing to state using for loop in Angular I want to push to state variable using a for loop in Angular, however, I get an error "cannot set property 'date' of undefined":
export class CalendarComponent implements OnInit {
  days: CalendarDay[]
  iterationDay: CalendarDay
  constructor() {}

  ngOnInit(): void {
    this.generateWeekData()
    console.log(this.days)
  }

  generateWeekData() {
    for (let i = 0; i < 8; i++) {
      let whenEven = i % 2 === 0
      ;(this.iterationDay.date = new Date()),
        (this.iterationDay.quantity = 24 - i),
        (this.iterationDay.price = 13),
        (this.iterationDay.eventType = 'string'),
        (this.iterationDay.isExpenseType = whenEven),
        (this.iterationDay.isHoursEventType = whenEven),
        (this.iterationDay.isAdditionalHoursEventType = whenEven),
        (this.iterationDay.isWorkHour = whenEven),
        (this.iterationDay.isApproved = whenEven),
        (this.iterationDay.isRejected = whenEven),
        (this.iterationDay.tasksCount = 2),
        (this.iterationDay.firstTaskStart = new Date()),
        (this.iterationDay.lastTaskEnd = new Date())

      this.days.push(this.iterationDay)
    }
  }
}

A: Foremost, you need to initialize iterationDay property
Something like this
iterationDay: CalendarDay = new CalendarDay()

or
iterationDay: CalendarDay = {};

based on the shape of your object.


text:
Q: Android Add date to calendar i converted String "Mon, 11 Feb 2013 08:00:00 CST" to date using the following code
java.util.Date d=null;
    try {
         d= new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z").parse("date");
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

How to add this date to calendar as a  beginTime and also an endTime 30minutes difference to the start time. i want to make a popup sheet to enter other details also.it should be compatable for all android versions.
can anyone helpme out in this

A: I know this may not directly be the answer you want but I've recently been working with time/date manipulation and I installed the Joda-time API. It's a lot easier to control.
http://joda-time.sourceforge.net/


text:
Q: expand some wildcards within given string and return list of strings Is it possible to write a proc which will give a string and will be expand some wildcards and will return list of strings, something like this:
proc expand_string { string } {
 ...
}

set a [expand_string {[1-5]a}]

puts $a #a is: 1a 2a 3a 4a 5a

The interested wildcards are:
[12..a..z]:
Match any character listed in the brackets.
[a-z]:
Match all characters between a and z.
?(abc):
Match zero or one instance of abc.


text:
Q: MySQL subquery with LIMIT I have read over similar posts on using subqueries and can't figure out how to apply it to my needs.
I have two drug tables:
Generics with fields GenericID and GenericName
and DrugCaseCounts with fields GenericID (links to Generics), DrugName and Cases
The Generics.GenericName is the active ingredient in the drug, e.g. fluoxetine, and the DrugCaseCounts.DrugName is the brand name, e.g. Prozac.  DrugCaseCounts.Cases is the number of Case reports where that brand name appears.  There can be more than 10 DrugCaseCounts records (different brand names) for one Generics.GenericID.
I want to produce a list that shows:
Generics.GenericID, Generics.GenericName, DrugCaseCounts.DrugName, Cases
listing the top 10 DrugCaseCounts.DrugName records, GROUPED BY GenericID in descending order by Cases.
I know this requires a subquery on the DrugCaseCounts table, but I can't figure out how to state it.


text:
Q: Turn a map canvas into a vector layer in QGIS I ran a program that created points on the nearest edge of a polygon, but it only appears in the iface.mapLayer() canvas.
The code is taken from the answer in: https://gis.stackexchange.com/a/94428

You can see that no layer is selected but the points are still showing.
How do I get the points onto a vector layer or a shapefile?
EDIT:
This is the modified code
import math
from qgis.gui import *
from PyQt4.QtCore import Qt

lineLayer = iface.mapCanvas().layer(0)
pointLayer =  iface.mapCanvas().layer(1)
canvas =  iface.mapCanvas()
spIndex = QgsSpatialIndex() #create spatial index object
lineIter =  lineLayer.getFeatures()

for lineFeature in lineIter:
    spIndex.insertFeature(lineFeature)

pointIter =  pointLayer.getFeatures()

for feature in pointIter:
    ptGeom = feature.geometry()
    pt = feature.geometry().asPoint()

    nearestIds = spIndex.nearestNeighbor(pt,1) # we need only one neighbour
    featureId = nearestIds[0]
    nearestIterator = lineLayer.getFeatures(QgsFeatureRequest().setFilterFid(featureId))
    nearFeature = QgsFeature()
    nearestIterator.nextFeature(nearFeature)

    closeSegResult = nearFeature.geometry().closestSegmentWithContext(ptGeom.asPoint())
    closePoint = closeSegResult[1]
    snapGeometry = QgsGeometry.fromPoint(QgsPoint(closePoint[0],closePoint[1]))

    p1 = ptGeom.asPoint()
    p2 = snapGeometry.asPoint()

    dist = math.hypot(p2.x() - p1.x(), p2.y() - p1.y())
    print dist

    r = QgsRubberBand(canvas,QGis.Point)
    r.setColor(Qt.red)
    r.setToGeometry(snapGeometry,pointLayer)

A: First we can create a point layer in memory using something like:
result = QgsVectorLayer("Point?crs=epsg:4326", "result", "memory")
pr = result.dataProvider()
fet = QgsFeature()

Then inside your for loop, we can add points to the memory layer using the coordinates of the snapped geometry:
fet.setGeometry(QgsGeometry.fromPoint(p2))
pr.addFeatures([fet])

Then finally add the memory layer into the canvas:
QgsMapLayerRegistry.instance().addMapLayer(result)

So the full code could look something like this:
import math
from qgis.gui import *
from PyQt4.QtCore import Qt

lineLayer = iface.mapCanvas().layer(0)
pointLayer =  iface.mapCanvas().layer(1)
canvas =  iface.mapCanvas()
spIndex = QgsSpatialIndex() #create spatial index object
lineIter =  lineLayer.getFeatures()

for lineFeature in lineIter:
    spIndex.insertFeature(lineFeature)

result = QgsVectorLayer("Point?crs=epsg:4326", "result", "memory")
pr = result.dataProvider()
fet = QgsFeature()

pointIter =  pointLayer.getFeatures()
for feature in pointIter:
    ptGeom = feature.geometry()
    pt = feature.geometry().asPoint()
    nearestIds = spIndex.nearestNeighbor(pt,1) # we need only one neighbour
    featureId = nearestIds[0]
    nearestIterator = lineLayer.getFeatures(QgsFeatureRequest().setFilterFid(featureId))
    nearFeature = QgsFeature()
    nearestIterator.nextFeature(nearFeature)
    closeSegResult = nearFeature.geometry().closestSegmentWithContext(ptGeom.asPoint())
    closePoint = closeSegResult[1]
    snapGeometry = QgsGeometry.fromPoint(QgsPoint(closePoint[0],closePoint[1]))
    p1 = ptGeom.asPoint()
    p2 = snapGeometry.asPoint()
    dist = math.hypot(p2.x() - p1.x(), p2.y() - p1.y())
    print dist
    r = QgsRubberBand(canvas,QGis.Point)
    r.setColor(Qt.red)
    r.setToGeometry(snapGeometry,pointLayer)
    fet.setGeometry(QgsGeometry.fromPoint(p2))
    pr.addFeatures([fet])

QgsMapLayerRegistry.instance().addMapLayer(result)

Example:
Sample points and lines before we run the code:

After we run the code, the red points are rubberband snapped points on canvas, the blue points are those saved in the memory layer:

EDIT:
If you want to add your original points also to the memory layer, we can add the following lines after we have created the layer:
# Create new memory layer
mlayer = QgsVectorLayer("Point?crs=epsg:4326", "result", "memory")
mlayer_data = mlayer.dataProvider()
feature = QgsFeature()

# Get original features from point layer and add to memory layer
feats = [feat for feat in pointLayer.getFeatures()]
attr = pointLayer.dataProvider().fields().toList()
mlayer_data.addAttributes(attr)
mlayer.updateFields()
mlayer_data.addFeatures(feats)

So now your full code might look something like the following (note: I changed some naming terms):
import math
from qgis.gui import *
from PyQt4.QtCore import Qt

lineLayer = iface.mapCanvas().layer(0)
pointLayer =  iface.mapCanvas().layer(1)

canvas =  iface.mapCanvas()
spIndex = QgsSpatialIndex() #create spatial index object
lineIter =  lineLayer.getFeatures()

for lineFeature in lineIter:
    spIndex.insertFeature(lineFeature)

# Create new memory layer
mlayer = QgsVectorLayer("Point?crs=epsg:4326", "result", "memory")
mlayer_data = mlayer.dataProvider()
feature = QgsFeature()

# Get original features from point layer and add to memory layer
feats = [feat for feat in pointLayer.getFeatures()]
attr = pointLayer.dataProvider().fields().toList()
mlayer_data.addAttributes(attr)
mlayer.updateFields()
mlayer_data.addFeatures(feats)

pointIter =  pointLayer.getFeatures()
for feature in pointIter:
    ptGeom = feature.geometry()
    pt = feature.geometry().asPoint()
    nearestIds = spIndex.nearestNeighbor(pt,1) # we need only one neighbour
    featureId = nearestIds[0]
    nearestIterator = lineLayer.getFeatures(QgsFeatureRequest().setFilterFid(featureId))
    nearFeature = QgsFeature()
    nearestIterator.nextFeature(nearFeature)
    closeSegResult = nearFeature.geometry().closestSegmentWithContext(ptGeom.asPoint())
    closePoint = closeSegResult[1]
    snapGeometry = QgsGeometry.fromPoint(QgsPoint(closePoint[0],closePoint[1]))
    p1 = ptGeom.asPoint()
    p2 = snapGeometry.asPoint()
    dist = math.hypot(p2.x() - p1.x(), p2.y() - p1.y())
    print dist
    r = QgsRubberBand(canvas,QGis.Point)
    r.setColor(Qt.red)
    r.setToGeometry(snapGeometry,pointLayer)
    feature.setGeometry(QgsGeometry.fromPoint(p2))
    # Add rubberband snapped features to memory layer
    mlayer_data.addFeatures([feature])

QgsMapLayerRegistry.instance().addMapLayer(mlayer)


text:
Q: Deserialize JSON string to c# object My Application is in Asp.Net MVC3 coded in C#.
This is what my requirement is. I want an object which is in the following format.This object should be achieved when I deserialize the Json string.
var obj1 = new { arg1=1,arg2=2 };

After using the below code:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize<object>(str);

The object what i get i.e obje does not acts as obj1

Here, in this example my JSON string is static, but actually JSON string is going to be dynamically generated runtime, so i won't be able get Arg1 and Arg2 all the time.

A: I believe you are looking for this:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

A: This may be useful:
var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);

Where "json" is the string that contains the JSON values.  Then to retrieve the values from the jsonObject you may use
myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);

Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).

A: solution :
 public Response Get(string jsonData) {
     var json = JsonConvert.DeserializeObject<modelname>(jsonData);
     var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
     return data;
 }

model:
 public class modelname {
     public long parameter{ get; set; }
     public int parameter{ get; set; }
     public int parameter{ get; set; }
     public string parameter{ get; set; }
 }

A: I think the JavaScriptSerializer does not create a dynamic object.
So you should define the class first:
class MyObj {
    public int arg1 {get;set;}
    public int arg2 {get;set;}
}

And deserialize that instead of object:
serializer.Deserialize<MyObj>(str);

Not testet, please try.

A: Same problem happened to me. So if the service returns the response as a JSON string you have to deserialize the string first, then you will be able to deserialize the object type from it properly:
string json= string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream(), true))
        {
            json= new JavaScriptSerializer().Deserialize<string>(streamReader.ReadToEnd());

        }
//To deserialize to your object type...
MyType myType;
using (var memoryStream = new MemoryStream())
         {
            byte[] jsonBytes = Encoding.UTF8.GetBytes(@json);
            memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
            memoryStream.Seek(0, SeekOrigin.Begin);
            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8,          XmlDictionaryReaderQuotas.Max, null))
            {
                var serializer = new DataContractJsonSerializer(typeof(MyType));
                myType = (MyType)serializer.ReadObject(jsonReader);

            }
        }

4 Sure it will work.... ;)

A: Use this code:
var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);


text:
Q: why javascript not wait for and of forEach and execute next line when I create my api in nodejs and trying to pushing mongoose return count to new created array, it's not wait for the forEach and execute json.res() and giving null response. when I use
setTimeout() then it's giving proper result.
let newcategories = [];
let service = 0;
const categories = await Category.find({}, '_id name');
categories.forEach(async (category) => {

service = await Service.count({category: category});

newcategories.push({ count:service });
console.log('newcategories is -- ', newcategories);

});  /* while executing this forEach it's not wait and execute res.json..*/

console.log('result --- ',result);
console.log('out newcategories is -- ', newcategories);
res.json({status: 200, data: newcategories});

A: You need to use map instead of forEach, to collect the awaits and wait for them to complete. Edit: Or you can use for..of which is pretty neat (thanks other ppl)!

const categories = ['a', 'b', 'c'];

function getNextCategory(oldCategory) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(String.fromCharCode(oldCategory.charCodeAt(0)+1));
    }, 1000);
  });
}

async function blah() {
  const categoryPromises = categories.map(getNextCategory);

  const nextCategories = await Promise.all(categoryPromises);

  console.log(nextCategories);
}

blah();

async function blah2() {
  const nextCategories = [];

  for (const category of categories) {
    nextCategories.push(await getNextCategory(category));
  };

  console.log(nextCategories);
}

blah2();

A: So the problem you have is that async marked functions will return a promise per default, but that the Array.prototype.forEach method doesn't care about the result type of your callback function, it is just executing an action.
Inside your async function, it will properly await your responses and fill up your new categories, but the forEach loop on categories will be long gone.
You could either choose to convert your statements into a for .. of loop, or you could use map and then await Promise.all( mapped )
The for..of loop would be like this
for (let category of categories) {
  service = await Service.count({category: category});

  newcategories.push({ count:service });
  console.log('newcategories is -- ', newcategories);
}

the map version would look like this
await Promise.all( categories.map(async (category) => {
  service = await Service.count({category: category});

  newcategories.push({ count:service });
  console.log('newcategories is -- ', newcategories);
}));

The second version simply works because Promise.all will only resolve once all promises have completed, and the map will return a potentially unresolved promise for each category


text:
Q: Load Preferences Settings in Swipable Tabs with Fragment I have searched the web but didnt find any proper solution.
I am trying to load some preference Settings in Tab Fragments.

In the first Image, When I use menu Inflator, I get those  3 dotted buttons, I dont need those, insted I want the menu to load in my Tab Fragment.
Below is the code of my
SettingPrefActivity.java
public class SettingsPrefActivity extends AppPreferenceActivity {
private static final String TAG = SettingsPrefActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // load settings fragment
    getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
}

public static class MainPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_main);

        // gallery EditText change listener
        bindPreferenceSummaryToValue(findPreference(getString(R.string.key_gallery_name)));

        // notification preference change listener
        bindPreferenceSummaryToValue(findPreference(getString(R.string.key_notifications_new_message_ringtone)));

        // feedback preference click listener
        Preference myPref = findPreference(getString(R.string.key_send_feedback));
        myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                sendFeedback(getActivity());
                return true;
            }
        });
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        onBackPressed();
    }
    return super.onOptionsItemSelected(item);
}

private static void bindPreferenceSummaryToValue(Preference preference) {
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
            PreferenceManager
                    .getDefaultSharedPreferences(preference.getContext())
                    .getString(preference.getKey(), ""));
}

/**
 * A preference value change listener that updates the preference's summary
 * to reflect its new value.
 */
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        String stringValue = newValue.toString();

        if (preference instanceof ListPreference) {
            // For list preferences, look up the correct display value in
            // the preference's 'entries' list.
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);

            // Set the summary to reflect the new value.
            preference.setSummary(
                    index >= 0
                            ? listPreference.getEntries()[index]
                            : null);

        } else if (preference instanceof RingtonePreference) {
            // For ringtone preferences, look up the correct display value
            // using RingtoneManager.
            if (TextUtils.isEmpty(stringValue)) {
                // Empty values correspond to 'silent' (no ringtone).
                preference.setSummary(R.string.pref_ringtone_silent);

            } else {
                Ringtone ringtone = RingtoneManager.getRingtone(
                        preference.getContext(), Uri.parse(stringValue));

                if (ringtone == null) {
                    // Clear the summary if there was a lookup error.
                    preference.setSummary(R.string.summary_choose_ringtone);
                } else {
                    // Set the summary to reflect the new ringtone display
                    // name.
                    String name = ringtone.getTitle(preference.getContext());
                    preference.setSummary(name);
                }
            }

        } else if (preference instanceof EditTextPreference) {
            if (preference.getKey().equals("key_gallery_name")) {
                // update the changed gallery name to summary filed
                preference.setSummary(stringValue);
            }
        } else {
            preference.setSummary(stringValue);
        }
        return true;
    }
};

/**
 * Email client intent to send support mail
 * Appends the necessary device information to email body
 * useful when providing support
 */
public static void sendFeedback(Context context) {
    String body = null;
    try {
        body = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        body = "\n\n-----------------------------\nPlease don't remove this information\n Device OS: Android \n Device OS version: " +
                Build.VERSION.RELEASE + "\n App Version: " + body + "\n Device Brand: " + Build.BRAND +
                "\n Device Model: " + Build.MODEL + "\n Device Manufacturer: " + Build.MANUFACTURER;
    } catch (PackageManager.NameNotFoundException e) {
    }
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"contact@androidhive.info"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Query from android app");
    intent.putExtra(Intent.EXTRA_TEXT, body);
    context.startActivity(Intent.createChooser(intent, context.getString(R.string.choose_email_client)));
}}

SettingsActivity.java
public class SettingsActivity extends  Fragment {
private static final String TAG = SettingsPrefActivity.class.getSimpleName();
/*public SettingsActivity() {
    // Required empty public constructor
}*/

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.setting_layout, container, false);
}

/*public boolean onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_main, menu);
    return true;
}
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        // launch settings activity
        startActivity(new Intent(SettingsActivity.this, SettingsPrefActivity.class));
        return true;
    }

    return super.onOptionsItemSelected(item);
}*/
}

pref_main.xml
<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="General">
    <EditTextPreference
        android:defaultValue="@string/default_gallery_storage"
        android:key="@string/key_gallery_name"
        android:summary="@string/default_gallery_storage"
        android:title="@string/title_gallery_storage" />

    <CheckBoxPreference
        android:defaultValue="true"
        android:key="@string/key_upload_over_wifi"
        android:summary="@string/summary_upload_over_wifi"
        android:title="@string/title_auto_upload" />

    <ListPreference
        android:defaultValue="3"
        android:dialogTitle="@string/title_upload_quality"
        android:entries="@array/pref_upload_quality_entries"
        android:entryValues="@array/pref_upload_quality_values"
        android:key="@string/key_upload_quality"
        android:summary="@string/summary_upload_video_quality"
        android:title="@string/title_upload_quality" />

</PreferenceCategory>

<PreferenceCategory android:title="@string/pref_title_notifications">

    <SwitchPreference
        android:defaultValue="true"
        android:key="@string/notifications_new_message"
        android:title="@string/title_new_notification_sound" />

    <RingtonePreference
        android:defaultValue="content://settings/system/notification_sound"
        android:dependency="notifications_new_message"
        android:key="@string/key_notifications_new_message_ringtone"
        android:ringtoneType="notification"
        android:summary="@string/summary_choose_ringtone"
        android:title="@string/pref_title_ringtone" />

    <SwitchPreference
        android:defaultValue="true"
        android:key="@string/key_vibrate"
        android:summary="@string/summary_vibrate"
        android:title="@string/title_vibrate" />
</PreferenceCategory>

<PreferenceCategory android:title="@string/pref_header_about">

    <Preference
        android:selectable="false"
        android:summary="@string/summary_about" />

    <Preference
        android:summary="@string/app_version"
        android:title="@string/title_version" />

    <Preference
        android:key="@string/key_send_feedback"
        android:summary="@string/summary_support"
        android:title="@string/title_send_feedback" />

    <!-- preference opens url in browser -->
    <Preference
        android:summary="@string/summary_faq"
        android:title="@string/title_faq">
        <intent
            android:action="android.intent.action.VIEW"
            android:data="@string/url_faq" />
    </Preference>

    <Preference android:title="@string/privacy_policy">
        <intent
            android:action="android.intent.action.VIEW"
            android:data="@string/url_privacy" />
    </Preference>

    <Preference android:title="@string/title_terms">
        <intent
            android:action="android.intent.action.VIEW"
            android:data="@string/url_terms" />
    </Preference>
</PreferenceCategory>
</PreferenceScreen>

menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="settings.MainActivity">

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
 </menu>

settings_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is Settings Page!! Coming Soon!"
    android:textSize="30dp"
    android:textStyle="bold"
    android:layout_centerInParent="true"/>
 </RelativeLayout>

MainActivity.java
public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {R.drawable.ic_action_name};
String[] tabTitle={"","All"};
int[] unreadCount={0,5,3,0,12,3,9,0};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    viewPager.setCurrentItem(1);

    setupTabIcons();
}

private View prepareTabView(int pos) {
    View view = getLayoutInflater().inflate(R.layout.custom_tab,null);
    TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
    TextView tv_count = (TextView) view.findViewById(R.id.tv_count);
    tv_title.setText(tabTitle[pos]);
    if(unreadCount[pos]>0)
    {
        tv_count.setVisibility(View.VISIBLE);
        tv_count.setText(""+unreadCount[pos]);
    }
    else
        tv_count.setVisibility(View.GONE);

    return view;
}

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);

        /*TabLayout.Tab tabitem = tabLayout.newTab();
        tabitem.setCustomView(prepareTabView(i));
        tabLayout.addTab(tabitem);*/

    for(int i = 1; i < unreadCount.length; i++)
    {
        /*TabLayout.Tab tabitem = tabLayout.newTab();
        tabitem.setCustomView(prepareTabView(i));
        tabLayout.addTab(tabitem);*/

        tabLayout.getTabAt(i).setCustomView(prepareTabView(i));
    }
    }

private TabLayout.OnTabSelectedListener onTabSelectedListener(final
ViewPager viewPager) {

    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new
ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new SettingsActivity(), "");
    adapter.addFragment(new AllTab(), "All");

    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="inc.apperz.passmanager.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@color/colorGreen"
        app:tabTextColor="@color/colorWhite"
        app:tabIndicatorColor="@color/colorWhite"
        app:tabGravity="fill"/>

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.constraint.ConstraintLayout>

Is there any possibility that I can include my main_menu.xml into my setting_layout.xml? such that it will get bind to my SettingsActivity.java?
If its possible, that would be great, but I tried that way and didn't find appropriate way to include it.
Can someone guide me to how to achieve this..

A: Try adding this to your fragment:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem item= menu.findItem(R.id.action_settings);
    item.setVisible(false);
    super.onPrepareOptionsMenu(menu);
    return true;
}


text:
Q: Unique Substrings in wrap around strings I have been given an infinite wrap around of the string str="abcdefghijklmnopqrstuvwxyz"  so it looks like
"..zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...." and another string p.
I need to find out how many unique non-empty substrings of p are present in the infinite wraparound string str?
For example: "zab"
There are 6 substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in str.

I tried finding all suffixes of p in a particular concatenation of the string str say for example: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
and as soon as i get a suffix which is a part of the above i add all its substrings to my result, as:
         for (int i=0;i<length;i++) {
             String suffix = p.substring(i,length);
             if(isPresent(suffix)) {
                 sum += (suffix.length()*(suffix.length()+1))/2;
                 break;
             } else {
                 sum++;
             }
         }

And my isPresent function is:
     private boolean isPresent(String s) {
            if(s.length()==1) {
                return true;
            }
            String main = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcde
fghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
            return main.contains(s);

        }

If the length of p is greater than my assumed concatenated string assumed in isPresent function, my algorithm fails!!
So how should i find the substrings irrespective of the the wrap around string str? Is there a better approach for this problem?

A: Some ideas/suggestions (not a full algo)

*

*you don't need to consider an infinite repetition of the wrap around string but only len(p)/len(repeating-fragment) + 1 (integral division) repetitions. Let's denote this string with S **

*if a substring sp of p is a substring of S, than any substrings of sp will be substrings of S
So the problem seems to reduce to:

*

*find sp (substring of both p and S) with the maximal length. This is called longest common substring and admits a dynamic programming solution with the complexity of O(n*m) (lengths of the two strings). The cited has a pseudo-code algo.

*repeat the above recursively with the 'remnants' of p after eliminating the longest common substring.

Now, you have a sequence of "longest common substrings". How many do you need to retain? I feel that the "longest common substring" may be used to trim down the need of brute-forcing every substring of any and all the above, but I'd need more time than I have available now.
I hope the sketch above helps.

** I might be wrong on the number of repetitions which need to be considered. If I am, then in any case there will be a maximal number of repetitions to be considered and there will be an S of minimal length that is sufficient for the purpose.


text:
Q: Windows Server 2008 R2 "Missing Operating System" on boot I have a demo server that I brought over with me to Berlin for TechEd 2009, I booted the server up after I arrived and I got a message saying "Missing Operating System".
I carried on the server and it didn't get jarred or bumped. It's running Windows 2008 Server R2 Enterprise with two Intel X25-M 160GB SSD drives.
I checked the connections to the drives and they're tight.  Anything I should troubleshoot?  I'm trying to get my hands on an OS disk so I can boot to the command prompt to see if I can see anything there.
Thank you

A: There are some possible reasons for this:

*

*The machine's BIOS doesn't detect the hard disk

*The boot hard drive is damaged

*Sector 0 of the hard disk has an damaged master boot record ( third-party programs or disk corruption can damage an MBR)

*An incompatible partition is marked as "active"

*A partition that contains the MBR is no longer active

If the MBR is corrupted, you could try to boot from the Windows installation DVD-ROM and use the
bootrec.exe

command. Here is a desciption of the utility: How to use the Bootrec.exe tool in the Windows Recovery Environment to troubleshoot and repair startup issues in Windows.

A: SSD's can fail just like anything else and NAND Flash based drives have some more interesting failure modes than other electronics as they are basically one huge exercise in managing statistical failure in the first place. Ars Technica published a nice overview of the history and state of the art of SSD storage this week that explains why.
Have you got any more details on the specific Intel SSD model (although if it's 128GB then I think it must be an X-25E) and whether you made any specific tweaks to the system. While the drives are excellent Intel have had issues with firmware releases, the most recent one for the X-25M G2 resulted in some drives getting bricked under Windows 7 (before it was pulled) and its likely that the same could happen with W2K8R2.
Are these set up as two standalone drives\RAID-0 or as a RAID-1 pack? If it's a RAID config then it's also possible that something went wrong at the controller level.


text: Q: How to interact with a Qt application widget from another Qt app? I am trying to get the text of a Qtextedit from an application written in QT (a chat messenger) using another QT app that i am writing code. After using Ranorex for UI automation test, I got the widget name and its properties. I would like to ask how I could interact with it? Just give me some guidelines and I will study . Thank you ~


text:
Q: How to retrieve ConfirmationToken in a .NET MVC 4 Web Application In my application I register an account using
public ActionResult Register(RegisterModel m){
    // validation

    string confirmationToken = WebSecurity.CreateUserAndAccount(m.email, m.Password, true);

    // send the token via email to confirm the email
    return View("WaitingForEmailVerification");
}

I want to implement a function that resend a second Confirmation email in case of failure of the first.
public ActionResult ResendConfirmationEmail(string username){
    // validation

    string confirmationToken = ...........

    // send the toke via email to confirm the email
    return View("WaitingForEmailVerification");
}

Is there any way with Membership class or WebSecurity to retrieve the confirmationToken?
Thanks in advance.


text:
Q: Let $M_i, i \in I$, be R-modules. Show that the (external) direct product $\prod_I M_i$ satisfies the following universal property Let $M_i, i \in I$, be R-modules. Show that the (external) direct product $\prod_I M_i$ satisfies the following universal property relative to the R-homomorphisms $\pi_j:\prod_I{M_i} \to Mj$ defined by $\{m_i\}_I \to m_j$ for all $j \in I$: Given an R-module $M$ and R-homomorphisms $g_j : M \to M_j$ for all $j \in I$, there exists a unique R-homomorphism $h:M → \prod_I M$ satisfying $g_j =π_j\circ h$ ,for all $j\in I$.
I have no idea how to start on this problem. Please help. Thanks!


text:
Q: How to display messages in every Indy event? I am working on a C++ Builder application using the Indy library. There are two main objectives:

*

*To perform a forward between a server and a client.

*To visualize the traffic and its decoding on a window (not console, windows app)

After implementing the solution described in:
Why do I need to send a message twice to trigger Indy's OnExecute event?
And modifying the solution to my needs, the application started to hang. Apparently, the application works well until I want to stop the TIdMappedPortTCP component or close the application.
As the application is small so far, I created a new project and started migrating portions of the code to try to identify the reason this is happening.
I was able to reproduce the undesired behaviour by just "printing" messages during Indy's events.
The OnExecute event has not been implemented yet (in the new project) which means that TCP data is flowing both ways.
This is my sync class implementation:
// TTextToDisplay.cpp
TTextToDisplay::TTextToDisplay() {
    lineToAdd = NULL;
    stringsToAdd = NULL;
}

TTextToDisplay::TTextToDisplay(String str) {
    lineToAdd = str;
    stringsToAdd = NULL;
}

void __fastcall TTextToDisplay::AddSingleLine(String str)
{
    lineToAdd = str;
}

void __fastcall TTextToDisplay::AddStringList(TStringList* strings)
{
    stringsToAdd = strings;
}

void __fastcall TTextToDisplay::DoSynchronize(){
            // Use the input parameters here...
        if (stringsToAdd)
            Form1->Display->Lines->AddStrings(stringsToAdd);
        else if (lineToAdd != NULL) {
            Form1->Display->Lines->Add(lineToAdd);
        }
}

Where Display is a TRichEdit control, lineToAdd is a String object and stringsToAdd is a TStringList.
Indy manages several events and I would like to add a text on each of them (if it's not forbidden by design or any other restriction).
I added this event:
void __fastcall TForm1::MITMProxyBeforeConnect(TIdContext *AContext)
{
    String tempStr;

    // displaying remote address.
    tempStr = "Received connection from " +
        AContext->Connection->Socket->Binding->PeerIP;
    TTextToDisplay *TextToDisplay = new TTextToDisplay(tempStr);
    TextToDisplay->Synchronize();
    delete TextToDisplay;
}

The application was working fine. Then I added this:
void __fastcall TForm1::MITMProxyDisconnect(TIdContext *AContext)
{
    String tempStr;

    // displaying remote address.
    tempStr = "Client disconnected"; TTextToDisplay *TextToDisplay =
        new TTextToDisplay(tempStr); TextToDisplay->Synchronize();
    delete TextToDisplay;
}

The application is still working fine. So I added one more
void __fastcall TForm1::MITMProxyConnect(TIdContext *AContext)
{
    String tempStr;

    // displaying remote address.
    tempStr = "Attempting to connect to the remote server " +
        MITMProxy->MappedHost + ":" + MITMProxy->MappedPort;
    TTextToDisplay *TextToDisplay = new TTextToDisplay(tempStr);
    TextToDisplay->Synchronize();
    delete TextToDisplay;

}

And now the application starts to hang.
Working fine means that I can close the TIdMappedPortTCP
MITMProxy->Active = False;

and reactivate it
MITMProxy->Active = True;

several times, receive some messages and then close the application without it becoming irresponsive.
I would like to keep the application as verbose as possible, so is there a better way to log every Indy event?
The application that I was originally working on was doing great until I add some custom display of the data. Then the problem appeared. I don't know if the cause is related but the behaviour is the same.
So my application instead of showing this string:
008460000000190210703800000EC00000164593560001791662000000000000080000000002104302040235313531353135313531353153414C4535313030313233343536373831323334353637383930313233

Now shows:
0000: 60 00 00 00 19 02 10 70 38 00 00 0E C0 00 00 16
0010: 45 93 56 00 01 79 16 62 00 00 00 00 00 00 08 00
0020: 00 00 00 02 10 43 02 04 02 35 31 35 31 35 31 35
0030: 31 35 31 35 31 53 41 4C 45 35 31 30 30 31 32 33
0040: 34 35 36 37 38 31 32 33 34 35 36 37 38 39 30 31
0050: 32 33

This is a TStringList because it's easier for me to add all those lines to the TRichEdit at once. I want a second TRichEdit to show the decoded message.
To give you an idea it would be something like this:
000 MsgType              : "0200"
001 BitMap               : "70 24 06 80 20 C0 06 10"
002 PAN                  : "4593560001791662"
003 ProcessingCode       : "000000"
004 TxnAmount            : "000000080000"
011 SystemTraceNo        : "000001"
014 ExpirationDate       : "2411"
022 POSEntryMode         : "520"
023 CardSequenceNo       : "000"
025 POSConditionCode     : "00"
035 Track2               : "4593560001791662=24111190000063900000"
041 TerminalID           : "00064600"
042 AcquirerID           : "000010585800001"
054 AddAmounts           : "0"
055 Field55              : "9F 26 08 35 C2 C4 DF B5 FC 7B 0E 9F 27 01 80 9F 10 07 06 01 0A 03 A0 B8 03 9F 37 04 C1 5C 4B 3B 9F 36 02 01 3A 95 05 00 80 00 80 00 9A 03 22 04 02 9C 01 00 9F 02"
060 Field60              : "00 00 08"
--------------------------------------------------------------
Field 55 by Tag:
9F26 AppCryptogram        : "35 C2 C4 DF B5 FC 7B 0E"
9F27 CryptogramInfoData   : "80"
9F10 IssuerAppData        : "06 01 0A 03 A0 B8 03"
9F37 UnpredictableNo      : "C1 5C 4B 3B"
9F36 AppTxnCounter        : "01 3A"
95   TermVerifResults     : "00 80 00 80 00"
9A   TxnDate              : "220402"
9C   TxnType              : "00"
9F02 AmountAuthNum        : "20"

A final consideration, I know apps that do the forwarding, and I know applications that decode, but I haven't seen apps that do both and that is why I want to create it. But, so far the hardest part has been the visualization. So I don't know if I am using the right tools or the right approach to build what I want. Any advice will be highly appreciated.

A: Indy servers are multi-threaded, and serrver shutdown is synchronous - it waits for the server's threads to fully terminate before returning to the caller.
TIdSync (and TThread::Synchronize() and equivalent) delegate to the main UI thread, blocking the calling thread until the main thread finishes processing the sync request.
So, you can easily get into a deadlock situation if you Synchronize with the main thread while the main thread is shutting down the server.  The main thread will be waiting on the server's threads, while a syncing thread will be waiting on the main thread.
So, your options are to either:

*

*Simply don't Synchronize at all during server shutdown.  Set a flag somewhere before starting the shutdown, and then look at that flag before performing a sync.  Although, this won't catch the scenario where the shutdown begins after a sync is already in flight.

*Don't perform a synchronous sync, perform an asynchronous sync instead (TIdNotify, TThread::Queue(), or equivalent).  There is no good reason to block your server threads waiting for the main thread to perform UI status updates.

*Shutdown the server in a separate thread, leaving the main thread free to process sync requests.


text:
Q: Chrome won't redirect back to URL after Authentication handling For at least a couple of years, I've been using code similar to this in my MVC solutions...
[Authorize]
public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
          ..........

Then in my Authentication code
myAuthenticationProperties = new Microsoft.Owin.Security.AuthenticationProperties();
myAuthenticationProperties.AllowRefresh = true;
myAuthenticationProperties.ExpiresUtc = DateTime.UtcNow.AddMinutes(60);
myAuthenticationManager.SignIn(myAuthenticationProperties, myClaimsIdentity);

return RedirectToAction("Index", "Home");

And in my Startup..
    public void Configuration(IAppBuilder app)
    {
        CookieAuthenticationOptions myAuthOptions = new CookieAuthenticationOptions();
        myAuthOptions.AuthenticationType = "ApplicationCookie";
        myAuthOptions.CookieHttpOnly = true;
        myAuthOptions.SlidingExpiration = true;
        myAuthOptions.LoginPath = new PathString("/Authentication/LogIn");

        //This is what was added for the Owin cookie "fix"
        myAuthOptions.CookieSameSite = SameSiteMode.Strict;
        myAuthOptions.CookieSecure = CookieSecureOption.Always;

        app.UseCookieAuthentication(myAuthOptions);
    }

And life has been dandy... until now. I've been chasing my tail all over the place trying to figure out why when I attempt to log in, sometimes it works, and other times it just hangs. Using some Debug Messages, I found that my Authentication process finishes, but when the RedirectToAction occurs, nothing happens.. just hangs.
Then I had a break through, I tried using IE and Edge and it seems to work every time. Only Chrome hangs and it does it at least 75% of the Time if not more.
** UPDATE **
I have used both Fiddler and Chrome's Debugging (Console and Network tabs) and when the RedirectToAction occurs, as far as the website is concerned it is done. However nothing, and I mean nothing, comes back on the network to my client (according to Fiddler and Chrome's Networking).
Yet, if I manually change the url to go back home, Chrome is happy, I'm now authenticated and my [Authorize] now allows the controller to load.
I have looked into the new Chrome cookie thing, and although the "fix" seems to be as clear as mud, I was able to find someone who used code to force the SameSite cookie to report something other than LAX. I implemented that, actually having it set to "Strict" and still.... Chrome Hangs.
** The Band-Aid **
I don't know how much time this is going to buy me, but I have kludged the problem by using a Javascript timer that when the user clicks the submit button, the timer starts, waits 6 seconds, and then redirects back to the Home/Index.
If the issue isn't there (IE, Edge) the Client redirects automatically before the timer gets a chance to take hold. If they are using Chrome and it decides to hang, 6 seconds later it will behave as if their browser is just slow and will also take them to the correct place.
** Fixed (maybe) **
So even though no network traffic can be seen coming back to the client, I ended up (in addition to my band-aid above), implementing some additional changes so now both the Owin and Asp.net cookies are reporting Secure and sameSite = Strict. This seems to make a difference with my problem, and in cases where it still wants to hang, my Timed re-direct finishes off the problem.
For those that may experience this oddity as well, the gist of the Cookie fix is this...

*

*Update your Owin packages to make sure you are using version 4.1

*Adjust your CookieAuthenticationOptions in your Startup.cs to the items I added above to make the Owin cookie compliant.

*Update the following in your Web.config to make your Asp.net cookie compliant
<system.web>
   <sessionState cookieSameSite="Strict" />
   <httpCookies requireSSL="true" />
</system.web>

Doing those 3 things, (along with running your project under SSL) will result in Chrome reporting both cookies as Secure and Strict.

A: Google made a change to how Chrome handles cookies without the SameSite attribute. Before, Chrome treated not having the SameSite attribute set on a cookie as the same as having SameSite=None, which meant the browser would accept all cookies. Now, they're treating it as having SameSite=Lax, which will only accept cookies from the same domain. To get the same effect as the old method, the attribute must be set as SameSite=None; Secure.
I can't tell if this is what's impacting you, but if this is the case you'll see an error in the Chrome console.

The official release was February 4th IIRC, but they're doing a phased rollout to judge an issues being caused.
Some resources:
Microsoft ASP.NET blog about the upcoming changes / Archived copy
Chromium Blog / Archived Copy