text:
Q: How to display iframe with parameters only through javascript I came across this resource where the .js file pulls out the iframe.
Source
The js file:
window.document.write("<iframe src=\"somedomain.com/page.htm\"/>");

However i'm not sure how to add attributes such as width/height/scrolling. Further more i would also like to add an image and link it as well, at the end of the iframe

A: You can use the same method:
window.document.write("<iframe src=\"somedomain.com/page.htm\" width='300' height='900' ></iframe>");

Note that iframe is not a self closing element tag, however most browser will render correctly. Inside the tag you can enter so alternative content incase the browser doesn't support iframes

A: can you get the reference to the Frame somehow such as this..  if its the first iframe on the page then you would use index [0]

function removeScroll()
{
window.parent.frames[0].scrolling="no";
}

A: try using createElement, the native method
      var tempIFrame=document.createElement('iframe');
      tempIFrame.setAttribute('id','RSIFrame');
      tempIFrame.style.border='0px';
      tempIFrame.style.width='0px';
      tempIFrame.style.height='0px';
      IFrameObj = document.body.appendChild(tempIFrame);

      if (document.frames) {
        // this is for IE5 Mac, because it will only
        // allow access to the document object
        // of the IFrame if we access it through
        // the document.frames array
        IFrameObj = document.frames['RSIFrame'];

A: Since this started with document.write, just continue it:
document.write("<iframe src=\"somedomain.com/page.htm\"/ width=200 scrolling='no'>");

Note that HTML doesn't actually require quotes for attributes in certain cases (see width), but they could be added just as with src. Also ' can be used in place of " and it simplifies the escaping (see scrolling). Please be consistent, the above notes are just informational.
Happy coding.


text:
Q: Riak link-walking like a join? I am looking to store pictures in a NoSQL database (<5MB) and link them to articles in a different bucket. What kind of speed does Riak's link walking feature offer? Is it like a RDBMS join at all?

A: Think one-way relationships and as fast as querying normally.  Not as slow as MapReduce.
From:
http://seancribbs.com/tech/2010/02/06/why-riak-should-power-your-next-rails-app/

The first way that Riak deals with
  this is with link-walking. Every datum
  stored in Riak can have one-way
  relationships to other data via the
  Link HTTP header. In the canonical
  example, you know the key of a band
  that you have stored in the "artists"
  bucket (Riak buckets are like database
  tables or S3 buckets). If that artist
  is linked to its albums, which are in
  turn linked to the tracks on the
  albums, you can find all of the tracks
  produced in a single request. As I'll
  describe in the next section, this is
  much less painful than a JOIN in SQL
  because each item is operated on
  independently, rather than a table at
  a time. Here's what that query would
  look like:
GET
  /raw/artists/TheBeatles/albums,,/tracks,_,1
  "/raw" is the top of the URL
  namespace, "artists" is the bucket,
  "TheBeatles" is the source object key.
  What follows are match specifications
  for which links to follow, in the form
  of bucket,tag,keep triples, where
  underscores match anything. The third
  parameter, "keep" says to return
  results from that step, meaning that
  you can retrieve results from any step
  you want, in any combination. I don't
  know about you, but to me that feels
  more natural than this:
SELECT tracks.* FROM tracks   INNER
  JOIN albums ON tracks.album_id =
  albums.id   INNER JOIN artists ON
  albums.artist_id = artists.id   WHERE
  artists.name = "The Beatles" The
  caveat of links is that they are
  inherently unidirectional, but this
  can be overcome with little difficulty
  in your application. Without
  referential integrity constraints in
  your SQL database (which ActiveRecord
  has made painful in the past), you
  have no solid guarantee that your
  DELETE or UPDATE won't cause a row to
  become orphaned, anyway. We're kind of
  spoiled because ActiveRecord handles
  the linkage of associations
  automatically.
The place where the link-walking
  feature really shines is in
  self-referential and deep transitive
  relationships (think has_many :through
  writ large). Since you don't have to
  create a virtual table via a JOIN and
  alias different versions of the same
  table, you can easily do things like
  social network graphs
  (friends-of-friends-of-friends), and
  data structures like trees and lists.

A: Links are not at all similar to JOINs (which involve a Cartesian product), but they can be used for similar purposes in some senses. They are very similar to links in an HTML document.
With link-walking you either start with a single key, or you create a map-reduce job that starts with multiple keys. (Link-walking/traversal is actually a special case of map-reduce.) Those values are fetched, their links filtered against your specification (bucket, tag) and then the matched links are passed along to the next phase (or back to the client).  Of course, all of this is done in parallel (unlike a JOIN) with high data-locality.
Also, map-reduce isn't slow by itself, you just don't have a sophisticated query planner to do the hard work for you; you have to think about how you will query and organize your data around that as necessary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I indent text within a tabular environment? I'm trying to create a table in r markdown where the age groups such as 0-20 and 21-55 are indented:
\documentclass{article}
\begin{document}
\begin{tabular}{lccc}
\toprule
Factors & 2 & 2 & P-Value\\
\midrule
Age\\
0-20 & 2 & 2 & 2\\
21-55 & 2 & 2 & 2\\
\bottomrule
\end{tabular}
\end{document}

I've tried using spaces, \indent, \hspace, \rowgroup (didn't compile in r markdown). Any help is greatly appreciated.

A: For me I like the simplicity of @Bernard and the indentation of @Mico, so I combined the two solutions:
    \begin{tabular}{@{\hspace*{1.8em}}lccc@{}}
    \toprule
    \multicolumn{1}{l}{Factors\hspace*{-1.8em}} & 2 & 2 & P-Value\\
    \midrule
    \multicolumn{1}{l}{Age}  & 2 & 2 & P-Value\\
                      0--20  & 2 & 2 & 2\\
                      21--55 & 2 & 2 & 2\\
    \bottomrule
    \end{tabular}

A: You could insert an \hspace{<some length>} directive at the start of cells. In the example below, I've set the length to 3mm; you're obviously free to choose a different length.

\documentclass{article}
\usepackage{booktabs}
\begin{document}
\noindent
\begin{tabular}{@{}lccc@{}}
\toprule
Factors & 2 & 2 & P-Value\\
\midrule
Age\\
\hspace{3mm}0--20 & 2 & 2 & 2\\
\hspace{3mm}21--55 & 2 & 2 & 2\\
\bottomrule
\end{tabular}
\end{document}

A: A slight improvement for the alignment of the left column (on the endash):
\documentclass{article}
\usepackage{booktabs}

\begin{document}

\noindent
\begin{tabular}{@{}rccc@{}}
\toprule
\multicolumn{1}{l}{Factors\hspace*{0.25em}} & 2 & 2 & P-Value\\
\midrule
\multicolumn{1}{l}{Age}\\
0--20 & 2 & 2 & 2\\
21--55 & 2 & 2 & 2\\
\bottomrule
\end{tabular}

\end{document}


text:
Q: customizing registration fields for new users in phpbb3 i am new to phpbb. i have a requirement where i need to remove some fields from registration page.(Some are mandatory and some are not). Can anybody please suggest where should i edit in file. i already changed in HTML file styles/themename/templets/ucp_register_original.html . but nothing is affecting the main interface.

    {L_LANGUAGE}:
    <select name="lang" onchange="change_language(this.value); return false;">{S_LANG_OPTIONS}</select>

i have disable this for example but it is still showing.

A: open

your_phpbb_root_directory/includes/ucp/ucp_register.php

then find any of these
'S_LANG_OPTIONS'    => (sizeof($lang_row) > 1) ? language_select($user_lang) : '',

and replace with this
'S_LANG_OPTIONS'    => '',

A: Apart from the answer given by Damien Keitel. one more and crucial thing you have to do is to delete cache/tpl_prosilver-se_ucp_register.html.php otherwise it will keep on showing the previous fields which you might have deleted.


text:
Q: GL_SCISSOR_TEST not working I'm using bindings of OpenGL and glfw for Go on OS X 10.7, OpenGL version 3.x.
I enable GL_SCISSOR_TEST and set scissor rectangle to (0, 0, 1, 1). But it has absolutely no effect on the rendering -- the whole viewport is being updated.
Here's the code:
gl.Enable(gl.SCISSOR_TEST)
gl.Scissor(0, 0, 1, 1)
fmt.Printf("scissor enabled = %v\n", gl.IsEnabled(gl.SCISSOR_TEST))
box := make([]int32, 4)
gl.GetIntegerv(gl.SCISSOR_BOX, box)
fmt.Printf("scissor box = %v\n", box)

Console output:
scissor enabled = true
scissor box = [0 0 1 1]

I'm not sure what to make of this. The fact that glIsEnabled() and glGetIntegerv() both report correct values make me think that there is still some state missing that is necessary for activating the scissor test. I tried enabling GL_STENCIL_TEST and initializing glfw with 1 and 8 bits for stencil, still no effect, although glIsEnabled(GL_STENCIL_TEST) returns true.


text:
Q: How to Properly Redirect in AspNetCore 3.0 Action Filter Attribute? I need to redirect to another action for setup if the account setup is not complete.
However, when I use this action filter:
public sealed class AccountSetupFilter : ActionFilterAttribute
    {
        ...
        public override async Task OnActionExecutionAsync(
        ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (context.HttpContext.User.Identity.IsAuthenticated &&
               await UserRequiresServiceAccount(context.HttpContext.User))
            {
                context.Result = new RedirectToActionResult("Setup", "Home", null);
            }
            else
            {
                await base.OnActionExecutionAsync(context, next);
            }
        }
...
}

I get an error:
InvalidOperationException: The model item passed into the ViewDataDictionary is
of type 'Models.SetupModel', but this ViewDataDictionary instance requires a model
item of type 'Models.OriginalControllerModel'.
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object value)

This is not expected because the new view requires a SetupModel. What am I missing?

A: Turns out I had a partial view referenced from the layout page that wanted a model so that it could make a login form. The page would load fine when no model was present as it only used the model for the tag helpers, but it would not work when an actual model was used. The solution was to just add a model="new MyEmptyModel()" to the partial tag helper.


text:
Q: How do I add a TXT file as resource to my EXE file? I have a TXT file containing about 10,000 lines of text. I want to display these lines in a TMemo.
But I don't want to distribute that TXT file my program. How do I integrate it into my EXE file as a resource WITHIUT using stringtable {} because this requires an identifier for each line (so I will have to add 10000 identifiers).
_
I have Delphi XE

A: I usually create an RC file (which is basically an text file) for this kind of resources, then add line like
MyText RCDATA ..\resources\filename.txt

for each file / resource into the RC file. If the RC file is part of the project it will be compiled (to res) and linked into exe. To use the resource I usually use TResourceStream, ie
var ResStream: TResourceStream;
ResStream := TResourceStream.Create(hInstance, 'MyText', RT_RCDATA);

BTW if the RC file wasn't added to the project automatically when you created it in the IDE then add line like
{$R 'myExtraRes.res' 'myExtraRes.RC'}

into the project file, right after the uses list.

A: Since you want to display the text in a TMemo, you could just copy/paste the text directly into the TMemo.Lines property editor at design-time. The text will be included in the owning Form/Frame's DFM resource at compile-time and loaded into the TMemo automatically at run-time for you.


