SQL Server 2008 not showing the Management Studio option

Question: I know this question is asked for many times.But I am unable to find a solution after googling much.I have installed MSSQL SERVER 2008(64 bit).(Windows 7 OS) in my system.I'm trying to create a new database using SQL Server 2008, and these are the steps that I follow:
Start -> Microsoft SQL Server 2008 ->
I get 2 options:
 Configuration tools
 Import and Export Data (32 bit).

When I choose Configuration tools and then get these options:
 SQL Server Configuration Manager
 SQL Server error and usage reporting
 SQL Server Installation Center

When I click 1. SQL Server Configuration Manager it shows sqlserverservices with status running.Unfortunately I didn't find SQLServer Management Studio inside this.When I searched this in the search bar I found it under the Documents and when I clicked,it shows 4 folders named

Code Snippets
Projects
Settings
Templates

I am unable to create database.Guys please help me
Comment: Did you check the SSMS.exe in C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\ location
Comment: Should be another Microsoft SQL Server folder with SSMS inside. Mine's called Microsoft SQL Server 2008 R2
Comment: @Knightwisp Since I am newbie,I dont get you about SSMS.Mine is MS SQL SERVER 2008 EXPRESS.Is it differenet from what you mention in your comment
Comment: @AnazA SQL Server Management Studio - what you're looking for.
Comment: @Knightwisp I cant create database after clicking management studio.It shows only 4 folders as I mentioned in the question.
Comment: @Oasis I didnt find SSMS.exe inside the location folder.It contains only 3 files
Answer: It seems that you have not selected the Management Tools Options while installing the sql server.Check all client tools options with Management Tools option while installing.
Try to reinstall or repair your installation.
After completed your installation Press Windows+R and type SSMS then Press Enter.It will open SQL Server Management studio.
Comment: I have selected all options including Client tools during installation
Comment: @AnazA : Then you should see ssms.exe in SSMS.exe in C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\ location
Comment: ssms.exe is not found.What to do then @Oasis
Comment: Then there is some problem in your installation.Try to repair or reinstall.
Answer: Maybe you haven't installed Sql Server Management Studio, only Sql Server.
Look for Sql Server Management Studio in the start menu and if it's not there then you'll need to install it.
Image:
Comment: SQL Server Management studio is shown in the start menu.But when I click it,it shows 4 folders as I mentioned in the question
Comment: Do you mean 4 folders in the Object Explorer of ssms?
Comment: Ya..they are:Code Snippets,
Projects,
Settings,
Templates
Comment: Can you post screenshots of where you try to open ssms?
Comment: @Mitco I have placed screen shots
Comment: I added an image of my start menu, let me know if you have the same option, if I understood your question.
Comment: @Mitco For me When I search like "management studio",it is coming like this,but in the form of a folder.I have placed the screen shot
Comment: Then you're missing something, try and install this: http://www.microsoft.com/en-us/download/details.aspx?id=7593


How to save tem file in my system with python

Question: i try to add geometry layer to my gis app from shb layer
i use Django for doing that and for uploading file i use serializer FileField
now my main question is How can i save temporary file to my system in python
is there any way to do that?
if there is please help me about that
Comment: Hi Emad, take a look at the build in [tempfile](https://docs.python.org/3/library/tempfile.html) library. I think this should do what you want.
Answer: Here is a similar question that has already been answered.
TL/DR
<code>import tempfile

with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
    f.write("hello world")

path_to_tempfile = f.name
</code>


Is f continuous? lower semicontinuous? upper semicontinuous?

Question: I'm learning analysis on my own, and I'm having difficulties.
Let $$\mu_{x_0}(E)=\begin{cases} 1 & x_0\in E \\ 0 & x_0\not\in E \end{cases}$$ and $V= B_r(x_0)=\{x|d(x,x_0)<r\}$.
Is $f(x)=\mu(V+x)$ continuous? lower semicontinuous? upper semicontinuous?
My attempt:
So $V+x=B_r(x_0+x)=\{x|d(x,x_0+x)<r\},$
$d(x,x_0+x) \leq d(x,x)+d(x_0,x) < r$
so $x_0 \not\in V+x,$ so $\mu(V+x)=0=f(x)$
How do we proceed?
Answer: HINT
Note that
$\mu(V+x)=1$ if $d(x,x_0)<r$ and
$\mu(V+x)=0$ if $d(x,x_0) \geq r$
So the function is not continuous.
Answer: As noted in another answer, $f$ is the indicator function of an open set (the open ball centered at $x_0$ of radius $r$). As such, $f$ is lower semi-continuous.
Exercise: Let $g(x):=[r-|x-x_0|]^+$ be the distance from $x$ to the complement of $B_r(x_0)$. Clearly $g$ is continuous. Show that as $n\to\infty$, the sequence $\{f_n\}$ of continuous functions defined by $f_n(x) :=g(x)/[n^{-1}+g(x)]$ increases pointwise to $f$


How does the 'in' operator determine membership?

Question: How does the in operator work for Python?
In the example below I have two namedtuples that are different objects, but the in operator evaluates to True for an array containing one of the objects.
Is in checking if the array contains the object, or does it check if any object in the array is equivalent? I tried searching for documentation but couldn't find anything specific, just simple examples.
In [3]: a = namedtuple('test', ['t'])

In [6]: b = a(1)

In [7]: c = a(1)

In [8]: b is c
Out[8]: False

In [9]: id(b)
Out[9]: 54740808

In [10]: id(c)
Out[10]: 88817352

In [11]: c in [b]
Out[11]: True

In [12]: b in [c]
Out[12]: True

In [13]: c == b
Out[13]: True

Comment: what `in` does is defined by the `__contains__()` method of the object on the right side of the operator. in case if that is a `list` it calls the `__eq__()` method (this can be uncovered by implementing a class with a custom `__eq__()` method), at `set` or `dict_keys` it compares the hash I guess, but not sure. also if any element does not have an `__eq__()` method `in` does not return `NotImplemented` those are just skipped silently.
Answer: The in operator is checking  the array contains the object which value is equivalent.
Here is example:
In [1]: a = {}

In [2]: b = {}

In [3]: c = [a]

In [4]: id(a), id(b), id(c[0])
Out[4]: (4514911128, 4515638640, 4514911128)

In [5]: a in c
Out[5]: True

In [6]: b in c
Out[6]: True


livro black hat go / variavel nao usada no golang

Question: func foo(i interface{}) {
switch v := i.(type) {
case int:
fmt.Println("I'm an integer!")
case string:
fmt.Println("I'm a string!")
default:
fmt.Println("Unknown type!")
}
}

pesquisei sobre essa estrutura de controle,mas como essa linguagem eh nova eu nao acho muita coisa no nosso idioma,minha compreensao do ingles nao eh das melhores.
peguei do livro "black hat go" e esse codigo nao esta funcionando,alguem poderia me dizer o motivo? e como fazer funcionar?
logs do compilador(1.13):
# command-line-arguments
./hw.go:6:9: v declared and not used

Answer: É exatamente o que o erro diz.
Enquanto algumas linguagens mostram um alerta quando você declara uma variável mas não a utiliza, Go te dá um erro de compilação. Essa é uma característica da linguagem que já foi bastante questionada, mas os criadores são bastante resilientes quanto a essa decisão, e parece que nada vai mudar por enquanto.
Também não tem como passar um parâmetro para o compilador para desligar essa analise de variáveis, então o jeito é arrumar o código e remover variáveis não utilizadas:
func foo(i interface{}) {
  switch i.(type) {
  case int:
    fmt.Println("I'm an integer!")
  case string:
    fmt.Println("I'm a string!")
  default:
    fmt.Println("Unknown type!")
  }
}

Outra estratégia que pode ser útil enquanto você está depurando o programa é atribuir o valor de uma variável não utilizada para _. Esse símbolo basicamente descarta qualquer valor atribuído a ele, e o compilador não reclama quando você está sendo explicito a respeito de um valor que não está sendo utilizado.


Binding In c++ programming Language

Question: Can any one explain this statement in a way that a 6 year old boy can understand?

Connecting the function call to the function body is called Binding. When it is done before the program is run, its called Early Binding or Static Binding or Compile-time Binding.

I wanted to know about Early and Late binding. I couldn't get what the above statement is saying.
Comment: @user2864740 i wouldn't have posted this question if i was able to understand ur link...
Comment: @user2864740 nothing at all ,plz explain in a simple way
Answer: There are two cases
void fun();

This is early binding, because compiler knows address of function to call.
Suppose you have fun in base class, which is virtual,
virtual void fun();

Also you have fun in derived class,
    class Base
    {
      public:
      virtual void fun(){//some code};

    };

     class Der : public Base
    {
      public:
      virtual void fun(){//some code};

    };

Now which fun will be called is depends on how you call function.
Let say,
int main()
{
 Base *b = new Base();
 b->fun(); //base version will be called

 Ber *d = new Der();
 b->fun(); //der version will be called

 return 0;
}

Comment: Ahh, I need to update my notion of the term "late binding" in context >_< It means something different in .NET (and even subtly different in Java).

Binding In c++ programming Language


Prove that if graph G is connectivity so for any 3 vertices $v,u,w$ :$ d(v,w)+d(w,u) \geq d(v,u)$

Question: d(v,u) denotes the shortest distance between 2 vertices: v,u. Prove that if graph G is connected, so for any 3 vertices v,u,w : $d(v,w)+d(w,u) \geq d(v,u)$.
Any help will be much appreciated.
Answer: I'd rather comment on this, but since I am not allowed to, I'll just post an answer.
If $d(u,v) = m$ and $d(v,w) = n$, there are paths from $u$ to $v$ of length $m$ and from $v$ to $w$ of length $n$. But the concatenation of those two paths is a path from $u$ to $w$ of length $m+n$, witnessing that the shortest path from $u$ to $w$ has at most length $m+n$, which gives the desired inequality.
Comment: Oh right! it was very silly. thanks:)
Comment: You're welcome.


Web-based System High Availability

Question: I'm a SysAdmin in one of the construction sites in a remote place. There is no reasonable internet speed can be reached there except a poor 3G/4G signal coverage which provide the users with non-stable average speed of 1 Mbps.
We have a web-based internal system and um wondering if I can use the high availability (Clustering) solution to make that system available offline (locally) to all the users in case the internet can't handle it. Then, give the whole bandwidth to the router to sync the content with the main server which is located in another country.
Hint: I'm imagining the same idea like Active Directory Replication.
Also, What about the content engine? is it the same idea like HA or gives more advantages?
Comment: You'll have to discuss with the vendor of this system what is possible in your situation. We don't know how it operates and how it is tied into other systems at your company, so it's impossible to make recommendations.
Comment: This is all completely dependent on the type of system and content you have. If it is mostly static files, this will be easy  but it can get complicate quite fast if the system is more complex and involves updating data and syncing it back.
Comment: @SvW actually it is a procurement system to make a purchase orders and get the approval by the site management. It is all can be done internally but the changes should be sync to the main server even with a delay.
Comment: IMO you'd be better off getting a high gain 3G/4G antenna, positioning it wherever the best coverage is and setting up a local WiFi network. Would probably be cheaper, more reliable and work better.
Comment: Is your application hosted in a stable location? Is your concern that you need to be able to access it despite your unstable connectivity?
Comment: The main problem is our site is based inside a military air base and such antennas are highly restricted.
Comment: But what are you connecting to?
Comment: Yes, it is in a stable location with a high speed internet connection. I just want to make it available locally to my site users and let the server to sync whenever it is available because we don't need any reaction from outside the LAN network, just to update the entire system which can be delayed. The high availability or the content engine will be a clone server of the main web-based system server.
Comment: 3G/4G unstable and poor coverage which i can connect like 4 USB modems to a load balance router (can generate a sum of 3Mbps) and give the bandwidth to the router VPN-Tunnel to sync instead of consuming the whole bandwidth on 40 users to access the website itself.
Comment: 1 Mbps sounds like 3G. Even a bad 4G connection would give you better than that.
Answer: The sort of thing you're asking for has to be already built into an application, can't be bolted on after the fact. Talk to your vendor about the issue, and talk to your IT department about (not) deploying an application that your infrastructure can't really support.
Comment: Unfortunately, it is a compulsory system to replace an old one. It has been applied to all the company sites but I have a problems to connect to the internet in my site due to the coverage and the restrictions of the military air base which our site based in.
Answer: My usual solution for something like this is to leverage multiple and diverse internet connections through the use of a link balancer (I prefer Elfiq). Your resiliency and susceptibility to internet outages improves considerably with this approach. Since you're connecting to a host in a stabile facility and don't seem to have inbound needs, this is probably the path of least resistance. This also allows you to aggregate bandwidth across your users and connections.
Comment: That may not be possible to change the application. If it's a stateless web-based system, get some diverse internet connectivity in to your location. 3G/4G, Fixed-wireless (microwave), DSL, cable, T1, fiber... whatever is available. Pool them and keep everyone happy.
Comment: Finally, I can fire up my services like VoIP, FTP, etc.

I called my devices set a TERMINATOR lolz and it contains the following:

Huawei E1820 3G USB Modem x4

TP-Link TL-MR3420 3G/4G wireless N Router x4

TP-Link TL-R480T+ Load Balance Broadband Router x1

It is all working perfectly and everybody happy :)

I really thank all of you guys and appreciate your effort to reply my question

Cheers ;)
Comment: Thank you so much @ewwhite. Actually, that what um thinking about but I need it to be more effective by reserving this bandwidth for sync with the main server through VPN-Tunnel if the content engine solution is applicable.
Comment: I MADE IT .. Cheers :)

