google route peering as nexthop

Question: Using the google cloud web interface for add a custom route with a peering as nexthop,But in this interface and in gcloud too, we can select only as next hop:
<code>--next-hop-address=NEXT_HOP_ADDRESS
--next-hop-gateway=NEXT_HOP_GATEWAY
--next-hop-ilb=NEXT_HOP_ILB
--next-hop-instance=NEXT_HOP_INSTANCE
--next-hop-vpn-tunnel=NEXT_HOP_VPN_TUNNEL)
--next-hop-ilb-region=NEXT_HOP_ILB_REGION]
--next-hop-instance-zone=NEXT_HOP_INSTANCE_ZONE]
--next-hop-vpn-tunnel-region=NEXT_HOP_VPN_TUNNEL_REGION
</code>
But if you do a vpc peering with automatic import and export routes, google cloud create ruotes using the peering as follow:
peering-route-c1c2eo5fcx1dfd1b  my-vpc  10.0.1.0/27   vpc-peering                          1000
My question is: is there anyway to create a custom route using the peering as nexthop?
Because event from google api the option exists:
<code>NextHopPeering
</code>
https://developers.google.com/resources/api-libraries/documentation/compute/v1/csharp/latest/classGoogle_1_1Apis_1_1Compute_1_1v1_1_1Data_1_1Route.html
Answer: Currently that feature is not available, however there is a feature request already created.
I share you the   link  to the public issue tracker. I suggest to star it and comment it so google can know that there are more customers requesting this feature.
Comment: Thanks, for the information :)

google route peering as nexthop


Uncaught TypeError: Cannot read property '0' of undefined - in jqGrid Spring MVC

Question: I got the message : Uncaught TypeError: Cannot read property '0' of undefined in jqGrid.min.js . When I submit to update data from grid.
my script:
$('#list-student').jqGrid({
    url: 'GetAllStudent',
    datatype: 'json',
    colNames:['ID','Student', 'Birth day', 'Is Male ?','Province'],
    colModel:[
        {name:'id',index:'id', editable:false,width:100, align:'center'},
        {name:'name',index:'name',editable:true, width:240},
        {
            name:'birth',
            index:'birth',
            editable:true,
            width:200,
            align:'center',
            editoptions:{
                size:12,
                dataInit:function(el){
                    $(el).datepicker({dateFormat:'yy-mm-dd',
                        beforeShow: function(){
                            $('.ui-datepicker').css({'font-size': 11, 'line-height': 1.2})
                            }
                    });
                }
            },
            editrules:{required:true}
        },
        {name:'male',index:'male', editable:true, formatter:'checkbox',width:100, align:'center',edittype:'checkbox',editoptions:{value:'true:false'}},
        {name:'homeTown.nameProvince',editable:true, index:'province', align:'center',edittype:'select',editoptions:{dataUrl:'GetAllProvinceHTML'}}
    ],
    jsonReader : {repeatitems:false},
    rowNum: 10,
    rowList:[10,20,30],
    pager: '#pager',
    sortname: 'id',
    viewrecords: true,
    height: 'auto',
    width: 'auto',
    sortorder: 'asc',
    loadonce: true,
    caption:'List Students',
    editurl: 'EditStudent'
});

$('#list-student').jqGrid(
    'navGrid',
    '#pager',
    {view:true},
    {
        reloadAfterSubmit:false,
        closeOnEscape:true,
        jqModal:true,
        afterSubmit:function(response, post_data){
            console.log(response.responseText);
        },
        closeAfterEdit: true
    }, // edit options
    {reloadAfterSubmit:false,jqModal:true, closeOnEscape:true,bottominfo:'Fields marked with (*) are required', closeAfterAdd: true}, // add options
    {reloadAfterSubmit:false,jqModal:true, closeOnEscape:true}, // del options
    {closeOnEscape:true}, // search options
    {jqModal:true,closeOnEscape:true} // view options
);