text:
Q: PHP cURL - issues with accessing HTTPS site I have been using cURL code to access Beanstream for awhile now, and all of a sudden it stopped working as of yesterday.  I have determined that this has to do with accessing the HTTPS URL for Beanstream processing, as if I test that same code and just go to the HTTP URL, it works (of course it returns an insecure connection code).
Prior to the below code I was setting VERIFYPEER / VERIFYHOST to FALSE, which was working up until yesterday.
    $url = 'https://www.google.com';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_CAINFO, "/xxxx/public_html/_cert/GeoTrustGlobalCA_google.crt");

    $getResponse = (curl_exec($ch));
    curl_close($ch);

    print_r($getResponse);

I have setup the above test code to try and access Google via HTTPS.  I had read that a proper connection requires the VERIFYPEER / CAINFO options to be set, which I have done and grabbed the Google .crt and placed it on the web server as well.
I still get a 503 Service Unavailable error back though.

The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.
Additionally, a 503 Service Unavailable error was encountered while
  trying to use an ErrorDocument to handle the request.


text:
Q: Reescribir una linea en un archivo.txt Java Tengo un archivo txt con unos datos:
Datos
Juan-123
----
Pedro-456
----
Jose-789
----

Y quiero buscar en el archivo la linea igual a Pedro-456 y reescribir los numeros 456 de esta por 0022, Sin alterar el contenido de las otras lineas. Mi codigo es el siguiente:
File ArchivoUsuarios = new File("ArchivoUsuarios.txt");
        FileReader fr = new FileReader(ArchivoUsuarios);
        BufferedReader Reader = new BufferedReader(fr);
          String User = Pedro;
          String ActPassword = 456;
          String NewPassword = 0022;
          String Wanted = User + "-" + ActPassword;
        try {
             while(Reader.readLine() != null){
                 String Aux = Reader.readLine();
                 String input = "";
                 if(Aux != null){
                     if (Aux.equals(Wanted)){
                         input += Aux.replace(ActPassword,NewPassword);
                         FileOutputStream fileOut = new FileOutputStream(ArchivoUsuarios);
                         fileOut.write(input.getBytes());
                         fileOut.close();
                     }
                 }
             }
        }catch (IOException ex) {}

El problema es que con este codigo me borra todo el contenido del archivo y me deja escrito unicamente el nuevo Pedro-0022, Como puedo solucionarlo?

A: Concatenas las lineas recorridas en un variable de salida dentro del While, cuando finalice de recorrer las lineas el String final sera escrito en el archivo con File.write.
   File ArchivoUsuarios = new File("file.txt");
   FileReader fr = new FileReader(ArchivoUsuarios);
   BufferedReader Reader = new BufferedReader(fr);
   String User = "Pedro";
   String ActPassword = 456;
   String NewPassword = 0022;
   String ln = "\n";
   String Wanted = User + "-" + ActPassword;
   try {
        StringBuilder Output = new StringBuilder() // equivale a String Output = ""; pero con mejor rendimiento
        while(Reader.readLine() != null ){
            String linea = Reader.readLine();
            if(linea != null && ){
                if (Aux.equals(Wanted)) {
                    Output.append(Aux.replace(ActPassword,NewPassword) + ln)
                } else {
                    Output.append(linea + ln);
                }
            }
        } // end while
        FileOutputStream fileOut = new FileOutputStream(ArchivoUsuarios);
        fileOut.write(Output.toString().getBytes());
        fileOut.close();
   }
   catch (IOException ex) {

   }


text:
Q: Accessing ASP.NET MVC routing parameters in AngularJS $routeParams I'm a newbie working with AngularJs routing in Asp.net mvc. I've read quite a lot of articles on internet already and might still have a little confusion when it comes to routing.
My problem is, i have multiple MVC controllers take these two for example Reviews and Broker.
In _Layout.cshtml
@Html.ActionLink("See Review", "Index", "Reviews", new { reviewId = 1299 }, null)

My Index action on Reviews controller takes the reviewId. My URL right now takes the form as:
http://localhost:52881/Reviews/Index?reviewId=1299

I want to get this reviewId in my angular controller therefore i have declared my route as:
var reviewModule = angular.module('reviewModule')
reviewModule.config(function ($routeProvider) {
var basePath = 'App/views/partial/';
$routeProvider.
    when('/', {
        redirectTo: '/reviews'
    }).
    when('/reviews', {
        templateUrl: basePath + 'review/review.html',
        controller: 'reviewscontroller'
    });

});
Now when i run the application and click on See Review link, my url becomes
http://localhost:52881/Reviews/Index?reviewId=1299#/reviews/

That's probably because angular routing engine took the url after the mvc querystring has ended and called the redirectTo '/reviews'.
In my reviewscontroller.js when i try to get the reviewId, i get an undefined probably because nothing was transferred after the #/reviews/ to angular route. Here is how i am getting the parameter in reviewscontroller.js controller.
console.log($routeParams.listingNumber);

My question is, how asp.net mvc action parameters can become the part of the angular route so that they can later be accessed for further processing?


text:
Q: Django form wizard multiple formsets on one page I am trying to create a form in Django with the form wizard where there are multiple (repeating) formsets in the same step of the wizard.
What I have is:
# forms.py
class FormStep1A(forms.Form):
    answerA = forms.CharField(max_length=100)
    remarkA = forms.CharField(widget=forms.Textarea)

class FormStep1B(forms.Form):
    answerB = forms.CharField(max_length=100)
    remarkB = forms.CharField(widget=forms.Textarea)

class FormStep1(forms.Form):
    partA = formset_factory(FormStep1A)
    partB = formset_factory(FormStep1B)

and
# urls.py
STEPS = (
    ('1', FormStep1),
    # ...
)
# FormWizard is a subclass of NamedUrlSessionWizardView
wizard = FormWizard.as_view(STEPS, url_name='form_new_step')
urlpatterns = patterns(
    '',
    url(r'^new/(?P<step>.+)/$', wizard,
        name='form_new_step'),
    url(r'^new/$', wizard, name='form_new'),
)

And my template looks the same as in the documentation. However, my form is rendered empty with no fields at all.
I know there are similar questions or recipes out there:

*

*Django formwizard with formsets and forms on same page

*django wizard, using form and formset in the same step

*Combining a Form and a FormSet in Django: How to pass them in the context?

But I just cannot get this to work. Any help is much appreciated, thank you!
UPDATE: My template looks like this:
{% extends 'base.html' %}

{% load i18n %}

{% block head %}
  {{ wizard.form.media }}
{% endblock %}

{% block content %}

{% trans "Questionnaire" %}

Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}

        <form action="" method="post">
          {% csrf_token %}
          {{ wizard.management_form }}
          {% if wizard.form.forms %}
            {{ wizard.form.management_form }}
            {% for form in wizard.form.forms %}
              {{ form }}
            {% endfor %}
          {% else %}
            {{ wizard.form }}
          {% endif %}
          {% if wizard.steps.prev %}
            <button class="button tiny" name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "First step" %}</button>
            <button class="button tiny" name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "Prev step" %}</button>
          {% endif %}
          <input class="button tiny" type="submit" value="{% trans "Submit" %}"/>
        </form>

{% endblock %}


text:
Q: Custom Queue Class Iteration and Data Retrieval C# So I'm working in Visual Studio 2015 with a few custom classes. One of which is called MinPriorityQueue, and it is a priority queue that, in this situation, allows me to retrieve the object of MinimumPriority in the queue via a property MinimumPriority. There is also a method called RemoveMinimumPriority, which is self-explanatory.
I am not allowed to modify this method, it was pre-made for us for this assignment, otherwise I would have already found a simple solution.
My program is meant to compare two text files, and return a value based off a certain equation which isn't important as far as this post goes. The problem I am having is within my UserInterface code. Here is my click event for the 'Analyze' button on my GUI.
private void uxAnalyze_Click(object sender, EventArgs e)
    {
        Dictionary<string, StoreWord> dictionary = new Dictionary<string, StoreWord>();
        const int _numFiles = 2;
        MinPriorityQueue<float, StoreInfo> minQueue = new MinPriorityQueue<float, StoreInfo>();
        int numWords1 = 0;
        int numWords2 = 0;

        //Process Both Input Files
        using (StreamReader sr = new StreamReader(uxTextBox1.Text))
        {
            for (int i = 0; i < _numFiles; i++)
            {
                if (i == 0)
                {
                    dictionary = ReadFile(dictionary, uxTextBox1.Text, i, out numWords1);
                }
                if (i == 1)
                {
                    dictionary = ReadFile(dictionary, uxTextBox2.Text, i, out numWords2);
                }
            }
        }

        int[] numWords = new int[2];
        numWords[0] = numWords1;
        numWords[1] = numWords2;

        //Get 50 Words with Highest Combined Frequencies
        foreach(var entry in dictionary.Values)
        {
            StoreInfo freq = new StoreInfo(entry, numWords);
            minQueue.Add(freq, Convert.ToSingle(entry[0] + entry[1]));
            if(minQueue.Count > 50)
            {
                minQueue.RemoveMinimumPriority();
            }
        }

        //Compute and Display the Difference Measure
        float diffMeasure = 0;
        float temp = 0;
        foreach( x in minQueue)

        for (int i = 0; i < minQueue.Count; i++)
        {
            temp += minQueue.????; //This is where my problem stems
        }

        diffMeasure = (float)(100 * Math.Sqrt(temp));
    }

A few lines from the end you will see a comment showing where my problem is located. The MinPriorityQueue (minQueue) has two parameters, a Priority, and a Value, where the Priority is a Float, and the Value is another class called StoreInfo. This class has an Indexer, which will return information from a different file depending on what the index is. In this case, there are only two files. For example: StoreInfo[i] returns the frequency of a word in the ith text file.
Ideally, my code would look like this:
for (int i = 0; i < minQueue.Count; i++)
{
    temp += (minQueue.minimumValue[0] - minQueue.minimumValue[1])*(minQueue.minimumValue[0] - minQueue.minimumValue[1]);
}
diffMeasure = (float)(100 * Math.Sqrt(temp));

Problem is, that would require a minimumValue property, which I don't have access to. All I have is minimumPriority.
As far as I can see, there is no other way for me to get the Values that I need in order to get the frequencies that I need to get from the indexer and put into the equation.
Help is much appreciated.

A: Alright guys, I've been thinking at this for far too long, and it doesn't seem like anyone else sees another solution either.
At this point, I'm just going to go with the logical solution and add another property into the MinPriorityQueue class, even though it is against my professor's wishes.
Thank you all anyway.


text:
Q: Label value is outside the valid range X = tf.placeholder(shape=(1, 5, 7), name='inputs', dtype=tf.float32)
X_flat = tf.layers.flatten(X)
y = tf.placeholder(shape=(1), name='outputs', dtype=tf.int32)
hidden1 = tf.layers.dense(X_flat, 150, kernel_initializer=he_init)
hidden2 = tf.layers.dense(hidden1, 50, kernel_initializer=he_init)
logits = tf.layers.dense(hidden2, 1, kernel_initializer=he_init)
with tf.name_scope("loss"):
    xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)
    loss = tf.reduce_mean(xentropy, name="loss")

