Show/ Hide components on the selection of checkbox of a Tree

Question: The onSelect event is present for the  component only and I want to show/hide my comboboxes for selected checkboxes only.
Here is my zul file for reference
![<?page title="MVVM Tree POC"?>
<zk>
    <borderlayout height="800px">
        <west size="25%"></west>

            <window apply="org.zkoss.bind.BindComposer"
                viewModel="@id('vm') @init('com.nagarro.viewmodel.TreeViewModel')"
                title="Dynamic Tree" border="normal">
                <tree checkmark="true" model="@bind(vm.treeModel)"
                    onSelect="@command('select')">
                    <treecols>
                        <treecol label="Name" align="center" />
                        <treecol label="Value" align="center" />
                        <treecol label="IP" align="center" />
                    </treecols>
                    <template name="model" var="node" status="s">
                        <treeitem checkable="@load(node.checkable)">
                            <treerow style="text-align:center;">
                                <treecell
                                    label="@bind(node.data.firstName)" style="text-align:left;">

                                </treecell>
                                <treecell style="text-align:center;">
                                    <combobox>
                                        <comboitem label="Fixed" />
                                        <comboitem label="System" />
                                        <comboitem label="Parameter" />
                                    </combobox>
                                </treecell>
                                <treecell style="text-align:center;">
                                    <combobox>
                                        <comboitem label="IP" />
                                    </combobox>
                                </treecell>
                            </treerow>

                        </treeitem>
                    </template>
                </tree>

            </window>

    </borderlayout>
</zk>]

snapshot of the issue
In the image I want to show the combo boxes only for the components which have checked checkboxes. There should not be any combobox shown for component without checkbox or unchecked checkbox. Thanks
Here is the mvvm file
public class TreeViewModel {

    private Request request;
    private AdvancedTreeModel treeModel;

    /**
     * @return the treeModel
     */
    public AdvancedTreeModel getTreeModel() {
        if(treeModel == null){
            TreeNode<Tree> treeNode = new TreeList(request).getRoot();
            treeModel = new AdvancedTreeModel(treeNode);
            treeModel.setMultiple(true);
        }
        return treeModel;
    }