Actually it was not that easy. I had to go over a container in the constructions site which is 300+ meters away from my server room and set my devices because I found a good coverage there where I never thought about checking before. Of course I had to put a multiple switches on the way to not lose the signal.

I got 4 Mbps stable speed and up to 12 Mbps in the best conditions.
Comment: I made it .. cheers :)

Huawei E1820 3G USB Modem x4
  // TP-Link TL-MR3420 3G/4G wireless N Router x4
  // TP-Link TL-R480T+ Load Balance Broadband Router x1

Web-based System High Availability


Capturar URL que esta dentro de uma div com Jquery

Question: Eu tenho um projeto onde tem vários boxes, com uma imagem, e um link. Eu gostaria que quando eu clicasse sobre a class .single-project capturasse o valor do href, mas não estou conseguindo.

$('.single-project').on('click', function() {
  window.location.href = ($(this).attr("href"));
});

Titulo

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Answer: Pelo o que eu entendi você precisa do seguinte código:
$('.single-project').on('click', function() {
   window.location.href = $(this).find("a").attr("href");
});

Caso tenha múltiplas URLS
$('.single-project').on('click', function() {
  var arr = [];
  $.each($(this).find('a'), function(index,valor){
   arr.push($(valor).attr('href'))
  });
  $('p').text(arr)
});

Comment: Funcionou perfeitamente, muito obrigado cara
Answer: O seu problema consiste no nível do pai da div e o operador this. Coloque a class 'single-project' na tag  da qual você quer extrair a URL e onde é acionado o click.

 $(document).ready(function() {
     $('.single-project').click(function(){
        alert($(this).attr("href"));
     })
    });

Titulo

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Comment: esse código não vai da certo, a ação que eu quero é quando clicar na caixa .single-project, pois dentro dela tem o link, uma descrição, e uma imagem
Comment: Então você não poderá usar o this. Nesse caso usaria $('a').attr("href")
Comment: desa forma aí ele vai pegar o primeiro link que aparecer no site


How do you theme a pager in a specific View?

Question: I have a few views, but each view would have a pager that would be themed differently. How do I go about targetting the pagers of each View for theming?
Answer: each view has own class like .view-id-name
so this class or id you can use to CSS your pager for each view
Comment: Thanks for your answer, but I must reiterate - I want to change the display output of the pager - changing the text and adding classes.


Unable to select option with Selenium IDE

Question: I can't select an option with Selenium IDE on my system:

Mac High Sierra
Firefox 52
Selenium IDE 2.9.1
(I know its old, but (normally) it works and I can't change it!

The select option has the following values:
<select name="t2_neurol_mot_l_t1" id="t2_neurol_mot_l_t1">
<option value="">Please select</option>
<option value="1">0</option>
<option value="2">0!</option>
<option value="3">1</option>
<option value="4">1!</option>
<option value="5">2</option>
<option value="6">2!</option>
<option value="7" selected="">3</option>
<option value="8">3!</option>
<option value="9">4</option>
<option value="10">4!</option>
<option value="11">5</option>
<option value="12">5*</option>
<option value="13">NT</option>
<option value="14">NT!</option>
<option value="15">NT*</option>
</select>

I need to select the last option NT* with value 15
All of these Commands don't seem to work correctly:
| Command       | Target                | Value     |
| select        | id=t2_neurol_mot_l_t1 | label=NT* |

| Command       | Target                | Value     |
| select        | id=t2_neurol_mot_l_t1 | NT*       |

| Command       | Target                | Value     |
| sendKeys      | id=t2_neurol_mot_l_t1 | NT*       |

| Command       | Target                | Value     |
| keyDown       | id=t2_neurol_mot_l_t1 | NT*       |

| Command       | Target                                         | Value     |
| clickAt       | css=select[name=drpReason] option[value=Other] |       |

The problem is the command select only selects NT, but not NT*
What would works is:
| Command       | Target                | Value     |
| select        | id=t2_neurol_mot_l_t1 | value=15  |

BUT, I dont have the value, so this option is not possible. I need to selected it with the label...
Any ideas? Could it be a problem of entities, since i can't select NT*, but NT! works...
You can try it on this page:
https://www.saccadic-training.com/is_test.html
Best regards
Beat
Answer: As * is used as regex criteria, it is not working. I tried with escape for *, it also didn't work.
But we can select NT* with xpath using click command,
| Command       | Target                      | Value     |
| click        | xpath=//option[text()='NT*']|           |

Comment: Nice idea. But does it work? I tried this: xpath=//select[@id='t2_neurol_mot_l_t1']/option[text()='NT*'], but i get this error: [error] Specified element is not a Select (has no options)
Comment: sorry for the typo. use click method. I have updated the answer
Comment: yes, i thought so... But that did not work for me... Did it work no your computer?
Comment: It should work 100% for u. Are u getting any error? It works for me in chrome and firefox. Both the selectors
Comment: Try clicking select box first , click   | id=t2_neurol_mot_l_t1 |   |, then click option  | click   | xpath=//option[text()='NT*']|           |
Answer: for the records, @Navarasu answers worked for me.
I couldn't select an option from my <select> tag -IDE error was that is was not a select element...)
I achieved filling my select with desired option like this :

**command :** click /// **target :** xpath=xpath_of_my_select
**command :** click /// **target :** xpath=//option[text()='**Foobar**']
any another command so that focus changes

NB : Foobar should be the desired option text value displayed on browser (not the "value" attribute in code if different)
NB : Might not work so well if there are 2 <select> elements


Bootstrap for CIs and Permutation Resampling for Hypothesis Test?

Question: In various scattered places online and StackExchange I've read that bootstrap resampling is more appropriate for calculating confidence intervals while permutation resampling is more appropriate for hypothesis testing, but why is this so (or is this generalization incorrect)?
I've seen it argued that this is because bootstrap resampling estimates the true population rather than the distribution under the null, but it seems to me that if confidence interval calculation is valid, the hypothesis testing is also appropriate via seeing if the null hypothesis value lies within the interval. Moreover, we can emulate the null distribution in bootstrapping by shifting our means (subtracting out the sample means and then adding back in the mean under the null).
Answer: Simply: The non-parametric bootstrap resampling generates datasets under the alternative hypothesis. Permutation resampling generates datasets under the null hypothesis. The CI probabilities are conditional upon the original sample estimate being the truth. The p-value probability is conditional upon the null hypothesis being the truth. Both procedures can perform the other's probability calculations with some simple to very complex modifications.
Comment: How does this address the pre-emption I raised that you *can* simulate the null distribution in bootstrapping fairly simply by shifting the means?
Comment: @Josh Because you can't do that for non-pivotal quantities.
Comment: I'm unfortunately ignorant as to what that ([not] for non-pivotal quantities) means :(
Comment: Actually I checked out the link @AdamO posted in the other comments on different bootstrap types which mentioned non-pivotal-ableness. (https://stats.stackexchange.com/questions/20701/computing-p-value-using-bootstrap-with-r/277391#277391) Which is quite helpful in understanding this issue also
Answer: Permutation tests address nonparametric hypotheses such as equal distributions of two samples or independence of two variables. These tests are exact in theory, and in practice approximation by Monte Carlo simulation is normally unbiased and very precise.
However, by nature they do not address parametric problems. It is true that there are parametric versions of equality and independence problems and permutation tests can be adapted to them. This includes computing confidence intervals, but these are cumbersome and do normally involve more assumptions than the permutation test would otherwise need.
Bootstrap tests on the other hand are usually biased. If a bootstrap and a proper permutation test can be set up for the same problem, there are in most cases good reasons to prefer the permutation test. However there are test problems for which there are no permutation tests (without tedious adaptation that may lose some of the original advantages) but that can be treated using bootstrap.
On the other hand, as permutation tests are by nature nonparametric, they don't lend themselves easily to confidence intervals.
So in general it's wrong to say that bootstrap is always preferable for CIs and permutation tests are always better for tests, however where a permutation test can be done it is usually better than a bootstrap test, and permutation CIs are tedious and problematic if available at all.
Comment: that made a ton of sense, particularly that last paragraph. I read it as Boostrap CIs are sometimes "preferred" more for their flexibility and ease of implementation given the other available options rather than their precision. I would be interested in more on what Bootstraps are more biased that permutation resampling if possible.
Comment: I can't go into detail here because this depends strongly on the precise parameter, estimator, testing problem. Bootstrap implicitly assumes that the observed empirical distribution is a perfect representation of the underlying distribution (at least regarding crucial aspects for the problem at hand), which is often true for sample sizes tending to infinity but usually not for finite samples. How this plays out depends critically on what exactly is done; often it is quite harmless, sometimes not.
Comment: This answer is wrong on many counts. Permutation tests have nothing to do with strong vs weak hypotheses. "Permuting" merely gives you a bunch of datasets simulating a null. Test for a two-sample mean difference using the sample mean, and you can "address" the parametric problem of estimating the center of a normal distribution. If you calculate the KS test statistic in those datasets, you can claim to test for a difference is CDFs, but the same hypothesis comes about using the *non-resampled* version of the test. The *wrong* bootstrap test will be biased, but correct versions are available.
Comment: The designation of the permutation test as "nonparmetric" has nothing to do with it's ability to "lend itself to confidence intervals". If anything, that's more to do with the fact it's a test and not an estimator. Still, the non-parametric Fisher's Exact test can easily be inverted to find confidence intervals. The *non-parametric* bootstrap is conceivably the gold standard example of a robust way to calculate confidence intervals. Examples of bootstrap tests here: https://stats.stackexchange.com/questions/20701/computing-p-value-using-bootstrap-with-r/277391#277391
Comment: I haven't said that these things can't be done; particularly I know that permutation based CIs can be constructed and they may well be fine for some problems. As far as I have seen theory for bootstrap in finite samples, there is always a bias term (normally going to zero with n to infinity). True, this can be reduced by more sophisticated/correct versions, but it can not normally be reduced to zero. Which of course doesn't mean that bootstrap isn't "available"; we can live with finite sample bias for many asymptotically motivated methods.
Comment: You are right that permutation and bootstrap as resampling principles have nothing specifically parametric or nonparametric about them. What I meant is that permutation gives you exact tests (independent of the underlying distribution) in problems in which the null is characterised by having the distribution of the test statistic unaffected by permutation, as opposed to the alternative. This is a "qualitative" characteristic that I'd see as essentially nonparametric, despite the fact that of course the test statistic can also be interpreted as estimating a parameter.


Customized search block

Question: I have a requirement in which there are two fields for search. One is text field and other is select box. The text field is for keywords and the select field are taxonomy terms. I need to fetch the values in both fields from text file and it should be autocomplete and display the results accordingly.
Please Help.
Thanks in Advance
Riya
Answer: You can try Custom Search module. This module alters the default search box in many ways. If you need to have options available like in advanced search, but directly in the search box.
The module adds options to select:

which content type(s) to search, which specific module search to use
(node, help, user or any module that implements search),
advanced criteria For all these choices, there are options to switch between a
select box, checkboxes or radio buttons,
You can also customize the selector label and the default <code>- Any -</code> text.

Customized search block


COntext used in other activity ,than main,giving null pointer exception in database operation

Question: @Override
public void onCreate(Bundle savedInstanceState) {

    /*Intent z=new Intent(this, HomePage.class);
    startActivityForResult(z, REQUEST_CODE);*/

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ctx = this;
    datasource = new CommentsDataSource(this);
    datasource.open();
    refresh();
}
private void refresh(){
    List<Comment> values = datasource.getAllComments();
    List<Comment> value_dif= new ArrayList<Comment>();
    for(int i=0;i<values.size();i++){
        Comment comment=new Comment();
        comment=values.get(i);
        if(comment.getToGive()>comment.getToTake())
            comment.setComment(comment.getComment()+" "+(comment.getToGive()-comment.getToTake()));
        else
            comment.setComment(comment.getComment()+" "+(comment.getToTake()-comment.getToGive()));
            value_dif.add(i,comment);
    }
    ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
            android.R.layout.simple_list_item_1, value_dif);
    setListAdapter(adapter);

    ListView listView = (ListView)findViewById(android.R.id.list);
    listView.setAdapter(new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, value_dif) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView textView = (TextView) super.getView(position, convertView, parent);
            List<Comment> values = datasource.getAllComments();
            Comment comment=datasource.getHisaab(values.get(position).getComment());
            if(comment.getToGive()>comment.getToTake()){
                textView.setTextColor(Color.RED);
            }
            else{
                textView.setTextColor(Color.GREEN);
            }
            /*String currentLocation = RouteFinderBookmarksActivity.this.getResources().getString(R.string.Current_Location);
            int textColor = textView.getText().toString().equals(currentLocation) ? R.color.holo_blue : R.color.text_color_btn_holo_dark;
            textView.setTextColor(RouteFinderBookmarksActivity.this.getResources().getColor(textColor));*/
            return textView;
        }
    });

}

