text:
Q: Concurrency transitions in D3 (circle following filling path) I am trying to create simple animated gauge charts, with red points on the end of each circle. Whole example is in here https://jsfiddle.net/yhLch8fc/3/ (please do not solve text position, it's not a problem). I tried to search on stack overflow, but tutorials like Change starting point of alongPath animation are not helping me, because my path is translated by X,Y and rotated. I thing the key part of code is:
circle.transition().duration(_duration)
    .attrTween('cx', arcCircleX(_myPath.node()))
    .attrTween('cy', arcCircleY(_myPath.node()));

you can easy switch to similar version (code from stack overflow above):
circle.transition().duration(_duration)
    .attrTween('transformation', circleTween(_myPath.node()));

I don't know why, but it seems the red circle goes to the left side. Maybe it's because the original path is translated and rotated.
(The original version was, when I try to follow filling path, but it does not work either.)

A: Instead of rotating the hover path, rotate the g element that contains both the path and the circle:
enter.append("g").attr("class", "hover")
     .attr("transform", "translate(" + _width / 2 + "," + _width / 2 + "), rotate(-90)");

Then:
circle.transition().duration(_duration)
   .attrTween('transform', circleTween(_myPath.node()));

Here's an example.  Is that what you were after?


text:
Q: how to insert the current url of the page in the database if (ModelState.IsValid)
        {

            ip.patientname = fc["patientname"];
            ip.patientmail = fc["patientmail"];
            ip.patientcountry = fc["patientcountry"];
            ip.patientquery = fc["patientquery"];
            ip.SecurityCode = fc["SecurityCode"];

            string url = Request.Url.AbsoluteUri;

            dblayer.Add_data_pharma(ip);
            TempData["msg"] = "Inserted";

        }
        else
        {
            TempData["msg"] = "Not Inserted";
        }

        ModelState.Clear();
        return Redirect(Request.UrlReferrer.PathAndQuery);
    }

