text:
Q: Setting up azure cache client for local development I've got our site all setup like this in my web.config:
<dataCacheClients>
    <dataCacheClient name="default">
      <hosts>
        <host name="mysite.cache.windows.net" cachePort="22233" />
      </hosts>

      <securityProperties mode="Message">
        <messageSecurity
          authorizationInfo="{key}">
        </messageSecurity>
      </securityProperties>
    </dataCacheClient>
  </dataCacheClients>

I'd like to edit this so while I'm developing on my laptop I'm not hitting the production cache but instead a cache on my laptop.
This is a hard problem to Google (at least for me) because "azure cache local" comes up with caching on web roles.

A: It looks like you are using Windows Azure Shared Cache, and you want to use some local cache when developing.
It might be better to have an abstract cache layer in your system so that you can switch caches between cloud and local, rather than changing the configuration. For example, to have an interface like ICache with some methods like GetItem, SetItem, etc. Then you can have some classes implemented this interface that are using in memory cache for local development, and Azure Cache for production.
There's a project named ServiceStack on GitHub that wrapped some cache implementation you can refer https://github.com/ServiceStack/ServiceStack.Contrib/tree/master/src
Alternatively, you can use the new Cloud Service Caching, which provides co-located/dedicate cache clusters alone with your cloud services (web role and worker role). It has full local emulator support which means you don't need to change any code and any configuration between local development (use local cache emulator) and production.
For more information about this Cloud Service Caching you can refer https://www.windowsazure.com/en-us/develop/net/how-to-guides/cache/

A: One option would be to use Web.config Transformations to change the config file for each deployment. I'm not an expert in that, but you can probably figure it out with Google.
Another option is to configure the cache in code. You can then easily change the settings in the .cscfg file for each environment. Here's a basic sample of configuration in code:
DataCacheFactoryConfiguration cacheConfig = new DataCacheFactoryConfiguration();

//Insert the Authentication Token as shown below
cacheConfig.SecurityProperties = new DataCacheSecurity(config.AuthToken, config.UseSSL);

int cachePort = (cacheUseSSL ? 22243 : 22233);
cacheConfig.Servers = new DataCacheServerEndpoint[] { new DataCacheServerEndpoint(cacheHostName, cachePort) };
cacheConfig.RequestTimeout = TimeSpan.FromSeconds(1);
cacheConfig.ChannelOpenTimeout = TimeSpan.FromSeconds(45);
cacheConfig.MaxConnectionsToServer = config.MaxConnections;
cacheConfig.TransportProperties.ReceiveTimeout = TimeSpan.FromSeconds(30);
cacheConfig.TransportProperties.ChannelInitializationTimeout = TimeSpan.FromSeconds(10);

var cacheFactory = new DataCacheFactory(cacheConfig);


text:
Q: How to unpack JSON data that comprises a common class in C# I'm having trouble unpacking a JSON response to a C# structure.
The JSON data comes from a call to Etsy to get a seller's list of taxonomies (.../taxonomy/seller/get). A sample (fudged) JSON response is:

