text:
Q: Database/code design for limiting hierarchical comments at certain level? I'm making small commenting app written in PHP as backend, React as frontend and PostgreSQL as database. I have table comment which holds all comments and it is self referencing table.
\d+ comment:
     Column      |           Type           | Collation | Nullable |               Default               | Storage  | Stats target | Description
-----------------+--------------------------+-----------+----------+-------------------------------------+----------+--------------+-------------
 id              | bigint                   |           | not null | nextval('comment_id_seq'::regclass) | plain    |              |
 website_page_id | bigint                   |           | not null |                                     | plain    |              |
 author_id       | bigint                   |           | not null |                                     | plain    |              |
 parent_id       | bigint                   |           |          |                                     | plain    |              |
 content         | text                     |           |          |                                     | extended |              |
 deleted_date    | timestamp with time zone |           |          |                                     | plain    |              |
 updated_date    | timestamp with time zone |           | not null |                                     | plain    |              |
 created_date    | timestamp with time zone |           | not null |                                     | plain    |

On the client side I make request to get all comments, backend makes recusrive query to database to grab all comments and return them in appropriate format, then I render it.
Here is JSON of parent comment:
{
    id: 1
    author_id: 1
    content: "Some content"
    created_date: "2019-05-29 06:11:43+00"
    depth: 0
    parent_id: null
    replies: [...]
    updated_date: "2019-05-29 06:11:43+00"
    website_page_id: null
}