string url = Request.Url.AbsoluteUri;
I want to know how to insert url name in the database using Request.Url.AbsoluteUri or any method.
public void Add_data_pharma(insert_askpharma_mar212019 ip)
        {
            SqlCommand com = new SqlCommand("insert_askpharma", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@pharmaid", ip.pharmaid);
            com.Parameters.AddWithValue("@patientname", ip.patientname);
            com.Parameters.AddWithValue("@patientmail", ip.patientmail);
            com.Parameters.AddWithValue("@patientcountry", ip.patientcountry);
            com.Parameters.AddWithValue("@patientquery", ip.patientquery);
            com.Parameters.AddWithValue("@SecurityCode", ip.SecurityCode);
            com.Parameters.AddWithValue("@urlname", string.Empty);
            com.Parameters.AddWithValue("@ipaddress", string.Empty);
            con.Open();
            com.ExecuteNonQuery();
            con.Close();
        }

I want to insewrt the current page url in the database using mvc

                                        <button type="button" class="close" data-dismiss="modal">×</button>

Personal Information

                                               @using (Html.BeginForm("AskOurPharmacist", "Basic", FormMethod.Post, new { @id = "kycFormTab5" }))
                                             {

                                                        Name*
                                                        <input type="text" class="form-control" id="patientname" name="patientname">

                                                        Phone*
                                                        <input type="text" class="form-control" id="" name="">

                                                        Email*
                                                        <input type="email" class="form-control" id="patientmail" name="patientmail">

                                                        <input type="hidden" class="form-control" id="patientcountry" name="patientcountry">

                                                        <input type="hidden" class="form-control" id="patientquery" name="patientquery">

                                                        <input type="hidden" class="form-control" id="SecurityCode" name="SecurityCode">

                                                        <input type="hidden" class="form-control" id="urlname" name="urlname">

                                                    <button type="submit" class="btn btn-success">Email me When in Stock</button>
                                             }

Why shop with Us?

 Trusted for Quality and Price

 80-90% Savings - Lowest Prices

 Free Shipping WorldWide*

 360° Round View of Products

 No Hidden Cost

 Saving Rewards, Referral Discounts

 Quality-Assured Medications

*T&C Apply

This is my view ,in one mehod i have inserted two forms in this form only i want to insert the url in the database all are in the same table
this is my database

A: you must have a column(if not add 1 with name url) in database let say url which also will be available(if not add a property with the name url) in Model class ip. You method dblayer.Add_data_pharma(ip) will do the rest.

ip.url = Request.Url.AbsoluteUri;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lisp - "case" macro implementation I'm wondering how the case macro works, but just expanding it is not enough. How does it generate the cond statement without knowing how many arguments there are? Does it use a loop or something? And if so then why does it not show up when i run macroexpand.
I need to write something that works in a similar way, that's why I ask.

A: Yes you would need to use iteration - one of loop, do, mapcar &c (or recursion).
Take a look at, e.g., CLISP's implementation of case:
(defun case-expand (whole-form form-name test keyform clauses)
  (let ((var (gensym (string-concat (symbol-name form-name) "-KEY-"))))
    `(let ((,var ,keyform))
      (cond
        ,@(maplist
           #'(lambda (remaining-clauses)
               (let ((clause (first remaining-clauses))
                     (remaining-clauses (rest remaining-clauses)))
                 (unless (consp clause)
                   (error-of-type 'source-program-error
                     :form whole-form
                     :detail clause
                     (TEXT "~S: missing key list")
                     form-name))
                 (let ((keys (first clause)))
                   `(,(cond ((or (eq keys 'T) (eq keys 'OTHERWISE))
                             (if remaining-clauses
                                 (error-of-type 'source-program-error
                                   :form whole-form
                                   :detail clause
                                   (TEXT "~S: the ~S clause must be the last one")
                                   form-name keys)
                                 't))
                            ((listp keys)
                             `(or ,@(mapcar #'(lambda (key)
                                                `(,test ,var ',key))
                                            keys)))
                            (t `(,test ,var ',keys)))
                     ,@(rest clause)))))
           clauses)))))

(defmacro case (&whole whole-form
                keyform &body clauses)
  (case-expand whole-form 'case 'eql keyform clauses))


text:
Q: Javascript Disable button when a specific option is selected I have a code here but the code for disabling the button is not working.
Button with link
   <button id="link-button">
    GO TO LINK
   </button>

Select Option
<select id="website" onchange='selecWeb(this)'>
  <option>Search Engine</option>
  <option value="https://google.com">Google</option>
  <option value="https://yahoo.com">Yahoo</option>
  <option value="https://bing.com">Bing</option>
 </select>

JS Code
function selecWeb(a){
    var val = a.value;

    if(a.options[a.selectedIndex].text== "Search Engine")
    {
        $('#link-button').prop('disabled', true);
    }
    else
    {
        $('#link-button').prop('disabled', false);
        document.getElementById('link-web').href = val;
    }
}

Why prop('disabled', true) is not working?
Is there another way?

A: Use JS disabled attribute :
document.getElementById("id").disabled = true;

A: The problem is that you have nested an a tag inside a button tag, which is not allowed by HTML5. A button can not contain interactive content. JSFiddle demonstrating this: http://jsfiddle.net/ykv695en/

function selecWeb(a){
    var val = a.value;

    if(val == "SearchEngine")
    {
        $('#link-button').prop('disabled', true);
    }
    else
    {
        $('#link-button').prop('disabled', false);
        $('#link-button').off();
       $('#link-button').click(function(){
        location.href = val;
       });
    }
}

<button id="link-button">
    GO TO LINK
   </button>
   <select id="website" onchange='selecWeb(this)'>
  <option value="SearchEngine">Search Engine</option>
  <option value="https://google.com">Google</option>
  <option value="https://yahoo.com">Yahoo</option>
  <option value="https://bing.com">Bing</option>
 </select>

A: Using change add a disabled class that will disable the href value of the a tag based on the selects new value.

$('#website').change(function(event) {
  if($(this).val() === 'Search Engine') {
    $('#link-button a').addClass('is-disabled');
  } else {
    $('#link-button a').removeClass('is-disabled');
    $('#link-button a').attr('href', $(this).val());
  }
});
a.is-disabled {
  color: currentColor;
  cursor: not-allowed;
  opacity: 0.5;
  text-decoration: none;
}

<button id="link-button">
  GO TO LINK
</button>

<select id="website">
  <option>Search Engine</option>
  <option value="https://google.com">Google</option>
  <option value="https://yahoo.com">Yahoo</option>
  <option value="https://bing.com">Bing</option>
</select>

A: here are two things.
 first that : anchor tag is inside a button element
 second: anchor tag doesn't have disabled property.
so your code be something like this
 <button id="link-button">GO TO LINK</button>
 <select id="website" onchange='selecWeb(this)'>
            <option>Search Engine</option>
            <option value="https://google.com">Google</option>
            <option value="https://yahoo.com">Yahoo</option>
            <option value="https://bing.com">Bing</option>
  </select>


text:
Q: C dynamic allocation for a grid when rows are not known I am trying to allocate a array of char*'s in C.
I know the number of columns in advance, but not the rows
and I want to allocate the rows as and when needed.
I tried to use:
char *(*data)[NUMCOLS]; //declare data as pointer to array NUMCOLS of pointer to char

data = malloc(sizeof(char*));

now, the above line should allocate for data[0] ... correct?
then, I must be able to use the row like
data[0][1] = strdup("test");
 .
 ..
data[0][NUMCOLS-1] = strdup("temp");

I am getting seg fault. I am not able to understand what is wrong here.
can anyone please help.

A: You haven't allocated enough memory for the things that you want to store. In this particular case, that would be:
data=malloc(sizeof(char*)*NUMCOLS*NUMROWS);

To resize the array, you would use:
data=realloc(data,(size_t)sizeof(char*)*NUMCOLS*NEW_NUMROWS);

More about it (reallocation) here

A: I would do this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(){
  char ***a = NULL;

  a       = realloc( a, 1 * sizeof(char **) ); // resizing the array to contains one raw
  a[0]    = malloc(     3 * sizeof(char  *) ); // the new raw will contains 3 element
  a[0][0] = strdup("a[0][0]");
  a[0][1] = strdup("a[0][1]");
  a[0][2] = strdup("a[0][2]");

  a       = realloc( a, 2 * sizeof(char **) ); // resizing the array to contains two raw
  a[1]    = malloc(     3 * sizeof(char  *) ); // the new raw will contains 3 element
  a[1][0] = strdup("a[1][0]");
  a[1][1] = strdup("a[1][1]");
  a[1][2] = strdup("a[1][2]");

  for( int rows=0; rows<2; rows++ ){
    for( int cols=0; cols<3; cols++ ){
      printf( "a[%i][%i]: '%s'\n", rows, cols, a[rows][cols] );
    }
  }
}


text:
Q: What is meant by a token in the context of rail-road diagrams? From Douglas Crockford's  JavaScript: The Good Parts, Chapter 2 Grammar

This chapter introduces the grammar of the good parts of JavaScript,
  presenting a quick overview of how the language is structured. We will
  represent the grammar with railroad diagrams.
The rules for interpreting these diagrams are simple:

*

*You start on the left edge and follow the tracks to the right edge.

*As you go, you will encounter literals in ovals, and rules or descriptions in rectangles.

*Any sequence that can be made by following the tracks is legal.

*Any sequence that cannot be made by following the tracks is not legal.

*Railroad diagrams with one bar at each end allow whitespace to be inserted between any pair of tokens. Railroad diagrams with two bars
  at each end do not.

  The grammar of the good parts presented in this chapter is
  significantly simpler than the grammar of the whole language.

I have seen this answer on SO which basically reiterates what is presented in the book. So what is meant by token here?

A: Tokens are the basic atomic units of a grammar. In a typical programming language, tokens would include things like algebraic operators (+, *), statement separators ((, {, ;), identifiers, numeric and string values, and reserved words.
The concept of a "token" is somewhat bound up with the way a grammar is written and parsed. Some parsing schemes don't involve the concept of tokenization (packrat parsers for PEGs). However, in this case the use of a railroad diagram implies a traditional BNF (or BNF-like) grammar, complete with a set of tokens.
edit — actually, looking at that other question, the discussion there is actually about a token grammar itself — the token grammar for JSON. I suppose you could consider the elements of the character set to be "tokens" for that purpose. Anyway it should be clear that in those cases — the rules for what numbers and strings look like — spaces can't appear in the middle of those constructs. That is, 23 and 2 3 are not the same.
Outside of the bizarre situations around automatic semicolon insertion, I can't think of places in the JavaScript grammar that disallows spaces between tokens.


text:
Q: Git submodules and orphaned commits I have a git repo (A) where each commit is an orphaned commit with a name (branch).  Git repo B consumes A as a submodule, and as such is always holding a reference to a SHA in A.  When I make a fresh clone of B I need to do the typical git submodule init/update incantation, but I don't want it to clone all of A.  I just want it to clone the single orphaned commit which is the submodule reference.
However, even when I try git submodule update --init --recursive --depth 1 path/to/A, git clones from master instead. Is there a way I can convince it to clone only the SHA that I care about?

A: If B consumes A as a submodule, it should do so by configuring A submodule to follow a branch.
That way, a git submodule update --init --recursive --remote --depth 1 path/to/A should checkout from the branch it is supposed to follow.


text:
Q: Filter unwanted symbols when prefixing static library in iOS I'm trying to prefix a PayPal static library so clients implementing our framework are able to use a different version of it. I've been following this article  and this post but I'm having some issues.

*

*I created a target and added libPayPalMobile.a to Link with binary libraries.

*I've added the run script that has been mentioned in the tutorials above.

*I've added my target as a dependency to the project.

After NamespacedDependencies.h gets generated, I'm seeing some unwanted symbols in the Externs section:
// Externs
#ifndef k1PasswordButtonWidth
#define k1PasswordButtonWidth __NS_SYMBOL(k1PasswordButtonWidth)
#endif

#ifndef k1PasswordButtonRightMargin
#define k1PasswordButtonRightMargin __NS_SYMBOL(k1PasswordButtonRightMargin)
#endif

l002
l003
l004
l003
l004
l005
l006
l001
l007
l002
l008
l003
l009
l010
l007
l011
l004
l012
l008
l009
l005
l010
l011
l003
l012
l004
l003
l005
l013
l003
l006
l004
l014
l003
l015
l007
l004
l016
l004
l008
l001
l005
l005
l002
...

I figured I could remove these using grep -v "l[0-9]{0,5}" but they seem to be dumped with the above symbols, meaning I can't simply filter out these.
Obviously, the problem is that I can't even compile since I'm getting Parse Issue: Unknown type name l002.
Any idea what these evil things are and how to get rid of them?
EDIT:
This is Externs part of the script:
echo "// Externs" >> $header

nm $CODESIGNING_FOLDER_PATH | sort | uniq | grep " D " | cut -d' ' -f3 | grep -v "\$_NS" | grep -v "\$_UI" | sed -e 's/_\(.*\)/#ifndef \1\'$'\n''#define \1 __NS_SYMBOL(\1)\'$'\n''#endif\'$'\n''/g' >> $header

nm $CODESIGNING_FOLDER_PATH | sort | uniq | grep " S " | cut -d' ' -f3 | grep -v "\$_NS" | grep -v ".eh" | grep -v "\$_UI" | grep -v "OBJC_" | sed -e 's/_\(.*\)/#ifndef \1\'$'\n''#define \1 __NS_SYMBOL(\1)\'$'\n''#endif\'$'\n''/g' >> $header

A: Rather than trying to distribute the PayPal library as part of your own, I'd encourage you to express a dependency so that developers always get the latest version.
I'd also encourage you to use the PayPal iOS SDK, or better yet, the Braintree SDK (which includes PayPal) rather than the obsolete MPL. Both Braintree and the iOS SDKs publish to Cocoapds to ease dependency management.


text:
Q: Create array of table cell values jQuery I have the following code, which I'm using to create an array of all the tr's in the tbody area of a table.
var $table = $('#mytable');
var $rows = $table.find("tbody tr");

It works fine and contains the data from the table.  However, I want to loop over each row and create an array of the value of each cell in that row.  I've tried:
for(x=0;x<$rows.length;x++)
{
    var aCells = $rows[x].find("td");
    alert(aCells.length);
}

But the console is showing an error stating that Object # has no method 'find'
Can anyone help me?  I just want to loop over each row in the tbody one at a time and create an array of the cell values within that row so I can access a specific cell on each loop.

A: This returns DOM not a jQuery object
$rows[x]

You want to use eq()
$rows.eq(x).find("td");

or just use each()
$rows.each(function(){
    var cells = $(this).find("td");
});

A: You can use .each() to iterate through the rows and you can access its td elements by using the $(this) reference.
Try
$rows.each(function(){
    var aCells = $(this).find("td");
    alert(aCells.length);
});

A: $rows is not an array. It's a jQuery object. Use $rows.eq(x) instead.
See the documentation of .eq()


text:
Q: the error in eclipse about that no resource found while making new project? As soon as I create a Android project in Eclipse Indigo I instantly get a resource error on the line, setContentView(R.layout.main); To make it worse, projects that were working now are having their 'gen' folder emptied upon being built.
Unfortunately using google gives me a million references to projects that need to have files renamed or rebuilt, so I thought I'd ask here.
Errors
Description Resource Path Location Type error: Error: No resource found that matches the given name: attr 'android:actionModeShareDrawable'. themes_base.xml /appcompat_v7/res/values-v11 line 352 Android AAPT Problem error

The link provided by you didn't help me?
please help me?
appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

A: you should fix the imports import the support library
https://developer.android.com/tools/support-library/setup.html
the issue is you development environment is not able to resolve issue related to resource not able to compile as it is not able to find appropriate reference to external resources which your project is using


text:
Q: how to fix error in python code (elif statement ) This is my code below, it is saying that there is an error but i cannot understand the error (the '^' is pointing at the ':' of the elif statement):
File "", line 47
elif:
^
SyntaxError: invalid syntax
''    print ("there are 27 sticks")
sticks = 27

player1 = True
Ai = False

print ("there are 27 sticks, pick the last one !")

print("1")
print("2")
print("3")

while player1 == True:

    inp = int(input("Enter the number of sticks you want to take: "))

    if inp == 1:
        inp = "1: 1 stick taken"
        sticks = sticks -1
        print (sticks)
        player1 = False
        Ai = True
    elif inp == 2:
        inp = "2 sticks taken"
        sticks = sticks - 2
        print (sticks)
        player1 = False
        Ai = True
    elif inp == 3:
        inp = "3 sticks taken"
        sticks = sticks - 3
        print (sticks)
        player1 = False
        Ai = True
    else:
        print("Invalid input!")

while Ai == True:
    if sticks == 7:
        InpAi = 3
        sticks = sticks - InpAi
        print (sticks)
        player1 = True
        Ai = False
    elif:
        print ("")

    else:
        ''

A: Your if tree in the second while loop has the structure if... elif... else but the elif doesn't have a condtion. It's throwing an error because there is no condtion.

A: You've declared an elif without a variable to check against, you need to put something like
elif something == 'something else':
    do this

A: while Ai == True:
    if sticks == 7:
        InpAi = 3
        sticks = sticks - InpAi
        print (sticks)
        player1 = True
        Ai = False
    elif: # <= add condition here if any otherwise remove that line :)
        print ("")

    else:
        ''


text:
Q: Modificar Excel con python Hice un script para cambiar un carácter de toda una fila de Excel por otro con Python, ejemplo todas las casillas de una fila del Excel tiene texto así: 'nombre_de_cuenta' y yo lo que hice fue cambiar el guion bajo por un espacio en blanco = 'nombre de cuenta' pero solo lo puedo hacer el cambio desde la A a la Z ya que para indicar el rango en el que se hace el cambio use el código ASCII, alguien sabe como puedo ir mas allá es decir de la A a la AZ.
import openpyxl

path = "archivo.xlsx"

plantilla = openpyxl.load_workbook(path)

sheetnames = plantilla.sheetnames

ws = plantilla[sheetnames[0]]

# Este es el rango en el que el cambio se realiza la 65=A es el inicio y
#el 90=Z es el  final
for i in range (65,90):
aux = ws[chr(i)+str(1)].value

ws[chr(i)+str(1)] = aux.replace(chr(95),' ')

plantilla.save(path)

print('bien')

A: Usa openpyxl.utils.cell.get_column_interval. Esta función devuelve, dados una columna inicial y final, todas las columnas intermedias (inclusive).
import openpyxl
from openpyxl.utils.cell import get_column_interval

path = "archivo.xlsx"

plantilla = openpyxl.load_workbook(path)

sheetnames = plantilla.sheetnames

ws = plantilla[sheetnames[0]]

for i in get_column_interval("A", "AZ"):
    print(i)
    aux = str(ws[i+"1"].value)
    ws[i+"1"] = aux.replace(chr(95),' ')

plantilla.save(path)


text:
Q: vscode: how to avoid "quick open"? I'm new to vscode. In other IDEs, when I hold CTRL button, put my cursor of method name and make a left mouse click, I'm navigated to a new tab in the IDE that includes the method definition.
However, in vscode, when I do it, I see this appearance:

A new windows is opened inside the current tab. I just want the "regular" behavior.
I edited settings.json file and added:
"workbench.editor.enablePreview": false,
"workbench.editor.enablePreviewFromQuickOpen": false

Unfortunately, it didn't work out.
Do you know what can help in this case?

A: "editor.gotoLocation.multiple": "goto",

Controls the behavior of 'Go To' commands, like Go To Definition, when multiple target locations exist.

Alternatively/additionally show references in the SideBar:
"references.preferredLocation": "view",


text:
Q: Open CV delay measure I'm using openCV library with yolov3 and darknet in my project. My app has been written in C++ and it reads rtsp stream and look for a human on the stream. I run it on my Nvidia Jetson Nano and everything is fine but there is one small issue. I have noticeable delay in video analysis. When I run it and I appear in camera view area I can see ~20s lag.
I'm analising substream (720p 2fps) but on recognition I would like to capture the right moment of recognition on the main stream (1080p 15fps) which I record using ffmpg. To do so i need to (1) don't have delay on recognition or (2) measure this delay during recognition to define which second of main video I need to capture.
I suppose (1) is not possible.
Do you know if openCV has such an option to display this delay? How can I measure it?
p.s. This delay is not always the same. But I noticed it is from 10 to 20 s,
Thank you a lot for any help ;)

A: It will be hard to sync the stream, as both fps and stream channels are different. And another problem it's the rtsp stream, openCV can skip a lot of frames caused by bootlenecks and you can't get them back.
You may find a answer if you look where is your bootleneck. Probably, as it's a deep learning algorithm, most of the gpu/cpu time will be in the detection algorithm.
What i would do is: Ignore the second stream and focus your code on the main stream, add some frames on a buffer and detect, if your counditions are reached, then you iterate over that buffer to save what you need.
ps: This can cause problems to, due to the time needed to save the buffer on disk. (Maybe create a Thread for this will help)


text:
Q: Flash As3 TextField  is not working I am using TextField in that Line break is not working  i given multiline property to true also. even though i am not getting line break.
how to do  using textfield in flash AS3.
Thanks in Advance

A: Add
textFieldName.condenseWhite = true;
textFieldName.multiline = true;

A: whenever you get texts from an external files like XML. if there is a one line breaks in your [!CDATA] content then you will get two line breaks in your Flash Text Field (It's a BUG). the solution is, before assigning text to TextField you need to search line breaks charactor. when you use ("/n") in XML that it comes in ("//n"), but it will be displayed as \n.
I do one of these str.split("\\n").join("\n") after I get the string from the xml.

A:  var txt:TextField = new TextField();
    txt.multiline = true;
    txt.htmlText = "benny
geo";
    addChild(txt);

For more to know about htmlText click here.

A: You probably want to wrap the words. You should set wordWrap parameter to true.
multiline parameter only says, whether it should respect "\n" in text or cut them out. There is a bug in Flash - multiline works only when type parameter is "input".
BTW. all you can display with htmlText you can also display without it (i.e. you can fully implement htmlText above TextField by yourself).

A: add a \n to the text where you want a newline, should work!

A: Use:

instead:

or:


text:
Q: Selecting parent list with child in CSS I want to keep hover color on parent list, when child list is hovered.
Here's example where second menu has submenus and when you hover over submenus, color of main menu is gone.
http://jsfiddle.net/ya8ga/
Thanks
HTML

Home

Hotel

Hotel Sub 1

Hotel Sub 2

A: change this:
#menu2 li a:hover{background:#89E00C; color:#2D1C13;}

to this:
#menu2 li:hover{background:#89E00C; color:#2D1C13;}


text:
Q: How to move an entire git repository with its history to a sub-folder of another git repository? I have one git repository of a library and another git repository of a project:
library/
project/

I need to copy the library to a folder inside the project:
project/ref/library/

Inside this project I will make modifications to the library specific to that project, thus it would not be viable to use submodules. I also need to preserve the history of this library.
As a bonus, I would like also to know how could I merge/rebase future developments of the library into my fork of the library inside the project.

A: I found a solution to the problem based on this answer:
cd library/
mkdir -p ref/library/
git mv * ref/library # Remember to not include the ref/library itself
git commit -m "moved to ref/library"
cd ../project/
git remote add library-repo ../library
git fetch library-repo
git branch library-branch remotes/library/master
git merge library-branch --allow-unrelated-histories
git remote rm library-repo

Once there is something new on the library, I can just go the library and do git fetch --rebase, then repeat the process.

A: One way to get what you want and still rely on git submodules is to clone your library as a git submodule inside your project, and then create a new branch specific to your project inside the library.
This way, you get all changes from the library whenever you do a merge/rebase on your branch, you do not have to push your commits back to the original library, and you can perform as many changes as you need in your branch to fit your project's needs.

A: I would suggest add library as submodule to project using (inside project repo):
git add submodule library.git ref/library

This will make it possible to code the changes inside ref/library, but also decide when to take in changes in ref/library.
The submodule command has a foreach sub command that can make it easier to pull new things into the submodules.
git submodule foreach git pull || :

Will run git pull in each submodule and continue if you get an error in one submodule, because of the || :
Good luck!


text:
Q: Get id attribute from a node in nodelist I have currently got a nodelist by using the document.getElementsByClassName method in javascript. I then check if the first node has any children and if not I would return a document.getElementById with that nodes ID.  I am unsure of how to get the ID from the node list.
 var columns = document.getElementsByClassName('.col-md-4.column');

if (countChildren(columns[0].childNodes) == 0) {
    return document.getElementById(columns[0].) //not sure what goes here
}

A: If you have a DOM node, it has an id property, you can't use getElementById to get that property
var columns = document.querySelectorAll('.col-md-4.column');

if ( countChildren(columns[0].childNodes) == 0 ) {
    return columns[0].id;
}

Note that getElementsByClassName takes the classes without the period, but for better support you might as well use querySelectorAll

A: Not surprisingly, it's .id:
return document.getElementById(columns[0].id);

But more importantly, you already have a reference to the node - don't query the DOM for it:
return columns[0];


text:
Q: Table - Vertical header and dynamic number of columns I am trying to make a table with vertical header and dynamic number of columns. I want to use ASP.NET MVC Razor and foreach loop to generate columns.
I have constant number of headers (rows) and dynamic number of columns, which every column has value for every row
What i want to get:
Header1 Value1,Value2,Value3
Header2 Value1,Value2,Value3
Header3 Value1,Value2,Value3

Model:
public class RootViewModel
{
    public List<Column> Columns { get; set; }
}
public class Column
{
    public int Header1Value { get; set; } //Value1
    public int Header2Value { get; set; } //Value2
    public int Header3Value { get; set; } //Value3
}

I really don't know how to resolve this problem without using 'foreach' for every property.

A: You need to modify your view models to represent what you want to display in the view.
public class RootViewModel
{
    public List<RowViewModel> Rows { get; set; }
}

public class RowViewModel
{
    public string Header{ get; set; }
    public List<int> Values { get; set; }
}

so that in the view you can generate the table using
@model RootViewModel

    @foreach(var row in Model.Rows)
    {

            @row.Header
            @foreach(var value in row.Values)
            {
                @value
            }

    }


text:
Q: How to: Create Thumbnail Images in c++ windows forms> I want to code to create Thumbnail images for my tool tip control using  c++ in windows forms.
Yes did research still getting errors..
Image^ picture;
picture->GetThumbnailImageAbort callback ;
callback =  gcnew picture->GetThumbnailImageAbort(ThumbnailCallback);

picture("image.jpg");
Image^ pThumbnail = picture->GetThumbnailImage(50,50,callback,gcnew IntPtr());
e->Graphics->DrawImage(pThumbnail,10,10,pThumbnail->GetWidth(),pThumbnail->GetHeight());

I am getting Following Errors-
left of '->GetWidth' must point to class/struct/union/generic ,
'pThumbnail' : undeclared identifier,
'callback'   : undeclared identifier,
'GetThumbnailImageAbort' : undeclared identifier
function call missing argument list; use  to create a pointer to member
even though i did it and declared all properly.
I am trying to code from Below but in c++:
 https://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2


text:
Q: White screen of death when including Elastica Bundle I'm trying to add the Elasticsearch bundle to my symfony2 project, when I add the bundle
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new FOS\ElasticaBundle\FOSElasticaBundle(),
    );
}

1st case : I don't touch the config file: Result : White screen of death
I put some configuration
fos_elastica:
clients:
    default: { host: localhost, port: 9200 }
indexes:
    website:
        client: default
        types:
            user:
                mappings:
                    coordinates: { boost: 5 }

Results : White screen of death!
Does anyone have any idea about what's going on ?


text:
Q: python3 selenium как вытащить текст? изучать selenium начал недавно и еще новичок помогите пожалуйста вот элемент:

и мне нужно чтобы в cmd просто вывелось 5 баллов

A: content = driver.find_element_by_class_name('do-task').text
print(content)

если вам понадобится однозначно идендитифицировать элемент (если элементов с класслом do-task на странице у вас много), то посмотрите в сторону find_element_by_css_selector и find_element_by_xpath Хоошая статья на хабре про селениум на эту тему
 А вот так, при помощи инспектора Google Chrome, можно легко получить xpatch путь до любого элемента.


text:
Q: Javascript on page preventing Selenium from detecting certain frames & elements I'm using Selenium with Python to fill in a form on a site where the frames are visible in the html but I still haven't been able to get Selenium to detect any frames or form elements.
I think it is because there is Javascript in the  since I see the same scripts referenced throughout the html of the form fields.
I'm very new to this so I'm not quite sure where to get started. From what I've read I might need to use Python's "execute_script" and/or Selenium's javascriptexecutor.
Here is a snippet of the HTML from top to the frame with the fields I'm after (the frame name "main" is the one with the form in it):

<html><head>
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>eBridge Inc.</title>
    <script type="text/javascript">
        function startup() {
            parent.header.location.href = 'header.aspx?guid=' + window.name;
            parent.nav.location.href = 'nav.aspx?guid=' + window.name;
            parent.main.location.href = 'welcome.aspx?guid=' + window.name;
            parent.footer.location.href = 'footer.aspx?guid=' + window.name;
        }
    </script>
</head>
<frameset rows="75px,25px,*,30px" frameborder="0" border="0" framespacing="0" onload="startup();">
    <frame name="header" scrolling="no" noresize="noresize" frameborder="0" marginheight="0">
    <frame name="nav" scrolling="no" noresize="noresize" frameborder="0" marginheight="0">
    <frame name="main" noresize="noresize" frameborder="0">
        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head>
        <html>
            <head>
                <title>Retrieve</title>
                <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
                <meta http-equiv="Pragma" content="no-cache">
                <meta http-equiv="Expires" content="0">
                <link id="mainStylesheet" href="../StyleSheet.css?62" rel="stylesheet" type="text/css">
                <link id="dhtmlxStylesheet" href="../Scripts/combobox/style/dhtmlxcombo_touch.css?62" rel="stylesheet" type="text/css">
                <link id="datepickerStylesheet" href="../Scripts/datepicker/jquery.ui.datepicker.css?62" rel="stylesheet">
                <link id="jqueryuiStylesheet" href="../Scripts/jquery-ui-1.10.3.custom.css?62" rel="stylesheet">

                <script src="../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
                <script src="../Scripts/jquery-ui-1.8.15.custom.min.js" type="text/javascript"></script>
                <script src="../Scripts/datepicker/jquery.ui.datepicker.min.js" type="text/javascript"></script>
                <script src="../Scripts/jquery.maskedinput-1.3.min.js" type="text/javascript"></script>
                <script src="../Scripts/json.js" type="text/javascript"></script>

                <script src="../Scripts/combobox/scripts/dhtmlxcommon.js?version=3" type="text/javascript"></script>
                <script src="../Scripts/combobox/scripts/dhtmlxcombo_touch.js?version=3" type="text/javascript"></script>
                <script type="text/javascript">
                    $(document).ready(function () {
                        try
                        {
                            parent.nav.document.location = '../nav.aspx?menu=&guid=' + parent.window.name;
                        }
                        catch(ex){}
                        //focus on first tb/ddl
                        $('#tblIndex').find('input[type=text]').filter(':visible:first').focus();

                        $("#start_date").datepicker({
                            changeMonth: true,
                            changeYear: true
                        });

                        $("#end_date").datepicker({
                            changeMonth: true,
                            changeYear: true
                        });

                        $("#start_date").mask("99/99/9999");
                        $("#end_date").mask("99/99/9999");

                        $("#start_calendar_icon").click(function (event) {
                            $("#start_date").focus();
                        });

                        $("#end_calendar_icon").click(function (event) {
                            $("#end_date").focus();
                        });
                        // for enter keystroke
                        $(document).keyup(function (e) {
                            CheckKeyCode(e);
                            e.preventDefault();
                        });

                        $('.dhx_combo_input').keyup(function (e) {
                            CheckKeyCode(e);
                            e.preventDefault();
                        });

When I use the following python in Selenium, it throws the "no such frame" exception:
driver.switch_to.frame("header")

It does this for the rest of the frames as well.
So I tried listing all elements on the page using this:
for ii in ids:
    print(ii.get_attribute('id'))

And it only returns a few of the page elements (none of which are form fields), namely these:
stylesheet
hf
imgLogo
welcome
h_log_out
retrieve
aView
help
aSupport
cabnm

My goal is to input text into the form fields within the frame "main". I normally don't have any issue with using Python to interact with pages, but I'm not sure how to deal with the scripts on this page that seem to be preventing me from detecting and switching frames.
Any advice on whether the scripts are the culprit and if so, how to make them display the rest of the frames and elements is appreciated. I prefer solutions in Python but am open to anything.

A: '@TodorMinakov: Thanks Todor, I was able to fill out and submit the form ONLY after adding the following lines before anything else:
driver.switch_to_default_content()
driver.switch_to.frame("main")

I'd love to know why this is necessary, but at least it works now.
Thanks again Todor for your answer in the comments.


text:
Q: Как запустить виртуальную среду venv через консоль PyCharm? ДЕнь добрый!
Изучаю django и Python для вэб.
Python поставил версию 3.7 для работы с Pandas бесплатно )
При перезапуске Windows запуская Pycharm вижу PS D:\django-sites\..., но не (venv) D:\django-sites...\

Какая комманда запускает вертуальную среду?
Где найти комманду для консоли Pycharm?
PS - условное значение локального диска?
Заранее спасибо

A: При создании нового проекта в PyCharm, виртуальная среда автоматически запускается. Если вы скачали код с github, то виртуальную среду можно включить следующими командами:
PS D:\django-sites\testsite\> python -m venv venv
PS D:\django-sites\testsite\> venv\Scripts\activate

Возможно виртуальная среда у вас уже установлена. Зайдите в PyCharm:
File > Settings > Tools > Terminal. Внутри Terminal:  Application Settings > Shell path: C:\WINDOWS\system32\cmd.exe. Сохраните изменения и перейдите в терминал. Теперь у вас должно отображаться без знака PS:
(venv) D:\django-sites\testsite\>

Если у вас нет надписи (venv), то проделайте команды выше!
После этого у вас установлена виртуальная среда!
PS - это означает, что у вас командная строка PowerShell


text:
Q: Count the number of lines in an Excel File
Possible Duplicate:
Efficiently counting the number of lines of a text file. (200mb+)
How do I determine the end of the file using PHPExcel library in chunk loop?

I can't seem  to get this to work in PHP
I'm trying to count the number of lines in an uploaded EXcel file
Here is what I have but it always multiplies this by two and I want to remove the first row because it is just headers, please help:
$countthelines= count(file($file)) -1;

A: Convert your Excel file to a CSV file and try something like this:
$countthelines = count(file($file, FILE_SKIP_EMPTY_LINES)) - 1;


text:
Q: Splitting NSString in IPhone I create an iPhone application using RSS Feed. I using XMLParsing and get the following result in a String. The parsing string having Html tags. I want to read image tag's src only. How can I read src only from the following String Value?

How can I read src content only from that string?

A: Use an XML parser. Your best options for iPhone are (IMHO):

*

*libxml2

*NSXMLParser

A: I found this... basically use NSRegularExpression class.
http://cocoabyss.com/2010/first-step-with-nsregularexpression/
The example there searches exactly what you want: src="..." ;)


text:
Q: add class to a specific parent div when click a component created with v-for I am new to vuejs, this is what I want to do:
I have a list of components, each in a div. Now if I do something with the component (i.e. click it). I want to add a class to the parent div. This is what I did so far, the code is simplified, just to show what I want to do with a simple case.
my app.vue:

    <app-comp :myName="name" :myIndex="index" @someEvent="doSomething"></app-counter>

data() {
    classActive: '',
    names: ['alpha', 'beta', 'gamma']
},
methods: {
    doSomething() {
        this.classActive === '' ? this.classActive = 'is-active': this.classActive='';
    }
}

the component:

    <button @click="toggle">{{ myName }} - {{ myIndex }}</button>

props: ['myName', 'myIndex'],
methods: {
    toggle() {
        this.$emit('someEvent', index);
    }
}

what this do: it creates 3 divs with "toggle-box"-class with a button in it which has the label "name - index". When I click a button, it emits the "someEvent"-event with index attached. The parent listens to this event and toggle the class 'is-active' on the div with the 'toggle-box' class. The thing is, right now, when I click a button, it adds the class to all 3 divs. Probably because there is no different between the 3 divs for vuejs. I know I can append the index to the event and call this with $event in the parent, but how do I use this? Or is there perhaps a better way to achieve what I want?
thanks for helping.

A: There are several different ways to approach this but I think the starting point is to think about how you want to represent this as data rather than how that appears in the UI. So model before view.
Presumably you're going to want to do something with these active items after they've been selected. I'd focus on that rather than the problem of highlighting them. The highlighting would then fall out relatively painlessly.
For the sake of argument, let's assume that an array of active items is a suitable model for what you're trying to achieve. It might not be but it makes for a simple example.
So:
data() {
    return {
        activeNames: [],
        names: ['alpha', 'beta', 'gamma']
    }
},

No mention of classes here as we're not worrying about the UI concern, we're trying to model the underlying data.
For the toggle method I'd be more inclined to emit the name than the index, but you're better placed to judge which represents the data better. For my example it'll be name:
methods: {
    toggle() {
        this.$emit('someEvent', this.myName);
    }
}

Then in the parent component we'll add/remove the name from the array when the event is emitted. Other data structures might be better for this, I'll come back to that at the end.
methods: {
    doSomething(name) {
        if (this.activeNames.includes(name)) {
            this.activeNames = this.activeNames.filter(item => item !== name);
        } else {
            this.activeNames.push(name);
        }
    }
}

Now we have an array containing the active names we can use that to derive the class for those wrapper divs.

Done.
As promised, I'll now return to other data structures you could use.
Instead of an array we might use an object with boolean values:
data() {
    return {
        names: ['alpha', 'beta', 'gamma'],
        activeNames: {
            alpha: false,
            beta: false,
            gamma: false
        }
    }
}

In many ways this is an easier structure to work with for this particular example but we do end up duplicating the names as property keys. If we don't prepopulate it like this we can end up with reactivity problems (though those can be solved using $set).
A further alternative is to use objects to represent the names in the first place:
data() {
    return {
        names: [
            {name: 'alpha', active: false},
            {name: 'beta', active: false},
            {name: 'gamma', active: false}
        ]
    }
}

Whether this kind of data structure makes sense for your use case I can't really judge.

Update:
Based on what you've said in the comments I'd be inclined to create another component to represent the toggle-box. Each of these can store its own active state rather than trying to hold them all on the parent component. Your v-for would then create instances of this new component directly. Depending on the circumstances it may be that this new component could merged into your original component.
There are all sorts of other considerations here that make it really difficult to give a definitive answer. If the active state needs to be known outside the toggle-box component then it's a very different scenario to if it's just internal state. If only one toggle-box can be open at once (like an accordion) then that's similarly tricky as internal state is not sufficient.


text:
Q: I want to run program on background . pref C# I want to run program on background . pref C#
I want put icon in the tray.
On specified time it's  synchronizes   folders (I know how to sync folders) .
How to run it on background and start sync ( for example at  2am)?

A: You need to consider using the windows scheduler service.

A: To run "in background"
Form.Visible = False
Form.ShowInTaskbar = False

To start the synchronization, use a Timer and...

*

*Check the time every minute, start synch if the time matches

*OR calculate the interval Now->TimeToStart, set it, start the Timer, and reset it to 24 hours on the first tick

You might also think about creating a service if you want it to be a background process only.

A: I very often use Notify Icon on my applications which comes with Visual Studio, http://www.developer.com/net/csharp/article.php/3336751 as for start syncing, you can call a function on another thread which will measure time every second and if it is 2am you can call another function in another thread to sync folders (you can use also a timer component).
Resources:
Notify Icon: http://www.developer.com/net/csharp/article.php/3336751
C# Threading: http://www.albahari.com/threading/
Timer Component: http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx and http://www.codeproject.com/KB/miscctrl/TimeSheet.aspx

A: If I were you, I'd use the scheduler services in Windows.
Having a service, keeping an icon in the tray, etc. means you'll be filling up valuable screen space and consuming resources. What's more, the user will need some way to configure the application so they can choose whether it starts with Windows or not; if you provide this configuration, it'll be necessarily different to how every other application does it.
A scheduler task, on the other hand, only needs one process - the task scheduler itself - and the user can disable or delete the task themselves. Both the Apple and Google automatic updater processes now run in this way, for example.

A: Well, if you start with a Windows Forms Application, and want it to run in background, hanging from the system tray, you have to create the system tray, hide the main form before Application.Run(MainForm), and you're on.
To hide the form, I use:
MainForm.WindowState = System.Windows.Forms.FormWindowState.Minimized;
MainForm.ShowInTaskBar = false;

(since setting visible= false will be turned back on by the Run() method.)
To create a System Tray, I used instructions from here:


text:
Q: Vanilla JavaScript Convex Hull unexpected polygon shape on Google maps I am having issues creating a complex Convex Hull.  If I change to s simple polygon with 10 points or so, it works great, but when I have 20-30 points over a large area, it creates a "split" in the polygon.  Whereas the math says it should be looking for all the outliers, and using them as "hull points".  I am wondering if my math is incorrect, or if this is a JavaScript fluke?
As a reference, here is the site where I gleaned the mathematics and sample code snippet from: The Convex Hull of a Planar Point Set
This is as stripped-down as I can get it while still being functional as a stand alone snippet.

        var gmarkers = [];
        var points = [];
        var hullPoints = [];
        var map = null;
        var polyline;

        var infowindow = new google.maps.InfoWindow(
            {
                size: new google.maps.Size(150, 50)
            });

        function initialize() {
            var myOptions = {
                zoom: 10,
                center: new google.maps.LatLng( 41.024767, -74.122642),
                mapTypeControl: true,
                mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
                navigationControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(document.getElementById("map_canvas"),
                myOptions);

            google.maps.event.addListener(map, 'click', function () {
                infowindow.close();
            });

            google.maps.event.addListenerOnce(map, 'bounds_changed', function () {
                // Add 10 markers to the map at random locations
                var bounds = map.getBounds();
                var southWest = bounds.getSouthWest();
                var northEast = bounds.getNorthEast();
                var lngSpan = northEast.lng() - southWest.lng();
                var latSpan = northEast.lat() - southWest.lat();
                map.setCenter(map.getCenter());
                map.setZoom(map.getZoom() - 1);

                points = [
                    new google.maps.LatLng(41.0247669,-74.1226425),
                    new google.maps.LatLng(41.0410868,-74.13484609999999),
                    new google.maps.LatLng(41.0238951,-74.13282749999999),
                    new google.maps.LatLng(41.0309834,-74.1264094),
                    new google.maps.LatLng(41.0252598,-74.155237),
                    new google.maps.LatLng(40.9419984,-73.9405831),
                    new google.maps.LatLng(40.9518704,-73.9264803),
                    new google.maps.LatLng(40.9530188,-73.9344715),
                    new google.maps.LatLng(40.6771541,-74.1165864),
                    new google.maps.LatLng(40.6586571,-74.12123179999999),
                    new google.maps.LatLng(40.8025724,-74.1505466),
                    new google.maps.LatLng(40.78835,-74.17700169999999),
                    new google.maps.LatLng(40.8024772,-74.1492507),
                    new google.maps.LatLng(40.7995324,-74.1508104),
                    new google.maps.LatLng(40.7954599,-74.1443422),
                    new google.maps.LatLng(40.917345,-73.9939529),
                    new google.maps.LatLng(40.9256096,-74.0012066),
                    new google.maps.LatLng(40.9114334,-74.0070829),
                    new google.maps.LatLng(40.9251857,-73.99491619999999),
                    new google.maps.LatLng(40.923538,-73.9888347),
                    new google.maps.LatLng(40.9356149,-74.0044661),
                    new google.maps.LatLng(40.9336639,-74.0126835),
                    new google.maps.LatLng(40.9168748,-74.0047416),
                    new google.maps.LatLng(40.9235845,-73.99615659999999),
                    new google.maps.LatLng(40.9346191,-73.9895914),
                    new google.maps.LatLng(40.9169838,-74.0046957),
                    new google.maps.LatLng(40.9319544,-74.0109391),
                    new google.maps.LatLng(40.924245,-74.00189530000002),
                    new google.maps.LatLng(40.9247537,-74.0057516),
                    new google.maps.LatLng(40.936268,-73.99291699999999),
                    new google.maps.LatLng(40.9354675,-74.00451199999999),
                    new google.maps.LatLng(40.9336023,-73.9827045),
                    new google.maps.LatLng(40.9173526,-73.9930577),
                    new google.maps.LatLng(40.9249738,-73.9951007),
                    new google.maps.LatLng(40.9114631,-74.0059352),
                    new google.maps.LatLng(40.9197391,-74.0056024),
                    new google.maps.LatLng(40.9147328,-74.0110768),
                    new google.maps.LatLng(40.9357446,-74.0051089),
                    new google.maps.LatLng(40.9206033,-74.002538),
                    new google.maps.LatLng(40.9247956,-74.0014362),
                    new google.maps.LatLng(40.9302183,-73.9943661),
                    new google.maps.LatLng(40.9320254,-74.0052007),
                    new google.maps.LatLng(40.6714401,-74.5352054),
                    new google.maps.LatLng(40.9356751,-73.9807761),
                    new google.maps.LatLng(40.922373,-73.9908769),
                    new google.maps.LatLng(40.9317953,-73.9832555),
                    new google.maps.LatLng(40.9337966,-74.0087355)
               ];

                for (var i = 0; i < points.length; i++) {
                    console.log ( points[i] + ", " + i);
                    var marker = createMarker(points[i], i);
                    gmarkers.push(marker);

                }

                calculateConvexHull();
            });
            google.maps.event.addListener(map, "click", function (evt) {
                if (evt.latLng) {
                    var latlng = evt.latLng;
//            alert("latlng:"+latlng.toUrlValue());
                    var marker = createMarker(latlng, gmarkers.length - 1);
                    points.push(latlng);
                    gmarkers.push(marker);
                    calculateConvexHull();

                }
            });
        }

        function createMarker(latlng, marker_number) {
            var html = "marker " + marker_number;
            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                zIndex: Math.round(latlng.lat() * -100000) << 5
            });

            return marker;
        }

        function calculateConvexHull() {
            if (polyline) polyline.setMap(null);

            points = [];
            for (var i = 0; i < gmarkers.length; i++) {
                points.push(gmarkers[i].getPosition());
            }
            points.sort(sortPointY);
            points.sort(sortPointX);
            DrawHull();
        }

        function sortPointX(a, b) {
            return a.lng() - b.lng();
        }

        function sortPointY(a, b) {
            return a.lat() - b.lat();
        }

        function DrawHull() {
            hullPoints = [];
            chainHull_2D(points, points.length, hullPoints);
            polyline = new google.maps.Polygon({
                map: map,
                paths: hullPoints,
                fillColor: "#FF0000",
                strokeWidth: 2,
                fillOpacity: 0.5,
                strokeColor: "#0000FF",
                strokeOpacity: 0.5
            });
            displayHullPts();
        }

        function displayHullPts() {
            for (var i = 0; i < hullPoints.length; i++) {
                document.getElementById("hull_points").innerHTML += hullPoints[i].toUrlValue() + "
";
            }
        }

        function sortPointX(a, b) {
            return a.lng() - b.lng();
        }
        function sortPointY(a, b) {
            return a.lat() - b.lat();
        }

        function isLeft(P0, P1, P2) {
            return (P1.lng() - P0.lng()) * (P2.lat() - P0.lat()) - (P2.lng() - P0.lng()) * (P1.lat() - P0.lat());
        }

        function chainHull_2D(P, n, H) {
            // the output array H[] will be used as the stack
            var bot = 0,
                top = (-1); // indices for bottom and top of the stack
            var i; // array scan index
            // Get the indices of points with min x-coord and min|max y-coord
            var minmin = 0,
                minmax;

            var xmin = P[0].lng();
            for (i = 1; i < n; i++) {
                if (P[i].lng() !== xmin) {
                    break;
                }
            }

            minmax = i - 1;
            if (minmax === n - 1) { // degenerate case: all x-coords == xmin
                H[++top] = P[minmin];
                if (P[minmax].lat() !== P[minmin].lat()) { // a nontrivial segment
                    H[++top] = P[minmax];
                    H[++top] = P[minmin]; // add polygon endpoint
                }
                return top + 1;
            }

            // Get the indices of points with max x-coord and min|max y-coord
            var maxmin, maxmax = n - 1;
            var xmax = P[n - 1].lng();
            for (i = n - 2; i >= 0; i--) {
                if (P[i].lng() !== xmax) {
                    break;
                }
            }
            maxmin = i + 1;

            // Compute the lower hull on the stack H
            H[++top] = P[minmin]; // push minmin point onto stack
            i = minmax;
            while (++i <= maxmin) {
                // the lower line joins P[minmin] with P[maxmin]
                if (isLeft(P[minmin], P[maxmin], P[i]) >= 0 && i < maxmin) {
                    continue; // ignore P[i] above or on the lower line
                }

                while (top > 0) { // there are at least 2 points on the stack
                    // test if P[i] is left of the line at the stack top
                    if (isLeft(H[top - 1], H[top], P[i]) > 0) {
                        break; // P[i] is a new hull vertex
                    }
                    else {
                        top--; // pop top point off stack
                    }
                }
                H[++top] = P[i]; // push P[i] onto stack
            }

            // Next, compute the upper hull on the stack H above the bottom hull
            if (maxmax !== maxmin) { // if distinct xmax points
                H[++top] = P[maxmax]; // push maxmax point onto stack
            }

            bot = top; // the bottom point of the upper hull stack
            i = maxmin;
            while (--i >= minmax) {
                // the upper line joins P[maxmax] with P[minmax]
                if (isLeft(P[maxmax], P[minmax], P[i]) >= 0 && i > minmax) {
                    continue; // ignore P[i] below or on the upper line
                }

                while (top > bot) { // at least 2 points on the upper stack
                    // test if P[i] is left of the line at the stack top
                    if (isLeft(H[top - 1], H[top], P[i]) > 0) {
                        break;  // P[i] is a new hull vertex
                    }
                    else {
                        top--; // pop top point off stack
                    }
                }

                H[++top] = P[i]; // push P[i] onto stack
            }

            if (minmax !== minmin) {
                H[++top] = P[minmin]; // push joining endpoint onto stack
            }

            return top + 1;
        }

    HULL POINTS

As you can see, the points will work with a small group of plot points, but why is JavaScript getting confused and not just plotting the outliers, why is it going into the polygon and back out again?

A: That's quite a lot of code to debug...
You might want to have a look at this library and this example implementation which as per the repository is an implementation of the Graham's Scan Convex Hull algorithm in JavaScript.
It looks like the result is what you want to achieve.
I found version 1.0.4 available here: https://cdn.jsdelivr.net/npm/graham_scan@1.0.4/graham_scan.min.js and the repo has version 1.0.5 so it might be better to use a local copy.
Working code snippet below, with the coords provided in your question:

function initialize() {

  var coords = [{
      'lat': 41.0247669,
      'lon': -74.1226425
    },
    {
      'lat': 41.0410868,
      'lon': -74.13484609999999
    },
    {
      'lat': 41.0238951,
      'lon': -74.13282749999999
    },
    {
      'lat': 41.0309834,
      'lon': -74.1264094
    },
    {
      'lat': 41.0252598,
      'lon': -74.155237
    },
    {
      'lat': 40.9419984,
      'lon': -73.9405831
    },
    {
      'lat': 40.9518704,
      'lon': -73.9264803
    },
    {
      'lat': 40.9530188,
      'lon': -73.9344715
    },
    {
      'lat': 40.6771541,
      'lon': -74.1165864
    },
    {
      'lat': 40.6586571,
      'lon': -74.12123179999999
    },
    {
      'lat': 40.8025724,
      'lon': -74.1505466
    },
    {
      'lat': 40.78835,
      'lon': -74.17700169999999
    },
    {
      'lat': 40.8024772,
      'lon': -74.1492507
    },
    {
      'lat': 40.7995324,
      'lon': -74.1508104
    },
    {
      'lat': 40.7954599,
      'lon': -74.1443422
    },
    {
      'lat': 40.917345,
      'lon': -73.9939529
    },
    {
      'lat': 40.9256096,
      'lon': -74.0012066
    },
    {
      'lat': 40.9114334,
      'lon': -74.0070829
    },
    {
      'lat': 40.9251857,
      'lon': -73.99491619999999
    },
    {
      'lat': 40.923538,
      'lon': -73.9888347
    },
    {
      'lat': 40.9356149,
      'lon': -74.0044661
    },
    {
      'lat': 40.9336639,
      'lon': -74.0126835
    },
    {
      'lat': 40.9168748,
      'lon': -74.0047416
    },
    {
      'lat': 40.9235845,
      'lon': -73.99615659999999
    },
    {
      'lat': 40.9346191,
      'lon': -73.9895914
    },
    {
      'lat': 40.9169838,
      'lon': -74.0046957
    },
    {
      'lat': 40.9319544,
      'lon': -74.0109391
    },
    {
      'lat': 40.924245,
      'lon': -74.00189530000002
    },
    {
      'lat': 40.9247537,
      'lon': -74.0057516
    },
    {
      'lat': 40.936268,
      'lon': -73.99291699999999
    },
    {
      'lat': 40.9354675,
      'lon': -74.00451199999999
    },
    {
      'lat': 40.9336023,
      'lon': -73.9827045
    },
    {
      'lat': 40.9173526,
      'lon': -73.9930577
    },
    {
      'lat': 40.9249738,
      'lon': -73.9951007
    },
    {
      'lat': 40.9114631,
      'lon': -74.0059352
    },
    {
      'lat': 40.9197391,
      'lon': -74.0056024
    },
    {
      'lat': 40.9147328,
      'lon': -74.0110768
    },
    {
      'lat': 40.9357446,
      'lon': -74.0051089
    },
    {
      'lat': 40.9206033,
      'lon': -74.002538
    },
    {
      'lat': 40.9247956,
      'lon': -74.0014362
    },
    {
      'lat': 40.9302183,
      'lon': -73.9943661
    },
    {
      'lat': 40.9320254,
      'lon': -74.0052007
    },
    {
      'lat': 40.6714401,
      'lon': -74.5352054
    },
    {
      'lat': 40.9356751,
      'lon': -73.9807761
    },
    {
      'lat': 40.922373,
      'lon': -73.9908769
    },
    {
      'lat': 40.9317953,
      'lon': -73.9832555
    },
  ];

  var centrePoint = new google.maps.LatLng(0,0);

  var mapOptions = {
    zoom: 9,
    center: centrePoint,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var poly;
  var polyHull;
  var convexHull = new ConvexHullGrahamScan();

  poly = new google.maps.Polygon({
    paths: coords.map(function(item) {
      return new google.maps.LatLng(item.lat, item.lon);
    }),
    strokeColor: '#000',
    strokeOpacity: 0.2,
    strokeWeight: 2,
    fillColor: '#000',
    fillOpacity: 0.1
  });

  var bounds = new google.maps.LatLngBounds();

  coords.forEach(function(item) {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(item.lat, item.lon),
      map: map
    });
    convexHull.addPoint(item.lon, item.lat);
    bounds.extend(new google.maps.LatLng(item.lat, item.lon));
  });

  if (convexHull.points.length > 0) {
    var hullPoints = convexHull.getHull();

    //Convert to google latlng objects
    hullPoints = hullPoints.map(function(item) {
      return new google.maps.LatLng(item.y, item.x);
    });

    console.log(hullPoints);

    polyHull = new google.maps.Polygon({
      paths: hullPoints,
      strokeColor: '#000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#000',
      fillOpacity: 0.35
    });

    polyHull.setMap(map);

    map.fitBounds(bounds);
  }
}
#map-canvas {
  height: 180px;
}


text:
Q: TimeZone Conversion for different Region Current Scenario.
DB server is deployed in US.
Application is deployed in Africa.
(Application fetches data-time from DB server which is in UTC and convert to local time zone which is Africa).
Client is using this application through browser in India.
(when client uses this application than it sees time that is of Africa through out application)
How to handle this so that client in India can see its local time instead of application time(Africa)????

A: this may help: How to get current user timezone in c#
The important function here is new Date().getTimezoneOffset();


text:
Q: Why does strict pragma fails for $a in Perl? The following code has unusual behaviour that I found to be odd. It's just part of a program that works otherwise.
 #!/usr/bin/perl -w

    use strict;

    $a = 0;
    $abc = 0;

 exit 0;

Due to use strict statement Perl insists that I modify the second declaration as:
my $abc = 0;
But it does not do so for $a! I tried this on multiple Linux distros and Perl versions. Could anyone explain the reason please?

A: From perldoc strict

Because of their special use by sort(), the variables $a and $b are exempted from this check

A: $a is used for sort() and as such doesn't require declaration.


text:
Q: Count messages from a channel I would like to clean all my channels and and I'm getting there.
The problem is, it's very, very long ...
message.guild.channels.cache.forEach(c => {
                if (c.isText()) {
                    let CompteurMessage = 0;
                    let CompteurSuppression;
                    c.messages.fetch().then(messages => {
                        messages.forEach(msg => {
                            msg.delete();
                        });
                    });

                    c.send(`Your server is the best, ${message.author}.`);
                }
            });

Do you have any idea how to go much faster, for example counting the number of messages in a channel ?
EDIT :
Now, I clone the channels but they change places ...
c.clone().then((clone) => {
                        clone.send(`Love ${message.author}.`);
                        const originalPosition = c.position;

                        c.delete();
                        clone.setPosition(originalPosition);
                    });

Channels n°3 and 4 change their place.
Thank you

A: Two ways to do this.
Cloning
You can clone the TextChannel using TextChannel.clone.
This stops you having the 14 day limitation using BulkDelete.
const newChannel = await message.channel.clone();
message.channel.delete();

newChannel.send('The channel has been purged.');

BulkDelete
You can delete all the messages in the last 14 days very easily.
await message.channel.messages.fetch();
const messageCount = message.channel.messages.cache.map(x => x).length;
message.channel.bulkDelete(messageCount, true);

Note: Not the most elegant solutions since it's late at night but this should help you out.


text:
Q: Is this possible to enable/disable mobile KeyPad programmatically using j2me midp2.0? I am using j2me midp2.0 in Sun Java wireless toolkit 2.5.2. Now I want to enable and disable my mobile keypad programmatically.
How can I do it?

A: AFAIK, it's not possible. You can't do with j2me.


text:
Q: Convert coordinates from picture to textpos I am trying to convert some code from using the picture environment to textpos for a titlepage but I have run into problems getting the text to align.The coordinates are given in points.
the original text is placed with
\AddToShipoutPicture*{\put(50,583.5){\fontsize{20 pt}{22pt}\tyk \OPGAVE}}

where the t-coordinate is given form the bottom of a (A4) page presumably with the lower left corner at the coordinates.
And the new text:
\begin{textblock}{200}[0,1](50,258.5)
     \noindent\fontsize{20 pt}{22 pt} \tyk \OPGAVE
\end{textblock}

where the y coordinates is given from the top of the page. I calculated the new y coordinates by y_new = 842-583.5=258.5, since the vertical dimension of a A4 page is 842 points.

The red text is the original.
Any assistance would be greatly appreciated!


text:
Q: How to get correct bounding box when camera is at an angle I am new to machine learning and currently I am using the Google Coral USB accelerator and Rapsberry Pi to perform object detection. When I point the Raspberry Pi camera to image right in front, the object is detected and bounding box is drawn correctly as shown below.

However, when the camera is at an angle, the bounding box is completely wrong as below:

How do I figure out the correct bounding box coordinates for the object when the camera is at an angle?


text:
Q: iPhone detecting Bluetooth Device I'm using the HeartMonitor example for CoreBluetooth, with a iPhone 5.
Right now I have a Bluetooth 4.0 dongle (bought off ebay), in the Dongle settings I set it as a headset. I am able to see/pair this in the iPhone Bluetooth settings in the iPhone. However using the HeartMonitor sample code (adjusted UUID option to Nil) but I'm unable to see any devices scanned. I've also tried UUID 180A (broadcast profile), 1108 (headset) and various others but no luck.
- (void) startScanningForUUIDString:(NSString *)uuidString
{
    [centralManager scanForPeripheralsWithServices:nil options:nil];

}

A: I did not put the options to nil.
I did use a NSDictionnary: NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:FALSE], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
Don't forget to use the CentralManager.


text:
Q: Java Spring boot, Spring batch, multi datasource circular references error I have a little test project to config several data sources on a spring batch, boot application.
As far as I see is ok, but I always have the jpaMappingContext  does not support circular references error. .
This is my dependencies. .
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

My database config
@Configuration
public class DatabaseConfiguration {

    @Bean
    @DependsOn({"entityManagerFactory"})
    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();

    jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
        return jpaTransactionManager;
    }

    @Bean
    @DependsOn({"dataSource"})
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean result = new LocalContainerEntityManagerFactoryBean();
    result.setPackagesToScan("juanjo.domain.entity");
    result.setDataSource(dataSource);

    HibernateJpaVendorAdapter obj = new HibernateJpaVendorAdapter();
    obj.setDatabasePlatform("org.hibernate.dialect.PostgreSQLDialect");
    obj.setShowSql(true);
    obj.setGenerateDdl(false);
    result.setJpaVendorAdapter(obj);
    return result;
    }

    @Bean(name = "dataSourceMaster", destroyMethod = "close")
    @ConfigurationProperties(prefix = "spring.datasource.db-1")
    public DataSource dataSourceMaster() {
    return DataSourceBuilder.create().build();
    }

    @Bean(name = "dataSourceOrigin", destroyMethod = "close")
    @ConfigurationProperties(prefix = "spring.datasource.db-O")
    public DataSource dataSourceOrigin() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dataSourceReplica", destroyMethod = "close")
    @ConfigurationProperties(prefix = "spring.datasource.db-2")
    public DataSource dataSourceReplica() {
        return DataSourceBuilder.create().build();
    }

    @Bean()
    @DependsOn({"dataSourceMaster", "dataSourceOrigin", "dataSourceReplica"})
    public DataSource dataSource() {
        RoutingDataSource result = new RoutingDataSource();
        Map<Object, Object> params = new HashMap<Object, Object>();
        params.put(DbType.MASTER, dataSourceMaster());
        params.put(DbType.REPLICA1, dataSourceReplica());
        params.put(DbType.ORIGIN, dataSourceOrigin());
        result.setDefaultTargetDataSource(dataSourceMaster());
        result.setTargetDataSources(params);
        result.afterPropertiesSet();
        return result;
    }

}

My job:
@Configuration
public class CountryBatch {
    @Autowired
    private CountryWriter countryWriter;
    ...
}

@Component
public class CountryWriter implements ItemWriter<CountryDTO> {
    @Autowired
    private CountrySplit countrySplit;
    ...
}

@Component
public class CountrySplit {
    @Autowired
    private CountryRepository repository;
    ...
}

public interface CountryRepository extends JpaRepository<Country, Long>
{
}

And the error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'countryBatch': Unsatisfied dependency
expressed through field 'countryWriter'; nested exception is org.
springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'countryWriter': Unsatisfied dependency
expressed through field 'countrySplit'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'countrySplit': Unsatisfied dependency
expressed through field 'repository'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'countryRepository': Cannot resolve reference to bean
'jpaMappingContext' while setting bean property 'mappingContext';
nested exception is
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'jpaMappingContext':
org.springframework.beans.factory.FactoryBeanNotInitializedException: org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFa
ctoryBean$$EnhancerBySpringCGLIB$$24da9e51 does not support circular
references

I couldn't see the circular dependencies problem.


text:
Q: CSS Image Hover Help I am trying to add a pseudo hover to a  tag, but no image is showing with either css class. Please can you tell me what I am doing wrong as I am new to css.
#AIM a {
    left:420px;
    top:590px;
    position: absolute;
    background-image: url('http://maxk.me/img/aim.png');
}
#AIM a:hover {
    left:420px;
    top:590px;
    position: absolute;
    background-image: url('http://maxk.me/img/aim-hover.png');
}

A: You  has no width or height so there is nowhere for a background image to display.
#AIM a is  a selector for anchor tags inside an element with id #AIM like in this example: http://jsfiddle.net/Paulpro/5yg7t/. You want to select an anchor tag with id="AIM" in which case you should just use an ID selector since ID's are unique. Use this:
#AIM {
    left:420px;
    top:590px;
    position: absolute;
    width: 55px;
    height: 54px;
    background-image: url('http://maxk.me/img/aim.png');
}

#AIM:hover {
    background-image: url('http://maxk.me/img/aim-hover.png');
}

JSFiddle Example

A: #AIM a matches  tags inside of #AIM.
You need to write a#AIM to match  tags that are #AIM.
You can also just write #AIM, since IDs must be unique.

A: Your  tags have no content, so they'll be effectively 0x0 invisible elements. Either add some text:

or give them a size in the CSS:
a#AIM {
   height: 10px;
   width: 10px;
}

or better yet, both.

A: Change the css to the following
a#AIM {
    left:420px;
    top:590px;
    position: absolute;
    background-image: url('http://maxk.me/img/aim.png');
}
a#AIM:hover {
    left:420px;
    top:590px;
    position: absolute;
    background-image: url('http://maxk.me/img/aim-hover.png');
}

Change the HTML to the following

A: Try adding
display: block;

to both classes; then try specifying a width and height...
width: 20px;
height: 20px;

A: The A tag has no idea how big your image is. A is also an inline element, so it stretches to the size of its content (usually the text inside).
You need to:

*

*Define width and height (I'm using 300px)

*Make it a block element
{
        display: block;
        width:300px;
        height:300px;
        left:420px;
        top:590px;
        position: absolute;
        background-image: url('http://maxk.me/img/aim.png');
    }


text:
Q: How to programmatically create a bookmark for another connections user? We want to create bookmarks programmatically and this works fine if the email parameter matches the account of the currently authenticated user.
The question is, how can we create a bookmark for another user ?
Below is the pseudo we use from the SBT.
String apiPath = "/dogear/api/app";
Response<String> postResponse = restClient.doPost(apiPath).parameter("email","another users email").body(body, "application/atom+xml").asString();

The log files are not very helpful, in the client we get an ERROR 400 Bad Request


text:
Q: How to fetch images from firebase storage and show as a thumbnail? I want to develop an application in which recycler listview fetch data from firebase database shows details to user like name, age, city and profile picture.
How to get profile picture from firebase storage and show in recycler list view and show as thumbnail.
     @Override
     public void onBindViewHolder(final UserViewHolder holder, final int position, Context context) {

    this.context = context;

    final BusinessDetailModel businessDetailModel = list.get(position);

    Picasso.with(context).load(list.get(position).getImageUrl()).resize(80, 80).into(holder.thumbnail);
    holder.businessName.setText(businessDetailModel.businessName);
    holder.businessCity.setText(businessDetailModel.city);
    holder.businessRating.setText(businessDetailModel.ratingValue + "");

Solution,
You can add global variable:
   private Context context;

then assign the context from here:
   @Override
    public FeedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {

View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.feedholder, parent, false);

ViewHolder vh = new ViewHolder(v);
// set the Context here
context = parent.getContext();
return vh;
}

A: You first need to get the download url and use a image loading library to fetch and display the image.
I would recommend using Picasso

A: When you have uploaded image in Firebase Storage, they have given you the URL for that image.
Use that path and make code for display thumbnail.
Firebase didn't provided the Thumbnail, so you have to make code for that.


text:
Q: jquery delete element In sharepoint content editor I have created a jquery to create a tab for list item and that jquery will insert  element tag to style the tabs on the paeg load,but problem is that when ever the page loaded again and again the  element tag also recreated .so, that  element tag created  many times as we visited it is created .So, i need to delete the  element tag before it is created again.
<script src="/jquery.min.js" type="text/javascript"></script>
<script src="/TabsForSharePointFormscolor.js" type="text/javascript"></script>
<script type="text/javascript">

var tabConstructor = {
    tabs:[ {name:'Activity',fields:['Name'], mouseOver:'This is the first tab',tabStyle:''}],
    settings:{
        viewAllFields:{show:true,name:'All fields',mouseOver:'This tab shows all fields',tabStyle:'',clickFunction:''},
        orphanFields:{show:true,name:'...',mouseOver:'All orphan fields',tabStyle:''},
        breakTabRowAt:null,
        hoverTabColor:'#FFF68F',
        selectedTabColor:'#B9D3EE'
    }
};

init_buildTabbedForm(tabConstructor,1);

  </script>

In this init_buildTabbedForm will create  element.

A: Try jQuery Empty. So something like
$(".tabId").empty()


text:
Q: Golang variable assignment Is there a way in go to assign two variables to a function that returns two values when you have one variable declared and the other not.
For example:
var host string
if host, err := func(); err != nil {}

In the above code, host is declared but err isn't. I want a clean way to do this other than declaring err

A: In your example you simply shouldn't be declaring host. There is no way to do partial assignment like that... Either your using := which is short hand for declaration and assignment or you using = and you're doing assignment only. I personally very rarely write the word var in Go.
To be clear, if you have one variable that has already been declared with one or more that have not, you're allowed to use := to assign to it, but the inverse is not true. Meaning you cannot use = if one or more of the left hand side values haven't been declared already.

A: When you use := in an if like that, you will always get new variables declared in the scope of the if. Following the if, the value of host will be the same as it was before. If you want to do this, you need to declare both host and err before the if (and don't use := in the if).


text:
Q: Not able to send form parameters to the server We are getting a issue wherein while submitting a form via javascript one of the parameters (invoiceCodes) is not sent to the server. Below is the snippet of the javascript code.
The flow is as follows. When user clicks on "Print" button validateTransition() method is called in which we make a ajax call. After response of that ajax we call couponPopup(url, invoiceCodes). In this function we submit newWinForm but sometimes invoiceCodes parameter is sent empty.
Also checkForInvoiceCode is true in this case which require user to input invoice codes
Is there anything wrong in the manner in which we are putting values in the form which may lead to invoiceCodes being not sent sometimes.
function couponPopup(url, invoiceCodes)
{
    var selectedOrders = '';
    $(".selectedOrder:checked").each(function() {
        selectedOrders += $(this).val() + ',';
    });

    var frm = document.forms["newWinForm"];
    frm.action = url;
    frm.selectedShipments.value= selectedOrders;
    frm.invoiceCodes.value = invoiceCodes;
    console.log("Selected orders are "+selectedOrders);
    console.log("Invoice codes with them in order are "+invoiceCodes);
    document.getElementById("hiddenInvoiceCodes").value=invoiceCodes;
    document.getElementById("hiddenselectedShipments").value=selectedOrders;
    frm.submit();
    return false;
}

function validateTransition() {
    $('#statusChangeSuccess').hide();
    $('#statusChangeFail').hide();

    var selectedOrders = '';
    var invoiceCodes = '';
    var flag = 0;
    var spaceError = 0;
    var commaError = 0;

    $(".selectedOrder:checked").each(function() {
        selectedOrders += $(this).val() + ',';
        <c:if test="${checkForInvoiceCode}">
        var emptyPattern = /^\s*$/;
        var commaPattern = /,/;
        var inv_code = $("#invoice-code-" + $(this).val()).val().trim();
        if (emptyPattern.test(inv_code)) {
            spaceError = 1;
            flag = 1;

        }
        if (commaPattern.test(inv_code)) {
            commaError = 1;
            flag = 1;

        }
        invoiceCodes += inv_code + ",";
        </c:if>
    });

    if(selectedOrders=='') {
        alert('Please select at least one order');
        return false;
    }

    if ( flag ) {
        if ( commaError ) {
            alert('One or more specified codes have comma, please remove comma from them');
        }
        if ( spaceError ) {
            alert('One or more specified codes has been left blank, please fill them up');
        }
        if ( !commaError && !spaceError ) {
            alert('Please contact tech');
        }

        return false;
    }

    var inputdata = {"selectedShipments" : selectedOrders,
        "statusCode" : "PRINT"
    };

    //this is where we are making an ajax call
    jQuery(function($){
            setTimeout(function(){
                var ajaxUrl = '/product/update/';

                $.ajax({url:ajaxUrl, type: "POST", dataType: 'json', data:inputdata , success: function(data) {
                    if(data['status'] == 'success') {
                        //couponPopup function is called where form is submitted
                        couponPopup("${path.http}/product/print/", invoiceCodes);
                        $('#statusChangeSuccess').html(data['message']).show();

                        $(".selectedOrder:checked").each(function() {
                            $("#row-" + $(this).val()).remove();
                        });

                    } else{
                        $('#statusChangeFail').html(data['message']).show();
                    }
                }});
        }, 10 );
    });

    return false;
}

<form id="newWinForm" name="newWinForm" action="" method="post" target="_blank" >
    <input type="hidden" id="hiddenselectedShipments" name="selectedShipments" value="" />
    <input type="hidden" id="hiddenInvoiceCodes" name="invoiceCodes" value="" />
</form>

Controller for the form. Invoice codes is sometimes empty even when we are sending it from client side.
@RequestMapping("/product/print")
public void printSelectedPendingOrders(@RequestParam("selectedShipments") String selectedShipments,
        @RequestParam(defaultValue = "", value = "invoiceCodes", required = false) String invoiceCodes, ModelMap modelMap, HttpServletResponse httpResponse)
        throws IOException, DocumentException, ParserConfigurationException, SAXException {


text:
Q: Trying to understand simple big number calculations I am trying to better understand how 'big numbers' libraries work, (like GMP for example).
I want to write my own function to Add() / Subtract() / Multiply() / Divide()
The class is traditionally defined ...
std::vector<unsigned char> _numbers; // all the numbers
bool _neg; // positive or negative number
long _decimalPos; // where the decimal point is located
                  // so 10.5 would be 1
                  //    10.25 would be 2
                  //    10 would be 0 for example

First I need to normalise the numbers so I can do
Using 2 numbers
    10(x) + 10.25(y) = 20.25
For simplicity, I would make them the same length,
For x:
    _numbers = (1,0,0,0) decimal = 2
For y:
    _numbers = (1,0,2,5) decimal = 2
And I can then reverse add x to y in a loop
...
// where x is 10.00 and y is 10.25
...
unsigned char carryOver = 0;
int totalLen = x._numbers.size();
for (size_t i = totalLen; i > 1 ; --i )
{
    unsigned char sum = x._numbers[i-1] + y._numbers[i-1] + carryOver;
    carryOver = 0;
    if (sum > _base)
    {
     sum -= _base;
     carryOver = 1;
    }
    numbers.insert( number.begin(), sum);
}

// any left over?
if (carryOver > 0)
{
  numbers.insert( number.begin(), 1 );
}

// decimal pos is the same for this number as x and y

...

The example above will work for adding two positive numbers, but will soon fall over once I need to add a negative number to a positive number.
And this gets more complicated when it comes to subtracting numbers, then even worse for multiplications and divisions.
Can someone suggest some simple functions to Add() / Subtract() / Multiply() / Divide()
I am not trying to re-write / improve libraries, I just want to understand how they work with numbers.

A: addition and substractions are pretty straightforward
You need to inspect signs and magnitudes of operands and if needed convert the operation to/from +/-. Typical C++ implementation of mine for this is like this:
//---------------------------------------------------------------------------
arbnum arbnum::operator + (const arbnum &x)
    {
    arbnum c;
    // you can skip this if you do not have NaN or Inf support
    // this just handles cases like adding inf or NaN or zero
    if (  isnan() ) return *this;
    if (x.isnan() ) { c.nan(); return c; }
    if (  iszero()) { c=x; return c; }
    if (x.iszero()) return *this;
    if (  isinf() ) { if (x.isinf()) { if (sig==x.sig) return *this;
                    c.nan(); return c; } return *this; }
    if (x.isinf()) { c.inf(); return c; }
    // this compares the sign bits if both signs are the same it is addition
    if (sig*x.sig>0) { c.add(x,this[0]); c.sig=sig; }
    // if not
    else{
        // compare absolute values (magnitudes)
        if (c.geq(this[0],x)) // |this| >= |x| ... return (this-x)
                {
                c.sub(this[0],x);
                c.sig=sig;    // use sign of the abs greater operand
                }
        else    {             // else return (x-this)
                c.sub(x,this[0]);
                c.sig=x.sig;
                }
        }
    return c;
    }
//---------------------------------------------------------------------------
arbnum arbnum::operator - (const arbnum &x)
    {
    arbnum c;
    if (  isnan() ) return *this;
    if (x.isnan() ) { c.nan(); return c; }
    if (  iszero()) { c=x; c.sig=-x.sig; return c; }
    if (x.iszero()) return *this;
    if (  isinf() ) { if (x.isinf()) { if (sig!=x.sig) return *this;
                    c.nan(); return c; } return *this; }
    if (x.isinf()) { c.inf(); c.sig=-x.sig;  return c; }
    if (x.sig*sig<0) { c.add(x,this[0]); c.sig=sig; }
    else{
        if (c.geq(this[0],x))
                {
                c.sub(this[0],x);
                c.sig=sig;
                }
        else    {
                c.sub(x,this[0]);
                c.sig=-x.sig;
                }
        }
    return c;
    }
//---------------------------------------------------------------------------

where:

*

*geq is unsigned comparison greater or equal

*add is unsigned +

*sub is unsigned -
division is a bit more complicated
see:

*

*bignum divisions

*approximational bignum divider
For divisions you need to have already implemented things like +,-,*,<<,>> and for some more advanced approaches you need even things like: absolute comparison (you need them for +/- anyway) , sqr, number of used bits usually separate for fractional and integer part.
The most important is the multiplication see Fast bignum square computation because it is core for most division algorithms.
performance
for some hints see BigInteger numbers implementation and performance
text conversion
If your number is in ASCII or in BASE=10^n digits then this is easy but If you use BASE=2^n instead for performance reasons then you need to have fast functions capable of converting between dec and hex strings so you can actually load and print some numbers to/from your class. see:

*

*How do I convert a very long binary number to decimal?

*How to convert a gi-normous integer (in string format) to hex format?


text:
Q: how to display data to the text field when the marker is clicked I'm using SQL to show marker to leaflet and How can I output the data of a marker into the input text field when the marker is clicked.
(https://milzon.site/web/home.php)
this my script

    Nama Lokasi : <input type="text" style="width: 800px; overflow:  ; " readonly value= "" />

    Alamat : <input type="text" style="width: 800px; overflow:  ; " readonly/>

    Longitude : <input type="text" style="width: 800px; overflow:  ; " readonly/>

    Latitude : <input type="text" style="width: 800px; overflow:  ; " readonly/>

    Core Info : <input type="text" style="width: 800px; overflow:  ; " readonly/>

    Route Info : <input type="text" style="width: 800px; overflow:  ; " readonly/>

A: Hello Fellow Indonesian
hopefully i can help you in some ways
as far as i know leaflet.js let you set an event listener to the marker object.
so basically all you need to do is

*

*give id to all your target input on the html

*set "click" event listener to the marker

*update the target input based on id

check my snippet..
have a nice day
HTML
Nama Lokasi :

<input id="nama" type="text" style="width: 800px; overflow:  ; " readonly value="" />

Longitude :

<input id="longitude" type="text" style="width: 800px; overflow:  ; " readonly/>

Latitude :

<input id="latitude" type="text" style="width: 800px; overflow:  ; " readonly/>

JS
$.getJSON("getData.php", function(data) {
  for (var i = 0; i < data.length; i++) {
    var location = new L.LatLng(data[i].lat, data[i].lng);
    var name = data[i].nama_lokasi;
    var longitude = data[i].longitude;
    var latitude = data[i].latitude;
    var marker = L.marker([data[i].lat, data[i].lng]).addTo(map);
    marker.bindPopup(name);

    // add event onclick to the markers
    marker.on('click', function(name, longitude, latitude) {
      $("#name").val(name)
      $("#longitude").val(longitude)
      $("#latitude").val(latitude)
    });
  }
})


text:
Q: Values inserted twice in Mysql PHP function disburseby_cash($branch,$mode,$date,$amount){

    if ($amount>0){
        $sql="INSERT INTO `pettycash_deliver` SET `branch_id`='$branch',`petCashDel_mode`='$mode',`petCashdel_dt`='$date',`petCashdel_amt`='$amount', `branch_status`='Y',`petCashdel_akBrnch`='N' ";
        return $fin_res=(parent :: selectquery($sql)) ? "OK":"NO";
    }else{
        return "fail";
    }
}

This is my code. When I was try to add some data.. It will inserted double         time. This problem will occurs on some time only.. Kindly give the solution...
Thanks in advance....