    /**
     * @param treeModel the TreeModel to set
     */
    public void setTreeModel(AdvancedTreeModel treeModel) {
        this.treeModel = treeModel;
    }
    @Init
    public void init(){
        try {
            File file = new File("C:\\Users\\jatin1937\\Desktop\\XML files\\Request.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Request.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            request = (Request) jaxbUnmarshaller.unmarshal(file);
        }catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return the request
     */
    public Request getRequest() {
        return request;
    }

    /**
     * @param request the request to set
     */
    public void setRequest(Request request) {
        this.request = request;
    }
    @Command
    public void select(){
        System.out.println("onSelect method entered");
    }
}

Tree data is prepared through some helper classes but thats not important to describe here.
Answer: I also tried it and found a way out. Now, instead of using onSelect event on tree component I am using onClick event on treeRow component.  I kept a field isChecked with my class which is referred by node.data in the zul file. According to the value of that boolean isChecked I show/hide the combobox.
Below is the zul file for reference
<?page title="MVVM Tree POC"?>
<zk>
    <borderlayout height="800px">
        <west size="25%"></west>

            <window apply="org.zkoss.bind.BindComposer"
                viewModel="@id('vm') @init('com.nagarro.viewmodel.TreeViewModel')"
                title="Dynamic Tree" border="normal">
                <tree checkmark="true" model="@bind(vm.treeModel)">
                    <template name="model" var="node" status="s">
                        <treeitem
                            checkable="@load(node.data.isCheckable)" open="true">
                            <treerow style="text-align:center;"
                                onClick="@command('select', treeNode = node.data)">
                                <treecell
                                    label="@bind(node.data.firstName)" style="text-align:left;">
                                </treecell>
                                <treecell style="text-align:center;"
                                    if="${node.data.isChecked == true}">
                                    <combobox>
                                        <comboitem label="Fixed" />
                                        <comboitem label="System" />
                                        <comboitem label="Parameter" />
                                    </combobox>
                                </treecell>
                                <treecell style="text-align:center;"
                                    if="${node.data.isChecked == true}">
                                    <combobox>
                                        <comboitem label="Fixed" />
                                        <comboitem label="System" />
                                        <comboitem label="Parameter" />
                                    </combobox>
                                </treecell>
                            </treerow>
                        </treeitem>
                    </template>
                </tree>

            </window>

    </borderlayout>
</zk>

Here is the select method in ViewModel for reference
@NotifyChange("treeModel")
@Command
public void select(@BindingParam("treeNode") final Tree tree){
    if(tree.getIsCheckable()){
        if(tree.getIsChecked() == true){
            tree.setIsChecked(false);
        }else{
            tree.setIsChecked(true);
        }
    }

}

Please note that Tree is a custom class through which I prepare tree
  data.  isCheckable is also a boolean field in the Tree class. If
  true then checkbox will appear in a treeRow else not.
  isChecked is another Boolean field in Tree class. If true then
  corresponding checkbox is checked else not
Answer: Just do it like this
<tree onSelect="@command('select', tree=self)" >

and in your vm
Set<Treeitem> oldSelection;
...

@Command
public void select(@BindingParam("tree")Tree tree){
   // delete
   Set<Treeitem> unselected = oldSelected.removeAll(tree.getSelectedItems());
   for(Treeitem x : unselected){
       x.getTreerow().getLastChild().setParent(null);
   }
   // add
   tree.getSelectedItem().getTreerow().appendChild(getCombobox());
   oldSelection = tree.getSelectedItems()
}


Bing Custom Search Engine

Question: What parameters should I use in order to get search result from only a site say abcd.com using bing 2.0 API? I am trying to fetch results in JSON format. Can anybody help?
Answer: fresh code to the masses
<code>            $query = array
        (
            'AppId' => <API_KEY>,
            'sources' => 'Web',
            'query' => 'site:www.tipografix.ro '.$keywords,
            'Version' => '2.0',
            'Options' => 'EnableHighlighting',
            'Web.Count' => $per_page,
            'Web.Offset' => $page_num,
            'Web.Options' => 'DisableHostCollapsing DisableQueryAlterations'
        );

        $request = 'http://api.bing.net/json.aspx?'.http_build_query($query);

        $response  = file_get_contents($request);
        $jsonobj  = json_decode($response);
</code>
Answer: Not sure how the JSON format of the API works but in the query parameter put in "site:abcd.com bacon" where bacon is your original query.
I'm using the XML format so if I'd send a request to:
<code>http://api.search.live.net/xml.aspx?Appid=________&query=site%3Aabcd.com+bacon&sources=web&web.count=5&web.offset=0
</code>

Bing Custom Search Engine


É possível remover o rolamento de um TWebBrowser?

Question: É possível remover o rolamento vertical e horizontal de um TWebBrowser?
Pesquisei em vários locais da internet, porém, não encontrei uma resposta válida, todos os exemplos eram falsos!
Comment: Posta seu código para o pessoal vê se pode ajudar?
Answer: Desabilitar é meio complicado, não tem uma propriedade para isso no componente!
Porem, posso te ajudar Ocultando as barras...
Adicione essas 2 linhas de código no OnDocumentComplete do TWebBrowser:
WebBrowser1.OleObject.Document.Body.Style.OverflowX := 'hidden';
WebBrowser1.OleObject.Document.Body.Style.OverflowY := 'hidden';

Com isto, após carregamento da Página as barras são ocultadas!


Does having an orthonormal basis imply that the vectors in that basis must all be orthongonal?

Question: I am computing singular value decomposition at the moment and the book gave us the left singular matrix to be
$$U = \begin{pmatrix}
\frac{-1}{3} &  \frac{2}{3}&\frac{2}{3} \\
\frac{2}{3} & \frac{-1}{3} &\frac{2}{3} \\
\frac{2}{3}& \frac{2}{3} & \frac{-1}{3}
\end{pmatrix}$$ for the matrix
$$A = \begin{pmatrix}
-3 &1 \\
 6&-2 \\
 6&-2
\end{pmatrix}$$
Noticed that the second column and the third column of $U$ are not orthogonal, yet the matrix still works!
Comment: Um, they look orthogonal to me...
Comment: $(2/3)(2/3)+(-1/3)(2/3)+(2/3)(-1/3)=(4/9)+(-2/3)+(-2/3)=(4/9)+(-4/9)=0$
Comment: No they aren't, (2/3)(2/3) + (-1/3)(2/3) + (2/3)(-1/3) = (2/3)(2/3) = 4/9
Answer: To answer the title of your question, yes.  If you have an orthonormal basis, then not only must each vector in the basis be orthogonal, they must also be of unit length[1].  However, as David Mitra has pointed out, the rows of $U$ that you provided are in fact orthogonal.
Comment: "each vector in the basis be orthogonal"--You mean, each vector much be orthogonal to all of the other vectors.


SSHd does not allow publickey authentication due to libcrypto bug

Question: I can not login to my server with public key.
Server details:

Ubuntu Server 16.04LTS
SSHd: OpenSSH_7.2p2 Ubuntu-4ubuntu2.4, OpenSSL 1.0.2g  1 Mar 2016

My public key is added to /home/user/.ssh/authorized_keys, but publickey authentication method is dropped when I try to connect.
Only one line in the /var/log/auth.log is corresponded:
<code>sshd[3830]: error: key_verify: error in libcrypto
</code>
Ubuntu on the server is fresh, just upgraded to the latest kernel and packages.
Anybody has any idea how can I overcome on this situation?
Comment: It's pretty unlikely that this is the result of a bug. Please add the actual configuration of your server to your question. The rest of the log file related to your login attempt might be relevant as well.
Comment: I have the same issue, did you find a solution?
Comment: You will need to recreate the keys and then it will be fine.
Comment: You may want to increase the [LogLevel](https://linux.die.net/man/5/sshd_config) to one of the debug levels in your `sshd_config` to get more detailed/useful information that will help you debug the issue. (It might be as simple as for instance missing/extra character(s) in the authorized_keys entry)
Answer: Actually, increasing the log level does not showed up anything related.
It only seems the client just jumped over the next possible key (DSA) which I have not got and then the method was dropped and password has been asked.
My client is a 14.04LTS, server is 16.04LTS.
The key was generated long time ago (by the time I was installed 14.04LTS).
The solution was to regenerate the RSA keys on the client and now it works as intended. Somehow the 16.04LTS is not backward compatible with the keys generated long time ago.
Comment: How long ago? Keys generated between 2006-2008 on Debian-based systems were [weak due to a bug](https://github.com/g0tmi1k/debian-ssh), and get rejected today.


Adding a file download link to a node

Question: I have a content type recipe and for each recipe type content I want to add a link which can download the recipe for the user.
How can this be done in Drupal 8.5.2?
I'm not sure if I should provide a field to attach the file or if it should be done in some other way like creating a template adding the values to it dynamically and then generating a PDF for the template and attaching a download link for it.
Comment: Maybe you can elaborate more how you have set it up right now? Do you have a field for the upload attached to the node?
Comment: this is what im actually not sure about if i should provide a field to attach the file or if it should be done in some other way like creating a template adding the values to it dynamically and then generating a pdf for the template and attaching a download link for it.
Answer: It sounds that you should be able to implement what you want like so:

Add a custom field to your recipe, assume you use a machine name like "file-containing-recipe" (change this name to whatever fits).
For the file-containing-recipe field, specify a field type "file", and combine it with whatever other configuration options that fit (eg: single value or multiple values, optional or mandatory, etc).

To verify your configuration, create a node of content type recipe, and use the newly defined "file-containing-recipe"-field to actually attach your file(s). After saving the new node, verify if the results are what you're asking for. If (still) not, go back to your "file-containing-recipe"-configuration to further tune any of its settings.
Done.

Adding a file download link to a node


How to get Span collection by id in Watir

Question: Is there a method in watir to get list of all the span collection by id. I can traverse the span tags only by index and one item at a time.
i want to get the entire collection of the span tags and loop through it.
<code>    irb(main):060:0> ie.span(:id =>/ctl00_ContentPlaceHolder1_DataList1_ctl132_lblSubject/).text
=> "30 stuff"

irb(main):065:0> ie.span(:id =>/ctl00_ContentPlaceHolder1_DataList1_ctl/).exists?
=> true
irb(main):073:0> spans=ie.span(:id =>/ctl00_ContentPlaceHolder1_DataList1_ctl/ ,:index=>3)
=> #<Watir::Span: located: false; {:id=>/ctl00_ContentPlaceHolder1_DataList1_ctl/, :index=>3, :tag_name=>"span"}>
irb(main):074:0> spans.text
=> "Well, morning."
irb(main):075:0>
</code>
Answer: Yes, you can iterate. Write the following code
<code>ie.spans(:id =>/ctl00_ContentPlaceHolder1_DataList1_ctl/).each do |span|
  p span.text
end
</code>
It will print all the span's text which is matching your id.


How to integrate Views with apache solr search?

Question: In my site I am implementing zip code based search, for that I created one view of user profile and add one expose filter to it which is exposing result on postal zip code entered by user. Now I am thinking that exposed filter integrate with Apache solr.
Help me out for which module I have to use for it and how I configure it?
List of modules I have used in my project:

addressfield
geofield
geocoder
geophp
apachesolr
facetapi
profile2
Answer: The module you want is the aptly named Apache Solr Views which will allow you to construct views from the SOLR index. Configuration is pretty simple. It's kind of a drop-in module. You'll choose to create an "Apache SOLR view". From the project page:

Create a view from admin/structure/views/add and choose Apachesolr search. All of the fields indexed in solr should be available as views fields/filters/sort. Configure the view as needed and save it

Hope that helps you. Good luck!
Comment: Thank you webkenny for your response and efforts! I am going to implement it.
Comment: You're welcome. If this did help don't forget to mark the question as answered. :)


Maximum a posteriori estimation with one single training example?

Question: I am doing maximum a posteriori (MAP) to estimate $\mu$ and $\sigma$ with $N$ samples drawn from $\mathcal{N}(5, 1)$. The priors that I place are $\mu\sim\mathcal{N}(5, 1)$ and $\sigma\sim\mathcal{N}(1, 1)$.
Taking the derivatives of the posteriors and setting the derivatives to 0, I get
\begin{align}
-\mu+5+\frac{1}{\sigma^2}\left(\sum\limits_{n=1}^{N}x_n-N\mu\right)   &= 0 \\
\ \\
-\sigma+1-\frac{N}{\sigma}+\frac{\sum_{n=1}^{N}(x_n-\mu)^2}{\sigma^3} &= 0,
\end{align}
which can be solved by plugging in $N$ data points $\{x_1,x_2,\ldots,x_N\}$.
My problem occurs when $N=1$. That is, I only have one data point available to do MAP. Say my that point is 5.1. Plugging in, I solve it in MATLAB by
<code>syms m s;
% Assume \sigma is non-zero
S = solve([ ...
    s^2*(m-5)-5.1+m == 0, ...
    -s^4+s^3-s^2+(5.1-m)^2 == 0], ...
    [m, s]);

mus_hat = double(vpa(S.m));
sigmas_hat = double(vpa(S.s));
</code>
All the solutions are complex and hence cannot be correct.
I understand that a prior $\sigma\sim\mathcal{N}(1, 1)$ might be inappropriate. But how to explain it is this prior that causes all the solutions to be complex? I can't really see the link. Is there an intuitive explanation for this?
Comment: Please stop vandalizing your post. You can flag it to have your user ID disconnected from the Q, if you want.
Comment: Instead of defacing your post, delete it if you want to delete it.
Comment: @J.Steen Crap. Sorry, new to the site. Didnt mean it. Great that it got rolled back. Thanks @gung!
Answer: If we write down the posterior distribution on $(\mu,\sigma)$ associated with a single observation $x$,
$$\pi(\mu,\sigma|x)\propto\sigma^{-1}\exp\frac{-1}{2}\left\{\sigma^{-2}(x-\mu)^2 +(\mu-5)^2+(\sigma-1)^2\right\}\mathbb{I}_{\mathbb{R}^+_-}(\sigma)$$
(as $\sigma$ is necessarily positive), this function takes the value
$$\pi(x,\sigma|x)\propto\sigma^{-1}\exp\frac{-1}{2}\left\{(\mu-5)^2+(\sigma-1)^2\right\}\mathbb{I}_{\mathbb{R}^+_-}(\sigma)$$
when $\mu=x$ and $\pi(x,\sigma|x)$ is unbounded when $\sigma$ goes to zero:
$$\lim_{\sigma\to 0^+} \pi(x,\sigma|x)=+\infty\,.$$
This demonstrates there is no MAP in this setting.
Comment: +1; Can I check this is what you meant: the posterior distribution given one sample shoots up to $+\infty$ at $(\mu, \sigma)=(x, 0)$; therefore, setting derivatives to 0 and solving for the maximum point will not return real solutions?
Comment: When the maximum occurs at a boundary point, first order conditions do not have to be satisfied.


How can you force a stylesheet reload in Drupal7?

Question: This is about that old trick of tacking a fake query argument onto the URL of a stylesheet (e.g., <link rel="stylesheet" type="text/css" href="http://www.example.com/site.css?v=123">) so that, when you change the stylesheet, it'll be reloaded by the users' browsers, since it looks like a URL that's not in the browser's cache.
So, the question: How can you do this in D7 where the stylesheets are specified in the .info files?  I tried adding a query arg onto the entry in my site's info file -- stylesheets[all][] = site.css?v=123 but without any luck (the page rendering got very unhappy).  Any ideas?
Comment: Related: [How can I have the JS/CSS cache refresh on every page load?](http://drupal.stackexchange.com/q/48336/1908)
Answer: You can do this with drush
$ drush help cache-clear
Clear a specific cache, or all drupal caches.

Arguments:
 type                                      The particular cache to clear. Omit
                                           this argument to choose from
                                           available caches.

Aliases: cc

So you can do
drush cc css-js

and this will rescan the cached CSS and JS files, nuke them if they are stale, and generate a new key that gets appended to CSS and JS URLs.
Comment: This should be the accepted answer because this _only_ clears the CSS and JS files, not the whole cache.
Comment: I believe page caches should be cleared afterwards as well, otherwise cached pages would be referencing stale CSS/JS aggregate files.
Answer: By default you can navigate to /admin/config/development/performance and select the Clear all caches button. Behind the scenes this will actually do what you describe by appending a new query-string to the CSS URL.
Answer: Flushing the Drupal caches should take care of this issue for you.
Answer: You can see your changes made to your theme.info file by issuing the 'theme-list' cache clear Drush command:
$ drush cc theme-list

you can also add this line to theme.info to force rebuilding cache on every page load:
settings[clear_registry] = 1


How to access vue props with name contains dash sign?

Question: I'm working on a Vue project. With the eslint's requirement, I cannot name the props with camel case and it will report a warning Attribute ':clientId' must be hyphenated. eslint vue/attribute-hyphenation is required to use kekab case instead. For example,
<GranfFather :client-id="clientId" v-bind="$attrs">
  <Father>
    <GrandSon />
  </Father>
</GrandFather>

I need to access the property in the <GrandSon /> component. Generally, I'd like to name the property as clientId, but due to the eslint's requirement of the company, I can only name it as client-id otherwise it will report a warnning. So, if I want to access this property, the only method I come up with is use this.$attrs["client-id"]. But I'm wondering how could I access this property via this.$attrs.clientId or in a similar method?
when I use this.$attrs in <GrandSon /> component, it print
{ client-id: "xxxxxx" }

Is this mean I can only client-id via this.$attrs["clientId"]?
What I want is access client-id just by using this.$attrs.clientId.
Comment: I believe you can just  access the prop as `clientId` inside the component as kekab  case are automatically converted to camel case ?
Comment: `client-id` is a prop. It's always normalized to camel case when it's accessed. There's no clientId or client-id prop in GrandSon because you didn't provide it to it.
Comment: Please, provide https://stackoverflow.com/help/mcve for your problem. It's unclear what you try to achieve. If you need to provide clientId prop to GrandSon then do this explicitly. There's a difference between attributes and props. Props are normalized to camel case. Attributes aren't. It's possible for GrandSon to inherit an *attribute* if it's root element of Father, and the same is for GrandFather-Father relation. See https://vuejs.org/guide/components/attrs.html .
Comment: Well, I currently cannot directly access the prop `clientId`. I don't know why when I use `this.$attrs.clientId`, it returns `undefined`. I can only access the prop when I use `this.$attrs["client-id"]`.
Comment: I have updated my description. What I want to achieve is just access the prop `client-id` in `camel` case in component ``.
Answer: There is a difference between props and attributes.
A prop is supposed to be specified in component props, it is normalized to camel case and received only by a component that a prop was provided to.
Attributes aren't normalized and can fall through components that are used as root elements. This behaviour is determined by inheritAttrs property in components. It is commonly used to provide HTML attributes to root HTML elements, but can also be used to provide a prop to nearest nested components that accept it.
If GrandSon is supposed to receive clientId prop, it needs to be declared in the component in props. Although it apparently can receive a prop as a fallthrough attribute from GrandFather in this case, it's preferable to explicitly provide it as <GrandSon :client-id="clientId"> in order for it to not depend on a specific hierarchy of root elements.


Divs using inline-block are overlapping

Question: I have a problem with my divs overlapping each other, with no space in between them. I've tried text-align center, removing and adding white space between the divs, setting margins, nothing seems to work. I just need these items to be spaced apart. Any help is appreciated.
Here is an example fiddle: https://jsfiddle.net/vn6t3nwd/
HTML:

up

down

stop

go

CSS:
#timer-container {
    position: relative;
    width: 100%;
    padding-bottom: 56.25%;
    display: table;
    background-color: black;
}

#timermode {
    position: absolute;
    width: 30%;
    font-family: "Avenir-Light";
    font-size: 40px;
    color: white;
    vertical-align: top;
    display: inline-block;
}

#timercontrol {
    position: absolute;
    display: inline-block;
    font-size: 40px;
    font-family: "Avenir-Light";
    color: white;
}

Edit: The problem was having position: absolute, however removing it causes the height of my background to increase slightly. I think it is due to my 56.25% padding on the bottom but I need to have that. Anyway to have it both ways?
Edit2: Updated the fiddle with the answer. I got around my height increase by adding another container.
Answer: You have overlapping because of position: absolute;
Also, id is made to be unique identifier, if you need to use same css for multiple html elements you should define it as a class
HTML:

up

down

stop

go

CSS:
#timer-container {
    ...
}
.timermode {
    ...
}
.timercontrol {
    ...
}