"{\"count\":1,\"results\":[{\"id\":1,\"name\":\"Accessories\",\"children_ids\":[1728],\"path\":\"accessories\",\"children\":[
  {\"id\":1728,\"name\":\"Baby
  Accessories\",\"children_ids\":[135,6078],\"path\":\"accessories.baby_accessories\",\"children\":[{\"id\":135,\"name\":\"Baby
  Carriers &
  Wraps\",\"children_ids\":[],\"path\":\"accessories.baby_accessories.baby_carriers_and_wraps\",\"children\":[],\"level\":2,\"parent\":\"accessories.baby_accessories\",\"parent_id\":1728,\"short_name\":null,\"all_name\":null,\"description\":null,\"page_title\":null,\"nav\":null,\"category_id\":69150455,\"full_path_taxonomy_ids\":[1,1728,135],\"source_finder\":\"seller:01-2017\",\"attributeValueSets\":[],\"filters\":{\"buyer\":[],\"byCraft\":[]},\"version\":\"3ff712c\"},{\"id\":6078,\"name\":\"Children's
  Photo
  Props\",\"children_ids\":[],\"path\":\"accessories.baby_accessories.childrens_photo_props\",\"children\":[],\"level\":2,\"parent\":\"accessories.baby_accessories\",\"parent_id\":1728,\"short_name\":null,\"all_name\":null,\"description\":null,\"page_title\":null,\"nav\":{\"buyer_target\":null,\"is_vintage\":null},\"category_id\":69150467,\"full_path_taxonomy_ids\":[1,1728,6078],\"source_finder\":\"seller:01-2017\",\"attributeValueSets\":[{\"attribute\":3,\"possibleValues\":[],\"selectedValues\":[],\"isRequired\":false,\"displayName\":\"Occasion\",\"novaIds\":[],\"version\":\"3ff712c\",\"taxonomyNode\":6078,\"userInputValidator\":null}],\"filters\":{\"buyer\":[],\"byCraft\":[]},\"version\":\"3ff712c\"}],\"level\":1,\"parent\":\"accessories\",\"parent_id\":1,\"short_name\":null,\"all_name\":null,\"description\":null,\"page_title\":null,\"nav\":null,\"category_id\":69150467,\"full_path_taxonomy_ids\":[1,1728],\"source_finder\":\"seller:01-2017\",\"attributeValueSets\":[{\"attribute\":2,\"possibleValues\":[],\"selectedValues\":[],\"isRequired\":false,\"displayName\":\"Primary
  color\",\"novaIds\":[],\"version\":\"3ff712c\",\"taxonomyNode\":1728,\"userInputValidator\":null}],\"filters\":{\"buyer\":[],\"byCraft\":[]},\"version\":\"3ff712c\"}]}]}"

I've pasted the JSON to https://jsonformatter.curiousconcept.com/ and viewed the formatted response, and as far as I can tell the way I've structured my classes for the response is ok (but clearly, it's not).
My confusion is that "children" in the JSON response seems to me like a recursive class, and so I created a class called children, which in itself can have "children" in its response.
But when I run the code, it almost works (please forgive any inefficiencies that you spot in the classes), but fails to unpack "children" - zero records unpacked.

My code:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Etsy
{
    public class TaxonomyData
    {
        #region Classes

        #region Supporting classes

        public class Nav
        {
            public string buyer_target { get; set; }
            public string is_vintage { get; set; }
        }

        public class ByCraft
        {
        }

        public class Buyer
        {
        }

        public class Filters
        {
            public Buyer buyer { get; set; }
            public ByCraft byCraft { get; set; }
        }

        public class AttributeValueSets
        {
            public int attribute { get; set; }
            public List<int> possibleValues { get; set; }
            public List<int> selectedValues { get; set; }
            public string isRequired { get; set; }
            public string displayName { get; set; }
            public List<string> novaId { get; set; }
            public string version { get; set; }
            public int taxonomyNode { get; set; }
            public string userInputValidator { get; set; }

            public AttributeValueSets()
            {
                possibleValues = new List<int>();
                selectedValues = new List<int>();
                novaId = new List<string>();
            }
        }

        public class Children
        {
            public string id { get; set; }
            public string name { get; set; }
            public List<int> children_ids { get; set; }
            public string path { get; set; }
            public List<Children> children { get; set; }

            public string level { get; set; }
            public string parent { get; set; }
            public int parent_id { get; set; }
            public string short_name { get; set; }
            public string all_name { get; set; }
            public string description { get; set; }
            public string page_title { get; set; }
            public Nav nav { get; set; }
            public int category_id { get; set; }
            public List<int> full_path_taxonomy_ids { get; set; }
            public string source_finder { get; set; }
            public List<AttributeValueSets> attributeValueSets { get; set; }
            public Filters filters { get; set; }
            public string version { get; set; }

            public Children()
            {
                children_ids = new List<int>();
                children = new List<Children>();

                nav = new Nav();
                full_path_taxonomy_ids = new List<int>();
                attributeValueSets = new List<AttributeValueSets>();
                filters = new Filters();
            }
        }

        public class Results
        {
            public string id { get; set; }
            public string name { get; set; }
            public List<int> children_ids { get; set; }
            public string path { get; set; }
            List<Children> children { get; set; }

            public Results()
            {
                children_ids = new List<int>();
                children = new List<Children>();
            }
        }

        #endregion Supporting classes

        public class TaxonomyResponse
        {
            public int count { get; set; }
            public List<Results> results { get; set; }

            public TaxonomyResponse()
            {
                results = new List<Results>();
            }
        }

        #endregion Classes

        public void GetTaxonomyData()
        {
            string testData = "{\"count\":1,\"results\":[{\"id\":1,\"name\":\"Accessories\",\"children_ids\":[1728],\"path\":\"accessories\",\"children\":[ {\"id\":1728,\"name\":\"Baby Accessories\",\"children_ids\":[135,6078],\"path\":\"accessories.baby_accessories\",\"children\":[{\"id\":135,\"name\":\"Baby Carriers & Wraps\",\"children_ids\":[],\"path\":\"accessories.baby_accessories.baby_carriers_and_wraps\",\"children\":[],\"level\":2,\"parent\":\"accessories.baby_accessories\",\"parent_id\":1728,\"short_name\":null,\"all_name\":null,\"description\":null,\"page_title\":null,\"nav\":null,\"category_id\":69150455,\"full_path_taxonomy_ids\":[1,1728,135],\"source_finder\":\"seller:01-2017\",\"attributeValueSets\":[],\"filters\":{\"buyer\":[],\"byCraft\":[]},\"version\":\"3ff712c\"},{\"id\":6078,\"name\":\"Children's Photo Props\",\"children_ids\":[],\"path\":\"accessories.baby_accessories.childrens_photo_props\",\"children\":[],\"level\":2,\"parent\":\"accessories.baby_accessories\",\"parent_id\":1728,\"short_name\":null,\"all_name\":null,\"description\":null,\"page_title\":null,\"nav\":{\"buyer_target\":null,\"is_vintage\":null},\"category_id\":69150467,\"full_path_taxonomy_ids\":[1,1728,6078],\"source_finder\":\"seller:01-2017\",\"attributeValueSets\":[{\"attribute\":3,\"possibleValues\":[],\"selectedValues\":[],\"isRequired\":false,\"displayName\":\"Occasion\",\"novaIds\":[],\"version\":\"3ff712c\",\"taxonomyNode\":6078,\"userInputValidator\":null}],\"filters\":{\"buyer\":[],\"byCraft\":[]},\"version\":\"3ff712c\"}],\"level\":1,\"parent\":\"accessories\",\"parent_id\":1,\"short_name\":null,\"all_name\":null,\"description\":null,\"page_title\":null,\"nav\":null,\"category_id\":69150467,\"full_path_taxonomy_ids\":[1,1728],\"source_finder\":\"seller:01-2017\",\"attributeValueSets\":[{\"attribute\":2,\"possibleValues\":[],\"selectedValues\":[],\"isRequired\":false,\"displayName\":\"Primary color\",\"novaIds\":[],\"version\":\"3ff712c\",\"taxonomyNode\":1728,\"userInputValidator\":null}],\"filters\":{\"buyer\":[],\"byCraft\":[]},\"version\":\"3ff712c\"}]}]}";
            TaxonomyResponse response;

            try
            {
                response = JsonConvert.DeserializeObject<TaxonomyResponse>(testData);

#if DEBUG
                if (!string.IsNullOrEmpty(testData))
                {
                    //
                    // And the response is ZERO children unpacked.
                    //
                }
#endif
            }
            catch (Exception ex)
            {
            }
        }

    }
}

What am I doing?  Why isn't children unpacking?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possibile to include a file in ansible inventory? I've a group of hosts that need a particular ssh key.
[group1]
host1
host2

This is the relative
inventory/group1.yml file:
---
ansible_user: custom-user
ansible_ssh_private_key_file: ~/.ssh/custom-key.pem

The path where the key is stored is system dependent so I wouldn't want to commit it to our git repository.
Is it possible to include a var file like inventory/local_custom-key.yml in the inventory that can be easily gitignored ?
EDIT: To explain better i want to know is this trick is possible:
inventory/custom-key.yml:
---
ansible_user: custom-user
magically_include_yaml: inventory/local_custom-key.yml

inventory/local_custom-key.yml
---
ansible_ssh_private_key_file: ~/ssh/custom-key.pem

.gitignore:
# local config to ignore
inventory/local_custom-key.yml


text:
Q: How To Initialize DropZone.js To Get It Working Properly? My HTML:
<form action="" class="dropzone">
    <div id="pck_Dropzone" class="fallback">
        <input name="file" type="file" multiple />
    </div>
</form>

My JS:
Dropzone.autoDiscover = false;

$(function(){
    var dropZone = new Dropzone("div#pck_Dropzone", {
        url: '/api/admin/UploadPackageImage',
        dictDefaultMessage: "Drag & Drop Images",
        clickable: true,
        enqueueForUpload: true,
        paramName: "file", // The name that will be used to transfer the file
        maxFilesize: 2, // MB
        maxFiles: 100,
        acceptedFiles: 'image/*',
        addRemoveLinks: true,
        uploadMultiple: true,
        autoProcessQueue: false,
        thumbnailWidth: 240,
        thumbnailHeight: 240,
        init: function(){
            console.log('init');
        }
    });
});

I know for a fact dropzone is attached to my DOM element. But its behavior doesn't come close to what's demo'ed and described in the documentation.

*

*Other than the init function, no other event ever fires. I tried console logging the 'addedfile' event, according to the documentation. It does not work.

*When I add multiple files and I call the getQueuedFiles() function, nothing is returned.

*No image preview files are ever generated. No remove links are ever shown.

*Dragging & dropping does not work. A drag & dropped image simply replaces the page the browser is currently showing (default browser behavior).

*The dictDefaultMessage 'Drag & Drop Images' isn't shown. That one only shows if I init the form instead of the div.
I'm using the 5.5.1 version from cloudflare cdn. It's identical to the latest version from github.
Stack Overflow is rife with examples on how to use this plugin. I tried many code examples. It all fails to do anything.
My dropzone looks like this.
No previews. No queue. No button to start uploading. No nothing.
What can I possibly be doing wrong?

A: My mistake was placing it inside of a VueJS app. When placed outside of it, it worked right away.


text:
Q: error of Monte Carlo estimate of root mean square speed (vrms) of ideal gas I am trying to use Monte Carlo method to estimate the oot mean square speed (vrms) of an ideal gas, the speed of an ideal gas follows the Maxwell-Boltzmann distribution:
$$p(v)= \frac{4}{\sqrt {\pi}}(\frac{m}{2k_BT})^{\frac{3}{2}}v^2 \exp({-\frac{mv^2}{2 k_BT}})$$
The Monte Carlo estimate of vrms is:
$ v_{rms} = \sqrt{\bar{v^2}}
                = \sqrt{\int_0^{\infty} v^2\ p(v)dv} $
So now, we use Monte Carlo to estimate the expectation of the square of the speed $E[v^2]$ and vrms is the square root of the estimate.
I know the error of the estimation of $E[v^2]$ with 95% CI is $1.96 \times \sqrt{\sigma^2/m}$, where m is the monte carlo sample size, and $\sigma^2$ is estimated by $s^2 = \frac{1}{n-1} \sum_{i=1}^n (v_i^2-\bar{v^2})^2$.
But how about the error of $\sqrt{E[v^2]}$? is it just $s^2= \frac{1}{n-1} \sum_{i=1}^n (v_i - v_{rms})^2$ or $s^2= \frac{1}{n-1} \sum_{i=1}^n (v_i - E[v])^2$ or neither of them? Thanks.
PS: Since $v_{rms}$ cannot have a negative value, is it valid to assume the monte carlo estimate follows a normal distribution when calculating the error? as it is just approximately normal


text:
Q: GitHub API V3 : what is the difference between pushed_at and updated_at? Looking to V3 API Repos (GET /repos/:owner/:repo) we have 3 datetime :
  "pushed_at": "2011-01-26T19:06:43Z",
  "created_at": "2011-01-26T19:01:12Z",
  "updated_at": "2011-01-26T19:14:43Z",

to have a fast example just link this https://api.github.com/repos/twitter/bootstrap
What is the difference between pushed_at and updated_at ?

A: UPDATE: the behavior described below wasn't intended. pushed_at will be updated any time a commit is pushed to any of the repository's branches. updated_at will be updated any time the repository object is updated, e.g. when the description or the primary language of the repository is updated. It's not necessary that a push will update the updated_at attribute -- that will only happen if a push triggers an update to the repository object. For example, if the primary language of the repository was Python, and then you pushed lots of JavaScript code -- that might change the primary language to JavaScript, which updates the repository object's language attribute and in turn updates the updated_at attribute. Previously, the primary language was getting updated after every push, even if it didn't change (which wasn't intended), so it triggered an update to updated_at.

The difference is that pushed_at represents the date and time of the last commit, whereas the updated_at represents the date and time of the last change the the repository. A change to the repository might be a commit, but it may also be other things, such as changing the description of the repo, creating wiki pages, etc. In other words, commits are a subset of updates, and the pushed_at timestamp will therefore either be the same as the updated_at timestamp, or it will be an earlier timestamp.


text:
Q: The type or namespace name 'Json' does not exist in the namespace 'System' (are you missing an assembly reference?) I am using .NET Framework 4.5 and I'm having this issue.
The type or namespace 'Json' does not exist in the namespace 'System'
I tried to Install-Package System.Json -Version 4.0.20126.16343 but I had this issue afterwards.
The type 'System.Uri' is defined in an assembly that is not referenced. You must add a reference to assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Source: https://www.nuget.org/packages/System.Json
Any ideas would be really appreciated!

A: That package is discontinued and shouldn't be used any more.
If you have a console application, I could recommend two options:

*

*JSON.NET. Not a part of the .NET Framework itself, but much faster than Microsofts implementation;

*Microsofts implementation of the JavaScriptSerializer.

Both are capable of reading and writing JSON. I find the JSON.NET library easier to use and more feature complete.

A: using Newtonsoft.Json; should get the job done.
Now you can use:
JsonConvert.SerializeObject
JsonConvert.DeserializeObject


text:
Q: What was the prediction of the standard electroweak theory about the $W$ and $Z$ boson masses? The standard electroweak theory has two coupling constants $g$ and $g^\prime$. In this theory, the $W$ mass and $Z$ mass are given by $$M_W=\frac{1}{2}gv,~M_Z=\frac{1}{2}(g^2+g^{\prime 2})^{1/2}v$$ where $v$ is the vacuum expectation value of the neutral component of the Higgs doublet. But what was the prediction of the SM? It does not seem to be the absolute values of the W and Z masses because neither the values of $g$ and $g^\prime$ nor that of $v$ is a priori known.
In terms of Weinberg angle $\theta_W$, defined as $e=g\sin\theta_W$, $M_W=M_Z \cos\theta_W$ which trades another parameter in place of $g^\prime$. How is it possible to predict any one mass when the other mass and $\theta_W$ is also unknown?

A: What you are stating is a "prediction" on the formalism that describes the electroweak interaction. The masses themselves had to be measured experimentally and the relations checked with the actual measured numbers. As you also state, no value could be extracted using the data at the time the model was proposed.


text:
Q: Why can't my python script change umask? This is my script
#!/usr/bin/python

import os

print "hello world from python"
os.system("echo 'hello world from bash'")
os.system("umask 055")
os.system("ls -alh > test")

If I run this code the permissions of file test are not set as 722 but as 600. What could be the reason?
the Umask of my shell is 0077.

A: This is perfectly normal behaviour, but probably not what you intend.
The umask 055 settings are there for the duration of the  os.system call, so they never change the settings for the Python script, and certainly not for the command called in the next os.system() call.
What you should do is something like:
import os

old_mask = os.umask(055)
os.system("ls -alh > test")
os.umask(old_mask)

A: When you run umask with system it runs in a shell: umask changes the mask of that shell, but the shell then immediately terminates and the change is lost.
To change the umask of your Python process, use os.umask(), which will:

Set the current numeric umask and return the previous umask.

That way the change will be made to your running program, rather than another program that immediately dies afterwards.

A: If you want an underlying shell command to run with certain permissions it would be possible to accomplish this by chaining the commands in a single system call.
os.system("umask 055")
os.system("ls -alh > test")

Becomes:
os.system("umask 055; ls -alh > test")

or, if you only want to run the second command if the previous exited successfully:
os.system("umask 055 && ls -alh > test")


text:
Q: Parse a TimeSpan greater than 24 hours? I have this function:
  public static decimal Hours(string s)
    {
        return (decimal)TimeSpan.Parse(s).TotalHours + 0.005M;
    }

The format is Hours:Minutes, ex: 30:20, or 10:17. It fails if I write give it say 25:03 or 30:20 since it is over 24 hours. Is there a way I can have it parse something > 23:59 ?
Simply put, if my string is 30:30, this function needs to return 30.5.

A: I'm not sure it can be done using standard TimeSpan.Parse() method, but you can do that:
public static decimal Hours(string s)
{
    decimal r;
    if (decimal.TryParse(s, out r))
        return r;

    var parts = s.Split(':');
    return (decimal)new TimeSpan(int.Parse(parts[0]), int.Parse(parts[1]),0).TotalHours;
}


text:
Q: How to sort keys in incomplete .json file (missing brackets) with Notepad++ or Python? I have incomplete .json files, with missing brackets,
but always the same five keys: "COUNTRY","CAPITOL","CURRENCY","POPULATION","OUTPUT"
Those five keys are also always in random order, as you can see in this example:
      "COUNTRY" : "Japan",
      "CAPITOL" : "Tokyo",
      "CURRENCY" : "Yen",
      "POPULATION" : "126 500 000",
      "OUTPUT" : "4 971 000 000 000",

      "CURRENCY" : "USD",
      "CAPITOL" : "Washington, D.C.",
      "COUNTRY" : "USA",
      "OUTPUT" : "20 000 000 000 000",
      "POPULATION" : "328 000 000"
      ...

Therefore I cannot automate the process of adding brackets with (preferably) Notepad++, or with Python.
Any ideas how to do it?
I want the output always in the same order, like "COUNTRY","CAPITOL","CURRENCY","POPULATION","OUTPUT".
Here's an example of the output I want to create:
      {"COUNTRY" : "Japan",
      "CAPITOL" : "Tokyo",
      "CURRENCY" : "Yen",
      "POPULATION" : "126 500 000",
      "OUTPUT" : "4 971 000 000 000"},

      {"COUNTRY" : "USA",
      "CAPITOL" : "Washington, D.C.",
      "CURRENCY" : "USD",
      "POPULATION" : "328 000 000",
      "OUTPUT" : "20 000 000 000 000"},
      ...

Any suggestions please? My idea is to sort the keys, but maybe there is another solution.

A: This can be done in Notepad++ with a weird regex!

*

*Ctrl+H

*Find what: (?:\G)\s*(?=[\s\S]*?("COUNTRY" : "[^"]+"),?\s?)(?=[\s\S]*?("CAPITOL" : "[^"]+"),?\s?)(?=[\s\S]*?("CURRENCY" : "[^"]+"),?\s?)(?=[\s\S]*?("POPULATION" : "[^"]+"),?\s?)(?=[\s\S]*?("OUTPUT" : "[^"]+"),?\s?)((?:.+\R?){5})

*Replace with: {\n$1,\n$2,\n$3,\n$4,\n$5\n},\n

*CHECK Match case

*CHECK Wrap around

*CHECK Regular expression

*UNCHECK . matches newline

*Replace all
Demo & Explanation
Screenshot (before):

Screenshot (after):


text:
Q: Center a container row on bootstrap I read online that you can use the below code to center a row in a container using bootstrap, but I haven't been able to get it to work and I think it might have something to do with the css.

Below is the current code. There was no .portfolio in the template and it won't let me add it.

.portfolio #portfolio-flters {
  padding: 0;
  width: 50%;
  margin: auto;
  list-style: center;
  text-align: center;
  border-radius: 50px;
}

.portfolio #portfolio-flters li {
  cursor: pointer;
  display: inline-block;
  padding: 10px 15px;
  font-size: 15px;
  font-weight: 500;
  line-height: 1;
  text-transform: uppercase;
  color: #444444;
  width: 50%;
  margin: auto;
  margin-bottom: 5px;
  transition: all 0.3s ease-in-out;
  font-family: "Poppins", sans-serif;
}

