When does one show a function is well defined?

Question: Sometimes in Linear Algebra, we just use linear transformations, and other times we have to check to make sure they are well defined. Since I'm not an experienced mathematician or anything, I can't seem to see the fine line between needing to show if a linear transformation is well defined or not. Could anyone who understands the nuance please explain it to me?
Edit: For example, when we began working with quotient spaces we had to show addition was well defined. In problems, if we wanted to construct a linear transformation from a quotient space to a vector space, we had to show that the linear transformation was well defined and linear. In the past, however, when we constructed linear transformations between vector spaces, we just had to show that they were linear, and we didn't talk about it being well defined.
Comment: You might want to include some examples in your question, so answerers can refer to those and know what you really are asking about.
Comment: The short answer is : always. Except that very often, functions you define are compositions of other functions and so their well-definedness just follows from that of composition, and that of the other functions that you already know are well-defined. Since these are then "obviously" well-defined, the question is swept under the rug and not mentioned. This becomes much less clear with, e.g. quotient spaces, where you often define maps on a class by saying what it does to a *representative*. There you have to explicitly check
Comment: See some comments [here](https://math.stackexchange.com/questions/60781/symmetric-groups-on-sets-with-the-same-number-of-elements-are-isomorphic/60788#60788).
Comment: Cf. [Wikipedia](https://en.wikipedia.org/wiki/Well-defined); a classic situation is when a function is defined on classes, and it must be shown that it is the same for all representatives of a class
Comment: I added a little more clarification the question, thank you
Answer: You need to show a function is well-defined when its definition involves some arbitrary choice. To illustrate this, imagine we have three functions $f,g, h: \{\text{high schools in your city}\} \to \{\text{people}\}$.
$f$ is "defined" as follows: if $x$ is a school, take a student, $y$, from that school. $f(x)$ is defined to be $y$'s father.
$g$ is defined as follows: if $x$ is a school, take a student, $y$, from that school. $g(x)$ is defined to be $y$'s principal.
$h$ is defined as follows: if $x$ is a school, take a student, $y$, from that school. $h(x)$ is defined as $y$'s current math teacher.

There is a problem with the definition of $f$. Namely, it depends on what student you pick from the school. You didn't specify how to choose the student, so the "function" isn't well defined---any given input doesn't correspond to exactly one output.
On the other hand, high schools students from the same school all have the same principal, so $g(x)$ is well-defined.
Now what about $h$? Well it depends. If the school has multiple math teachers, it isn't. But maybe each school has exactly one math teacher who teaches all the students. It's possible $h$ is well-defined, but it might not be depending on the circumstances. If you want to use the function in a mathematical context, you need to show that it actually makes sense.

Now back to linear algebra. If you're constructing a function from a quotient space, your probably did something like this:

take an element from the quotient space $V/W$. This has the form $v +W$ for some $v \in V$ (ie the coset of $v$). Now [do something with $v$] to get the value $f(v + W)$.

There is a potential problem with this definition: the coset $v + W$ can likely be represented by many different choices of $v$, but we define its image in terms of a single representative. There's a chance our definition depends on this choice, so we need to check that it doesn't in order for our function to make sense.
(To make an analogy with the above, the cosets are schools, the different $v$'s which represent cosets are the different students which might schools)
Comment: The school analogy is very nice.
Answer: Here is a linear algebra example.
Let $V$ be a finite dimensional vector space, say with $V= \operatorname{span}(e_1, \dots, e_n)$. Consider arbitrary vectors $v_1, \dots, v_n \in V$ and define a map. By our assumption, we can write every vector $v\in V$ as a sum
$$v= \sum_{i=1}^n a_i e_i$$
with $a_1, \dots, a_n \in \mathbb{R}$
$$f: V \to V:v=\sum_{i =1}^n a_i e_i \mapsto \sum_{i=1}^n a_i v_i$$
Is this well-defined? This is obvious you will say! But in fact it is not obvious and this is not even well-defined. Indeed, suppose that we can write $\sum_{i=1}^n a_i e_i = \sum_{i=1}^n b_i e_i$ where $a_i \neq b_i$ for some $i$, or equivalently when $\{e_1, \dots, e_n\}$ is linearly dependent. Then $f$ is not well-defined as it is not clear that we should assign the value $\sum_{i=1}^n a_i v_i$ or $\sum_{i=1}^n b_i v_i$ to $f(v)$.
So, if there are choices made to define an object, you must try to show that the $f$-value is invariant under all these choices. Then your map will be well-defined.
Of course, there is no rule that works in general.


ruby on rails: undefined method `_path'

Question: I'm getting the error from line #7 of my views when I'm trying to create a new room:
undefined method `rooms_path' for #<#<Class:0x007fb46b5db2a0>:0x007fb46b5d9ec8>

I'm a little confused about why am I getting this error. I have built a relationship between Room and Facility that each Facility has many Rooms. The Facility part works bug free, I've been able to create/edit/show facilities.
Views (views/rooms/new.html.erb)

    Create your beautiful room

      <%= form_for @room do |f| %>

          Name
          <%=f.text_field :room_name, placeholder: "What is the name of the room?", class: "form-control", required: true%>

<%= f.submit "Create This Room", class: "btn btn-normal" %>

      <%end%>

My Room model (models/room.rb):

class Room < ApplicationRecord
  belongs_to :facility

  validates :room_type, presence: true
  validates :room_name, presence: true
end

My Facility model (models/facility.rb):

class Facility < ApplicationRecord
  belongs_to :user
  has_many :photos
  has_many :rooms

  validates :facility_name, presence: true
  validates :address, presence: true
  validates :license, presence: true
  validates :phone, presence: true

  def cover_photo(size)
    if self.photos.length > 0
      self.photos[0].image.url(size)
    else
      "blank.jpg"
    end
  end

end

My Rooms Controller(controllers/rooms_controller.rb)

class RoomsController < ApplicationController
  before_action :set_room, except: [:index, :new, :create]

  def index
    @facility = Facility.find(params[:facility_id])
    @rooms = @facility.rooms
  end

  def new
    @facility = Facility.find(params[:facility_id])
    @room = @facility.rooms.build
  end
 end

Routes (routes.rb)

Rails.application.routes.draw do
  devise_for :users,
              path: '',
              path_names: {sign_in: 'login', sign_out: 'logout', edit: 'profile', sign_up: 'registration'},
              controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'}

  resources :users, only: [:show]
  resources :facilities, except: [:edit] do
    member  do
      get 'listing'
      get 'pricing'
      get 'features'
      get 'services'
      get 'types_care'
      get 'photo_upload'
      get 'room_upload'
    end

    resources :rooms, except: [:edit] do
      member  do
        get 'listing'
        get 'pricing'
        get 'photo_upload'
      end
    end

    resources :photos, only: [:create, :destroy]
  end
end

Been stuck on this for a couple of days and would really appreciate the help :) Thanks so much in advance!
Comment: Hey Could you add the output of `rake routes`...
Comment: https://stackoverflow.com/questions/2034700/form-for-with-nested-resources rooms are a nested resource in your case
Answer: Choose any of the following for form_for instead of <%= form_for @room do |f| %> as your routes are nested
<%= form_for @room, url: [@room.facility, @room] do |f| %>

<%= form_for @room, url: [:facility, @room] do |f| %>

<%= form_for [@room.facility, @room] do |f| %>

<%= form_for [:facility, @room] do |f| %>

Here you can get more detail about form_for helper
Answer: form_for generate url based on class of @room, it doesn't include outer resource. Thus, you have to tell Rails to do that explicitly using below statement:
<%= form_for [@room.facility, @room] do |f| %>

ruby on rails: undefined method `_path'


Extract text with newline

Question: I am using this pattern
const string ptnBodytext = @"
\s*(.+?)\s*
";

in order to extract the text within the
 tags. It works fine except for those text with newline, e.g.:

    Lorem ipsum
    second line or
    third one?

How can I change the pattern in order to include newline, tabs and so on?
Comment: If you are parsing HTML: http://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c
Comment: Well, why not use `.Replace("", "").Replace("", "")`?
Answer: You either need to activate the dotall mode or:
const string ptnBodytext = @"
([\s\S]+?)
";

See a demo on regex101.com.
Comment: `const string ptnBodytext = @"(.+?)";`  and pass the `RegexOptions.Singleline`  flag when building the regex object.
Answer: Just remove the \s*:
const string ptnBodytext = @"
(.+?)
";

Comment: [**Not** true](https://regex101.com/r/yG5hW3/1) without [`DOTALL`](https://regex101.com/r/yG5hW3/2) mode. Additionally, `\s*` matches *zero* or more whitespace characters.

Extract text with newline


Is it possible to generate xsd from asmx

Question: I have a webservice provided by third party company , The web service return xml as string , like :
<code><string xmlns="http://www.BMS.co.il/">
<?xml version="1.0" encoding="utf-8"?>
 .....
</code>
Is there any possibility to generate XSD from asmx ? Then I can Create classes from this and not to parse those things manually.
Thanks.
Answer: XSD.Exe will generate xsd and then you can use this to generate classes,
<code>  xsd file.xml [/outputdir:directory]
</code>
"If you specify an XML file (.xml extension), Xsd.exe infers a schema from the data in the file and produces an XSD schema. The output file has the same name as the XML file, but with the .xsd extension.
If you specify an XML schema file (.xsd extension), Xsd.exe generates source code for runtime objects that correspond to the XML schema."
also,
If you have wsdl(you must have) then you can directly generate classes from it using WSDL.EXE
<code>     wsdl http://hostServer/WebserviceRoot/WebServiceName.asmx?WSDL
</code>


I want to call a function on onclick but that function should be inside another function

Question: Javascript code:
function abc() {
  function def() {
    //do something
  }
}

HTML code:
<button onclick="def()">click me</button>

I get the error def() is not defined.
Comment: def is not part of the global scope, that's why you cannot access it with event handlers. you could return `def` from `abc` and call `abc` like so `abc()()`
Comment: def is private scoped function of abc, what is significance of keeping def inside abc?
Comment: you can do `onclick="abc()"` and in abc run `def()`
Comment: So are you saying that there is no way to accomplish this task?
Comment: @SaketSuraj to accomplish your task i have answered below
Comment: There is some important data in abc() function so that is being used in def(). So I need to put def() inside abc().
Comment: It would be best to use `addEventListener`
Comment: What is private, should be private.
Comment: @SaketSuraj did you try my answer?
Comment: @juanram0n yes I did try your solution, unfortunately it was not working.
Comment: @SaketSuraj I have just added a code snippet with the complete code in my answer, you can try it. It works. Greetings.
Answer: Try this.
 function def(){
         //do something
       }
function abc(playDef){
       if(playDef){
        def()
     }
    }
<button onclick="def(true)">click me</button>

For more functions you can pass arguments and manage if condition
Answer: You only need to declare def in global scope:
function abc(){
   window.def = function(){
       console.log("hello, I'm function def");
   }
}
abc();
def();

But remember you need to call abc first to get access to def function.
Hope this helps. Good luck.
I have completed my answer with a code snippet, you can try the working solution:

function abc(){
   window.def = function(){
       console.log("hello, I'm function def");
   }
}
abc();
<button onclick='def();'>Click Me!</button>


Proof or disprove: There exists a real $n \times n$ matrix $A$ that satisfies the equation when $n$ is even.

Question: Prove or disprove: There exists a real $n \times n$ matrix $A$ with
$$
A^2+2\cdot A+5\cdot I_n = 0
$$
if and only if n is even.
I could not find a counterexample for an odd $n$. Therefore, I suspect that the statement is true, but I have not yet found a solution.
Answer: If $n$ is odd, then $A$ has a a real eigenvalue $\lambda$. But then $\lambda^2+2\lambda+5=0$ and no such real number exists.
If $n=2$, consider$$A=\begin{bmatrix}-1&-2\\2&-1\end{bmatrix}.$$It will work because its eigenvalues are $-1\pm2i$, which are the roots of $\lambda^2+2\lambda+5$.
Can you generalize this for $n$ even and greater than $2$?
Answer: Suppose that you have $A \in \mathcal{M}_n(\mathbb{R})$ satisfying $A^2+2A+5I_n=0$. Then $A$ is diagonalizable in $\mathbb{C}$ and its possible eigenvalues are
$$\lambda=-1+2i \quad \text{and} \quad \mu=-1-2i$$
Let $k$ be the multiplicity of $\lambda$ and $l$ be the multiplicity of $\mu$. You must have
$$\mathrm{Tr}(A)=k\lambda + l\mu = (-k-l)+i(2k-2l)$$
But because $\mathrm{Tr}(A) \in \mathbb{R}$, you deduce that $k=l$, so $n=k+l=2k$ is even.
Answer: A possible generalization of Santos's answer:
Note that $A^T$ also satisfies the equation. Hence $A^2+2A+5I_n = {A^T}^2+2A^T+5I_n$ => $A^2-{A^T}^2=-2(A-A^T)$ => $(A+A^T)(A-A^T)+AA^T-A^TA = -2(A-A^T)$ => $(A+A^T+2I_n)(A-A^T)=-AA^T+A^TA$. Now take transpose on both sides: we now have:
$-(A+A^T+2I_n)(A-A^T)=-AA^T+A^TA$. Hence $(A+A^T+2I_n)(A-A^T)=0$. Since $A\neq A^T$ as this would mean $A$ is symmetric and real eigen values. A guess (not the answer) is to assume $A$ is skew symmetric and hence we have: $A= -A^T-2I_n$ and hence we have $a_{ii}=-a_{ii}-2$. Hence $a_{ii}=-1$. This is a possibility.
Also we have from original equation: $A(A+2I_n)/5 = -I_n$. Hence we have $-5A^{-1}=A+2I_n$. If we substitute this in $A= -A^T-2I_n$ then we get $-5A^{-1}=-A^T$=> $5I_n = A^TA$. hence one possibility is to choose $A$ as a skew symmetric orthogonal matrix with diagonal entries $-1$ with norm if each column $5$. This matches the idea of solution given by Santos.


Is it possible to get info on other installed iOS apps?

Question: Is it possible to read the contents of another application installed on an iPhone? What about from an extension or keyboard?
I'm trying to come up with something that 'checks' other apps to see if they have any deep links (like Twitter's Twitter://timeline that takes users straight to the timeline in the Twitter app).

Is there any smart way to check a given app for deep links?
Is it even possible to peek at another app's contents from within my app? I suspect no.
If no, what about making a keyboard or extension of some sort that I can access from an app like Twitter and see its contents, such as a URL deep link?
Answer: You don't have much options, you may use <code>-canOpenURL:</code>, but, since iOS9, must include special credentails listing all the custom schemes you want to check.
You can't read other app's contents on a non-rooted device unless this app is sharing a keychain (so it can exchange data via the shared keychain). The same thing goes with extensions.
iOS has some high bars on security, so, don't expect much or even, anything.
Something you may want is IntentKit. Also there are ideas around the web about standard url query format like MobileDeepLinking.


Settings disabled in flash context menu

Question: I have two flash movies, both seem to have the same embed/object params and publish settings, but one will display the 'settings' option and one won't.
I would really like the user to be able to select the settings, but can't figure out how to force it to be enabled, or even find any information on under which circumstances it would be disabled.
Google just wants to tell me about custom context menus, which is not quite the point.
Anyone got any clues?
Answer: Argh. It was the stage size of the flash movie - too small to display the settings dialog.
Answer: Guess, minimal dimensions to enable settings menu item provided in this discussion will be helpful to anyone:

It appears that there is a minimum width and height requirement for
  the settings dialog to be enabled.
Try setting your swf width >= 215px and height >= 138px.

Settings disabled in flash context menu


Media query não funciona em site não responsivo

Question: Boa tarde a todos, eu coloquei media query css3 para funcionar em um site com largura fixa, mas não funciona. Só funciona em sites responsivos?
http://bblender.com.br/clientes/moldin/
@media only screen and (max-width: 959px) {
.tit-h2{margin-left:2px!important;}
#rodape{
width: 104%;
height: 180px;
background: #F68624;
position: absolute;
bottom: 0;}}

Obrigado a todos.
Answer: Você deve colocar a METATAG VIEWPORT no cabeçalho HEAD da página:
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">

OBS: Você pode modifica-lá a sua necessidade alterando o valor dos atributos:

width - Define uma largura para o viewport. Os valores podem ser em
PX ou "device-width", que determina automaticamente um valor igual a
largura da tela do dispositivo.
height - Define uma altura para o viewport. Os valores podem ser em
PX ou "device-height", que determina automaticamente um valor igual a
altura da tela do dispositivo.
initial-scale - Define a escala inicial do viewport.
user-scalable - Define a possibilidade de o usuário fazer "zoom" em
um determinado lugar da tela. É ativado quando o usuário bate duas
vezes com o dedo em um lugar da tela.

Com CSS você só define os estilos para cada resolução.
A METATAG é para informar o dispositivo que a largura que ele deve usar é a largura que aparenta ter, e não a da resolução dele que é em PIXELS.
Você precisa utilizar CSS com MEDIA QUERIES e a METATAG VIEWPORT.
Recomendo que você comece a trabalhar com medidas relativas ao invés de fixas para trabalhar com layouts responsivos pois são mais adequadas.
Comment: resolvi, esta assim agora.

@media only screen and (max-device-width: 959px) {
    .tit-h2{margin-left:2px!important;}
    #rodape{
    width: 104%;
    height: 180px;
    background: #F68624;
    position: absolute;
    bottom: 0;
}
}
Comment: Se utilizar assim (max-device-width: 959px), ele vai funcionar somente em devices. O monitor é um desktop, não um dispositivo mobile. Se você colocar só o min-width, max-width, ele irá atender a qualquer tipo de tela, não apenas a mobiles e por isso deve-se utilizar a metatag viewport.
Comment: Vlw pela dica, mas foi mesmo só neste caso especial que precisava  ajeitar este detalhe do titulo.


Can't use varien

Question: In the template register.phtml I added an input type radio for some terms and condition agreements.
This one is required.
I didn't success to use the javascript Magento's frontend validation. I add all sort of classes but nothing worked.
Is Someone knows how to do please ? thanks
Here the html

        <input type="radio" name="accept" title="<?php echo $this->__('I Agree to our Terms & Conditions') ?>" id="accept"  class="radio required-entry validate-one-required-by-name validation-passed validation-failed" >
        <?php echo $this->__('I Agree to our Terms & Conditions') ?>

Comment: What exactly your register file look?
Comment: have you removed this new Varien.FileElement('accept'); or not?
Comment: So it should work. in my form its working fine have you find any javascript error in console?
Answer: First of all remove all class other then required-entry
<input type="radio" name="accept" title="<?php echo $this->__('I Agree to our Terms & Conditions') ?>" id="accept"  class="radio required-entry" >

And put this in your form tag, you don't need to create any javascript for this just ensure that it is under form tag, in register.phtml file magento already define validation javascript so don't put your javascript again.
Comment: Thanks Mufaddal for your answer but unfortunatly this doesn't walk.
Comment: ok I had deleted the script which instancied the varien validation.
Answer: @Mufaddal

            <form action="<?php echo $this->getPostActionUrl() ?>" method="post" id="form-validate" enctype="multipart/form-data" class="ctools-use-modal-processed" novalidate="novalidate">

                    <input type="hidden" name="success_url" value="<?php echo $this->getSuccessUrl() ?>" />
                    <input type="hidden" name="error_url" value="<?php echo $this->getErrorUrl() ?>" />

<?php  echo  $this->getLayout()->createBlock('customer/widget_name')->setObject($this->getFormData())->setForceUseCustomerAttributes(true)->toHtml() ?>

                    *Email Address

                        <input type="text" name="email" id="email_address" value="<?php echo $this->escapeHtml($this->getFormData()->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" class="input-text validate-email required-entry" placeholder="<?php echo $this->__("Email Address") ?>" />

                        *<?php echo $this->__('Password') ?>

                            <input type="password" name="password" id="password" title="<?php echo $this->__('Password') ?>" class="input-text required-entry validate-password" placeholder="Password" />

                        *<?php echo $this->__('Confirm Password') ?>

                            <input type="password" name="confirmation" title="<?php echo $this->__('Confirm Password') ?>" id="confirmation" class="input-text required-entry validate-cpassword" placeholder="Confirm Password" />

                        <input type="radio" name="accept" title="<?php echo $this->__('I Agree to our Terms & Conditions') ?>" id="accept"  class="radio required-entry" >
                        <?php echo $this->__('I Agree to our Terms & Conditions') ?>

                        __('Submit') ?>" id="form-submit">
                            __('maak mijn profiel aan') ?>

                </form>

Can't use varien


Routing public IPs (each a /32) through a VPN to another server

Question: Hopefully the title makes sense; I have a server currently in a colo facility, with many IP addresses routed to it. They are individual IPs and not in a contiguous block.
Due to vastly improved connectivity (fibre) at home I am slowly bringing my infrastructure in-house for managability and eventually, cost savings. What I would like to do though is use the IP addresses allocated to my existing server, at home. I have an IP block allocated to me on my new ISP connection, but for a couple of reasons I'd like to make use of the colo ones for now:

Ease of transition - lots of domains, dns, hard-coded IPs in programs, etc.
Connectivity fallback. If my primary line goes down and switches to
fallback 1 (dsl) or fallback 2 (4G), I lose access to the
ISP-allocated IP block of IPs that are only presented on the primary
WAN interface.

What I'd like to achieve is my home virtualisation server (Proxmox/Debian-based) "dials in" to the colo server in the colo facility (also Proxmox/Debian) via VPN or similar, and gets to make use of the IP addresses that currently terminate on the colo box. If the primary connection to my ISP goes down and one of the fallback routes kicks in, the VPN tunnel will just time out and then be re-established on the backup connection instead.
I'm sure this is doable, but I have no idea how. I'm not afraid to get my hands dirty, I just don't really know where to start?
Comment: Don't host anything important at home.
Answer: This is quite a broad question so it's hard to give very specific answers, but the way I'd solve it by building a VPN between your home network and your server using either OpenVPN or some IPsec based solution like OpenSwan (might be a bit tougher to configure). On your router set the default gateway to the VPN connection (OpenVPN can push a route for this, probably even better), and on your server, configure NAT so traffic coming from your home network is using one of your server's IP addresses for external connectivity.
Comment: Apologies for the broad start, but when you don't really have a clue of how to achieve something broad is a good place to start. I think "install OpenVPN and play" is probably about as specific as I'm going to get as an answer for now. I was just hoping someone else may have done this or similar already and could throw some tips/iptables rules my way :)


Difference between DateTimeOffset?(Nullable) and DateTimeOffset.Now

Question: How can I calculate the time between between a nullable DateTimeOffset? to DateTimeOffset.Now ?
I need the result like "x day y hours ago"
I started by doing something like this.
  var creationTime = //A nullable DateTimeOffset on Database
  var difference = DateTimeOffset.Now.Subtract(creationTime);

But since creationTime is a nullable time, it gives me an error and I can't really find the difference.
Comment: You can use the `-` operator.
Answer: Depending on what difference you expect from a NULL database value you can simply handle this using the ?? operator:
DateTimeOffset? creationTime = null; // A nullable DateTimeOffset on Database
DateTimeOffset rightnow = DateTimeOffset.Now;
DateTimeOffset somewhen = creationTime ?? rightnow; // if NULL, it's NOW
var difference = rightnow.Subtract(somewhen);

(could of course be shortend to using ?? just when reading the database value)
Comment: Thanks @Filburt. That worked in the first try. I really appreciate it.
Answer: First test if it has a value with HasValue and if it does use the Value property to get the actual value
if(creationTime.HasValue)
    TimeSpan difference = DateTimeOffset.Now.Subtract(creationTime.Value);

Or if you have a default value in mind you can use GetValueOrDefault
TimeSpan difference = DateTimeOffset.Now.Subtract(creationTime.GetValueOrDefault(default));

A final option would be to just use the - operator.
TimeSpan? difference = DateTimeOffset.Now - creationTime;

but note that difference will be a TimeSpan? and will be null if creationTime is null.
Comment: Thanks you very much. I'll keep the idea of checking value in future.
Answer: Just in case anyone comes across this issue, here is the extension method that I came up with the help of above answers.
namespace Extensions{
public static class DateExtensions
{
    public static string GetDifferenceTillNow(this DateTimeOffset? datetimeoffset) {
        DateTimeOffset? creationTime = datetimeoffset;
        DateTimeOffset rightnow = DateTimeOffset.Now;
        DateTimeOffset somewhen = creationTime ?? rightnow;
        TimeSpan difference = rightnow.Subtract(somewhen);
        return difference.Days.ToString() +" days & " +  difference.Hours.ToString() + " hours ago";
    }
  }
}


A Hausdorff space such that all of its subspaces are compact.

Question: As I understand the definition of a subspace, I can simply take any subset of a topological space and promote it to a subspace by endowing it with the subspace topology. Then in this case every subset of my Hausdorff space, endowed with the subspace topology for whatever topology the space has, is compact. Therefore every subspace is a closed subset. I would like for this generalization to be true since from here I think I can go on to talk about the topology on my Hausdorff space being the discrete topology and the space being finite.
Comment: What is your question, exactly?
Comment: It's indeed true all subsets are closed
Comment: @EricWofsey If I can take the fact that every subspace is closed to an extreme of sorts by saying every subset of my space endowed with the subspace topology is a subspace and so every subset of my space is closed.
Comment: It is still not clear what your question is, but let me tell you that your conclusion that every space satisfying the condition of the title is finite discrete, is correct.
Comment: Sorry for being unclear. I just want to make sure that I can say every subset of my space is closed from the assumption that every subspace of my space is compact. As an additional question, since discreteness is incredibly easy to prove if all the subsets of my space are closed, what would you recommend I try to show finiteness? This part actually is not as easy as I thought it'd be.
Comment: Well if the space is infinite, there is an infinite subspace. This subspace is discrete and compact, so it can't be infinite. contradiction.
Answer: Let $A \subset X$. Then by assumption, $A$ (in the subspace topology, what else?)
is compact. A compact subspace in a Hausdorff space is closed. So $A$ is closed.
So all subsets of $X$ are closed, so all subsets have a closed complement as well, so all subsets are open too. Hence $X$ is discrete etc.
Comment: @MatemáticosChibchas Yes, he already concluded that according to the question.


is there a way to change icon of the installer file using jpackage?

Question: I have a simple modular javafx application.
i compile it using
dir /s /b src\*.java > sources.txt & javac --module-path %PATH_TO_FX% -d mods/hellofx @sources.txt & del sources.txt

This creates mods directory
I then create runtime image using the command
jlink --module-path "%PATH_TO_FX_MODS%;mods" --add-modules hellofx --output hellofx

This creates the runtime image in hellofx directory
Now i use the jpackage command to create the windows installer. In the directory i have an icon for the application.
jpackage --runtime-image hellofx --module hellofx/hellofx.HelloFX --win-shortcut --win-menu --icon smile.ico

This icon was used for the installed application but is there a way to create an icon for the installer file itself? The installer file named HelloFX-1.0 doesnt have an icon. Is there a way to configure jpackage to also change icon of this file? Thanks for the help!
Answer: Under the hood the jpackage tool uses platform-specific tooling to create the various package types. The customization of the packaging is therefore also very platform-specific and has to be handled individually for each supported platform and package type. However, there are two common features of jpackage that you can use to make this task easier.
The first one is the option --temp some_temp_dir which asks jpackage to copy all scripts and resources needed to create the selected package type into a directory some_temp_dir. These are the scripts and resources that jpackage would use by default.
The second one is the option --resource-dir some_resource_dir which asks jpackage to first look for resources in the directory some_resource_dir and then use its defaults only for the ones it does not find there.
With these two options you can first generate a set of default resources from which you can pick the ones you want to modify and copy them over to the directory some_resource_dir. In a second run of jpackage you can then apply these changes. The most likely changes you can make this way is to exchange the default icons, used by the various package types, with your own ones.
Comment: thank you. can you also look into this issue ? https://stackoverflow.com/questions/62227980/why-jpackage-icon-not-used-in-windows-search-toolbar thanks for help!
Comment: Sorry, I can't help you with that because I have not much experience with Windows. I only tried this on my Mac.


How to implement a transparent proxy over akka http

Question: I need to implement a lightweight sharding service over http using AKKA HTTP. To illustrate the idea please let me introduce a fake service with only one REST resource list called /users/. Customer can create new users by POSTing to the list, or query existing useers by its ID  /users/:userID.
The sharding service simply routes to the right shard (concrete service). For POST it creates a new ID and decides which service will handle, for GET or DELETE it gets the ID of the user and routes to the one handling it.
The following image shows how it works.

I am new to the AKKA HTTP framework, but given the concrete service is already implemented, I just have to implement a sort of transparent proxy in front that will take requests from client, and then forwards the right concrete service according to the routing strategy.
Is there any simple implementation in akka that does just that?
Answer: This link is a repo containing a solution that does a round robin for a reverse proxy implemented using akka htttp. A small shange to handle sharding instead will solve this question.


Gerar número sequencial em java

Question: Olá, eu tenho uma classe Aluno com os atributos nome e matrícula. O usuário pode inserir o nome pelo setNome(), mas gostaria de saber como faço pra que a matrícula seja gerada automaticamente (1, 2 , 3, ...)
Comment: Você está salvando num banco de dados?
Comment: @MaiconCarraro Não
Answer: Cria uma classe que vai possuir o valor static e que sempre vai te retornar o valor com incremento, exemplo:
GeradorMatricula.java
public class GeradorMatricula {
    private static int ID = 1;

    public static int getProximaMatricula() {
        return ID++;
    }
}

Utilizando
public static void main(String[] argv) {
    System.out.println(GeradorMatricula.getProximaMatricula());
    System.out.println(GeradorMatricula.getProximaMatricula());
}

Saída

1
2
Comment: O `ID` deveria ser inicializado com zero.
Comment: Na verdade não @ramaral, seria necessário zero apenas se eu retornasse `++ID` ao invés de `ID++`.
Comment: Tem razão, peço desculpa, distracção minha.
Comment: @ramaral Estamos aqui pra se ajudar, não se preocupe :)

Gerar número sequencial em java


can't access www.livesite.com/admin

Question: I have just transferred my local server to a live site. I am able to log in as an administrator, but I am not able to access my administrator tools. The page directs me to a blank page. Initially I was able to change the site's theme, through the admin tools, but now I can't even do that. I am not sure what am I doing wrong, or if there is something that I have to change in the settings.php file etc?
Btw, the site update was using ftp only.
Comment: Chech out http://drupal.org/node/158043/
Answer: A blank page often indicates a PHP Error. Is there an error in the PHP error logs you can reference?
Also, when uploading via FTP, you want to be sure that you properly transferred your .htaccess file which, on some Operating Systems, will be hidden on your local filesystem.
Comment: I checked the .htcaccess files, they seem to be present in certain folders. Should it be present in all folders?
Comment: Which folders? I would assume your sites/default/files path and probably the document root. Do you have access to the watchdog to check for possible PHP errors?
Answer: I think you are getting a memory_limit error for admin pages. Usual admin pages will take more memory. Please check the error log  and increase the memory_limit.
Comment: how do you increase memory_limit?
Comment: http://drupal.org/node/207036  I followed this, and now my site won't even show up. www.asblab2012.mie.utoronto.ca
Comment: Your problem still exist or resolved?Have yuou checked your error log?
Answer: Look in settings.php and change domains path, from your local to live domain.
Comment: It can be a memory issue as John said. *Only way to find out is looking into your log files.*
Comment: I modified $base_url: asblab.mie.utoronto.ca  . It is weird, because i am able to access the admin/build/blocks, but others I cant access. Is it possible that my theme is protected or something?  Thanks.
Comment: is the admin theme on the first box installed on the second?
Comment: I am really sorry guys, was able to come online today only. This is the dummy site www.asblab2012.mie.utoronto.ca , you can see the error messages. So this is what happened, I changed the theme to blue marine, and then I was unable to access the site as an admin again. This is a dummy site that has been rehosted again after I failed to access my original page.  The problem is I am not very familiar with log files, someone mentioned me to look in to /var/log/httpd/  error_log file.And I can't find it:/ .
Comment: I check my error_log file, this is one of the errors PHP Fatal error:  Call to undefined function json_decode() in /asblab/WWW/site2012/sites/all/themes/ninesixtyrobots/template.php on line 64 . If this error looks familiar let me know of any suggestions that you may all have :).
Comment: I just had to update the json_decode in server, which the server guy did. And also never change the .sql file manually because drupal has a weird way of reading sql file.

can't access www.livesite.com/admin


Find location where process started from on linux

Question: If I have output from ps like the following, is there any way to determine where 'blah' is on the file system? For my particular situation, the -p specifies which port the application should run on.
user 22913 22470  0 09:58 ?        00:00:06 ./blah -p 12345

My question is basically whether or not it is possible to find the location of an executable given the PID or port of the application. The distro being used is Redhat.
Answer: Do any of these give information?
ps -ef
ps -eLf
ps axms
Or maybe
ps -o cmd= -p $PID
This might be more useful:
readlink -f /proc/$PID/exe
?
Comment: readlink just echoes back what the input is on the system I'm using. The other commands give me back the ./blah instead of the /abc/def/blah I'm looking for.
Comment: What do you mean by the input the system is using?
bsilver@desktop:~$ ps
  PID TTY          TIME CMD
29626 pts/3    00:00:00 bash
29644 pts/3    00:00:00 ps
bsilver@desktop:~$ readlink -f /proc/29626/exe
/bin/bash
bsilver@desktop:~$
Comment: Whoops didn't format that right...but it did show that ps was saying "bash" but readlink for that PID said /bin/bash is the executable path.
Comment: The command I used was "readlink -f /proc/29626/exe" to get that pathname.
Comment: Sorry. It was because the user I was logged on as didn't have permissions. readlink is exactly what I was looking for.
Answer: Like Bart suggested,
readlink -f /proc/$PID/exe

shoud give you your answer.
Answer: To build on the readlink stuff, another way might be readlink -f /proc/$PID/cwd.  This will display the Current Working Directory of a process, which can be handy if you've executed a bash script, since the exe link is then /bin/bash, with an argument of ./blah.
And as a bit more random information, you can just cd to /proc/$PID.  There will be symlinks for cwd and exe, as mentioned, as well as where that processes root directory is (useful if chrooted)  ls -l will show where these are pointing, which is essentially what readlink is doing.
Answer: sudo /usr/sbin/lsof -p 22913


Solving a differential equation with given eigenvalues and eigenvectors

Question: I am currently working on a differential equation problem and could use some help in solving it. The problem is to find the general solution of the differential equation:
$$
\mathbf{x}^{\prime}=A \mathbf{x}
$$
where the matrix $A$ has eigenvalues 2 and 1 with the corresponding eigenvectors $[2,-3]^{T}$ and $[-3,5]^{T}$.
I have attempted to solve the problem by first finding the matrix $P$ that diagonalizes $A$, which can be found by stacking the eigenvectors into the columns of the matrix $P$ and calculating the inverse of $P$:
$$
P=\begin{bmatrix}
2 & -3 \\
-3 & 5
\end{bmatrix},\quad P^{-1}=\frac{1}{16}\begin{bmatrix}
5 & 3 \\
3 & 2
\end{bmatrix}
$$
Then, I can diagonalize $A$ as:
$$
A=PDP^{-1}=\begin{bmatrix}
2 & -3 \\
-3 & 5
\end{bmatrix}
\begin{bmatrix}
2 & 0 \\
0 & 1
\end{bmatrix}
\frac{1}{16}\begin{bmatrix}
5 & 3 \\
3 & 2
\end{bmatrix}
=\frac{1}{16}\begin{bmatrix}
1 & -3 \\
-3 & 5
\end{bmatrix}
\begin{bmatrix}
5 & 3 \\
3 & 2
\end{bmatrix}
=\begin{bmatrix}
1 & 0 \\
0 & 2
\end{bmatrix}
$$
Thus, the solution to the differential equation is given by:
$$
\mathbf{x}(t)=e^{At}\mathbf{c}=Pe^{Dt}P^{-1}\mathbf{c}
$$
where $\mathbf{c}$ is the constant vector determined by the initial conditions.
However, I am not entirely confident in my solution and would appreciate any feedback or guidance on whether my approach and solution are correct.
Thank you in advance for your help!
Comment: Can you verify your results of $\det P$ and hence $P^{-1}$?
Comment: Do you have the original matrix $A$? I did this multiplication in MATLAB and you may have done the multiplication wrong.
Answer: Assuming that the matrix $A$ is $2\times 2$ and you have found $2$ distinct eigenvalues $\lambda_1,\lambda_2$ corresponding to two $2$ linearly independent eigenvectors $v_1,v_2$, you have found a basis of eigenvectors.
This means that the matrix $A$ is diagonalisable. However there is no need to try and diagonalise the matrix yourself in order to find the solution to the system. In fact you've made several mistakes while doing so. It is best to avoid this since the solution the the equation is simply
$$  \alpha_1 x_1(t) + \alpha_2x_2(t)$$ where $$x_i(t) = e^{\lambda_i t}v_i$$
verifies $x_i'(t) = Ax_i$ and $\alpha_1,\alpha_2$ are constants defined by the initial conditions.


What is a latin rhythm and how do I play it on Double Bass?

Question: I have to practice this song:

Where the A part is supposed to be played Latin and B Swing. How do I play the Latin part on double bass?
Comment: If I remember correctly, this one of the many songs in the Real Books that appears in the 'wrong' key, as in not the key the original is in or not the standard key that players usually choose.  This is often the result of the transcription coming from someone that plays a transposing instrument and writing it in the key of their instrument.
Answer: Used like this "Latin" is a rather non-specific term. Markings denoting specific styles of Latin American Music, for instance Bossa-Nova, Samba, Mambo, Rumba, Salsa etc. would suggest particular associated rhythmic patterns, particularly for bass and drums. However, this generic use of the word "Latin" leaves a lot of room for interpretation by the performer; in fact, you could argue that it can lead to a generic, somewhat sanitised Latin feel (one band I used to work in called this "Gameshow-Latin"!). This post (and its answers) discuss the differences between specific and generic Latin rhythms. But, of course, experienced players will bring all of their knowledge "to-the-table" when seeing a simple "Latin" marking, drawing upon their vocabulary of Latin styles (and knowledge of a wide range of Jazz "standards") to use patterns and rhythms best suiting the chart on the stand.
You can easily replicate a generic Latin feel on bass by using techniques such as alternating root and fifth, on beats 1 and 3 respectively, and adding in some dotted and eighth notes for syncopation along the way.
However, I don't think that is what you want here. Looking at the part, you see that the first section just has a pedal C note in the bass part (all the chords are on C or over C). So, you could get away with just playing long Cs, or maybe octave Cs. After all, the bass line will "take-off" if you start walking in the Swing section - you want to create a bit of tension on the pedal note, before the swing, by not doing too much…
In fact, this is what the bass player does in this Miles Davis version, it's pretty effective:

(BTW, the version I link to starts in Eb - I've transposed to the same key as your chart… And, it's a rough transcription, giving you the main ideas, it's not "note-for-note"!)
Answer: As a percussionist having played folkloric Afro-Cuban music, popular "Latin" music, jazz, Brazilian batucada & bossa nova, etc. for over 20 years now, I can say that Bob Broadley's answer is is really pretty clear and accurate.
Calling something a "Latin" beat is really vague. Someone who actually performs any type of "Latin" music wouldn't even use the term very often except to describe it to someone who doesn't know the music that well.
My suggestion would be to start by listening to/ watching some heavy hitters play a standard like this, and you'll quickly see that there are countless ways to interpret the composition.
If you want to learn more, there are some good instructional books/DVDs that focus on Salsa or other genres. This one was very good: http://www.amazon.com/Salsa-Rhythm-Latin-Performance-Series/dp/0941677354  but there are others that are specific to bass. This book is also supposed to be incredible: http://www.amazon.com/Salsa-Guidebook-For-Piano-Ensemble/dp/0961470194
Here are a few videos of Green Dolphin, just as examples:
Legit (& fast) very "Latin" version - Paquito D'Rivera's group:

More laid back version- Paul Chambers on bass:

Nice recording/video - bass is very clear
Answer: Shift the accents from the strong beats to the weaker beats in the measures marked Latin, as per syncopation. A Brazilian percussionist reminds me that in Samba, the joke is, "Where's the one?"
Here's a youtube of Bill Evans...

Might help?
[Disclaimer: I am not a qualified Jazz bassist, nor Latin Bassist.]
Comment: In IT, we worry about missing ones and zeros, wonder if James has the zeros too?
Comment: Maybe James Brown stole all the "ones"...


Simple properties of a direct product

Question: I am working on some homework for modern algebra class. The problem I just finished seems relatively easy, but I have learned to be wary of that feeling when it comes to this material. Below are the problem statement and my solution. Please comment on my solution's validity, if you are so inclined.
This is problem 3, pg. 92 of Herstein's Abstract Algebra. Let $G$ be a group, and $A = G \times G = \{ (x,y) |\ \ x,y \in G \} $ the direct product of that group with itself. Let $T = \{(g,g) |\ \ g \in G\}$. What I need to do is to prove that

$T \cong G$  and
$T \triangleleft A \Leftrightarrow G\ $ is abelian.

My solutions for these are as follows:

Let $\varphi : T \rightarrow G |\ \ \varphi((g,g)) = g$. We can show that $\varphi$ is an isomporphism in the following way: first, we will prove that $\varphi$ is a homomorphism.
Let $t,s \in T |\ \ t = (g_{1},g_{1}), s = (g_{2},g_{2}), g_{1}, g_{2} \in G$.
Then $\varphi(st) = \varphi((g_{1}g_{2},g_{1}g_{2})) = g_{1}g_{2} = \varphi((g_{1},g_{1}))\varphi((g_{2},g_{2})) = \varphi(s)\varphi(t)$, indicating that $\varphi$ is a homomorphism.
Next we will show that $\varphi$ is a monomorphism. Let $\varphi(s) = \varphi(t)$. This implies that $\varphi((g_{1},g_{1}))=\varphi((g_{2},g_{2})) \Rightarrow g_{1} = g_{2}$, proving that $\varphi$ is a 1-1 mapping, and so is a monomorphism.
Finally, we must show that $\varphi$ is onto. We can show that this mapping covers all of $G$ like so: $\forall\ g \in G\ \exists\ x \in T |\ \ x = (g,g)\ \&\ \varphi(x) = g$. This proves that $\varphi$ is an isomorphism from $T$ to $G$. The existence of this isomorphism proves that $T \cong G$. $\blacksquare$
First, we will prove that $T \triangleleft A \Rightarrow G$ is abelian. $T \triangleleft A \Rightarrow \forall\ x \in A, x^{-1}Tx \subset T$. Let $x = (g_{1},g_{2}) \in A, g_{1},g_{2} \in G, t = (h,h) \in T, h \in G$. Then $x^{-1} = (g_{1}^{-1},g_{2}^{-1})$, with both inverses existing as a consequence of $A$ being a group. This is easy to see since $A$ is the direct product of the group $G$ with itself. Let us now form the product: $x^{-1}tx = (g_{1}^{-1}hg_{1}, g_{2}^{-1}hg_{2}) = u \in T$, since $T \triangleleft A$. This, in turn, tells us about the struture of the product; because of $T$'s definition, we can tell that $g_{1}^{-1}hg_{1} = g_{2}^{-1}hg_{2}$. Rearranging the terms, this gives us $h = g_{1}g_{2}^{-1}hg_{2}g_{1}^{-1}.$ We know that $(g_{1}g_{2}^{-1})^{-1} = g_{2}g_{1}^{-1}$, so we can multiply this through: $g_{2}g_{1}^{-1}h = hg_{2}g_{1}^{-1}$, which shows that $G$ must be abelian.
Next, we will show that the other implication is true and prove that $G$ being abelian implies that $T \triangleleft A$. Let $x=(g_{1},g_{2}) \in A, t = (h,h) \in T, g_{1},g_{2},h \in G$. This makes the product $x^{-1}hx = (g_{1}^{-1}hg_{1},g_{2}^{-1}hg_{2})$. We know that $G$ is abelian, so $(g_{1}^{-1}hg_{1},g_{2}^{-1}hg_{2}) = (g_{1}^{-1}g_{1}h,g_{2}^{-1}g_{2}h) = (h,h) \in T$, proving that $x^{-1}Tx \subset T\ \forall\ x \in A$, and, equivalently, that $T \triangleleft A$.
These two statements together prove that $T \triangleleft A \Leftrightarrow G\ $ is abelian. $\blacksquare$.

Thanks in advance for any help you may be able to provide.
Answer: This looks pretty good. I only have two comments:

Your $\varphi$ could also be introduced as the restriction of one of the projection maps that come with $G \times G$. Depending on what you have already proved about products of groups, this might save you some work. Also note that $\varphi$ has an inverse that is easy to write down: define $\Delta\colon G \to T$ by $\Delta(g) = (g, g)$.
When proving the "$\Rightarrow$" direction in the second part, you should conclude by saying something like, "set $g_1 = e$ to obtain $g_2h = hg_2$ for all $h, g_2 \in G$". Overall, it might be quicker to write, for each $g, h \in G$,
$$
(h, e)(g, g)(h, e)^{-1} = (h, e)(g, g)(h^{-1}, e) = (hgh^{-1}, g) \in T.
$$
Then manipulate $hgh^{-1} = g$ to finish the proof.

But in a technical sense I think you've improved a great deal.
Comment: Thanks to both you and @AMPerrine for your helpful replies. I'll clean it up a bit soon with the feedback you've provided.
Answer: First off, I believe your proofs to be correct.  However, I suggest making the first part of the second proof a bit cleaner.  Try this:
Let $x,y$ be elements of $G$, and $e$ the identity.  Then $(e,x)\in A$ and $(y,y)\in T$.
Proceed with your proof as above and you should get your result with much less fuss.

Simple properties of a direct product


How to add a checkbox to form builder component settings form?

Question: I have webform and formbuilder modules installed.
In the file field settings form I want to add an extra checkbox field just like the required field but I am unable to do that.
I can add it to the webform_component_edit_form like the following
$form['validation']['check'] = array(
      '#type' => 'checkbox',
      '#title' => t('Check'),
      '#default_value' => ($component['check'] == '1' ? TRUE : FALSE),
      '#description' => t('Check this option if the user should be able to upload files.'),
      '#weight' => -1,
      '#parents' => array('check'),
    );

But it is not displaying in the formbuilder file settings edit form form_builder_field_configure.
Is there any way to add a field to form_builder_field_configure form and save with the node just like other fields?
Comment: Install File Entity module then create a field checkbox type like alt text.
Answer: you have to do it inside the form_id 'form_builder_field_configure'.
Example :
hook_form_alter($form,$form_state,$form_id){
`switch($form_id){
     case 'form_builder_field_configure':
     // You put your code here
     $form['check'] = array(
       '#form_builder' => array(
         'property_group' => 'validation'
       ),
       '#type' => 'checkbox',
       '#title' => t('Check'),
       '#default_value' => '',
       '#description' => t('Check this option if the user should be able
    to upload
     files.'),
      '#weight' => -1,
);
  break;
 }

}
     `
I hope it'll help you.


Subset in a regular expression

Question: Is this true for every two regular expressions $G$ and $K$?

$(GG + K)^*$ is a subset of $(KGG)^*$ and
$(KGG)^*$ is also a subset of $(GG + K)^*$
Answer: Take $G = a$ and $K = b$. Then $aa$ matches $(GG + K)^*$ but not $(KGG)^*$. Thus (1) is not true.
However (2) is true, since $(KGG)^*$ is the infinite union of the sets $(KGG)^n$ (where $n \geqslant 0$) and $\underbrace{(KGGKGG \cdots KGG)}_{n \text{ times}}\ $ can be written as a product of $GG$ and $K$.

Subset in a regular expression


Using php creating file and adding text to it

Question: I am trying to create a text file using php and the value is coming through a db call
<code>$result = mysql_query("SELECT code FROM topic_master");
while ($row = mysql_fetch_array($result)) {
$x1=$row{'code'};
exec("printf $x1 >> code.txt");
}
</code>
But the value is not inserted in the code.txt. Only array(code) is inserted in the code.txt.
Actually the $row{'code'} has "#xy { } () %". How can i write the values to txt file.
Answer: This will solve your problem:
<code>$result = mysql_query("SELECT code FROM topic_master");
while ($row = mysql_fetch_array($result)) {
file_put_contents('code.txt',$row['code'],FILE_APPEND);//FILE_APPEND is necessary
}
</code>
Comment: Same data will append in every refresh.
Comment: @Salim no , data change in each iteration,and File_APPEND put cursor in the end of file so data are not erased
Comment: $x1="abc "; file_put_contents('code.txt',$x1, FILE_APPEND); If you refresh page 3 times output will be 'abc abc abc'
Comment: @Salim OP have not said anything about this.He should specify what he wants,don't forget that database is not a variable and values change
Comment: no needs for `$x1=$row['code'];` every cycle. Just `file_put_contents('code.txt', $row['code'], FILE_APPEND);`. Mysql deprecated. Cyclic file access instead one save...
Answer: Use file_put_contents instead of that exec and do
<code>$s = "";
while ($row = mysql_fetch_array($result)) {
    $x1=$row['code'];
    $s .= $x1 . "\n";
}
file_put_contents("code.txt", $s, FILE_APPEND);
</code>
Comment: WIth the `FILE_APPEND` flag to not erase the previous data
Comment: i think \r\n is better
Comment: @FaceOfJock Using `\r\n ` in Linux will produce undesirable results. This works fine for Windows, but not Linux.
Comment: @Fred-ii- but in notepad++ for example , \n will not pass to next line
Comment: @FaceOfJock What do you by *"will not pass to next line"*?
Comment: @Fred-ii- sorry for my english , i mean if you open file using notepad for example , you will see that all lines are in one line ,but if you use \r\n this is overpassed
Comment: @FaceOfJock Not a problem and thanks for the clarification and I now understand what you mean.
Answer: First of all, you shouldn't use $row{'code'} the correct usage is $row['code']
Also, I would suggest using file_put_contents() instead of exec so you could do
<code>$result = mysql_query("SELECT code FROM topic_master");
while ($row = mysql_fetch_array($result)) {
$x1=$row['code'];
file_put_contents('code.txt',$x1, FILE_APPEND);
}
</code>
Comment: FILE_APPEND should be in file_input or content will be errased and only last line will be in the file
Comment: I think it will append data for every refresh of this page. same data will store every time
Comment: $x1="abc ";
 file_put_contents('code.txt',$x1, FILE_APPEND);
If you refresh page 3 time output will be 'abc abc abc' I think he did not want this
Comment: See the answer code.txt will contain amount of data which is in database in every refresh http://stackoverflow.com/a/18642996/2459296
Answer:
<code>$result = mysql_query("SELECT code FROM topic_master");

// if you want to APPEND the data in code.txt, use this
// however, using that particular SQL query the same data will be written over and over because there's nothing specifying a parameter change
while ($row = mysql_fetch_array($result)) {
    $x1 = $row['code'];
    write_file('code.txt',$x1,'a');
}

// if you want to OVERWRITE the data in code.txt use this
while ($row = mysql_fetch_array($result)) {
    $x1 .= $row['code'];
}
write_file('code.txt',$x1,'w');

// function to write content to a file (with error checking)
function write_file($filename,$content,$flag) {
    if(is_writable($filename)) {
        if(!$handle = fopen($filename, $flag)) {
            // die, or (preferably) write to error handler function
            die('error');
        }
        if(fwrite($handle, $content) === FALSE) {
            // die, or (preferably) write to error handler function
            die('error');
        }
        fclose($handle);
    }
}
</code>
Edit: changed flag from w to a.
Another edit: if you want to APPEND to the file, leave the fopen() flag set to 'a'. If you want to overwrite the existing contents, change the flag to 'w'.
Final edit: added two versions with explanation
Comment: `w` will overwrite content. OP needs to append, therefore `a` or `a+`
Comment: Thanks, didn't see that. Where does he state he needs to append?
Comment: You're welcome Tim. In the title *"Using php creating file and adding text to it"*
Comment: Yeah, it's not always clear when the important stuff is in the title and not the question body itself; an honest mistake ;-)
Comment: Totally confusing regardless, because "adding" can mean both. :)
Comment: Ahh... you have a point there! However, the OP did accept the one with `FILE_APPEND`, so I take it that's what the goal was, but again, you do have a point there. *"Touché"* ;-)
Answer: Actually, you are not creating a text file using PHP, you are creating a text file using shell execution. Why don't you just try file functions?
<code>$result = mysql_query("SELECT code FROM topic_master");
$file = fopen("code.txt", "ab");
while ($row = mysql_fetch_array($result)) {
    fwrite($file, $row["code"]);
}
fclose($file);
</code>
Comment: `"ab"`? `b` is for binary. Either `a` or `a+` if it's text, not the `b` switch.
Comment: [PHP manual](http://php.net/fopen) says, among other things: "For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen()."
Answer: Get all data in a variable and write it in file
<code><?php

$result = mysql_query("SELECT code FROM topic_master");

$data = "";
while ($row = mysql_fetch_array($result)) {

    $x1=$row['code'];

    $data .= $x1;

}

$fp = fopen("code.txt","w");

fwrite($fp,$data);

fclose($fp);

?>
</code>
Comment: fwrite($fp,$data) instead of fwrite($fp,$x1) and also **$fp = fopen("code.txt","a");** to place pointer in end of file not in the beginning
Comment: @Salim `w` will overwrite content. OP needs to append, therefore `a` or `a+`
Comment: It is out of loop and all value stored in variable $data it is writing to file only once
Comment: @Salim As per OP's title *"Using php creating file and adding text to it"* See accepted answer, where it uses `FILE_APPEND`
Comment: Read comments in excepted answer


Solving differential equations "$c$" value

Question: I have two questions regarding solving differential equations given initial conditions:
1) When do you substitute the initial conditions into the equation to calculate the value of the constant "$c$". Do you substitute it once you integrate both sides of the differential equations and you get a constant "$c$"? Or do you substitute the initial conditions after integrating both sides AS WELL AS rearranging the equations to get $y$ in terms of $x$ and $c$. Using the second method, sometimes you get two values for "$c$" with only one value being correct.
2) When you solve certain differential equations, you get one side written with "$\pm$" in the front. However, only one equation fits the initial conditions even after you solve for the constant "$c$". The one that fits is either the one with the "$+$" or the one with the "$-$" in the front. How do you justify which one is correct without giving geometric representations of both and then saying "according to graph, this one insert equation is correct". Can you somehow solve without getting the "$\pm$" in the front?
Thanks.
Comment: The *insert equation* is just there as a place holder for an example. Not a particular equation
Comment: Have you forgotten to insert an equation?
Comment: Ah brill, that makes sense!
Answer: For your first question. Wait until you have got a solution that is dependent on this constant $c$, then plug in your initial conditions to find out it's value. Sometimes you won't have initial conditions so you can just leave $c$ in there.
With regards to the second part, often your answer won't make sense if you pick the $+$ or the $-$. For example if you have $y$ defined as being positive, but taking the $-$ makes it negative. It is often left to you to justify your choice, and if you can't, it can be possible that both hold.
Comment: If i solve (dy/dx)=y+y(x^2), the solution is y=+-e^(x+(x^3)/3). The correct solution occurs when y has a positive in the front. However, there are no conditions given for y or x. So how do you justify the positive choice?
Comment: Do you have any physical interpretation that could limit it? Or some condition on the range/domain of $x/y$ that could influence it?
Comment: I am given the initial conditions (a point that the solution curve cuts). But even after I substitute the initial conditions, i get the solution I stated above. However, only one equation fulfils the initial conditions (cuts the given point) even though i got both versions of the solution ("+" and "-") using the initial condition. So, my question is, is there a way to determine which solution is the correct one without saying  "according to graph, this one *insert equation* is correct"?
Comment: If only one solution fulfills the initial conditions then this is the correct one
Comment: thats the only explanation i can give isn't it
Comment: I think so, sorry
Answer: $$dy/dx)=y+y(x^2),$$
$$\implies y'-y(1+x^2)=0$$
With integrating factor
$$(ye^{-x-x^3/3})'=0$$
Integrate
$$y(x)=Ke^{x+x^3/3}$$
You just have a constant K ...and that depends upon initial conditions.
Answer: Substituting Initial Conditions:
Typically, you substitute the initial conditions after integrating both sides of the differential equation and obtaining the general solution with an arbitrary constant "C". This general solution will have the form of an equation relating y and x. Then, you apply the initial conditions to determine the specific value of "C" that satisfies the given conditions. This allows you to find the particular solution that fits the initial conditions.
Sometimes, rearranging the equation to solve for "y" explicitly in terms of "x" and "C" can yield multiple possible values for "C". In such cases, you must evaluate which value(s) of "C" satisfy the given initial conditions. It's crucial to ensure consistency with the initial conditions when determining the appropriate value(s) for "C".
Dealing with "±" in the Solution:
In some cases, after integrating and simplifying the differential equation, you might end up with an equation that contains "±" in the solution. This "±" indicates that there are two possible solutions, one with the positive sign and another with the negative sign. However, only one of these solutions will satisfy the given initial conditions.
To determine the correct solution, substitute the initial conditions into both possible solutions separately. Evaluate which one satisfies the initial conditions and matches the given values. This will allow you to select the appropriate solution that fits the initial conditions.
It's important to note that for some differential equations, the "±" arises due to the nature of the equation itself, and it may not be possible to avoid it. In such cases, evaluating the solutions using the initial conditions becomes necessary to determine the correct one.
By applying these methods, you can ensure that you find the particular solution that satisfies the given initial conditions and accurately represents the behavior of the system described by the differential equation.
I hope this clarifies the process for you! Feel free to ask any additional questions.


How do I tell gcc that my inline assembly clobbers part of the stack?

Question: Consider inline assembly like this:
uint64_t flags;
asm ("pushf\n\tpop %0" : "=rm"(flags) : : /* ??? */);

Nonwithstanding the fact that there is probably some kind of intrinsic to get the contents of RFLAGS, how do I indicate to the compiler that my inline assembly clobbers one quadword of memory at the top of stack?
Comment: AFAIK, you can't.  I *think* the only safe way to write this is by modifying rsp around the pushf/pop so you don't step on the red zone.  (Use `add -128` / `sub -128` so they can use an imm8 encoding).  And then of course the output constraint has to be `"=r"`, because a memory operand could use an rsp-relative addressing mode.  Avoiding the red-zone is the best anyone's been able to come up with in discussions of the same issue on previous SO questions.
Comment: There is no way to tell extended asm that you are clobbering the stack.  That said, what exactly are you trying to accomplish?  There might be some other tricks that do what you need (maybe lahf?).
Comment: @DavidWohlferd I was thinking about how inline assembly that clobbers part of the stack would work and this is a good example for motivation as `pushf` is the only way to get the entire RFLAGS register.
Comment: related: you can't tell gcc that you want to clobber the *whole* red zone either (except by compiling the whole file or function with `-mno-red-zone`).  So to make a function call in inline-asm, you have to jump through hoops:  See http://stackoverflow.com/questions/37502841/calling-printf-in-extended-inline-asm and http://stackoverflow.com/questions/37639993/is-this-assembly-function-call-safe-complete.  (Calling functions from inline asm is just a bad idea, but people trying to learn asm using inline-asm keep wanting to do it.)
Comment: @PetrSkocik I didn't know this is possible!  Please post this approach as an answer so I can accept it.
Comment: You could also save/restore `[rsp-8]` into a register, but that seems worse than modifying rsp, even if it makes the stack engine insert an extra uop.
Comment: Oh and yeah, there is an intrinsic: `__readeflags()` (and yes, it works on x64).
Comment: @DavidWohlferd Interestingly, the [intrinsics](https://gcc.gnu.org/ml/gcc-patches/2013-12/msg00386.html) don't seem to address this issue either.
Comment: Ah, I see, that was the first stab, it seems like they reimplemented that as a builtin afterwards.
Comment: Or just list "rsp" as a clobber and suppress the warnings. It seems gcc handles it just fine (by avoiding the redzone and addressing local spills relative to `%rbp` rather than `%rsp`) with only a small amount of perhaps unavoidable waste (`leave` or similar (`lea someConst(%rbp), %rsp; ...popsToRestoreNonVolatiles...; ret;`) as there seems to be no way to tell the compiler that the modified `rsp` was restored). The mechanism is needed for VLAs/allocas anyway. I only ran into some issues w/ rsp clobb. on clang but the fix seems simple (https://github.com/llvm/llvm-project/issues/61898).
Answer: As far as I am concerned, this is currently not possible.
Comment: One workaround is to do something like `add $-128, %rsp` before using the stack, to skip past the red-zone, and `sub $-128, %rsp` after.  (`-128` fits in an imm8 so it's smaller than sub $128).  TODO: link an existing Q&A.
Comment: [Calling printf in extended inline ASM](https://stackoverflow.com/a/37503773) shows an example of skipping the red-zone before using the stack in inline asm.  (And the inconvenience of declaring clobbers on all the call-clobbered registers, if you're going to call an arbitrary function!)
Answer: Apart from Peter Cordes's approach of skipping the redzone:
long getflags0(void){
    long f; __asm(
        "add $-128, %%rsp;\n"
        "pushf; pop %0;\n"
        "sub $-128, %%rsp\n" : "=r"(f) :: );
    return f;
}

which renders:
0000000000000000 <getflags0>:
   0:   48 83 c4 80             add    $0xffffffffffffff80,%rsp
   4:   9c                      pushfq
   5:   58                      pop    %rax
   6:   48 83 ec 80             sub    $0xffffffffffffff80,%rsp
   a:   c3                      retq
$sz(getflags0)=11

you can also just list rsp as a clobber and silence the deprecation warning:
long getflags(void){
    long f;
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wdeprecated"
    __asm("pushf; pop %0" : "=r"(f) :: "rsp");
    #pragma GCC diagnostic pop
    return f;
}

which renders:
000000000000000b <getflags>:
   b:   55                      push   %rbp
   c:   48 89 e5                mov    %rsp,%rbp
   f:   9c                      pushfq
  10:   58                      pop    %rax
  11:   c9                      leaveq
  12:   c3                      retq
$sz(getflags)=8

From experience (played with this quite a bit), gcc actually handles rsp clobbers quite well -- by forcing a frame pointer (which it won't let you clobber alongside rsp -- that's a hard assembler error), avoiding the redzone, addressing locals relatively to the frame pointer, and by forcing an %rsp restoring code at the end of the function.
The mechanism of making the compiler let go of the end of the stack is needed for VLAs and allocas anyway, so I don't think it's going anywhere.
I think such rsp clobbers are quite usable for custom stack allocations, frees, and stack switches, as long as you don't mess with what the compiler spilled below the stack pointer it gave you (or open it up to being messed with).
I only had some issues with this approach on clang, but the fix to the compiler seems trivial: https://github.com/llvm/llvm-project/issues/61898.
As for suppressing the warnings without affecting the whole compilation unit,
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
//...
#pragma GCC diagnostic pop

can work well inside a (possibly inline -- had no issues with rsp clobbers inside inline functions either) function, or you can generate the pragma with _Pragma to make it usable inside of macros.
Clang doesn't complain about rsp clobbers (though you will run into issues on it if you use rsp clobbers on it for memory allocation unless you apply my fix to a custom build) unless you compile with -fstack-clash-protection. Then the warning is -Wstack-protector, and it's silenceable equivalently.
Please keep in mind that while this happens to work, it is not officially supported. From https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#Clobbers-and-Scratch-Registers-1:

The compiler requires the value of the stack pointer to be the same after an asm statement as it was on entry to the statement. However, previous versions of GCC did not enforce this rule and allowed the stack pointer to appear in the list, with unclear semantics. This behavior is deprecated and listing the stack pointer may become an error in future versions of GCC.
Comment: RSP clobber sounds like a "happens-to-work" behaviour. GCC's manual (https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#Clobbers-and-Scratch-Registers-1) says: *the clobber list should not contain the stack pointer ... The compiler requires the value of the stack pointer to be the same after an asm statement as it was on entry to the statement. However, **previous versions of GCC did not enforce this rule and allowed the stack pointer to appear in the list, with unclear semantics**. This behavior is deprecated and listing the stack pointer **may become an error in future versions of GCC**.*
Comment: I added a `volatile int foo = 0;` to your example to verify that it didn't put it in the red-zone.  It allocates stack space for it so it's above RSP even in a leaf function.  I guess an `"rsp"` clobber is treated similarly to `alloca` with a runtime-variable size.  Function calls after that do assume RSP is still aligned, so it doesn't cost extra instructions re-aligning RSP after you tell GCC it was clobbered.  https://godbolt.org/z/6fzsE59ee
Comment: @PeterCordes Yes, exactly. That's why the answer also mentions VLAs and allocas. In my experience (gcc and my very slightly modified clang) it works quite well and opens up new interesting applications (easy custom allocas+freeas, access to raw pushes/pops from C, etc.). I had originally only made a daredevil comment and, in light of the official deprecation, didn't intend to answer, but I took fuz's bait. Maybe they'll un-deprecate it if people develop enough interesting applications for it :D.
Comment: @PeterCordes Yeah, that's a very good note that I should've probably somehow included in the answer.
Comment: @PeterCordes If not for all the useful applications, they should definitely undeprecate it to make the notorious aligned call from inline assembly simpler https://godbolt.org/z/KTGvMoT6d. :D
Comment: They'd need to be careful about defining the semantics re; alignment, but yeah it's a gap in current GCC's features.  i.e. they'd have to carefully document either per-target or generally that `asm` with a stack-pointer clobber means the stack will be aligned appropriately for a function call on entry, and that it should still be aligned on exit even if it's grown.  Otherwise an RSP clobber means the compiler needs to `and rsp, -16` after each such asm statement, if it allowed RSP modification to any arbitrary value.


Trim FASTA sequences in R, before and after a certain pattern

Question: I have a fasta file, that consist of 4 fasta sequences. They all consist of similar protein sequences with few mutations in it. The file is attached here: https://drive.google.com/file/d/11OKZs47wOqYRw11Akwb4zj2RRzdqSQsC/view?usp=sharing
I want to trim all of the fasta sequences with a specific pattern. I want to only select the sequences which start by "QCVN...RAAR". However, I cannot directly use the filter function because there might be mutations s in between the "QCVN...RAAR", which might not give the exact sequences. The part that is not mutated is the start "QCVN" and the end "RRAR" that stays the same across the 4 fasta sequences gathered. Thus, is it possible for to trim the sequences before the "QCVN"and after the "RAAR"?
>UPH85748.1 |surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]
MFVFLVLLPLVSS"**QCVNLXTRTQSYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFSNVT
WFHAIHVSGTNGTKRFDNPVLPFNDGVYFASTEKSNIIRGWIFGTTLDSKTQSLLIVNNA
TNVVIKVCEFQFCNDPFLDVYYHKNNKSWMESEFRVYSSANNCTFEYVSQPFLMDLEGKQ
GNFKNLREFVFKNIDGYFKIYSKHTPINLGRDLPQGFSALEPLVDLPIGINITRFQTLLA
LHRSYLTPGDSSSGWTAGAAAYYVGYLQPRTFLLKYNENGTITDAVDCALDPLSETKCTL
KSFTVEKGIYQTSNFRVQPTESIVRFPNITNLCPFDEVFNATRFASVYAWNRKRISNCVA
DYSVLYNLAPFFTFKCYGVSPTKLNDLCFTNVYADSFVIRGDEVXQXAPGQTGNIADYNY
KLPDDFTGCVIAWNSNKLDSKVGGNYNYLYRLFRKSNLKPFERDISTEIYQAGNKPCNGV
AGFNCYFPLRSYGFRPTYGVGHQPYRVVVLSFELLHAPATVCGPKKSTNLVKNKCVNFNF
NGLTGTGVLTESNKKFLPFQQFGRDIADTTDAVRDPQTLEILDITPCSFGGVSVITPGTN
TSNQVAVLYQGVNCTEVPVAIHADQLTPTWRVYSTGSNVFQTRAGCLIGAEYVNNSYECD
IPIGAGICASYQTQTKSHRRAR**"SVASQSIIAYTMSLGAENSVAYSNNSIAIPTNFTISVT
TEILPVSMTKTSVDCTMYICGDSTECSNLLLQYGSFCTQLKRALTGIAVEQDKNTQEVFA
QVKQIYKTPPIKYFGGFNFSQILPDPSKPSKRSFIEDLLFNKVTLADAGFIKQYGDCLGD
IAARDLICAQKFNGLTVLPPLLTDEMIAQYTSALLAGTITSGWTFGAGAALQIPFAMQMA
YRFNGIGVTQNVLYENQKLIANQFNSAIGKIQDSLSSTASALGKLQDVVNHNAQALNTLV
KQLSSKFGAISSVLNDILSRLDKVEAEVQIDRLITGRLQSLQTYVTQQLIRAAEIRASAN
LAATKMSECVLGQSKRVDFCGKGYHLMSFPQSAPHGVVFLHVTYVPAQEKNFTTAPAICH
DGKAHFPREGVFVSNGTHWFVTQRNFYEPQIITTDNTFVSGNCDVVIGIVNNTVYDPLQP
ELDSFKEELDKYFKNHTSPDVDLGDISGINASVVNIQKEIDRLNEVAKNLNESLIDLQEL
GKYEQYIKWPWYIWLGFIAGLIAIVMVTIMLCCMTSCCSCLKGCCSCGSCCKFDEDDSEP
VLKGVKLHYT

Here are the codes that I tried to use to read the FASTA file
# Load the Biostrings package
library(Biostrings)

# Read the FASTA file
fasta <-readAAStringSet("sequences-2.fasta")
print(fasta)

It gives out this result
AAStringSet object of length 4:
    width seq                                                                                names
[1]  1270 MFVFLVLLPLVSSQCVNLXTRTQSYTNSFTRGVYYPDKVFRSSVLHS...VMVTIMLCCMTSCCSCLKGCCSCGSCCKFDEDDSEPVLKGVKLHYT UPH85748.1 |surfa...
[2]  1270 MFVFLVLLPLVSSQCVNLITRTQSYTNSFTRGVYYPDKVFRSSVLHS...VMVTIMLCCMTSCCSCLKGCCSCGSCCKFDEDDSEPVLKGVKLHYT UUT03046.1 |surfa...
[3]  1270 MFVFLVLLPLVSSQCVNLRTRTQSYTNSFTRGVYYPDKVFRSSVLHS...VMVTIMLCCMTSCCSCLKGCCSCGSCCKFDEDDSEPVLKGVKLHYT UYE44393.1 |surfa...
[4]  1271 MFVFLVLLPLVSSQCVNFRTRTQLPPAYTNSFTRGVYYPDKVFRSSV...VMVTIMLCCMTSCCSCLKGCCSCGSCCKFDEDDSEPVLKGVKLHYT UYW62681.1 |surfa...

Then I tried to use this code to trim the sequences before "QCVN"
# Loop through the sequences and trim the pattern
for (i in 1:length(fasta)) {
  sequence <- as.character(fasta[[i]]) # convert the sequence to a character string
  sequence <- gsub(paste("^.*", stop_pattern), stop_pattern, sequence) # remove everything that comes before the pattern
  fasta[[i]] <- AAString(sequence) # convert the trimmed sequence back to a AAString object
}

# Write the trimmed sequences to a new FASTA file
writeXStringSet(fasta, "file.fasta")

But it didnt work, as it didn't trim anything from the sequences.
Is there any possible way to trim the sequences before the "QCVN"and after the "RAAR"?
Comment: Since you're using Biostrings, look at the documentation for `trimLRPatterns()` and `matchLRPatterns()`
Answer: You can use just one gsub for both. You can keep the middle part if it matches the group .*(pattern).* as it is saved to \\1
example <- "somethingbadQCVNsomethingelsebutgoodRAARsomethingbad"

gsub(".*(QCVN.*RAAR).*", "\\1", example)

Result
[1] "QCVNsomethingelsebutgoodRAAR"

see this question for more details


Parallel programming using pthread

Question: I have just started learning parallel programming using pthreads. So, for the learning purpose I tried sum of two integer arrays parallely. I have declared struct construct with three array variables a, b and c. I want to do addition of a, b and store the result in c.
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

#define MAX 6

struct data {
  int a[MAX];
  int b[MAX];
  int c[MAX];
};

void *addition(void *index) {
  struct data *d1 = (struct data *)index;
  printf("value of d1 structure=%d\n", d1->a[0]);
}

int main() {
  int i, j, t;
  struct data *item = NULL;
  pthread_t threads[MAX];

  item = (struct data *)malloc(sizeof *item);

  printf("enter the value for arrray a\n");
  for (i = 0; i < MAX; i++) {
    scanf("%d", &item->a[i]);
  }

  printf("enter the value of array b\n");
  for (j = 0; j < MAX; j++) {
    scanf("%d", &item->b[j]);
  }

  for (t = 0; t < MAX; t++) {
    pthread_create(&threads[t], NULL, addition, (void *)&item);
  }
}

Here, as of now I have not added the addition of arrays in the function addition(), because in pthread_create() when I am passing the three arguments with the help of structure, in function addition the variables a and b are not getting copied. Printing a is giving me garbage value. Can anybody help me how to copy the structure variable to the function argument called by pthread_create().
Comment: What is the type of `item`? What is the type of `&item`? When you know that then the problem should be obvious.
Comment: You need some `pthread_join()` calls to synchronize the processing as the threads finish. You'll also need to demonstrate that the threads worked. You have not shown how your 6 different threads are doing 6 different computations. They're all doing the same computation (6 additions and assignments) without any control over access to the data. This is a major cause of (potential) trouble. You may not notice because the workload is so small that the threads never get a chance to interfere with each other. The thread function should return a value — a null pointer. Your compiler should complain!
Answer: pthread_create Function  :
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

Kindly note (*arg) is pointer to the arg.
You have created struct data *item as a pointer then you are passing its address i.e. pointer to pointer.
pthread_create(&threads[t], NULL, addition, (void *)&item);

Change the call to
pthread_create(&threads[t], NULL, addition, (void *)item).

Comment: changing the call to : pthread_create(&threads[t] , NULL, addition, (void *)item. worked. Problem solved. Thanks
Comment: Thank You so much

Parallel programming using pthread


My Value won't text align center

Question: Can anyone please help me understand why this text value of "7" is not centering?
<input id="button7" value="7" onclick='Calc.Input.value += "7"' type="button" class="button"/>

For the web version the 7 is centering, but not the mobile version through media querying.
My Media Query CSS only is;
@media only screen and (min-device-width : 320px) and (max-device-width : 568px) {

.set_1 {
  height: 270px;
  width: auto;
}

.set_2 {
  height: 266px;
  width: auto;
}

.set_3 {
  height: 266px;
  width: auto;
}

.set_4 {
  height: 266px;
  width: auto;
}

.set_5 {
  height: 266px;
  width: auto;
}

.text_box{
  height: 180px;
  width: 730px;
  font-size: 100px;
}

.button {
  height:200px;
  width:200px;
  font-size: 100px;
  text-align: center;
}

}

Comment: So can you post the media query?
Comment: Can you show us the media query?
Comment: Maybe a CSS definition is overriding your `text-align:center` in the mobile version. Are any additional style sheets loaded for the mobile version?
Comment: only the regular css and media query stylesheet (in one file), which I posted as requested.
Comment: I can't reproduce the issue. Any chance you can create a [jsfiddle](http://jsfiddle.net/) to illustrate the problem (or share a link to your working page)?
Comment: I did it in a jsfiddle; http://jsfiddle.net/PUDq8/.  the text looks centered here; however, on my iphone 5 mobile device, the text is not align center.
Answer: add:
display: block;

I believe....

My Value won't text align center


Adding error class to Webform fields

Question: I have a Webform which I'm validating implementing the _validate event (i.e. altering $form["#validate"] by adding a custom validator which accepts &$form and &$form_state).
In my code I have something like this:
if ($nombre && !CasabacaS3SValidaciones::validarLongitud($nombre, 30))
{
    form_set_error('columnas][datos_personales][nombre', t('El nombre no debe superar 30 carácteres'));
    //what should I put in THIS LINE, replacing this comment, to add the error class?
}

I have no clue about adding the "error" class (e.g. fields marked as required have class "required", and also class "error" when the field is not set). How can I alter the field (take this example field in the form_set_error and assume input variables are &$form and &$form_state) so I can add the error for display?
NOTE: I'm seeking to add the "error" class to the fields, and NOT to the wrapping divs (i.e. those divs having form-item class).
(If a quick solution involves themes, please attach a link so I can read about because i'm banging my head about drupal yet, i'm a total n00b :s).
Answer: You could use a preprocess functions in your theme for this. You can add preprocess in your template.php.
function mytheme_preprocess_textfield(&$vars) { // OR preprocess_field.

  $vars['#attributes']['class'][] = 'test' ;
}

Check the $vars parameter for values that may help you determine the logic. For examples, just search your code base for preprocess_textfield or preprocess_field. For more inf
Comment: How do I install those theme handlers? Can you point me a link? (i.e. how to actually make "mytheme" to available to my forms).
Comment: I edited my answer. If you have not idea what a preprocess function is then I suggest you read some tutorials about the thmeing system in drupal. For preprocesses functions you can take a look here https://drupal.org/node/11811 And here https://drupal.org/node/223430
Comment: Still not getting a clear idea. Documentation did not help me.
Comment: found the current theme! but when i edit the template.php adding casabaca_preprocess_field(&$vars) { dpm($vars); }, and refreshing the cache, it does nothing (yes, casabaca.info is the theme name).

Adding error class to Webform fields


Can Android apps communicate with WP7 ones?

Question: I was wondering if it's possible to make an app on android communicate with one on Windows Phone 7, or if there's even a way to develop apps for both platforms in the same language.
Comment: Your question is overly broad. What kind of communication are you interested in?
Comment: No we can develop an app using same language. but app same for each platform in their language that communicate through bluetooth or wifi is possible.but very complicated.. i dont if its really possible or not.
Comment: Mostly game related data communication. Imagine pong as a simple example, when the ball goes off the top of one player's screen, data containing the position, speed and direction will be sent to the other device.
Answer: The best way would likely be communicating via a web server to pass the data too and from each device. It depends on what you intend to pass between them though.
Answer: Network sockets will allow communication between ANY devices.
Comment: Except you can't create a socket in the current version of WP7.
Answer: It is possible to share some(!) code of the business layer logic.
There is a mono framework for android and iphone. You can use it to write code in C# for both devices.
However, the UI is device-dependent, so that cannot be shared.
Answer: A lot of quick and dirty ways now to develop apps for cross-platform is to use a mini-browser windows that simply points to a URL with no toolbars such as m.example.com.
Developing your "app" site in HTML5 allows a lot of possibilities to open up as far as what you can do from there. This gives you the opportunity to work a lot with cross-platform databases and dynamic data as well.


Test for paired samples with normal distribution

Question: When using R to test the mean difference of paired samples with normal distribution, which method is more effective among "t.test" "z.test" and "wilcox.test"?
As an example, for the two paired samples below(new and ori), they have been verfied to accord with the normal distribution by using shapiro.test. When using the t.test and wilcox.test, the mean value of the "new" data is shown to be greater than the "ori" data. However, when using left tailed and right tailed z.test, both of the p-value are larger than 0.05. Does it mean that the z.test is ineffective under this situation?
Attached below are the code. Thanks very much for the kind help!
library(BSDA)

new=c(459,367,303,392,310,342,421,446,430,412)
ori=c(414,306,321,443,281,301,353,391,405,390)

z.test(new,ori,alternative="less",sigma.x=sd(new),sigma.y=sd(ori))#p-value = 0.8674
z.test(new,ori,alternative="greater",sigma.x=sd(new),sigma.y=sd(ori))#p-value = 0.1326

Answer:
When using R to test the mean difference of paired samples with normal distribution, which method is more effective among "t.test" "z.test" and "wilcox.test"?

When the population is actually normal the t-test has (slightly) more power than the Wilcoxon signed rank test. In large samples it's like you have about an extra observation for every 20 in the sample.
The z-test has the wrong significance level (since the population sd of the differences is not known), so it's not actually comparable unless you know the population standard deviation; use the t-test for preference.

As an example, for the two paired samples below(new and ori), they have been verfied to accord with the normal distribution by using shapiro.test.

No; failure to reject does not mean that you have normality. Indeed it would be easy to be in a situation where the Wilcoxon signed rank test outperforms the t-test (because the tails were slightly heavier than the normal) but the Shapiro-Wilk test would not be all that likely to reject.
As an example, consider the case where both new and ori had the logistic distribution. With a sample size of 10, the Shapiro-Wilk test on the differences has about a 6.5% chance of rejecting normality at the 5% level (that is, with 16 such tests, on average for 15 of them you would have apparently mistakenly concluded that the distribution was normal -- but as I said that's not the correct conclusion, because failure to reject doesn't mean it is normal). This is what that density of differences looks like:
 $\hspace{2cm}$
It looks pretty normalish right?
Nevertheless, the Wilcoxon test actually has slightly better power to pick up small differences in this situation (when the two tests are carried out at the same significance level).
If you let the differences be logistic instead (which implies heavier tails on the original pairs than logistic), the Shapiro-Wilk test gets slightly better (about 8% chance of rejecting normality) but the Wilcoxon signed rank test is also more clearly showing greater power against small differences, getting about twice the relative power advantage over the previous case.
A suitable conclusion from those examples is that if you expect the population distribution to be roughly normalish but there's a reasonable possibility of there being heavier tails than you get with the normal distribution, it's probably safer to use the Wilcoxon signed rank test, but it depends in part what your precise hypothesis is and what you're prepared to assume.

However, when using left tailed and right tailed z.test, both of the p-value are larger than 0.05. Does it mean that the z.test is ineffective under this situation?

You can't make that judgement on the basis of a single sample; the tests respond slightly differently to the observations. The outcome of a single test is affected by random variation which may lead to one test having a higher p-value on that particular sample even though it has better power overall.
You can't directly compare one tailed tests with two tailed tests.
You didn't do a paired z-test, so if you did correctly do the paired test in the other two cases you're not comparing like with like. The p-value for a one-sample z-test (ignoring that we estimated the population sd of the differences) would be 0.01771.
(z.test(new-ori,sigma.x=sd(new-ori)))

For a large sample (>30 data values) with normal distribution, is the z.test more appropriate than t.test?

The t-test is still correct, the z-test is approximate, but as the sample size increases, the t-test gets closer to a z-test. Ultimately in sufficiently large samples it doesn't matter which you do, but if you truly had normality there's no particular reason to use the z-test over the t-test no matter how big the sample size. With computers to do the calculation, there's no need to replace the t with an approximation since there's no additional effort involved.
Comment: This is a good answer. I like that you emphasized that the signed rank test is the appropriate form of the Wilcoxon test to use with paired data.  I think it would also be good to distinguish that  the paired t test should be used rather than unpaired t test.
Comment: Thanks very much for the response@Glen,@Michael. Both of your answers are very helpful for me! I made a mistake that in this case, I should use the paired t test rather than unpaired one.     I have another question. For the large sample(>30 data) with normal distribution, is the z.test more appropriate than t.test?
Comment: @宓辰羲 No. The t-test is still correct, the z-test is approximate, but as the sample size increases, the t-test gets closer to a z-test. Ultimately in sufficiently large samples it doesn't matter which you do, but if you truly had normality there's no particular reason to use the z-test over the t-test no matter how big the sample size. With computers to do the calculation, there's no need to replace the t with an approximation.


Regex for validating barcodes

Question: Im new to regexes. Im having a hard time understanding everything and I wanted to write a not so simple program about e-mails but then decided on barcodes. The barcode is valid if it:

Is surrounded with a "@" followed by one or more "#"
Is at least 6  characters long (without the surrounding "@" or "#")
Starts with a capital letter
Contains only letters (lower and upper case) and digits
Ends with a capital letter

I tried a couple of things and achieved absolutely nothing. I even watched a detailed explanation of regexes but still can't come up with anything.
Sample input: @#GoodCodE@# would be valid but @Invalid_CodE@ / @#InvalidTry@# would not.
(@#+)([A-Z][A-Za-z0-9]{4,}[A-Z])(?:@#+) Thank you for all the help! ?= didn't include the @#+ so I replaced it with ?: which does apparently.
Comment: It would help if you add a sample input and expected output..much more easier to follow for some
Comment: ^ would also help to add your own attempt, no matter how terrible =). Without any sample data it look like you want to get capture group one of something like: `(@#+)([A-Z][A-Za-z0-9]{4,}[A-Z])(?=@#+)` (without leading/trailing @# combination)
Comment: (@#+)([A-Z][A-Za-z0-9]{4,}[A-Z])(@#+) worked. ?= excludes @#+ from the capture right? ?: also works so I assume it includes it?
Answer: You could use the following expression: ^@#+[A-Z][A-Za-z0-9]{4,}[A-Z]@#+$
Broken down it means:

^ requires beginning of string (line)
@ match a @ character
#+ match one or more of # characters
[A-Z] match an uppercase letter  (counts as 1st of the 6)
@[A-Za-z0-9]{4,} match 4 or more of upper/lowercase letters and digits
[A-Z] match an uppercase letter  (counts as last of the 6)
@ match a @ character
#+ match one or more of # characters
$ requires end of string (line)
Comment: That's right, but we need `(#)+` to get "one or more "#"".
Comment: Reading the OP's example data, I think the pattern is missing the `#` at the beginning. I think it should be like `^@#+[A-Z][A-Za-z0-9]{4,}[A-Z]@#+$` https://regex101.com/r/GZkDJH/1
Answer: Try this one:
import re

def check_re(inval):
    """
    >>> check_re('@#GoodCodE@#')
    True
    >>> check_re('@Invalid_CodE@/@#InvalidTry@#')
    False
    >>> check_re('@#IdE@#')
    False
    """
    bar_re = re.compile(r'^@#+[A-Z]([A-Za-z0-9]){4,}[A-Z]@#+$')
    m = re.match(bar_re, inval)
    return m is not None

if __name__ == '__main__':
    import doctest
    doctest.testmod()

See the explanation in Alain's answer.

Regex for validating barcodes


Why can't I create a div that has more than one style element?

Question: I am trying to create div like so using jQuery:
let gridBlock = $("

");

However when I look at the render page the console shows that the div only has a style of width:

What am I doing wrong?
Comment: You forgot to quote the style value. Change it to `style='width:10px; height:20px; background-color:red;'`
Comment: Try `let gridBlock = $("");`
Answer: Use quotes mate
let gridBlock = $("

");

Answer: Though you have already got the answer in comment but there is a better way to implement using class. The reason css-specificity. Adding style using style attribute is hard to overwrite & need to use !important for that.
So to avoid that you can use the class attribute and define the style in css file
some.css
.someClass {
  width: 10px;
  height: 20px;
  background-color: red;
}

in js file
let gridBlock = $("
Hello
");

DEMO


How to club a week and day string like "21Fr" into DateTime format?

Question: Hi I am having the day and week of the year that is in the format "21Fr" (21st week of year and day as Friday) and time in "06:00". I want to club this 2 values and get the output in below format? Any help would be highly appreciable

23/05/2014 06:00:00
Comment: Your 21st week can be change depends on `FirstDayOfWeek`. Have you tried anything so far?
Comment: @SonerGönül not only that, but how first week of the year is defined.
Comment: @SonerGönül yes i will update my qtn with the code
Comment: I suggest _clubbing_ whoever gave you datetime in this format into giving you a better format.
Answer: I strongly recommend changing your input format if possible. However, here's one approach:
<code>// parse the input
string input = "21Fr";
// assuming week number is always 2 characters. e.g.: 01, 02, ..., 21, ...
int weeks = int.Parse(input.Substring(0, 2));
// assuming abbreviated day names like this
string[] abbrDayNames = { "Su", "Mo", "Tu", "We","Th", "Fr", "Sa" };
int dayOfWeekValue = Array.IndexOf(abbrDayNames, input.Substring(2));
DayOfWeek dayOfWeek = (DayOfWeek)dayOfWeekValue;

// now let's build the DateTime
// start from first day of year, 6:00 AM
DateTime parsed = new DateTime(DateTime.Now.Year, 1 ,1, 6, 0, 0);
// add first part, weeks
parsed = parsed.AddDays((weeks - 1) * 7);
// reset to first day of week
parsed = parsed.AddDays(-(int)parsed.DayOfWeek);
// then add the second part, day of week
parsed = parsed.AddDays((int)dayOfWeek);
</code>
This also assumes (based on your sample output) week 21 means you're in the 21st week of year.
Comment: thank u  so much it worked. the data is returned from mainframe database cant help to change.