IF i use the database operation in other activity by again creating the datasource object with giving context as this then it shows error......if i do database operation s in this activity everything runs fine.....
Answer: Initialize the ListView listView = (ListView)findViewById(android.R.id.list); in your onCreate or before setListAdapter(adapter); line in your refresh() method.
Comment: Thanks guys for all your answers...it was silly mistake by me...i didnt open the database ....:-|
Answer: Try with the application's context instead of the activity's context: replace this with this.getApplicationContext()


Rubik's Slide Proof's and Symmetries in a Rubik's Slide

Question: $\quad$In the February edition of The Mathematical Association of America Monthly there is a article called "$\mathit{Rubik's\ on\ the\ Torus}$". Where they are dealing with solving problems involving the electronic puzzle game called the Rubik's Slide.
$\mathbf{\underline{NOTE:}}$ I've given all the details about this topic that I believe will help give you an idea of what I'm working with. I've also tried to make this as clean as possible, but If you believe I should somehow break this up into a smaller question or multiple questions tell me and I will do it.
Important: Permutation Multiplication Goes From Left to Right in This Article!
$\mathbf{\underline{Introduction:}}$ So we have: $$\text {Vertical Shift} = (147)(258)(369)$$$$\text{Horizontal Shift} = (123)(456)(789)$$$$\text {Clockwise rotation around center}=(12369874)$$Where my $3\times3$ Rubik's Slide looks like this:
$$\begin{bmatrix}
        1 & 2 & 3\\
        4 & 5 & 6\\
        7 & 8 & 9
        \end{bmatrix}$$
$\mathbf{\underline{Lemma 1:}}$ The subgroup $<h,v>$ generated by $h$ and $v$ is abelian and of order $S_9$.
$\underline{Proof:}$ By computation we can see that
$$hv=(159)(267)(348)=vh.$$
We also know that $$h^3=\varepsilon=v^3$$
I believe now I can make the assumption that $$\text{"If a subgroup is generated by two cyclic groups is commutative that the subgroups is also abelian."}$$ I think it's a theorem, I just can't find it.
Thus $$<h,v>=\{h^iv^j:i,j=0,1,2\}=S_9$$
$\mathbf{\underline{Lemma 2:}}$ $$c^3h=(14)(2739568) \  \text{and} \ (c^3h)^7=(14)$$
$\underline{Proof:}$ By Computation.
The one that I really stuck on is this one,
$\mathbf{\underline{Theorem 3:}}$ The group $<h,v,c>$ contains every transposition in $S_9$; hence $<h,v,c>=S_9$
The proof that is given in the article states that to transpose two squares, $x$ and $y$
1) Repeatedly apply $h$ and $v$ to move $x$ to position $5$ and to call this series of moves $\sigma$
2) Repeatedly apply $c$ to move $y$ to position $2$ and call this series of moves $\tau$
3) Now apply $h^{-1}$ to move $x$ to position $4$ and $y$ to position $1$.
4) Now swap $x$ and $y$ using Lemma 2.
5) Lastly apply $h\tau^{-1}\sigma^{-1}$
6) Thus the resulting product of moves, $\sigma\tau h^{-1}(c^3h)^7h\tau^{-1}\sigma^{-1}=\ \text{transposition} \ (x,y)$
$\mathbf{\underline{What\ I\ Need\ Help\ With:}}$
I completely believe it works and have proven multiple cases. The problem I'm having is how to prove that it works for all choices of $x$ and $y$.
$\quad$So far I have been looking into conjugacy classes, but I can't seem to find a way to use them to prove this formula.
$\quad$The best Idea I've come up with is to prove that I can transpose any two neighbors with each other without effecting any other square. The reason I'm doing this is because once I prove that I can do that with every neighbor ($12$ cases) I can prove the big transposition equation by saying that any transposition is just the product of transpositions. Therefore since I can transpose every neighbor I can transpose any two squares on the Rubik's slide. So far I've only figured out a couple of the cases.
$\quad$This is where the symmetry comes in. If I can find the vertical and horizontal symmetries of the Rubik's Slide I believe I can narrow down my cases to like $4$ instead of $12$.
Comment: Which of the 6 steps in the proof do you have trouble with?
Comment: I understand the concept behind the proof, but I'm having trouble proving that step $6$ works for any possible combination of squares $x$ and $y$. I'm trying to come up with a mathematically rigorous proof.
Comment: x @Fmonkey: But step 6 just restates and summarizes what you have already done in the first 5 steps. If you agree that steps 1-3 combine to something that moves $x$ to position $4$ and $y$ to position $1$, then conjugating your known combination for $(14)$ with that setup _necessarily_ yields a transposition of $x$ and $y$.
Comment: I guess I'm having trouble writing it in a mathematically rigorous manner. I obviously am over thinking it, but I'm trying to make it rigorous enough to be able to present it to fellow graduate students.
Comment: In a presentation, I think making it more "rigorous" than the formulation you've quoted would amount to disguising the forest with trees. But depending on the audience, you might make a point of this being a _general_ technique for showing that a given set of permutations generate $S_n$: first show that _some_ transposition is made, then show that any two chosen elements can be brought into the right position, and conjugation then does the rest.
Answer: If you have trouble arranging your understanding of the proof, I suggest splitting it into two parts.
Lemma, for any permutation group. For any $x,y,a,b$, if $\rho$ is a permutation such that $\rho(x)=a$ and $\rho(y)=b$, then $\rho^{-1}(a\,b)\rho=(x\,y)$ -- or, depending on whether you compose left-to-right or right-to-left, $\rho(a\,b)\rho^{-1}=(x\,y)$.
You can prove the lemma completely algebraically, by verifying that the two permutations it asserts are equal take the same elements to the same results.
Observation. For any two different positions $x$ and $y$ on the slide, there is a sequence of moves that take $x$ to position $4$ and $y$ to position $1$.
This is just step 1,2,3 in the proof sketch, steps you say you do trust.
Corollary. Any transposition is realizable in the slide group, by the Lemma with $a=4, b=1$ and $\rho$ being the sequence of moves from the observation.