So I get the following error:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Received a label value of 1 which is outside the valid range of [0, 1).  Label values: 1

My labels have integers that range from 0 to 4. I'm curious as to why this is not working. When I worked with MNIST in a sample code, I don't think the y training set was in the range of 0 to 1, but apparently that is what is going on here.
How do I make the cross entropy function work? Is there any sort of normalization which will make the code work?
Also how come MNIST can use integers but this one cannot for the labels?

A: Edit
Just to be sure, this is what I changed into.
X = tf.placeholder(shape=(1, 5, 7), name='inputs', dtype=tf.float32)
X_flat = tf.layers.flatten(X)
y = tf.placeholder(shape=(1), name='outputs', dtype=tf.int32)
hidden1 = tf.layers.dense(X_flat, 150, kernel_initializer=he_init)
hidden2 = tf.layers.dense(hidden1, 50, kernel_initializer=he_init)
logits = tf.layers.dense(hidden2, 5, kernel_initializer=he_init)
with tf.name_scope("loss"):
    xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)
    loss = tf.reduce_mean(xentropy, name="loss")

This runs without problem on my end.
Original
Okay. So if your y variable has range (0,4), then your logit needs to have the shape (batch_size, 5) (in your case, (1,5)), since each value is your model's confidence on a particular label.
This:
logits = tf.layers.dense(hidden2, 1, kernel_initializer=he_init)

Needs to be this:
logits = tf.layers.dense(hidden2, 5, kernel_initializer=he_init)

To do even better, you should probably define these variables.
num_classes = 5
# ...
logits = tf.layers.dense(hidden2, num_classes, kernel_initializer=he_init)
# ...


text:
Q: store variable value inside a if statement 1st if condition:
if (currentQuestionIndex == 2) {
    var xvalue = currentscore;
}

2nd if condition: (note: current score increments for every currentQuestionIndex)
if (currentQuestionIndex == 5 && currentscore ==xvalue) {
    console.log('thanks for your participation')
}

I want to access the value of xvalue in 1st if condition and reference it in 2nd if condition. Is there any way to store value of a variable and reference it later without regards to if condition

A: Just define the variable xvalue outside of if statement:

///Just for testing
var currentQuestionIndex = 2
var currentscore = 2
///

var xvalue = 0;

if (currentQuestionIndex == 2) {
  xvalue = currentscore;
}

///Just for testing
currentQuestionIndex = 5
currentscore = 4
console.log('xvalue: ' + xvalue)
///

if (currentQuestionIndex == 5 && currentscore == xvalue) {
  console.log('thanks for your participation')
  ///Just for testing
  console.log('xvalue: ' + xvalue)
  ///
}

And read about variable scopes, for example here.

A: Actually, you can access a variable declared with var inside if statement. A if block (or any block) does not create a new scope: in JavaScript, only a function do that.
This is valid (example from the docs):
if (true) {
  var x = 5;
}
console.log(x);  // x is 5

This happens because JavaScript interpreter scans your function before executing it, and keep track of all variable declarations (like moving it to the top).
So, the above code is equivalent to (interpreter perspective):
var x;

if (true) {
  x = 5;
}
console.log(x);  // x is 5

Quoting from MDN:

JavaScript before ECMAScript 2015 does not have block statement scope;
  rather, a variable declared within a block is local to the function
  (or global scope) that the block resides within.

As pointed, this behavior changes with the introduction of ECMAScript 2015 let.
if (true) {
  let x = 5;
}
console.log(x);  //x is not defined

So, to use your code as an example, this will run fine:
/* arbitrary values */
var currentQuestionIndex = 2;
var currentscore = 10;

if (currentQuestionIndex == 2) {
    var xvalue = currentscore; //declared inside if block
}

if (currentQuestionIndex == 2 && xvalue == 10) { //I can read here
    console.log('value of xvalue: ' + xvalue); //can read here too: will print 10
    console.log('thanks for your participation')
}

Anyway, just because you can, doesn't mean you should. As a matter of readability and code organization, a recommended practice is to declare your variable at the beginning of your scope (global, if outside any function, or local, if inside a function).

A: You can set your xvalue variable outside of your if statement.
var xvalue = 0;
or simply:
var xvalue;
This way the variable is always able to be accessed by any other function, even if you haven't given it a value.

A: Just declare xvalue outside the first if like this:
var xvalue; // decalare it here so it can be accessed by both if statements (probably you'll have to initialize it with something)
if (currentQuestionIndex == 2) {
    xvalue = currentscore; // don't redeclare it here so you won't shadow the above one
}

Read more about scopes, variables lifetime and shadowing!


text:
Q: C# json custom serializing I have created a custom label object in c# and I need to make json object from this object.
But I have derived the Label from the 'Label' control to custom label object.
After serializing custom label object, json is getting filled with label properties.
But, I don't need it. I need to pass only the custom label object.
This is custom label :
public class customLabel:Label
{

        public string X { get; set; }

        public string Y { get; set; }

        public string H { get; set; }

        public string W { get; set; }

        public string FontName { get; set; }

        public string FontSize { get; set; }

        public string Type { get; set; }

        public string Align { get; set; }

        public string _Text { get; set; }

}

I am using  Newtonsoft.Json  for json serializng

A: Create a custom JsonConvertor that includes the properties you want.
Then pass it to SerializeObject to control the serialization.
string result = JsonConvert.SerializeObject(
                     customLabel,
                     Formatting.Indented,
                     new CustomLabelConverter(typeof(CustomLabel)));

A: Take a look at this Ignore Base Class Properties in Json.NET Serialization
[JsonObject(MemberSerialization.OptIn)]
public class customLabel:Label
{
    [JsonProperty("X")]
    public string X { get; set; }

    [JsonProperty("Y")]
    public string Y { get; set; }

    ...
    public string H { get; set; }

    public string W { get; set; }

    public string FontName { get; set; }

    public string FontSize { get; set; }

    public string Type { get; set; }

    public string Align { get; set; }

    public string _Text { get; set; }

}

but you need to put JsonProperty to all any property you need to serialize it

A: Try something like this:
customLabel yourLabel = new customLabel();

yourLabel.X = 50;
yourLabel.Y = 20;
//....

string output = JsonConvert.SerializeObject(yourLabel);
//output contains the serialized object

customLabel deserializedLabel = JsonConvert.DeserializeObject<customLabel>(output);

edit:
Change your class to this:
[DataContract]
public class customLabel:Label
{
     [DataMember]
     public string X { get; set; }
     [DataMember]
     public string Y { get; set; }
     [DataMember]
     public string H { get; set; }
     [DataMember]
     public string W { get; set; }
     [DataMember]
     public string FontName { get; set; }
     [DataMember]
     public string FontSize { get; set; }
     [DataMember]
     public string Type { get; set;
     [DataMember]
     public string Align { get; set; }
     [DataMember]
     public string _Text { get; set; }
}

Now only the properties with the attribute [DataMember] should be included
And take a look at the documentation: https://www.newtonsoft.com/json/help/html/SerializingJSON.htm


text:
Q: Catch Textbox Scroll Event? Textbox or richtextbox, only thing i want is triggering a function when scrollbar moves.
I already found GetScrollPos and SetScrollPos. I thought of checking scrollbar position periodically but there must be a better way. So, what is the better way?
Update: Using WinForms

A: Assuming WinForms, you can try pinvoking:
public class MyRTF: RichTextBox {

  private const int WM_HSCROLL = 0x114;
  private const int WM_VSCROLL = 0x115;
  private const int WM_MOUSEWHEEL = 0x20A;