.portfolio #portfolio-flters li:hover,
.portfolio #portfolio-flters li.filter-active {
  color: #593d4a;
}

.portfolio #portfolio-flters li:last-child {
  margin-right: 0;
}

.portfolio .portfolio-item {
  margin-bottom: 30px;
}

.portfolio .portfolio-item .portfolio-info {
  opacity: 0;
  position: absolute;
  left: 30px;
  right: 30px;
  margin: auto;
  width: 20%;
  text-align: center;
  bottom: 0;
  z-index: 3;
  transition: all ease-in-out 0.3s;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
}

.portfolio .portfolio-item .portfolio-info h4 {
  font-size: 12px;
  color: #fff;
  font-weight: 600;
  color: #191919;
}

.portfolio .portfolio-item .portfolio-info p {
  color: #4c4c4c;
  font-size: 14px;
  margin-bottom: 0;
}

.portfolio .portfolio-item .portfolio-info .preview-link,
.portfolio .portfolio-item .portfolio-info .details-link {
  position: absolute;
  right: 40px;
  font-size: 24px;
  top: calc(50% - 18px);
  color: #333333;
}

.portfolio .portfolio-item .portfolio-info .preview-link:hover,
.portfolio .portfolio-item .portfolio-info .details-link:hover {
  color: #593d4a;
}

.portfolio .portfolio-item .portfolio-info .details-link {
  right: 10px;
}

.portfolio .portfolio-item .portfolio-links {
  opacity: 0;
  left: 0;
  right: 0;
  text-align: center;
  z-index: 3;
  position: absolute;
  transition: all ease-in-out 0.3s;
}

.portfolio .portfolio-item .portfolio-links a {
  color: #fff;
  margin: 0 2px;
  font-size: 28px;
  display: inline-block;
  transition: 0.3s;
}

.portfolio .portfolio-item .portfolio-links a:hover {
  color: #593d4a;
}

.portfolio .portfolio-item:hover .portfolio-info {
  opacity: 1;
  bottom: 20px;
}
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">

Word Clouds

20 Nov

21 Nov

22 Nov

23 Nov

24 Nov

And this is an image of the problem, the last row isn't centered:

Thank you so much in advance for the help!


text:
Q: In Magento how to show invoice no.? I want to show invoice no. in a page what is the code for insert invoice no. for particular order and show particular invoice no. there is any way to show.

A: $order = Mage::getModel('sales/order')->load($orderid);
if ($order->hasInvoices()) { // check if order has invoice
    foreach ($order->getInvoiceCollection() as $inv) {
        $invIncrementIDs[] = $inv->getIncrementId();
    //other invoice details...
    }
  print_r($invIncrementIDs);
}

I think this might help you


text:
Q: How to check the number of partitions of a Spark DataFrame without incurring the cost of .rdd There are a number of questions about how to obtain the number of partitions  of a n RDD and or a DataFrame : the answers invariably are:
 rdd.getNumPartitions

or
 df.rdd.getNumPartitions

Unfortunately that is an expensive operation on a DataFrame because the
 df.rdd

requires conversion from the DataFrame to an rdd.  This is on the order of the time it takes to run
 df.count

I am writing logic that optionally repartition's or coalesce's a DataFrame - based on whether the current number of partitions were within a range of acceptable values or instead below or above them.
  def repartition(inDf: DataFrame, minPartitions: Option[Int],
       maxPartitions: Option[Int]): DataFrame = {
    val inputPartitions= inDf.rdd.getNumPartitions  // EXPENSIVE!
    val outDf = minPartitions.flatMap{ minp =>
      if (inputPartitions < minp) {
        info(s"Repartition the input from $inputPartitions to $minp partitions..")
        Option(inDf.repartition(minp))
      } else {
        None
      }
    }.getOrElse( maxPartitions.map{ maxp =>
      if (inputPartitions > maxp) {
        info(s"Coalesce the input from $inputPartitions to $maxp partitions..")
        inDf.coalesce(maxp)
      } else inDf
    }.getOrElse(inDf))
    outDf
  }

But we can not afford to incur the cost of the rdd.getNumPartitions for every DataFrame in this manner.
Is there not any way to obtain this information - e.g. from querying the online/temporary catalog for the registered table maybe?
Update  The Spark GUI showed the DataFrame.rdd operation as taking as long as the longest sql in the job. I will re-run the job and attach the screenshot in a bit here.
The following is just a testcase : it is using a small fraction of the data size of that in production.  The longest sql is only five minutes - and this one is on its way to spending that amount of time as well (note that the sql is not helped out here: it also has to execute subsequently thus effectively doubling the cumulative execution time).

We can see that the .rdd operation at DataFrameUtils line 30 (shown in the snippet above) takes 5.1mins - and yet the save operation still took 5.2 mins later -i.e. we did not save any time by doing the .rdd in terms of the execution time of the subsequent save.

A: In my experience df.rdd.getNumPartitions is very fast, I never encountered taking this more than a second or so.
Alternatively, you could also try
val numPartitions: Long = df
      .select(org.apache.spark.sql.functions.spark_partition_id()).distinct().count()

which would avoid using .rdd

A: There is no inherent cost of rdd component in rdd.getNumPartitions, because returned RDD is never evaluated.
While you can easily determine this empirically, using debugger (I'll leave this as an exercise for the reader), or establishing that no jobs are triggered in the base case scenario
Spark session available as 'spark'.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.4.0
      /_/

Using Scala version 2.11.12 (OpenJDK 64-Bit Server VM, Java 1.8.0_181)
Type in expressions to have them evaluated.
Type :help for more information.

scala> val ds = spark.read.text("README.md")
ds: org.apache.spark.sql.DataFrame = [value: string]

scala> ds.rdd.getNumPartitions
res0: Int = 1

scala> spark.sparkContext.statusTracker.getJobIdsForGroup(null).isEmpty // Check if there are any known jobs
res1: Boolean = true

it might be not enough to convince you. So let's approach this in a more systematic way:

*

*rdd returns a MapPartitionRDD (ds as defined above):
scala> ds.rdd.getClass
res2: Class[_ <: org.apache.spark.rdd.RDD[org.apache.spark.sql.Row]] = class org.apache.spark.rdd.MapPartitionsRDD

*RDD.getNumPartitions invokes RDD.partitions.

*In non-checkpointed scenario RDD.partitions invokes getPartitions (feel free to trace the checkpoint path as well).

*RDD.getPartitions is abstract.

*So the actual implementation used in this case is MapPartitionsRDD.getPartitions, which simply delegates the call to the parent.

*There are only MapPartitionsRDD between rdd and the source.
scala> ds.rdd.toDebugString
res3: String =
(1) MapPartitionsRDD[3] at rdd at <console>:26 []
 |  MapPartitionsRDD[2] at rdd at <console>:26 []
 |  MapPartitionsRDD[1] at rdd at <console>:26 []
 |  FileScanRDD[0] at rdd at <console>:26 []

Similarly if Dataset contained an exchange we would follow the parents to the nearest shuffle:
scala> ds.orderBy("value").rdd.toDebugString
res4: String =
(67) MapPartitionsRDD[13] at rdd at <console>:26 []
 |   MapPartitionsRDD[12] at rdd at <console>:26 []
 |   MapPartitionsRDD[11] at rdd at <console>:26 []
 |   ShuffledRowRDD[10] at rdd at <console>:26 []
 +-(1) MapPartitionsRDD[9] at rdd at <console>:26 []
    |  MapPartitionsRDD[5] at rdd at <console>:26 []
    |  FileScanRDD[4] at rdd at <console>:26 []

Note that this case is particularly interesting, because we actually triggered a job:
scala> spark.sparkContext.statusTracker.getJobIdsForGroup(null).isEmpty
res5: Boolean = false

scala> spark.sparkContext.statusTracker.getJobIdsForGroup(null)
res6: Array[Int] = Array(0)

That's because we've encountered as scenario where the  partitions cannot be determined statically (see Number of dataframe partitions after sorting? and Why does sortBy transformation trigger a Spark job?).
In such scenario getNumPartitions will also trigger a job:
scala> ds.orderBy("value").rdd.getNumPartitions
res7: Int = 67

scala> spark.sparkContext.statusTracker.getJobIdsForGroup(null)  // Note new job id
res8: Array[Int] = Array(1, 0)

however it doesn't mean that the observed cost is somehow related to .rdd call. Instead it is an intrinsic cost of finding partitions in case, where there is no static formula (some Hadoop input formats for example, where full scan of the data is required).
Please note that the points made here shouldn't be extrapolated to other applications of Dataset.rdd. For example ds.rdd.count would be indeed expensive and wasteful.


text:
Q: Rails 4: Ember.js doesn't see my templates? I am trying to just render a template from templates/about.handlebars.
I have the outlet setup in rails view:
%script{ type: 'text/x-handlebars'}

 My app

  {{ outlet }}
  ^-- outlet

the about route looks like this:
Admin.Router.map ->
  @route 'about', path: '/'

And the about template is plain html:

This is ABOUT!

What seems to work:

*

*I can see the Ember debug message, that confirms ember is working

*I have ember chrome extension installed and it can see the application template

But, when I ask for Ember.TEMPLATES, I get:
Object {application: function}
application: function (context, options) {
__proto__: Object

and no about template there.
Digging in the compiled js file, I can see the handlebar template is physically there:
(function() {
  this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
  this.HandlebarsTemplates["about"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};

  return "\n
This is ABOUT!
\n\n";
  });
  return this.HandlebarsTemplates["about"];
}).call(this);