Error deploying webservice on weblogic: cannot cast to com.sun.xml.ws.spi.db.DatabindingProvider

Question: I'm trying to deploy a web-service in weblogic and I get the following errors:
    weblogic.management.DeploymentException: com.sun.xml.ws.transport.http.servlet.WSServletException: WSSERVLET11: Fallo al analizar el descriptor en tiempo de ejecución: com.sun.xml.ws.util.ServiceConfigurationError: com.sun.xml.ws.spi.db.DatabindingProvider: Provider weblogic.wsee.databinding.internal.wlsjaxrpc.JaxRpcProvider is specified in jar:file:/C:/Oracle/Middleware/Oracle_Home/oracle_common/modules/com.oracle.webservices.wls.wls-ws-metainf-services-impl_12.1.3.jar!/META-INF/services/com.sun.xml.ws.spi.db.DatabindingProviderbut could not be instantiated: java.lang.ClassCastException: Cannot cast weblogic.wsee.databinding.internal.wlsjaxrpc.JaxRpcProvider to com.sun.xml.ws.spi.db.DatabindingProvider

com.sun.xml.ws.transport.http.servlet.WSServletException: WSSERVLET11: Fallo al analizar el descriptor en tiempo de ejecución: com.sun.xml.ws.util.ServiceConfigurationError: com.sun.xml.ws.spi.db.DatabindingProvider: Provider weblogic.wsee.databinding.internal.wlsjaxrpc.JaxRpcProvider is specified in jar:file:/C:/Oracle/Middleware/Oracle_Home/oracle_common/modules/com.oracle.webservices.wls.wls-ws-metainf-services-impl_12.1.3.jar!/META-INF/services/com.sun.xml.ws.spi.db.DatabindingProviderbut could not be instantiated: java.lang.ClassCastException: Cannot cast weblogic.wsee.databinding.internal.wlsjaxrpc.JaxRpcProvider to com.sun.xml.ws.spi.db.DatabindingProvider

What am I doing wrong? I used jaxws-rt for my webservice
java web-services weblogic
Answer: You have a problem of clashing classes, the ones you ship in your deployment and the ones provided by WebLogic, as the error message is telling you:
Cannot cast weblogic.wsee.databinding.internal.wlsjaxrpc.JaxRpcProvider to com.sun.xml.ws.spi.db.DatabindingProvider

Set a filter in your web.xml to tell your application to prefer its own resources.
Comment: I added that property in the weblogic.xml configuration file: false


Windows Update Group Policy Removed but still shows up on Workstation

Question: I have a new Windows 7 SP1 workstation. Installation of updates failed, in part I believe because of a misconfigured AD domain controller. So I went through a lot of trouble on the workstation to get the updates to work (installing patches and deleting the below-mentioned registry entry), and I also went to the group policy editor in my Domain Controller and told it to no longer control Windows Updates in my domain. But hours later the workstation still says "Some settings are managed by your system administrator" in the windows update settings control panel, and I notice that- after I had removed HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate using regedit, and performed the updates- it is now back with the old settings (I can see that WUServer has the old entry in it).
My domain controller is running on Windows Server 2003 :-( (old, I know). How do I tell it to stop trying to control updates in the domain?
I had gone to the Group Policy Object Editor in the domain controller and changed all settings in Computer Configuration->Administrative Templates->Windows Components->Windows Update so that the state for each setting is "Not Configured". I also went to User Configuration->Administrative Templates->Windows Components->Windows Updates and made sure that all of those states are "Not configured".
I went to the Workstation and ran gpupdate /force in a cmd window as Administrator. I also have waited some hours since making these changes.
Still, it has reared its ugly head. How can I tell the domain controller to leave my poor workstations alone?
Ultimately, I want to configure a new domain controller with Windows 2012 r2 but I need the updates running nowish, and I'm too green to feel comfortable slamming an upgraded DC into place so I can get a supported solution. I just need this strange little problem to go away for right now.
Comment: Check the following registry settings on the Windows 7 workstation:

HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\WindowsUpdate if there is an entry named "DisableWindowsUpdate" in this path, then change the its value of 1 to 0.

Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\ExplorerNoWindowsUpdate (REG_DWORD) - change the value from 1 to 0.

I don't know for sure if changing one of these values will fix the issue because, honestly, it is hit and miss
Comment: In the past, I've had a workstation just not let go of the Domain level GPO giving it WSUS settings.  I had to edit the registry key "disablewindowsupdate" from 1 to 0.
Answer: I went to the Group Policy Object Editor and changed all settings in Computer Configuration->Administrative Templates->Windows Components->Windows Update so that the state for each setting is "Not Configured". I also went to User Configuration->Administrative Templates->Windows Components->Windows Updates and made sure that all of those states are "Not configured".
Do you mean that you did this on the local machine? If so, then you've modified the local Group Policy and not the domain Group Policy. You need to edit/modify the domain Group Policy by using the Group Policy Management Console on your Domain Controller.
Comment: My apologies for being pedantic about this, I'm just trying to understand how you're doing this. When you say that you're using the Group Policy Object Editor on the Domain Controller do you mean that you're using GPEDIT.msc or are you using the GPMC (Group Policy Management Console.? They're not the same thing.
Comment: @joeqwerty that is a great question to ask.  I would only add, using Group Policy Object Editor (gpedit.msc) on the Domain Controller is only looking at the local Group Policies for the domain controller.  Thus, only affecting the domain controller computer.  To control all computers in the domain you need to use the Group Policy Management Console.
Comment: No problem about pedanticness (obviously, I barely know what I'm doing). Regarding your question, I don't know for sure but I'll make a guess: GPEDIT.msc is run from a CMD window, and I didn't do that, but it does bring up a window that's identical to the one I've been using. It's entitled "Group Policy Object Editor". What I did do was open an app called "Group Policy Management" from the start menu. There, I drilled down into my Forest->Domains->(my domainname)->Default Domain Policy, then right-clicked, chose Edit, and it brought up the same window.
Comment: @MikeS: OK. Understood. As Art stated, using GPEDIT.MSC would be editing and affecting the local Group Policy on the Domain Controller, which is **not** what you want. Using the GPMC **is** what you want. If you've used the GPMC and are seeing the same results I'd suggest looking at the Scope of Management of the GPO. Is the Security Filtering set to "Authenticated Users"?
Comment: Ok, I see that there is not only the Default Domain Policy, but there are "Small Business Server Update Services Client Computers Policy" which, when I edit it, has Computer Configuration->Administrative Templates->Windows Components->Windows Update. And a bunch of stuff is Enabled. Likewise, I have Small Business Server Update Services Common Settings Policy. And I have Small Business Server Update Services Server Computers Policy. ...Yikes!
Comment: Is Inheritance blocked on those OU's? If you select one of those OU's in the left pane of the GPMC what GPO's do you see on the Linked Group Policy Objects tab in the right pane? Are your computer accounts in one of those OU's in ADUC?
Comment: I see 13 Linked Group Policy Objects in th LGPO tab in the right pane, and then from here http://www.howtogeek.com/116184/how-to-see-which-group-policies-are-applied-to-your-pc-and-user-account/ I found out how to find which Group Policies have been applied. There were a number of settings from the Small Business Server policies that I mention above.
Comment: @joeqwerty - Thanks, that did it. I have shut off the policy. Now I have to learn about GPOs :-)
Comment: No, it was on my domain controller. Updated my question.
Answer: As it turns out, there are a number of items in the Group Policies that control your domain. For a neophyte like myself, the methods are myriad and daunting. Thanks to @joeqwerty, this is what I discovered:

You can have local group policies and domain group policies. Make sure you are controlling the domain, by entering the Group Policy Editor from the Group Policy Management (GPM) window.
Inside GPM, you drill down into your Forest, then Domain, then your specific domain name. There you will see a list of items. My settings were in more than one of the items, including the Default Domain Policy and the Small Business Server Update Services Client Computer Policy.
Go to the workstation in question. We need to find which group policies are applied to my computer and account. See http://www.howtogeek.com/116184/how-to-see-which-group-policies-are-applied-to-your-pc-and-user-account/ . Specifically, from the Start Menu->Run box, enter rsop.msc
There, you'll find all the policy settings that were applied to the machine. Drill through them to find the setting that seems to apply.
Right click on it and chose "Properties". Click on the Precedence tab. It will show you the GPO Name that made this apply.
Go back to the Domain Controller, and find that Policy. Go into it and shut it off.
Wait a couple hours for the Group Policies to propagate, or run in an Administrator command prompt: gpupdate /force
Rerun rsop.msc and review your settings.
Comment: Re: #1 - There is "local policy" and "group policy". There are not any "local group policies"
Comment: @Craig620: I don't understand your comment. Of course there is a local group policy. The order of group policy processing is: LSDOU. Local, Site, Domain, Organizational Unit.
Comment: Oops... never mind, my mistake. Thought we were making up new terms. But I see know that is an actual term. I find the term "local group policy" misleading. If its "local" there nothing "group" about it, it's a single individual instance. Whats "group" about that?!
Comment: True enough. Microsoft goofed by calling it "Group" Policy. :)


Alice Phoebe Lou — Name of the fingerpicking technique

Question: Is there any special name for this fingerpicking technique?

Is the pattern just:
e|--------------|
B|-----------1--|
G|-----1--------|
D|--------T-----|
A|--T-----------|
E|--------------|

aka
e|--------------|
B|-----------i--|
G|-----i--------|
D|--------p-----|
A|--p-----------|
E|--------------|

…or more?
Comment: You'll find bottom string is D, not E. And I suspect 5th string is F#. Couldn't listen to much, sorry.
Answer: TL;DR

Is there any special name for this fingerpicking technique?

Yes. It is called the regular alternate thumb pattern.

It is indeed an African fingerpicking technique.
African fiddles in general are played with two fingers mainly (the thumb and the index finger), with occasional assistance from the middle finger in a pattern often referred to as the regular alternate thumb pattern. It is close to the classic arpeggio fingering style (for a pattern of two) which on the other hand is an utterance of the thumb and middle finger.
The regular alternate thumb pattern is a pattern which is often repetitive with a varieties of themes and variance just as fingering patterns (sequential order), syncopated rhythms, recitatives (based on regular language tonal expression used in communication involving local dialects), among other possible methods and pivoting mainly on the thumb finger usually for completing sequential loops of the harmony or simple utterances.
Please note that on a guitar this may extend to the use of the ring finger as the guitar is held in a manner that does not marginally require assistance from the hand of the player for stability.
Individuals mainly influenced with a taste, feel (whether played, watched or listened) or influence of typical native African instruments tend to limit themselves to a p and i alternate movement pattern, with occasional m, transposing this native African fiddle fingering technique, either knowingly or unknowingly, to the guitar.
Example of such instruments include the Kora and the Seperewa (Ghana mainly), both predominantly West African, which are mainly held and played directly with both hands, using thumbs and index fingers (with the middle finger occasionally) as other fingers contribute softly to grip and stabilise the instrument for fingering precision, even though supported sometimes and of late with a strap.
Answer: In classical guitar music notation, the use of your Thumb and Index finger (which is being used in the video) is:
Finger  Notation    Finger  Notation
Thumb   T           Thumb   p
Index   1           Index   i
Middle  2           Middle  m
Ring    3           Ring    a
Little  4           Little  c or x or e

She is using the following alternation pattern: p-i-p-i
Regular alternate thumb pattern.
Comment: I've seen her live a few times here in South Africa and from what I've observed she primarily uses her index finger and thumb. It's unorthodox but I see people doing it alot.
Answer: Alice Phoebe Lou is South African, so I'm going with my first impression, that this two-fingered picking style is based on African models. I'd look online for "African fingerpicking" tutorials, or listen to some of the amazing players from Mali.


Mat tooltip not working inside of material list-item

Question: My mat tooltip is not showing inside of my mat-list-item.
I have done the following:

Added MatTooltipModule & BrowserAnimationsModule
Tried making a class to put the tooltip in front of other elements.

This is the code:
<mat-accordion mat-list-option>
  <mat-expansion-panel [togglePosition]="'before'">
    <mat-expansion-panel-header>
      <mat-icon [svgIcon]="'heroicons_outline:user-group'"></mat-icon>
      <mat-panel-title>Channel members</mat-panel-title>
    </mat-expansion-panel-header>
    <mat-nav-list>
      <mat-list-item *ngFor="let users of currentUsers" mat-menu-item>
        <mat-icon
          class="items-begin relative"
          [svgIcon]="'heroicons_outline:user'"
          ></mat-icon>
        {{ users.data.displayName }}
      </mat-list-item>
    </mat-nav-list>
  </mat-expansion-panel>
</mat-accordion>

Does someone know how to fix this issue?
Answer: Hey welcome to Stack Overflow!
I think I at least got you closer to a solution. I believe your issue was just mismatching tags and attributes. I changed the matMenuItem to a matListItem and I changed mat-nav-list to just a mat-list. I also took out a lot to get a minimum reproducible example going, but I hope this at least gets you to where you need to be to finish it up!
I have the template and component files here for you, but I also encourage you to check out this stackblitz that I used to get this solution. I encourage you to fork it and make it how you need it for your specific example
import { Component } from '@angular/core';
import { TooltipPosition } from '@angular/material';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'basictooltip',
  templateUrl: 'basictooltip.html',
})
export class BasicTooltip {
  public currentUsers = [
    {
      data: {
        status: 'active',
        displayName: 'Ricky Bobby',
      },
    },
    {
      data: {
        status: 'active',
        displayName: 'Ricky Bobby',
      },
    },
    {
      data: {
        status: 'active',
        displayName: 'Ricky Bobby',
      },
    },
    {
      data: {
        status: 'active',
        displayName: 'Ricky Bobby',
      },
    },
  ];
}