  protected override void WndProc(ref Message m) {
    base.WndProc(ref m);

    if (m.Msg == WM_VSCROLL || m.Msg == WM_HSCROLL || m.Msg == WM_MOUSEWHEEL) {
      // scrolling...
    }
  }

}

A: Adapted the accepted answer to include HorizontalScrollPosition and VerticalScrollPosition properties (to get and set the scroll positions) and ScrollChanged event (which uses .NET's ScrollEventArgs). ScrollChanged will also fire on key navigation and text modification as well as during selection drag, control resize, and font resize.
  /// <summary>
  /// TextBox with support for getting and setting the vertical scroll bar
  /// position, as well as listening to vertical scroll events.
  /// </summary>
  public class ScrollTextBox : System.Windows.Forms.TextBox
  {

     public ScrollTextBox()
     {  _components = new System.ComponentModel.Container();
        // Calculate width of "W" to set as the small horizontal increment
        OnFontChanged(null);
     }

     [  System.ComponentModel.DefaultValue(0)
     ,  System.ComponentModel.Category("Appearance")
     ,  System.ComponentModel.Description
        (  "Gets or sets the vertical scroll bar's position"
        )
     ]
     public int VerticalScrollPosition
     {  set { SetScroll(value, Win32.WM_VSCROLL, Win32.SB_VERT); }
        get { return GetScroll(Win32.SB_VERT); }
     }

     [  System.ComponentModel.DefaultValue(0)
     ,  System.ComponentModel.Category("Appearance")
     ,  System.ComponentModel.Description
        (  "Gets or sets the horizontal scroll bar's position"
        )
     ]
     public int HorizontalScrollPosition
     {  set { SetScroll(value, Win32.WM_HSCROLL, Win32.SB_HORZ); }
        get { return GetScroll(Win32.SB_HORZ); }
     }

     [  System.ComponentModel.Description
        (  "Fired when the scroll bar's vertical position changes"
        )
     ,  System.ComponentModel.Category("Property Changed")
     ]
     public event System.Windows.Forms.ScrollEventHandler ScrollChanged;

     // Fire scroll event if the scroll-bars are moved
     protected override void WndProc
     (  ref System.Windows.Forms.Message message
     ){ base.WndProc(ref message);
        if(message.Msg == Win32.WM_VSCROLL
        || message.Msg == Win32.WM_HSCROLL
        || message.Msg == Win32.WM_MOUSEWHEEL
        )  TryFireScrollEvent();
     }

     // Key-down includes navigation keys, but also typing and pasting can
     // cause a scroll event
     protected override void OnKeyDown
     (  System.Windows.Forms.KeyEventArgs e
     ){ base.OnKeyDown(e);
        TryFireScrollEvent();
     }

     protected override void OnKeyUp
     (  System.Windows.Forms.KeyEventArgs e
     ){ base.OnKeyUp(e);
        TryFireScrollEvent();
     }

     // Resizing can alter the word-wrap or fit the content causing the text
     // to scroll
     protected override void OnResize
     (  System.EventArgs e
     ){ base.OnResize(e);
        TryFireScrollEvent();
     }

     // Clicking an empty space can move the carot to the beginning of the
     // line causing a scroll event
     protected override void OnMouseDown
     (  System.Windows.Forms.MouseEventArgs e
     ){ base.OnMouseDown(e);
        TryFireScrollEvent();
     }

     protected override void OnMouseUp
     (  System.Windows.Forms.MouseEventArgs e
     ){ base.OnMouseUp(e);
        TryFireScrollEvent();
     }

     // If the mouse button is down, a text selection is probably being done
     // where dragging the selection can caues scroll events
     protected override void OnMouseMove
     (  System.Windows.Forms.MouseEventArgs e
     ){ base.OnMouseMove(e);
        if(e.Button != System.Windows.Forms.MouseButtons.None)
           TryFireScrollEvent();
     }

     // Changing the size of the font can cause a scroll event. Also, when
     // scrolling horizontally, the event will notify whether the scroll
     // was a large or small change. For vertical, small increments are 1
     // line, but for horizontal, it is several pixels. To guess what a
     // small increment is, get the width of the W character and anything
     // smaller than that will be represented as a small increment
     protected override void OnFontChanged
     (  System.EventArgs e
     ){ base.OnFontChanged(e);
        using(System.Drawing.Graphics graphics = this.CreateGraphics())
           _fontWidth = (int)graphics.MeasureString("W", this.Font).Width;
        TryFireScrollEvent();
     }

     protected override void Dispose
     (  bool disposing
     ){ if(disposing && (_components != null))
           _components.Dispose();
        base.Dispose(disposing);
     }

     private void SetScroll
     (  int value
     ,  uint windowsMessage
     ,  int scrollBarMessage
     ){ Win32.SetScrollPos
        (  (System.IntPtr)this.Handle
        ,  scrollBarMessage
        ,  value
        ,  true
        );
        Win32.PostMessage
        (  (System.IntPtr)this.Handle
        ,  windowsMessage
        ,  4 + 0x10000 * value
        ,  0
        );
     }

     private int GetScroll
     (  int scrollBarMessage
     ){ return Win32.GetScrollPos
        (  (System.IntPtr)this.Handle
        ,  scrollBarMessage
        );
     }

     // Fire both horizontal and vertical scroll events seperately, one
     // after the other. These first test if a scroll actually occurred
     // and won't fire if there was no actual movement
     private void TryFireScrollEvent()
     {  // Don't do anything if there is no event handler
        if(ScrollChanged == null)
           return;
        TryFireHorizontalScrollEvent();
        TryFireVerticalScrollEvent();
     }

     private void TryFireHorizontalScrollEvent()
     {

        // Don't do anything if there is no event handler
        if(ScrollChanged == null)
           return;

        int lastScrollPosition = _lastHorizontalScrollPosition;
        int scrollPosition = HorizontalScrollPosition;

        // Don't do anything if there was no change in position
        if(scrollPosition == lastScrollPosition)
           return;

        _lastHorizontalScrollPosition = scrollPosition;

        ScrollChanged
        (  this
        ,  new System.Windows.Forms.ScrollEventArgs
           (  scrollPosition < lastScrollPosition - _fontWidth
              ?  System.Windows.Forms.ScrollEventType.LargeDecrement
              :  scrollPosition > lastScrollPosition + _fontWidth
              ?  System.Windows.Forms.ScrollEventType.LargeIncrement
              :  scrollPosition < lastScrollPosition
              ?  System.Windows.Forms.ScrollEventType.SmallDecrement
              :  System.Windows.Forms.ScrollEventType.SmallIncrement
           ,  lastScrollPosition
           ,  scrollPosition
           ,  System.Windows.Forms.ScrollOrientation.HorizontalScroll
           )
        );

     }

     private void TryFireVerticalScrollEvent()
     {

        // Don't do anything if there is no event handler
        if(ScrollChanged == null)
           return;

        int lastScrollPosition = _lastVerticalScrollPosition;
        int scrollPosition = VerticalScrollPosition;

        // Don't do anything if there was no change in position
        if(scrollPosition == lastScrollPosition)
           return;

        _lastVerticalScrollPosition = scrollPosition;

        ScrollChanged
        (  this
        ,  new System.Windows.Forms.ScrollEventArgs
           (  scrollPosition < lastScrollPosition - 1
              ?  System.Windows.Forms.ScrollEventType.LargeDecrement
              :  scrollPosition > lastScrollPosition + 1
              ?  System.Windows.Forms.ScrollEventType.LargeIncrement
              :  scrollPosition < lastScrollPosition
              ?  System.Windows.Forms.ScrollEventType.SmallDecrement
              :  System.Windows.Forms.ScrollEventType.SmallIncrement
           ,  lastScrollPosition
           ,  scrollPosition
           ,  System.Windows.Forms.ScrollOrientation.VerticalScroll
           )
        );

     }

     private int _lastVerticalScrollPosition;
     private int _lastHorizontalScrollPosition;
     private int _fontWidth;
     private System.ComponentModel.IContainer _components = null;

     private static class Win32
     {

        public const uint WM_HSCROLL    = 0x114;
        public const uint WM_VSCROLL    = 0x115;
        public const uint WM_MOUSEWHEEL = 0x20A;
        public const int  SB_VERT       = 0x1;
        public const int  SB_HORZ       = 0x0;

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern int SetScrollPos
        (  System.IntPtr hWnd
        ,  int nBar
        ,  int nPos
        ,  bool bRedraw
        );
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern int GetScrollPos
        (  System.IntPtr hWnd
        ,  int nBar
        );

        [  System.Runtime.InteropServices.DllImport
           (  "User32.Dll"
           ,  EntryPoint = "PostMessageA")
        ]
        public static extern bool PostMessage
        (  System.IntPtr hWnd
        ,  uint msg
        ,  int wParam
        ,  int lParam
        );

     }

  }

A: Even better -- the hidden MouseWheel event: https://stackoverflow.com/a/26672097/1037948
public Form1()
{
    InitializeComponent();
    textBox1.MouseWheel += textBox1_MouseWheel;
}

void textBox1_MouseWheel(object sender, MouseEventArgs e)
{
    throw new NotImplementedException();
}


text:
Q: How to fill between lines with plotly when missing data is present? Consider the following code
set.seed(1234)
r = rnorm(200)
ir = cumsum(r)
df = data.frame(low = ir - 2*abs(r), high = ir + 2*abs(r), mid = ir, x = 1:200)
df[90:110,] <- NA

plot_ly(data = df) |>
  add_lines(x = ~x, y = ~high, line = list(width = 2), name = "high") |>
  add_lines(x = ~x, y = ~low, fillcolor='rgba(0,100,80,0.2)', fill = "tonexty", line = list(width = 2), name = "low") |>
  add_lines(x = ~x, y = ~mid, line = list(color = "black"), name = "mid")

which generates the following chart

I want to have a break in the chart where the data is missing, and I want to fill the area between the lines, but I don't want this weird artifact you can see. Any ideas?


text:
Q: prevent android app from being installed on TV devices i want to block users from installing app on their smart TVs. i implemented this code in my main activity but doesn't seem to prevent that.
if (checkIsTelevision()) {
            new AlertDialog.Builder(this)
                    .setTitle("Not supported")
                    .setMessage("This app is not compatible with TV devices")
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            MainActivity.this.finish();
                        }
                    })
                    .setCancelable(false)
                    .show();
            return;
        }

A: There are two solutions for this,

*

*While building the app at first step of selecting devices you can
uncheck TV.

*TV system cancels the installation if the manifest file    consists
of a access to hardware sensors. so you can check for the    device
type and set the value as true for tv and false for non-tv
devices. refer [https://developer.android.com/training/tv/start/hardware.html]


text:
Q: Redirect php page to another php page using 301 .htaccess I have a dynamic page that I need to redirect to another dynamic page in .htaccess.
I have tried different syntax for the redirect but nothing seems to work:
RewriteEngine on
RewriteRule /index.php?p=page&page_id=store$ http://www.website.com/index.php [R=301]

OR
RewriteEngine on
RewriteCond %{QUERY_STRING} ^p=page&page_id=store$
RewriteRule ^/index.php$ http://www.website.com/index.php? [L,R=301]

EDIT:  I have an old php page in the shopping cart that I have transferred to the new address. So in order to preserve search engine page ranking I want to redirect old page to the new address. I want visitors who still visit www.website.com/index.php?p=page&page_id=store to be redirected to website.com/index.php
Thanks in advance!

A: URI's that are fed to rewrite rules inside htaccess files always have the leading slash stripped off. So instead of /index.php, you have index.php, since htaccess files are essentially a per-directory case, similar to the <Directory> directive. So you want the second option but without the leading slash:
RewriteEngine on
RewriteCond %{QUERY_STRING} ^p=page&page_id=store$
# no slash --v
RewriteRule ^index.php$ http://www.website.com/index.php? [L,R=301]


text:
Q: Custom post type yearly/ monthly archive I have a custom post type "news" in my Wordpress site. I am using Advanced Custom Fields plugin to add meta data to each post.
I want to create an array of news items as an archive:
[2013]
    [January] => 5
[2012]
    [January] => 20
    [February] => 10
[2011]
    [April] => 30

I managed to get this working using:
    global $wpdb;
    $news = $wpdb->get_results(
        "SELECT wp_posts.post_date, COUNT(wp_posts.ID) as count
         FROM $wpdb->posts
         WHERE
         wp_posts.post_type = 'news' AND
         wp_posts.post_status = 'publish' AND
         wp_posts.post_date <= CURDATE() AND
         wp_posts.post_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR)
         GROUP BY YEAR(wp_posts.post_date), MONTH(wp_posts.post_date)
         ORDER BY wp_posts.post_date DESC",
         ARRAY_A);

    $archive = array();
    foreach ($news as $post):
        $year = date('Y', strtotime($post['post_date']));
        $month = date('m', strtotime($post['post_date']));
        $month_name = date('F', strtotime($post['post_date']));
        $post['url'] = 'NOT SURE ABOUT URL';
        $archive[$year][$month_name] = $post;
    endforeach;

I need to be able to link to specific years and months using http://example.com/2012/ and http://example.com/2012/10/.
As this involves a custom post type "news" I'm unsure how to make this happen?

A: I know this is an old post, but there is a much more succinct way of doing what the OP is asking:
function cpt_add_rewrite_rules()
{
    $cpt = 'news';

    add_rewrite_rule($cpt.'/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})?$',
        'index.php?post_type='.$cpt.'&year=$matches[1]&monthnum=$matches[2]&day=$matches[3]',
        'top');

    add_rewrite_rule($cpt.'/([0-9]{4})/([0-9]{1,2})?$',
        'index.php?post_type='.$cpt.'&year=$matches[1]&monthnum=$matches[2]',
        'top');

    add_rewrite_rule($cpt.'/([0-9]{4})?$',
        'index.php?post_type='.$cpt.'&year=$matches[1]',
        'top');
}

add_filter('init', 'cpt_add_rewrite_rules');

A: In order to do what you require, you need to modify Wordpress rewrites to be able to capture the year/month/etc post data for a custom post type.
You may do this with the following code:
/**
 * Custom post type date archives
 */

/**
 * Custom post type specific rewrite rules
 * @return wp_rewrite             Rewrite rules handled by Wordpress
 */
function cpt_rewrite_rules($wp_rewrite) {
    $rules = cpt_generate_date_archives('news', $wp_rewrite);
    $wp_rewrite->rules = $rules + $wp_rewrite->rules;
    return $wp_rewrite;
}
add_action('generate_rewrite_rules', 'cpt_rewrite_rules');