But I don't see it being explicitly added to Ember.TEMPLATES.
Update 1: Inspecting the ember-rails gem, I see that handlebars will match only files that have .raw.(hjs|...), or mustache.(hjs|...) in their names? Documentation doesn't seem to speak about this.
Even if I rename the template it still doesn't show and its supper weird since I haven't seen templates names like that in tutorials, or the gem documentation.

A: Ember looks for precompiled templates in Ember.TEMPLATES, not HandlebarsTemplates.


text:
Q: IF statement to color Datagridview rows bound to a SQL query Alright, maybe I'm missing something simple but I can not get an if statement inside a for loop to color a datagridview row based on a cell's value. Maybe you guys can see something I can't.
Here is my SQL code:
SELECT
    Part,
    CASE
       WHEN missing = 1 OR secondmissing = 1
          THEN '1'
       WHEN missing IS NULL AND secondMissing IS NULL
          THEN '0'
    END AS 'missing'
FROM
    TableA

This query returns a list of part numbers and if they have been marked as missing or not and appears to run fine. In my Winforms application, I have a For loop to check the datagridview loaded with the SQL query above to color any rows yellow that have the missing marked as 1. However nothing I seem to try work for catching line items marked as 1.
Here is my VB code:
For x as integer = 0 to DataGridView1.rows.count - 1
  With Datagridview1.rows(x)
    if .cells(1).value.tostring = "1" then *
       .DefaultCellStyle.Backcolor = Color.Yellow
   else
       .DefaultCellStyle.BackColor = Color.White
   End If
 End With
Next

Notice in the for loop I marked a line with an *. Here are all the things I have tried here.
if .cells("missing").value = True Then
if .cells(1).value.tostring = "1" Then
if CInt(.cells(1).value) = 1 Then
if CInt(.cells(1).value.tostring) = 1 Then

None of the above options seem to work. If I try and use the column name "missing" instead of the column integer of 1 it completely misses the code.
Any help would be great.
EDIT:
I guess I should note the SQL columns datatypes: Part is NVARCHAR(25) and both missing and secondmissing are BIT.


text:
Q: Why does this odd glitch exist with graphing programs? In Grapher on Mac and the TI-84's built-in graphing program, there is a problem with imaginary numbers. If I input $ i\sqrt {x}$, the graph ends up looking like this, even though it ought to look like $-\sqrt {-x}$. The same problem happens in the TI-84. I decided to test it in Grapher and entered
$$
y = \begin{cases}
  1, & i = \sqrt{-1}, \\
  2, & i ≠ \sqrt{-1}
\end{cases}$$
And it showed y=2. I'm not sure if these are the same bug, but I think they are related. I'm also not sure if the latter bug exists on TI-84. Note: This glitch doesn't seem to occur in Wolfram Alpha
EDIT: TI-84's normal calculation does just fine with this stuff, and so does TI-BASIC


text:
Q: Why Groovy file write with UTF-16LE produce BOM char? Do you have idea why first and secod lines below do not produce BOM to the file and third line does? I thought UTF-16LE is correct encoding name and that encoding does no create BOM automatically to beginning of the file.
new File("foo-wo-bom.txt").withPrintWriter("utf-16le") {it << "test"}
new File("foo-bom1.txt").withPrintWriter("UnicodeLittleUnmarked") {it << "test"}
new File("foo-bom.txt").withPrintWriter("UTF-16LE") {it << "test"}

Another samples
new File("foo-bom.txt").withPrintWriter("UTF-16LE") {it << "test"}
new File("foo-bom.txt").getBytes().each {System.out.format("%02x ", it)}

prints
ff fe 74 00 65 00 73 00 74 00

and with java
        PrintWriter w = new PrintWriter("foo.txt","UTF-16LE");
        w.print("test");
        w.close();
        FileInputStream r = new FileInputStream("foo.txt");
        int c;
        while ((c = r.read()) != -1) {
            System.out.format("%02x ",c);
        }
        r.close();

prints
74 00 65 00 73 00 74 00

With Java is does not produce BOM and with Groovy there is BOM.

A: There appears to be a difference in behavior with withPrintWriter.  Try this out in your GroovyConsole
File file = new File("tmp.txt")
try {
    String text = " "
    String charset = "UTF-16LE"

    file.withPrintWriter(charset) { it << text }
    println "withPrintWriter"
    file.getBytes().each { System.out.format("%02x ", it) }

    PrintWriter w = new PrintWriter(file, charset)
    w.print(text)
    w.close()
    println "\n\nnew PrintWriter"
    file.getBytes().each { System.out.format("%02x ", it) }
} finally {
    file.delete()
}

It outputs

withPrintWriter
ff fe 20 00

new PrintWriter
20 00

This is because calling new PrintWriter calls the Java constructor, but calling withPrintWriter eventually calls org.codehaus.groovy.runtime.ResourceGroovyMethods.writeUTF16BomIfRequired(), which writes the BOM.
I'm uncertain whether this difference in behavior is intentional.  I was curious about this, so I asked on the mailing list.  Someone there should know the history behind the design.
Edit: GROOVY-7465 was created out of the aforementioned discussion.


text:
Q: How to get a string value in input as invalid? I've been playing around with strings and I've found that when one inputs a string into a input function it gives an error.
I was wondering how to print "invalid" if a string was typed for an input variable. I want to do this the simplest way possible and the function should be the input and not the raw_input and I don't want to use try or except because that would complicate the code I'm planning to create.
testing_variable = input ("enter a number:")
# if a string is entered print invalid
if testing_variable == "":
# the "" is what im using if a string is entered and im having a hard time solving this
#Tips or advice of any coversion of the input would be helpful
    print "invalid"

A: Python 2.7 supports input and raw_input.
So, with input, you are expected to wrap your input with quotes. If you are wanting to avoid this, then use raw_input.
Example with raw_input:
>>> raw_input('hi ')
hi hey
'hey'

If you are looking to force the user to always enter a digit, then you can wrap it in a try/except as such:
try:
    i = int(raw_input("Enter a number: "))
except:
    print("you did not enter a number")

A: Using the input function in Python 2 is generally a bad idea. It is equivalent to eval(raw_input()), and thus expects the user to input a valid Python expression. If they type in something that is not valid Python, you'll always get an error.
While you could catch various exceptions and translate them into useful error messages, a better approach is to use raw_input and do your own validation for the specific types of input you want to be able to handle. If you only want to accept numbers, try converting the string you get from raw_input to int or float (and catching ValueError exceptions which indicate non-numeric input). For your desired result of printing "invalid":
try:
    result = int(raw_input("enter a number"))
except ValueError:
    print "invalid"

This is the most Pythonic way to solve the issue. If for some reason you don't want to use exception handling, you can save the string you get from raw_input and analyze it first to make sure it has only the characters you expect before converting it to a number. For base 10 integers this is not too hard, as only digits need to be checked for, and the isdigit method on a string will check if it contains only digit charaters:
str_input = raw_input("enter a number")
if str_input.isdigit():
    result = int(str_input)
else: # string contains non-digit characters
    print "invalid"

It's quite a bit more complicated to validate the input string if you want to support floating point numbers, as there's no convenient function like isdigit that will check all the characters for you. You could do it if you really wanted to, but I'd strongly recommend going with the exception catching code style shown above and just passing the string to float to see if it works.

A: This is the best way in my opinion:
testing_variable = input ("enter a number:")
try:
   number_var = int(testing_variable)
   print(number_var)
except ValueError:
   print("Invalid")

Without using try you can do:
testing_variable = input ("enter a number:")
if not testing_variable.isdigit():
    print("Invalid")


text:
Q: Unzip multiple folders with password protected spreadsheet Hi I have multiple zipped folders and each zipped folder contains one password protected excel spreadsheet.
#Get all the zip files
zipF = list.files(path="C:/Users/whyka/Desktop/School", pattern = "*.zip", full.names = TRUE)

#unzip all the files
ldply(.data = zipF, .fun =unzip, exdir = getwd())

I was able to extract the files but since they were password protected, the spreadsheets are blank and does not contain anything. *all of the spreadsheets contain the same password. help will be greatly appreciated


text:
Q: Trying to replace 1 value with a conditional replaces the whole column Dim WB As Workbook
Set WB = ThisWorkbook

Dim lrow As Long
lrow = WB.Sheets("Updated Sheet").Range("B" & Rows.Count).End(xlUp).row

Dim myrange As Range
Set myrange = WB.Sheets("Updated Sheet").Range("R2:R" & lrow)
Dim row As Long
Dim col As Long

row = WB.Sheets("Updated Sheet").Range("AJ2").row
col = WB.Sheets("Updated Sheet").Range("AJ2").Column

For Each cl In myrange  'myrange is basically column "R"

If wb.Sheets("Updated Sheet").Cells(row, col) = "Paid" Then
cl.value = "Paid"
Else
End If
row = row + 1
Next cl

This is the code I currently have for an if statement where I want to replace the value in column R with the string "Paid" if the value in (row, col) is "Paid" as well.
However, the function currently replaces all values in column R even if there is only one "Paid" match, even though running through with f8/adding a msgbox line shows that the value in cell(row, col) is not "paid" for every line.
How should I go about fixing this?

A: Add .value to your cell reference. Currrently you are comparing a string with a cell object. That could lead to strange results.
If wb.Sheets("Updated Sheet").Cells(row, col).value = "Paid" Then

A: Try Autofilter instead of looping through cells.
Please give this a try...
Sub David()
Dim WB As Workbook
Dim WS As Worksheet
Dim lrow As Long
Set WB = ThisWorkbook
Set WS = WB.Sheets("Updated Sheet")
WS.AutoFilterMode = False
lrow = WB.Sheets("Updated Sheet").Range("B" & Rows.Count).End(xlUp).row
With WS.Range("AJ1:AJ" & lrow)
    .AutoFilter field:=1, Criteria1:="Paid"
    If WS.Range("R1:R" & lrow).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
        WS.Range("R2:R" & lrow).SpecialCells(xlCellTypeVisible).Value = "Paid"
    End If
    .AutoFilter
End With
End Sub


text:
Q: Can you find the logical size of a single NotesDocument in a DAOS-enabled database or an uploaded file size? I'm doing some feasability for an XPages application. One of the aspects is checking the amount of space used by users.
The database will be DAOS-enabled to minimise the size of the NSF. Is it possible to identify the logical size of a NotesDocuemnt that has a DAOSed attachment? I know I can find the logical size of the overall database, but need to identify it based on users.
LotusScript or Java would be acceptable options.
The other option is to capture file sizes at upload time and store that information against the user. Is it possible to identify the attachment size at the point of upload and deletion? This would need to be captured before the attachment was moved to the DAOS store.