<mat-accordion mat-list-option>
  <mat-expansion-panel>
    <mat-expansion-panel-header>
      <mat-icon></mat-icon>
      <mat-panel-title>Channel members</mat-panel-title>
    </mat-expansion-panel-header>
    <mat-list>
      <mat-list-item
        *ngFor="let users of currentUsers"
        matListItem
        class="absolute left-5 bottom-4 h-2 w-2 rounded-full"
        matTooltip="Show something!"
        matTooltipPosition="above"
      >
        {{ users.data.displayName }}
      </mat-list-item>
    </mat-list>
  </mat-expansion-panel>
</mat-accordion>

As promised, here is the stackblitz to go to play with this and make it how you need https://angular-tooltip-material-6synxp.stackblitz.io


Can't see any changes in nohup.out

Question: I have a python script that I run on a server with this command:
sudo nohup python fetch_script.py &

It creates a nohup.out file on the same directory.
After a few days I came back and tried to check it, I did:
tail -f nohup.out

It gave me a result:
root@xx-xxx-xxx-xx:/home/ubuntu# tail -f nohup.out
8809896
8809897
8809898
8809899
8809900
8809901
8809902
8809903
8809904
8809905

I waited a little bit but nothing happend. The script supposed to send messages to the RabbitMQ and update count and print it. The script was running the whole time, I know for sure, because I could see new messages where coming constantly. But nohup.out stuck. I also checked it with ls -l command to see if the size changed, but still no luck.
Do you know what could be the reason for that? I assume that it will be eventually updated but don't know how long it would take. So are there any ways to constantly update this file? Will nice -20 help in this case?
UPDATE
Just rotate the Log, with /usr/sbin/logrotate waited a bit and saw changes in fresh nohup.out
Comment: are you sure the process is still running?
Comment: The process is running, and the script is running also
Answer: The nohup.out file is written directly by the program that is being run under nohup, just like with normal shell redirection. If it's not being updated the problem is with the Python program, not with nohup itself.
Comment: It's more probable that the python process just decided to flush its output buffer to disk. What often happens with programs is that if their output is connected to an interactive terminal their output is line-buffered, so that every time that a line is written it is flushed to the output, but if the program is run with stdout redirected to a file it is block-buffered and the output file is updated less frequently.
Comment: Do you know if the file (`nohup.out`) will become large like 1G, could it be the problem of delay that I see in output?

Can't see any changes in nohup.out


Using regex to remove everything after "..."

Question: I have a string like this:

"Product DescriptionThe Signature Series treatment makes the strategy
  guide a COLLECTIBLE ITEM for StarCraft II fans. Single-player CAMPAIGN
  WALKTHROUGH covers all possible mission branches, including bonus
  objectives throughout the campaign. Exclusive MAPS found only in the
  official guide, show locations of units,... \n\n\n\n\n\n\nRead More\n"

How can I use regex the .text[/(...)/] to remove what's after the ... so that it outputs like below?

"Product DescriptionThe Signature Series treatment makes the strategy
  guide a COLLECTIBLE ITEM for StarCraft II fans. Single-player CAMPAIGN
  WALKTHROUGH covers all possible mission branches, including bonus
  objectives throughout the campaign. Exclusive MAPS found only in the
  official guide, show locations of units,..."
Comment: Why don't you split by `...` and take only the first element?
Answer: You need to escape the period.
string.sub(/(?<=\.\.\.).*/m, "")

or
string[/.*\.\.\./m]

Answer: You should be able to use the split method, something like that (I'm not that familiar with Ruby).
arr = text.split("...")  #=> text before '...' and text after '...'
arr[0]                   #=> text before '...'

Answer: No need to use lookarounds, you could simply do something like:
string.sub(/\.{3}.*/s, "...")

Answer: You can also do
/(^.*)(\.\.\..*)/.match(string).captures[0]


Views Full Pager alignment

Question: What would be the easiest way to make the Views PAGER text on a view aka first previous next etc, align center in the view?
Thank  you!
Answer: In Drupal 7, Views 3, we added text-align: center to our stylesheet:
<code>.item-list .pager {
    text-align: center;
}
</code>
And to make it only apply to one specific view:
<code>.view-id-my_view_name.view-display-id-page_1 .item-list .pager {
    text-align: center;
}
</code>

Views Full Pager alignment


Can we delete the older version jquery libraries from jquery_update module?

Question: The recent version of jquery_update module has 1.10 version of jquery library. And it also has older versions in it. Can we delete these older version files from the module? Will there be any problem if i delete them from the module directly?
Answer: You can delete them, as long as nothing is trying to use them, but they'll be restored when the module is updated.
They're only a few hundred kb between them, common sense might suggest to leave them where they are.


Porque o retorno da função recursiva não está sendo usado?

Question: O que acontece quando eu chamo uma função, recursivamente, sem atribuir o retorno dela a uma variável? Por que não há a necessidade, neste caso, de atribuir a função mergeSort explicitamente a variável array?
public static int[] mergeSort(int[] array, int inicio, int fim) {
        if (fim <= inicio) {
            return array;
        }
        int meio = (inicio + fim) / 2;
        mergeSort(array, inicio, meio);
        mergeSort(array, meio + 1, fim);
        int[] A = new int[meio - inicio + 1];
        int[] B = new int[fim - meio];
        for (int i = 0; i <= meio - inicio; i++) {
            A[i] = array[inicio + i];
        }
        for (int i = 0; i <= fim - meio - 1; i++) {
            B[i] = array[meio + 1 + i];
        }
        int i = 0;
        int j = 0;
        for (int k = inicio; k <= fim; k++) {
            if (i < A.length && j < B.length) {
                if (A[i] < B[j]) {
                    array[k] = A[i++];
                } else {
                    array[k] = B[j++];
                }
            } else if (i < A.length) {
                array[k] = A[i++];
            } else if (j < B.length) {
                array[k] = B[j++];
            }
        }
        return array;
    }
}

Answer: Porque array é um tipo por referência. Tipos por referência passados como argumento de métodos se confundem com o parâmetro. Ao contrário dos tipos por valor em que uma cópia do objeto (do valor) é feito na passagem do argumento para o método, neste tipo a cópia é a penas da referência, o objeto permanece o mesmo.
Então qualquer alteração que faça no parâmetro recebido se refletirá no argumento. Você não está alterando uma cópia e sim o que foi passado, por isso o retorno é desnecessário.
O retorno só seria necessário se a classificação fosse feita em outro array, como ele está sendo feito in-place (no mesmo array passado), o retorno é redundante. Eu particularmente tornaria este método com retorno void.
Tem mais informações sobre referência em outra pergunta.
Comment: Eu até tento responder rápido, mas ser mais rápido que você é quase impossível @bigown. Que horas você dorme mesmo? :-)
Comment: Eu nem tava aqui qdo foi perguntado :)
Answer: Isso acontece, pois a variável array é do tipo int[]. Isso é um vetor e todo vetor em Java é um objeto. Dessa maneira, sempre que você chama a função mergeSort de maneira recursiva como exibido abaixo, a referência desse vetor é passada (via passagem por valor) para a próxima chamada recursiva.
mergeSort(array, inicio, meio);

Em outras palavras, você está manipulando sempre o mesmo vetor na memória. Você nem mesmo precisa retorná-lo no fim da função.


Find $7^{1604} \mod28$