/**
 * Generate date archive rewrite rules for a given custom post type
 * @param  string $cpt        slug of the custom post type
 * @return rules              returns a set of rewrite rules for Wordpress to handle
 */
function cpt_generate_date_archives($cpt, $wp_rewrite) {
    $rules = array();

    $post_type = get_post_type_object($cpt);
    $slug_archive = $post_type->has_archive;
    if ($slug_archive === false) return $rules;
    if ($slug_archive === true) {
        $slug_archive = $post_type->name;
    }

    $dates = array(
        array(
            'rule' => "([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})",
            'vars' => array('year', 'monthnum', 'day')),
        array(
            'rule' => "([0-9]{4})/([0-9]{1,2})",
            'vars' => array('year', 'monthnum')),
        array(
            'rule' => "([0-9]{4})",
            'vars' => array('year'))
        );

    foreach ($dates as $data) {
        $query = 'index.php?post_type='.$cpt;
        $rule = $slug_archive.'/'.$data['rule'];

        $i = 1;
        foreach ($data['vars'] as $var) {
            $query.= '&'.$var.'='.$wp_rewrite->preg_index($i);
            $i++;
        }

        $rules[$rule."/?$"] = $query;
        $rules[$rule."/feed/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
        $rules[$rule."/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
        $rules[$rule."/page/([0-9]{1,})/?$"] = $query."&paged=".$wp_rewrite->preg_index($i);
    }
    return $rules;
}

You will notice that I have hard-coded news in to the $rules = cpt_generate_date_archives('news', $wp_rewrite); portion of the code. You can change this as needed.
With this code, you should be able to navigate to http://yoursite.com/news/2013/02/ and receive an archive listing for that specific post type for that specific time.
For completeness, I will include how to generate a monthly archive widget in order to utilize this.
/**
 * Get a montlhy archive list for a custom post type
 * @param  string  $cpt  Slug of the custom post type
 * @param  boolean $echo Whether to echo the output
 * @return array         Return the output as an array to be parsed on the template level
 */
function get_cpt_archives( $cpt, $echo = false )
{
    global $wpdb;
    $sql = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = %s AND post_status = 'publish' GROUP BY YEAR($wpdb->posts.post_date), MONTH($wpdb->posts.post_date) ORDER BY $wpdb->posts.post_date DESC", $cpt);
    $results = $wpdb->get_results($sql);

    if ( $results )
    {
        $archive = array();
        foreach ($results as $r)
        {
            $year = date('Y', strtotime( $r->post_date ) );
            $month = date('F', strtotime( $r->post_date ) );
            $month_num = date('m', strtotime( $r->post_date ) );
            $link = get_bloginfo('siteurl') . '/' . $cpt . '/' . $year . '/' . $month_num;
            $this_archive = array( 'month' => $month, 'year' => $year, 'link' => $link );
            array_push( $archive, $this_archive );
        }

        if( !$echo )
            return $archive;
        foreach( $archive as $a )
        {
            echo '
' . $a['month'] . ' ' . $a['year'] . '
';
        }
    }
    return false;
}

To use this function just supply the slug of the custom post type, ie: get_cpt_archives( 'news' ). This will return an array of unique Year/Dates/Links, ie:
Array
(
    [0] => Array
        (
            [month] => February
            [year] => 2013
            [link] => http://yoursite.com/news/2013/02
        )

    [1] => Array
        (
            [month] => January
            [year] => 2013
            [link] => http://yoursite.com/news/2013/01
        )

)

You can loop through these with a foreach and output them however you want.
Alternatively, you can use get_cpt_archives( 'news', true ) which will automatically echo each item wrapped in an
 linking to its specific archive.
The formatting of the output is not exactly what you wanted, so you will have to tweak it a bit to get it to display in the
Year
    Month
    Month
Year
    Month

format that you require.
I hope this helps.


text:
Q: PayPal ignores the billing_country field, defaults to "United States" Recently I was testing a site I maintain, based in Canada.
I found that when arriving at the PayPal payment, the country field was set to United States, despite the fact that I have set billing_country set to CA.
How can I get PayPal to respect the billing_country I have set?
I have reproduced the same behaviour on the paypal sandbox.
Here is the relevant PayPal form with all variables:
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" accept-charset="UTF-8" method="post">
<input name="item_name_1" value="Test Item" type="hidden">
<input name="business" value="test-business@example.com" type="hidden">
<input name="email" value="test-customer@example.com" type="hidden">
<input name="cmd" value="_cart" type="hidden">
<input name="charset" value="utf-8" type="hidden">
<input name="upload" value="1" type="hidden">
<input name="amount_1" value="10.00" type="hidden">
<input name="quantity_1" value="1" type="hidden">
<input name="tax_cart" value="0.00" type="hidden">
<input name="currency_code" value="CAD" type="hidden">
<input name="lc" value="CA" type="hidden">
<input name="no_shipping" value="1" type="hidden">
<input name="no_note" value="1" type="hidden">
<input name="address_override" value="1" type="hidden">
<input name="country" value="CA" type="hidden">
<input name="address1" value="123 Broadway" type="hidden">
<input name="city" value="Winnipeg" type="hidden">
<input name="state" value="MB" type="hidden">
<input name="zip" value="R3G 1N1" type="hidden">
<input name="night_phone_a" value="555" type="hidden">
<input name="night_phone_b" value="555" type="hidden">
<input name="night_phone_c" value="5555" type="hidden">
<input style="vertical-align: middle" name="continue" value="Continue" type="submit">
</form>

A: Through testing and comparing code against a different site where this issue does not occur, I have determined this is a PayPal bug.
The workaround I found is to set:
<input name="landing_page" value="billing" type="hidden">

After setting this variable, PayPal started to respect the billing_country field I set.


text:
Q: Simple code to calculate frequency of Live Mic Audio using WebAudio API I have website in which I need to display the frequency of the Live Mic Audio.
I have a this code, but its extremely difficult to understand (It uses Fourier Transform and all).
On some research I got to know of getByteFrequencyData() which returns the frequency of the audio. Has anyone used it before with Live Mic Audio preferably in Web Audio API?

A: I write a simple code that you can show frequency in your webpage:

const audioCtx = new AudioContext();
const analyser = audioCtx.createAnalyser();
const source = audioCtx.createMediaElementSource(audio);

source.connect(analyser);
analyser.connect(audioCtx.destination);
analyser.fftSize = 32;

let frequencyData = new Uint8Array(analyser.frequencyBinCount);

function renderFrame() {
    analyser.getByteFrequencyData(frequencyData);
    P10.style.height = ((frequencyData[0] * 100) / 256) + "%";
    P20.style.height = ((frequencyData[1] * 100) / 256) + "%";
    P30.style.height = ((frequencyData[2] * 100) / 256) + "%";
    P40.style.height = ((frequencyData[3] * 100) / 256) + "%";
    P50.style.height = ((frequencyData[4] * 100) / 256) + "%";
    P60.style.height = ((frequencyData[5] * 100) / 256) + "%";
    P70.style.height = ((frequencyData[6] * 100) / 256) + "%";
    P80.style.height = ((frequencyData[7] * 100) / 256) + "%";
    P90.style.height = ((frequencyData[8] * 100) / 256) + "%";
    console.log(frequencyData)
    requestAnimationFrame(renderFrame);
}
audio.pause();
audio.play();
renderFrame();
#bar {
    position: fixed;
    top: 20%;
    left: 40%;
    width: 40%;
    height: 40%;
    -webkit-transition: 0.1s ease all;
}

.p {
    background-color: blue;
    height: 100%;
    width: 10%;
    float: left;
}
<audio id="audio" src="2.mp3"></audio>

Good luck.

A: "Displaying the frequency" can mean many things.  Actually, my PitchDetect demo DOESN'T use a Fourier Transform - it uses autocorrelation.  But that will only give you a single pitch, at high accuracy.  If your signal has multiple simultaneous notes - well, that's a hard problem.
If you want to see a frequency analysis breakdown of the live mic input, check out http://webaudiodemos.appspot.com/AudioRecorder/index.html (code at https://github.com/cwilso/AudioRecorder).  That uses the built-in FFT in the RealtimeAnalyser to show a frequency spectrum graph of a live audio signal.


text:
Q: Gauge anomalies ruin the unitarity - the explanation involving ghosts An outline
As is known, the presence of gauge anomalies leads to breakdown of the unitarity of the gauge theory.
One way to understand this is to involve the BRST quantization of the gauge field theory. It reads by the following way. The gauge invariance describes in fact the redundance of the Hilbert space of gauge variant rays to the space of gauge-invariant rays. In the result, the correct state in gauge theory is defined to be invariant under the gauge transformation. In path integral formulation of the gauge theory, this redundancy is nothing but reduction the integration over all gauge fields configuration to the integration over ones satisfying the gauge fixing condition; the latter defines a surface (gauge orbit) in space of gauge fields configurations.
For particular choices of the gauge fixing condition this redundancy leads to generating the ghosts action. The ghoats are unphysical states with indefinite norm in the Hilbert space. Although they mediate the physical processes, they can't be in in- or out- states, so their indefinite norm doesn't make the unitarity to be broken. Their ability to contribute to the physical state is forbidden by Slavnov-Taylor identities; the latter are direct consequence of underlying gauge invariance.
If, however, the gauge anomaly is present, then the Slavnov-Taylor identities are broken. Therefore the ghosts contribute in the Hilbert space of physical states, and the unitarity is broken.
My question
It is always possible to choose the gauge fixing in a way that ghosts don't present. In abelian gauge theories an example is Lorentz gauge. In non-abelian gauge theories, an example is the so-called auxillary gauge. With this choice of gauge fixing conditions, there are no intermediate states with indefinite norm whose presence leads to the violation of the unitarity in a case of the gauge anomaly. So where exactly the unitarity breakdown is hidden in the case of fixing the gauge condition in a way such that the ghosts are absent?
In fact, although the gauge invariance says us that all gauge fixing conditions are equivalent, and one might say that the unitarity has to be preserved for all possible choices. However, I may say that the gauge anomaly requires the quantization by using the ghost-free choices of fixing condition, so that the unitarity is preserved (as long as I don't see where the unitarity breakdown is hidden).

A: In the classical theory, the gauge symmetry is necessary for removing the unphysical deegres of freedom of a given gauge field (sometimes also called ghosts).
A massless vector field should only have 2 phyiscal deegres of freedom. Yet, if you think of QED, without the gauge fixing condition the photon still has 3 d.o.f., one of these with zero norm, therefore spoiling unitarity. The decoupling of these unphysical d.o.f. in the quantized theory is ensured by the Ward identites (or the Slavnov-Taylor identites in the non-Abelian case). In QED imposing a gauge condition does not break the conservation of the electromagnetic current, which is a source of the gauge field, and the Ward identities follow directly from the conservation of this current. An anomalous symmetry spoils the conservation of the associated current and the Ward identities break down. Therefore, in an anomalous QED the photon would couple with 3 deegres of freedom to physical processes, which is of course inconsistent with reality.
The Faddeev–Popov ghosts you are referring to arise in the non-Abelian case because there the gauge fixing condition breaks the conservation of the associated current automatically and therefore, no Ward identity can be constructed there. In order to remove the unphysical deegre of freedom from our gauge field, we need to modify our Lagrangian appropriatly, which introduces the Faddeev-Popov determinant and therefore the ghosts. These ghost states ensure the decoupling of the unphysical d.o.f. but of course they are themselves not physical as they are only introduced by a choice of gauge fixing. Therefore the Slavnov-Taylor identites guarantee their decoupling as external states. These can also be derived from the conservation of a specific supersymmetric current in the BRST system by the way and an anomaly spoils the conservation of this BRST current.
Of course you could also choose a gauge in which the ghosts decouple from the gauge field completely and therefore can just be put in the normalization of the PI. But the price to pay for that is the rather complicated form of the gauge boson propagator which itself has now to guarantee the decoupling of the unphysical d.o.f. . For an explicit calculation see my links below.
Moreover, there can be some topological obstacles for choosing this auxilliary gauge globally over a non-trivial base manifold, since this is equivalent to a globally defined section in the gauge bundle (which does not need to exist for non-trivial bundles).
Summary: Unitarity breaks down in presence of an Anomaly because the unphysical (zero-norm) deegres of freedom of the gauge field don't decouple anymore. The introduction of Faddeev-Popov ghosts only "shifts" the unphysical d.o.f. to these new states, therefore they have to decouple in an anomaly free theory.
Sources:
The Problem of the existence of the globally defined section, known as Gribov ambiguity
A book in which the calculation of the propagator for the axial gauge and the decoupling of unphysical d.o.f. of the gauge boson is shown
A paper which i wasn't able to find in the internet by Kummer, W.
(1976) Acta Phys. Austriaca Suppl. XV, 423.


text:
Q: Determining Sp2013 Sp1 Update Approach We are trying to upgrade our Sp2013 Standard server with SP1. I read through the Technet document about 2 different recommended approach.
http://technet.microsoft.com/en-us/library/ff806331(v=office.15).aspx
Inplace Upgrade:
1.Inplace without backward compatibility
2.Inplace with backward compatibility
Database Attach Upgrade:
I am testing in our Dev Environment first which includes 1 APP, 1 WFE, 1 Workflow, 1SQL Server.
My next step would be to take changes up to Qa and Finally to PROD.
I am preferebly going to take InPlace upgrade on this one. But between Inplace with and Without backward Compatibility which one is better suggested route, keeping in mind the PROD update in future involving minimum downtime and other factors related to SharePoint farm.
Your valuable input would be very helpful.

A: Generally you want to go with approach #1. Running with backwards compatibility for long periods of time is not recommended, and does not actually "upgrade" your farm (it does not upgrade the schema on the databases, for example).
Unless you have a very large farm in terms of number of servers, or have an unusual requirement to be able to leverage backwards compatibility, I would go with #1.

A: As Per my Experience InPlace upgrade without backward compatibility. But we did a little change to reduce the down time. We have tons of Content DB with more than 10TB of data.
Here are the steps we followed.

*

*Install bits(SP) on all SharePoint server

*Now Run the Upgrade content-Database for each Content DB.

*Now Run the Config Wizard, one by one on all SharePoint server

When you run the upgrade-content Database against content DB before COnfig wizard, you upgrade all content quickly. We run the 4 instance of Powershell on each SharePoint server so that Means 4 dbs upgrade at same time. Let's say you have 4 server and run upgrade DB on all servers then 20 DBs will upgraded at once.
But if you run config wizard and let it run then it will upgrade Db one by one. I hope you get my point.
Key thing always, Perform testing, testing and testing before applying to Production. Check my response here.Sp2013 Standard Server Sp1 Upgrade Roll Back Plan


text:
Q: How do I convert date and time string(1975-07-14T16:32:47.000Z) to Day-Month name-Year (14 July 1975) format in python I am writing a UI automated test that checks a date in the database and returns the date as a string in this format 1975-07-14T16:32:47.000Z and comparing it to the date that is displayed on the webpage but the date on the webpage is in this format Day-Month name-Year (14 July 1975), therefore I need to convert the date return by the database to Day-Month name-Year (14 July 1975) so that I am comparing like for like. How do I change the date string to the format I need

A: You can use dateutil.parser to parse the string you got from the datebase into a datetime.datetime, which in turn can be formatted using strftime:
import dateutil.parser

input="1975-07-14T16:32:47.000Z"

dt = dateutil.parser.parse(input)

print(dt.strftime("%d %B %Y"))

A: from datetime import datetime
dt_string = "1975-07-14T16:32:47.000Z"
datetime_object = datetime.strptime(dt_string, "%Y-%m-%dT%H:%M:%S.%fZ")
new_datetime_string = datetime.strftime(datetime_object, "%d-%B-%Y")
print(new_datetime_string)
# prints "14-July-1975"

We are using datetime module where datetime.strptime will generate a datetime object where you can call .date(),.time(),.today() and other functions but to get back to string as per the given format of Day-Month Name-Year datetime.strftime()(stringify time) is used. This converts datetime obj to given format of datetime string.

*

*%d - date (DD - 01,02,...,31)

*%m - month (MM - 01,02,...,12)

*%Y - Year (YYYY - 2022,2021,...)

*%B - Full Month Name (January, Feburary,..)

*%f - Milliseconds

you can find out more in following link: Datetime format codes


text:
Q: ViewController delegate methods not fired from AppDelegate I'm trying to implement Apple Pay for a Flutter app. The code below successfully presents the Apple Pay view, correctly populated. However, when it attempts to make a charge, the paymentAuthorizationViewController -> didAuthorizePayment method should fire, and it does not. What should happen is that function gets hit, I send the token back to my API to create the charge from the server.
I am guessing the issue is with the line paymentAuthorizationViewController.delegate = self as? PKPaymentAuthorizationViewControllerDelegate but I haven't been able to sort it out.
import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

    var flutterViewController: FlutterViewController!

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
        ) -> Bool {

        GeneratedPluginRegistrant.register(with: self)

        flutterViewController = (window.rootViewController as? FlutterViewController)

        let stripeChannel = FlutterMethodChannel(name: "com.tram.gondola.ios/stripe", binaryMessenger: flutterViewController)
        stripeChannel.setMethodCallHandler({
            (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
            if ("handleApplePayButtonTapped" == call.method) {
                // create paymentRequest
                let paymentAmount: NSDecimalNumber = 12.34
                let merchantIdentifier = "merchant.com.merchantid"
                let paymentRequest = Stripe.paymentRequest(withMerchantIdentifier: merchantIdentifier, country: "US", currency: "USD")

                // Configure the line items on the payment request
                paymentRequest.paymentSummaryItems = [
                    // The final line should represent your company;
                    PKPaymentSummaryItem(label: "Company Name", amount: paymentAmount),
                ]

                if Stripe.canSubmitPaymentRequest(paymentRequest) {
                    // Setup payment authorization view controller
                    let paymentAuthorizationViewController = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
                    paymentAuthorizationViewController.delegate = self as? PKPaymentAuthorizationViewControllerDelegate

                    // Present payment authorization view controller
                    self.flutterViewController.present(paymentAuthorizationViewController, animated: true)
                }

            }
            else {
                // There is a problem with your Apple Pay configuration
                result(false)
            }

        })

        return super.application(application, didFinishLaunchingWithOptions: launchOptions);
    }

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {
        print("didAuthorizePayment hit")
        STPAPIClient.shared().createToken(with: payment) { (token: STPToken?, error: Error?) in
            guard let token = token, error == nil else {
                // Present error to user...
                print("error")
                return
            }

            // send token back to flutter
            print(token)
            return
        }
    }

    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
        // Dismiss payment authorization view controller
        controller.dismiss(animated: true, completion: {
            //if (paymentSucceeded) {
            // Show a receipt page...
            //}
        })
    }
}