A: Paul,
As far as I know from the client point of view he can't see if a Database/Document has been DAOS'ed or not. SO this meahs that using LotusScript against the document would report the document size as if the attachment(s) would be in the document. I haven't tested it myself to give you a 100% guarantee but you could test it for yourself very easily by enabling a database for DAOS and then create 10 docs with all of them the exact same attachment attached to the documents. If the docs report a size of arround the attachment size when accessed via LotusScript you will have your answer !

A: You could check the logical size of the database before and after saving the document. But unfortunately, you would have to rig the critical section of this code with a semaphore or some other mechanism that assures that only one instance can run at a time, otherwise two simultaneous saves would give you bad results.

A: Build a view with a column whose formulas is @DocLength or @Sum(@AttachmentLengths) This will show the logical size of the docs as if DAOS was not active.
/Newbs


text:
Q: Libreoffice Calc Tokenize (?) a Cell Hello and thanks in advance for answers.
I have a spreadsheet in Calc that contains a cell that contains minutes played for goalies. An example of data in the cell is:
1975:30:00
This means 1975 minutes and 30 seconds.
I'm trying to "tokenize" (I don't know if that is proper term) by the : and present the data in 3 adjacent cells.
For example:
A1: 1975:30:30
A2: 1975
A3: 30
A4: 00
I cannot for the life of me figure it out. I'm quite proficient in Excel but I don't want to pay for another licence on the laptop I'm using for this project so I'm using LibreOffice Calc. I am beginner level in LibreOffice Calc.
So please keep in mind my newbie status in Calc if you are able to answer this question.

A: Ok I figured it out:
A1: 1975:30:00
A2: =Quotient(A1 * 24, 1)
A3: =Mod(A1 * 24, 1) * 60
A4: is not needed.