Question: How do I find $7^{1604} \mod28$? 7 and 28 aren't coprime, so I can't use Fermat's little theorem. How do I approach that types of problmes? Do I use Chinese Remainder theorem?
Comment: $7^1 \equiv 7 \pmod {28} $, $7^2 \equiv 21 \pmod {28} $, but $7^3 \equiv 7  \pmod {28}$ so the pattern repeats...
Comment: How about calculating $7^{1603}\mod 4$ instead?
Comment: Even, if there might be easier solutions, I always solve such congruences with the chinese remainder theorem. So I would suggest to do that. Another possibility is to use the Carmichael function. Here, the chinese remainder theorem almost immediately gives the solution.
Answer: A typical approach to problems with a fixed number to take modulo of is to break the number up to prime powers. In your case, you break $28$ up to $7\times 2^2$.
Next, use CRT to convert the problem to 2 subproblems, investigating the remainder modulo 7 and 4. The first one is obvious, you just get 0. What about the second one? Can you use Fermat's little theorem?
Don't forget to put everything together with CRT when you're done!
Answer: Using elementary math, $$7^{1604}=28q+r$$ so $r$ is divisible by $7$,
$$7^{1603}=4q+(r/7)$$
But $7=-1$ modulo $4$, so $7^{1603}=4m-1$. Hence $$r=7(r/7)=28-7=21$$
Answer: Indeed, use the Chinese remainder theorem,  more precisely the formula for the inverse isomorphism of
\begin{align}
\varphi:\mathbf Z/28\mathbf Z&\longrightarrow\mathbf Z/4\mathbf Z\times\mathbf Z/7\mathbf Z,\\
n\bmod 28&\longmapsto (n\bmod 4,n\bmod7),
\end{align}
which is deduced from a Bézout's relation between $4$ and $7$:
$2\cdot 4-7=1$,
$$\varphi^{-1}(x\bmod 4,y\bmod 7)=[y\cdot2\cdot 4-x\cdot 7] \bmod 28.$$

Find $7^{1604} \mod28$


How do you define definition symbol :=?