A: Your AppDelegate does not conform to PKPaymentAuthorizationViewControllerDelegate, so the cast there fails, and the as? returns nil. Thus, your paymentAuthorizationViewController has no delegate, and so its delegate methods do not get called. You should make your AppDelegate conform to PKPaymentAuthorizationViewControllerDelegate, like this:
@objc class AppDelegate: FlutterAppDelegate, PKPaymentAuthorizationViewControllerDelegate{


text:
Q: Powershell comparing values / then checking the validity I have been trying numerous functions in Powershell including Comparison Object, for each function but with no success.
This is what I want to do.
I have two files named as File 1 and File 2. Within File 1, I have a line like this.
In File 2, I have this.
So I want to compare the value of ContractGroups from File 1 to the value of ContractGroups in file 2. If matched, I want to add an outcome to the file.
The difficulty I am having is that I can set up a variable to get the content for matching. But when comparing, I want to only take into account of ContractGroups for a match. So as soon as file 2 is scanned, then I want to see if the value of ContractGroups matches to file 1.
I have tried this.
$file1 = Get-Content "C:\Users\Altunokc\Desktop\Guardian\NotUsed\20200513 Environment parameters\EnvironmentParameters_ICE_EU_PROD.xml"
$file2 = Get-Content "C:\Users\Altunokc\Desktop\inetpub\wwwroot\EU\Guardian\Website\appSettings.config"
$pattern = $file1| %{$_ -MATCH   '.Name="ContractGroups" Value'}

$result = "C:\Users\Altunokc\Desktop\Differentdd.txt"

$file1 | foreach { $pattern = $file2 -match $_

        if ( $match ) { $match | Out-File -Force $result -Append }

      }

and this way
if(Compare-Object -ReferenceObject $(Get-Content $file2 )   -DifferenceObject $(Get-Content $file1 ) | %{$_ -MATCH   '.Name="ContractGroups" Value'}  -SimpleMatch|
Out-File  -FilePath C:\Users\Altunokc\Desktop\Different.txt)