So each comment as depth parameter, which I use to define identation (I don't nest comments recursively like comment -> replies -> comment -> replies, it is only comment and all its replies. I do extra processing on backend to make this form, PostgreSQL returns just data as it is with depth definition.
I have a form for creating new comments and replies to existing comments. So far replies can nest as far as it can go (not sure about database limitations).
Here are my concerns:

*

*I don't want to nest forever as it kills performance (I assume). Does it really? Also, it is resonable to limit it up to n level by default so it does not go off the screen on the client side.

*Not sure where and how to make limitation. Whether it should be on the database level, backend or client side?

I had only one idea how to solve it, but so far it does not seem to be elegant solution. Here it is:
Ignore that it nests on the database level and just limit identation on client side, so if I defined 5 level as maximum, then anything above that would have 5 level identation. It works, but it does not help the database performace.
I am pretty sure there are other possible ways to do this, help would be appreciated!

A: Recursive queries (when they take advantage of index) are really fast. It will probably take more time to nest the results in Javascript. The nesting limitation is more for the UI and not very difficult to fetch:
    with recursive
      comment_node (comment_id, parent_id, level) as (
        select comment_id, comment_parent_id, 1::int4 as level
        from comment
        where website_page_id = $*
        union all
        select c.comment_id, c.comment_parent_id, parent.level + 1 as level
        from comment as c
          inner join comment_node as parent
            on parent.comment_id = c.parent_id
            and parent.level < 5
      )
    select c.comment_id, cn.level, c.comment_parent_id, c.content, a.name, ...
    from comment as c
      join comment_node as cn
        using (comment_id)
      join author as a
        using (author_id)

Limiting the insertion of comments with a nesting level of 5 or more is probably not a meaningful database constraint as it does not break the data consistency.


text:
Q: django: The database driver doesn't support modern datatime types I am trying the connect the MSSQL server and pull the data from the SQL server.
I landed on below error.

"django.core.exceptions.ImproperlyConfigured: The database driver
  doesn't support modern datatime types."

Version:
Django: 2.2
Python: 3.7
django-pyodbc-azure-2.1.0.0
pyodbc-4.0.26
 DATABASES = {
     'default': {
         'ENGINE': 'sql_server.pyodbc',
         'HOST': 'server\\DB',
         'NAME': 'Archive',
         'USER': 'Admin',
         'PASSWORD': '*****',
         'PORT': '49422',

         'OPTIONS': {
             'driver': 'SQL Server',
             'dsn': 'Django',
             'extra_params': "Persist Security Info=False;server=server\\DB",
         },
     }
 }

A: The "SQL Server" ODBC driver that ships with windows is unaware of SQL Server data types introduced after SQL Server 2000 (e.g. date, time, datetime2, datetimeoffset). It is intended only for legacy applications and shouldn't be used for new development.
Instead, download and install the separately distributed ODBC driver. In addition to supporting newer data types, the newer drivers support TLS protocol enhancements and encryption features. The current ODBC driver as of this writing is the ODBC Driver 17 for SQL Server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JComboBox is throwing a NullPointerException when told to addItemListener() I am getting a NullPointerException on line 27 (listOfWindTurbines.addItemListener(new dropDownListener());) when I try to run my program. Please Help!
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class PlannerMain {
JFrame frame;
JButton makeMap;
JPanel panel;
JLabel outcome;
JComboBox listOfWindTurbines;
String[] windTurbineSpace = new String[10];
Integer[] windTurbineLengths = new Integer[10];
Integer[] windTurbineWidths = new Integer[10];
JTextField lengthOfRoom, widthOfRoom, widthObjectNeeds, lengthObjectNeeds;
int lengthOfRoomInt, widthOfRoomInt, widthObjectNeedsInt, lengthObjectNeedsInt, largerObjectMeasurement, numberOfItems, numberOfItemsShort;
public static void main(String[] args){
PlannerMain p = new PlannerMain();

}

public PlannerMain(){
    windTurbineLengths[0] = 1;
    windTurbineWidths[0] = 1;
    for(int i = 0;i<=9;i++){
    int wNum = i + 1;
    windTurbineSpace[i] = "Windturbine "+ wNum;
    }
    listOfWindTurbines.addItemListener(new dropDownListener());
    frame = new JFrame("Minecraft Land Planner");
    outcome = new JLabel();
    panel = new JPanel();
    makeMap = new JButton("Make Map");
    lengthOfRoom = new JTextField("Length of Room");
    widthOfRoom = new JTextField("Width of Room");
    widthObjectNeeds = new JTextField("Width Object Needs");
    lengthObjectNeeds = new JTextField("Length Object Needs");
    listOfWindTurbines = new JComboBox(windTurbineSpace);
    makeMap.addActionListener(new makeMapListener());
    frame.setSize(580,550);
    frame.add(panel);
    panel.add(makeMap);
    panel.add(lengthOfRoom);
    panel.add(widthOfRoom);
    panel.add(lengthObjectNeeds);
    panel.add(widthObjectNeeds);
    panel.add(listOfWindTurbines);
    panel.add(outcome);
    frame.setVisible(true);

}

class makeMapListener implements ActionListener{

    public void actionPerformed(ActionEvent e) {

        lengthOfRoomInt = Integer.parseInt(lengthOfRoom.getText());
        widthOfRoomInt = Integer.parseInt(widthOfRoom.getText());
        lengthObjectNeedsInt = Integer.parseInt(lengthObjectNeeds.getText());
        widthObjectNeedsInt = Integer.parseInt(widthObjectNeeds.getText());
        if(lengthObjectNeedsInt<=widthObjectNeedsInt){

            largerObjectMeasurement = widthObjectNeedsInt;

        }
        if(widthObjectNeedsInt<=lengthObjectNeedsInt){
            largerObjectMeasurement = lengthObjectNeedsInt;

        }
        numberOfItems = (lengthOfRoomInt/lengthObjectNeedsInt)*(widthOfRoomInt/widthObjectNeedsInt);
        outcome.setText(String.valueOf(numberOfItems));
        lengthOfRoom.setSize(30, 20);
        widthOfRoom.setSize(30, 20);
        widthObjectNeeds.setSize(30, 10);
        lengthObjectNeeds.setSize(100, 20);

        }

    }

class dropDownListener implements ItemListener{

    public void itemStateChanged(ItemEvent event) {
        if(event.getStateChange() == ItemEvent.SELECTED){
            lengthObjectNeeds.setText(Integer.toString(windTurbineLengths[listOfWindTurbines.getSelectedIndex()]));
            widthObjectNeeds.setText(Integer.toString(windTurbineLengths[listOfWindTurbines.getSelectedIndex()]));
        }

    }

}
}

A: You need to initialize the listOfWindTurbines variable, for example:
JComboBox listOfWindTurbines = new JComboBox();


text:
Q: Redirecting URL using GetHTMLElement in NiFi I have fetched the next url from an HTML page using GetHTTP and GetHTMLElement processor in NiFi. How do I use this fetched URL in another GetHTMLElement processor, because it does not take or consider attributes from its previous processor.
Version of NiFi:NiFi 1.1.1
Any answers would be helpful at the earliest.
Thanks

A: You could send the URL to an InvokeHttp processor which supports incoming flow files and you can set the "Remote URL" to expression language like "${HTMLElement}" or whatever the attribute name is where the url is.

A: As suggested by Bryan Bende,
I extracted the next url by setting the base URL and setting Attribute name as abs:href in GetHTMLElement and sent it to InvokeHTTP processor.Then I looped back the output of InvokeHTTP to the previous GetHTMLElement to extract further next URLs.
Setting Attribute name as abs:href in GetHTMLElement helps in forming the proper URL.In my case it helped in forming the full URL as:
www.abc.com/extracted_next_url

My base URL was:
www.abc.com

Thanks


text:
Q: How do you check a random number against multiple lists in Python? I'm making a little text-based game in python for school. I also play a lot of runescape, so I wanted to incorporate some chance instead of just forcing interactions with monsters. I have four different rarites (common 1/5, uncommon 1/15, etc.) I want to roll at each part of the dungeon to determine the level/difficulty of the monster before I give the user their input.
I tried to make it as simple and consise as possible by putting the rarities and ther respective ranges in a dictionary and then using a for loop to catch the rarity from the randint roll, but I can't figure it out.
rolls = {'common': list(range(1, 6)), 'uncommon': list(range(6, 21)), 'rare': list(range(21, 46)), 'omg': list(range(46, 146))}

chance = random.randint(1,146)
for i in rolls:
    if i == chance:
        print(i)

I have tried variations of loops, I've googled a ton, and now I'm getting an error: TypeError: unhashable type: 'list'

A: Combining some of the earlier remarks:

*

*Ensure that your 'rarities' are correctly weighted. If you want to assign ranges for the randomint, the most common result must have the largest weight.

*There is no need to create entire lists of integers to evaluate the random value. It is sufficient to store the beginning or the end value of each these ranges in order to evaluate further.

the resulting code can be something like:
from random import randint

# store for every label the end of the range
chance_labels = [
    ('common', 20),
    ('uncommon', 27),
    ('rare', 31),
    ('omg', 32)
]

# get the second value from the last tuple in chance_labels (32) is the max value to be 'rolled'
max_randint = chance_labels[-1][1]

chance = randint(1, max_randint)

# get the first tuple from chance_labels for which 'chance' is smaller than the end of the range
label = next(label for label, range_end in chance_labels if chance <= range_end)
print(f'{chance}: {label}')

note that in order to get a 1/5 chance of something to happen ('common' in your example), the other options must add up to 4/5. Meaning that the sum of the other chances must be 4 times bigger.


text:
Q: Use OverlayIdentifiers icons in namespace extension I develop namespace extension for windows explorer.
In my extension I use overlay icons, I implemented the interface:
IShellIconOverlay
int GetOverlayIndex(IntPtr pidl, out int iconIndex);
int GetOverlayIconIndex(IntPtr pidl, out int iconIndex);

In that function I use the function SHGetIconOverlayIndex to get icon overlay index in the image list from dll location and index.
My problem is that I have already icons in the list of Overlay Identifiers registry from another extension that I use and I want to use the same icons from my overlay icon extension to my namespace extension.
Currently the SHGetIconOverlayIndex function create new slot in the image list and it is well known that windows have limits of 14-15 overlay icons.
So How can I recycle my icons between those two extensions?

A: If 'SHGetIconOverlayIndex' function gives you a limited system imagelist, why not load icons from Overlay icon extension's resources using 'LoadLibrary'->'FindResource' or use 'ExtractIcon'. You can create your own imagelist in namespace extension and add your overlay image to this imagelist as overlay using 'ImageList_SetOverlayImage'.

A: MSDN says about SHGetIconOverlayIndex:

Note  After the image has been loaded into the system image list during initialization, it cannot be changed. The file name and index specified by pszIconPath and iIconIndex are used only to identify the icon overlay. SHGetIconOverlayIndex cannot be used to modify the system image list.

So just pass filename and index to SHGetIconOverlayIndex. Window will not create new slot and will use already created by overlay icon handler.


text:
Q: Interesting gun versus car fatality question I think I'm overthinking this problem, but it doesn't seem intuitive: if 184 million people drive daily resulting in 33,000 fatalities yearly, and there are 1.5 million gun owners who use their guns yearly, resulting in 776 unintentional fatalities yearly, what would be the equivalent fatality rate if adjusted for daily gun use?

A: It's impossible to answer this question sensibly without knowing more details about what "yearly gun use" means.  At one extreme, all gun owners use their guns every day, so "yearly gun use"="daily gun use".  At the other extreme, all gun owners use their guns one day per year, so if instead they used their guns every day, there would be 365 times as many unintentional fatalities each year, or 283,240.

A: The naive way: $184$ million, $33000$ fatalities = $179$ fatalities per year per million people. $776$ fatalities yearly naively becomes $776\times 365=283240$ fatalities per year = $188826$ deaths per year for daily usage per million people. Voilà! Guns are $1054$ times more deadly than cars.
Note that this is extremely naive. First of all, yearly gun users may not use their gun only once per year - that is quite unlikely (given most of them hunt a lot or practice at ranges a lot). Secondly, deaths with guns are usually 1. accidents 2. attacks. In the first case, using guns daily will improve skill a LOT (try finding a soldier who accidentally shot himself in the foot so hard he died). In the second case, murderers don't murder people as a linear function of gun uses (I WILL MURDER A PERSON EVERY 100TH TIME I USE A GUN MWAHAHA), but as a (roughly) linear function of people they unfortunately want to kill.


text:
Q: In Eclipse, how to maintain editor focus after opening a resource? Similarly related to this question.
As a Java developer, I'm frequently switching between classes. Using the open resource shortcut (Ctrl + Shift + R) has been an absolute time saver, and I use it very often. Recently, I switched from Windows XP/Eclipse Indigo to Ubuntu 12.04/Eclipse Juno. My setup consists of dual monitors with the Eclipse editor open on one and a few panels on the other (namely the console and package explorer). I've noticed, however, that when I open a resource using this setup, after the resource opens, the focus moves to one of the panels that I have 'broken' out and moved off to the side. It does this even though focus was previously in the editor window. Since I had been using Indigo previously on Windows, without issue, I thought perhaps it was an Juno issue, so I tried the same thing using Indigo on Ubuntu (using a plain, vanilla setup), but the issue persists. This leads me to believe that it's an Eclipse + Ubuntu (or GTK) issue. In Ubuntu, what determines who gets the focus when a dialog is dismissed?
I'm aware that there are shortcuts for refocusing to the editor, but unfortunately, this is a major distraction. Has anybody else faced a similar situation, and if so, how did you overcome it?


text:
Q: Nginx configuration for multiple domain names with same root folder I have configured nginx server request process on AWS as below:
The below code fragments are form custom conf file inside nginx
server {
    listen   80;
    server_name  abc.tk www.abc.tk;

    # note that these lines are originally from the "location /" block
    #root   /usr/share/nginx/html;
    #index index.php index.html index.htm;

    #location / {
        #try_files $uri $uri/ =404;
    #}

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Initially,  I had one domain(as above), It is working fine, But now I want to do the same redirection for another domain to the same root folder. By the way, I have not mentioned root folder here, it is coming from nginx.conf. I tried different approaches from reading the online sources but didn't get any success.
Below is what I am trying right now but it is not working. Giving me 521: web server down error. Also, I have used cloudflare for ssl for both the domain.
server {
    listen   80;
    server_name  abc.com www.abc.com abc.tk www.abc.tk;

    # note that these lines are originally from the "location /" block
    #root   /usr/share/nginx/html;
    #index index.php index.html index.htm;

    #location / {
        #try_files $uri $uri/ =404;
    #}

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Quick help would be appreciated. Thanks in advance!

A: Could you try this way:
server {
    listen   80;
    server_name  abc.com www.abc.com abc.tk www.abc.tk;

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
        location / {
            root /usr/share/nginx/html
            index  index.html index.htm index.php;
            try_files $uri $uri/;
        }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}


text:
Q: Интервал ListRow в Leaback Использую leanback библиотеку, как изменить отступ слева при построении рядов (ListRow)?

A: Я нашел, где я могу редактировать отступы на ListRow.
Идем в тему вашей активити и добавляем элемент
<item name="rowHorizontalGridStyle">@style/CustomHorizontalGridView</item>

И в стиле CustomHorHorizontalGridView можно редактировать отступы
<style name="HorizontalGridView">
<item name="android:focusable">true</item>
<item name="android:focusableInTouchMode">true</item>

<item name="android:paddingStart">@dimen/content_padding_horizontal</item>
<item name="android:paddingEnd">@dimen/content_padding_horizontal</item>

<item name="android:paddingBottom">@dimen/lb_browse_item_vertical_spacing</item>
<item name="android:paddingTop">@dimen/lb_browse_item_vertical_spacing</item>
<item name="android:horizontalSpacing">@dimen/lb_browse_item_horizontal_spacing</item>
<item name="android:verticalSpacing">@dimen/lb_browse_item_vertical_spacing</item>
<item name="focusOutFront">true</item>


text:
Q: How can I properly type a subclass of class which sub-types a Generic base class? I have two classes inheriting from dict, like this:
class A(dict):

class B(A):

This all works fine - the two classes use the inherited dict functionality and do other required stuff.  However, I also want to use type-hinting.  The first should reduce the range of the Dict generic and the second should reduce it further.  For example, I'd like to write something like:
class A(Dict[str, Any]):

class B(A[str, int]):

This works fine for A but not for B (that code is not syntactically correct, of course).
Class B isn't a sub-type of A (since it can't handle anything other than int) and that's fine but I do need it to inherit.  Can I get mypy to understand the correct type of B and still inherit from A?
The only solution I can see at present is to re-implement all the inherited methods from A but that would be a lot of runtime boiler-plate just to declare the correct typing.

A: So a little more thought and I think it's easy. I just need to move the shared functionality out of A and into a new generic which inherits from Dict.  Simple:
from typing import Generic, TypeVar, Dict, Any

KT = TypeVar('KT')
VT = TypeVar('VT')

class GenericA(Dict[KT, VT]):
    def my_method(self):
        print(list(self.values()))

A = GenericA[str, Any]

class B(GenericA[str, int]):
    def more_methods(self):
        print(list(self.keys()))

a = A({"a" : "blob", "b" : "blib"})
a.my_method()

b = B({"a" : 1, "b" : 2})
b.my_method()
b.more_methods()


text:
Q: jQueryUI, function on window close I've this function in jQuery:
    $("#bottone_mail").on("click", function(){
        $('#container_body').fadeTo(1000, 0.25);
        $( "#form" ).dialog({
            width:510,height:500});
            return false;

That creates a form window. When the user clicks the "Send" button, this script is executed:
        $("#invia").on("click", function(){
        $( "#form" ).dialog("close");
        $('#container_body').fadeTo(1000, 1);
        $("#spc1").html("
 Messaggio inviato con successo, grazie!
");
        return false;
        });

I want  $('#container_body').fadeTo(1000, 1); to be executed when the user closes the form window with the "X" button, other than when the "Send" button is pressed.
The only related answer I could find is this:
jQuery UI Dialog Box - does not open after being closed
It doesn't work for me, though, as a function name is required.
I'm at my first steps with jQuery, so I'd be very thankful if someone was to post a tailored solution with an explanation...

A: You can do it like this -
$("#form").on('dialogclose', function(event) {
   $('#container_body').fadeTo(1000, 1);
});

*

*http://api.jqueryui.com/dialog/#method-close

A: you have options when you create the dialog.
Maybe you can use something like:
$( "#form" ).dialog({
        width:510,
        height:500,
        close: function() {
                    $('#container_body').fadeTo(1000, 1);
        }
});


text:
Q: RabbitMq как ограничить количество обработки очереди в день? Только начал изучать RabbitMq, и мне нужно, ограничить количество выполнений в день до 200 как это можно сделать?
У меня есть определённое событие, которые вызывается при обработке очереди, мне нужно если кол-во обработанных сообщений уже больше 200 за день, то не вызвать это событие пока не наступит другой день.
public class RabbitMqConsumer : IRabbitMqConsumer
{
    private readonly IConnection _connection;
    private readonly IModel _channel;
    private readonly string _queueName;

    public RabbitMqConsumer(string uri, string queueName)
    {
        if (string.IsNullOrWhiteSpace(uri))
            throw new ArgumentNullException(nameof(uri));

        if (string.IsNullOrWhiteSpace(queueName))
            throw new ArgumentNullException(nameof(queueName));

        _queueName = queueName;

        IConnectionFactory connectionFactory = new ConnectionFactory
        {
            Uri = new Uri(uri)
        };

        _connection = connectionFactory.CreateConnection();

        _channel = _connection.CreateModel();

        _channel.QueueDeclare(_queueName, exclusive: false, autoDelete: false);
    }

    public event ProducerEventHandler? Producer;

    public void Start()
    {
        var consumer = new EventingBasicConsumer(_channel);

        consumer.Received += (sender, args) =>
        {
            var json = Encoding.UTF8.GetString(args.Body.ToArray());

            var request = JsonConvert.DeserializeObject<IndexApiRequest>(json);

            Console.WriteLine(request.Url);

            Producer?.Invoke(request);
        };

        _channel.BasicConsume(_queueName, true, consumer);
    }

    public void Dispose()
    {
        _channel.Dispose();
        _connection.Dispose();

        _channel.Close();
        _connection.Close();
    }
}


text:
Q: Undesired anti-aliasing when drawing bitmap on a window I'm rendering an image into a System.Drawing.Bitmap and subsequently drawing it into a window, however I can see that the edges are being anti-aliased. How do prevent this?
Some more detail. The bitmap is created like thus:
new Bitmap (this.Width, this.Height, Imaging.PixelFormat.Format32bppArgb)

I then set pixels to either Color.Black or Color.White. I've tried using both Bitmap.SetPixel and writing bytes directly to the bitmap data using Bitmap.LockBits.
Once the bitmap is ready I draw it in my Form.OnPaint override:
            pea.Graphics.DrawImage
                ( !this.bitmap
                , this.ClientRectangle
                , new Rectangle (0, 0, this.Width, this.Height)
                , GraphicsUnit.Pixel
                )

Every pixel should either black or white however I can see that pixels at the edges are grey.

A: Set the InterpolationMode property to NearestNeighbor and PixelOffsetMode to None.
pea.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
pea.Graphics.PixelOffsetMode = PixelOffsetMode.None; // or PixelOffsetMode.Half

Drawing the bitmap unscaled is best.  In which case you probably want to use the ClientSize.Width and Height properties to initialize the bitmap.  Odds are good that you are making the bitmap too large right now by including the form's border and caption.  I can't tell from the snippet.


text:
Q: Thymeleaf preprocessed expression cannot have brankets appended No matter whether I append () or () at the end of the preprocessed expression, Thymeleaf doesn't substitute the preprocessed expression with its value. Strange enough, But it looks Ok the preprocessed expression append "aa"
Here is the html:
<* href="javascript:void(0)" class="easyui-linkbutton" th:onclick="submit__${container.name}\__()" style="width:80px">Submit</*>
<* href="javascript:void(0)" class="easyui-linkbutton" th:onclick="submit__${container.name}__aa" style="width:80px">Clear</*>

Here is the html source after Thymeleaf transformed.
<* href="javascript:void(0)" class="easyui-linkbutton" onclick="submit__${container.name}__()" style="width:80px">Submit<*/>
<* href="javascript:void(0)" class="easyui-linkbutton" onclick="submitformaa" style="width:80px">Clear</*>

Please help me out of this as it drives me to the wall. Thanks


text:
Q: Implementing stateless NPC scripting with coroutines/C# 5's await I'm trying to implement NPC scripting using C#'s new await feature. This is my proof of concept.
In NPC.cs you can see this snippet:
public async void Run(INPC npc)
{
    npc.Say("Hello!");
    await npc.WaitForOk();
    npc.Say("This is an example of some weird crap.");
    await npc.WaitForOk();
    npc.Say("Bye.");
    await npc.WaitForOk();
}

In a real example the script would be implemented in a scripting language like IronPython. Even though it may support the async/await keywords in the future, having to do that for every call is very troublesome and annoying.
I've tried having another method be async and do the await, and having the script simply call that, but due to the way async/await works, the script method (Run) would simply continue without pausing/blocking.
Is there a way to avoid having to make the script method async and having to use await in front of each call, while still retaining coroutine-like functionality?
Also, if there is a better solution to this already available than to use async/await while still being thread-efficient, please highlight it.
Thanks!

A: That's a very interesting use for async/await.
I've compiled a lot of syntax-related questions from around the web into one of my blog posts. In short, there are good reasons why async and await are both required.
If you're willing to add state to your NPCs, consider using an observer-based approach (Rx). This approach is capable of complex interactions, and could also allow parallel execution of different NPCs.
You could also pattern your NPCs on threadpool tasks, which are pretty efficient - when they block, the CPU is made available for other tasks.

A: I'm not sure why are you trying to avoid await so hard. I think it's a good idea to require it for this kind of code, because it would be hard to tell what the code actually does otherwise. So, my opinion is that using await this way is probably your best option.
Also, it's a good idea to avoid async void methods, if you can, since you can't catch exceptions they throw.
I can imagine there are ways to avoid writing async, like:
npc.AddAction(n => n.Say("Hello!"))
   .AddAction(n => n.WaitForOk())
   .AddAction(n => n.Say("This is an example of some weird crap."))
   .AddAction(n => n.WaitForOk());

npc.Run();

Here, Run() processes the list of actions built using AddAction() and uses await where necessary.
But I doubt you can make it as simple as your code with awaits. (Also, implementing any kind of control flow in a code like this would make it really unreadable.)


text:
Q: Google Cloud Datastore Index not found even if it is set I have a kind named 'audit' and has many properties however, I need to index only certain properties and in a specific order since I mostly query:
select DISTINCT ON (traceId) * from audit where tenantId='123'

When I try to run this in the GCP console it throws an error:
GQL Query error: Your Datastore does not have the composite index (developer-supplied) required for this query.
I also tried running this from a node js application that uses @google-cloud/datastore package, and datastore throws error:
9 FAILED_PRECONDITION: no matching index found. recommended index is:
- kind: audit
  properties:
  - name: tenantId
  - name: traceId

The index.yaml is created using terraforms and the contents are:
indexes:
- kind: "audit"
  properties:
  - name: "tenantId"
  - name: "traceId"
# AUTOGENERATED
# This index.yaml is automatically updated whenever the Cloud Datastore
# emulator detects that a new type of query is run. If you want to manage the
# index.yaml file manually, remove the "# AUTOGENERATED" marker line above.
# If you want to manage some indexes manually, move them above the marker line.

With this index.yaml file the local datastore emulator works as expected.
In the GCP console, I see the index being set and is in serving status.

A: It seems you have additional quotes,  " around your Datastore property names in the index.yaml file.
indexes:

- kind: Cat
  properties:
  - name: name
  - name: age

Please refer to the documentation on correct syntax.
On the Google Provider Terraform side, there is a ~> Warning mentioned, make sure to follow it to create a compatible database type. Refer here for more details on compatibility settings.


text:
Q: Mac OS X 10.5 Apache and Subversion upgrade alternatives I've found myself down a rabbit hole and would like advice.  It looks like Mac OS X 10.5.8 comes bundled with a pre-configured version of Apache 2.2.11 (located in /usr/sbin), PHP 5.2.10 (located in /usr/bin) and subversion 1.4.4 (located in /usr/bin).  I have installed MAMP for MySQL 5.0.41 (located in /Applications/MAMP/...) which comes with Apache 2.0.59 and PHP 5.2.6.  The current version of MySQL is 5.1 (mysql.com).  I have also installed the latest Subversion binaries 1.6.5 (they get located in /opt/subversion/...).  This is becoming a mess. Ideally I would like to have one copy each of Apache, PHP, MySQL, and Subversion and have them all be the latest release and have them work together properly.  Are there configuration pitfalls specific to the Mac that I need to watch for if I install the newest binaries of Apache in /usr/sbin, PHP5 in /usr/bin, subversion in /usr/bin, and Mysql in /usr/bin (or /usr/local/bin)? Am I just asking for trouble?

A: Do not install ANYTHING in /usr/bin or /usr/sbin.  Those are managed by Apple and you can get yourself and your system in trouble when you start modifying stuff there.  Other than a bit of wasted disk space, there's normally no problem with having more than one copy of things like Apache.  Just accept it.
If you need newer or missing versions of open source packages, you might want to look into using MacPorts or Fink to supplement what's provided by Apple.

A: My personal preference is just not to do this development on my Mac at all, and instead run a Linux Virtual Machine using VMWare Fusion, VirtualBox or similar.  One of thes nice things about VMWare Fusion 2 (not 3 though, bizarrely) is that you can run these virtual machines in headless mode, and simply SSH into them via terminal on your Mac.
The benefit to me here is that my VMs are able to very closely mirror the setup of my production machines, I'm able to closely control what software is actually installed on them, and if I need to work on a new machine I can simply copy the VM from one machine to another.  I can also easily take snapshots of the VM at any point, and roll back to them if I do manage to muck something up.
Here's a good guide to using VMWare Fusion for doing development on OSX.

A: I have been developing for the LAMP stack on a Mac for bit over 4 years now. I have tried pretty much every flavor of the stack on the Mac.

*

*Native: Not viable, because it's an old codebase.

*MacPorts: I ran into trouble with OS X updates.

*Self Compiled: Same as with the MacPorts, I ran into trouble with OS X updates.

*MAMPP: I didn't like this package, yet this is a personal dislike. I kind of disliked it's freemium like style. The package is not easily configurable, except using the commercial configuration software.

*XAMPP: I ended up sticking with XAMPP.

About XAMPP:
The XAMPP code base is rather up to date. With the Developer Package, you get all the tools necessary to compile additional extensions. Everything is configured in /Applications/XAMPP/etc/.


text:
Q: send touch event to UIviewController stacked in the back In my app I have 2 transparent UIViewController layers.
the first layer contain UIView object that i am trying to recognize by touch with:
 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;

method.
the problem is,
there is an transparent UIViewController above it.
I have tried to implement touch event on the SeconedStackedViewController and to create an instance of FirstStackedViewController and call the same method from there. the methods are called, but the hit test not.
Code:
FirstStackedViewController *fsvc = [[FirstStackedViewController alloc]init];

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
      [fsvc hitTest:point withEvent:event];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
      fsvc = [[FirstStackedViewController alloc]init];
      [fsvc touchesEnded:touches withEvent:event];
}

How can I override this method to be called on the FirstStackedViewController?
if i will can simulate a touch on the FirstStackedViewController i think it will make the work

A: My first question is why you are pushing a transparent view controller. Might your needs be better served by layering a transparent view within the same controller?
Without looking at your requirements, it's hard to say for sure, but most likely this is more in accord with the usual separation of logic: you have a need for code that can receive input from one view and pass it to other logic. It has need to know about the internals of both, and therefore is a good candidate for a controller object with the knowledge needed to accomplish your task.
In this case, you would have no trouble at all - just present your transparent view, and pass touches to whatever action you wish.
But there are good reasons to do a VC with a transparent view. To access the VC beneath you, you can as another responder said access the app delegate. I'd keep the app delegate out of it, and just access self.navController.viewControllers. This array represents the stack of VCs. Then iterate downward - the one 'below' you is the one you want to relay the message to.
Most likely rather than using isMemberOfClass you'd want to define a protocol and check whether the VC conformsToProtocol.
for (int i=0; i < navBar.viewControllers.count ; i++) {
   UIViewController *current = navBar.viewControllers[i];
   if (current == self) {
      UIViewController *targetVC = navBar.viewControllers[i+1]; // make sure you're not over bounds - you could do this in the loop def'n.
      if ([targetVC class] conformsToProtocol("TransparentPassingActions")]) {
         // pass message
      }
   }
}

You can also just use indexOfObject to get the current VC, I suppose, and then look one lower. That gets rid of the loop.
The pseudo-code in the previous answer confuses UIViews and UIViewControllers, by the way; perhaps this was clear to you. It is not possible to access view controllers by accessing views.

A: I'd start by getting a refernce to the rootViewController.  I'm assuming your hierarchy is root ->1st view controller --> 2nd view controller, then by initing fsvc you are creating a new instance and you are not actually getting the reference from the view hierarchy.
I'd recommend iterating through rootviewcontroller subviews and find your instance for first viewcontroller, then call the method on that instance.
//PSEUDO-Code for class names, but iteration should solve the problem.
if(UIView *view in RootViewController.subviews){
     if(view isMemberOfClass: [FirstStackedViewController class]]){
          [(FirstStackedViewController *)view touchesEnded:touches withEvent:event];
     }
}

//ToolUser was right about mixing up VCs and regular Views, you'd want to do this:
for(UIViewController *vc in self.navigationController.viewControllers){
        if(view isMemberOfClass: [FirstStackedViewController class]]){
              [(FirstStackedViewController *)vc touchesEnded:touches withEvent:event];
         }
}


text:
Q: Download PDF from SQL Server database I have searched for answers and it seems everything is asp.net and webforms.
I'm trying to find an entity/MVC solution I have to assume they are similar.
I have a database which has the info for the file stored in SQL Server datatype Image. I already have all the code to attach to files to the right people as needed. The only thing I am missing is how to build the Download link.
The HTML View will look like this.
The information about the document will be in a table containing information like document name, type etc.  It will also have a Download link.  Once they click this link I would like to have the file served to them for download.
This is the part that escapes me when doing it in MVC. I have the document in a model incoming_file is the column that contains the document.
How do I force the download of everything in incoming_file when they click Download?


text:
Q: read-only input while page load How to make <input type="text" name="mynumber" value="456" /> read-only while my page is loading?

A: <input type="text" name="mynumber" value="456" readonly="readonly" />

<script>
$(document).ready(function() {
    $("input[name='mynumber']").attr("readonly", false);
});
</script>

A: Disable it using disabled="true"
document.getElementById("t1").disabled=true

<input type="text" name="mynumber" id="t1" value="456" disabled="true"/>


text:
Q: Asignación de variables Cordial saludo.
En mi sitio web tengo varios campos para registrar los códigos id de las llantas de un vehículo en el momento en que se montan estas. eso quiere decir que cuento con 4 campos.
Cuando el usuario ingresa los campos, (que pueden ir de 1 a 4), y da ejecutar, estos ID quedan asignados en 4 variables que definí así:
$IDM1=$_POST['IDM1'];
$IDM2=$_POST['IDM2'];
$IDM3=$_POST['IDM3'];
$IDM4=$_POST['IDM4'];

Luego deseo saber, cuantas campos registro el usuario, para lo cual realizo lo siguiente:
$iM=0;
for ($i=1; $i<=4; $i=$i+1) {
   $IDM='IDM'.$i;
   while ($$IDM!="") {
   $iM=$iM+1;
   break;
   }
}

Ahora en este punto, deseo insertar los datos que registro el usuario para lo cual hago lo siguiente:
for ($i=1; $i<=4; $i=$i+1) {
$IDM='IDM'.$i;
   while ($$IDM!="") {
   $sql_queryIDMN="INSERT INTO [dbo].[Llan]
   (id,usuario,FechaIngreso)  Values
   ('$$IDM','$Usu',GETDATE())";
   $stmlInserIDMN=sqlsrv_query($con,$sql_queryIDMN);
   break;
   }
}

Cuando hago una prueba, identifico que el contador de llantas registradas por el usuario esta bien y los ciclos FOR y WHILE funcionan Ok, pero encuentro el siguiente problema:
Supongamos que el usuario solo registra una llanta cuyo dato registrado es 1039, la cual queda asignada a la variable $IDM1.
Yo pensaba que al poner $$IDM en el INSERT, me iba a salir el dato 1039, pero me sale es $IDM1, ósea que lo que me sale es:
$sql_queryIDMN="INSERT INTO [dbo].[Llan]
(id,,usuario,FechaIngreso)  Values
('$IDM1','prueba',GETDATE())";

cuando realmente lo que necesitaba que saliera era:
$sql_queryIDMN="INSERT INTO [dbo].[Llan]
(id,,usuario,FechaIngreso)  Values
('1039','prueba',GETDATE())";

Agradezco me indiquen como puedo hacer para obtener lo que deseo

A: Para evaluar una variable variable dentro de una cadena puedes usar la sintáxis compleja:
$sql_queryIDMN="INSERT INTO [dbo].[Llan]
   (id,usuario,FechaIngreso)  Values
   ('${$IDM}','$Usu',GETDATE())";

Sin embargo, te ahorras mucho usando simplemente arreglos.
En el formulario:
<form ...>
   <input type="text" name="idm[]">
   <input type="text" name="idm[]">
   <input type="text" name="idm[]">
   <input type="text" name="idm[]">
   ...
</form>

Y al procesar el formulario:
$idm = null;
$sql = "INSERT INTO [dbo].[Llan] (id, usuario, FechaIngreso)
          VALUES( ?, ?, GETDATE() )";
// En este punto se asume que ya tienes declarado $Usu
$stmt = sqlsrv_prepare( $conn, $sql, array( &$idm, &$Usu ) );
foreach( $_REQUEST['idm'] as $idm ){   // Recorres cada idm
    sqlsrv_execute( $stmt );
    ...
}

Aprovechando las bondades de las sentencias preparadas.


text:
Q: Best orthogonal approximation of rank 1 matrix Let $X=\lambda_0u_0v_0^T\in\mathbb{R}^{n\times n}$ be a rank 1 matrix where $\lambda_0\in\mathbb{R}$, $u_0,v_0$ are of unit Euclidean norm. What is the solution of the following problem?
$$\hat{X}=\arg\min_{\substack{Y:Y=aU\\U\in O(n)\\a\in\mathbb{R}}}\|Y-X\|_F^2$$
where $U$ is orthogonal and $\|\|_F$ is the Frobenius norm. In other words, what is the best scaled orthogonal approximation of rank 1 matrix?

A: As suggested by Federico Poloni in a comment, it suffices via the SVD to consider the case when $X$ has $x_{1,1} > 0$ and $x_{i,j} = 0$ when $(i,j) \neq (1,1)$. Then for any orthogonal matrix $U$ with columns $\mathbf{u}_1,\ldots,\mathbf{u}_n$ and scalar $a \in \mathbb{R}$ we have
\begin{align*}
    \|X - aU\|_F^2 & = \|x_{1,1}\mathbf{e}_1 - a\mathbf{u}_1\|^2 + \sum_{j=2}^n\|a\mathbf{u}_j\|^2 \\
    & = \big(x_{1,1}^2 - 2ax_{1,1}u_{1,1} + a^2\big) + \big(\sum_{j=2}^na^2\big) \\
    & = x_{1,1}^2 - 2ax_{1,1}u_{1,1} + na^2,
\end{align*}
where $\mathbf{e}_1 \in \mathbb{R}^n$ is the first standard basis vector. There is only one term in this expression that depends on $U$ at all, so (for any given value of $a$) it is minimized when we make $u_{1,1}$ as large as possible (i.e., $u_{1,1} = 1$). The remaining columns of $U$ are arbitrary (but of course must be orthogonal to the first column $\mathbf{e}_1$).
Our goal is then to minimize
\begin{align*}
    x_{1,1}^2 - 2ax_{1,1} + na^2,
\end{align*}
which is a quadratic in $a$ with vertex (i.e., minimum) at $a = x_{1,1}/n$.


text:
Q: Setting Layer Properties Using ArcPy I am writing an ArcPy script that creates a Point Density Raster file, and then changes the following properties in the resulting layer:

*

*Symbology
Classified
Classes = 10
Classification Method = Geometrical Interval
Excluded Value = 0

*Display
Resample during display using:  bilinear interpolation
I know I can set lyr.symbology.numClasses = 10. and lyr.symbology.excludedValues = 0, and even create a dummy layer with the above properties (symbologyLayer) and arcpy.ApplySymbologyFromLayer_management(lyr, symbologyLayer).  Is there a way to do this simply by setting attributes of lyr.symbology, do I have to do it in one fell swoop with ApplySymbologyFromLayer_management, or is there a better way?

A: If you're writing a geoprocessing script, I'd recommend authoring a .lyr file you bundle with your toolbox and set the symbology in the script tool parameters to point to the .lyr file (see the "Symbology" part of the dialog).


text:
Q: Is there a "Script table as - MERGE" function somewhere? In SSMS 2008 R2, when I right click on a table I see "Script Table as" then options for Insert and Update.  But what about Merge?  Merge is really just the two of these together.
Is there any tool I can get that will add that option?  (So I can script a merge statement ready for me to add in source information (kind of like the Insert and Update scripts are ready for adding the data to insert or update).

A: There is no built-in functionality in SSMS that performs such operation(I guess it may be possible with external plugin).
There is a procedure sp_GenMerge(licensed under MIT license) written by Michał Gołoś that allows to script table with data as merge statement.
Sample scenario:
CREATE TABLE [Customer]  (
   ID                   INT                  IDENTITY(1,1) CONSTRAINT PK_CUSTOMER PRIMARY KEY (ID),
   FIRSTNAME            NVARCHAR(30)         NOT NULL,
   LASTNAME             NVARCHAR(30)         NOT NULL,
   CITY                 NVARCHAR(30)         NULL,
   COUNTRY              NVARCHAR(30)         NULL,
   PHONE                NVARCHAR(20)         NULL
);

INSERT INTO [Customer] ([FirstName],[LastName],[City],[Country],[Phone])
VALUES('John','Smith','Berlin','Germany','12345'),('Cathrine','Fa','Brasilia','Brasil','(3) 4324-4723');

Basic SP call(it supports more options - see doc):
EXEC sp_GenMerge @source_table = 'dbo.Customer';

Output:
DECLARE @xml XML = N'
<!-- Insert the generated data here -->
';

MERGE INTO dbo.Customer AS Target
USING (SELECT x.value('(@ID)', 'int') AS [ID]
            , x.value('(@FIRSTNAME)', 'nvarchar(30)') AS [FIRSTNAME]
            , x.value('(@LASTNAME)', 'nvarchar(30)') AS [LASTNAME]
            , x.value('(@CITY)', 'nvarchar(30)') AS [CITY]
            , x.value('(@COUNTRY)', 'nvarchar(30)') AS [COUNTRY]
            , x.value('(@PHONE)', 'nvarchar(20)') AS [PHONE]
        FROM @xml.nodes('v') AS t(x)) AS Source ([ID], [FIRSTNAME], [LASTNAME], [CITY], [COUNTRY], [PHONE])
  ON (Target.[ID] = Source.[ID])
WHEN NOT MATCHED BY TARGET
THEN INSERT([FIRSTNAME]
          , [LASTNAME]
          , [CITY]
          , [COUNTRY]
          , [PHONE])
     VALUES(Source.[FIRSTNAME]
          , Source.[LASTNAME]
          , Source.[CITY]
          , Source.[COUNTRY]
          , Source.[PHONE])
WHEN MATCHED AND EXISTS (SELECT Target.[FIRSTNAME]
                              , Target.[LASTNAME]
                              , Target.[CITY]
                              , Target.[COUNTRY]
                              , Target.[PHONE]
                         EXCEPT
                         SELECT Source.[FIRSTNAME]
                              , Source.[LASTNAME]
                              , Source.[CITY]
                              , Source.[COUNTRY]
                              , Source.[PHONE])
THEN UPDATE SET Target.[FIRSTNAME] = Source.[FIRSTNAME]
              , Target.[LASTNAME] = Source.[LASTNAME]
              , Target.[CITY] = Source.[CITY]
              , Target.[COUNTRY] = Source.[COUNTRY]
              , Target.[PHONE] = Source.[PHONE];
GO

And scripted rows as XML payload:
<v ID="1" FIRSTNAME="John" LASTNAME="Smith" CITY="Berlin" COUNTRY="Germany" PHONE="12345" />
<v ID="2" FIRSTNAME="Cathrine" LASTNAME="Fa" CITY="Brasilia" COUNTRY="Brasil" PHONE="(3) 4324-4723" />

A: Until i know you can´t but there are some tips:
How to edit SSMS Script Table As templates?

A: There is a very useful script on GitHub that I've been using with great success.
Generate SQL MERGE statements with Table data
Use Cases:

*

*Generate statements for static data tables, store the .SQL file in source control/add it to a Visual Studio Database Project and use it as part of your Dev/Test/Prod deployments. The generated statements are re-runnable, so you can make changes to the file and easily migrate those changes between environments.

*Generate statements from your Production tables and then run those statements in your Dev/Test environments. Schedule this as part of a SQL Job to keep all of your environments in-sync.

*Enter test data into your Dev environment, and then generate statements from the Dev tables so that you can always reproduce your test database with valid sample data.

How Does It Work?
The generated MERGE statement populates the target table to match the source data. This includes the removal of any excess rows that are not present in the source.
When the generated MERGE statement is executed, the following logic is applied based on whether a match is found:

*

*If the source row does not exist in the target table, an INSERT is performed

*If a given row in the target table does not exist in the source, a DELETE is performed

*If the source row already exists in the target table and has changed, an UPDATE is performed

*If the source row already exists in the target table but the data has not changed, no action is performed (configurable)

Usage:

*

*Ensure that your SQL client is configured to send results to grid.

*Execute the proc, providing the source table name as a parameter

*Click the hyperlink within the result set.

*Copy the SQL (excluding the Output tags) and paste into a new query window to execute.

Example:
To generate a MERGE statement containing all data within the Person.AddressType table, excluding the ModifiedDate and rowguid columns:
EXEC AdventureWorks.dbo.sp_generate_merge @schema = 'Person', @table_name ='AddressType', @cols_to_exclude = '''ModifiedDate'',''rowguid'''

OUTPUT:
SET NOCOUNT ON
GO
SET IDENTITY_INSERT [Person].[AddressType] ON
GO
MERGE INTO [Person].[AddressType] AS Target
USING (VALUES
  (1,'Billing')
 ,(2,'Home')
 ,(3,'Main Office')
 ,(4,'Primary')
 ,(5,'Shipping')
 ,(6,'Contact')
) AS Source ([AddressTypeID],[Name])
ON (Target.[AddressTypeID] = Source.[AddressTypeID])
WHEN MATCHED AND (
    NULLIF(Source.[Name], Target.[Name]) IS NOT NULL OR NULLIF(Target.[Name], Source.[Name]) IS NOT NULL) THEN
 UPDATE SET
 [Name] = Source.[Name]
WHEN NOT MATCHED BY TARGET THEN
 INSERT([AddressTypeID],[Name])
 VALUES(Source.[AddressTypeID],Source.[Name])
WHEN NOT MATCHED BY SOURCE THEN
 DELETE;

SET IDENTITY_INSERT [Person].[AddressType] OFF
GO
SET NOCOUNT OFF
GO


text:
Q: RecyclerView click listener best practice and without memory leaks I can't figure out why RecyclerView is such recommended, i am getting so many memory leaks. Most of it are Library Leaks which are out of my control (please correct me if i am wrong) but now i got a memory leak from the the ClickListener. I looked at google and i can't figure out the best practice for click Listeners since their are so many approaches. oh why did android didn't add a simple solution??
The last Click Listener approach i tired was from the next Youtube Link
RecyclerView OnClickListener (Best practice way) - is it really???
The difference from my implementation and the video was that i made the ViewHolder static but that was only since the android documentation in the next link (which btw i only changed because i had some Library leaks and i thought it might fix it)
Android recyclerView documentation
Here is the code:
    public class CollaborateAdapter
extends FirestoreRecyclerAdapter < FireContact, CollaborateAdapter.CollaborateViewHolder > {

    private Glist mGlist;
    private ClickListener mOnClickListener;

    CollaborateAdapter(@NonNull FirestoreRecyclerOptions < FireContact > options, Glist glist, ClickListener listener) {
        super(options);
        mOnClickListener = listener;
        mGlist = glist;
    }

    public interface ClickListener {
        void onClick(int i);
    }

    @NonNull
    @Override
    public CollaborateViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_collaborate, parent, false);

        return new CollaborateViewHolder(view, mOnClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull CollaborateViewHolder holder, int position,
        @NonNull FireContact model) {
        holder.mNameTextView.setText(model.getNa());
        holder.mPhoneTextView.setText(model.getPho());

        if (isCollaborator(model.getFuid())) {
            holder.mAddImageView.setImageResource(R.drawable.baseline_remove_circle_24px);
        } else {
            holder.mAddImageView.setImageResource(R.drawable.baseline_add);
        }
    }

    boolean isCollaborator(String contactUid) {
        //.....
    }

    void updateGlist(Glist glist) {
        mGlist = glist;
        notifyDataSetChanged();
    }

    public static class CollaborateViewHolder extends RecyclerView.ViewHolder
    implements View.OnClickListener {
        TextView mNameTextView;
        TextView mPhoneTextView;
        ImageView mAddImageView;

        ClickListener mListener;

        CollaborateViewHolder(@NonNull View itemView, ClickListener clickListener) {
            super(itemView);
            mNameTextView = itemView.findViewById(R.id.list_collaborate_name_tv);
            mPhoneTextView = itemView.findViewById(R.id.list_collaborate_phone);
            mAddImageView = itemView.findViewById(R.id.list_collaborate_add_iv);
            mListener = clickListener;
            mAddImageView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.list_collaborate_add_iv) {
                mListener.onClick(getAdapterPosition());
            }
        }
    }
}

And here is the memory leak
┬───
│ GC Root: Local variable in native code
│
├─ android.net.ConnectivityThread instance
│    Leaking: NO (PathClassLoader↓ is not leaking)
│    Thread name: 'ConnectivityThread'
│    ↓ ConnectivityThread.contextClassLoader
├─ dalvik.system.PathClassLoader instance
│    Leaking: NO (CollaborateAdapter↓ is not leaking and A ClassLoader is never leaking)
│    ↓ PathClassLoader.runtimeInternalObjects
├─ java.lang.Object[] array
│    Leaking: NO (CollaborateAdapter↓ is not leaking)
│    ↓ Object[].[1559]
├─ com.android.rangroceryshopping.collaborate.CollaborateAdapter class
│    Leaking: NO (a class is never leaking)
│    ↓ static CollaborateAdapter.mOnClickListener
│                                ~~~~~~
╰→ com.android.rangroceryshopping.collaborate.CollaborateActivity instance
     Leaking: YES (ObjectWatcher was watching this because com.android.rangroceryshopping.collaborate.CollaborateActivity received Activity#onDestroy() callback and Activity#mDestroyed is true)
     key = 2ac23d62-e7b9-49c8-b881-b8f32592027a
     watchDurationMillis = 5353
     retainedDurationMillis = 351

METADATA

Build.VERSION.SDK_INT: 28
Build.MANUFACTURER: samsung
LeakCanary version: 2.2
App process name: com.android.rangroceryshopping
Analysis duration: 19112 ms


text:
Q: What are the best debugging techniques available in visual studio 2008 to save a lot of time finding the exact reason of the problem? What are the best debugging techniques available in visual studio 2008 to save a lot of time finding the exact reason of the problem?

A: The number one feature I find useful, especially when debugging other people's buggy software, is turning on break on exceptions.
see this MSDN link for further information.

A: I tend to make liberal use of the Immediate window and conditional breakpoints especially. Walking up the Call Stack is also a good idea to get some context of your code's execution.
When debugging data access stuff, you can use the Text Visualiser window to get the value of your sql query string literals without having to strip out all the escape sequences (\t, \n, \, etc) manually.
Using System.Diagnostics.Debugger.Break() is sometimes helpful or even required, but don't forget to strip the out of the code when you're done.

A: I agree with coxymla, but besides that i have to say, that there is no automatic tool that can

"save a lot of time finding the exact
  reason of the problem"

There are very valuable tools that help - right. But finding root causes, and the like will always be at most up to your skills, your knowledge AND your ability to use tools.

A: Look for sourceindexing + symbolserver with a supported scm. (at least for c++).
When you write minidumps when your app fails, you can start them in your ide, and you get the sourcefile pointing at the crash locaten including callstack an some available vars!
this is really a great feature!


text:
Q: Full text search stored procedure error This is the error I am getting:
Syntax error near 'online' in the full-text search condition '""online"*" and "and*" and ""text"*"'.

This is my stored procedure:
ALTER PROCEDURE dbo.StoredProcedure1
(
    @text varchar(1000)=null
)
AS
SET NOCOUNT ON

declare @whereclause varchar(1000)

SET @whereclause = @text

SELECT articles.ArticleID AS linkid,
       articles.abstract as descriptiontext,
       articles.title as title,
       'article' as source,
       articles.releasedate as lasteditdate
 FROM articles
        WHERE  CONTAINS(title, @whereclause)

ORDER BY lasteditdate DESC, source ASC

This what i pass to SP:
string content = "\"online\" and \"text\"";

part of C# code:
 using (SqlConnection cn = new SqlConnection(this.ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("StoredProcedure1", cn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@text", SqlDbType.VarChar).Value = searchExpression;
                cn.Open();

UPDATE:
Strings that i try and errors that i get:
content = "online text";
Syntax error near 'text' in the full-text search condition 'online text'.

content = "\"online\" and \"text\"";
Syntax error near 'online' in the full-text search condition '""online"*" and "and*" and ""text"*"'.

content = "\"online and text\"";
Syntax error near 'online*' in the full-text search condition '""online*" and "and*" and "text"*"'.

A: From msdn:

Specifies the text to search for in column_name and the conditions for a match.
 is nvarchar. An implicit conversion occurs when another character data type is used as input.
Because "parameter sniffing" does not work across conversion, use nvarchar for better performance.
So i've changed everything to nvarchar:
cmd.Parameters.Add("@text", SqlDbType.NVarChar).Value = searchExpression;

declare @whereclause nvarchar(1000)

A: Try this one in your c# code when adding parameter:
cmd.Parameters.Add("@text", searchExpression);

A: I think SQl uses % instead of *

A: The problem is with the extra quotation marks.
Instead of this:
string content = "\"online\" and \"text\"";

try this:
string content = "online and text";

It will generate a correct condition:
 '"online*" and "and*" and "text*"'

Also if accept user input and pass it directly into a query like this - you are really opening your application to SQL injection.

A: Not sure if it's significant, but your procedure is expecting varchar and your calling code is saying the parameter is SqlDbType.Char.
I'm quite fond of DeriveParameters :
SqlCommand cmd = new SqlCommand("StoredProcedure1", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open()
SqlCommandBuilder.DeriveParameters cmd;
cmd.Parameters("@text").Value = searchExpression;

A: I use this method to remove slashes and then pass the resulting char array to sp.
public static char[] RemoveBackslash(string value)
{
    char[] c = value.ToCharArray();
    return Array.FindAll(c, val => val != 39).ToArray();
}

string content = "'\"online\" and \"text\"'";

Sqlparam = new SqlParameter("@search", SqlDbType.NVarChar);
Sqlparam.Value = RemoveBackslash(content);
Sqlcomm.Parameters.Add(Sqlparam);


text:
Q: How to get the name of bindingsource which is currently binding to a control I have a textbox and I add bindingsource into it as a databinding, and then I want to get the name of the bindingsource, which is in the example bellow the bindingsource name is "bindingSource1". How to achive this? Because I have many bindingsource and sometime I changed the databinding of the textbox so that I need to check the name of bindingsource that currently bind to it. Thanks.
textBox1.DataBindings.Add("Text", bindingSource1, "Address", True)

A: Thank you guys, because of your comments, finally I got the idea how to achive my goal, this is what I need to do:
If textBox1.DataBindings(0).DataSource Is bindingSource1 Then
'do the jobs
End If


text:
Q: how to use some properties inside the object to use them? In my last block of code in the while loop, I'm trying to access each object created by Team teamWork = new Team(....), but for some reason it says cannot find the symbol.
The Teamm.Statttis an int in another class that defines if a robot(the object) is ready or passed the inspection (which are enumerations).
is there something I'm missing? Syntax or logic?
Feel free to critique my coding skills, still learning so it is appreciated!
for (int x = 1; x<=2; x++)
{
    String teamName, sponsoringSchool, financialSponsor;
    int noOfTeamMem, Teamnumber;
    tour.Judging(); // how to assign?
    System.out.print("Please enter Team Name\n");
    teamName = input.next();
    System.out.print("Please Enter Sponoring School?\n");
    sponsoringSchool = input.next();
    System.out.print("Please Enter Financial Sponsor\n");
    financialSponsor = input.next();
    System.out.print("Please Enter no of team Mem\n");
    noOfTeamMem = input.nextInt();
    System.out.print("please enter team number\n");
    Teamnumber = input.nextInt();

    Team teamWork = new Team(teamName, 1, 1, x ,noOfTeamMem, sponsoringSchool , financialSponsor);
    Robot Rob = new Robot(teamWork);
    for (int i = 1 ; i <= noOfTeamMem ; i++)
    {
        System.out.print("Please Enter first name ?\n");
        String firstName = input.next();
        System.out.print("please Enter Last Name\n");
        String lastName = input.next();
        System.out.print("Please Enter Email");
        String email = input.next();
        Person person = new Person(teamWork, firstName,lastName,email);
    }
    teams.add(teamWork);

}

while (true)
{

System.out.print("MENU\n"
        + "1)PREPARING TEAM TURN ROBOT ON\n"
        +"2)PREPARING TEAM HARDWARE\n"
        + "3)HAVE HW INSPECT READY ROBOT\n"
        + "4)HAVE PRERPARING TEAM TAKE HW_INSPECTED ROBOT TO STATION\n"
        + "5)HAVE SW INSPECT ROBOT\n"
        + "6)HAVE A PREPARING TEAM TAKE TO FIELD TEST\n"
        + "7)HAVE A FIELD TEST INSPEC\n"
        + "8)HAVE A BEFORE TEAM GO TO JUDGE\n"
        + "9)HAVE JUDGES INTERVIEW\n"
        + "10)CHANGE TEAM STATUS TO PASSED_INSPECTION\n"
        + "11)TOURNAMENT STATUS TO MATCH\n"
        + "12)\n"
        + "13)ROBOT CAN'T PLAY IF OFF, READY, OR STILL AT TESTING\n"
        + "14)CHANGE TOURNAMENT TO MATCHES\n"
        + "15)GENERATE POINTS\n"
        + "16)JUDGE POINTS\n"
        + "17)CHANGE TOURNAMENT TO AWARDS\n"
        + "18)PRINT TOP TEAMS JUDGING\n"
        + "19) PRINT TOP BY QULIFYING \n"
        + "20)DISPLAY TEAM PERSONS\n"
        + "21)DISPLAY TEAM INFO\n"
        + "22)DISPLAY INFO ABOUT ROBOTS\n"
        + "23)INFO ABOUT TOURNAMENT\n"
        + "24)END\n");
int choice;
choice = input.nextInt();
if (choice == 1)
{
    for (Object team : teams) {
        if (teamm.teamStattt == 1)
        {
            robb.Robot(teamWork , 1);
        }
    }
}

The First Part of Team Class which includes the while loop;
public class Team {
    public String teamName;
    public int teamNumber;
    public String robotDesc;
    public int noOfTeamMem;
    ArrayList teamMem = new ArrayList();
    public String sponsoringSchool;
    public String financialSponsor;
    public teamJudgeStat judgeing;
    public String judgingLocation;
    public int teamJudgee;
    public int teamStattt;
    private teamJudgeStat teamJudge;
    private teamStat teamStatus;
    private teamJudgeStat teamJudgeStatus;
    public String teamJudginStatus; // ENUMERATED!!!
    public int totalRankingPoints;
    public int totalQualifyingPoints;
    public int totalJudgingPoints;
    Random gener = new Random();

    public Team(String teamName,int teamStatus,int teamJudgeStatus, int Teamnumber, int noOfTeamMem, String sponsoringSchool, String financialSponsor) {
        this.teamName = teamName;
        this.teamNumber = Teamnumber;
        this.teamJudgee = teamJudgeStatus;
        this.noOfTeamMem = noOfTeamMem;
        this.sponsoringSchool = sponsoringSchool;
        this.financialSponsor = financialSponsor;
        this.teamStattt = teamStatus;
    }
    public Team()
    {

    }
    public void teamStats()
    {
        if (teamStattt == 1)
        {
        teamStatus= teamStat.PREPARING;
        }
        else if ( teamStattt == 2 )
        {
            teamStatus = teamStat.PASSED_INSPECTION;
        }
        else if (teamStattt == 3)
        {
            teamStatus = teamStat.PLAYED5_MATCHES;
        }
        else if (teamStattt==4)
        {
            teamStatus = teamStat.INELIGIBLE;
        }

    }

A: What is the type of teams ? Check that you have specified the generic type if teams is a list or set - i.e. make sure it's List<Team> or Set<Team> rather than just a List or Set. Then the for each loop would be
for (Team team : teams) {
    if (teamm.teamStattt == 1)
    {
        robb.Robot(teamWork , 1);
    }
}

and make sure that teamm is of type Team.


text:
Q: OSX 10.7 and up file sharing issue first question here. Be gentle with me.
So....my question.
Since I upgraded from OSX 10.6 to 10.7 (then all the way up to 10.8.2). When I share files with my windows PC. It can see my entire mac hard drive.
In system prefs. I enable file sharing, then enable windows file sharing and pick my mac user account that windows has to authenticate with. I've only selected 2 folders to share (movies and downloads). Yet when I connect to my mac on windows, I put in my mac UN&PW and boom, I've got full access to my entire mac hard drive.
Anyone know of a fix for this? I've scoured through the apple support forums and I'm not alone. No one seems to have come up with any solutions though.
Cheers in advance :)

A: You're seeing the entire hard drive because the user you are logging in as is an administrator.
Notice this line on the File Sharing pane:
"File Sharing allows other users to access shared folders on this computer and allows administrators to access all volumes."
The solution is to create a sharing only account in OS X and add that user to SMB sharing. Then give the new user read / write (or just read if that's what you're looking for) permission on those two folders.

A: If you provide your full login credentials (name and password), then you will have full access, much like when you log in when sitting at your Mac. This is not a bug or something that needs fixing.
However, when you connect to your Mac as a Guest and/or without logging in, that's when your Movies and Downloads folders should be available. The sharing setup you've configured is for non-system users, such as yourself.


text:
Q: Proving that the Riemann sum of $|f|$ is ≤ $f$ I need to prove $U_{|f |} (Z ) − L_{|f |} (Z ) ≤ U_f (Z ) − L_f (Z )$
Where $U$ is the upper estimate and $L$ is the lower estimate and $f$ is bounded.
I get that since $f$ is bounded, I have $m_j = inf(f)$ and $M_j = sup(f)$
Since $|f| ≥ f$, there is also $q_j = inf(|f|)$ and $Q_j = sup(|f|)$ and $q_j ≥ m_j, Q_j ≥ M_j$
So then
$U_{|f |} ≥ U_f (Z )$ and $L_{|f |} (Z ) ≥ L_f (Z )$
Which gives me two equalities and something like this when combined:
$$U_{|f |} (Z ) + L_{|f |} (Z ) ≥ U_f (Z ) + L_f (Z )$$ which is quite off.
How can I prove $U_{|f |} (Z ) − L_{|f |} (Z ) ≤ U_f (Z ) − L_f (Z )$?

A: !read this answer after the comment i just put.
if $M_j \geq 0$ then $Q_j=M_j$ , and since $q_j \geq m_j$:
$$
Q_j-q_j \leq M_j - m_j \tag{1}
$$
if $M_j <0$ then $f(x)$ is strictly negative on $\Delta x_j$, hence $|f(x)| = -f(x)$ therefore $Q_j = -m_j$ and $q_j = - M_j$ so :
$$
Q_j -q_j = -(m_j-M_j)=M_j-m_j. \tag{2}
$$
for every $j$ either $M_j \geq0$ or $M_j<0$ and in both case $Q_j-q_j \leq M_j - m_j$. so multiply this by length of $\Delta x_j$ and sum over all $j$:
$$
\sum_j (Q_j-q_j)\Delta x_j \leq \sum_j (M_j-m_j)\Delta x_j
$$
it's true for every partition $P$ and then take $||P|| \rightarrow 0$.


text:
Q: When does cublasInit() return a NOT_INITIALIZED status? during my cublas initialization, i get an error, i.e. not the wanted CUBLAS_STATUS_SUCCESS.
Checking the returned status, i figured out that the returned status is CUBLAS_STATUS_NOT_INITIALIZED which is not listed as possible returns of that function.
Does anyone have an idea what may have caused that behavior?

A: The CUBLAS 4.x documentation mentions CUBLAS_STATUS_NOT_INITIALIZED as error code for cublasCreate with the meaning "the CUDA Runtime initialization failed".
Can you verify that you have a valid CUDA context?
If so, did you create a valid CUBLAS context?
For CUBLAS 3.x and CUBLAS 4.x using the legacy API: did you call cublasInit while there is a CUDA context in the current thread active, and did it return CUBLAS_STATUS_SUCCESS?
For CUBLAS 4.x with new API: did you call cublasCreate and did it return CUBLAS_STATUS_SUCCESS? Are you using the handle created when calling cublas..._v2 methods?


text:
Q: Puppet install of Openstack: Could not find resource 'Package[dnsmasq-base]Package[dnsmasq-utils]' for relationship on 'Package[neutron-dhcp-agent]' ebug: Executing '/etc/puppet/etckeeper-commit-pre'
debug: catalog supports formats: b64_zlib_yaml dot pson raw yaml; using pson
err: Could not retrieve catalog from remote server: Error 400 on SERVER: Could not find resource 'Package[dnsmasq-base]Package[dnsmasq-utils]' for relationship on 'Package[neutron-dhcp-agent]' on node controller6.ec2.internal
warning: Not using cache on failed catalog
err: Could not retrieve catalog; skipping run

I must be missing something obvious, I have the packages dnsmasq, dnsmasq-base, and dnsmasq-utils installed on my Ubuntu 12.04 LTS server yet puppet is unable to find them. I'm running sudo puppet so I don't think this would be a permissions issue. Disabling the requirement in my params.pp let the installation continue (but it got hung up on a separate issue so I can't tell you if it would have worked had it finished). I've also tried with v3.2 and 3.3 of neutron, and the rest of the modules have the versions required of them by openstack. Lastly, if I disable neutron in the openstack all.pp I can get a working install of Openstack functioning (minus networking).
Hoping someone here has a hint or two for me, thanks for reading.
Edit
Wanted to add that I have since manually installed the neutron-dhcp-agent package in hopes of fixing this problem but have been unsuccessful.
Edit 2
   $dnsmasq_packages   = ['dnsmasq-base', 'dnsmasq-utils']

Line 105 in /etc/puppet/modules/neutron/manifests/params.pp
If I comment out the packages (replace with []) then it will continue past the point it errors out at.
Edit 3
I believe the problem originates here, /etc/puppet/modules/neutron/manifests/agents/dhcp.pp Any suggestions on how I should try to fix this? I'm going to put two checks instead of one and see how that goes.
include neutron::params

      Neutron_config<||>            ~> Service['neutron-dhcp-service']

 Neutron_dhcp_agent_config<||> ~> Service['neutron-dhcp-service']

  case $dhcp_driver {
    /\.Dnsmasq/: {
      Package[$::neutron::params::dnsmasq_packages] -> Package<| title == 'neutron-dhcp-agent' |>
      ensure_packages($::neutron::params::dnsmasq_packages)
    }
    default: {
      fail("Unsupported dhcp_driver ${dhcp_driver}")
    }
  }

A: To fix the problem I followed the suggestions in the comments and split
$dnsmasq_packages   = ['dnsmasq-base', 'dnsmasq-utils']

into two lines, you can see the changes here.
For the sake of having everything in one place here are the changes:
manifests/agents/dhcp.pp
Starts on line 85
    case $dhcp_driver {
      /\.Dnsmasq/: {
 -      Package[$::neutron::params::dnsmasq_packages] -> Package<| title == 'neutron-dhcp-agent' |>
 -      ensure_packages($::neutron::params::dnsmasq_packages)
 +      Package[$::neutron::params::dnsmasq-base_package] -> Package<| title == 'neutron-dhcp-agent' |>
 +      Package[$::neutron::params::dnsmasq-utils_package] -> Package<| title == 'neutron-dhcp-agent' |>
 +      ensure_packages($::neutron::params::dnsmasq-base_package)
 +      ensure_packages($::neutron::params::dnsmasq-utils_package)
      }
      default: {
        fail("Unsupported dhcp_driver ${dhcp_driver}")

manifests/params.pp
Starts on line 93
 $metadata_agent_package = 'neutron-metadata-agent'
  $metadata_agent_service = 'neutron-metadata-agent'

 -    $dnsmasq_packages   = ['dnsmasq-base', 'dnsmasq-utils']
 +    $dnsmasq-base_package = ['dnsmasq-base']
 +    $dnsmasq-utils_package = ['dnsmasq-utils']

      $isc_dhcp_packages  = ['isc-dhcp-server']

Edit
Although the above fixed my problem while running Puppet 2.7.11, I recently upgraded to version 3.5.1 and the problem disappeared. So two potential solutions if you ever run into this :)


text:
Q: Spring Plug-in error on Eclipse I had installed Spring plug-in form Eclipse (Mars) MP.
Then it keep showing below error message page every time when I open the IDE:

Plug-in "org.springsource.ide.eclipse.commons.gettingstarted" was unable to instantiate class "org.springsource.ide.eclipse.commons.gettingstarted.dashboard.WelcomeDashboard".

So I had removed the plug-in, however the error page still bother me a lot.

A: Usually that is just some preference you can disable for the startup.
Preferences > General > Startup and Shutdown


text:
Q: WP e-commerce remove button For adding a product to cart by id I've got this code:
<form class="product_form" enctype="multipart/form-data" action="<?php bloginfo('url');?>" method="post" name="1" id="product_143">
<input type="hidden" value="add_to_cart" name="wpsc_ajax_action">
<input type="hidden" value="143" name="product_id">
<button>+</button>

Is there a code to remove a item by id?
I've tried this:
<form action="<?php bloginfo('url');?>" method="post" class="adjustform remove">
<input type="hidden" name="quantity" value="0">
<input type="hidden" name="key" value="0">
<input type="hidden" name="wpsc_update_quantity" value="true">
<input type="submit" value="-">
</form>

But this removes the first item in the cart.


text:
Q: что почитать о решениях нечётких множеств? Хочется написать бот для игры в rummy / кун-кен
На сколько я понимаю логика получается нечёткая.
Дерево решений? мне кажется будет очень большое.
Коллапс волновой функции применить?
Нейронные сети в конце концов, хоть и не совсем подходят мне кажется.
Наверняка кто-то делал подобное. Может встречались вам разборы?

A: *

*Круглов - Нечёткая логика и искусственные нейронные сети

*McNeill - Fuzzy logic. A practical approach

*Zadeh - Fuzzy sets

*Батыршин - Основные операции нечеткой логики и их обобщения

*Вятченин - Нечеткие методы автоматической классификации

*Григорьев - Обработка ненадежных знаний в CLIPS

*Дюбуа Прад - Теория возможностей. Приложения к представлению знаний в информатике

*Заде - Понятие лингвистической переменной и его применение к принятию приближенных решений

*Заде - Тени нечетких множеств

*Заде - Принятие решений в расплывчатых условиях

*Кофман - Введение в теорию нечетких множеств

*Леоненков - Нечеткое моделирование в среде Matlab и FuzzyTech

*Поспелов - Нечеткие множества в моделях управления и искусственном интеллекте

*Тэрано - Прикладные нечеткие системы

*Яхъяева - Нечеткие множества и нейронные сети


text:
Q: Passport redirect to login page after successful save in DB I have setup Passport with Facebook strategy (just facebook strategy), And set up the check if user exists function to save user in Mongodb within a users collection.
I throw console.log for successful save in DB and I can see that the user has successfully saved in the collection (I can see it also in the DB itself with Terminal.
But the issue is that after successful registration the passport.authenticate function takes me to the login page and not to the 'getusergames' page.
Any Idea why is that?
function(accessToken, refreshToken, profile, done) {
    // Checking if this user is already in DB and if no, Add this user to DB
    insertUser.findOne({facebook_id: profile.id}, function(err, user) {
        // Print Error
        if (err) {
            return done(err);
        }
        // Save new user if there is no user exists
        if (!user) {
            var userId = profile.id;
            var userToken = accessToken;
            var user_name = profile.displayName;
            var newuser = new insertUser({
                username: user_name,
                facebook_id: userId,
                facebook_token: userToken
            });
            newuser.save(function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log('New User has Saved!');
                    done(null, user);
                }
            });
        }
        // If there is a user, Return his object and done.
        else if (user) {
            done(null, user);
        }

    });
}

A: So, the problem was that I didn't put return before the done(null, user);


text:
Q: Does not sort the NSMutableDictionary? I got the data from the web service like the below order
<?xml version="1.0" encoding="UTF-8"?><Racine><Resultat_detaille><XML.03_-_Caisse_Snack><Espece>234,00</Espece><CA>234,00</CA><Offert>0,00</Offert></XML.03_-_Caisse_Snack>

But...
If the xml change to NSMutableDictionary, its goes to the sorting order.
"Resultat_detaille" =         {
    "XML.03_-_Caisse_Snack" =             {
        CA = "234,00";
        Espece = "234,00";
        Offert = "0,00";
    };

I don't want sorting, but the dictionary is sorted order. I am using the RestKit for getting the data from the web. How can I get the original data to the dictionary? Please help me. Thanks in advance.

A: I don't know why you want to avoid this. But dictionary contains object in key-value pairs and it does not depend any sorting. But if you want the data in same manner as in XML, then you can parse it manually using NSXmlParse and also can store each dictionary object in array. like:
    arr[0] = CA -> "234,00";
    arr[1] = Espece -> "234,00";
    arr[2] = Offert -> "0,00";

I am not giving you actual code. I am telling only logic behind array objects here.

A: NSDictionary is not sorted, it is not an array, order has no meaning to a structure like a dictionary
From the looks of your xml, it has been correctly parsed into a dictionary


text:
Q: Secure OkHttp with key I have this code:
JSONParser jsonParser1 = new JSONParser();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("url")
        .build();
Call call = client.newCall(request);

call.enqueue(new okhttp3.Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        //observe reason of failure using
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if(response.isSuccessful()){
    }
}

Currently the code uses this to call the json info from "url".
I want to change the code so it passes in a key with the url and if the key matches to the one being checked in PHP, it returns the data.


text:
Q: Apply same function to each li element one by one I have to create a function for each li in a wordpress page but using the different content of the same attribute that each li has.
This is what I tried to do, I hope it can help you to better understand.
jQuery('li.product').each(function() {
   if(window.location.href === "https://www.website.it/shop/"){
   var jQueryRightLink = jQuery('a.product-info').attr('href');
   jQuery('a.add-to-cart-button').attr('href', jQueryRightLink);
   }
});

I would copy href of the "a.product-info" element to the "a.add-to-cart-button" element inside each li. Now with what I did all "a.add-to-cart-button" elements get the same href instead of different href.
I tried to search how to repeat the same function separately but with no luck.


text:
Q: Using Apple Pay in a dynamically rendered iframe (same-origin) I'm trying to use Apple Pay within an iframe that I create and populate its DOM with Javascript.
(Context: I work on 3rd party widget that websites can embed into their existing websites, hence the need to isolate everything in an iframe; there are other options for isolating, but this is what we currently use).
Apple Pay has two requirements, as far as I know:

*

*The frame has a secure source

*The frame has the same origin as the main frame on the page.

In order to satisfy these two requirements, I have tried to use the following code (tested in Safari):
const iframe = document.createElement('iframe')
document.body.appendChild(iframe)
// the iframe origin is 'about:blank'
// let's try to fix that
iframe.contentDocument.open()
// Render the DOM content here
iframe.contentDocument.close()
// That seems to set the origin of the iframe to the origin of the caller of `open`

// Test
const script = iframe.contentDocument.createElement('script')
script.text = `
console.log(location.origin == parent.location.origin)
// true, so iframe origin should be secure now like the parent

console.log(ApplePaySession.supportsVersion(2))
// But it still triggers the following error:
// "InvalidAccessError: Trying to start an Apple Pay session from an insecure document."
`
iframe.contentDocument.head.appendChild(script)

As you can see, this does not work despite the fact that the document origin is recognized as being the same as the parent origin and it is secure.
In conclusion: Is there any way I can use Apple Pay from within an iframe which I dynamically create on a 3rd party website?
Any help will be appericiated.