Question: How is "$:=$" defined formally and why?  "$\iff$", "$=$", ...?
Comment: := := :=, if you know what I mean. ;-)
Comment: After reading the answers I have arrived at a conclusion. Please tell me what you think about it. First of all ":=" is a symbol of the language. Hence the rules to use it are given in metalogic. I can think of: $\alpha := \beta \Longleftrightarrow \alpha \longleftrightarrow \beta$ if $\alpha$ and $\beta$ are formulas, and $\alpha := \beta \Longleftrightarrow \alpha = \beta$ if $\alpha$ and $\beta$ are terms in the language.
Answer: There is no need of a formal definition of a definition. A definition is just an abbreviation. For example, in formal arithmetic (number theory) we write $x\mid y$ ($x$ divides $y$) as an abbreviation for $\exists z (y=x\times z)$. Whenever $s\mid t$ is used, it can be replaced in principle by the "long" form.
Comment: Does is mean that it is a metamathical concept?
Comment: what about $\exists !x (\phi (x)) $ then $Tip=:x$?
Comment: In my answer above, I deliberately simplified to make a point. One can extend a language "by definition." Every so often in formal logic, the notion is useful.
Comment: Thank you so much for your answer. Although this doesn't answer my quesion directly this guided me to find my answer: https://en.wikipedia.org/wiki/Extension_by_definitions
Comment: In a more general sense: https://en.wikipedia.org/wiki/Conservative_extension
Answer: I do not know of any formal meaning of the definition symbol $:=$.  I have not seen it used in mathematical logic (although I'm sure someone somewhere has used it in some formal system.)
In ordinary mathematics, the definition symbol has an informal meaning, namely to signal that the current sentence serves as a definition of what follows the symbol.  Sometimes you can substitute $=$ for $:=$ and sometimes you can substitute $\iff$, so long as you add some words to make it clear that you are defining something.
For example, the sentence "$f(x) := x^2+1$" means "we define the function $f$ by $f(x) = x^2+1$" as opposed to "$f(x)$ turns out to equal $x^2+1$ even though the function $f$ was defined previously in some other way."  And the sentence "$P(x) := x > 1$" could be used to mean "we define the property $P$ by $P(x) \iff x>1$.
I think it is usually better to use words rather than the $:=$ symbol to make it clear that you are defining something.

How do you define definition symbol :=?


Use a T-bar as a snowboarder without pain

Question: Disclaimer: I originally posted this question on Lifehacks, but it unfortunately belongs on here. Since both sites are in beta I will leave the original question online.
I'd describe myself as a rather experienced snowboarder respectively T-bar rider. I used to fall out the T-bar when I was a beginner. So now, riding the T-bar to the top isn't a problem at all. I'm having a problem with the pain I get in my inner thigh. If it's one T-bar a day it's not bad at all. But if 90% of lifts are T-bars and I'm riding a whole week in the same resort, the pain in the evenings is tremendous.
I used to ride ski before riding snowboard, and as a skier the T-bars aren't a problem. They just pull at your butt and it won't hurt - even after a week.
I thought about placing a small cushion at my inner thigh but I'm worried, that it will restrict me while riding down the hills.
Pulling with my arms only temporarily decreases the pressure on my thigh.
I hope there's a hacky solution to prevent the pain in my inner thigh which hopefully won't restrict my leg in movement while riding my snowboard.
Possible solution could be using some kind of climbing harness as suggested by MaxD, but I haven't tried that.
Comment: Are you placing the bar behind your front leg or back leg? Also is your back leg strapped in or free?
Comment: @diggers3 Behind my front leg. My back leg is **not** strapped in.
Comment: what you can try is repositioning of your rear foot. Putting it next to your front foot can have some effect, but you will have less balance. The other thing you can do is holding the bar with your front hand and put other hand on the other side of the bar(if you're alone). Then you can pull yourself forward a bit with your front arm and use other hand to reposition the bar a bit, so that it hurts less
Comment: @Novarg I have tried both of your suggestions. When the track gets steeper I automatically place my rear foot close to the front foot (behind it, since next to it isn't possible because of the angle of the binding) to reduce the pressure. Pulling with my hands only works to reposition the T-bar before there's a steep section or to reduce the pain temporarily. Short rides are ok, bearable. I only have problems with **10mins lifts** with **>50% gradient**.
Answer: I would consider putting the bar behind your back leg, essentially under your butt cheek.
Here is a short video:
ehow.com Riding a T-Bar on a Snowboard
Comment: I couldn't try this the whole week, but the last day. It definitely doesn't hurt. But I think the T-Bar doesn't hold as good as placing it between my legs (e.g. riding hands free, for drinking or eating) plus my back leg got numb, if the ride goes on long/is steep.
I tried placing the T-Bar **on** and **under** my butt cheek - same effect.
Comment: I was able to test this thoroughly the last few days and it seems to be the easiest and best solution. I had to get used to it at first, also because my back leg is getting pulled to the front and I'm therefore not standing completely sideways anymore. Anyways, with some training I was even able to drink and eat while riding the T-Bar. I just had to be more aware of the bumps ahead. It is a quite unpleasant feeling at the butt of my back leg after some days but by far not as bad as the aching inner thigh after a week of riding the T-Bar the "usual" way.
Answer: I experienced the same problem, I would just take my scarf, wrap it once around it, so when I sit on it I won't lose it but I could take it away easily, and then use the rest as u cushion.
It's not the best solution, but it was the easiest for me and it took away alot of the pressure on my leg
Answer: I tend to hook it behind my front leg, but I do rest against the upright/cable with my arm/hand. This gives you more freedom to move the point of pressure, especially on a long/steep climb, and as I have damage to my spine from an old injury I need some way to do this, but it does preclude eating/drinking.
As I don't eat or drink while on the board this doesn't bother me, but it might annoy you if that is what you like to do.


How to delete all but last [n] ZFS snapshots?

Question: I'm currently snapshotting my ZFS-based NAS nightly and weekly, a process that has saved my ass a few times. However, while the creation of the snapshot is automatic (from cron), the deletion of old snapshots is still a manual task. Obviously there's a risk that if I get hit by a bus, or the manual task isn't carried out, the NAS will run out of disk space.
Does anyone have any good ways / scripts they use to manage the number of snapshots stored on their ZFS systems? Ideally, I'd like a script that iterates through all the snapshots for a given ZFS filesystem and deletes all but the last n snapshots for that filesystem.
E.g. I've got two filesystems, one called tank and another called sastank. Snapshots are named with the date on which they were created: sastank@AutoD-2011-12-13 so a simple sort command should list them in order. I'm looking to keep the last 2 week's worth of daily snapshots on tank, but only the last two days worth of snapshots on sastank.
Answer: You may find something like this a little simpler
zfs list -t snapshot -o name | grep ^tank@Auto | tac | tail -n +16 | xargs -n 1 zfs destroy -r

Output the list of the snapshot (names only) with zfs list -t snapshot -o name
Filter to keep only the ones that match tank@Auto with grep ^tank@Auto
Reverse the list (previously sorted from oldest to newest) with tac
Limit output to the 16th oldest result and following with tail -n +16
Then destroy with xargs -n 1 zfs destroy -vr

Deleting snapshots in reverse order is supposedly more efficient or sort in reverse order of creation.
zfs list -t snapshot -o name -S creation | grep ^tank@Auto | tail -n +16 | xargs -n 1 zfs destroy -vr

Test it with ...|xargs -n 1 echo.
Comment: He stated "deleting snapshots in reverse order is supposedly more efficient", thus the sort order.
Comment: I think this needs a `sort -r` before the `sed` command. `sed` seems to output the bottom of the list beyond the first 15 lines, which in the default sort is the most recent. Flipping the list means I get the oldest snapshots at the bottom.
Answer: This totally doesn't answer the question itself, but don't forget you can delete ranges of snapshots.

zfs destroy zpool1/dataset@20160918%20161107

Would destroy all snapshots from "20160918" to "20161107" inclusive. Either end may be left blank, to mean "oldest" or "newest". So you could cook something up that figures out the "n" then destroy "...%n"..
Sorry to resurrect an old question.
Answer: More general case of getting most recent snapshot based on creation date, not by name.
zfs list -H -t snapshot -o name -S creation | head -1
Scoped to a specific filesystem name TestOne
zfs list -H -t snapshot -o name -S creation -d1 TestOne | head -1
-H:No header so that first line is a snapshot name
-t snapshot: List snapshots (list can list other things like pools and volumes)
-o name: Display the snapshot name property.
-S creation: Capital S denotes descending sort, based on creation time.  This puts most recent snapshot as the first line.
-d1 TestOne: Says include children, which seems confusing but its because as far as this command is concerned, snapshots of TestOne are children.  This will NOT list snapshots of volumes within TestOne such as TestOne/SubVol@someSnapshot.
| head -1: Pipe to head and only return first line.
Comment: Thanks for the `-d1`. That was the key to the question "How do I get all snapshots for a given dataset?"
Answer: You might also want to check out zfs-prune-snapshots.

Remove snapshots from one or more zpools that match given criteria

It has a fairly robust time based mechanism for deleting snapshots, an example from the docs:

Remove snapshots older than two months on the tank pool that end with the string "_frequent"
zfs-prune-snapshots -s '_frequent' 2M tank
Comment: wow! nice&&neat. doing exactly what is needed
Comment: This should be updated to be the accepted answer, much cleaner than all the bash-fu.
Comment: how do you install it on ubuntu?
Comment: @tatsu this is a script so you dont need to install, just download the script. You can do so with: `git clone https://github.com/bahamas10/zfs-prune-snapshots.git`

Once you have the code, `cd zfs-prune-snapshots` and to run it: `zfs-prune-snapshots --help`

You will likely want to add the path to where `zfs-prune-snapshots` is located to your path. You can also run `make man` to generate a manpage for it (see the 'Manpage' section https://github.com/bahamas10/zfs-prune-snapshots#manpage
Answer: growse's didn't work on OpenIndiana for me. It didn't understand -0 for xargs.
If using sort, be aware that it sorts alphabetically which may not be desired as you are probably wanting to find the most recent.
Here is code that will delete all but the last snapshots.
Remove the 'echo' to go live.
RETENTION=5
FS=tank1/test
SNAPNAME=daily-

zfs list -t snapshot -o name | grep ^$FS@${SNAPNAME} |  sed -n -e :a -e '1,${RETENTION}!{P;N;D;};N;ba' | xargs -n 1 echo zfs destroy -r

Sources:
http://sed.sourceforge.net/sed1line.txt
Comment: Upvote because anyone who can use sed like that deserves it.
Comment: After a recent software update, that sed string stopped working for me and it started deleting all snapshots! bad sed! Luckily the production server was old and stayed safe.

I now use  sed -n -e :a -e '1,${RETENTION}!{P;N;D;};N;ba'
Comment: I've never seen anyone SED like that.
Comment: I have only become aware of this thread a few days ago, but it appears some time in the last few years there has been another software update that broke this script. This is the sed line that worked for me: sed -n -e :a -e "1,${RETENTION}!{P;N;D;};N;ba" . In my case, at least, double quote marks were needed.
Answer: I may have solved this with some bash-fu.
 zfs list -t snapshot -o name | grep ^tank@AutoD- | sort -r | wc -l | xargs -n 1 expr -$NUM_TO_KEEP + | tr -d '\n' | xargs -0 -i bash -c "zfs list -t snapshot -o name | grep ^tank@AutoD- | sort -r | tail -n{} | sort |xargs -t -n 1 zfs destroy -r"

Wow. It feels so wrong.
Answer: Just wanted to chime in on how I'm doing this on FreeBSD and OmniOS:
Get number of snapshots:
zfs list -t snapshot -o name | grep ^tank@Auto | wc -l
141

Subtract number you want to leave for n (e.g. 30 for a month of latest daily snapshots):
zfs list -t snapshot -o name | grep ^tank@Auto |  head -n +111 | xargs -n 1 zfs destroy -vr

Note how I replaced tail with head to delete in order from oldest to newest, since there's no tac command on FreeBSD
That's it!  Works great for me...
Answer: The path for head is needed on Solaris, but should work without the path on other distros.
retention=14
dataset=vmstorage-17/824

zfs list -rt snap -H -o name ${dataset} | \
/usr/gnu/bin/head -n -${retention} | xargs -n 1 zfs destroy -r

Answer: Identify the latest two snapshots for a given dataset (creation, newest to oldest)
zfs_latest=`zfs list -H -t snapshot -o name -S creation | grep ^tank/example_dataset@ | head -2`

Identify ALL snapshots for a given dataset (creation, newest to oldest)
zfs_delete=`zfs list -H -t snapshot -o name -S creation | grep ^tanks/example_dataset@`

Remove latest snapshots from all set; creating a list of snapshots to delete.
for keep_snap in ${zfs_latest[@]}; do
  zfs_delete=( "${zfs_delete[@]/$keep_snap}" );
done

Remove the old snapshots
for snap in ${zfs_delete[@]}; do
  zfs destroy ${snap}
done

Answer: If someone wants to do recursive snapshots of the entire pool's datasets, I wrote this script to do just that:
#!/bin/bash

#Method to purge old snapshots. $1 is the dataset that snapshots are being purged for. $2 is the number of snapshots to retain.
purge_snapshots() {
  echo -e "\n  Purging snapshots for: $1"

  #We search for snapshots and return jsut the name sorted by creation time. We filter with grep just for snapshots created with this script with prefix "$1@auto"
  snapshots=$(zfs list -t snapshot -H -o name -S creation "$1" | grep ^"$1"@auto)
  if [[ -z "$snapshots" ]]; then
    echo -e "\n    No snapshots found for dataset"
    return 0
  fi
  echo -e "\n    Existing snapshots for $1:\n"
  echo "$snapshots"

  #We use "tail -n +" to skip the first $2 snapshots. We need + 1 to begin after that many snapshots. This gives us the list of snapshots to purge
  old_snapshots=$(echo "$snapshots" | tail -n +"$(($2 + 1))")
  if [[ -z "$old_snapshots" ]]; then
    echo -e "\n    Not enough old snapshots too purge"
    return 0
  fi
  echo -e "\n    Deleting the following old snapshots:\n"
  echo "$old_snapshots"
  echo "$old_snapshots" | xargs -n 1 zfs destroy -r
}

#Function to create snapshots. it receives the list of snapshots in $1 and retention count in $2.
create_snapshots() {
  formatted_date="$(date +"%Y-%m-%d_%H-%M-%S")"

  #We loop the list of datasets and create and purge snapshots for each of them with the same timestamp. this way all child datasets will have the same timestamp and retention count as the root dataset.
  while read -r dataset; do
    echo -e "\nCreating snapshot for: $dataset"
    snapshot_name="${dataset}@auto-${formatted_date}"
    zfs snapshot "$snapshot_name"
    echo -e "\n  Snapshot created: $snapshot_name"
    purge_snapshots "$dataset" "$2"
  done <<< "$1"
}

#We validate the input arguments. $1 is the pool name and $2 is the retention count.
if [ "$#" -ne 2 ]; then
  echo "Usage: $0 poolname retentioncount"
  exit 1
fi

if [[ -z "$1" ]]; then
  echo "poolname cannot be empty"
  exit 2
fi

if [[ "$2" -le 0 ]]; then
  echo "retentioncount must be a positive number"
  exit 3
fi

#We get the list of data sets in the pool recursively so that we include every single child dataset in the pool.
datasets=$(zfs list -H -o name -r "$1")
echo -e "Datasets in pool $1:\n"
echo "$datasets"
create_snapshots "$datasets" "$2"

Comment: I am an avid supporter that good code is its own documentation. I believe the code is self evident. but I will add some comments to clarify some bash syntax that may be confusing.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Here is my version of Dan Buhler's script:
\# Ref: https://manpages.ubuntu.com/manpages/kinetic/man8/zfs-destroy.8.html

\# To get a list of datasets:
\# zfs list -t snapshot -o name -S creation

\# To get a list of memory usage:
\# zfs list -r -o space

\# The number of the most recent snapshots to be retained:
RETENTION=5

\# The datasets to prune with filesystem and snapshot name:
\# Format: <filesystem>@<snapshot name>
declare -a SNAPS=(
\# Example array elements:
bpool/BOOT/ubuntu_7pdn8o@autozsys_
rpool/ROOT/ubuntu_7pdn8o/usr@autozsys_
rpool/ROOT/ubuntu_7pdn8o/var/cache@autozsys_
rpool/USERDATA/root_kpsn24@autozsys_
)

echo Deleting all but the last $RETENTION system snapshots.
for SNAP in ${SNAPS[@]}
do
echo SNAP=${SNAP}
\# The dry run (comment out when satisfied all is well):
zfs list -t snapshot -o name | grep ^${SNAP} | sed -n -e :a -e "1,${RETENTION}!{P;N;D;};N;ba" | xargs -n 1 zfs destroy -nprd
\# For real (uncomment when all is well):
\# zfs list -t snapshot -o name | grep ^${SNAP} | sed -n -e :a -e "1,${RETENTION}!{P;N;D;};N;ba" | xargs -n 1 zfs destroy -rd
done

After running this it may be necessary to reboot before all is finally deleted.
I configured my Ubuntu 22.04 OS to run this script whenever it boots.


Quick way to create multi-array with same size of another without iterating?

Question: Just a quick question is there a quick method of creating a new multi-array with the same as another without iterating through each of the first arrays (as it could be a jagged array).
I haven't found such a solution yet so wondering if it exists or not. Just wondering if Java already has a handy efficient way of doing so?
Example if I wasn't clear:
int[][] array1 = new int[5][4];
int[][] array2 = // quickly (one line) make this the same as above based on array1 without iterating through each first array?

Just to clarify, I don't care about the contents, just the size.
Answer: You can try:
int[][] array2 = new int[array1.length][array1[0].length];

assuming that your array will always be square and that you don't have dimensions of 0.
Comment: For the question example of [5][4], I thought this would create [4][5]
Comment: @anonymous Yes, I had the dimensions flipped; thanks!
Comment: Yeah I thought about that originally with the assumption that it will always be a square, which although I have been told should, I shouldn't rely fully on it... If only Java kept track of the length of the largest inner array, then I wouldn't mind a lit bit of wasted space if it was jagged.
Answer: you can try java.util.Arrays#copyOf
Comment: See the last sentence of the question.
Comment: @arshajii So then it doesn't matter that they are the same :)


$f: R^{m} \rightarrow R^{n}$ be defined $ f(x)=B \cdot x+b $ where $B$ is an $n$ by $m$ matrix, and $b \in R^{n}$. Show $f$ is differentiable at $a.$

Question: Definition. Let $A \subset \mathbf{R}^{m},$ let $f: A \rightarrow \mathbf{R}^{n} .$ Suppose $A$ contains a neighborhood of a. We say that $f$ is differentiable at a if there is an $n$ by $m$ matrix $B$ such that
$$
\frac{f(\mathbf{a}+\mathbf{h})-f(\mathbf{a})-B \cdot \mathbf{h}}{|\mathbf{h}|} \rightarrow \mathbf{0} \quad \text { as } \quad \mathbf{h} \rightarrow \mathbf{0}
$$
The matrix $B$, which is unique, is called the derivative of $f$ at a $;$ it is denoted $D f(\mathbf{a}).$

Question. Let $f: R^{m} \rightarrow R^{n}$ be defined by the equation
$$
f(x)=B \cdot x+b
$$
where $B$ is an $n$ by $m$ matrix, and $b \in R^{n}$. Show that $f$ is differentiable at $a.$

My Answer. Take $B=Df(x)$. Then when we apply the definition we get
$$
\frac{f(\mathbf{a}+\mathbf{h})-f(\mathbf{a})-B \cdot \mathbf{h}}{|\mathbf{h}|}=\frac {B \cdot \mathbf{h}-B \cdot \mathbf{h}} {|\mathbf{h}|}=0
$$
as $h\rightarrow 0.$
Therefore $f$ is differentiable at $a$.
Can you check my answer? Thanks...
Answer: Yes, that is correct.
$f(a+h)=B(a+h)+b=Ba+Bh+b$
$f(a)=Ba+b$.
Hence, $f(a+h)-f(a)=Bh$.
Therefore setting $Df(a)=B$ gives you the desired result.


db error, axios get method returns (TypeError: int() argument must be a string, a bytes-like object or a number, not 'AnonymousUser') 500

Question: I am trying get a list of data associated with logged in user, I am using vuejs, axios and drf. corsheader activated on both sides.
I succeeded getting auth token, change the state and save it in the local storage.
the code is failing in getting user specified data, here is my codes:
views.py
class blogsListView(generics.ListAPIView):
    def get_queryset(self):
        return CodeNote.objects.filter(user=self.request.user)
    serializer_class = blogsSerializer

myblogs.vue

the console shows the token successfully. I am not sure if I am doing the right request, or the problem is with filtering.
Answer: There are few checks you need to do.

Check If you have add Default Authentication  class  in REST Framework Setting. Implement Whichever you wish to have.

 REST_FRAMEWORK = {
                'DEFAULT_AUTHENTICATION_CLASSES':(
                    'rest_framework.authentication.BasicAuthentication',
                    'rest_framework.authentication.SessionAuthentication',
                    'rest_framework.authentication.TokenAuthentication',
                )
    }

In Your View You must Add permission_classes. If you want to provide access to only authenticated users.

  class blogsListView(generics.ListAPIView):
        queryset = CodeNote.objects.all()
        serializer_class = blogsSerializer
        permission_classes = [IsAuthenticated

If your want to provide access to both authenticated and normal users.
you must check if user is authenticated and process accordingly.

 def get_queryset(self):
     if self.request.user.is_authenticated:
        return CodeNote.objects.filter(user=self.request.user)
     return []

Check If Token you are sending from local storage from frontend actually exists in Database.
All in One

    class blogsListView(generics.ListAPIView):
        queryset = CodeNote.objects.all()
        serializer_class = blogsSerializer
        # permission_classes = [IsAuthenticated]

        def get_queryset(self):
            if self.request.user.is_authenticated:
                return CodeNote.objects.filter(user=self.request.user)
            return []

Comment: It is working in normal backend api view, but in the front end not. I will try your suggestions, thank you.
Comment: @omeraiman. Sure please check updated answer. Let me know if it helps. Thank you
Comment: I am getting empty response. I think the problem is in the request from the front end using axios. I am not sure if I am sending the token right attached with the request.
Comment: Can you show error? May be the token is expired one or wrong one. Check if token you are sending exists in database. ie token from local storage with database
Answer: it worked out, thank you @bkwan for help, I add rest framework settings, and edited the axios request like this:
 REST_FRAMEWORK = {
                'DEFAULT_AUTHENTICATION_CLASSES':(
                    'rest_framework.authentication.BasicAuthentication',
                    'rest_framework.authentication.SessionAuthentication',
                    'rest_framework.authentication.TokenAuthentication',
                )
    }

 def get_queryset(self):
     if self.request.user.is_authenticated:
        return CodeNote.objects.filter(user=self.request.user)
     return []

axios
      .get(API_URL + "blogs/mylist", {
        headers: { Authorization: `Token ${token}` }
      })


Covariate analysis comparing distributions / means of circular data

Question: Are there publicly available software packages to run an analysis comparing the means or distributions of two samples of circular data with the presence of a covariate? If not, are there ways to modify existing tests to account for the potential covariate?
I am able to run a Watson-Williams test or a non-parametric Watson's U2 on just the circular data, but I believe that another variable will moderate the effect of the angular mean differences.
Answer: Instead of modeling the circular angles directly, a common approach is to project them onto a normal distribution, after which a variety of statistical tests (such as ANCOVA and mixed-effects models) can occur.
The R package bpnreg has a regression function (bpnr), that does this conversion and regression. A guided example can be found in this reference. Here is the snippet that they used:
fit.Motor <- bpnr(pred.I = Phaserad ~ 1 + Cond, data = Motor, its = 10000, burn = 100, n.lag = 3, seed = 101)


question on homeomorphisms of $\mathbb{R}^2$

Question: Let $R$ be the set of rectangles with sides parallel to axes.
Let $h$ be a homeomorphism of $\mathbb{R}^2$ such that $h(r)\in R$ for any $r\in R$.
Does it imply that $h(x,y)=(f(x),g(y))$ or $h(x,y)=(g(y),f(x))$ for $f,g$ being homeomorphisms of $\mathbb{R}$?
Comment: @Mankind You seem to have misread the question.  $h(r)$ is required to be an element of $R$, not a subset of $r$.
Comment: What can $h$ even be except the identity? For instance $h(]x-\epsilon;x+\epsilon[\times ]y-\epsilon; y+\epsilon[) \subseteq ]x-\epsilon;x+\epsilon[\times ]y-\epsilon; y+\epsilon[$ for all $x,y$ and all $\epsilon>0$.
Answer: Let $h\colon\mathbb{R}^2\to\mathbb{R}^2$ be a homeomorphism that preserves $R$. Observe that we can characterise straight line segments as intersections of rectangles: If we have a straight line segment $L$ parallel to one of the axes, then there are $r,r'\in R$ such that their interiors are disjoint and their intersection is $L$. On the other hand every such intersection is either a point or a straight line segment. Since $h$ preserves $R$ and is a homeomorphism, it also preserves line segments parallel to one of the axes.
Now let $h\colon\mathbb{R}^2\to\mathbb{R}^2$ be a map that preserves lines parallel to the $y$-axis. Then there is a map $f\colon\mathbb{R}\to\mathbb{R}$ such that the $x$-coordinate of $h$ is given by
$f(x)$, that is $h(x,y)=(f(x),y')$ for some $y'$. This is just a reformulation of what it means to preserve lines parallel to the $y$-axis.
In conclusion, up to switching the $x$ and $y$ axis, we may assume that $h$ preserves lines parallel to both axes seperately. Then by the above, there are maps $f$ and $g$ that give the $x$ and $y$ coordinate of $h$, i.e. $h(x,y)=(f(x),g(y))$.
In the other case we get that $h(x,y)=(f(y),g(x))$.


Does imputation introduce unacceptable bias?

Question: I have recently come to know about imputation techniques, which, in short, "guess" realistic values with which to replace missing values in a dataset. My big issue with this is that we are guessing data by assuming that they are similar to the ones we already had, which is going to reinforce any pattern that might be in the data, potentially turning a non-significant pattern into a significant one. How is this practice acceptable? What am I missing?
I am relatively new to the topic but I have done some studying and I am aware that imputation techniques range from replacing all NA with a fixed "realistic" value, to replacing it with the mean value of the observed values, to guessing the missing values with nearest-neighbor methods or with maximum likelihood methods. While I understand how these methods work I cannot shake off me the idea that they are crafting data. Imputation techniques differ in complexity and in how close to real the crafted data may look, but they are still crafting data. To me, this practice defeats the whole point of statistics as a tool to draw realistic inferences about a population based on a real, untampered sample of it, and not just a realistic sample of it. My question, to paraphrase Ian Malcolm, is not about whether we can do it but whether we should.
The first of Tukey's principles against statistician's hubris states:

The combination of some data and an aching desire for an answer does not ensure that a reasonable answer can be extracted from a given body of data.

(From "Sunset Salvo", The American Statistician 40(1), 72-76, February 1986)
Doesn't imputation collide with it?
I realise that it may just be my ignorance talking, which may be making any statistician reading this livid. If that's the case, please enlighten me. I would also appreciate pointers towards relevant literature. So far I only read the relevant chapter in Robinson's "Forest analytics in R". Cheers!
Comment: +1. This is precisely why I have always been extremely uncomfortable with the entire concept of imputation for missing values. I'm looking forward to learning from answers.
Comment: (+1)  @StephanKolassa The key to it understanding this is where data are missing completely at random, or missing at random (missing data can be predicted from observed), all should be, good provided the imputation model is specified correctly.  I'm talking about multiple imputation btw. The problem is that when data are missing not at random, things can fall apart pretty quickly, and there is no way to know when data are MNAR unless you "know" they are, and even when you do it's difficult to do anything about. Will try to answer in detail if I have ime later :)
Comment: I think you are missing the fact that sensible multiple imputation methods do not simply create a single value but a range of values ( eg dont replace by mean but by random samples with same mean and standard deviation), so that you see an uncertainty in your estimates. (and obviously if you can avoid imputation then you should, but given the choice of making some sensible estimate and no estimate I know what I would choose)
Comment: @seanv507: even sampling from a distribution *that was learned from the valid observations* will tend to reinforce our (possibly misplaced) confidence in precisely this distribution, so the critique would still stand. Regarding your choice: if you can't get a useful estimate without imputation, then I would question what you would base your imputation on - and whether any estimates based on that imputation would be of any use.
Comment: I really don't like imputation. I think it's just a work around to when you don't want top do proper MLE estimation with missing data
Comment: It depends on the data, which could be rich in spatial correlations, for example. So, try selecting a set of random points from your data whose values are known. Look at naive forecasting models assuming these points are indeed missing. For example, try the nearest neighbor as a predictor, or the average of nearest neighbors or the overall sample mean as a point estimate. The naive model producing the smallest defined average error over the selected data set would be my choice. Could repeat with other point selections for validation. Note, error estimates encompasses bias assessment as well.
Answer: There is no clear cut answer here. The fun though is that one can verify the effects of the imputation using a validation procedure: let the data decide!
Should one throw away a feature if a few values are missing? Or the observations then? What if those observations have valuable information in the other features and your algorithm cannot handle missing values? And so on.
Imputation, like removing observations or features, is just a way of dealing with missing values. The decison of which one is best should be supported by good machine procedures like (cross-)validation.


Navigating to view

Question: In a storyboard I have added 2 views. On each there's a TabBar (I'm doing navigation programmatically).

I added ViewController class to my view with table:
MediaListViewController.h
MediaListViewController.m
And on my main view i do this:
<code>-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    if(item.title!=@"All")
    {

         MediaListViewController *tableViewController =[[MediaListViewController alloc] init];
        [self.navigationController pushViewController:tableViewController animated:YES];
    }
}
</code>
It enters MediaListViewController loaded function, but my view from StoryBoard doesn't sghow up. just black screen.
What am i doing wrong?
I finally did this, almost...
PROBLEM 2:
I have added this:
<code>UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    MediaListViewController *viewController = (MediaListViewController *)[storyboard instantiateViewControllerWithIdentifier:@"Table"];
    [self.navigationController pushViewController:viewController animated:YES];
</code>
But now, for some reason TabBar doesn't show up - how to fix it?
As you can see from screenshot - there is TabBar
Comment: Please include the code of how you are creating the views.
Comment: Do you actually load your controller from the storyboard? Alloc/init isn't enough...
Answer: Maybe you forget to set frame of your tableViewController?
Try to put tableViewController.frame = CGRectMake (some rect);
Comment: use this tutorial http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1
Comment: This is a comment not an answer.
Answer: Constraints weren't set correctly, thats why my app TabBar was somewhere out of rang of display

Navigating to view