 {"match"}
Else  {"No "}

No luck.
I think for comparison, I just need to find a way of scanning the line that contains Name="ContractGroups" Value from file 1 and then reading its value (CC) and then scanning file 2 to first see if has a line matches Name="ContractGroups" Value and if yes, and then does the value of it is the same (CC) as file one? If yes, then just write that "Matched" to a blank file.
It would be helpful if you shed light on this. Sorry as I am new on PS.


text:
Q: Why has my div changed when i add tags I have a div which contains other divs inside. I have set the css so they are arranged properly as shown here:
which i use the following code for:
HTML

Road Bikes

Mountain Bikes

Hybrid Bikes

City Bikes

CSS
.catogories {
position: absolute;
width: 60%;
float: left;
left: 20%;
height: 600px;
top: 70%;
background-color: green;

}

.category {
position: relative;
height: 330px;
width: 300px;
float: left;
left: 5%;
margin: 4%;
background-color: red;
}

.category h1{
font-size: 40px;
font-family: Arial;
text-align: center;
}

It all looks fine, so i decided to add links to them, make them clickable. So i added the  tag which completly ruined everything and i have no idea why. I even have a screenshot:

HTML

Road Bikes

Mountain Bikes

Hybrid Bikes

City Bikes

CSS
.catogories {
position: absolute;
width: 60%;
float: left;
left: 20%;
height: 600px;
top: 70%;
background-color: green;

}

.category {
position: relative;
height: 330px;
width: 300px;
float: left;
left: 5%;
margin: 4%;
background-color: red;
}

.category h1{
font-size: 40px;
font-family: Arial;
text-align: center;
}

A: Try to order them like this:

Road Bikes


text:
Q: Can Minkowski difference be realized with support functions? Minkowski sum of two compact convex sets is easily computed if they are represented in terms of support functions, one just adds the two support vectors for each direction.
$X \oplus Y = \{x+y : x \in X \quad \mathrm{and}\quad y \in Y\}$
$\rho(l,X\oplus Y) = \rho(l,X) + \rho(l,Y)$ where  $l \in \mathbb{R}^n$
Does this also hold for Minkowski difference of two compact convex sets?
$X \ominus Y = \{x-y : x \in X \quad \mathrm{and}\quad y \in Y\}$
Can one just take the difference of their respective support vectors? If not, are there conditions under which this will hold?

A: $X \ominus Y = X \oplus (-Y)$. So yes.

A: It's not exactly the difference of the support function values, but you can take the difference of the support function value of l in X and -l in Y.
ρ(l,X⊖Y)=ρ(l,X) - ρ(-l,Y)
Here's a simple 1-d example showing the difference:
X = [0, 10]
Y = [0, 1]
X⊖Y = [-1, 10]
if l is the vector <1>, then ρ(l,X⊖Y) should be 10
However, ρ(l,X) = 10, ρ(l,Y) = 1, and so ρ(l,X) - ρ(l,Y) gives the incorrect answer 9.
Whereas ρ(l,X) - ρ(-l,Y) = 10 - 0 = 10, which is correct

A: I know this is an old question, but here are my 2 cents.
We have that $$\rho(l; X - Y) = \rho(l; X) + \rho(-l; Y).$$ This follows simply by using the definition of a support function.


text:
Q: Parsing Shopify JSON Webhook to CSV I need to parse specific fields from a Shopify Webhook that has been exported in JSON into CSV file.  One of the fields I need to target is the shipping address, how do I select "shipping_address" ==> "address1":"123 Shipping Street"?
{
"created_at":"2014-12-30T11:58:01-05:00",
"email":"jon@doe.ca",
"name":"#9999",
"subtotal_price":"229.94",
"taxes_included":false,
"order_number":1234,
"billing_address":{
    "address1":"123 Billing Street",
    "address2":null,
    "city":"Billtown",
    "company":"My Company",
    "country":"United States",
    "first_name":"Bob",
    "last_name":"Biller",
    "latitude":null,
    "longitude":null,
    "phone":"555-555-BILL",
    "province":"Kentucky",
    "zip":"K2P0B0",
    "name":"Bob Biller",
    "country_code":"US",
    "province_code":"KY"
    },
"shipping_address":{
    "address1":"123 Shipping Street",<!-- NEED THIS ADDRESS -->
    "address2":null,
    "city":"Shippington",
    "company":"Shipping Company",
    "country":"United States",
    "first_name":"Steve",
    "last_name":"Shipper",
    "latitude":null,
    "longitude":null,
    "phone":"555-555-SHIP",
    "province":"Kentucky",
    "zip":"K2P0S0",
    "name":"Steve Shipper",
    "country_code":"US",
    "province_code":"KY"
},
"customer":{
    "accepts_marketing":false,
    "created_at":null,
    "email":"john@test.com",
    "first_name":"John",
    "id":null,
    "last_name":"Smith",
    "last_order_id":null,
    "multipass_identifier":null,
    "note":null,
    "orders_count":0,
    "state":"disabled",
    "total_spent":"0.00",
    "updated_at":null,
    "verified_email":true,
    "tags":"",
    "last_order_name":null,
    "default_address":{
        "address1":"123 Elm St.",
        "address2":null,
        "city":"Ottawa",
        "company":null,
        "country":"Canada",
        "first_name":null,
        "id":null,
        "last_name":null,
        "phone":"123-123-1234",
        "province":"Ontario",
        "zip":"K2H7A8",
        "name":"",
        "province_code":"ON",
        "country_code":"CA",
        "country_name":"Canada",
        "default":true
    }
}

A: this is a way to get data json from a webhook:
class Data{
    private $arrayOrder = array();
    public function __construct(){
        $this->process();
    }

    private function process(){
        $order = $this->getContents();
        if(!$order){
            error_log('something failed');
            exit();
        }
        $this->arrayOrder = array(
            'email'=>$order->email,
            'billing_address_address1'=>$order->billing_address->address1,
            'shipping_address_address1'=>$order->shipping_address->address1,
            'customer'=>array(
                'first_name'=>$order->customer->first_name,
                'default_address'=>$order->customer->default_address->address1
            )
        );
        error_log(json_encode($this->arrayOrder));//to test
    }

    private function getContents(){
        $webhookContent = "";
        $webhookContent = file_get_contents("php://input");
        if($webhookContent){
            $data = json_decode($webhookContent);
            return $data;
        }
        return false;
    }
}
$csv = new Data();

to create a csv, use the manual example to put csv :http://php.net/manual/en/function.fputcsv.php

A: Use a JSON parser of course. The most obvious answer is always the one I go with. Since JSON can be directly interpreted with Javascript, your scripting language of choice could be Javascript to do this! If you cannot for some reason write your scripting code in Javascript, almost all other scripting languages of note come with a JSON parse instruction. In Ruby for example, you simply do a
data = JSON.parse someJSON

and now you can play with data. By not telling the world your choice of scripting language in your question, or whether you are in client or server world, it is nearly impossible to help you out more. Lucky for you, JSON is just text as is your CSV file. So nothing is stopping you from parsing your JSON using a JSON parser or just plain old Javascript.


text:
Q: How to rewind an activity in wf4.0? Suppose there are 5 activities in workflow Service (xamlx) and 2nd and 5th activity need to run again by user by any control mechanism.
Please help me how to control this and how to re run those activities. Is flowchart a solution?

A: There is no standard way to reset the execution pointer in a workflow. You need model the logic in your workflow.


text:
Q: Populate chained select menu I am working on a chained select menu, which you can see here - http://jsfiddle.net/stocktrader/EhUKJ/. I have it coded so that the "country" selection changes the "state/zip/city" options via show/hide. All of that is working well.
But my problems is that this form is also used for updating this information for each person. And when I populate the form with current data, I can't get the correct show/hide settings to trigger based on the country setting. You can see an example in the current fiddle where I pre-selected "United States", but the "city/state/zip" options don't come up. The DO come up if you click to a different country and then back on.
I attempted to write some JavaScript that would change the populated show/hide settings by retrieving the "country" value but I don't know JavaScript at all. I tried the below code, which is in the fiddle, but I doubt it is even close.
var s = document.getElementById('country');
var item1 = s.options[s.selectedIndex].value;
function cty()
{
    if (item1 == 'group1')
    unhide('.group1_opts');
}

A: When you bind a function to any of the event handlers in jQuery - simply calling the handler a second time without a parameter will trigger it's execution.
Eg. $('select').change(); will run the "change group" function you applied to it - In this case any "pre-selected" options will be processed.
updated your fiddle


text:
Q: ¿Cómo puedo obtener la lista de datas de un package y que puedan ser utilizados en un bucle for? Me gustaría obtener una lista de de datas que formen parte de un package para que puedan ser utilizados en un bucle for, por ejemplo tengo el package:
data_package <- data(package ='datasets')

Data sets in package 'datasets':

AirPassengers             Monthly Airline Passenger Numbers 1949-1960
BJsales                   Sales Data with Leading Indicator
BJsales.lead (BJsales)    Sales Data with Leading Indicator
BOD                       Biochemical Oxygen Demand
CO2                       Carbon Dioxide Uptake in Grass Plants
ChickWeight               Weight versus age of chicks on different diets
DNase                     Elisa assay of DNase
EuStockMarkets            Daily Closing Prices of Major European Stock
                          Indices, 1991-1998

y quiero obtener las datas de tal forma que puedan ser utilizados en un bucle for, por ejemplo estaba intentando de esta forma:
data_package <- data(package ='datasets')

for (i in data_package){
sum(i)
}

El sum es una función cualquiera utilizada en el ejemplo pero se debe mencionar que todas las datas del package que estoy utilizando tiene las mismas columnas:
Pacientes Sexo Medida

Entonces, quisiera aplicar la misma función a cada una de las datas que se encuentran dentro del paquete.
Gracias por la información.

A: Con el ejemplo del paquete dataset.
Con la siguiente sintaxis se obtiene la lista de data sets del paquete.
sd<-data(package = "datasets")

El objeto sd es una lista que en objeto results guarda los nombres de los data set.
Entonces, si quieres aplicar una función a cada uno de los data set con un for, sería así. Voy aplicar la función lenght()
for (i in 1:104) {
  print(length(get(gsub(" .*","",sd[["results"]][,3][i]))))
}

Que arroja...
[1] 144
[1] 32
[1] 3
[1] 19
[1] 5307
[1] 3
[1] 2
[1] 3
[1] 3
[1] 3
[1] 2
[1] 84
[1] 98
...

Primero, que nada estoy usando la función gsub() para eliminar los caracteres que están después del nombre de los dataframe, es probable que para tu ejemplo no sea necesario, así que puedes omitirlo y te quedaría así:
for (i in 1:104) {
  print(length(get(sd[["results"]][,3][i])))
}

La función get() retorna el valor de los objetos cuando se le brinda el nombre de los objetos. Ahora porque el for va desde 1 a 104, porque ese es el número de data set que tiene este paquete.

A: Si te sirve, esta función recupera los datasets de un paquete, carga el paquete y carga los datos en una lista que termina retornando:
get_data_from_package <- function(package) {
  datas <- data(package=package, envir=new.env())$results[,"Item"]
  datas <- sapply(strsplit(datas, split=" ", fixed=TRUE), "[", 1)
  if (length(datas)>0) {
    library(package,character.only = TRUE)
    lst <- lapply(datas, get)
    names(lst) <- datas
    detach(paste("package", package, sep = ":"), unload = TRUE, character.only = TRUE)
    return(lst)
  }
  return(list())
}

Por ejemplo, si quieres los datos de ggplot2:
lista <- get_data_from_package("ggplot2")
sapply(lista, nrow)

      diamonds      economics economics_long      faithfuld    luv_colours        midwest            mpg
         53940            574           2870           5625            657            437            234
        msleep   presidential          seals      txhousing
            83             11           1155           8602


text:
Q: Python Binary? to Text/String I'm trying to parse a possibly binary file as text/strings in Python. I'm not positive of the file format, so I'm assuming it's binary. Basically, it is an exported key (*.reg) from MS regedit. If I open the key in Notepad++ I can read it easily. However, if I try to iterate the lines in python (specifically iPython Notebook) it prints gobbledygook. Here's a sample:
InFile = open("F:\Uninstallkey.reg","r")

for line in InFile:
    print "%r" % (line)

InFile.close()

Output:
'\xff\xfeW\x00i\x00n\x00d\x00o\x00w\x00s\x00 \x00R\x00e\x00g\x00i\x00s\x00t\x00r\x00y\x00 \x00E\x00d\x00i\x00t\x00o\x00r\x00 \x00V\x00e\x00r\x00s\x00i\x00o\x00n\x00 \x005\x00.\x000\x000\x00\r\x00\n'
'\x00\r\x00\n'
'\x00[\x00H\x00K\x00E\x00Y\x00_\x00L\x00O\x00C\x00A\x00L\x00_\x00M\x00A\x00C\x00H\x00I\x00N\x00E\x00\\\x00S\x00O\x00F\x00T\x00W\x00A\x00R\x00E\x00\\\x00M\x00i\x00c\x00r\x00o\x00s\x00o\x00f\x00t\x00\\\x00W\x00i\x00n\x00d\x00o\x00w\x00s\x00\\\x00C\x00u\x00r\x00r\x00e\x00n\x00t\x00V\x00e\x00r\x00s\x00i\x00o\x00n\x00\\\x00U\x00n\x00i\x00n\x00s\x00t\x00a\x00l\x00l\x00]\x00\r\x00\n'
'\x00\r\x00\n'

In notepad++:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall]

Strangely, in iPython it prints properly:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall]