text:
Q: Synchronously process Observable to prevent too many HTTP requests from timing out using rxjs Angular and ngrx I have the following code. It gets an array of Patients and builds a rows object this.rows that I show in a table on the frontEnd of this angular 4 component (I am also using rxjs 5.5).
My issue is the hasAlert property of each row is assigned by a call to hasAlerts(). In the HasAlerts method, I make an http request, for each patient via this.dataService.fetchItems<Observation>(.
When there are many patients, too many HTTP requests will occur asynchronously and they will start to fail (timeout) from HasAlerts(). Is there a way to throttle this,or process one Observable at a time from hasAlerts()?
Below are possible ways to solve this

*

*I think concatMap may be helpful but I am not sure how to use it. Also should use it to process each patient/row or should try and aggregate each hasAlert() observable into a list and then try and use concatMap to process them one at a time?

*A workaround is the patientsAlertsProcessed variable wrapper that I added with the comment // is done to throttle the hasAlertsMethod. I limit it to only hit that method for 15 times to avoid timeout issues. This is not ideal because I am not able to start it up again once those 15 async requests complete.

Code is below
ngOnInit(): void {
    this.store.dispatch(new patients.Load([]));

    this.patients$ = this.store.select(fromPatients.getAll);
    var patientsAlertsProcessed =0;
    this.patients$.debounceTime(2000).map(p =>{//Emits Observable<Patient[]>s, the debounceTime is to take the last one as it builds up
      this.rows = p.map(pat => {// p = Patient[], iterate through the array of patients
        var observations=0;
        var rowX= {
          username: pat.username,
          id: pat.id,
          hasAlert:false,
        };

        if (patientsAlertsProcessed<15){// this is done to throttle the HasAlerts Method
          this.hasAlerts(pat).do(x => {
            observations++;
            if (observations>0)
            {
              rowX.hasAlert=true;
            }
          }).subscribe();
          patientsAlertsProcessed++;
        }
        return rowX;
      });
    }).subscribe(
       ()=> { },
       ()=> {
        this.table.recalculatePages();
      }
    );

  }
  hasAlerts(pat: Patient): Observable<Observation> {
    var obs$= this.dataService.fetchItems<Observation>(// this is making an HTTP get request
        "Observation",
        null,
        pat.id
      ).filter(function (x){
        if (x.category.coding[0].code == "GlucoseEvent"){
            return true;
        }
        else{
          return false;
        }
      }
    );
    return obs$;
  }

A: You may want to try something along these lines.
const concurrency = 10;
const rowsWithAlerts = [];

this.patients$.debounceTime(2000)
.switchMap(patients => Observable.from(patients)) // patients is of type Patient[]
.mergeMap(patient => {
   rowsWithAlerts.push(patient);
   this.hasAlerts(patient).do(
   hasAlertsResult => {
     // here you have hold to both the patient and the result of
     // hasAlerts call
     patient.hasAlerts = hasAlertsResult;
   }}), concurrency)
.subscribe(
   () => this.rows = rowsWithAlerts;
)

The key here is to use the mergeMap operator with the concurrency level set to a value, in this example 10 but clearly can be anything.
This allows to limit the number of observables to which you subscribe at the same time, which in your case means to limit the number of http calls you make.


text:
Q: Show md-dialog on a div not on whole body I am trying to apply md-dialog only on a div not on the whole body , so that I can use textbox inside the header div when the md-dialog is opened.
Example : HTML

    <input type="text">

      <md-content>
        <md-button ng-click="showDialog($event)">Launch Dialog</md-button>
      </md-content>

Controller :
 function showDialog($event) {
    var parentEl = angular.element(document.querySelector('md-content'));
    alert = $mdDialog.alert({
      parent: parentEl,
      targetEvent: parentEl,
      template:
        '<md-dialog aria-label="Sample Dialog">' +
        '  <md-content>'+
        '    </md-list>'+
        '  </md-content>' +
        '
' +
        '    <md-button ng-click="ctrl.closeDialog()">' +
        '      Close Greeting' +
        '    </md-button>' +
        '
' +
        '</md-dialog>',
        locals: {
          closeDialog: $scope.closeDialog
        },
        bindToController: true,
        controllerAs: 'ctrl',
        controller: 'DialogController'
    });

From the above example i want to make first_div independent of md-dialog.
only second_div should show the dialog.
So that when dialog is shown to user , user should be able to enter details in the first div.
Check CodePen for more info
Code Pen Link

A: To position a dialog above a particular div, you must provide the parent and the targetEvent :
$scope.showAlert = function(ev) {
    $mdDialog.show(
      $mdDialog.alert()
        .parent(angular.element(document.querySelector('#second_div')))
        .clickOutsideToClose(true)
        .title('This is an alert title')
        .content('You can specify some description text in here.')
        .ariaLabel('Alert Dialog Demo')
        .ok('Got it!')
        .targetEvent(ev)
    );
};

After that, to make your input available, you must apply "z-index" to the div containing your input.
CSS
#first_div{
    z-index:1000;
}


text:
Q: PowerBuilder. Number Type for table Column in DataWindow I have got such code
table(column=(type=number updatewhereclause=no name=a dbname="a" )
column=(type=number updatewhereclause=no name=b dbname="b")
column=(type=number updatewhereclause=no name=c dbname="c" values="8    8/10    10/12   12/14   14/16   16/" ))

I read powerbuilder tutorial but don't find any information about "number" type.
Can anybody describe this type for me? Thanks.

A: It appears as though the datawindow object in question is using an External Datasource.  Per the documentation:

The number datatype is equivalent to the PowerBuilder double datatype.


text:
Q: You throw a dice 3 times,probabilty whats the probability of the number k to be the highest? You throw a fair dice 3 times,
let X be the highest number you will get.
What is the PDF of $P(X=K), K=1,...6$ ?
The answer is : $$\frac{k^3-(k-1)^3}{216}$$
However, I can't understand it, could help me to understand why is this the right answer?
Thank you

A: The probability that the biggest roll will be $K$ is the probability that all three rolls are less than or equal to $K$, minus the case where all the rolls are in fact strictly less than $K$.
Let $X_1,X_2,X_3$ be the outcome of our three rolls (so $X = \max(X_1,X_2,X_3)$). Then $$P(X = K) = P(X_1 \leq K)P(X_2 \leq K)P(X_3 \leq K) - P(X_1 \leq K - 1)P(X_2 \leq K - 1)P(X_3 \leq K - 1)$$
Now $P(X_i \leq K) = \frac{K}{6}$. Hence $$P(X = K) = (\frac{K}{6})^3 - (\frac{K-1}{6})^3$$ which is the answer you are looking for.

A: For $k$ to be the highest at least one must be $k$ and the other two must be at less or equal to $k$.
If there is only one that has $k$ there are $3$ dice which may be the $k$, and the other two must be less than $k$, there are $k-1$ options for each.  So there are $3(k-1)^2$ ways for there to be exactly one $k$ and it being the highest.
If there are two that have $k$ then there are are ${3 \choose 2} =3$ dice that might have the $k$s and $1$ that has the $k-1$ option to not be $k$.  So there are $3(k-1)$ ways for that to occur.
And finally there is exactly $1$ way for there to be all three showing $k$.
So $3(k-1)^2 + 3(k-1) + 1 = $
$[(k-1)^3 +3(k-1)^2 + 3(k-1) + 1] - (k-1)^3 = $
$[(k-1) + 1]^3 - (k-1)^3 =$
$k^3 - (k-1)^3$ ways to do this.
And there are $6^3=216$ ways to roll three dice total.
So $P = \frac {k^3 - (k-1)^3}{216}$.


text:
Q: bootstrap Carousel disappears when its looping hellow everyone, the slider is working good , but when it comes to the last image and want to go back to the first image , it disappears .
here is the bootstrap code  , i didn't use jquery yet

            ...

            ...

            ...

            ...

            ...

        Previous

        Next

here is it , when the slider disappears


text:
Q: How do I change the terminal's path style in Mac OS I have searched on Google but I couldn't find the exact solution.
Please take a look at the picture and let me know how to change the path's background color as you can see.
I know how to change the font or the background but I meant that exactly background of the path in terminal.


text:
Q: How to save flappy bird (made with pygame on python 3.9) scores into sql database I m new to pygame and started learning it by making flappy bird by watching tutorials. I need to save the player's name and score to the sql database ( the table already has been created by me to store data) for a project. But whenever the program comes to saving the name and score, the GUI gets hanged rather than restarting the game and the data doesn't get saved. Here's the code:-
import pygame, sys, random
def sql():
    import mysql.connector as c
    m=c.connect(host="localhost",user="root",password= "password",database="flappy
bird")
    my=m.cursor()
    n=input('enter your name')
    r = score
    my.execute("insert into table(name, score) values({},'{}')".format(n,r))
    m.commit()
    my.execute("select * from table")
    for i in my:
      print(i)

def draw_floor():
    screen.blit(floor_surface,(floor_x_pos,900))
    screen.blit(floor_surface,(floor_x_pos + 576,900))

def create_pipe():
    random_pipe_pos = random.choice(pipe_height)
    bottom_pipe = pipe_surface.get_rect(midtop = (700,random_pipe_pos))
    top_pipe = pipe_surface.get_rect(midbottom = (700,random_pipe_pos - 300))
    return bottom_pipe,top_pipe

def move_pipes(pipes):
    for pipe in pipes:
        pipe.centerx -= 5
    visible_pipes = [pipe for pipe in pipes if pipe.right > -50]
    return visible_pipes

def draw_pipes(pipes):
    for pipe in pipes:
        if pipe.bottom >= 1024:
            screen.blit(pipe_surface,pipe)
        else:
            flip_pipe = pygame.transform.flip(pipe_surface,False,True)
            screen.blit(flip_pipe,pipe)

def check_collision(pipes):
    global can_score
    for pipe in pipes:
        if bird_rect.colliderect(pipe):
            death_sound.play()
            can_score = True
            return False

    if bird_rect.top <= -100 or bird_rect.bottom >= 900:
        can_score = True
        return False

    return True

def rotate_bird(bird):
    new_bird = pygame.transform.rotozoom(bird,-bird_movement * 3,1)
    return new_bird

def bird_animation():
    new_bird = bird_frames[bird_index]
    new_bird_rect = new_bird.get_rect(center = (100,bird_rect.centery))
    return new_bird,new_bird_rect

def score_display(game_state):
    if game_state == 'main_game':
        score_surface = game_font.render(str(int(score)),True,(255,255,255))
        score_rect = score_surface.get_rect(center = (288,100))
        screen.blit(score_surface,score_rect)
    if game_state == 'game_over':
        score_surface = game_font.render(f'Score: {int(score)}' ,True,(255,255,255))
        score_rect = score_surface.get_rect(center = (288,100))
        screen.blit(score_surface,score_rect)

        high_score_surface = game_font.render(f'High score: {int(high_score)}',True,
        (255,255,255))
        high_score_rect = high_score_surface.get_rect(center = (288,850))
        screen.blit(high_score_surface,high_score_rect)

def update_score(score, high_score):
    if score > high_score:
        high_score = score
    return high_score

def pipe_score_check():
    global score, can_score

    if pipe_list:
        for pipe in pipe_list:
            if 95 < pipe.centerx < 105 and can_score:
                score += 1
                score_sound.play()
                can_score = False
            if pipe.centerx < 0:
                can_score = True

#pygame.mixer.pre_init(frequency = 44100, size = 16, channels = 2, buffer = 1024)
pygame.init()
screen = pygame.display.set_mode((576,1024))
clock = pygame.time.Clock()
game_font = pygame.font.Font('04B_19.ttf',40)

# Game Variables
gravity = 0.5
bird_movement = 0
game_active = True
score = 0
high_score = 0
can_score = True
bg_surface =
pygame.image.load('assets/background-
day.png').convert()
bg_surface = pygame.transform.scale2x(bg_surface)

floor_surface =
pygame.image.load('assets/base.png').convert()
floor_surface =
pygame.transform.scale2x(floor_surface)
floor_x_pos = 0

bird_downflap =
pygame.transform.scale2x(pygame.image.load('assets/bluebird-
downflap.png').convert_alpha())
bird_midflap = pygame.transform.scale2x(pygame.image.load('assets/bluebird-
midflap.png').convert_alpha())
bird_upflap = pygame.transform.scale2x(pygame.image.load('assets/bluebird-
upflap.png').convert_alpha())
bird_frames = [bird_downflap,bird_midflap,bird_upflap]
bird_index = 0
bird_surface = bird_frames[bird_index]
bird_rect = bird_surface.get_rect(center = (100,512))

BIRDFLAP = pygame.USEREVENT + 1
pygame.time.set_timer(BIRDFLAP,200)

# bird_surface = pygame.image.load('assets/bluebird-midflap.png').convert_alpha()
# bird_surface = pygame.transform.scale2x(bird_surface)
# bird_rect = bird_surface.get_rect(center = (100,512))

pipe_surface = pygame.image.load('assets/pipe-green.png')
pipe_surface = pygame.transform.scale2x(pipe_surface)
pipe_list = []
SPAWNPIPE = pygame.USEREVENT
pygame.time.set_timer(SPAWNPIPE,1200)
pipe_height = [400,600,800]

game_over_surface =
pygame.transform.scale2x(pygame.image.load('assets/message.png').convert_alpha())
game_over_rect = game_over_surface.get_rect(center = (288,512))

flap_sound = pygame.mixer.Sound('sound/sfx_wing.wav')
death_sound = pygame.mixer.Sound('sound/sfx_hit.wav')
score_sound = pygame.mixer.Sound('sound/sfx_point.wav')
score_sound_countdown = 100
SCOREEVENT = pygame.USEREVENT + 2
pygame.time.set_timer(SCOREEVENT,100)

while True:
   for event in pygame.event.get():
       if event.type == pygame.QUIT:
           pygame.quit()
           sys.exit()
       if event.type == pygame.KEYDOWN:
           if event.key == pygame.K_SPACE and game_active:
               bird_movement = 0
               bird_movement -= 12
               flap_sound.play()
           if event.key == pygame.K_SPACE and game_active == False:
               game_active = True
               pipe_list.clear()
               bird_rect.center = (100,512)
               bird_movement = 0
               score = 0

       if event.type == SPAWNPIPE:
           pipe_list.extend(create_pipe())

       if event.type == BIRDFLAP:
           if bird_index < 2:
               bird_index += 1
           else:
               bird_index = 0

           bird_surface,bird_rect = bird_animation()

   screen.blit(bg_surface,(0,0))

   if game_active:
       # Bird
       bird_movement += gravity
       rotated_bird = rotate_bird(bird_surface)
       bird_rect.centery += bird_movement
       screen.blit(rotated_bird,bird_rect)
       game_active = check_collision(pipe_list)

       # Pipes
       pipe_list = move_pipes(pipe_list)
       draw_pipes(pipe_list)

       # Score
       pipe_score_check()
       score_display('main_game')
   else:
       screen.blit(game_over_surface,game_over_rect)
       high_score = update_score(score,high_score)
       score_display('game_over')
       sql()

   # Floor
   floor_x_pos -= 1
   draw_floor()
   if floor_x_pos <= -576:
       floor_x_pos = 0

   pygame.display.update()
   clock.tick(120)

please tell how to solve this. Thank you!

A: As commenters have pointed out, calling input() will block your program from processing events, so the operating system will think your program has frozen.
To achieve your goals with minimal redesign, you can incorporate the built-in tkinter dialogs to obtain a user name instead of using input(). The application will still block, but your operating system won't think it is non-responsive.
import tkinter
import tkinter.simpledialog

def prompt_username():
    """Create a Tk file dialog and cleanup when finished"""
    top = tkinter.Tk()
    top.withdraw()  # hide window
    user_name = tkinter.simpledialog.askstring(
        "Name?", "What is your name?", parent=top
    )
    top.destroy()
    return user_name

In your sql() function, replace n=input('enter your name') with n = prompt_username(). Although you could do yourself a favour and use variable names with more than one character.
You'll see a dialog like this:

Check the documentation for more information.


text:
Q: Printooth character code don't work, need cyrillic Displays characters when sending Cyrillic for printing.
I checked all available encodings in the library by printing the text "Тест" and got no result.

The printer supports the Cyrillic alphabet, I checked it on the application from the market:

Here is the part of the code where I set the print data:
public void testPrint(View view){
     ArrayList<Printable> printables = getTestPrint("Тест");
     PairedPrinter printer = new PairedPrinter(name, mac);
     Printooth.INSTANCE.printer(printer).print(printables);
}

 public static ArrayList<Printable> getTestPrint(String text){

    ArrayList<Printable> printables = new ArrayList<>();

    Byte lineSpacing = (byte) Settings.lineSpacing(context);
    int spaceAfter = Settings.spaceAfter(context);

    printables.add(gerRawPrintable());

    Map<String, Byte> bytes = Printer.getCharacterCode();

    for(var entry: bytes.entrySet()){
        printables.add(new TextPrintable.Builder()
                .setText(entry.getKey() + " - " + text)
                .setCharacterCode((byte) entry.getValue())
                .setCustomConverter(new DefaultConverter())
                .setAlignment(DefaultPrinter.Companion.getALIGNMENT_LEFT())
                .setNewLinesAfter(spaceAfter)
                .setLineSpacing(lineSpacing)
                .build()
        );
    }

    return printables;

}

 public static RawPrintable gerRawPrintable(){
      return new RawPrintable.Builder(new byte[]{27, 100, 4}).build();
 }

  public static Printable getPrintElement(String text, Byte lineSpacing, byte characterCode){

      return new TextPrintable.Builder()
         .setText(text)
         .setAlignment(DefaultPrinter.Companion.getALIGNMENT_LEFT())
         .setNewLinesAfter(Settings.spaceAfter(MainActivity.context))
         .setLineSpacing(lineSpacing)
         .setCharacterCode(characterCode)
         .build();
  }

 public static Map<String, Byte> getCharacterCode(){
    Map<String, Byte> bytes = new HashMap<>();

    bytes.put("ARABIC CP720", DefaultPrinter.Companion.getCHARCODE_ARABIC_CP720());
    ...
    bytes.put("WEU", DefaultPrinter.Companion.getCHARCODE_WEU());

    return bytes;

}

A: I solved the problem by sending the text to print using the RavPrint class:
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    printables.add(new RawPrintable.Builder(bytes).setNewLinesAfter(1).build());


text:
Q: Python script to add new vaule at the end of each row in the csv output file based on the checking conditon I want to write a python script to add new value at the end of a row in CSV file that produced by the initial part of the script.
The CSV file has values like below
name,isactive,ful_name,emailaddress
rajesh,active,Rajesh Pidikiti,myemail@corp.####.com
james,active,James wood,mail@mail.com

I need to consider the name of each row and check the user has admin privileges (by running one curl command) or not. If the user is admin then add admin as new value at end of the row (new column). If not then add user as the new value.
The output will be like this
name,isactive,ful_name,emailaddress,isadmin
rajesh,active,Rajesh Pidikiti,myemail@corp.####.com,admin
james,active,James wood,mail@mail.com,user

I have tried by creating function and for a loop but not successful. I'm okay to either Appending the results to input or creating a new output file.
This what I have written so far.
def to_add_new_col(input_file,output_file)
        with open(input_file, 'rb') as infile:
                with open(output_file, 'wb') as outfile:
                        reader = csv.reader(infile, lineterminator='\n')
                        writer = csv.writer(outfile, lineterminator='\n')

                        check_and_add(reader, writer)

def check_and_add(reader, writer)
        for i in reader:
                for field in (i)
                        if(curl_result(field):
                                i=admin
                        else
                                i=user

                writer.writerow(i)

A: You can use the default settings for both the CSV reader and writer. First you need to read in the header row, add the new column heading and then write it to your output CSV file. Then for each row in your input CSV file, pass the is_admin() function a user to test which returns either admin or user (I have created a dummy function which just tests if the user name has an even or odd number of characters). This returned value can then be added to the list of values in the row and written to the output.
If you are not sure how this is working, add a print statement to help. For example add print(row):
import csv

def is_admin(user):
    """ Test if user is admin (replace with your curl test) """
    return 'admin' if len(user) % 2 == 0 else 'user'

with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_reader = csv.reader(f_input)
    csv_writer = csv.writer(f_output)
    csv_writer.writerow(next(csv_reader) + ['isadmin'])

    for row in csv_reader:
        csv_writer.writerow(row + [is_admin(row[0])])

This would give you an output.csv file containing:
name,isactive,ful_name,emailaddress,isadmin
rajesh,active,Rajesh Pidikiti,myemail@corp.####.com,admin
james,active,James wood,mail@mail.com,user


text:
Q: Arquillian + ear + wildfly in remote container = NoSuchMethodError I have an ear created with ShrinkWrap. I'm trying to run AQ tests on remote (dockered) wildfly 12 container. WF is deployed properly, necessary ports are opened and available. While trying to run tests I get:
16:05:42,922 TRACE [listener] Invoking listener org.jboss.remoting3.remote.RemoteConnection$RemoteWriteListener@56babcc2 on channel org.xnio.conduits.ConduitStreamSinkChannel@34dcf94b
16:05:42,924 ERROR [listener] XNIO001007: A channel event listener threw an exception
java.lang.NoSuchMethodError: org.jboss.remoting3._private.Messages.tracef(Ljava/lang/String;J)V
at org.jboss.remoting3.remote.RemoteConnection$RemoteWriteListener.handleEvent(RemoteConnection.java:275)
at org.jboss.remoting3.remote.RemoteConnection$RemoteWriteListener.handleEvent(RemoteConnection.java:243)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.conduits.WriteReadyHandler$ChannelListenerHandler.writeReady(WriteReadyHandler.java:65)
at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:94)
at org.xnio.nio.WorkerThread.run(WorkerThread.java:571)

and have no clue how to deal with it.
I'm using:
<dependency>
     <groupId>org.wildfly.arquillian</groupId>
     <artifactId>wildfly-arquillian-container-remote</artifactId>
     <version>2.1.0.Final</version>
     <scope>test</scope>
</dependency>
...
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.jboss.arquillian</groupId>
            <artifactId>arquillian-bom</artifactId>
            <version>1.4.1.Final</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

Any clues?


text:
Q: TypeError: 'NoneType' object is not callable but object is not nonetype def winner(board):
    WAYS_TOWIN = ((0, 1, 2),
                  (3, 4, 5),
                  (6, 7, 8),
                  (0, 4, 8),
                  (2, 4, 6),
                  (0, 3, 6),
                  (1, 4, 7),
                  (2, 5, 8))
    for row in WAYS_TOWIN:
        if board[row[0]] == board[row[1]] == board[row[2]] != " ":
            winner = board[row[0]]
            return winner
    if " " not in board:
            return TIE
    else:
        return None

#Main
instructions()
human = input("Enter your name: "); print("\n")
pieces = who_first(human, computer); print("\n")#pieces becomes a list with human piece first and computer piece second
board = new_board(); print("\n")
winner = winner(board)

while winner == None and winner != TIE:
    if turn == pieces[0]:#if human is first
        winner = winner(board)

When I run the winner function the first time, it returns none to the winner variable and there are no errors. But when I run it for the second time it gives me TypeError: 'NoneType' object is not callable. The board is a list with [" "]*9 and i dont get why calling the board the second time is a nonetype  object.

A: The first time you run winner = winner(board) winner becomes None therefore on the second call it's not calling the function but None hence the Error. Changing the names will solve the problem, it's not recommended to use same variable name and function name.


text:
Q: Comparison error for quantiles for survival (survfit object) I am trying to follow a textbook example of survival analysis and am not sure where I'm going wrong here:
df1 <- as.data.frame( cbind(seq(1:5),c(6,44,21,14,62),c(1,1,0,1,1)) )
names(df1) <- c('subject','time','censor')
require(survival)
f1 <- survfit(Surv(time=time, event=censor) ~1, data=df1)
quantile(f1)

Which gives the following:
Error in xi == xj : comparison of these types is not implemented
In addition: Warning messages:
1: In `[.survfit`(x, !nas) :Survfit object has only a single survival curve
2: In `[.survfit`(x, i) : Survfit object has only a single survival curve
3: In `[.survfit`(x, j) : Survfit object has only a single survival curve

I have tried this with survfit objects with more than one curve and still get the same message...
"R version 2.14.1 (2011-12-22)"
"x86_64-pc-linux-gnu"
Output from search():
[1] ".GlobalEnv"        "package:km.ci"     "package:survival"
[4] "package:splines"   "package:stats"     "package:graphics"
[7] "package:grDevices" "package:utils"     "package:datasets"
[10] "package:methods"   "Autoloads"         "package:base"

Many thanks!
EDIT: thanks DWin and sorry I missed that in help(Surv).
However I'm still getting the same error message.
I'm reading the help for:
quantile.survfit {survival} which is documented as an S3 generic, so I was expecting that using quantile(f1) should invoke this method.
However I'm finding that the following doesn't work:
survival:::quantile.survfit(f1)

Gives:
Error: 'quantile.survfit' is not an exported object from 'namespace:survival'

Tried re-installing survival and it's still the most current version: survival_2.36-10

A: Two concerns I have. In the help page for Surv I see this sentence: "The time,time2 and event arguments are matched by position, not by name, so use, eg, Surv(time, dead) rather than Surv(time, event=dead)". Which solves the first problem I had with your code by dropping the event argument in the call:
f1 <- survfit(Surv(time=time, censor) ~1, data=df1)

But then I was expecting to find that was a fit object, i.e. a list,  and I was not surprised that quantile objected:
> quantile(f1)
Error in approx(c(0, 1 - newy), c(0:length(newy)), p) :
  need at least two non-NA values to interpolate

So did you want:
> quantile(f1$time)
  0%  25%  50%  75% 100%
   6   14   21   44   62     # ???

Edit: Apparently sometime in the intervening 10 years there is now a quantile method for survfit objects and you now get.
> quantile(f1)
$quantile
25 50 75
14 44 62

$lower
25 50 75
 6 14 44

$upper
25 50 75
NA NA NA


text:
Q: Tabs displayed incorrectly when populated from array I'm trying to create some tabs like in this tutorial. I can display hard coded tabs no problem but when I try to populate the tabs from a list, they are displayed incorrectly.
Code and image below.
tabsv2.html
<template>

${name}

${name}

${name} is a capital city.

London

Paris

Tokyo

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

</template>

tabsv2.js
export class tabsv2 {

    collection = ["London", "Dublin", "Paris"];

    openTab(evt, cityName) {
        // Declare all variables
        var i, tabcontent, tablinks;

        // Get all elements with class="tabcontent" and hide them
        tabcontent = document.getElementsByClassName("tabcontent");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }

        // Get all elements with class="tablinks" and remove the class "active"
        tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }

        console.log("Display place:");
        console.log(cityName);

        // Show the current tab, and add an "active" class to the link that opened the tab
        document.getElementById(cityName).style.display = "block";
        evt.currentTarget.className += " active";
    }
}

The first set of tabs, populated from an array, are displayed vertically and are unclickable. The hard coded ones are displayed correctly.
Does anybody know what might be causing this?
Update
As Fabio suggested, I moved the repeat.for so it looks like this:

${name}

${name}

${name} is a capital city.

The tabs are correctly displayed horizontally but still do not expand when clicked:

A: Had a mistake in my code:
${name}

Should have been:
${name}


text:
Q: How to get text in BeautifulSoup? I'm trying to get the string  "Carlos Pellegrini 551, C1009ABK Buenos Aires, Argentina" using BS but I'm having problems. (It's just before the  at the end)
<span class="
hp_address_subtitle
js-hp_address_subtitle
jq_tooltip
" rel="14" data-source="top_link" data-coords="," data-component="tooltip" data-tooltip-text="

Ubicación excelente, ¡puntuada con 9,3/10! (puntaje basado en Más recomendado comentarios)

Valorado por las personas después de hospedarse en el Hotel Panamericano Buenos Aires.

" data-tooltip-animation="false" tabindex="0" data-bbox="-58.4028009366937,-34.6199039159457,-58.3590682554297,-34.5839730827995" data-node_tt_id="location_score_tooltip" data-width="350" title="" aria-describedby="tooltip-1">
Carlos Pellegrini 551, C1009ABK Buenos Aires, Argentina

I tried the following:
soup.find(attrs={'class':"hotel_address_subtitle"}).get_text()

But I get None ad a result.
Please help me!

A: You can do this to only find text on the website:
soup.find_all(text=True)

instead of:
soup.find(attrs={'class':"hotel_address_subtitle"}).get_text()
try:
for element in soup.find_all(text=True):
    print(element)

edit after I saw your comment, try this:
from bs4 import BeautifulSoup
import requests

page = requests.get("https://www.booking.com/hotel/ar/panamericano-buenos-aires.es-ar.html")
soup = BeautifulSoup(page.content, 'html.parser')
output = soup.find("span", {"class": "hp_address_subtitle"})
print(output.text)

outputs
Carlos Pellegrini 551, C1009ABK Buenos Aires, Argentina

A: You can use "select_one". you can try it:
from bs4 import BeautifulSoup
html_doc='''<span class="
hp_address_subtitle
js-hp_address_subtitle
jq_tooltip
" rel="14" data-source="top_link" data-coords="," data-component="tooltip" data-tooltip-text="

Ubicación excelente, ¡puntuada con 9,3/10! (puntaje basado en Más recomendado comentarios)

Valorado por las personas después de hospedarse en el Hotel Panamericano Buenos Aires.

" data-tooltip-animation="false" tabindex="0" data-bbox="-58.4028009366937,-34.6199039159457,-58.3590682554297,-34.5839730827995" data-node_tt_id="location_score_tooltip" data-width="350" title="" aria-describedby="tooltip-1">
Carlos Pellegrini 551, C1009ABK Buenos Aires, Argentina
'''

soup = BeautifulSoup(html_doc, 'lxml')
result = soup.select_one("span").text

print(result)

Output will be:
Carlos Pellegrini 551, C1009ABK Buenos Aires, Argentina


text:
Q: VSTS Nuget Restore "System.InvalidOperationException: Ambiguous project name" Built a xamarin forms cross-platform plugin using bait + switch using the method found here: https://blog.xamarin.com/creating-reusable-plugins-for-xamarin-forms/.
In the process of moving builds to VSTS and can't seem to run the NuGet restore task (stacktrace is attached).
Project structure looks something like this:
AppUtils.Forms -> Wrappers and common code
AppUtils.Forms.Android -> Android implementation
AppUtils.Forms.iOS -> iOS implementation
AppUtils.Forms.NuGet -> NuGet packaging project (using VS17 for Mac)

I can build the NuGet package locally but on VSTS I can't even get as far as restoring the packages. Any ideas?
System.AggregateException: One or more errors occurred. ---> System.InvalidOperationException: Ambiguous project name 'AppUtils.Forms'.
   at NuGet.Commands.RestoreCommand.GetProjectReferences(RemoteWalkContext context)
   at NuGet.Commands.RestoreCommand.<ExecuteRestoreAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreCommand.<ExecuteAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<ExecuteAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<ExecuteAndCommitAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<CompleteTaskAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<RunAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<Run>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.CommandLine.RestoreCommand.<ExecuteCommandAsync>d__30.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at NuGet.CommandLine.Command.Execute()
   at NuGet.CommandLine.Program.MainCore(String workingDirectory, String[] args)
---> (Inner Exception #0) System.InvalidOperationException: Ambiguous project name 'Biotaware.AppUtils.Forms'.
   at NuGet.Commands.RestoreCommand.GetProjectReferences(RemoteWalkContext context)
   at NuGet.Commands.RestoreCommand.<ExecuteRestoreAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreCommand.<ExecuteAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<ExecuteAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<ExecuteAndCommitAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<CompleteTaskAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<RunAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.RestoreRunner.<Run>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.CommandLine.RestoreCommand.<ExecuteCommandAsync>d__30.MoveNext()<---


text:
Q: Playwright fails to fill input I'm running a Playwright script on a Jenkins page that has input elements. When I try to fill one of the inputs with text, it fails with this error:
(node:3337) UnhandledPromiseRejectionWarning: page.fill: Protocol error (Page.insertText): error in channel "content::page": exception while running method "insertText" in namespace "page": Component returned failure code: 0xc1f30001 (NS_ERROR_NOT_INITIALIZED) [nsITextInputProcessor.commitCompositionWith] _insertText@chrome://juggler/content/content/PageAgent.js:891:32

I've tried running with DEBUG=pw:api environment enabled but the logs there aren't too helpful. From the normal console log I get the following log:
waiting for selector "input[name="_.buildNumber"]"
  selector resolved to visible <input value="" type="text" name="_.buildNumber" class=…/>
elementHandle.fill("54")
  waiting for element to be visible, enabled and editable
  element is visible, enabled and editable

So it seems like the element exists and can be edited but for some reason Playwright is unsuccessful at trying to fill it. What am I missing here?

A: This is a Playwright bug that is specific to Firefox. To get around it for now, you should be able to switch to using either Chrome or Safari in your import statement. So either:
import { chromium } from 'playwright';

Or using Safari:
import { webkit } from 'playwright';


text:
Q: Custom Case Form Not Working With Controller I am looking to create a web form that will create cases with the information filled out on it. Right now I am just trying to get the basic nuts and bolts working. I have built a form, used the standard case controller, and created an extension.
To start, here is the form. It is very basic and comes together just fine:
 <apex:page sidebar="false" showHeader="false"standardController="Case" extensions="PartnerSupportCaseController">
  <apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection title = "Partner Support Form">
          <apex:inputField value="{!Case.Supplied_Email__c}"/>
       </apex:pageBlockSection>
        <apex:pageBlockSection >
           <apex:inputText required="true" value="{!Case.Subject}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection >
            <apex:inputTextArea required="true" rows="5" value="{!Case.Description}"/>
        </apex:pageBlockSection>

        <apex:commandButton action = "{!Save}" value = "Save" />
    </apex:pageBlock>
 </apex:form>
</apex:page>

The problem, I believe, lies in the extension:
public class PartnerSupportCaseController {

    public Case supportCase {get;set;}

    public PartnerSupportCaseController(ApexPages.StandardController controller)
    {
        supportCase = New Case();
    }

    public pagereference Save()
    {
        insert supportCase;
        PageReference pg = Page.<PartnerSupportThankYou>;
        pg.setredirect(true);
        return pg;
    }

}

I have made reference to a very basic thank you page that I threw together, as I want the user redirected to that page after they fill out the form. (I can worry about querying and returning the case number for them to view and save for future reference later on). What is happening is that I am getting an error on the visualforce page stating:
Unknown constructor 'PartnerSupportCaseController.PartnerSupportCaseController(ApexPages.StandardController controller)'
Also, an error is stating: Unexpected token ';' in line 13 (the line that contains PageReference pg = Page.;).
As I mentioned, I am really just trying to plug some of the nuts and bolts together here, so the styling and other functionality is lacking. I was hoping that someone had some insight as to what I am doing wrong in plugging these two components together.
THanks, thanks.
-CP

A: The error 'Unexpected Token' is because
PageReference pg = Page.<PartnerSupportThankYou>;

is invalid syntax - remove the < and >.
and because that failed, the class failed to compile so the VF page will get an error unknown constructor
That said, it looks like you are going to have a binding issue between the VF page and the standardController Extension class. Your VF page is trying to bind
<apex:inputField value="{!Case.Supplied_Email__c}"/>

to the standard object Case yet your Controller is manipulating/saving a different variable, not bound to the VF page supportCase.
A typical pattern to resolve this would be to change the Constructor to
public PartnerSupportCaseController(ApexPages.StandardController stdController) {
  this.supportCase = (Case)stdController.getRecord();
}

as the getRecord() handles the binding between the VF page {!Case.xxx} and your controller variable. For more reading - see Building a Controller Extension


text:
Q: How to add a variable as custom launch option? An error occurred when I used a system variable I set like this:
"C:\Program Files (x86)\Exampleapp\examplefoleder\Example.exe"%variable%

A: The error you are getting is most probably something like:

This is because if variable contains, for example, the value of file.txt
the command after substitution will look like:
notepad.exefile.txt

Windows will not be able to find a file named notepad.exefile.txt.
To fix this, leave a blank between the executable and its argument.


text:
Q: Web application, Update members status to other member i want to make something like a friend status if he is online or offline.
c# code behind, javascript , html5
There is a similar question but it uses .php and i dont know anything about php.
Anyway I was thinking that for the online, you can track when the user has actually logged on.(turn a field in the DB for online to true)
But how do you send that info to the person who needs to know if the other user logged in? can the codebehind or the js have like a receiving function/method that is called when he gets online?(like an observer pattern?)
also then when it updates we dont want a whole page refresh but the least possible @flickering for the page. post-back?
Finally to track if the user is offline it could be like a http response to check for a responce from the online user if he is still online. But how? :P
If we finally get that its offline can we use the same receiving function/method that we informed the other person that he was online?
Any help would be much appriciated. Hope this could become a reference for similar threads.

A:
But how do you send that info to the person who needs to know if the other user logged in?

You can't send the information to the user. He must get the information himself. What I mean is that http is a "pull protocol", which means that you can't push information to the client, you just give him what he requests.
Now, what you want is the client to request the information without noticing the fact that his browser is sending requests. The best way to do this is to use Ajax in javascript to send a request to a web service. This way, you can get information from your server without doing any postbacks. Then, to give an impression of live information, you'll want to set your ajax call in a setTimeout to get the information any given time interval (30 seconds, 1 minute, your choice).
To simplify - a lot - your ajax calls, have a look at Jquery Ajax.
If you don't know any of this, don't give up, it may look more complicated than it actually is.

Finally to track if the user is offline

What I suggest is that you keep track of every request from that user, and after a certain time without any request, you declare this user as logged out.
Hope this helps!


text:
Q: C# Reading parts of a string into a list I have the following JSON string:
[
    {
        "Id": 1,
        "UserName": "Test1",
        "UserPassword": "Test1",
        "FirstName": "TF1",
        "LastName": "TL1",
        "Mobile": "Test1",
        "Email": "TE1",
        "CreatedDate": "2022-05-29T00:00:00.000Z"
    },
    {
        "Id": 4,
        "UserName": "Test4",
        "UserPassword": "Test4",
        "FirstName": "T4F",
        "LastName": "TL4",
        "Mobile": "Test4",
        "Email": "TE4",
        "CreatedDate": "2022-05-29T00:00:00.000Z"
    },
    {
        "Id": 3,
        "UserName": "Test3",
        "UserPassword": "Test3",
        "FirstName": "TF3",
        "LastName": "TL3",
        "Mobile": "Test3",
        "Email": "TE3",
        "CreatedDate": "2022-05-29T00:00:00.000Z"
    },
    {
        "Id": 7,
        "UserName": "Test7",
        "UserPassword": "Test7",
        "FirstName": "T7F",
        "LastName": "TL7",
        "Mobile": "Test7",
        "Email": "TE7",
        "CreatedDate": "2022-05-29T00:00:00.000Z"
    },
    {
        "Id": 7,
        "UserName": "Test7",
        "UserPassword": "Test7",
        "FirstName": "T7F",
        "LastName": "TL7",
        "Mobile": "Test7",
        "Email": "TE7",
        "CreatedDate": "2022-05-29T00:00:00.000Z"
    },
    {
        "Id": null,
        "UserName": "PT",
        "UserPassword": "PT",
        "FirstName": null,
        "LastName": null,
        "Mobile": null,
        "Email": null,
        "CreatedDate": null
    },
    {
        "Id": null,
        "UserName": "CTest",
        "UserPassword": "CTest",
        "FirstName": null,
        "LastName": null,
        "Mobile": null,
        "Email": null,
        "CreatedDate": null
    },
    {
        "Id": 5,
        "UserName": "Test5",
        "UserPassword": "Test5",
        "FirstName": "TF5",
        "LastName": "TL5",
        "Mobile": "Test5",
        "Email": "TE5",
        "CreatedDate": "2022-05-29T00:00:00.000Z"
    }
]

And would like to read the all the values of the UserName & UserPassword fields of the string into the following lists:
var UserName = new List<string>();
var UserPassword = new List<string>();

A: Create a class containing at least those two properties (it could have the others also):
class User
{
    public string UserName;
    public string UserPassword;
}

Parse the JSON using a suitable parser, such as Json.NET
var list = JsonConvert.DeserializeObject<List<User>>(yourJson);

Use Linq to pull out the data you want
var UserName = list.Select(u => u.UserName).ToList();
var UserPassword = list.Select(u => u.UserPassword ).ToList();

dotnetfiddle

A: From your JSON string
string JSON_String = ...;

You can also extract the data you want with the help of Regex and LINQ. Here is an example
var UserName = Regex
    .Matches(JSON_String, "\"UserName\":\\s*\"\\w+\"")
    .Cast<Match>()
    .Select(m => m.Value)
    .Select(s => Regex.Match(s, "\"\\w+\"", RegexOptions.RightToLeft).Value)
    .Select(s => s.Substring(1, s.Length - 2))
    .ToList();

var UserPassword = Regex
    .Matches(JSON_String, "\"UserPassword\":\\s*\"\\w+\"")
    .Cast<Match>()
    .Select(m => m.Value)
    .Select(s => Regex.Match(s, "\"\\w+\"", RegexOptions.RightToLeft).Value)
    .Select(s => s.Substring(1, s.Length - 2))
    .ToList();


text:
Q: testing nonlinear hypothesis glm R I estimate probit model:
\begin{align*}
P(y=1|x_1, x_2, x_3) = \Phi(\alpha_0 + \alpha_1 x_1 + \alpha_2 x_2+ \alpha_3 x_3)
\end{align*}
using: probitMain <- glm(y~x1+x2+x3, family=binomial(link="probit"), data=MD).
I want to test nonlinear hypothesis $f(\alpha_0, \alpha_1, \alpha_2, \alpha_3) = 0$,
where $f$ is a rational function $f(\alpha_0,\alpha_1, \alpha_2, \alpha_3) = \frac{\alpha_2 + \alpha_0 \frac{\alpha_3}{\alpha_1}}{1+\frac{\alpha_3}{\alpha_1}}$.
I have tried to use nlWaldTest package for nonlinear Wald test,  but it doesn't seem to work with glm objects.
Is there any other R package that can test nonlinear hypothesis for glm?

A: I solve the problem like this.  Write the probit equation as:
\begin{align}
P(y=1|x_1, x_2, x_3)=\Phi \left(\gamma_1 + \gamma_2 x_1 + (\gamma_3 + \gamma_3 \gamma_4 -\gamma_1)x_2 + \gamma_2 \gamma_4 x_3 \right)
\end{align}
I estimate this equation using ML with respect to $\gamma's$ (with function mle2 from bbmle package). Note that $\gamma_2$ is exactly the parameter I was originally interested in. From Hessian of the ML estimation I can retrieve standard errors.