Comment: You guys are correct, the position:absolute is causing the problem, however by removing it the height of background changes. I think it's due to my 56.25% padding on the container. Is there a way to get around this?
Answer: I'm a young aspiring programmer so my answer may and may not help you. I think it's because of the position absolute. I edit your code in JSFiddel and notice that when I remove the absolute style it position all of the elements according to their relative position. Hope it helps. Happy coding.
Answer: Removing the absolute positioning of the child elements will allow them to display inline as intended. Also, as stated only use id attributes for unique elements, use classes for repeating elements as in the example below.

#timer-container {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%;
  display: table;
  background-color: black;
}
.timermode {
  width: 30%;
  font-family: "Avenir-Light";
  font-size: 40px;
  color: white;
  vertical-align: top;
  display: inline-block;
}
.timercontrol {
  display: inline-block;
  font-size: 40px;
  font-family: "Avenir-Light";
  color: white;
}

up

down

stop

go

Divs using inline-block are overlapping


Basic "empty" entity type?

Question: Is there a module that provides an empty entity, to which I can add my own fields. I guess it would include just an Entity-ID as a primary field, and work with other entity modules.
For me, nodes have too much baggage included: title, nid, vid, publishing options, author and date.
Answer: You should really check out the Console project.
https://www.drupal.org/project/console
It allows for command line creation of modules, and will generate entities for your module.
Here's a video explaining it all in 5 minutes.
https://www.youtube.com/watch?v=agcqTEr5_48
navigate to the modules directory in the drupal root in your command line tool
enter command: bin/console generate:module enter the name for your module
enter a machine name for your module hit enter for the default path
enter a description hit enter for defaults for rest of questions
enter command: bin/console generate:entity:content
enter the name of the module you just created
enter a class name for the Entity you are creating
Comment: Thanks for that, I'll take a look. Be nice if there was GUI, though perhaps there is a good reason why not.
Comment: There is no GUI for entity creation in Drupal 8 that I am aware of.  The Entity Construction Kit that adds some UI for entity creation in D7 doesn't have a D8 release, and may be some time before it becomes available

Basic "empty" entity type?


Classic asp . Objects not shown

Question: I have a weird issue. I have a website built with classic asp. It was working fine for years, but now for some reason, some of my htc are not shown when the page loads. Then when I try to access these objects like this: document.All(objName).value, I get: Object doesn't support this property or method.
Any idea?
Thanks.
Comment: Try `document.All.objName.value` if `objName` is an actual element ID (not a variable), or `document.getElementById(objName)` if it's a variable with an element ID.
Comment: what browser are you using?
Comment: I'm using IExplorer 9
Answer: First of all wanted to mention this got nothing to do with classic ASP, it's pure client side issue.
Now to the point. The notorious document.all should not be used, period. Client side VBScript should also be avoided becuase it's IE only meaning it won't work for over 50% of your visitors.
To sum it up: switch to JavaScript and use the standard document.getElementById. Change your code from such line:
MyValue = document.All(objName).value

To this instead:
var myValue = document.getElementById(objName).value;

In case the objName is name and not id e.g. <input type="text" name="MyInput" /> you can use:
var myValue = document.getElementsByName("MyInput")[0].value;

(assuming you have only one element with that name)
Answer: Was it solved? If this issue was particularly generated on IE browser, you could make it compatible version by adding the following line of ASP code?
Response.AddHeader "X-UA-Compatible", "IE=edge,chrome=1"

Classic asp . Objects not shown


Three players with their own coin flip untill they have heads. The first one with heads wins