Long story short, how can I tell the file format and how can I convert the file so I can print/parse it as text?

A: As mentioned above the file is in utf-16.  Here's an easy way to open files with encoding:
import codecs
InFile = codecs.open(path_to_registry, encoding='utf-16')

A: The file appears to be a plain text file that is simply encoded in little-endian UTF-16.  Instead of using the normal open function, open the file with io.open with an encoding argument of "UTF-16LE".


text:
Q: finding the branches that are available between 2 git commits I have a start commit from which i want to find all the branches till i reach another dont find a note for the commit.
commit 1
|
commit 2
|         commit5
commit3  /
|       /
commit 4
|
commit 6

in this case say all the commit from commit 1-5 have notes "find branch"
and commit 6 doesn't have a not with that value.
So i will start with commit 1 find all the parent (ie: commit 2) and try to check if there is an branch for this commit (ie: number of children is more than 1). if there is more than 1 childs

*

*the getChildren() method is there only for PlotCommit object, but the method parentCommit.getParents() return only RevCommit Object.

*i want to find the branch name present in the particular commit

then when there is no more notes on the commit (ie commit 6 doesnt have notes) the logic will stop there and the collection of Branch name is returned
    Repository repo;//will be set as part of some other logic
    private Set findBranchesForCommit(PlotCommit parentCommit, String note) throws ExecutionException, MissingObjectException, IncorrectObjectTypeException, IOException {
        Set branches = new HashSet();
        PlotCommit[] parents = (PlotCommit[]) parentCommit.getParents();//XXX will throw exception as this return RevCommit[]
        for (int i = 0; i < parents .length; i++) {
            PlotCommit commit = parents[i];
            String result = extractExistingMessage(repo, "refs/notes", commit);//will return the if the note available for particular commit
            if (result.trim().length() > 0 && result.equalsIgnoreCase(note)) {
                System.out.println("#########"+commit.getChildCount());
                //TODO need to add logic to find the branch of the particular commit
                branches.add(""); //add the branches available for the commit
                branches.addAll(findBranchesForCommit(commit, note));
            }
        }
        return branches;
    }

expected result
i want to find the branch names of commits that contain a particular git note. in the above example the branch name of Commit 1 and commit 5 will be returned

A: While the git command for this kind of request (finding branches for a given commit) is:
git branch --contains <commit>

(as in "Git: Finding what branch a commit came from", and "How to list branches that contain a given commit?")
it isn't implemented as is in JGit.
This thread has this to propose:
'git branch --contains <commit>' will report every branch which contains this commit.
In the standard push/fetch workflows for all commits you get from remote only "origin/master" is reported.
And even for local commits: Imagine you have merged your feature branch back to master. Then this command will report also the master branch and all feature branches created after merging.
Git simply doesn't store for a revision on which branch it was created.

After these warnings: a rough implementation of "git branch --contains " could look like this:

Repository repo = new FileRepository(args[0]);
RevWalk walk = new RevWalk(repo);
RevCommit commit = walk.parseCommit(repo.resolve(args[1] + "^0"));
for (Map.Entry<String, Ref> e : repo.getAllRefs().entrySet())
  if (e.getKey().startsWith(Constants.R_HEADS))
    if (walk.isMergedInto(commit,
        walk.parseCommit(e.getValue().getObjectId())))
      System.out.println("Ref " + e.getValue().getName()
                                + " contains commit " + commit);


text:
Q: Is there a way to query JSON column in SQL Server ignoring capitalization of keys? I am trying to query a JSON column that has mixed capitalization.  For instance, some rows have keys that are all lower case like below:
{"name":"Screening 1","type":"template","pages":[{"pageNumber":1,...}

However, some of the rows have keys that are capitalized on its first letter like this:
{"Type":"template","Name":"Screening2","Pages":[{"PageNumber":1,...}

Unfortunately, SQL Server seems to only supports JSON path system that is case sensitive.  Therefore, I can't query on all rows successfully.  If I use lower case path like '$.pages' in a query like below:
SELECT ST.Id AS Screening_Tool_Id
    , ST.Name AS Screening_Tool_Name
    , ST.Description AS Screening_Tool_Description
    , COUNT(JSON_VALUE (SRQuestions.value, '$.id'))  AS Question_Specific_Id

FROM dbo.ScreeningTemplate AS ST
    CROSS APPLY OPENJSON(ST.Workflow, '$.pages') AS SRPages
        CROSS APPLY OPENJSON(SRPages.Value, '$.sections') AS SRSections

I miss any row that has capitalized keys.  Is there any way to query all rows ignoring their capitalization?

A: According to MS, looks like you're stuck with a case-sensitive query:

When OPENJSON parses a JSON array, the function returns the indexes of
  the elements in the JSON text as keys.+ The comparison used to match
  path steps with the properties of the JSON expression is
case-sensitive and collation-unaware (that is, a BIN2 comparison).
  https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql

If the only variations are in the capitalization of the first character, you could try to work around this limitation by creating queries with the variants and UNION the results together.

A: Maybe you can just lower the json:
COUNT(JSON_VALUE (lower(SRQuestions.value), '$.id'))  AS Question_Specific_Id

A: Old question but I came across this when googling a similar issue so I will chip in with my solution:
SELECT @pb = PB from
   OPENJSON(@PropertyBagsAsJson, '$."$values"')
    WITH (
          PbId1 nvarchar(MAX) 'lax $.Id',
          PbId2 nvarchar(MAX) 'lax $.id',
          PB nvarchar(MAX)  '$' AS JSON
    )
WHERE COALESCE(PbId1,PbId2) = @PropertyBagId

I hope that the example is clear. Basically I just add all possible casing of the property and then just use Coalesce to filter the results.

A: You can use openjson. Instead of
    JSON_VALUE (SRQuestions.value, '$.id')

you can write
    (select Value
       from openjson( SRQuestions.value )
      where [Key] collate latin1_general_ci = 'id')

You must use a Case-Insensitive "_ci" collation here. "UTF8_General_CI" works too, as does "database_default" if the database uses a CI collation.


text:
Q: How to get the Particular column value using jquery I used this code to get the particular column value using jquery..
$("#Grid td:first-child").click(function() {
                var resultArray = $(this).closest('tr').find('td').text();
                   alert(resultArray);
            });

How do I get the particular column value? That is, I need grid 4th and 5th column value?

A: Use the :eq selector:
$("#Grid td:first-child").click(function() {
   var value = $(this).closest('tr').find('td:eq(2)').text(); // for third column
   alert(value);

   var value = $(this).closest('tr').find('td:eq(3)').text(); // for fourth column
   alert(value);
});

That will alert value of 3rd and 4rth TD/column when first td of element with id Grid (td:first-child) is clicked.
If however, you want an array of values of TDs, use the map and get methods like this:
$("#Grid td:first-child").click(function() {
   var value_array = $(this).closest('tr').find('td').map(function(){
     return $(this).text();
   }).get();
});

Now value_array will contains text for found TDs eg:
value_array[0] // first
value_array[1] // second
value_array[2] // third

A: $('#Grid td:first-child').click( function(){
    var resultArray = $(this).closest('tr').find('td').map( function(){
        return $(this).text();
    }).get();

    alert(resultArray[2]); // third
    alert(resultArray[3]); // fourth..

});

or
$('#Grid td:first-child').click( function(){
    var resultArray = $(this).closest('tr')
        //     third     fourth
        .find('td:eq(2), td:eq(3)').map( function(){
             return $(this).text();
        }).get();

    alert(resultArray[0]);
    alert(resultArray[1]);

});


text:
Q: Dataframe binned averages, skip nan I have a dataframe of the following structure which is simplified for the sake of this question:
Date      A    B
2016/1/1  nan  nan
2016/1/2  nan  nan
2016/1/3  3    2
2016/1/4  4    1
2016/1/5  nan  nan
2016/1/6  6    8
2016/1/7  7    nan
2016/1/8  8    3
2016/1/9  9    5

What I wish to do is create a 3 day binned average, I can easily do this using
df = df.resample('3D', on='Date').mean()

However using this method the nan values are counted as zero values and they affect the mean value like so:
Date      A    B
2016/1/1  nan  nan
2016/1/2  nan  nan
2016/1/3  3    2

Using df.resample('3D', on='Date').mean()  returns:
Date      A  B
2016/1/3  1  2/3

Where as I wish to obtain:
Date      A  B
2016/1/3  3  2

Where the na values are ignored for the calculation.
According to the documentation on .mean() I should be able to skipna values as listed on the page:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mean.html#pandas.Series.mean
However when I run the following:
df = df.resample('3D', on='Date').mean(skipna=True)

The following is returned:
UnsupportedFunctionCall: numpy operations are not valid with resample. Use .resample(...).mean() instead

How do I go about solving this error and producing the correct mean values that I desire?

A: You need:
#mean works perfectly
df1 = df.resample('3D', on='Date').mean()
print (df1)
              A    B
Date
2016-01-01  3.0  2.0
2016-01-04  5.0  4.5
2016-01-07  8.0  4.0

For cumsum and cumcount with omiting NaNs need transform, also for cumcount is used trick count 1s:
df[['A1','B1']] = df.resample('3D', on='Date').transform('cumsum')

df[['A2','B2']] = df[['A','B']].mask(df[['A','B']].notnull(), 1)
df[['A2','B2']] = df.resample('3D', on='Date')[['A2','B2']].transform('cumsum') - 1
print (df)
        Date    A    B    A1   B1   A2   B2
0 2016-01-01  NaN  NaN   NaN  NaN  NaN  NaN
1 2016-01-02  NaN  NaN   NaN  NaN  NaN  NaN
2 2016-01-03  3.0  2.0   3.0  2.0  0.0  0.0
3 2016-01-04  4.0  1.0   4.0  1.0  0.0  0.0
4 2016-01-05  NaN  NaN   NaN  NaN  NaN  NaN
5 2016-01-06  6.0  8.0  10.0  9.0  1.0  1.0
6 2016-01-07  7.0  NaN   7.0  NaN  0.0  NaN
7 2016-01-08  8.0  3.0  15.0  3.0  1.0  0.0
8 2016-01-09  9.0  5.0  24.0  8.0  2.0  1.0