in Spring Controller
package controller;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Province;
import model.ProvinceService;
import model.Student;
import model.StudentService;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value="PostMes", method = RequestMethod.POST)
public class StudentController {
    @RequestMapping(value="Get",method = RequestMethod.GET)
    public String abc(){
        return "Manage";
    }
    @RequestMapping(value="GetAllStudent",method = RequestMethod.GET)
    public @ResponseBody List<Student> getAllStudent(){
        StudentService sts=new StudentService();
        List<Student> list= sts.getAllStudents();
        return list;
    }
    @RequestMapping(value="GetAllProvince",method = RequestMethod.GET)
    public @ResponseBody List<Province> getAllProvince(){
        ProvinceService sts=new ProvinceService();
        List<Province> list= sts.getAllProvinces();
        return list;
    }
    @RequestMapping(value = "GetAllProvinceHTML", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public  @ResponseBody String getAllProcinveHTML(HttpServletResponse response){
        ProvinceService sts=new ProvinceService();
        List<Province> list= sts.getAllProvinces();
        String returnString="";
        for(Province pro:list){
            returnString+="<option id='"+pro.getId()+"'>"+pro.getNameProvince()+"</option>";
        }
        returnString="<select class='provinceGroup'>" + returnString + "</select>";
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        return returnString;
    }
    @RequestMapping(value = "EditStudent",method = RequestMethod.POST)
    public @ResponseBody List<Student> editStudent(HttpServletRequest request, HttpServletResponse res){
        System.out.println(request.getParameter("id"));
        System.out.println(request.getParameter("oper"));//what operation we re doing example: "add" , "edit"
        System.out.println("Controller recieved");
        List<String> returnList=new ArrayList<String>();
        List<Student> list=new ArrayList<Student>();
        Student st=new Student();
        st.setName("Shayne");
        list.add(st);
        list.add(st);list.add(st);list.add(st);list.add(st);
        return list;
    }
}

When I edit a row, and click submit => in controller received request , but after sent response to client I got message "Uncaught TypeError: Cannot read property '0' of undefined in jqGrid.min.js"
my include :

Comment: Which version of jqGrid you use? Could you repeat the test with `jquery.jqGrid.src.js` instead of `jquery.jqGrid.min.js` and include the line number of `jquery.jqGrid.src.js` where the error take place?
Comment: @Oleg I replaced by jqGrid.src.js and still have this error in line 7936:

jqGrid.src.js:7936 Uncaught TypeError: Cannot read property '0' of undefined
Comment: I repeat my previous question: **Which version of jqGrid you use?**. Neither jqGrid 4.7 nor 4.6 have suspected lines in the line 7936.
Comment: srr, I forgot give the version! My jqGrid version 4.7
Comment: @Oleg : I found solution for this issue, I removed

afterSubmit:function(response, post_data){                            console.log(response.responseText);

and it's working fine! Can you explain for me please ?
Comment: Sorry, but the line 7936 of jqGrid 4.7 contains only `}`. It can't produce the error "Cannot read property '0' of undefined". So I do suppose that you use another version of jqGrid or the error was in another line. About `afterSubmit`. You can just add any callback in the grid with `console.log` or something like that. You have to hold the rules of *the callback*. For example `afterSubmit` should return array with 1 till 3 items. In case of no error detected you should use `return [true];` from `afterSubmit`.
Comment: About the error "Cannot read property '0' of undefined". I do remind about such error in some old version of jqGrid. The reason was `dataInit` callback was called *multiple times* and one time it will be called erroneously with `el` as absolutely wrong parameter. It was fixed by me by adding `dataInit` in `setAttributes` (see [the line](https://github.com/tonytomov/jqGrid/blob/v4.7.0/js/grid.common.js#L312)) if I remind correctly the problem.
Comment: @Oleg : thanks for your help. all are working fine ^^
Answer: the afterSubmit must return an array for instance :
afterSubmit: function()(response, postdata) {
   var res = $.parseJSON(response.responseText);
   if(YOUR_CONDITION_NOT_SATISFIED) {
        return [false,'MY ERROR MESSAGE'];
    }
    else {
        return [true];
    }
}


How to use np.random.uniform() for real world examples

Question:
What I tried
from numpy import random
import matplotlib.pyplot as plt

import seaborn as sns

sns.distplot(random.uniform(0,30, 5), hist=True)

plt.show()

Result which I got
Here its showing 8% and 12%, but my required answer as according to manual prediction is 16%. I think I am confused about the size parameter in `random.binomial()
Comment: you have density of probability on negative values, I dont understand what you are doing but someone can not wait for -5 minutes so whatever you are doing is wrong.
Answer: From what I understand you want to simulate the result.
Try the following
import numpy as np

# sample 100k uniform random values (it can be any large number) from 0 to 30
waiting_time = np.random.uniform(0, 30, size = 100_000)

# caclulate the proportion that are between 10 and 15
np.mean((waiting_time >=10) & (waiting_time <= 15))
# will be around 0.166 i.e. around 16.6%.

Plot
import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(waiting_time)
plt.show();

# OR
import matplotlib.pyplot as plt
plt.hist(waiting_time);


Wrap comment replies in a collapsible fieldset

Question: I found an article about wrapping all comments (http://scito.ch/content/wrap-comments-collapsible-fieldset), but I just want to wrap comment replies in a collapsible fieldset.
How do I achieve this?
Answer: Implement hook_form_alter() or hook_form_FORM_ID_alter() and add the collapsible fieldset to the form field.  For example:
function MODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
    //Create the fieldset
    $form['custom_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('My Collapsible Fieldset'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );

    //Move the field into the fieldset
    $form['custom_fieldset']['comment_body'] = $form['comment_body'];

    //Unset the original field
    unset($form['comment_body']);
}

You can set '#collapsed' => TRUE if you want the fieldset to be closed by default.

If you're looking for a Module based approach, you may want to look into the Field group project.
I'm not sure how well this module will get along with the Comment module though.  You may need to implement hook_form_alter() in a custom module or in your theme.
Comment: $form['comment_body'] contain my custom define field,so how can i just warp comment reply?
Comment: Ah, I may have misunderstood your question.  Are you wrapping the actual comments or the reply entry field?
Comment: just the reply entry field.because if many people post a comment reply in the same comment,the comment reply list so long so i want to collapse it
Comment: WIll you add your custom defined code to your question? I think I need to see it to move forward. :)
Comment: i use orginal drupal 7.14 with comment module and zen template.and also install ideal comment.i have not custom defined some code.Thank you again.


ENTITY FRAMEWORK - add-migration Novo Projeto sem renomear tabelas do antigo

Question: Quero compartilhar um banco de dados com alguns projetos.
Já fiz o primeiro projeto com o banco e está ok.
Copiei o projeto para criar outro similar, alterei o prefixo inicial das tabelas Ex: projeto1_cliente, projeto2_cliente e ai que está acontecendo o problema.
Ao gerar o add-migration no novo projeto ele está sugerindo renomear as tabelas do projeto antigo.
Como posso trabalhar distintamente o add-migration nos projetos?
Comment: Como foi feita essa prefixação?
Answer: Use um TableAttribute <code>[Table("NomeTabela")]</code>
<code>@using System.ComponentModel.DataAnnotations.Schema;

[Table("NomeTabela")]
public class NomeClasse
{
    public int ID { get; set; }

    public string Name { get; set; }
}
</code>
Ele é responsável por mapear sua entidade para a tabela com o nome especificado.


How to copy blocks placement and settings between themes?

Question: How can I copy blocks placement and settings between themes?
I've found this module: https://drupal.org/project/blockregion and this code to do it in the database. But both are for D6. How can I do this for D7
First, clear the existing block information for the new theme:
DELETE FROM blocks WHERE theme = 'NEW_THEME_NAME'

Now, copy all the block information from the old theme:
INSERT INTO blocks (module, delta, theme, status, weight, region, custom, throttle, visibility, pages, title, cache) (SELECT module, delta, 'NEW_THEME_NAME', status, weight, region, custom, throttle, visibility, pages, title, cache FROM blocks WHERE theme = 'OLD_THEME_NAME')

Also found this, but for D5: http://pierrerebours.com/blog/duplicating-block-settings-across-themes-drupal
Answer: I changed a little bit the code and it worked:
Before running this code you should be sure that both themes have the same regions and, if needed you will have to create the missing regionsin the new theme.
DELETE FROM block WHERE theme = 'NEW-THEME'

INSERT INTO block (module, delta, theme, status, weight, region, custom, visibility, pages, title, cache, i18n_mode) (SELECT module, delta, 'NEW-THEME', status, weight, region, custom, visibility, pages, title, cache, i18n_mode FROM block WHERE theme = 'OLD-THEME')

Comment: Don't forget to note that it may cause unexpected behaviour if you will insert blocks into regions that does not exist. Region list differ per theme and your query ignores it. It shouldn't cause WSOD, but may cause minor display glitches.
Comment: You are right, I just first created the missing regions in the new theme.


Difference between "mark" and "performance"

Question: The results on IAAF (International Association of Athletics Federations) are varying between mark and performance. What's the difference between them?
An example can be found on an athlete's profile. Compare the "Personal Bests" or "Progression" tab with the "Honours" tab (e.g. Usain Bolt).
Answer: I believe that in this context, "mark" and "performance" are two different names for the same thing, which is the athlete's actual time in the race.
Looking at Usain Bolt's world record time in the 100 m on 16 August 2009 in Berlin, the tables show the same time (9.58 s) on the Personal Best, Progression, and Honours tabs.  The time is also shown on the IAAF records list, where it is listed under the heading of "mark."
Answer: The IAAF doesn't have a formal editorial style guide for the relative use of these terms, so in practice they're interchangeable as Ben Miller answered. I'd be interested to see if there are similar synonyms in French and Italian, as French is also an official language of the IAAF and their primary statisticians are English and Italian.
As terms of art, the two words are often used to distinguish when an athlete appears on e.g. an annual list multiple times: Bolt might have six performances in the ten best for a given year, but for other athletes down the list, only their best mark is listed.
In other contexts, e.g. a field event which is ongoing, an athlete might have three existing marks "on the board", but their performance will be the best of those marks when the competition is completed. But I wouldn't want to suggest either of these as rules which are followed rigorously.

Difference between “mark” and “performance”


Coefficient of variation of log-Gamma distribution

Question: If I have a Gamma distributed random variable $y$:
\begin{equation}
    y \sim Gamma(\alpha, \beta)
\end{equation}
which has coefficient of variation $\frac{1}{\sqrt{\alpha}}$, then what would be the coefficient of variation of $x$, defined as:
\begin{equation}
    x = \ln(y)
\end{equation}
? I have found some information on the log-Gamma distribution, but it isn't clear to me whether the coefficient of variation is just $\ln( \frac{1}{\sqrt{\alpha}})$.
Thanks!
Answer: The logarithm of $Y$ has momentgenerating function
\begin{align}
M(t) &= Ee^{t\ln Y}
\\ &= E(Y^t)
\\ &= \int_0^\infty \frac{\lambda^\alpha}{\Gamma(\alpha)}y^{\alpha + t - 1}e^{-\lambda t}dt
\\ &= \frac{\lambda^\alpha\Gamma(\alpha+t)}{\Gamma(\alpha)\lambda^{\alpha+t}}
\\ &= \frac{\Gamma(\alpha+t)}{\Gamma(\alpha)\lambda^t}
\end{align}
and cumulant generating function
\begin{align}
K(t)=\ln M(t)=\ln\Gamma(\alpha + t)-\ln\Gamma(\alpha)-t\ln\lambda.
\end{align}
Hence,
\begin{align}
  E(\ln Y)&=K'(0)=\psi_0(\alpha)-\ln\lambda,
\\ \operatorname{Var}(\ln Y)&=K''(0)=\psi_1(\alpha),
\end{align}
and
$$
 \operatorname{CV}(\ln Y)=\frac{\sqrt{\psi_1(\alpha)}}{\psi_0(\alpha)-\ln\lambda},
$$
where $\psi_0$ and $\psi_1$ are the di- and trigamma functions.


Econ.SE Potential Moderator Election -- Community Interest Check

Question: Our longtime colleague Ubiquitous is stepping down as moderator, so let me take a moment to say thanks for your contributions to our site, both as a moderator and as a member. So now the site has two moderators, myself and EconJohn, where it's usual to have three.
Because our site is in Beta, we've never held an official election, though we have had a referendum before. SE Community Managers have suggested though we try to organize an actual election however, to fill the third slot.
To avoid finding ourselves in a situation where an election would fail due to an insufficient number of candidates, I was asked to post this to try to assess community members' willingness to step up and nominate themselves, if and when an actual election's nomination period starts.
Therefore,

Please leave an answer if you'd be willing to run for a moderator position, should we decide to run an election.

Comments on moderating:
What does being a moderator entail?
Being a moderator mostly involves checking in on flags that steadily come in every day, usually not for very long. Rarely have I spent more than an hour a day having to moderate, and usually it's shorter. Sometimes when I wasn't sure what to do, especially when I was newer, I've had to go to the Teacher's Lounge (a private chat room with all mods) to ask the community of mods what they think would be an appropriate course of action. There's also a lesser used private chat room for just Econ mods, which I've used on occasion, but now I prefer different means of communication (more on this later).
StackOverflow has a private Q+A section for just moderators to ask more involved questions related to moderating. It's also used to communicate network wide things to look out for, like a spike in certain problem users across multiple related networks. So this is a resource that is very helpful for when you are moderating.
Every moderator has their own strengths and weaknesses. The SE team tries to be supportive about helping moderators deal with whatever may come. For example, there's recently been a short online course put out for moderators about conflict resolution. As for between us mods, for me and EconJohn, I've found for the most part we've successfully avoided stepping on each other's toes and working with each other's moderating style. I think EconJohn is a bit more diplomatic and patient than I am, whereas maybe I'm a bit more stern on certain issues, (and have sometimes taken things too seriously). Our different styles are helpful depending on the situation, and in the end I think we're both good influences on each other.
Currently, me and EconJohn communicate through Discord, which I think is an agglomeration benefit for both of us, since we use it for other communications, and it sometimes provides a more direct way for other users we know to get our attention. SE is pretty rigid when it comes to how to communicate with other users, which I think is for the best, but it's nice to have a more informal/flexible place to be able to talk to other users. (As an aside, these venues of course require moderators to keep private user information private.)
Hopefully then this will give you some idea of what it is like to work as a moderator with us existing mods.
What are the benefits and costs to being a moderator?
The benefits of moderating are mostly abstract as far as I can tell. The costs are different for everyone. For the costs, there's the usual staring at flags. Most flags are not too hard to sift through, but sometimes you'll have to make a judgement call as to whether someone is being uncivil or not. Trying to interpret some behavior over text is hard.
Some reviews in the review queues can also be head scratchers and take some time. I've found since a moderator vote, say, in closing a question is instant, regardless of who else has voted, I've taken a more hands off approach to dealing with some questions. That said, if the queue is very large or a specific issue is very urgent, sometimes you find it best to deal with these sooner rather than later.
The tasks that take longest are trying to help correct users in a tactful and helpful way, writing messages to users for particularly bad behavior, and trying to write topics in meta like this to keep the community in the loop. All of these tasks above get better over time as you get a feel for your own jurisprudence and get to know the rhythm of the other mods.
The opportunity cost of being a moderator is higher if you are a busy academic or working professional, so what I expect is that some of the best contributors to the site will find themselves putting their efforts...well, not in moderating. But moderators should have some substantiative knowledge about economics so they don't find themselves out of depth. I can't speak for everyone, but the main benefit to moderating for me is fulfilling some sense of civic duty, or if you so please, altruism in the utility model. :) I just like being able to contribute to the Econ.SE community in this particular way.
I think the ideal moderator probably will not worry too much about any tangible benefits, and will be somewhere in the middle of that broad range of human capital of economic knowledge that will help them to deal with the wide variety of issues that come up in many of these threads. So it'd be someone who is already pretty active and has consistently good contributions, and then would be willing to substitute some of that time more directly into keeping the streets clean out here.
Anyhow, forgive the organization of these comments. I wrote more than I thought I would. Please also refer to EconJohn's written answer below on his view of the costs and benefits of moderating.

(Edit: I have removed the section asking for nominating others, to try and get a better feel for who is interested enough to put themselves out there. Please feel free to continue to put yourself out there.)
NOTE: This is not an official election nomination thread, just a "pulse check" to get a notion of how many people here would be willing to step up.
Comment: Thank you Ubiquitous for your service on the site!
Comment: Hi everyone. You'll surely have noticed that I have neglected my duties here for some time. Having climbed my way up the academic hierarchy and acquired a wide range of professional responsibilities along the way, I find that I have much less time for everything--this site included. My apologies. But it has been gratifying to see the site grow and I hope still to be able to occasionally contribute as a member. Hoping for a new moderator who can help take the community to exciting new places (maybe even out of beta?!) Thanks for the kind words.
Comment: Kitsune or @Econjohn before asking people to nominate themselves it may be good to give a rough approximation of (non-monetary) costs and benefits of being a mod so people know what they get themselves into if they actually decide to run for mod
Comment: Sure, I can add an edit to the post quickly.
Answer:
Please leave an answer if you'd be willing to run for a moderator position, should we decide to run an election.

I would be willing to run if there was an election.

If desired, please leave an answer if there is someone you would like to suggest as a moderator. That person can then express whether or not they'd be interested in running in the moderator election.

Beside myself if there would be election I would be happy to nominate Giskard, Kenny LJ, Herr K,  BKay, Brian Romanchuk or Adam Bailey- all respected users that frequent the site relatively often and any of them would be a good moderator in my opinion if they would be willing to run.

PS: I would also like to thank Ubiquitous for the service. I did not interacted with Ubiquitous much but I seen many answers of the user and they are excellent so I am sure the user deserves high praise for contributions to this site.
Comment: The difference with your community volunteering is that here you are mostly "helping" lazy undergraduates who have no interest in economics but must take a class on Mankiw. SE achieves this through the gamification of the system which extracts value from you exploiting your psychological weaknesses. No different to cocaine addiction. Trust me. In 3 years you will remember this comment.
Answer: If there is a need for a number of candidates, I will also announce my intention to run.
I'm afraid my philosophy of moderation is rather polarizing, so I will lay it out in advance: I'm in favor of more pro-active moderation.
Even though a moderator's vote to close closes the question immediately, in several cases (gibberish questions or clear cut homework questions) I would cast such a vote. This saves other users time, and it also creates a disincentive to post bad questions and provides a quick signal to the user that they need to change something if the question is important to them. It also means the moderator casting the vote will likely err sometimes (type I vs type II error trade-off). I argue that as long as this is rare, it is not a deadly sin, as moderators' votes can be overriden by a vote to reopen.
Another one of my key issues is that if turning comments into answers is an option, I will definitely turn most of Henry's short but insightful comments into answers.
I am also willing to politely correspond with users at some length but not indefinitely. I feel that we are not dealing with life and death issues here; hence users only have a limited claim on the moderators' time. This is not normally an issue, most users are pretty nice, but I have had a few instances of nearly endless comment exchanges on this site, and I will not spend an extra two hours a week chatting to accommodate this small minority.
Disclaimer: I am not a native speaker of English, and I frequently make minor spelling and grammar mistakes.
Answer: Maarten Punt asked about some of the non-monetary costs and benefits of being a mod on this site. For myself I've noticed the following:
Costs

You need to spend some time reviewing flags (most of these flags are actions done by the community to close a question or spam users) This takes around 20-30 minutes a week.
Every now and again (maybe once every 2 years) you have to chat with a disenchanted user regarding their dissatisfaction with this site.

Benefits

Bragging rights to your econ buddies.
If you're someone applying to grad school it signals that you do economics in your spare time so it shows some seriousness regarding further studies (this is speculative benefit though).
I've had a number of conversations with people about this site in the real world, this in my experience makes you perceived as a more interesting person to talk to (this is just my experience though).


udevadm/persistent USB names not working (permission error)

Question: I have 2 identical Bluetooth receivers attached to a Raspberry Pi that
I need to monitor Bluetooth signals at different parts of a room.
Unfortunately, the 2 devices have the same idVendor and idProduct so I
have resorted to using the ATTR{serial} in hopes udev could
distinguish between the two.
The issue is that after I created the udev rules (with new SYMLINK),
only 1 of the Bluetooth receivers shows a DEVLINK of the correct name
I provided in the rule. The other Bluetooth receiver DEVLINK name is
never shown. I have tried a number of things: rebooting, reload udev
rules, restarting udevadm. The console provides the following error
when in dm test (full outputs provided below- I think there
may be a permission issue per the latter part of this output?):
udev_event_execute_rules: no node name set, will use kernel supplied
name 'bus/usb/001/006'
udev_node_add: creating device node '/dev/bus/usb/001/006',
devnum=189:5, mode=01664, uid=0, gid=0
udev_node_mknod: preserve file '/dev/bus/usb/001/006', because it has
correct dev_t
udev_node_mknod: preserve permissions /dev/bus/usb/001/006, 021664, uid=0, gid=0
node_symlink: preserve already existing symlink '/dev/char/189:5' to
'../bus/usb/001/006'
udev_device_update_db: unable to create temporary db file
'/run/udev/data/c189:5.tmp': Permission denied
ACTION=add
BUSNUM=001
DEVNAME=/dev/bus/usb/001/006

If it helps, here is what I did in order to create the rules and
execute the tests:
First, I ran udevadm info to identify differing attributes between the
2 receivers.
The idVendor, serial, and idProduct on 1 device were the following:
ATTR{idVendor}=="0a5c"
ATTR{serial}=="0002723FAE6C"
ATTR{idProduct}=="21e8"

And on the other device...
ATTR{idVendor}=="0a5c"
ATTR{serial}=="5CF37067320A"
ATTR{idProduct}=="21e8"

I created a new rules file called "00-my-usb-device.rules" which looks
like the following:
SUBSYSTEM=="usb", ATTR{idVendor}=="0a5c",
ATTRS{serial}=="5CF37067320A", SYMLINK+="driverBT"

I then created a separate rules filed called "01-my-usb-device.rules"
(originally I had both rules in 1 file but wanted to try all
possibilities. This file looks like the following:
SUBSYSTEM=="USB", ATTR{serial}=="0002723FAE6C",
ATTR{idVendor}=="0a5c", SYMLINK+="rearBT"

Running devadm on the first port with serial num "5CF37067320A" (also
was the first rule that I set):
    udevadm test /devices/platform/bcm2708_usb/usb1/1-1/1-1.5/1-1.5.2
    run_command: calling: test
    adm_test: version 175
    This program is for debugging only, it does not run any program,
    specified by a RUN key. It may show incorrect results, because
    some values may be different, or not available at a simulation run.
parse_file: reading '/etc/udev/rules.d/00-my-usb-device.rules' as rules file
parse_file: reading '/etc/udev/rules.d/01-my-usb-device.rules' as rules file
parse_file: reading '/lib/udev/rules.d/10-local-rpi.rules' as rules file
parse_file: reading '/etc/udev/rules.d/40-scratch.rules' as rules file
parse_file: reading '/lib/udev/rules.d/42-qemu-usb.rules' as rules file
parse_file: reading '/lib/udev/rules.d/50-udev-default.rules' as rules file
parse_file: reading '/lib/udev/rules.d/55-dm.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-cdrom_id.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-fuse.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-gnupg.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-gpsd.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-i2c-tools.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-ifplugd.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-libgphoto2-2.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-alsa.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-input.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-serial.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-storage-dm.rules'
as rules file
parse_file: reading
'/lib/udev/rules.d/60-persistent-storage-tape.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-storage.rules' as
rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-v4l.rules' as rules     file
parse_file: reading '/lib/udev/rules.d/60-python-pifacecommon.rules'
as rules file
parse_file: reading '/lib/udev/rules.d/60-python3-pifacecommon.rules'
as rules file
parse_file: reading '/lib/udev/rules.d/60-triggerhappy.rules' as rules file
parse_file: reading '/lib/udev/rules.d/61-accelerometer.rules' as rules file
parse_file: reading '/run/udev/rules.d/61-dev-root-link.rules' as rules file
parse_file: reading '/lib/udev/rules.d/64-xorg-xkb.rules' as rules file
parse_file: reading '/lib/udev/rules.d/70-uaccess.rules' as rules file
add_rule: IMPORT found builtin 'usb_id', replacing
/lib/udev/rules.d/70-uaccess.rules:13
parse_file: reading '/lib/udev/rules.d/70-udev-acl.rules' as rules file
parse_file: reading '/lib/udev/rules.d/71-seat.rules' as rules file
add_rule: IMPORT found builtin 'path_id', replacing
/lib/udev/rules.d/71-seat.rules:23
parse_file: reading '/lib/udev/rules.d/73-seat-late.rules' as rules file
parse_file: reading '/lib/udev/rules.d/75-cd-aliases-generator.rules'
as rules file
parse_file: reading '/lib/udev/rules.d/75-net-description.rules' as rules file
parse_file: reading
'/lib/udev/rules.d/75-persistent-net-generator.rules' as rules file
parse_file: reading '/lib/udev/rules.d/75-probe_mtd.rules' as rules file
parse_file: reading '/lib/udev/rules.d/75-tty-description.rules' as rules file
parse_file: reading '/lib/udev/rules.d/78-sound-card.rules' as rules file
parse_file: reading '/lib/udev/rules.d/80-drivers.rules' as rules file
parse_file: reading '/lib/udev/rules.d/80-networking.rules' as rules file
parse_file: reading '/lib/udev/rules.d/80-udisks.rules' as rules file
parse_file: reading '/lib/udev/rules.d/85-hwclock.rules' as rules file
parse_file: reading '/lib/udev/rules.d/85-usbmuxd.rules' as rules file
parse_file: reading '/lib/udev/rules.d/90-alsa-restore.rules' as rules file
parse_file: reading '/lib/udev/rules.d/91-permissions.rules' as rules file
parse_file: reading
'/lib/udev/rules.d/95-keyboard-force-release.rules' as rules file
parse_file: reading '/lib/udev/rules.d/95-keymap.rules' as rules file
parse_file: reading '/lib/udev/rules.d/95-udev-late.rules' as rules file
parse_file: reading '/lib/udev/rules.d/97-hid2hci.rules' as rules file
parse_file: reading '/etc/udev/rules.d/99-input.rules' as rules file
parse_file: reading '/lib/udev/rules.d/99-systemd.rules' as rules file
udev_rules_new: rules use 145392 bytes tokens (12116 * 12 bytes),
24358 bytes buffer
udev_rules_new: temporary index used 39920 bytes (1996 * 20 bytes)
udev_device_new_from_syspath: device 0x18b5748 has devpath
'/devices/platform/bcm2708_usb/usb1/1-1/1-1.5/1-1.5.2'
udev_device_new_from_syspath: device 0x18b2258 has devpath
'/devices/platform/bcm2708_usb/usb1/1-1/1-1.5/1-1.5.2'
udev_device_read_db: device 0x18b2258 filled with db file data
udev_rules_apply_to_event: LINK 'driverBT'
/etc/udev/rules.d/00-my-usb-device.rules:1
udev_device_new_from_syspath: device 0x18b3188 has devpath
'/devices/platform/bcm2708_usb/usb1/1-1/1-1.5'
udev_device_new_from_syspath: device 0x18b3640 has devpath
'/devices/platform/bcm2708_usb/usb1/1-1'
udev_device_new_from_syspath: device 0x18b3ae8 has devpath
'/devices/platform/bcm2708_usb/usb1'
udev_device_new_from_syspath: device 0x18b3f88 has devpath
'/devices/platform/bcm2708_usb'
udev_device_new_from_syspath: device 0x18b42d8 has devpath         '/devices/platform'
udev_rules_apply_to_event: IMPORT builtin 'usb_id'
/lib/udev/rules.d/60-libgphoto2-2.rules:11
udev_builtin_add_property: ID_VENDOR=Broadcom_Corp
udev_builtin_add_property: ID_VENDOR_ENC=Broadcom\x20Corp
udev_builtin_add_property: ID_VENDOR_ID=0a5c
udev_builtin_add_property: ID_MODEL=BCM20702A0
udev_builtin_add_property: ID_MODEL_ENC=BCM20702A0
udev_builtin_add_property: ID_MODEL_ID=21e8
udev_builtin_add_property: ID_REVISION=0112
udev_builtin_add_property: ID_SERIAL=Broadcom_Corp_BCM20702A0_5CF37067320A
udev_builtin_add_property: ID_SERIAL_SHORT=5CF37067320A
udev_builtin_add_property: ID_BUS=usb
udev_builtin_add_property: ID_USB_INTERFACES=:ff0101:ffffff:fe0101:
udev_rules_apply_to_event: MODE 0664 /lib/udev/rules.d/91-permissions.rules:36
udev_event_execute_rules: no node name set, will use kernel supplied
name 'bus/usb/001/009'
udev_node_add: creating device node '/dev/bus/usb/001/009',
devnum=189:8, mode=01664, uid=0, gid=0
udev_node_mknod: preserve file '/dev/bus/usb/001/009', because it has
correct dev_t
udev_node_mknod: preserve permissions /dev/bus/usb/001/009, 021664, uid=0,     gid=0
node_symlink: preserve already existing symlink '/dev/char/189:8' to
'../bus/usb/001/009'
link_find_prioritized: found 'c189:8' claiming '/run/udev/links/driverBT'
link_update: creating link '/dev/driverBT' to '/dev/bus/usb/001/009'
node_symlink: preserve already existing symlink '/dev/driverBT' to
'bus/usb/001/009'
udev_device_update_db: unable to create temporary db file
'/run/udev/data/c189:8.tmp': Permission denied
ACTION=add
BUSNUM=001
DEVLINKS=/dev/driverBT
DEVNAME=/dev/bus/usb/001/009
DEVNUM=009
DEVPATH=/devices/platform/bcm2708_usb/usb1/1-1/1-1.5/1-1.5.2
DEVTYPE=usb_device
DRIVER=usb
ID_BUS=usb
ID_MODEL=BCM20702A0
ID_MODEL_ENC=BCM20702A0
ID_MODEL_ID=21e8
ID_REVISION=0112
ID_SERIAL=Broadcom_Corp_BCM20702A0_5CF37067320A
ID_SERIAL_SHORT=5CF37067320A
ID_USB_INTERFACES=:ff0101:ffffff:fe0101:
ID_VENDOR=Broadcom_Corp
ID_VENDOR_ENC=Broadcom\x20Corp
ID_VENDOR_ID=0a5c
MAJOR=189
MINOR=8
PRODUCT=a5c/21e8/112
SUBSYSTEM=usb
TYPE=255/1/1
UDEV_LOG=6
USEC_INITIALIZED=465479898

Running udevadm test on second port (DEVLINK does not exist here as
compared to other device):
udevadm test /devices/platform/bcm2708_usb/usb1/1-1/1-1.5
    run_command: calling: test
    adm_test: version 175
    This program is for debugging only, it does not run any program,
    specified by a RUN key. It may show incorrect results, because
    some values may be different, or not available at a simulation run.
parse_file: reading '/etc/udev/rules.d/00-my-usb-device.rules' as rules file
parse_file: reading '/etc/udev/rules.d/01-my-usb-device.rules' as rules file
parse_file: reading '/lib/udev/rules.d/10-local-rpi.rules' as rules file
parse_file: reading '/etc/udev/rules.d/40-scratch.rules' as rules file
parse_file: reading '/lib/udev/rules.d/42-qemu-usb.rules' as rules file
parse_file: reading '/lib/udev/rules.d/50-udev-default.rules' as rules file
parse_file: reading '/lib/udev/rules.d/55-dm.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-cdrom_id.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-fuse.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-gnupg.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-gpsd.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-i2c-tools.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-ifplugd.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-libgphoto2-2.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-alsa.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-input.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-serial.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-storage-dm.rules'
as rules file
parse_file: reading
'/lib/udev/rules.d/60-persistent-storage-tape.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-storage.rules' as
rules file
parse_file: reading '/lib/udev/rules.d/60-persistent-v4l.rules' as rules file
parse_file: reading '/lib/udev/rules.d/60-python-pifacecommon.rules'
as rules file
parse_file: reading '/lib/udev/rules.d/60-python3-pifacecommon.rules'
as rules file
parse_file: reading '/lib/udev/rules.d/60-triggerhappy.rules' as rules file
parse_file: reading '/lib/udev/rules.d/61-accelerometer.rules' as rules file
parse_file: reading '/run/udev/rules.d/61-dev-root-link.rules' as rules file
parse_file: reading '/lib/udev/rules.d/64-xorg-xkb.rules' as rules file
parse_file: reading '/lib/udev/rules.d/70-uaccess.rules' as rules file
add_rule: IMPORT found builtin 'usb_id', replacing
/lib/udev/rules.d/70-uaccess.rules:13
parse_file: reading '/lib/udev/rules.d/70-udev-acl.rules' as rules file
parse_file: reading '/lib/udev/rules.d/71-seat.rules' as rules file
add_rule: IMPORT found builtin 'path_id', replacing
/lib/udev/rules.d/71-seat.rules:23
parse_file: reading '/lib/udev/rules.d/73-seat-late.rules' as rules file
parse_file: reading '/lib/udev/rules.d/75-cd-aliases-generator.rules'
as rules file
parse_file: reading '/lib/udev/rules.d/75-net-description.rules' as rules file
parse_file: reading
'/lib/udev/rules.d/75-persistent-net-generator.rules' as rules file
parse_file: reading '/lib/udev/rules.d/75-probe_mtd.rules' as rules file
parse_file: reading '/lib/udev/rules.d/75-tty-description.rules' as rules file
parse_file: reading '/lib/udev/rules.d/78-sound-card.rules' as rules file
parse_file: reading '/lib/udev/rules.d/80-drivers.rules' as rules file
parse_file: reading '/lib/udev/rules.d/80-networking.rules' as rules file
parse_file: reading '/lib/udev/rules.d/80-udisks.rules' as rules file
parse_file: reading '/lib/udev/rules.d/85-hwclock.rules' as rules file
parse_file: reading '/lib/udev/rules.d/85-usbmuxd.rules' as rules file
parse_file: reading '/lib/udev/rules.d/90-alsa-restore.rules' as rules file
parse_file: reading '/lib/udev/rules.d/91-permissions.rules' as rules file
parse_file: reading
'/lib/udev/rules.d/95-keyboard-force-release.rules' as rules file
parse_file: reading '/lib/udev/rules.d/95-keymap.rules' as rules file
parse_file: reading '/lib/udev/rules.d/95-udev-late.rules' as rules file
parse_file: reading '/lib/udev/rules.d/97-hid2hci.rules' as rules file
parse_file: reading '/etc/udev/rules.d/99-input.rules' as rules file
parse_file: reading '/lib/udev/rules.d/99-systemd.rules' as rules file
udev_rules_new: rules use 145392 bytes tokens (12116 * 12 bytes),
24358 bytes buffer
udev_rules_new: temporary index used 39920 bytes (1996 * 20 bytes)
udev_device_new_from_syspath: device 0x17a748 has devpath
'/devices/platform/bcm2708_usb/usb1/1-1/1-1.5'
udev_device_new_from_syspath: device 0x177258 has devpath
'/devices/platform/bcm2708_usb/usb1/1-1/1-1.5'
udev_device_read_db: device 0x177258 filled with db file data
udev_device_new_from_syspath: device 0x177db8 has devpath
'/devices/platform/bcm2708_usb/usb1/1-1'
udev_device_new_from_syspath: device 0x178260 has devpath
'/devices/platform/bcm2708_usb/usb1'
udev_device_new_from_syspath: device 0x1786d8 has devpath
'/devices/platform/bcm2708_usb'
udev_device_new_from_syspath: device 0x178a28 has devpath '/devices/platform'
udev_rules_apply_to_event: IMPORT builtin 'usb_id'
/lib/udev/rules.d/60-libgphoto2-2.rules:11
udev_builtin_add_property: ID_VENDOR=050d
udev_builtin_add_property: ID_VENDOR_ENC=050d
udev_builtin_add_property: ID_VENDOR_ID=050d
udev_builtin_add_property: ID_MODEL=0234
udev_builtin_add_property: ID_MODEL_ENC=0234
udev_builtin_add_property: ID_MODEL_ID=0234
udev_builtin_add_property: ID_REVISION=3298
udev_builtin_add_property: ID_SERIAL=050d_0234
udev_builtin_add_property: ID_BUS=usb
udev_builtin_add_property: ID_USB_INTERFACES=:090001:090002:
udev_rules_apply_to_event: MODE 0664 /lib/udev/rules.d/91-    permissions.rules:36
udev_event_execute_rules: no node name set, will use kernel supplied
name 'bus/usb/001/006'
udev_node_add: creating device node '/dev/bus/usb/001/006',
devnum=189:5, mode=01664, uid=0, gid=0
udev_node_mknod: preserve file '/dev/bus/usb/001/006', because it has
correct dev_t
udev_node_mknod: preserve permissions /dev/bus/usb/001/006, 021664, uid=0,     gid=0
node_symlink: preserve already existing symlink '/dev/char/189:5' to
'../bus/usb/001/006'
udev_device_update_db: unable to create temporary db file
'/run/udev/data/c189:5.tmp': Permission denied
ACTION=add
BUSNUM=001
DEVNAME=/dev/bus/usb/001/006
DEVNUM=006
DEVPATH=/devices/platform/bcm2708_usb/usb1/1-1/1-1.5
DEVTYPE=usb_device
DRIVER=usb
ID_BUS=usb
ID_MODEL=0234
ID_MODEL_ENC=0234
ID_MODEL_ID=0234
ID_REVISION=3298
ID_SERIAL=050d_0234
ID_USB_INTERFACES=:090001:090002:
ID_VENDOR=050d
ID_VENDOR_ENC=050d
ID_VENDOR_ID=050d
MAJOR=189
MINOR=5
PRODUCT=50d/234/3298
SUBSYSTEM=usb
TYPE=9/0/2
UDEV_LOG=6
USEC_INITIALIZED=200440100

Answer: Kernel was required. The 2 BT adapters are hooked into a 4-port hub. Once I specified the Kernel in each of the 2 rules, everything worked.
Product and serial were also used to distinguish between the 2 devices (product probably not as necessary since it matches the other BT device, but serial definitely required).


Tentando gerar um gráfico de uma série temporal

Question: Isso foi o que fiz..
<code>#Lê a base de dados
ano1<-read.csv("os dados abaixo...",header = TRUE ,sep=";", row.names=1)

#Cria a série temporal
ano<-ts(ano1[,1],start=c(2009,1), end=c(2010,12),freq=12)

#plota a série
plot(ano,ylab='indice', xlab='ano',main='distribuiçao dos casos')
</code>
Esses são os dados:
<code>##       Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
## 2009  1.6  1.0  0.2  0.0 -0.2  0.1  0.9  1.4  0.8 -0.4 -0.8  0.1
## 2010  1.8  1.2  0.3 -0.1 -0.2 -0.3  1.5  1.9  1.2  0.1 -0.6 -0.5
</code>
Porém ele plota um gráfico "periódico".
Ps.: São vários anos, mas queria aprender nesse 'simples' pra aplicar no outro.

Answer: Minha sugestão seria para você transpor os dados usando o comando t() e, em seguida plotar utilizando o comando matplot() ou ts.plot().
Answer: Você pode fazer usar um for para criar a lista de anos, se os dados tiver em um array, o mesmo sera populado de acordo com o indice
Segue um codigo que fiz em java seguindo um loop
<code>graphDonut = Morris.Donut({
                element: 'hero-donut', // elemento chave de referencia
                data: [// dados do grafico
        <c:forEach items="${valorList}" var="catP">

                    {label: '${catP.categoria}', value: '${catP.porcentagem}'},
        </c:forEach>
                ],
                colors: ['#8bc34a', '#ffc107', '#34495e', '#03a9f4', '#9c27b0', '#90a4ae'], //cores do grafico

                formatter: function (y) {

                    return y;
                }
                , //formatação dos números a exibir
                resize: true // redimensionavel true
            });
</code>
Nele, temos um graphDonut, onde temos categorias e porcentagem, o forEach faz o add das categorias e porcentagem de acordo com um array que fiz no backend. abaixo a estrutura que se repete
<code>{label: '${catP.categoria}', value: '${catP.porcentagem}'},
</code>
Se precisa de algum codigo de referencia em back, pode falar ae. Mesmo que nao esteja usando java vc pode implementar isso com algumas alterações de acordo com a linguagem


Can I drop a variable from a logistic regression, score on the other variables and then add back in for a different model? (See Body)

Question: So what I have is a logistic regression equation with the first variable having a large (not overly so) coefficient ie.
ln(p/1-p) = C + B1V1 + B2V2 + B3V3 + B4V4 +B5*V5
Because this coefficient is so large there is a need to remove this as part of a strategy but we could also try to adjust the power of this variable in the above model. I've considered ridge regression but I think the following method is much simpler and quicker if it indeed works.
My question is can I have the following model with B1*V1 removed:
ln(p/1-p) = C + B2V2 + B3V3 + B4V4 +B5V5
Then convert to a score base on pdo and base score and use this score to go into a new model with the previous first variable ie.
ln(p/1-p) = C + B1.1*(Score calculated from first model) + B1*V1
And would this result in the same model? I am thinking it would not because the iterative process would have less coefficients to optimise and the score from the previous model would be much more predictive than the variable we dropped and used in the second model.
Comment: Please edit the post to include the equation as LaTeX. If
it helps, we have some
[resources on using LaTeX on Cross Validated](https://stats.meta.stackexchange.com/a/1605/155836).
Answer: In most cases, having a variable with a very large $\beta$ in the logistic model, even with $\beta=\infty$, does not cause a problem.  It still leads to the right probability estimate.  Of course we don't really believe the probability to be 1.0, and penalized maximum likelihood estimation will lead to a more reasonable probability.  But if you flip a coin 10 times and get 10 heads the maximum likelihood estimate of P(heads) is 1.0, leading to a log odds of $\infty$.
Large $\beta$ is not a reason to remove a variable from the model.  Only worry about this if you get probability estimates that don't make any sense.
Answer: I don't see why splitting to two linear models will work better. Also, large coefficients are not necessarily a problem. If you are worried about the large coefficient, you can try one of the following (depending on the specific details of your problem)

standartization or normalization - it can improves stability, and can make coefficients smaller.
regularization - it can improve generalization and performance on out of sample data and almost by definition will make coefficients smaller.


Understanding this summation identity

Question: I'm currently reading a book in which part of the solution to the problem involve this identity:
$$\sum_{j=i+1}^{n}j = \sum_{j=1}^{n}j-\sum_{j=1}^{i}j$$
Which I cannot derive myself. The only thing I can do with it is this:
$$\sum_{j=i+1}^{n}j = \sum_{j=1}^{n}j+i = \sum_{j=1}^{n}j + \sum_{j=1}^{i}i$$
Which seems to me completely useless.
Any help in understanding this (as I am unaccustomed to summation manipulation in general) would be greatly appreciated.
I know it's related to " Calculate integer summation when lower bound is a variable " but I still don't see the why.
Answer: We have
$$\sum_{j=1}^{i}j+\sum_{j=i+1}^n j=\sum_{j=1}^n j.\tag{$1$}$$
The result you are looking for follows by subtraction.
If $(1)$ seems unclear, let us take particular numbers, say $i=7$ and $n=19$.
We have
$$\sum_{j=1}^{i}j =\sum_{j=1}^7j=1+2+\cdots+7$$
and
$$\sum_{j=i+1}^{n}j =\sum_{j=8}^{19} j=8+9+\cdots +19.$$
If you add them, you get
$$1+2+\cdots+7+8+9+\cdots +19.$$
This is equal to
$$\sum_{j=1}^{19} j.$$
Remark: Exactly the same argument shows that if $a_1,a_2,\dots$ is any sequence, then
$$\sum_{j=i+1}^n a_j=\sum_{j=1}^n a_j -\sum_{j=1}^i a_j.$$
Comment: Didn't expect answers which would come as quickly and be as good. Thanks.
Answer: Note that
\begin{align}
\sum_{j=1}^{n} j & = 1 + 2 + \cdots + i + (i+1) + (i+2) + \cdots + n\\
& = \left(1 + 2 + 3 + \cdots + i \right) + \left((i+1) + (i+2) + \cdots + n \right)\\
& = \sum_{j=1}^{i} j + \sum_{j=i+1}^{n} j
\end{align}
Hence, we get that $$\sum_{j=i+1}^{n} j = \sum_{j=1}^{n} j - \sum_{j=1}^{i} j$$
Answer: \begin{align}
6+7+8 = \Big(1+2+3+4+5+6+7+8\Big) - \Big(1+2+3+4+5\Big)
\end{align}
That's all there is to it.  Your way of phrasing the question makes me wonder if you think there's something more to it than that.
Comment: I guess that when manipulating new symbols (the Sigma notation isn't exactly new to me but it had never been center stage) their complete meaning isn't immediately apparent. I didn't see it concretely.

Understanding this summation identity


How to set env variables and run multiple commands with PsExec?

Question: How can I run multiple commands with PsExec, and how can I export environment variables?
I can run two commands by doing the below, but when I try to export an environment variable the second command errors out.
Running two commands:
psexec \\servername cmd /c p4 info & dir

^ This works
Trying to export env variable and then run another command:
psexec \\servername cmd /c set P4PORT=xx.xxx.xx.xx & p4 -c client -P ################## -u user diff -f //dir/dir2/dir3/...

^ This errors out on the second command, it complains about the client spec name I'm passing in, but it runs fine if i run just the second command. It's like the first command throws off the second.
Thanks!
Answer: I believe you will find the second command is running on the local machine, not the remote one.  You need to use quote marks like this:
psexec \\servername cmd /c "p4 info & dir"

Comment: perfect, this did it!
Comment: Worked for me, too.  Thank you!


Set of numbers given, find mean and SD of the other

Question: A set of eight numbers has mean 5 and SD 4. The number 21 and another integer n are added to the set. The standard deviation of the set is now 6. Find n and the mean of the set now.
Comment: Finding the sum and the sums of squares, trying to form equations about variance.
Comment: I fooled around some and using SD equal to the square root of $(1/8)\sum(x_i-\bar{x})^2$, got an equation that seems not to give integer $n$. But it was done quickly and I am accident-prone.
Answer: One way to do this is to concoct $8$ numbers which have a mean of $5$ and a standard deviation of $4$.  For example, take
$$
-1,1,3,5,5,7,9,11,
$$
and label these points $x_1 , x_2, \dots , x_8$.  Then, one can easily check:
$$
\frac{1}{8}\sum_{i=1}^8 x_i  = 5
$$
and
$$
\sqrt{\sum_{i=1}^{8} \frac{(x_i - 5)^2}{8 - 1}} = 4.
$$
Adding $21$ and $n$ gives
$$
\mu = \frac{8 \cdot \mu_1 + 21 + n}{10} = \frac{61 + n}{10}.
$$
The new standard deviation is
$$
6 = \sigma = \sqrt{\sum_{i=1}^{8} \frac{(x_i - \mu)^2}{10 - 1} + \frac{(21 - \mu)^2}{10 - 1} + \frac{(n - \mu)^2}{10 - 1}}.
$$
Expanding gives a quadratic equation in $\mu$:
$$\begin{align}
324 = & (-1 - \mu)^2 + (1 - \mu)^2 + (3 - \mu)^2 + 2(5 - \mu)^2
\\
&+ (7 - \mu)^2 + (9 - \mu)^2 + (11 - \mu)^2 + (21 - \mu)^2 + (9 \mu - 61)^2
\end{align}$$
Note that the last term is $(10 \mu - 61 - \mu)^2$ as $\mu_2 = \frac{61 + n}{10}$.  Solving this for $\mu$ yields $\mu = 8$.  Hence, $n = 19$.

Edit: For clarification, this does not totally answer the question at hand.  My example does not prove that $n = 19$ is the only (integer) solution.  However, it is likely that this is the case.  The method I used to find the set of integers which worked was by noticing that we needing to find $8$ squares that sum to $112 = 4^2 \cdot (8 -1)$.  This gave a natural choice of
$$
112 = 6^2 + 6^2 + 4^2 + 4^2 + 2^2 + 2^2 + 0^2 + 0^2
$$
which implied that
$$\begin{array}{c}
 x_1 = 5 - 6
\\
 x_2 = 5 + 6
\\
 x_3 = 5 - 4
\\
 x_4 = 5+4
\\
 x_5 = 5 - 2
\\
 x_6 = 5+2
\\
 x_7 = 5 - 0
\\
 x_8 = 5 + 0
\end{array}$$  This happened to lead to a integral value of $\mu$ and therefore an integral value of $n$.
Comment: This is a proof by "My professor says it must be true", i.e., you do one example and assume it gives the same answer as any other example.
Comment: @Grapth: I never claimed that this solves the complete problem.  Your point is valid in the sense that the question has not been fully answered, but this is not a proof, and hence your comment doesn't apply.
Comment: I wonder why you are dividing by 7, and not by 8 (in your calculation of the standard deviation)? I realize there are circumstances where division by $n-1$ is correct, but I would have thought that in this case $n$ would be the correct denominator.


How to set SelectedItem of a ComboBox when item is not part of the ItemsSource collection?

Question: Following scenario:
<ComboBox ItemsSource="{Binding Path=Names}"
          SelectedItem="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}">
</ComboBox>

Names is a string collection which might change through code in the ViewModel. For example Names could be set to either male names (John, Paul, George) or female names (Mary, Jane, Karen).
Let's assume the male collection is active and the user selects "John" making it the SelectedItem. Now the collection changes to female names. By default the SelectedItem will be set to Null and John will not be displayed anymore. Instead an empty string will be displayed.
What I would like to achieve is that "John" is still visible as SelectedItem although it is not in the collection anymore. However as it is not part of the collection I would like to change the color of the SelectedItem to red.
I have played around with the IsEditable property, but didn't like the changing appearance of the ComboBox. The user should not be able to enter text manually anyway.
I tried to use different templates and styles (e.g. Template, ItemTemplate, ItemContainerStyle), but didn't find a way to use it to my favour.
Is it possible to style the provided ComboBox the way I need it or do I have to create my own user control?
EDIT:
I have found a solution I can live with.
<ComboBox IsEditable="True" IsReadOnly="True"
          ItemsSource="{Binding Path=Names}"
          Text="{Binding Path=Name}">
  <ComboBox.Style>

    </Style>
  </ComboBox.Style>
  <ComboBox.ItemContainerStyle>

  </ComboBox.ItemContainerStyle>
</ComboBox>

In the ViewModel I make sure that the Name property does not change when the Names collection changes. The boolean property IsNameInCollection will be updated when the Name property or the collection changes.
Comment: So you basically want one combobox to act as using 2 comboboxes?
Comment: Actually it's only two in the example given above. In the real application I have many different collections.
Answer: Note: this no a real, working answer / solution, but just some thoughts you might find worth to consider:
First, the SelectedItem will always change to null if the collection changes (either by replacing it with a new collection or clearing and refilling it). So as you are binding to Name property of some object, can you prevent that property from being overridden with null there internally? That way the value might not change in the ComboBox (maybe you also need TwoWayBinding for Name to make the value stick; or even firing a change event, but that depends on some testing).
Second, the rendering needs to change, so the easiest way would be to use the ItemTemplate and a custom IValueConverter implementation to convert the information of the special entry with different color / style. But the downside of this is, that the ItemTemplate will normally be used for every entry, including the current selected.
One way to deal with this is to use an ItemTemplateSelector like described here: http://www.wpftutorial.net/datatemplates.html (section "How to use a DataTemplateSelector to switch the Template depending on the data")
Another way would be to use a container instead of plain string. That container would also hold a boolean value to indicte a different rendering. That boolean value could be used in the ItemTemplate. But in this scenario you need to wrap all string values.
Third, how should the ComboBox react if the selected value is still the old value that is not in the current list, and then the user selects another value. One logic would be that the old value just disappears, but then the user cannot select it back. If it should be still available in the list, then you must somehow add it to the list of current values, but mark it that it is a special value. In both cases you also need a logic that detects later if a value was chosen that is not valid according to the current available list.
I hope this helps to find a working solution.
Comment: 1. I did prevent that the property will be overridden with null, but eventhough the property didn't change when the collection did, the ComboBox didn't show it anymore.  2. So far I wasn't successfull in using the templates to my favour, but I will continue trying.  3. The old value can disappear in that case, so that's not an issue.
Comment: Although you didn't provide a solution, I have marked your answer as accepted, because you gave me some ideas and pushed me in the right direction :-)
Comment: I'm glad that I could help at least a little bit.


How to Create Required validation for radio group and check box list and Textbox in uploaded pdf in docusign using c#.net

Question: I am  displaying  pdf file with docusign integration using c#.
Pdf file actually contains no of Radio buttons(Yes or No) and text fields and signature.
I am trying to implement Required field validation for pdf form fields in docusign integration.But I am unable to get solution for this.
Can any body please give the solution how apply the validations for docusign integration pdf form  using c#.net.
Comment: what do you mean by validation? just to ensure fields are filled? or some other logic?
Answer: If the textbox tab is required tab - it will be validated, to ensure some text was entered. You can also specify maximum length like this:
<code>    Text textTab = new Text();
    textTab.MaxLength = "10";
    textTab.ValidationMessage = "must be at least 10 charchters";
</code>
As for checkboxes, you can make them checked or unchecked by default. There's no validation because they only have 2 states.
Radio buttons, you can group them together and require that exactly one is selected.
<code>    RadioGroup rg = new RadioGroup { Radios = new List<Radio>() };
    Radio r1 = new Radio();
    Radio r2 = new Radio();
    rg.Radios.Add(r1);
    rg.Radios.Add(r2);
</code>


SQL - Substraction using values from previous columns

Question: I  have a query which lists a country name ,total number of customers per country and number of active customers( they exist in the sales table).
I need a column where  the number of  inactive customers should be calculated ,but since one can't use  defined aliases in the same select statement ,I  got stuck
Here is the query:
SELECT  country_name , COUNT(DISTINCT cust.cust_id) AS TOTAL_NUM_CUSTOMERS ,
COUNT(DISTINCT sh.cust_id) AS NUM_ACTIVE_CUSTOMERS

FROM countries ctr JOIN customers cust
ON (cust.country_id = ctr.country_id)
LEFT JOIN  sales sh
ON (sh.cust_id =  cust.cust_id)

GROUP BY  country name

How should I approach this problem ?
Comment: you can subtract the 2 counts in the query.
Comment: Edit your question and provide sample data and desires results.
Comment: COUNT(DISTINCT cust.cust_id) -  COUNT(DISTINCT sh.cust_id)  - Like this ?  I thought so , but SQLDeveloper says it's syntax error  and  wouldn't let me do it for some reason
Answer: Given your approach, you would do:
SELECT ctr.country_name,
       COUNT(DISTINCT cust.cust_id) AS TOTAL_NUM_CUSTOMERS,
       COUNT(DISTINCT sh.cust_id) AS NUM_ACTIVE_CUSTOMERS
       (COUNT(DISTINCT cust.cust_id) - COUNT(DISTINCT sh.cust_id)) AS NUM_INACTIVE_CUSTOMERS
FROM countries ctr JOIN
     customers cust
     ON cust.country_id = ctr.country_id LEFT JOIN
     sales sh
     ON sh.cust_id =  cust.cust_id
GROUP BY ctr.country_name;

For performance, I would suggest doing an aggregation before the join:
SELECT ctr.country_name,
       COUNT(cust.cust_id) AS TOTAL_NUM_CUSTOMERS,
       COUNT(sh.cust_id) AS NUM_ACTIVE_CUSTOMERS
       (COUNT(cust.cust_id) - COUNT(sh.cust_id)) AS NUM_INACTIVE_CUSTOMERS
FROM countries ctr JOIN
     customers cust
     ON cust.country_id = ctr.country_id LEFT JOIN
     (SELECT DISTINCT cust_id
      FROM sales sh
     ) sh
     ON sh.cust_id =  cust.cust_id
GROUP BY country_name;

This removes the need for the count(distinct).
Comment: Thank you , I've  actually reinstalled SQLDeveloper and now the substraction works fine , but  i didn't thought about doing the aggregation before join , thanks again
Answer: Use subquery for this case :
SELECT country_name,TOTAL_NUM_CUSTOMERS,NUM_ACTIVE_CUSTOMERS,
(TOTAL_NUM_CUSTOMERS-ACTIVE_CUSTOMERS) AS INACTIVE_CUSTOMERS FROM (
SELECT  country_name , COUNT(DISTINCT cust.cust_id) AS TOTAL_NUM_CUSTOMERS ,
COUNT(DISTINCT sh.cust_id) AS NUM_ACTIVE_CUSTOMERS
FROM countries ctr JOIN customers cust
ON (cust.country_id = ctr.country_id)
LEFT JOIN  sales sh
ON (sh.cust_id =  cust.cust_id)
GROUP BY  country name ) AS A

Answer: Wrap the query in an outer query; that will let you use the column aliases:
SELECT  t.*,
        TOTAL_NUM_CUSTOMERS - NUM_ACTIVE_CUSTOMERS AS NUM_INACTIVE_CUSTOMERS
FROM    (
  SELECT  country_name,
          COUNT(DISTINCT cust.cust_id) AS TOTAL_NUM_CUSTOMERS,
          COUNT(DISTINCT sh.cust_id) AS NUM_ACTIVE_CUSTOMERS
  FROM    countries ctr
          JOIN customers cust
          ON (cust.country_id = ctr.country_id)
          LEFT JOIN  sales sh
          ON (sh.cust_id =  cust.cust_id)
  GROUP BY  country name
) t


checking how long are comments in a file

Question: I just finished an assingment and according to the instructions I can't have a line of code or comment longer than 120 chars. is there a quick way to check that?
I'm using VSCODE on windows 10. I saw somewhere that I can make a verticle line in the editor to see if a row is too long but I can't find it now.
for example :
// return stack->size since stack->size holds the number of values that can be stored inside the array at a given time.
this comment is 119 chars so it is ok but anything bigger will cause me to lose points.
I know I can hold the last char in the sentence and see the 'col' number in VSCODE, I was hoping for something better.
thanks
Answer: "editor.rulers": [120]
Look at the Editor: Rulers setting:

Render vertical rulers after a certain number of monospace characters.
  Use multiple values for multiple rulers. No rulers are drawn if array
  is empty.

You can change its color or opacity like so  (in your settings.json):
"workbench.colorCustomizations": {
  "editorRuler.foreground": "#ff0000ff",
}

That changes the color to red, the last two hex digits are opacity.  ff is 100% opaque.  So you could try more transparent with #ff000080 for example.  Color and transparency are the only two modifications you can make to rulers.
Comment: Thank you! worked perfectly. is there a way to make the line transparent?
Comment: Transparent?  You wouldn't see it then.
Comment: I mean not solid.. I still want to see the line just don't want it to stand out
Comment: I edited the answer for info on changing the color and/or transparency of rulers.


Angular Material - Datepicker make max value a month from selected value

Question: I have two datepickers. One to pick the "fromDate" and the other to pick the
"toDate". I am excepting the user to first select fromDate, and toDate should have a max value of a month from the fromDate.
The max value will disable users from selecting a date over 30 days from the startDate/fromDate.
Angular material doc #datevalidation
https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings
Html:
<code><mat-form-field class="datepicker">
        <input matInput [matDatepicker]="frompicker" placeholder="from" [formControl]="fromDate">
        <mat-datepicker-toggle matSuffix [for]="frompicker"></mat-datepicker-toggle>
        <mat-datepicker #frompicker></mat-datepicker>
      </mat-form-field>

      <mat-form-field class="datepicker">
        <input matInput [max]="maxDate" [matDatepicker]="topicker"  placeholder="to" [formControl]="toDate">
        <mat-datepicker-toggle matSuffix [for]="topicker"></mat-datepicker-toggle>
        <mat-datepicker #topicker></mat-datepicker>
      </mat-form-field>
</code>
Ts file:
<code>  setMaxDateForCalender(){

    let fullyear = this.datePipe.transform(this.fromDate.value, "yyyy");

    this.maxDate = new Date();
    this.maxDate.setDate(this.fromDate.value.getDate());
    this.maxDate.setMonth(this.fromDate.value.getMonth() + 1);
    this.maxDate.setFullYear(Number(fullyear));

    console.log("Max Date After: " + this.datePipe.transform(this.maxDate, this.dateFormat));
  }
</code>
I tried different ways to do this, but the max value doesn't seem to trigger after fromDate is selected.
Answer: Are you use Reactive form, formControl or ngModel? where you call the function setMaxDateForCalendar()?
<code>//if you're using ReactiveForm
..AFTER you create the form...
this.myForm.get('fromDate').valueChanges
        .subscribe((date:any) => {
            ..use "date", NOT this.myForm.value.fromDate
        })

//If this.fromDate is a FormControl use
this.fromDate.valueChanges
        .subscribe((date:any) => {
            ..use "date", NOT this.fromDate.value
        })
</code>


Why is the tangent of an angle called that?

Question: I am teaching the foundations of trig and find it a bit weird that tangent is called that.
I've never questioned it before, but what I keep finding online is the phrase 'tangent of an angle'.
Is anyone able to explain, maybe using some visual intuition, why we call it the tangent of an angle? Especially in the context of the unit circle.
Does it relate to the definition of a tangent to a curve?
Comment: See [The Etymology of Trig Functions](https://mathisonian.github.io/trig/etymology/).
Comment: In some places tg is short for tangent.
Comment: There are two questions here, (i) why is it called tangent and (ii) why is the standard abbreviation $\tan$. Regarding the latter, presumably ta is a bit ambiguous thank you and tang would be sued by General Foods Corporation.
Comment: See https://english.stackexchange.com/questions/40364/what-reasoning-is-behind-the-names-of-the-trigonometric-functions-sine-secan
Comment: It seems like Doug M's [reasoning](https://en.wikipedia.org/wiki/Trigonometric_functions#Etymology) is correct.
Comment: You might find my note helpful: ["(Almost) Everything You Need to Remember about Trigonometry, in One Simple Diagram" (PDF)](http://trigonography.com/misc/AlmostEverythingAboutTrig.pdf)
Comment: Shouldn't this question and its answers be moved to the History of Science and Mathematics SE?
Answer: I can't say for certain that this is the origin of the name of the function.
But if you construct a line that is tangent to the unit circle, using either of these constructions:

then the red segment has a measure of $\tan x$.
In the second figure, the green segment has measure $\cot x$.
Comment: Just for clarification: what is "x" in your diagram?
Comment: In your second figure, the red segment extends all the way from the x-axis to the y-axis, but the part of it to the left of the tangent-point is *partly* hidden by the green segment. So this is a bit confusing. I'm assuming that the red segment is only intended to extend from the x-axis to the tangent point?
Comment: The red segment is supposed to run from the point of tangency to the x axis and the green segement from the point of tangency to the y axis.
Comment: And to answer the follow-up question, the length of the horizontal segment from the origin to the base of the red segment is the secant of x, just as that line is a secant to the circle.
Comment: @rprospero x is the angle, PI/4
Comment: I edited the image to remove the red pixels peeking out from under the green line. It should now hopefully be less misleading to people with good color vision like @ruakh. :)
Comment: @IlmariKaronen: Thank you!
Comment: @PerdiEstaquel : $x$ is indeed the angle, but it's larger than $\pi/4$.
Answer: This is not an explanation why the word tangent is used (I think the other answers nicely do this), but a historical digression.
The first occurence of a mathematical symbol as denotation of the tangent-function I have personally seen is in Leonhard Euler's "Introductio in Analysin Infinitorum, Volume 2" from 1748. This was written in Latin which at that time was the universal language of European scholars. The Latin word is "tangens" which is the present participle of the verb "tangere" and Euler abbreviated it by the symbol tang. In many modern languages the word "tangens" was replaced by "tangent" (English) or similar forms ("tangente" in French and Italian) , but for example in German and Russian the original form is used. Note that the "t" in the end of the word comes in via Latin declination.
Although the concept of tangent was known much longer (for certain in Arabic/Islamic mathematics, first formal use by Abū al-Wafāʾ who lived from 940 to 998), the word "tangens" was at first introduced by Thomas Fincke in his book "Geometria rotundi" from 1583.
From Euler's "Introductio in Analysin Infinitorum":

Edited: After a little "research" I found that the symbol tan for tangent was introduced long before Euler. In fact, it seems that Albert Girard introduced it in his work "Trigonométrie" from 1626. However, other sources say it was introduced by Edmund Gunter in 1624.
It may also be interesting that the Arabic word for tangent is "shadow" which is in use for more than 1000 years.
Comment: @nick012000 tangere = to touch, tangens = touching
Comment: In French, we use "tangente" as a noun ("la tangente d'une courbe", "la tangente d'un angle").  As an adjective, "tangent" and "tangente" are used, depending on the gender of the noun they characterize.
Comment: @Taladris Thank you for clarification, I edited the answer. It shows how poor my French is - which is very sad ...
Comment: What does the Latin word "tangens"/"tangere" translate to in English?
Answer: Although I hardly believe there is any particular reason for this, the following interpretation might be satisfactory.
How does one interpret/define $\sin x$ and $\cos x$ using a unit circle? Consider a unit circle (i.e. it has radius 1) with $O$ being it's centre. Suppose $A, B$ are two points on the circle such that $\angle AOB$ measures $x$ radian. Draw $BD\perp OA$. Then, $BD=\sin x$ and $OD =\cos x.$ Now you might be curious how $\tan x$ comes into this picture. Draw the tangent to this circle at $A,$ let it meet $OB$ at $C.$ Then, $CA=\tan x.$


Two rates of change

Question: Two mice (say $A$ and $B$) eat a piece of food. The rate of consumption for $A$ is proportional to amount of food left(Proportionality constant = $2$) and rate of consumption for $B$ is proportional to amount of food eaten by $A$(Proportionality constant = $1/2$ ).
Find the time it takes the food to be finished.
Also find the time after which the rate of consumption of both mice is same.
My Attempt
Let $F_A$ and $F_B$ be the amount of food eaten by A and B after time t.
$\frac{dF_A}{dt}=-2\{N-(F_A+F_B)\}$
$\frac{dF_B}{dt}=\frac{1}{2}F_A\Rightarrow \frac{d^2F_B}{dt^2}=\frac{1}{2}\frac{dF_A}{dt}$
So eliminating $F_A$ and $\frac{dF_A}{dt}$ we get
$\frac{d^2F_B}{dt^2}-2\frac{dF_B}{dt}-F_B+N=0$
Are my deductions correct. How to proceed further now
Answer given is $1$ time unit and $0.66$ time units
Comment: 1) Solve the ODE for $F_B$ with the initial conditions $F_B(0)=0$ and $F_B'(0)=0$ (the latter follows from $F_B'=(1/2)F_A$). 2) Solve $F_A(t)+F_B(t)=N$. 3) Solve $F_A'(t)=F_B'(t)$.
Comment: I have just realized that your first equation has a sign error. It should be $\frac{dF_A}{dt}=+2\{N-(F_A+F_B)\}$.
Comment: I was missing $F'_B(0)=0$ and of course the sign error. I realize now that with increase in time $F_A$ increases so putting a minus sign is clearly wrong.
Answer: As per what Gonçalo said I followed his advice.
Let $N$ be the amount of food in the beginning.
$$\frac{dF_A}{dt}=2\{N-(F_A+F_B)\}$$
$$\frac{dF_B}{dt}=\frac{1}{2}F_A\Rightarrow \frac{d^2F_B}{dt^2}=\frac{1}{2}\frac{dF_A}{dt}$$
So eliminating $F_A$ and $\frac{dF_A}{dt}$ we get
$$\frac{d^2F_B}{dt^2}+2\frac{dF_B}{dt}+F_B=N$$
$$e^t\frac{d^2F_B}{dt^2}+2e^t\frac{dF_B}{dt}+e^tF_B=Ne^t$$
$$\frac{d^2(e^tF_B)}{dt^2}=Ne^t$$
Integrating twice
$$e^tF_B=Ne^t+Ct+D$$
$$F_B=N+(Ct+D)e^{-t}$$
Clearly $F_B(0)=0$ and $F'_B(0)=0$
so we have $$F_B=N-(1+t)Ne^{-t}$$
and $$F_A=2Nte^{-t}$$
When the food is finished we have $$F_A+F_B=N$$
Substituting for $F_A$ and $F_B$ in above equation we get $t=1$
To find the time after which the rates of consumption are equal we obviously put
$$F'_A=F'_B$$ to obtain $$t=\frac{2}{3}$$

Two rates of change


Javascript print square using for loop and conditional statement only

Question: Just started my uni course, struggling a little with javascript. I have been asked to display a square using any character, however, the solution must combine for loops and if statements.
This is what I have so far and I feel pretty close but I just can't get the second line to display. I know this can be done via two for loops, (one for iteration of the variable and another for spaces). But this is not how I have been asked to solve this problem.
Here is my code:
var size = 3;
let i;

for(i = 0; i < size; i++) {
print ("*");
if (size === i){
println ("");
}
}

For context, this is all taking place int he professors homemade learning environment.
Answer: You could use nested for loops and take a line break after each filled line.

function print(s) { document.getElementById('out').innerHTML += s; }
function println(s) { document.getElementById('out').innerHTML += s + '\n'; }

var size = 5,
    i, j;

for (i = 0; i < size; i++) {
    for (j = 0; j < size; j++) {
        print("*");
    }
    println("");
}

Single loop with a check if i is unequal to zero and if the remainder is zero, then add a line break.
Using:

=== identity/strict equality operator checks the type and the value, for example if both are numbers and if the value is the same,
!== non-identity/strict inequality operator it is like above, but it checks the oposite of it,
% remainder operator, which returns a rest of a number which division returns an integer number.
&& logical AND operator, which check both sides and returns the last value if both a truthy (like any array, object, number not zero, a not empty string, true), or the first, if it is falsy (like undefined, null, 0, '' (empty string), false, the oposite of truthy).

function print(s) { document.getElementById('out').innerHTML += s; }
function println(s) { document.getElementById('out').innerHTML += s + '\n'; }

var size = 5,
    i;

for (i = 0; i < size * size; i++) {
    if (i !== 0 && i % size === 0) {
        println("");
    }
    print("*");
}

Comment: This is confusing me a little lol, also, the output for instance would need to appear like a filled in square not an empty one. Thankyou though.
Comment: sorry, now with filled output.
Comment: This is how I have done it before, however, he now wants a conditional statement to be in there. This was my first suggestion but he said I was not playing the game fair lol.
Comment: Some of those conditional operations are lost on me, any chance of some annotation to explain what the modulus function is doing?
Comment: Thanks a bunch, I really like the way this one works, I should have thought about the problem a bit more before typing anything. I had not even considered checking the remainder of from i to create a new line. My think was much more linear.
Answer: Well the for loop is only iterating 3 times, printing the first line. If you want a square you'll have to print 9 stars total, right? So i'm assuming, is this is the approach you'd go for, you would need to iterate not until size, but until size * size.
Comment: The loop needs to actually capture the user input of the number of *'s which make up the square. if I was to iterate on size * size would I not just end up with a string of 9 *'s though? - Thanks for your help!
Answer: You wanna make a square of * where the size is the number of * on its sides?
Let's split a task into 3 parts:

where you print top side like *****
where you print middle (left and right sides) like *    *
where you print bottom (same as top)

Now let's code that, I kept the code as simple as possible, this can be done in fewer lines but I think this will be easier to understand for beginners:
var size = 5;
var i = 0;

// top
for (i = 0; i < size; i++)
    console.log("*");

//middle
for (var j = 0; j < size - 2; j++){
  console.log("\n"); // go to next row
  // middle (2 on sides with size-2 in between)
  console.log("*");
  for (i = 0; i < size-2; i++)
    console.log(" ");
  console.log("*\n"); // goes to new row as well
}

// same as top
for (i = 0; i < size; i++)
    console.log("*");

Full square is even simpler:
var size = 5;
var i = 0;

for (var i = 0; i < size; i++){ // iterates rows
  for (var j = 0; j < size; j++) // iterates * in row
      console.log("*");
  console.log("\n") // moves to new row
}

In order to print a row, you print same sign X times. Well, to print X rows we can use just that 1 more time (only this time we are iterating over a different variable (j is * in a row, i is a number of rows).
After a row is made we go to go to next row with \n.
As for

it must contain if statement

Put this at the end:
if (youCanHandleTheTruth) console.log("It's a terrible practice to tell students their solution MUST CONTAIN CODEWORDS. If you need them to showcase something, write appropriate task that will require them to do so.");

Comment: This is incredibly helpful however the square does not need to be empty, its needs to be s static X*X squares with a character in each.
Comment: Just a reminder it must contain at least one if statement.
Comment: Tell to whoever gave you a task that conditioning the solution to contain codewords is terrible. It's not in the spirit of programming. But, fine, you can always add an if in the end ;) If you wanna it showed just initialize youCanHandleTheTruth to truthy value :D
Comment: Hahah i'm sure he will be over the moon with that feed back!

I took a break and I have come back to this, which is giving the correct display for the first line at least. I thought about putting an else in but I just can't figure out how I would get it scale effectively without lines and lines of nested ifs.
Answer: I'm using console.log to 'print' the square:
    var dimension = 10;
    var edge = '*';
    var inside = ' ';
    var printLine;

    for (var i = 1; i <= dimension; i++) {
        if (i === 1 || i === dimension) {
            printline = Array(dimension + 1).join(edge);
        } else {
            printline = edge + Array(dimension - 1).join(inside) + edge;
        }
        console.log(printline);
    }

Note that in the following example, an array of length 11 gets you only 10 "a"s, since Array.join puts the argument between the array elements:
Array(11).join('a'); // create string with 10 as "aaaaaaaaaa"

Comment: Nice thinking with Array.join().


How do I add keys to a dictionary with existing data?

Question: The code im trying to create is supposed to have two keys:
["democrats"]
["republicans"]
I've nearly got it with all the correct data, I just don't have the key dictionaries. This is what I'm currently working with:
def getPartyUserTwitterUsage(tweetFile):
    import csv

    myFile = open(tweetFile,"r") # opening file in read

    csvReader = csv.reader(myFile,delimiter=",") # splitting for ','

    next(csvReader) # skipping header

    tweetList = {}

    repTweet = 0
    demoTweet = 0

    for row in csvReader: # iterating through file
        if (row[1] == 'R'):
            if (row[0] not in tweetList):
                tweetList[row[0]] = 1
            else:
                tweetList[row[0]] += 1

        if (row[1] == 'D'):
            if (row[0] not in tweetList):
                tweetList[row[0]] = 1
            else:
                tweetList[row[0]] += 1

    return tweetList

This function:
getPartyUserTwitterUsage("Tweets-2020 (2).csv")
returns:
{'ChrisMurphyCT': 1000,
 'SenBlumenthal': 1000,
 'SenatorCarper': 1000,
 'ChrisCoons': 1000,
 'brianschatz': 1000,
 'maziehirono': 1000,
 'SenatorDurbin': 1000,
 'SenatorHarkin': 1000,
 'lisamurkowski': 1000,
 'JeffFlake': 1000,
 'marcorubio': 1000,
 'MikeCrapo': 958,
 'SenatorRisch': 1000,
 'ChuckGrassley': 1000,
 'SenPatRoberts': 1000,
 'JerryMoran': 1000}

This is the output im expecting:
{'Republicans': {'lisamurkowski': 1000,
  'JeffFlake': 1000,
  'marcorubio': 1000,
  'MikeCrapo': 958,
  'SenatorRisch': 1000,
  'ChuckGrassley': 1000,
  'SenPatRoberts': 1000,
  'JerryMoran': 1000},
 'Democrats': {'ChrisMurphyCT': 1000,
  'SenBlumenthal': 1000,
  'SenatorCarper': 1000,
  'ChrisCoons': 1000,
  'brianschatz': 1000,
  'maziehirono': 1000,
  'SenatorDurbin': 1000,
  'SenatorHarkin': 1000}}

Comment: Please kindly show some first line (i.e. first 5 rows) of csv, because it might be hard to figure out how to help you.
Comment: To create a key/value pair in a Python dictionary, you just need to do `your_dictionary[] = `. For instance, if you wanted to have `"Republicans"` and `"Democrats"` as keys in a dictionary named `test_dict`, and the values associated with these keys to be dictionaries themselves, you would do `test_dict["Republicans"] = {}` and `test_dict["Democrats"]`. If you want to know how to sort your data in these dictionaries, please do as @DhanaD. suggested and post some of your data.
Comment: Use `tweetList  = defaultdict(dict)`. And then use two keys to add data into your dict: `tweetList[row[1]][row[0]] = 1`
Answer: You need to create the keys: Republicans and Democrats before inserting the entries.
...
    tweetList["Republicans"] = {}
    tweetList["Democrats"] = {}
    for row in csvReader: # iterating through file
        if (row[1] == 'R'):
            if (row[0] not in tweetList["Republicans"]):
                tweetList["Republicans"][row[0]] = 1
            else:
                tweetList["Republicans"][row[0]] += 1

        if (row[1] == 'D'):
            if (row[0] not in tweetList["Democrats"]):
                tweetList["Democrats"][row[0]] = 1
            else:
                tweetList["Democrats"][row[0]] += 1

    return tweetList


HTML email preheader image ALT being ignored

Question: I've been using an HTML email template for quite some time that has a few images and then a footer that is copy. The top image always has a descriptive ALT attribute that we assumed was being used for a preheader but we just noticed the footer is the text that comes through for the preheader text in email clients. Does ALT text not get recognized before the actual copy in the footer? Wouldn't the ALT text be the first text that would come through in the HTML and not the footer copy?
Answer: I wouldn't count on the Alt tag being in the Mail and getting recognized as a Preheader. I always use this Preheader:

        PREHEADER

This works fine in every Client I've tested so far
Comment: Thank you, I'm going to start using this moving forward. I thought that since preview text is pulled from the first few lines of text found within an email, the ALT text would be included but I guess that isn't the case.


Filtering in ArrayList in C#

Question: I have an ArrayList
ArrayList mixed = new ArrayList { "Joe", 200, "Root", false, "David" };

What is business logic should I use to filter only string from given ArrayList?
I mean I need {"Joe","Root","David"} as a filtered result.
I am using C# 4.0
Comment: Why in the name of all that is good, do you use `ArrayList` at all? Why oh why do you have a list made of different types?
Comment: Gotta agree with Oded. Your list is from Hell.
Answer: You could use
 var StringOnly = mixed.OfType<string>();

to filter your arraylist.

Filtering in ArrayList in C#


Advanced forum how to change the html without modifying the core

Question: I want to change the html for the topics list in Advanced forum module. I use a custom style. I foond that the file which displays the html is

sites\all\modules\advanced_forum\styles\mystyle\advanced-forum.naked.topic-list-view.tpl.php

If I edit this file the changes are displayed. But I don't want to modify core files in order to be able to upgrade. So I tried to copy this file to my custom style's folder. But the changes are not displayed. Is it possible to change the html without modifying the naked style and if yes how?
Thanks in advance
Answer: The easiest way to find the correct file name for your custom template files is to use the Theme Developer moduel. It allows you to point and click on anything in the browser and it tells you which part of the theme framwork rendered it and what options you have to override it.
Please note: You have to clear the theme registery after you added new templates, otherwise they are not shown.
Answer: I realize this question was asked months ago, but I ran into a similar situation when trying to override an advanced_forum template.
The solution was to copy the file into your theme templates folder, and rename it removing the advanced_forums style name.
In the example of your case, you would copy the file:
*sites\all\modules\advanced_forum\styles\mystyle\advanced-forum.naked.topic-list-view.tpl.php*
to:
sites\all\theme\mythemename\templates\advanced-forum-topic-list-view.tpl.php
Note the name change, and that "mythemename" should be whatever your custom theme is. You may also need to copy the file advanced-forum-forums.tpl.php into your theme directory


Como converte um tipo enum em list?

Question: Existe alguma forma de converte um Enum em List?
public enum TiposHospedagem
{
    Casa = 1,
    Hotel = 2,
    Pousada = 3,
    CasaCampo = 4
}

Estou tentando vare o enum e adicionar na lista, mas o foreach não aceita fazer isso.
protected void Page_Load(object sender, EventArgs e)
{
    var lista = new List<Int32>();

    foreach (var th in TiposHospedagem)
    {
        lista.Add(Convert.ToInt32(th));
    }
}

Comment: Veja se ajuda: http://stackoverflow.com/a/1167367/5524514
Comment: Eu coloquei um link para o post original, será que ficaria melhor se eu colocasse mais alguma informação? Minha intenção é colaborar o máximo possível.
Comment: diegofm, sei que a sua intenção é ajudar, mas postei como resposta uma tradução livre da resposta no SO em inglês, pois muitos não compreendem o idioma e por este motivo utilizam o SO em Português.
Comment: @BrunoBermann não que eu me importe com isso, mas dar os créditos não seria nada ruim :)
Comment: @diegofm, valeu pelo link, só não tinha entendido como convertia para int.
Answer: Conforme resposta no SO, pode fazer isso:
using System;
using System.Linq;
using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var lista = new List<int>();
        foreach (int item in Enum.GetValues(typeof(TiposHospedagem))) lista.Add(item);
        foreach (var item in lista) WriteLine(item);
    }
}

public enum TiposHospedagem {
    Casa = 1,
    Hotel = 2,
    Pousada = 3,
    CasaCampo = 4
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
A solução obviamente poderá variar conforme a necessidade. Então outra possibilidade seria:
var lista = Enum.GetValues(typeof(TiposHospedagem)).Cast<int>().ToList();

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Pode não ser muito performático já que usa reflexão, mas deve atender bem a maioria das necessidades.
Esse código pega todos os valores existentes na enumeração, faz um cast em cada um dos membros para um inteiro, já que é o tipo que se deseja (se quisesse outro poderia ser um problema) e converte para a lista. Tudo isso usando LINQ, por isso dá para fazer em uma só linha.
Comment: Por que não utilizar apenas `foreach (int item in Enum.GetValues(typeof(TiposHospedagem)))`?
Comment: Mas você tem razão: é preciso dizer isso pro compilador, usando `int item` em vez de `var item`
Comment: Obrigado, deu certo aqui....
Comment: @ramaral porque o resultado de cada item retornado por [`GetValues()`](https://msdn.microsoft.com/en-us/library/system.enum.getvalues(v=vs.110).aspx) será um `object` e se deseja um `int`. Sabe-se que o resultado será um `int`, mas precisa dizer isso pro compilador. API ruim.
Comment: Não, ele compila.
Comment: @ramaral ah, é que aí há um *cast* implícito, poderia ser feito assim também. Modifiquei, fica melhor. Créditos para você nessa parte.
Answer: Você pode utilizar a seguinte sintaxe:
Enum.GetValues(typeof(MeuEnumerador)).Cast<MeuEnumerador>();

E isso retornará uma interface IEnumerable especializada ao tipo MeuEnumerador.
Para converter os dados através desta interface para uma lista você deve utilizar o método ".ToList()" dela
Observação: É necessário incluir o namespace System.Linq no seu código para utilizar este código.
Créditos: Resposta baseada na pergunta do SO-En localizada neste link

Como converte um tipo enum em list?


Genericity of embeddings of closed manifolds

Question: Let $M$ be a closed manifold, and let $f:M\to\mathbb{R}^n$ be a continuous map. Then, assuming that $n$ is sufficiently large, is it true that $f$ is generically an embedding in a certain sense?
Here's one attempt to make this question more precise (and please point out if there are better ways to do so):
Question: Is it true that for any $\epsilon>0$, there exists a continuous embedding $f':M\to\mathbb{R}^n$ such $\|f-f'\|_\infty<\epsilon$?
Any references for a related discussion would also be great.
Comment: I'd even expect the embeddings to eventually be an open dense subspace, by analogy with the same result for Morse functions.
Answer: This can be done with a few transversality arguments. Most of the relevant background information can be found in chapter $6$ of Lee's Introduction to Smooth Manifolds. While this is by no means the most eloquent argument, (my choices of parameterized families are probably overkill), your claim appears to be true for $n\ge 2m+1$.
Throughout, $M$ is a smooth compact manifold without boundary of dimension $m$, $TM$ is its tangent bundle, and $SM\subseteq TM$ be an arbitrary choice of sphere bundle (the submanifold of tangent vectors which have unit norm w.r.t. some Riemannian metric).
The main theorem is the parametric Transversality theorem, which I'll quote from Lee.
Parameteric Transversality Theorem [Lee, Thm 6.35] Suppose $N$ and $M$ are
smooth manifolds, $X\subseteq M$ is an embedded submanifold, and $\{F_s:s\in S\}$ is a
smooth family of maps from $N$ to $M$. If the map $F:N\times S\to M$ is transverse
to $X$, then for almost every $s\in S$, the map $F_s:N\to M$ is transverse to $X$.
Two other useful theorems:
Whitney Approximation Theorem: For any continuous map $f:M\to\mathbb{R}^n$ and any $\epsilon>0$, there is a smooth map $g:M\to\mathbb{R}^n$ which is $\epsilon$-close to $f$.
Whitney Immersion Theorem: There exists a smooth immersion $f:M\to\mathbb{R}^n$ for $n\ge2m$.
In addition to these, some other lemmas are required, which I haven't been able to find anywhere (though the first is an exercise in Lee).
Lemma 1: For any smooth map $f:M\to \mathbb{R}^n$ with $n\ge 2m$, and any $\epsilon>0$, there is an immersion that is $\epsilon$-close to $f$.
Proof: Fix $f,\epsilon$ as above, and let $\varphi:M\to\mathbb{R}^n$ be a Whitney immersion. By composing with a smooth map $\mathbb{R}^n\to\mathbb{B}^n$, we can assume that $\operatorname{im}(\varphi)$ is contained in the unit ball. Let $f_A$ be defined by
$$
f^i_A(x)=f^i(x)+A^i_j\varphi^j(x)
$$
Where $A\in\mathbb{R}^{n\times n}$. Let $F:SM\times\mathbb{R}^{n\times n}\to\mathbb{R}^n$ be a parameterized family of maps defined by $F(v,A)=d_xf_A(v)$, where $v\in S_xM$. I claim that $F$ is transverse to $\{0\}\subset\mathbb{R}^n$. To see this, suppose $F(v,A)=0$. Since $\varphi$ is an immersion and $v\neq 0$, $d_x\varphi(v)\neq 0$. Fixing $i$ and choosing $B\in\mathbb{R}^{n\times n}$ such that $B^j_kd_x\varphi^k(v)=\delta^j_i$ (such a $B$ always exists), we have
$$
\frac{d}{dt}\left(F(v,A+tB)\right)|_{t=0}=B^j_kd_x\varphi^k(v)\partial_j=\partial_i
$$
Since this can be done for any $i\in\{1,\dots,n\}$, and the $\partial_i$ form a basis of $\mathbb{R}^n$, $dF$ is surjective, and thus $F$ is transverse to $\{0\}\subset\mathbb{R}^n$. Now by applying parametric transversality theorem, $df_A:SM\to\mathbb{R}^n$ is transverse to $0$ for almost all $A\in\mathbb{R}^{n\times n}$. Since $SM$ has dimension $2m-1$, this means that for $n\ge 2m$, $0\notin df_A(SM)$, and thus $df_A$ is full rank and $f_A$ is an immersion for almost all $A$.
The set $S=\{B\in\mathbb{R}^{n\times n}:\|B\|_{op}<\epsilon\}$ is open, so there is an $A\in S$ such that $f_A$ is an immersion. Since $\|\varphi(x)\|\le 1$, we have
$$
\|f_A(x)-f(x)\|=\|A\varphi(x)\|<\epsilon
$$
And thus $f_A$ is $\epsilon$-close to $f$.
$\square$
Lemma 2: For any smooth immersion $f:M\to\mathbb{R}^n$ with $n\ge 2m+1$, and any $\epsilon>0$, there is an injective immersion that is $\epsilon$-close to $f$.
Proof: Since $f$ is an immersion, it is a local embedding, and so we may choose a finite covering $\{U_\alpha\}_{\alpha=1,\dots,k}$ of $M$ by extendable open balls $U_\alpha$ such that $f|_{\overline{U_\alpha}}$ is injective for each $\alpha$, and there is a collection of bump functions $\psi_\alpha:M\to\mathbb{R}$ such that $\psi_\alpha|_{U_\alpha}>0$ and $\psi_\alpha|_{M\setminus U_\alpha}=0$.
Let $S=\{(x,y)\in M^2:x\neq y\}$, and define $\Delta_f:S\to\mathbb{R}^n$ by $\Delta_f(x,y)=f(x)-f(y)$. Note that $f$ is injective iff $\Delta_f$ is nonvanishing.
To find a nearby injective map, we can define a parametric family $F:M\times \mathcal{V}\to\mathbb{R}^n$, by
$$
F^i(x,A)=f^i(x)+\sum_{\alpha=1}^kA^i_\alpha\psi_\alpha(x)
$$
Where $\mathcal{V}\subset\mathbb{R}^{n\times k}$ is a neighborhood of zero such that $F_A|_{\overline{U_\alpha}}$ is injective for all $\alpha\in\{1,\dots,k\}$, $A\in\mathcal{V}$. We define $\Delta_F:S\times\mathbb{R}^{n\times k}\to\mathbb{R}^n$ by $\Delta_F((x,y),A)=F(x,A)-F(y,A)$. To show that $\Delta_F$ is transverse to $0$, we choose $(x,y)\in S$ such that $\Delta_F(A,(x,y))=0$. Choosing $\alpha,\beta$ such that $x\in U_\alpha,y\in U_\beta$, it must be the case that $x\notin U_\beta$ and $y\notin U_\alpha$. Thus, choosing $B\in\mathcal{V}$ such that $B^i_\alpha\neq0$ and all other entries are zero,
$$
\frac{d}{dt}(\Delta_F((x,y),A+tB)|_{t=0}=B^j_\alpha\psi_\alpha(x)\partial_j=c\partial_i,\ \ \ c\neq 0
$$
Again doing this for $i\in\{1,\dots,n\}$ gives a basis for $\mathbb{R}^n$, ad so $d\Delta_F$ is surjective wherever $\Delta_F$ vanishes, and so $\Delta_F$ is transverse to $\{0\}\subset\mathbb{R}^n$. By parametric transversality theorem, $\Delta_{F_A}$ is transverse to zero for almost all $A\in\mathcal{V}$, and thus if $n\ge 2m+1$, $F_A$ is injective for almost all $A\in V$. We may thus choose an $A$ such that $F_A$ is injective and $\epsilon$-close to $f$.
$\square$
Combining these two lemmas and the Whitney approximation theorem, we see that for any continuous map $f:M\to\mathbb{R}^n$ with $n\ge 2m+1$, there is an embedding which is $\epsilon$-close to $f$. This bound is sharp. For $n=2m$, immersions can intersect themselves transversally, and these intersections will be stable w.r.t. $L^\infty$-small deformations (consider for instance the $\infty$ symbol as a map $S^1\to\mathbb{R}^2$).
It seems likely that this remains true for other, finer topologies, such as Sobolev or Fréchet topologies on $C^k(M,\mathbb{R}^n)$. The proofs would be a bit more nuanced, of course.
Comment: Right, +1. For the sake of completeness: The same density result also holds for topological and for PL manifolds. The set of embeddings (with topology of $C^0$ convergence) is not open, but is $G_\delta$.