Question: I have been stuck with this question for some time and I'm not sure if I'm doing it correctly.
There are three players who each have their own coin—each coin having a different probability for it to land on heads. They play this game simultaneously, the first one to flip heads wins the game.
Let $X$ be the number of flips player 1 needs to get heads, $Y$ the number of flips for player 2 till he has heads,  and $Z$ be the flips for player 3 till he has heads.
Now I noted this down as $X\sim \textrm{Geom}(p), Y\sim \textrm{Geom}(q)$, and $Z\sim \textrm{Geom}(r)$. These three variables are independent.
My first question would be: What is the probability that player 1 wins?
I thought it was enough to calculate $\mathrm{P}(X < Y < Z) + \mathrm{P}(X < Z < Y)$.
But now I'm not sure that this is enough.
I'm also not so sure about this: the number of turns needed to determine the winner of this game would be the $\mathrm{Min}\{X, Y, Z\}$, since the first person to flip heads will win. Hence meaning that its the minimum right?
So the number of turns after the winner is known until the last person to flip heads would be the $M = \mathrm{Max}\{X,Y,Z\}$, after someone wins the game you go and play until everyone has heads. This would mean the maximum of the flips? So since these three variables are geometric and independent this comes down to:
$$
\mathrm{P} (M>m) = \mathrm{P} (X>m;  Y>m; Z>m)= ((1-p)(1-q)(1-r)^m)
$$
This means that $M$ is also Geometric but then moved to zero.
So I hope someone can maybe tell me if I'm doing this correctly, or if I should calculate these things differently.
Comment: You need to specify in a little more detail what "They play this game simultaneously, the first one to flip heads wins the game" means - what if e.g. X and Y both get a heads on their first toss?
Comment: Since $X, Y$, and $Z$ are claimed to be geometric random variables with different parameters, they are **not iid** random variables if you are using the standard meaning of iid _independent and identically distributed._  Clearly they are _not_ identically distributed.  Also, as silverfish asks, you need to specify what it means to be the first to toss a head in case of ties.
Comment: Simply ignore ties.
Comment: @DavidG.Stork please allow the original poster to specify the intent of their question.
Comment: Dilip: Yeah sorry about the iid, its clearly doesnt have the same parameter, its just independent. @Silverfish: Now to calculate that player 1 wins this game: You cant have two players that toss heads at the same time. So to calculate the player 1 wins:  if we think about this in turns we can say that player 1 wins in the kth turn. You have to assume that he can only win if no one else flipped heads before this kth turn and that in this turn no one else has heads. This is how I understand this, I hope it makes more sense now.
Comment: Oh and @Glen_b I hope this explains it a bit more.
Comment: "You cant have two players that toss heads at the same time" - why is this true, if "They play this game simultaneously"? Do you mean that player 1 tosses first, then player 2, then player 3?
Comment: @Silverfish, this is an old exam question. To me it seems that in order for player 1 to win it means that no one else can toss heads before he does and that in the turn he does toss heads no one else does that. Maybe im just thinking about this the wrong way, but yeah do you have any suggestions? If two players do toss heads at the same time how can I calculate the probability that player 1 wins? It is in discrete time so tossing at the same time shouldnt be such a problem I think.
Comment: A straightforward (not very pretty) way to such problems is writing $p^{(k)}$ for the probability that player 1 wins *in turn k*. Then P(player 1 wins) is given by the sum of the series $p^{(1)}+p^{(2)}+p^{(3)}+...$ which is an easily summable geometric series. You need to get $p^{(1)}$ right (if players toss in sequence with player 1 going first then it's simply $p$, if they toss simultaneously it's harder: you also need to make sure players 2 and 3 don't get a head that turn). For $p^{(2)}$, find the probability the game even reaches a 2nd turn, aside from that it's much like $p^{(1)}$.
Comment: @Silverfish thats why I thought that calculating  $\mathrm{P}(X < Y < Z) + \mathrm{P}(X < Z < Y)$ would give me the result that I'm looking for. I think that that means that player one needs less turns to toss heads than player 2 and 3. Hence the  $\mathrm{P}(X < Y < Z)$. Since its all geometric and independent this is indeed an easy geometric series. But  $\mathrm{P}(X < Y < Z) + \mathrm{P}(X < Z < Y)$ should be the answer right? Or do I need to add something else to this?
Comment: If your situation is as you describe, then no. $X$ and $Y$ and $Z$ are not much help to you at all, as they only describe the *first* time that a players get a head but a player might only win on e.g. their third head (if their first two heads were in drawn rounds). You might define some new variables (let's say $U$, $V$, $W$) as the first time that a player gets a *winning head* (i.e. they get a head but their opponents don't), but then note that $U$, $V$ and $W$ are no longer independent since if $U=1$ then $P(V=1)=0$ (player 2 can't have a winning head in round 1 if player 1 did).
Comment: @Silverfish ah yeah I get it! This isnt as nice as I hoped it would be.
Answer: I am sure there are many ways to analyze this situation, but the following one is appealing for its simplicity and use of only the most basic properties of probability.  Assuming ties for heads cause the game to continue until a result is uniquely determined, it shows the chance of a player winning the game is her relative odds: the proportion of her odds of heads, divided by the sum of the odds of heads among all players. The game length obviously has a geometric distribution. Its parameter is proportional to this sum of odds. The constant of proportionality is the product of all the chances of tails.
Other methods of resolving ties (to create a definite winner) can be analyzed in a similar way, starting with computing the chance that a given player will win a particular round and continuing as shown here.

Let there be $m$ players, each using a coin with probability $p_i$ of heads.  Let $i,j,\ldots, k$ be any permutation of $(1,2,\ldots,m)$.
Suppose that when a tie occurs, no outcome is declared and play continues.  Then the chance that player $i$ wins is the chance that she is the sole person to toss heads, equal to
$$p_i(1-p_j)\ldots(1-p_k) = \frac{p_i}{1-p_i}\prod_{l=1}^m (1-p_l) = \pi_i Q$$
where I have written $\pi_i = p_i/(1-p_i)$ for player $i$'s odds of heads and $Q$ for the product of all $1-p_l$ (the chance that everybody simultaneously observes a tail).
If no player wins a round, the game starts over, with exactly the same probabilities.  Therefore the chance that player $i$ wins the entire game is the chance they can win a given round, divided by the sum of all players' chances to win the round:
$$\Pr(i\text{ wins}) = \frac{\pi_i Q}{\sum_{l=1}^m \pi_l Q} = \frac{\pi_i}{\sum_{l=1}^m \pi_l} = \frac{\pi_i}{\pi}.$$
It is their proportion of the total odds $\pi$.
The chance that the game ends on any particular round is the chance that exactly one player observes heads, equal to
$$\sum_{l=1}^m \pi_l Q = \pi Q.$$
Thus the length of the game has a geometric distribution with parameter $\pi Q$.
This result is supported by simulation:

It was carried out with this R script, which can simulate and summarize tens of millions of tosses per second for arbitrarily many players (up to limits determined by RAM).
coins <- log(2:10); coins <- coins / sum(coins)
n.players <- length(coins)
n.rounds <- 1e6
#
# Simulate many rounds.
#
system.time({
  tosses <- matrix(runif(n.rounds * n.players), nrow=n.players) < coins
  wins <- colSums(tosses) == 1
  winners <- colSums(1:n.players * tosses) * wins
  (results <- tabulate(winners[winners != 0], n.players))
})
#
# Compare to theory.
#
odds <- coins / (1-coins)
p <- odds / sum(odds)
rbind(Simulation=results / sum(results), Theory=p)
#
# Display the distribution of game lengths compared to the geometric distribution.
#
lengths <- diff(c(0, which(wins==TRUE)))
Q <- prod(1 - coins)
pQ <- sum(odds) * Q
n.max <- ceiling((log(.002) + log(pQ)) / log(1-pQ)) # Plotting limit
prob.geometric <- (1 - pQ)^(1:n.max - 1) * pQ

subtitle <- paste(sum(results),"games played with coins",
                  paste(round(coins, 2), collapse=","))
hist(lengths[lengths < n.max], freq=FALSE, breaks=(1:n.max)-1/2,
     main="Simulation (bars) vs. Theory (lines)",
     xlab="Game lengths",
     sub=subtitle)

invisible(sapply(1:n.max, function(i) {
  lines(c(i,i), c(0, prob.geometric[i]), lwd=2, col="Red")
}))


Is it possible to reduce $a^2+b^2 - 2Kab = 0 $ to some sort of a (a+b) (a-b) kind of equation?

Question: Is it possible to reduce $a^2+b^2 - 2Kab = 0 $
to some sort of a (a+b) (a-b) kind of equation? Or something that tells how a is related to b? The K is the spoiler being faced.
Comment: Not really anything to do with linear algebra. Tags edited.
Answer: Yes, if you allow complex coefficients.
Hint: Factorize $x^2 - 2Kx + 1 $.
E.g. Calculate the roots using the quadratic formula.
Hence, factorize $a^2 - 2Kab + b^2$.


Why does integrating a probability density function give probability?

Question: It is well know that integrating a probability density function gives probability, that is,
$$P(X\geq a) = \int_a^\infty f_X(x)\, dx$$
where $X$ is a continuous random variable, $a$ is a scalar and $f_X(x)$ is the probability density function of $X.$

Question: Why is this the case?

When I learn this, I just memorize this without understanding it.
But recently I started pondering about this.
Comment: This is the usual *definition* of the density: when a function $f_X$ exists with this property, it is called a PDF.  It is not unique, but any two such functions can disagree only on a set of Lebesgue measure zero.
Comment: It's actually very similar to discrete cases when you have frequencies (for ex. binomial), do you understand why this is true in that case?
Answer: The probability density function is actually defined by this requirement.  In introductory probability courses, you will see the density function defined as the (Riemann) derivative of the cumulative distribution function:
$$f_X(x) \equiv \frac{d F_X}{dx}(x) = \frac{d}{dx} \mathbb{P}(X \leqslant x)
= \lim_{\Delta \downarrow 0} \frac{\mathbb{P}(x < X \leqslant x + \Delta)}{\Delta}.$$
Using the fundamental theorem of calculus, you then have:
$$\begin{equation} \begin{aligned}
\mathbb{P}(X \leqslant a)
= F_x(a)
= \int \limits_{-\infty}^a \frac{d F_X}{dx}(x) dx
= \int \limits_{-\infty}^a f_X(x) dx.
\end{aligned} \end{equation}$$
The corresponding equation you give in your question is then obtained using the norming axiom of probability.  You can see from this reasoning that the integral equations for probabilities of continuous random variables follow from the definition of the density function, combined with the fundamental theorem of calculus.
If you go on to do graduate-level probability theory (based on measure theory), the relationship is even more direct.  In the measure-theoretic definitions, the density function is defined as a broader type of derivative that is called the Radon-Nikodym derivative, which is a type of "anti-integral" defined directly by the stated integral requirement.  In this case, the integral requirement is essentially the definition of the density ---i.e., any function that integrates to give the probability of any stipulated event (integrating over the space of that event) is a valid density function.
Comment: This does answer the question in a nice way, but in the second line of equations, the integrands should be reversed, i.e. from $-\infty$ to $a$, alternatively stated as $P[X> a]$ and subsequently $1-F_X(a)$ about the first equality sign.
Comment: @Emil: Well-spotted - edited.


Why is selection of one amongst the group of highly correlated variables by lasso is stated as its disadvantage?

Question: I have seen PCA being used to eliminate variables for dimensionality reduction, but LASSO's ability to eliminate variables for the very same purpose is often described as a disadvantage.
My intuition is that in PCA we still retain some of the information in the reduced dimensions as the newly formed features are linear combinations of the old variables, whereas in LASSO we just completely drop some of the original variables by setting the coefficients of non selected features to zero. Is my intuition correct? If not, then why is dimensionality reduction a drawback in one scenario and an advantage in the other?
Comment: See also https://stats.stackexchange.com/questions/264016/why-lasso-or-elasticnet-perform-better-than-ridge-when-the-features-are-correlat/264118#264118
Answer: Principal Components Analysis (PCA) doesn't select among the original features unless the features are orthogonal. It lowers the dimension of the feature space by ignoring PCs (linear combinations of potentially all the predictors) that explain little of the feature-set variance, but in general it does not remove any of the original features from the problem.
Some find the ability of LASSO to choose among several correlated features to be a strength rather than a weakness, particularly when the number of features greatly exceeds the number of cases. Yes, LASSO's choice among correlated features can be highly sample dependent. Nevertheless, as LASSO penalizes the coefficients for the retained variables it can still be useful for developing prediction models. The "disadvantage" is when one tries to interpret the selection by LASSO in terms of "variable importance" for inference.
The issues raised in this question point out a potential advantage of ridge regression, which is effectively PCA with varying weights among the PCs rather than simple 0/1 weights. (See page 79 of ESLII.) Try both LASSO and ridge regression on multiple bootstrap samples of a data set having correlated predictors. The particular features selected by LASSO may change dramatically among the bootstrap samples. This illustrates the mistake of interpreting choices by LASSO in terms of an underlying true "variable importance." The coefficients of correlated predictors in ridge regression may be variable among bootstrap samples but the ridge models will contain all the features.
Comment: I'm a bit confused about your argument in favor of Ridge regression against LASSO in the last paragraph. While I agree that one shouldn't interpret LASSO as assessing each variable's *importance* for highly correlated predictors, are you saying that among different bootstrap samples, the coefficient variability in Ridge is never greater than LASSO? I would guess that depending on the size of the regularization $\lambda$, the primary difference would be that LASSO may change which features are set to 0, while Ridge changes which features are assigned coefficients close to 0 - so what?
Comment: @DonWalpola I see my last paragraph more as a warning than as an argument against LASSO. From a set of correlated predictors, any predictor-selection method will choose the one that happened to work best on the data sample at hand. The selected predictor might not work so well on a new data set, while one of those omitted might have worked better on the new data. Unlike LASSO, ridge doesn't throw away information about correlated predictors and might mitigate somewhat against this phenomenon. So with a moderate number of predictors at least, why choose LASSO over ridge for prediction?
Comment: Well, I guess my question has to do with how Ridge performs regularization, and if you can really say that it doesn't throw out information. I don't have much experience with using Ridge, but my understanding is that there would still be a significant difference in the magnitude of the coefficients assigned to each predictor in a correlated set. If my understanding is correct, wouldn't that mean that the same risk of misinterpreting 'importance' based on coefficient magnitude is present in Ridge, even though you technically haven't 'thrown away' any variables?
Comment: @DonWalpola you are correct that there will be sample-dependent differences in magnitudes of coefficients within a set of correlated predictors, but at least all are included into the final model. In the context of prediction, whether LASSO or ridge will perform better may depend on the scale of the data and the numbers of predictors available; the hybrid elastic net can combine their strengths. In the context of inference, my warning would be always to avoid assigning 'importance' to predictors based either on what LASSO selected or on the relative magnitudes of ridge coefficients.
Comment: Alright, thanks for the clarification. I think I was just confused because I didn't see you explicitly make reference to possible inferential pitfalls that occur in regularization techniques used for 'variable selection/importance' in general in your original post. I wonder, once scale normalization is performed, would the rotational invariance of the $L_{2}$ norm provide a means to demonstrate whether or not the coefficients from ridge regression suffered from a similar magnitude disparity as those from LASSO?
Answer: Using PCA to do feature selection is different than using LASSO because PCA does not consider the response variable, but only check the variance in features.
See my answers here, with graphical illustration (logistic regression case / linear method without regularization).
How to decide between PCA and logistic regression?
Comment: I know that, but my question is of different taste. I want to know why is dropping some correlated variables is advantage in one and disadvantage in the other irrespective of whether they use the response or not.


Using a Drupal 6 tutorial for Drupal 7

Question: I hate making posts like this because I feel like I am asking people to do all my work for  me! However, in times like this, when I am pressed for time, I have to.
I am trying to add an user profile in the topics in the Forum module. I have found a brilliant tutorial, but unfortunately it is for Drupal 6 and some of the functions are not compatible with Drupal 7; I couldn't find the equivalent functions, and I figured some of you may know them.
If you do, I would greatly appreciate it if you could share them with me; even if you don't provide the whole of the functions in tutorial (which would be nice), and just provide me with the Drupal 7 functions to replace the ones in the tutorial; anything would help.
The main functions that do not work are the profile_load_profile($user), and the get_user_XYZ($user) functions.
By the way, I am assuming it is because those functions are depreciated in Drupal 7 when it says "Undefined"! I can't see any other reason for it not to work, and I kind of expected some of the tutorials wouldn't work properly on Drupal 6.
Answer: Drupal 7 doesn't include the core profile module since users are entities which you can attach fields to. If you have added additional fields to the user you can get them with just user_load().
FYI: it is not advisable to the $user when calling user_load() since $user is a global variable which can cause problems.
It doesn't look like that tutorial would ever fully work since get_user_comment_count() is never defined and the get_user_rank() parameter call's for a comment count but uses the $user object in the user_forum_load() function.
To get the comment count of a user you could just lookup the number of comments from the comment table for a given user and the tutorial's user_comment_rank() should still work.
Comment: Hi, sorry for my slow reply. At the minute, I have just commented the two lines at fault out so that there is no error from the template file, I still can't get it to show up! There a now errors or anything, it just seems that drupal isn't taking notice of the functions! And it is the same with [this](http://www.forum-software.org/news/21122010-drupal-tip-9-theme-forum-topics) tutorial! So does anyone have a working solution, or alternitive for Drupal 7. Thanks for the information @acouch!
Comment: The tutorial you just linked to is about updating template files. What the first tutorial you linked to does is add extra data to the $user object. Once you've added to the $user object in hook_user() you need to call that either directly in the node-forum.tpl.php or comment-forum.tpl.php. If you added $user->foo in hook_user() you can call that in node-forum.tpl.php as print $user->foo() .  You can check to see if your hook_user() is working by global $user; var_dump($user); in the node-forum.tpl.php.
Comment: Sorry for the slow reply! I've just got so ****ed off trying to do this, and it's not even for me, so I've decided to bite the bullet and just install Advanced Forum. So now, I think the forum will meet my clients requirements. Thanks for your excellent support though! Now I ask myself: Why didn't I take the easy way out to start with, instead of spending hours and getting no where? A question I ask all too often!
Answer: Drupal 6 doesn't define any function whose name starts with "get_user"; those are functions defined in the code used by the tutorial, or from a module the tutorial is referring to.
The User profile module, in Drupal 7, is only used when updating from a Drupal 6 site; differently the User profile module is not shown in the list of the modules, as it is hidden by default, and users cannot enable it using the user interface.
The alternative to using the User profile module is to create fields using the user interface provided by the Field module.
Comment: You are right, those functions are defined in code used by tutorial, apart from the comment_count, which acouch has already mentioned! But, the tutorial doesn't refer to a module anyway. Does it?... It looks like I may have to use your alternitive, if nobody can put forward a better way, or a tweaked tutorial, etc. Thanks anyway
Comment: I was precisating what I said in the first phrase: If you find a reference to a `get_user_XYZ()` function, but the tutorial code doesn't have the code for that function, then the tutorial is referring a third-party module, although modules should prefix a function name with their machine name, and that does not seem it done with `get_user_XYZ()`.

Using a Drupal 6 tutorial for Drupal 7


Using training data for training another model

Question: I'm working on NIPS 2017 Learning to Run project. I have limited time and I need to try 2 models(DDPG and Soft Actor Critic). The simulation is slow and it takes too much time.
I wonder,
After I trained one of them, is it possible to use its state-action-reward data for training the other one?
Answer: If you replaced the Q-table of an untrained SAC model with a trained DDPG's Q-table then you'd be using a converged policy produced from the DDPG method. Likewise, replacing an untrained DDPG model's Q-table with the Q-table from a trained SAC model will give it the converged policy from following the SAC method.
If you have not already, you should check out this paper which discusses and experiments with the differences between DDPG and SAC.


Details of a proof for a theorem about Hilbert symbol

Question: Kato's Number Theory 1: Fermat's Dream writes:

PROPOSITION 2.4. Let $v$ be a prime number or $\infty$. For $a, b \in \mathbb{Q}^{\times}$ we have the following:
  (1) $(a,b)_v = (b,a)_v$.
  (2) $(a,bc)_v = (a,b)_v(a,c)_v$
  (3) $(a,-a)_v = 1$. If $a\neq 1$, then $(a,1-a)_v = 1$.
  ...

and

THEOREM 2.5. Let $a,b\in\mathbb{Q}^{\times}$. Then $(a,b)_v$ is equal to $1$ except for a finite number of $v$, and we have $$\prod_v (a,b)_v = 1$$ where $v$ runs through all the prime numbers and $\infty$.

In the second part of the proof of this theorem, this book says that in order to show that the product is $1$ it suffices to show it in the following cases (i)-(iii) since we have to prove it only for each prime factor of $a$ and $b$ and for $-1$ thanks to Prop. 2.4(1), (2) and (3).
(i) $a$ and $b$ are two distinct odd prime numbers.
(ii) $a$ is an odd prime number, and $b = -1$ or $2$.
(iii) $a=-1$, and $b=-1$ or $2$.

My question is, how can the Prop 2.4(1)-(3) be applied to reduce the proof to cases (i)-(iii)?
From 2.4(2) I know that we may consider the factor of $a,b\in \mathbb{Q}^{\times}$, but why is it prime? If we take $a = \frac{c}{d}\in\mathbb{Q}^{\times}$ where $c,d\in\mathbb{Z}$, then we can consider the prime factor of $c$, but what about $\frac{1}{d}$?
Answer: By multiplicativity, and the fact that $(1,b)_v = 1$, for any $a,b\in \mathbb{Q}^\times$ you get
$$(a^{-1},b)_v = (a,b)^{-1}_v = (a,b)_v,$$
which means that the product formula may be checked for the numerator and denominator separately:
$$(\frac{c}{d}, b)_v = (c, b)_v\cdot (d, b)_v.$$


Como usar o for pra comparar um index específico?

Question: Na função bonAppetit, eu quero pegar apenas o índice k (no caso, k=1 e o valor é 10), e ver se esse numero é menor ou igual a b.
Só que o meu programa está rodando a lista inteira.
def bonAppetit(bill, k, b):
    n = len(bill)

    for k in range(n):
        if bill[k] >= b:
            print('Bon Appetit')
    del(bill[k])
    x = sum(bill)
    if x / 2 < b:
        y = (b - (x / 2))
        print(f'{y:.0f}')
print(bonAppetit([3, 10, 2, 9], 1, 7))

output desejado:
Bon Appetit

output que estou tendo:
Bon Appetit
Bon Appetit

Answer: Se você só quer um índice específico em vez da lista inteira, então acesse o elemento diretamente em vez de fazer um for:
def bonAppetit(bill, k, b):
    if bill[k] >= b: # <-- **AQUI** - não precisa de for, acesse o índice diretamente
        print('Bon Appetit')
    del(bill[k])
    x = sum(bill)
    if x / 2 < b:
        y = (b - (x / 2))
        print(f'{y:.0f}')

bonAppetit([3, 10, 2, 9], 1, 7)

Também retirei a variável n que agora ficou sem uso, e ao chamar a função retirei o print, pois a função não retorna nenhum valor, então não há o que imprimir.


Universal Property of Quotient Field

Question: I have following question about Universal Property for Quotient Field that leads me to following contradiction:
The statement is: Let $R$ be an intergal domain and $\phi: R \to F$ is a ring morphism. Futhermore, let $i: R \to Q(R)$ be the canonic inclusion. Then there exist a unique morphism $\bar{\phi}: Q(R) \to F$ with $\phi = \bar{\phi} \circ i$.
Then I consider following example: Let $R = \mathbb{Z}, F = \mathbb{Z}/(p)$ for a prime $p$. Let $\phi: \mathbb{Z} \to \mathbb{Z}/(p)$ be the canonic projection. Obviously, $\phi \neq 0$. But on the other hand the extension $\bar{\phi}: \mathbb{Q}= Q(\mathbb{Z}) \to \mathbb{Z}/(p)$ is obviously zero map since in $\mathbb{Q}= Q(\mathbb{Z})$ we have $1 = \frac{p}{p}$ and therefore $\bar{\phi(1)}=0$. Where is the error in my reasonings?
Comment: It can be made to work as long as your restrict to the subring of rationals writable with denominator coprime to $\,p,\,$ as I explain in my answer.
Answer: The ring homomorphisms $\phi:R\to F$ is required to be injective (and $F$ is required to be a field).
See here for example.
More generally, a ring homomorphism $\phi:R\to F$ extends to a ring homomorphism $Q(R)\to F$ if and only if $\phi$ maps every non-zero element of $R$ into a unit in $F$.
Comment: Technically true but not the best way to view it conceptually. Rather. the point is that the map must send denominators to *unis* since they are units in the fraction field. Viewing it this way shows how to workaround the obstruction, as I explain in my answer.
Answer: Your statement of the universal property is incorrect.  It only applies when the homomorphism $\phi:R\to F$ is injective.
Answer: The theorem requires that the map sends denominators into units, which fails for denominators that are multiples of $p$.  We can work around this if we restrict to fractions having denominators coprime to $p$. Then, by a similar proof, the natural ring map of $\,\Bbb Z\,$ into $\,\Bbb Z/p\,$ extends to the subring of $\,\Bbb Q\,$ of fractions writable with denominator coprime to $p$, via  $\,a/b \mapsto ab^{-1}\pmod p.\,$ This implies that it is valid to use such fractions when working in $\,\Bbb Z/p.\,$ You can find many examples of such modular fraction arithmetic in my posts here.

Universal Property of Quotient Field


How often does the event loop run in a browser?

Question: I understand the event loop is run periodically to check if there's any events from the browser, and to check the task queue. But, how often does this happen? Is there a set interval?
I understand blocking code on a webpage will block up the event loop because JavaScript is single threaded, but in async code (with minimal blocking) how often does the event loop run?
Comment: A good question with ludicrous down-votes and dreadful answers. + 1
Comment: [Here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#Event_loop)
Comment: *"queue.waitForMessage waits synchronously for a message to arrive if there is none currently."* --> the event loop runs whenever there is an event to process. Again, it's not a loop that's continuously running like an interval.
Comment: The engine that has the event loop is implemented in C or C++ or some other language that doesn't have the same kind of asynchronous nature as JavaScript. The engine has a while loop that looks something like `while(queue.waitForMessage()) { ... }`. The `queue.waitForMessage()` is a *synchronous* function that blocks execution until it returns a value, and it doesn't return until it has received a message. The loop makes another iteration right after and then starts waiting for a new message. You're free to believe it's not true, but I'm afraid that's the answer you're going to get.
Comment: The event loop in Node uses libnv. Now, you've just said it "the engine uses a while loop" ... this is what I have been saying from the start. Scroll up. Now, the question was, how often does this loop run. We're really talking internals here, and I think most people who left a comment thought I was talking about something completely different. Hence why I am confused at the downvotes because it's a genuine question.
Comment: The event loop runs when there's something to process in the queues. It's not like an interval in JavaScript.
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
Comment: @Juhana no that still doesn't explain how often the event loop runs. That simply explains what it does. Don't worry, I'll dig through the V8 source ... that will answer the question.
Comment: @BugHunterUK : lets take a while loop that runs directly on the processor (not js) . How long will it need to run trough the loop once? No one can predict. It depends on the processor (how fast it is) and on interrupts that may "interrupt" ;) your loop
Comment: Why the downvotes?
Comment: Wasn't me, but probably because questions at SO have to mention what problem you trying to solve, what code you used, and what error messages you got
Comment: Why do you want to know this? As you can see in a simple test (keypress->event-> doing sth) the browser runs very fast...
Comment: Certain events (like keypresses) arent handled in a loop. See "Interrupt" and "Interrupt Handler"
Comment: Yes, your question is not clear. Read on internet about javascript eventlisteners. However, if you want to terminate the listener as some point of time, there are ways to unbind it.
Comment: aside from the animationFrame type callback/event, nearly all events are fired immediately after the UX that triggered them.
Comment: Who said anything about terminating? I'm interested in general at how a browser implements the event loop and how often in runs. This is more a question related to JavaScript internals.
Comment: @jusopi That wasn't the question I asked. The event loop runs either at a specific interval or at certain points if the script isn't blocking. I wanted to know the specifics. Is that not allowed on StackOverflow ... lol.
Comment: @JuanMendes where in that document does it answer the question?
Comment: Of course there's a loop. There has to be a loop. We're talking about the event "loop". The loop that listens for events and passes them on. In it's very primitive form akin to a while loop. How often does this event loop run, at what interval? ... jeez. I can't believe people are falling over such a simple question.
Comment: No, the loop doesn't listen to the events. The loop runs whenever there's stuff in the message queue that needs processing.
Comment: @Juhana No. When using one of the webapis, that's pushed into the task queue. The event loop pulls from the task queue. This loop that is doing that HAS to be implemented as a loop for it to function. At what interval is it running?
Comment: Webapi -> Pushes to task queue -> Event loop takes it -> Pushes onto stack. That's how it works.
Comment: Well now we're getting somewhere. As you can see that MDN page doesn't explain anything what we're discussing now which was my original question. Now, I assumed that chrome wouldn't implement the event loop to run when it likes and would have maybe specified an interval for the event loop to run. Which is why I asked the question. If you've got a complete answer to correct me please submit it. It was exactly the answer I was looking for.
Answer: The event thread is not triggered on intervals, but by signals from the OS that add events to the message queue, like key and mouse events, or by callbacks in your own code (like XHRs and setTimeout). See https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#Event_loop
The main thread is shared between:

UI Layout
JS execution

Whenever an event occurs (XHR callback, click handler, setTimeout callback...), your JS runs, but the UI doesn't update until your JS has finished executing.
There is a way to use other threads, WebWorkers, and that code doesn't have access to the DOM, so it's thread safe and can run indefinitely.
Also note that each window object has a separate thread.
Comment: Doesn't answer the question buddy. What I am asking is the event loop, the one the browser implements, that pulls data from the task queue ... at what interval is this event loop running.
Comment: So your question is how often does the browser check the message queue?
Comment: I've reposted just incase my OP wasn't clear enough http://stackoverflow.com/questions/39109205/javascript-internals-at-what-interval-does-the-event-loop-run?noredirect=1#comment65566030_39109205
Comment: @BugHunterUK I think it's still not a good question for SO. SO questions need to show code, expected behavior, error messages. It's hard to provide an answer if you don't explain the relevance of the question


How can I use tap gestures in parent (with or without consuming them)?

Question: Note: this is very similar to this unanswered question, but that question is mixing events (onTap and onLongPress) and I don't know if that makes a difference or not.
I can react on tap events on an object with .pointerInput and detectTapGestures. With nested composables, the tap is consumed by the innermost child.
For example, if I nest a Box inside another Box, like so:
Box(
    modifier = Modifier
        .pointerInput(Unit) {
            detectTapGestures(onTap = {
                println("TAP in parent Box")
            })
        }
) {
    Box(
        modifier = Modifier
            .pointerInput(Unit) {
                detectTapGestures(onTap = {
                    println("TAP in child Box")
                })
            }
    ) {}
}

Then tapping the box will result in the innermost callback being triggered, showing "TAP in child Box".
How could I intercept the tap in the parent Box? And is there a way to not consume it, such that it goes through to the child?
Comment: You can't do this with default detectTapGestures. Because gestures are propagated from child to parent by default as you can see in [this answer](https://stackoverflow.com/a/70847531/5457853) You need to change PointerEventPass from Main to Initial to change propagation direction from parent to child and write a function that consumes conditionally. I posted similar one for transformGestures, it's not that difficult to write one for tap as well. https://stackoverflow.com/a/76021552/5457853
Comment: It's not based on if they are easy or complex. In the link i posted i'm consuming in parent based on users preference. It applies to every pointerEventChange. If you inspect detectTapGestures source code you will see that with `waitForUpOrCancellation` it checks whether `awaitPointerEvent` is consumed before canceling gesture. This is how gestures mostly work. They check if it's consumed event that propagated to them is consumed before and if it's consumed they either return null or do nothing. This is how you intercept propagation. By consuming instead of letting another gesture gets event.
Comment: Sure. detectTransformGestures checks 2 things for tap. First, if it has been down long enough to be a long press with timeout function, if it has been moved out of Composable  before timeout. If it's up before timeout and up inside Composable it's a tap. There are more details for second tap and pressscope but basically what tap is as you described. And between you can set consume param or PointerEventPass to intercept or change propagation direction
Comment: Thanks for the links! However, it seems like your solutions are intercepting the "complex" gestures (scroll, zoom) and letting the "easy" ones go through (e.g. a tap or a long press), right? In my case I want to consume only the tap. Does that mean that I need to implement my own timer there? I'd like my custom tap to use the same timing as the default ones, though...
Comment: I understand that, but it seems like your code is lower level than a "tap". I can detect a "down" and an "up", but not a "tap". So I assume that to detect a tap, I need to somehow detect a "down", start a timer, and if it goes up fast enough I consume both events and make that a tap? It's not completely clear to me yet.
Comment: I posted a custom long press to detect if gesture has ended. They are all similar. https://stackoverflow.com/a/75781146/5457853
Comment: And code is not lower than tap. That's how you do transform functions. Basics are same for almost every gesture. Get awaitFirstDown, then awaitPointeEvent or if you need second down get another awaitFirstDown and implement your logic between. Get zoom, centroid, rotation, etc., get time for down, consume/intercept or change propagation direction are implementation details based on your logic.
Comment: I got something to do roughly what I want (still working into detecting the double tap). Feel free to comment there, and thanks a lot for the help @Thracian!
Answer: Following @Thracian's guidance, I got to the following, which detects a tap (making the difference with a "slop" and a long press, but interpreting a double tap as two taps):
suspend fun PointerInputScope.interceptTap(
    pass: PointerEventPass = PointerEventPass.Initial,
    onTap: ((Offset) -> Unit)? = null,
) = coroutineScope {
    if (onTap == null) return@coroutineScope

    awaitEachGesture {
        val down = awaitFirstDown(pass = pass)
        val downTime = System.currentTimeMillis()
        val tapTimeout = viewConfiguration.longPressTimeoutMillis
        val tapPosition = down.position

        do {
            val event = awaitPointerEvent(pass)
            val currentTime = System.currentTimeMillis()

            if (event.changes.size != 1) break // More than one event: not a tap
            if (currentTime - downTime >= tapTimeout) break // Too slow: not a tap

            val change = event.changes[0]

            // Too much movement: not a tap
            if ((change.position - tapPosition).getDistance() > viewConfiguration.touchSlop) break

            if (change.id == down.id && !change.pressed) {
                change.consume()
                onTap(change.position)
            }
        } while (event.changes.any { it.id == down.id && it.pressed })
    }
}

Note that it only consumes the event when the main pointer is released. So the "down" event is passed through to the descendants, as are all the events that are not an "up" event of this same pointer, within the tap timeout and slop limit.


Any idea how to check if a div contains ONLY an image tag inside it?

Question: I've been trying to search this on stackoverflow but the answers arent exactly what im looking for, plus they use jquery. So is there any way of determing if a div element contains only an image element inside it, and therefore returning a boolean?
I have tried things like:

but this returned false. Even if this would work, I'd like it to return true only if there is an image regardless if there is a p tag or something else inside.
Comment: What have you tried so far to solve this on your own?
Comment: seems like it would make sense to do this in React, but we see not code.
Comment: i didnt put code as i dont not know how to approach this
Comment: That makes no sense.... What in the react is actually setting the image/content?
Comment: what do you mean image/content? the source?
Comment: Why do you want to do this exactly? Maybe there's some other way to approach this.
Comment: i want to do this because im building a chat app, and so i want to apply different styles if there is only an image present in that div.
Comment: But aren't you setting the content of that div yourself? Say the images are present in the `images` state (array). You could then use `images.length`. Providing more context might lead to a better solution here.
Comment: I'm retrieving HTML string from firebase, firestore, which is then converted to HTML elements with dangerouslysethtml property inside a div. therefore i want to determine if the innerhtml of the div contains only an image tag, and if it does i want to style that parent div differently.
Answer: I am also new to this world, but messing around a little I created this:
HTML

JS
const container = document.querySelector('.container')

const booleanResult = checkChildElement()

function checkChildElement(){
if(container.childElementCount === 1 && container.children[0].tagName === 'IMG'){
   return true
}
else{
   return false
}
}

console.log(booleanResult)

Comment: how would you do it if there were more than one container, so for example, change the class of the parent div to container and hasImg, and the container that doesnt contain an image, return container.
Answer: Solution

class App extends React.Component {
  state = {
    isImageExist: false,
    totalImages: 0,
    isRender: false,
  };
  checkIsImage(ref) {
    if (ref && !this.state.isRender) {
      let totalImages = Object.entries(ref.children).filter(
        ([key, child]) => child.nodeName === "IMG"
      );
      this.setState({
        totalImages: totalImages.length,
        isImageExist: totalImages.length > 0,
        isRender: true,
      });
      console.log("Total Images", totalImages.length);
    }
  }

  render() {
    return (

 {
          this.checkIsImage(ref);
        }}
      >
        <img
          src={`https://www.gravatar.com/avatar/b4185aac47f6262b40dc8f11535a32c0?s=48&d=identicon&r=PG`}
        >
        <img
          src={`https://www.gravatar.com/avatar/b4185aac47f6262b40dc8f11535a32c0?s=48&d=identicon&r=PG`}
        >

{this.state.totalImages}

    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));

Comment: Why are you writing in class based components? that is so 2018. provide functional components like everyone else its 2021
Comment: @Aviale Right! ,  most of the projects are based on class based components so it's easy for the reader, and of course, FC has lots of advantage over class based, I am one of the hooks lovers <3
Comment: I'd use this if i were familiar with old react, D:. But maybe it will help someone else so thanks!


Pandas : Performing an operation using two dataframes

Question: I have two dataframes as shown below:
df1 =

                        A     B     C      D       E       F
timestamp
2022-04-08 10:07:00     40    50    NaN    50     NaN    NaN
2022-04-08 10:07:01     70    80    80     10     NaN    NaN
2022-04-08 10:07:02     200   220   NaN    10     10     NaN

df2 =

             A_1       B_1

C            10        10
D            20        10
E            30        20
F            5         15

As you can see, the columns C,D,E and F of df1 are index of df2. I want to perform an operation as follows:
For each row in df1, the values in columns C D E and F are checked. If there is a value present in one of the columns, the name of the column is noted. Then the corresponding values for columns A and B are taken. These values are added with the values in A_1 and B_1 of df2 for that particular index (which was noted earlier) and this sum is updated back in df1. The below table might explain the problem better. The expected output is as follows:
df1 =

                        A     B     C      D       E       F    Sum_C  Sum_D   Sum_E   Sum_F
timestamp
2022-04-08 10:07:00     40    50    NaN    50     NaN    NaN    NaN    120     NaN     NaN
2022-04-08 10:07:01     70    80    80     10     NaN    NaN   170     180     NaN     NaN
2022-04-08 10:07:02     200   220   NaN    10     10     NaN    NaN    450     470     NaN

Here,
In the first row of df1, there is a value for column D. The values from column A and B are 40 and 50. Now, since there is a value present in column D of df1, the index D of df2 is selected, the corresponding A_1 and B_1 is noted which in this case is 20 and 10.
All of these values (A + B + A_1 + B_1) is added resulting in a value of 120. This is added in Sum_D column of df1. The rest of the values (Sum_C,Sum_E,Sum_F) are NaN.
Would appreciate if there is an easier way to do this.
Thanks in advance!
EDIT: Instead of adding the values obtained from columns A,B,A_1,B_1, I would like to do the following:
import geopy.distance as distance
P1 = (A,B)
P2 = (A_1,B_1)

Calculate the distance using distance.great_circle(P1,P2) and store this result in df1.
So in the columns Sum_C,Sum_D,Sum_E and Sum_F, instead of adding the values A + B + A_1 + B_1, I would like to do the above operation.
Answer: IIUC, you can use:
d = df1[df2.index].notna()
out = (df1
       .join(d.mul(df2.sum(1)) # add sum from df2
              .add(df1[['A', 'B']].sum(1), axis=0) # add data from A/B
              .where(d)                            # keep only original non-NAN
              .add_prefix('Sum_')
            )
       )

output:
                       A    B     C   D     E   F  Sum_C  Sum_D  Sum_E  Sum_F
timestamp
2022-04-08 10:07:00   40   50   NaN  50   NaN NaN    NaN    120    NaN    NaN
2022-04-08 10:07:01   70   80  80.0  10   NaN NaN  170.0    180    NaN    NaN
2022-04-08 10:07:02  200  220   NaN  10  10.0 NaN    NaN    450  470.0    NaN

Comment: then it might be more tricky, probably worth asking a separate question with all the relevant details
Comment: Thank you! In this case, its just calculating sum. But If I have to perform a bit advanced mathematical operation, how do I alter this?
Comment: Well, hard to know without more details. This could be an easy change or a completely different strategy... Maybe this should be a follow up question?
Comment: Well, its just a small operation using the geopy.distance and I have mentioned it in the edit.
Comment: Provided all the relevant details in this https://stackoverflow.com/questions/72200861/performing-an-operation-using-two-dataframes-using-pandas


Open Atrium permission issue

Question: I've added new roles and give it to them a permissions to create content and for some content... and fields but not work with open atrium.
Please help!
Answer: My guess is that you're using the general drupal roles and permissions rather than the organic_groups ones.  Start by reading https://www.drupal.org/node/2340349, and then if you are still stuck, clarify exactly roles and permissions you've been modifying.

Open Atrium permission issue


My throat hurts when I sing

Question: Every time I sing, my throat ends up hurting and I can't figure out why. My vocal teacher doesn't know why either so that doesn't help me at all. She said she thought that maybe I was trying to be too loud when I start singing and she's right.
I try to be louder than I can be, but I tried singing softer and it still hurts, but I don't think I know how to sing softly because then I end up being breathy and I think that's why it hurts.
It's hard to explain where it hurts too. It's kind of in the back of my throat where my soft pallet is but I have no idea how to fix it. I think I'm using my diaphragm and I do lift my soft pallet (but maybe I lift it too much?). I would say that maybe I'm just tensing up a lot and straining but I don't know what it is that I need to relax.
Comment: Go and see a doctor. You may have a medical condition that requires treatment. And while you are at it, if your vocal teacher cannot sympathize and cannot offer any help, then perhaps you need a different vocal teacher.
Comment: Yes. A doctor is a very good idea. We can't diagnose you here, we can give you tips for recovering from an ailment.
Answer: You may already know about this, but it may help: when singing, you ought to use abdominal breathing instead of thoracic breathing. When singing, practice exclusively abdominal breathing, and your voice shouldn't hurt. Moreover, it should allow you to sing far louder without effort.
Abdominal breathing is how we breathe naturally when we sleep: only the belly moves, in a repetitive up and down fashion; you can feel it with your hand to be sure you are doing it right.
When singing, you must feel that the actual power of your voice comes from your belly, not from your throat. Your throat must not "push", not produce the power, but let it flow.
Answer: If a medical problem is ruled out, I suggest making sure to drink enough water throughout the day - 8 cups at least. I can tell you from personal experience, once I became aware of how little water I was drinking and started drinking more, it had a major positive impact not only on my singing voice, but also on my speaking voice.
The other thing I would tell you is make sure to use 'cover' on your high notes - not doing so leads to strain and pain (of course this needs to be developed under the guidance of a teacher).
Here is a demonstration by Pavarotti -
Answer: See a speech pathologist: get scoped (a local university with a vocal program should be able to recommend one in your area).  Plus it's fun to see your vocal cords!
Comment: The pathologist may recommend seeing an otolaryngologist

My throat hurts when I sing


How to find reason for system reboot or shutdown in ubuntu 16.04 system?

Question: my ubuntu 16.04 server occassionaly reboots itself and i dont have a clue why? below is the syslog file content which have keyword named Shutdown
<code>Nov 21 13:51:42 AB-active-server systemd[1]: Created slice User Slice of support.
Nov 21 13:51:42 AB-active-server systemd[1]: Starting User Manager for UID 1000...
Nov 21 13:51:42 AB-active-server systemd[1]: Started Session 1196 of user support.
Nov 21 13:51:42 AB-active-server systemd[18340]: Reached target Sockets.
Nov 21 13:51:42 AB-active-server systemd[18340]: Reached target Paths.
Nov 21 13:51:42 AB-active-server systemd[18340]: Reached target Timers.
Nov 21 13:51:42 AB-active-server systemd[18340]: Reached target Basic System.
Nov 21 13:51:42 AB-active-server systemd[18340]: Reached target Default.
Nov 21 13:51:42 AB-active-server systemd[18340]: Startup finished in 15ms.
Nov 21 13:51:42 AB-active-server systemd[1]: Started User Manager for UID 1000.
Nov 21 13:51:42 AB-active-server console-kit-daemon[21735]: (process:18348): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failed
Nov 21 13:51:42 AB-active-server console-kit-daemon[21735]: missing action
Nov 21 13:51:44 AB-active-server systemd[1]: Stopping User Manager for UID 1000...
Nov 21 13:51:44 AB-active-server systemd[18340]: Stopped target Default.
Nov 21 13:51:44 AB-active-server systemd[18340]: Reached target Shutdown.
Nov 21 13:51:44 AB-active-server console-kit-daemon[21735]: (process:18386): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failed
Nov 21 13:51:44 AB-active-server console-kit-daemon[21735]: missing action
Nov 21 13:51:44 AB-active-server console-kit-daemon[21735]: console-kit-daemon[21735]: GLib-CRITICAL: Source ID 739 was not found when attempting to remove it
Nov 21 13:51:44 AB-active-server systemd[18340]: Starting Exit the Session...
Nov 21 13:51:44 AB-active-server console-kit-daemon[21735]: GLib-CRITICAL: Source ID 739 was not found when attempting to remove it
Nov 21 13:51:44 AB-active-server systemd[18340]: Stopped target Basic System.
Nov 21 13:51:44 AB-active-server systemd[18340]: Stopped target Timers.
Nov 21 13:51:44 AB-active-server systemd[18340]: Stopped target Sockets.
Nov 21 13:51:44 AB-active-server systemd[18340]: Stopped target Paths.
Nov 21 13:51:44 AB-active-server systemd[18340]: Received SIGRTMIN+24 from PID 18387 (kill).
Nov 21 13:51:44 AB-active-server systemd[1]: Stopped User Manager for UID 1000.
Nov 21 13:51:44 AB-active-server systemd[1]: Removed slice User Slice of support.
</code>
the server's disk partitions have 60%+ storage free and inodes are used 1% only
Memory is 60G and intel Intel(R) Xeon(R) CPU E5-2620 v4 @ 2.10GHz
Answer: If I have an unexplained shutdown I go looking in my logs, all of them, they are likely the only chance you have to find out what happened. I look in the system log and find where it started to boot and then look at the earlier entries.
Sometimes there is no smoking gun, then you can ask your DC if they had a power event and to check their equipment. I recently has a server go offline unexpectedly a couple of times and it turned out to be a faulty rack PDU.
Comment: i looked into all logs with `egrep -ir "(shut|reboot)" /var/log/* ` and it all points down to syslog and old rotated syslog which all have above logs. Iguess there might be power issue in the DC its hosted
Comment: You have to find where the system boots and work backwards. There may be reasons that the system crashed that don't play nice by leaving a message containing shut|reboot


Process multiple csv files and store data in separate text files (removing spaces and new lines) using Powershell

Question: I am struggling to get this script work.
I am trying to process all csv files (one at a time) using powershell and save each csv file as a separate text file.
In the text file, i am looking to have all the IP's in a single line separated by a comma (for example 192.168.73.44,192.168.75.224,192.168.76.45,192.168.77.105,192.168.77.237,192.168.78.33,192.168.78.92)
So this script should extract each ipv4address column value from a particular csv file and add a comma "," after every IP address and append all the IP's from that particular csv to a text file.
My script is processing the csv's and generating the text files but it is only writing the first IP found in csv to a text file.
Could you please help me out here?
<code>Get-ChildItem C:\Temp\Qualys\All\AssetGroups\*.csv | Foreach-Object {

  $basename = $_.Name

  $detail = import-csv $_

 foreach ($csv in $detail) {

 $Outputs =@()
 $field = $csv.ipv4address

 $field = $field + ","
 $Outputs +=$field

 }

$Outputs | Out-File "C:\Temp\Qualys\All\AssetGroups\Textfiles\$basename.txt"

$regexA = "(\s,)"

$regexB = "\s"

(Get-Content C:\Temp\Qualys\All\AssetGroups\Textfiles\$basename.txt | Out-String) -replace $regexA,' ' -replace "`r?`n(?!`r?`n)"  -join ' ' -replace $regexB, ''|

Set-Content C:\Temp\Qualys\All\AssetGroups\Textfiles\$basename.txt

$b = Get-Content -Path C:\Temp\Qualys\All\AssetGroups\Textfiles\$basename.txt
@(ForEach ($a in $b) {$a.Replace(' ', '')}) > C:\Temp\Qualys\All\AssetGroups\Textfiles\$basename.txt
}
</code>
IPs.csv
Comment: Could you share the CSV file, for us to have some sample data to work with?
Comment: Hi Motz, I have uploaded csv on this link https://drive.google.com/file/d/1kY3VIwMiBauESgtfm0YE9QZyqkPXWpXW/view?usp=sharing
Answer: After looking at your CSV, I figured this would just be easier to re-write. It is a lot easier to follow than what you were doing.
<code>$skips = $null, '', ' '
Get-ChildItem C:\Temp\Qualys\All\AssetGroups\*.csv| ForEach-Object {
    $csv = import-csv $_.FullName
    $IPArray = @()
    Foreach($ip in $csv) {
        if(!($ip.ipv4address -in $skips)) {
            $IPArray += $ip.ipv4address
        }
    }
    $IPArray -join ','| Out-File C:\Temp\Qualys\All\AssetGroups\Textfiles\$($_.BaseName).txt
}
</code>
Comment: Hi Drew, tried this but it still gives the same result.
Comment: Re-wrote the entire thing, works on my end now, based on the CSV you provided.
Comment: Hi Drew, This works perfect, just one thing, if csv has some blank values in IP column the end result will look like something as below: is there a way we can remove null values in the same code you provided? 10.190.83.208,10.190.54.237,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,10.190.174.125,10.190.175.210 so the result looks something like 10.190.83.208,10.190.54.237,10.190.174.125,10.190.175.210
Comment: @Analyst I have updated the code for you. Just got back into work so sorry for the delay.
Comment: Awesome Drew, Thanks so much


How to apply Euler-Lagrange equation when end points are not fixed

Question: How do you apply Euler-Lagrange equations when you want to minimise the cost of travelling a distance of $L$ from a certain point, $0$, given some cost function $C(t)=f(y,y')$?
My trouble with this is that the derivation of Euler-Lagrange equations required a boundary term to be $0$, and to achieve this we assumed the boundary was fixed. Here we have some integral $$\int_0^{T}f(y,y')\,dt$$ but $\delta y(T)$ is not fixed.
Comment: This is called variable-endpoint problems. See e.g. http://liberzon.csl.illinois.edu/teaching/cvoc/node32.html ; http://chilli.open.ac.uk/dr9/m820-block3.pdf
Answer: The boundary terms don't necesarily need to be 0, when the boundary terms are not given to be zero extra boundary conditions arise. The best way to see this is to derive the Euler-Lagrange Equations.
$$min\int_0^T f(y,y')dt$$
We want to find the optimal $y$ let's call it $\tilde{y}$. We can say
$$y=\tilde{y}+\alpha v$$
$$y'=\tilde{y}'+\alpha v'$$
Where $v$ is an "admissible variation" and $\alpha$ is just a scalar multiplier. All we are really saying is that any $y$ can be expressed as the optimal $y$ plus the variation from the optimal. Now, since we want our integral to be minimized when $\alpha=0$ we can state that
$$\frac{d}{d\alpha}\int_0^T f(\tilde{y}+\alpha v,\tilde{y}'+\alpha v')dt|_{\alpha=0}=0$$
From calculus we remember that
$$\frac{df}{d\alpha}=\frac{\partial f}{\partial y}\frac{d y}{d \alpha} + \frac{\partial f}{\partial y'}\frac{d y'}{d \alpha}$$
Thus our equation becomes
$$\int_0^T \frac{\partial f}{\partial y}(\tilde{y},\tilde{y}')v+\frac{\partial f}{\partial y'}(\tilde{y},\tilde{y}')v'dt=0$$ Note that I have set the alphas to 0. From this point on all my $y$s are really$\tilde{y}$ but i will neglect the tildes for the sake of cleaner notation.  So we have the equation
$$\int_0^T \frac{\partial f}{\partial y}v+\frac{\partial f}{\partial y'}v'dt=0$$
We don't like having derivatives of variations so we will use product rule (aka integration by parts) to get rid of them.
$$\frac{\partial f}{\partial y'}v'=\frac{d}{dt}(\frac{\partial f}{\partial y'}v)-(\frac{d}{dt}\frac{\partial f}{\partial y'})v$$ Pluging this back in to the integral and simplifying we get
$$\int_0^T v(\frac{\partial f}{\partial y}-\frac{d}{dt}\frac{\partial f}{\partial y'})dt + (\frac{\partial f}{\partial y'}v)|_0^T=0$$
Now, we are gonna set each of the parts equal to zero since we don't have much control over $v$. From setting the integral equal to zero we get our classic euler lagrange equation
$$\frac{\partial f}{\partial y}-\frac{d}{dt}\frac{\partial f}{\partial y'}=0$$
Now for the boundary term.
If we were given $y$ at $0$ and $T$, $v$ would have to be zero there since y does not vary. However if we are not given BCs at both ends then we still need that term to be zero two more conditions can arise.
$$\frac{\partial f}{\partial y'}(t=T)=0$$
and
$$\frac{\partial f}{\partial y'}(t=0)=0$$
If you are given a boundary condition at only one end (for example at 0)only use the extra BC for the other end (T in our example). One last note, the boundary conditions that we just got are sometimes called natural boundary conditions since they arise naturally from the derivation, while boundary conditions you are explicitly given are called essential boundary conditions.


presentViewController shows not all elements on presented view controller

Question: I encountered a problem while trying to present a new view controller within a storyboard using following code:
    let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("ViewControllerIdentifier")
    self.presentViewController(viewController!, animated: true, completion: nil)

The view controller does appear, but shows for some reason only two buttons, no other elements.
What have I tried so far:

Loading the view controller as initial view controller to see if the
problem remains.
No, all elements are at the right position.
Switching animated from true to false. Problem still remains
Printing the hidden attribute as well as x and y positions. Hidden
is false, and the positions are what they are supposed to be
Cleaning and rebuilding the project, since this seems to fix 99% of
all strange bugs based on my experience. Sadly this helped not this
time
Setting hidden first on true, then on false. Resetting the attribute
does not help.
Using CFRunLoopWakeUp(CFRunLoopGetCurrent()) . Does not help
either.

I have a simple drawing of what my view looks like attached.

As stated, the view controller is shown perfectly fine when I load it as initial view controller, but only the buttons are shown when using the code above.
ViewDidAppear is called as well.
I am using Xcode Version 7.2.1
EDIT:
As requested by comment, this is my code for the view controller to be presented:
import UIKit

class myViewController : UIViewController {

    @IBOutlet weak var myImage: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }

    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask    {
        return UIInterfaceOrientationMask.Portrait
    }

}

Edit:
I found a solution to this problem:
By creating the transition within the following block.
dispatch_async(dispatch_get_main_queue(),^{

});

It appears that my problem was, that the lines that trigger said transition weren't executed on the UI thread. I still have no idea why this lead to the behaviour explained above, but at least there is a solution.
Comment: Click and select each UI Controls in Storyboard ViewController file.
Go to Editor->Arrange->Send to Front. Try doing this.
Comment: can you show the code in the viewController being presented?
Comment: @Ted I edited the question to show the code, but as you can see it is nothing impressive. I just turned off the landscape mode so far.
Comment: @Vignesh This made no difference.
Comment: @Nerethar did you add any constraints? if you did, set constraints to all UI controls. and try running
Comment: @Vignesh Yes, I did set them up manually and they work just fine when I start the view controller without this code.
Answer: In my experience problems like this can be down to your auto layout constraints being messed up or not quite as you need them (although the fact that it presents correctly when it is the default might suggest I am not headed down the right path).
Are there any warnings in the storyboard editor that suggest the constraints are not correct? I would also suggesting using the view debugging feature to help troubleshoot. Click on the circled icon when your app is running to show your view hierarchy and then try to find the views you think should be there. It also allows you to look at constraints, so that might help with point 1 above as well.
Comment: I set the constrains myself manually, and they work fine. I could see it while loading the view as initial view. I also get no warnings or errors regarding constrains. Using the debugging with this icon I see my view controller without the labels (but I can see where they are placed and I see the text in the window to the right). The image views are shown correctly in debug.
Comment: OK...when, i.e. in which function, are you calling the methods to present the VC in question?


Catalan numbers: Number of different arrangements for 2 different kinds of parentheses

Question: Let's say I have () and [] for parentheses. How many different balanced arrangements do I have for them?
I know how to calculate with 1 type of parentheses but not for more than 1.
In general, for n different kinds of parentheses, how do I calculate the different balanced arrangements?
Comment: To be crystal clear, does `([)]` count as balanced, or not?
Comment: It does! Although I have another question where ([)] isn't balanced, so I'd like both answers for both situations.
Answer: If you only require that the parentheses and square brackets be balanced independently, so that <code>([)]</code> counts as balanced, it's not too hard. Say that you have $m$ pairs of parentheses and $n$ pairs of square brackets. There are $C_m=\frac1{m+1}\binom{2m}m$ balanced strings of the parentheses and $C_n=\frac1{n+1}\binom{2n}n$ balanced strings of the square brackets, and you can interlace the two strings arbitrarily to form a string of length $2m+2n$. There are $\binom{2(m+n)}{2m}$ ways to choose which $2m$ positions in the string get the parentheses, so there altogether
$$C_mC_n\binom{2(m+n)}{2m}=\frac1{(m+1)(n+1)}\binom{2m}m\binom{2n}n\binom{2(m+n)}{2m}$$
of these weakly balanced strings. The total number of weakly balanced strings of length $2\ell$ is then
$$\sum_{m=0}^\ell C_mC_{\ell-m}\binom{2\ell}{2m}\;.$$
If we require the stronger kind of balancing, the calculation is rather different and, perhaps surprisingly, a good bit nicer. We can start with any of the $C_\ell$ balanced strings of square brackets and then simply choose $m$ of the balanced pairs to convert to parentheses. That can be done in $\binom{\ell}m$ ways, so we get a total of
$$C_\ell\binom{\ell}m=\frac1{\ell+1}\binom{2\ell}\ell\binom{\ell}m$$
of these strongly balanced strings with $m$ pairs of parentheses and $n=\ell-m$ pairs of square brackets, and the grand total is then
$$C_\ell\sum_{m=0}^\ell\binom{\ell}m=2^\ell C_\ell=\frac{2^\ell}{\ell+1}\binom{2\ell}\ell\;.$$