Check directory before creating file in puppet?

Question: I'm trying to make a function which directory/file will be created only when the first directory exists, of not it must be skipped because of failed dependence.
I've tried this "onlyif" workaround, but unfortunately it doesn't work with my function.
$check_directory = file("/path/to/directory")
if($check_directory != '') {
    file{"/path/to/config":
        ensure  =>  directory,
        mode    =>  0755,
    }
    file{"/path/to/config/a.conf":
        ensure  =>  file,
        mode    =>  0755,
        content =>  template("config_template.conf"),
    }
}

I've got an error:
Error: Is a directory - /path/to/directory

Is there a way to do any other if statement? Or any parameter? Thank you.
Answer: You should be able to simply use a require statement in your a.conf file resource:
file{"/path/to/directory":
    ensure  =>  directory,
    mode    =>  0755,
}

file{"/path/to/config":
    ensure  =>  directory,
    mode    =>  0755,
}
file{"/path/to/config/a.conf":
    ensure  =>  file,
    mode    =>  0755,
    content =>  template("config_template.conf"),
    require => File["/path/to/directory"],
}

This will make sure that the directory will be created before the file.
Comment: Thanks for the answer, but it's difference directory. I would like to check another path to configuration, not the one that will be created. if I do so, I will get .. Error: Could not find dependency
Comment: Then you have to add a file resource for that new directory and then use `require` with that resource. See my edited answer.
Comment: Directory/file will be created only when the first directory exists, of not it must be skipped because of failed dependence.
Comment: Sorry, now I got it. But the sample code you wrote doesn't use the `onlyif` trick you linked to. So I am still confused - what exactly did you try and what didn't work. Please read [How to ask better questions on Serverfault](http://meta.serverfault.com/questions/3608/how-can-i-ask-better-questions-on-server-fault) to avoid wasting your and our time.
Answer: The ethos of @Sven's answer is absolutely correct: you set up resource dependencies in Puppet using before, require, notify, etc.  The only thing I would change is I would use the defined() function to test:
file { '/tmp/foo':
  ensure => 'directory',
  mode   => '0755',
}
if defined(File['/tmp/foo']) {
  notice("/tmp/foo is defined! making /tmp/bar/baz")

  file { '/tmp/bar':
    ensure => 'directory',
    mode   => '0755',
  }

  file { '/tmp/bar/baz':
    ensure  => 'present',
    mode    => '0755',
    require => File['/tmp/bar'],
  }
}

Two other useful tidbits:

If you enable the "Future Parser" in Puppet 3.2+, you can access resource attributes like so: $a = File['/tmp/foo']['ensure'].  This would store the value of the ensure attribute for the /tmp/foo file resource in the variable $a.  If you decide to look into this, I would rewrite the above example to use if defined(File['/tmp/foo']) and File['/tmp/foo']['ensure'] == 'directory' (UNTESTED).
If you're passing these items as parameters to a class, there is a sneaky way to access the values of class parameters via in-puppet-how-can-i-access-a-variable-attribute-inside-a-defined-type.
Answer: EDIT: The below works if you're using puppet apply but not otherwise, because the find_file function is evaluated during catalog compilation.  That means this approach checks the existence of /path/to/directory/. on whatever server is used to compile the catalog, NOT on the host where the catalog is actually applied.  So likely not what the average user is looking for.  In a traditional puppetmaster/client architecture, the catalog is not compiled on the host that is to use that catalog.

Seems to work fine with find_file; hat tip to this blog post that led me in the right direction.
$check_directory = find_file("/path/to/directory/.")
if $check_directory {
    file{"/path/to/config":
        ensure  =>  directory,
        mode    =>  0755,
    }
    file{"/path/to/config/a.conf":
        ensure  =>  file,
        mode    =>  0755,
        content =>  template("config_template.conf"),
    }
}

$check_directory will be undef if the directory isn't present, so that evaluates to false.
Note the addition of the trailing /. which causes the check to fail (and the code not to be run) in the case that /path/to/directory exists but is a FILE rather than a directory.


OWL API: How to assign domain to range on OWLObjectProperty

Question: In fact I want to create an ontology based in a list of concepts(String) and relationships between concepts(Map). I have two types of relation "kind of" and "sub Topic of". So I tried to create this ontology trough owl api. To create relation between two OWL classes I used OWLObjectPreportyDomain and OWLObjectProprertyRange and specified a relation through OWLObjectProperty.
My problem is when I create a relation that has many domains and many ranges, I didn't find a manner to assign each domain to each range.
I want to find a solution for that. Could any one give me an idea ?
For example I have this Map : Map<String, String> relation = new HashMap<String, String>; which contains two concepts and relation between each other.
LinkedList<Map<String, String>> listRelation = new LikedList<Map<String,String>>;
this list contains the list of relation between concepts.
relation("concept1")="AUTHETICATION";
realtion("relation")="kind of";
relation("concept2")="VALIDATION";
listRelation.add(relation);
relation = new HashMap<String, String>;
relation("concept1")="ENCRYPTION";
realtion("relation")="kind of";
relation("concept2")="CRYPTHOGRAPHY";
listRelation.add(relation);
And I create an other Map which contains concept and his instance like:
Map<String,String> inst;
inst("concept")="authentication";
inst("instance")="topNet";
how could I create this in OWL. Concepts are OWLClass or OWLNamedIndividual. If they are OWLNamedIndividual so instances are what. Moreover if concepts are OWLClass how to declare relation between them ?
Comment: Can you explain what you mean by 'each domain to each range'? There is no particular relation between a domain class expression and a range class expression, in OWL
Comment: I will intorduce in the following an example:

"AUTHENTIFICATION"  concept is a kind of "VALIDATION" concept and "ENCRYPTION" is kind of "CRYPTOGRAPHY".

In this case, I have two domains AUTHENTIFICATION and ENCRYPTION" and two ranges VALIDATION and CRYPTOGRAPHY.

Therefore, The OWLObjectProperty:"#kind of" has  two domains and two ranges but when I check the .owl file I can't know which range is for which domains.
Comment: From your example I get the impression that `Authentication` and `Validation` are not classes but individuals, and that what you have are assertions and not domain and range declarations. However, declaring multiple domains is equivalent to declaring an intersection of all classes listed and assigning it to be the domain; same for the range. There isn't a preferred domain for a particular range. What you can do is, e.g., writing a class which is a subclass of the domain and of `all kind_of range
Answer: From your example I get the impression that Authentication and Validation are not classes but individuals, and that what you have are assertions and not domain and range declarations.
However, declaring multiple domains is equivalent to declaring an intersection of all classes listed and assigning it to be the domain; same for the range. There isn't a preferred domain for a particular range.
What you can do is, e.g., writing a class C subclass of Authentication and subclass of all kind_of Validation, which, for any instance, will assert domain and range equivalent for kind_of
Comment: Thank you so much for the answer. But I'm still bit confused how to distinguish between OWLClass and OWLIndividual. In fact my ontology has concepts and instances. To implement it in OWL language I thought that concept is a class and instance is an individual. on my exemple Authentication  and Validation are declared as concepts in the ontology. I could use `OWLNamedIndividual` to declare concept in OWL ?
Comment: It's becoming difficult to discuss this without a concrete example. Can you add your ontology, or the relevant portion, to the question?
Comment: Ok, I have edited my question and I added a concrete example.
Answer: class = concept,
individual = instance (of a class, you instantiate a class to get an individual)
I'll continue with the assumption that you consider these classes/concepts.
If you just want to say that Encryption is a type of Cryptography, then you only need to declare Ecryption subClassOf Cryptography. No need of object properties at all.
If you have other types of relations that you want to use, say "hasRelationYTo" you'll write the axiom, something like

Encryption and hasRelationYTo some/only Cryptography (Manchester syntax)

Like Ignazio said,

There is no particular relation between a domain class expression and
  a range class expression, in OWL

The range and domain of the property (=relation=function) are generic and meant to prevent errors. This means you cannot specify
Domain1 - propA - Range1 (but not, say Domain2 - propA - Range1)
Domain2- propA -Range2
Object property declaration allows you only declarations like {Domain1 U Domain2} - propA - {Range1 U Range2} . If you really really need to do something like above, you'll have to use 2 different object properties propA and propB. This is often not the case and having multiple Domains and Ranges together is enough.
Here is the OWL file that models
"AUTHENTIFICATION" is a kind of "VALIDATION"
"ENCRYPTION" is kind of "CRYPTOGRAPHY"
Also, you might want to have a look at the protege pizza tutorial to get a better feeling of OWL . If I remember well, it only takes about 20 mins to do.
<?xml version="1.0"?>

<!DOCTYPE rdf:RDF [
<!ENTITY owl "http://www.w3.org/2002/07/owl#" >
<!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" >
<!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" >
<!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" >

]>

<owl:ObjectProperty rdf:about="http://www.semanticweb.org/tudose/ontologies/2014/3/untitled-ontology-59#is_a_kind_of"/>

<owl:Class rdf:about="http://www.semanticweb.org/tudose/ontologies/2014/3/untitled-ontology-59#AUTHENTIFICATION">
    <rdfs:subClassOf>
        <owl:Restriction>
            <owl:onProperty rdf:resource="http://www.semanticweb.org/tudose/ontologies/2014/3/untitled-ontology-59#is_a_kind_of"/>
            <owl:someValuesFrom rdf:resource="http://www.semanticweb.org/tudose/ontologies/2014/3/untitled-ontology-59#Validation"/>
        </owl:Restriction>
    </rdfs:subClassOf>
</owl:Class>

<owl:Class rdf:about="http://www.semanticweb.org/tudose/ontologies/2014/3/untitled-ontology-59#Cryptography">
    <rdfs:subClassOf>
        <owl:Restriction>
            <owl:onProperty rdf:resource="http://www.semanticweb.org/tudose/ontologies/2014/3/untitled-ontology-59#is_a_kind_of"/>
            <owl:someValuesFrom rdf:resource="http://www.semanticweb.org/tudose/ontologies/2014/3/untitled-ontology-59#Encryption"/>
        </owl:Restriction>
    </rdfs:subClassOf>
</owl:Class>

<owl:Class rdf:about="http://www.semanticweb.org/tudose/ontologies/2014/3/untitled-ontology-59#Encryption"/>

<owl:Class rdf:about="http://www.semanticweb.org/tudose/ontologies/2014/3/untitled-ontology-59#Validation"/>

Comment: thank you very much for your response. In fact I try to create a new ObjectProperty with the same URI as I have many concepts that are linked with the same type of relationship but it refers to a single ObjectProperty automatically.  therefore as a conclusion we  can not have multiple ObjectProperty with the same IRI. I thought about using SubClassOf  but I have other types of relationships. I really have not succeeded in finding a solution that doing about this problem
Comment: No, you cannot use the same URI for different objects, U stands for unique.
Comment: I think maybe you are trying to model your example at the property level instead of adding an axiom?
Comment: thank you for your help. My problem is besides of relation KindOf I have other relations like subTopicOf, parTOf... and it has multiple domain and range.
Im adding an axiom:`genders.add(factory.getOWLObjectPropertyAssertionAxiom(sub-topicOf, c1,c2));` which `genders` is a `HashSet()` and then I do this ` List la=manager.addAxioms(ontology, genders); manager.applyChanges(la)`
I just need to declare c1 and c2 as OWLClass not an OWLNamedIndividual as in this example in the given code. I read OWL documentation and I can't found solution.I hope that I will find it here.
Comment: An other question please : could we make relation between two OWLClass trough AWLAnnotationAssertion and it has the same result as OWLObjectProperty ??
Thanks in advance for the answer.


Java Spring: Método post não insere o id do relacionamento

Question: Estou aprendendo o framework Spring, tentei seguir alguns tutoriais de relacionamento 1-1 onde uma biblioteca possui um endereço. Ao enviar no body os dados da biblioteca e o id do endereço, um novo registro é inserido na tabela bibliotecas, porém o address_id que referencia um endereço não é inserido, mesmo passando no request payload.
Meu model Library:
@Entity
@Table(name = "Bibliotecas")
public class Library implements Serializable {
  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  private String name;

  @OneToOne
  @JoinColumn(name = "address_id", referencedColumnName = "id")
  private Address address;

  public Library() {
  }

  public long getId() {
    return this.id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Address getAddress() {
    return this.address;
  }

  public void setAddress(Address address) {
    this.address = address;
  }

}

Meu model Address:
@Entity
public class Address {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @Column(nullable = false)
  private String location;

  public long getId() {
    return this.id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getLocation() {
    return this.location;
  }

  public void setLocation(String location) {
    this.location = location;
  }

  @OneToOne(mappedBy = "address", fetch = FetchType.LAZY, optional = false)
  private Library library;

}

Meus repositories:
public interface LibraryRepository extends JpaRepository<Library, Long> {}
public interface AddressRepository extends JpaRepository<Address, Long> {}

Meu library resource:
@RestController
@RequestMapping(value = "/api")
public class LibraryResource {

  @Autowired
  LibraryRepository libraryRepository;

  @GetMapping("/libraries")
  public List<Library> listaBibliotecas() {
    return libraryRepository.findAll();
  }

  @PostMapping("/library")
  public Library salvaBiblioteca(@RequestBody Library library) {
    return libraryRepository.save(library);
  }
}

E então eu passo no meu request:
{
    "name": "Biblioteca test",
    "address_id": 1
}

Obs: Existe um address com id 1, eu recebo de retorno:
{
    "id": 5,
    "name": "Biblioteca test",
    "address": null
}

No meu retorno address é null, e quando dou um select no banco, o registro criado possui address_id null. Como posso corrigir a ligação entre esses dois modelos? Porque isso está ocorrendo?
Answer: Sua request deveria ser assim.
Montei um exemplo aqui no Github com base nas suas classes.
{
    "name": "Biblioteca test",
    "address": {
        "id":"1"
    }
}

Response
Comment: O save não irá retornar o objeto do seu relacionamento de forma gerenciada. ELe irá retornar os dados que você enviar para ele.

Nesse caso aqui, ele irá tentar fazer o relacionamento com o adress de id 1 e irá retornar o objeto com as demais propriedades que você enviou.

{
    "name": "Biblioteca test",
    "address": {
     "id":"1",
     "location": "objeto"
    }
}

Talvez se você trocar o método sabe pelo merge resolva o problema ou você teria que realizar a consulta do objeto library para ele retornar todos os dados.
Comment: Funcionou dessa forma, @rafaelchagasb, obrigado. Você sabe me dizer porque o location retorna null mesmo quando o registro relacionado possui dados na coluna location?


Twig template name for field when content type is viewed in particular view mode

Question: Based on twig template naming conventions I have created twig for any field type of given content:
field--node--myContentType.html.twig

Is it possible to use different twig when myContentType is visible in "full" view mode? I've already tried:
field--node--myContentType--full.html.twig

But it does not triggers. I can use node--myContentType.html.twig and node--myContentType--full.html.twig for full view of the node, but it doesn't work for field twig.
Answer: Field templates have no name suggestion for the view mode.
From the linked page:

This page lists the conventions used for the base html structure, the
  page, regions, blocks, nodes, fields, and other core components. (It's
  good to know that it is possible to create custom template name
  suggestions using function hook_theme_suggestions_HOOK_alter.)

You have to create a custom name suggestion.
You find the view mode in the variables of the field: Getting node view mode in field preprocess


Why do servers bounce the ball before serving?

Question: I've participated in a volleyball tournament, and noticed that servers (especially those doing overhand serves) bounced the ball twice before starting the serve.
Why do servers do this?
Comment: As far as I can tell, this is more of a "ritual" than anything that gives you an actual advantage.  It's something you do to kind of focus yourself and keep your mind on something you've done a million times instead of thinking about anything else in the game.
Answer: It's just a ritual.
Some players hold the ball straight in front of them (like Marcus Böhme, Maxim Mikhailov), some bounce it, some even talk to themselves (like Christian Fromm from the German National team). It helps concentration. It helps you focus on your serve and it let's you take full advantage of the eight seconds available to perform your serve. Some beginners tend to hasten doing their serve, resulting in a lack of focus and increasing the chance of erring.
Some players don't have any ritual at all, though.


Partial sorting: select at most N elements including for sure the top T elements

Question: To whom it may concern.
My "population" with known size P is a landscape and has not more than 4 peaks with about same high. Naturally top elements group locally within the population. I seek the top T elements. Sorting the whole population is easy, but takes to much time.
My question belongs to the topic of partial sorting: Not the whole population shall be sorted, but only at most top N elements, which shall include for sure the top T elements.
To achieve this, I evenly sample the population, sort the sampled set and use a quantile to find / estimate a threshold from the sorted sub-population. Then I split the whole population with the threshold to get (hopefully) at most top N elements, but for sure those top T elements.

Can the sufficient sample size S be calculated from P, so that I do not get more than N top elements including for sure those top T elements?
The threshold is an estimate. Can the quantile be calculated, so I do for sure do not get more than top N elements?

Which field in statistics belongs this question?
Thanks in advance. Best regards, Stephan
Edit:
Your reflection and further research on the internet convinced me, that my approach is not robust without iterations.
The better approach is a selection algorithm seeking the nth element in an unordered list.
Comment: Please merge your 3(!) accounts (there is information [here](http://stats.stackexchange.com/help/merging-accounts)). Then you will be able to edit & comment on your own question & be notified of answers, comments & other activity here.
Comment: I will share my current level as an answer, because as guest I cannot comment. I think I cannot be 100% sure, too. This is the way how I calculate the quantile to access the threshold from the sorted list: uint quantile = N / sampleStepping ; // trunc() uint threshold = d_subKeysIn[ numSamples -1 - quantile ]; In my case: P is 221000, N is desired by me to be less equal 1024, hence N is 1000, sampleStepping is 101 which gives numSamples = 2188 I also was thinking about iterating. But I could also use a larger quantile just from the beginning. But there is this constraint about N ... I tried a
Comment: The problem with *not* merging accounts is that when the posts you put in place of answers are (necessarily) turned into comments, they get truncated at 500 characters. There's nothing we can do about that.  We can't merge your accounts for you, either: you have to click that button.
Answer: Given the description, I don't think you can know anything for sure without looking at most of the data. It seems like maybe making a pass through the data is not that expensive but you don't want to do a complete sort. I'd suggest a scheme similar to yours -- something like sampling approximately $P/T$ points; find the max, $m$, of those results (note: you do not need to do a complete sort to do that, just go through the numbers and replace $m$ with a new value whenever it is exceeded); then go through all the data and identify all the points greater than $m$. With a little luck, you'll have at least $T$ of them. If not, go back through using the second largest initial value instead of $m$.
We don't have a probability model for the data you are looking at, so this is really more of an algorithmic, rather than statistical, question. You might find better advice on Stack Overflow?
Comment: (+1) A version of Quicksort, which formalizes the *ad hoc* method described here, is optimal for finding a fixed number $k$ of highest values. It operates in expected $O(k n)$ time for $n$ numbers. A full sort, which takes $O(n\log n)$, is more expensive when $n$ is large and $k$ is small. Heap-based algorithms attain the same asymptotics, too, even in worst-case time.


RecyclerView Messing Up Views When Scrolling - With Picture

Question: I am working on a chat app. I have the chat activity where the two users can send messages like WhatsApp, but I have a problem.
Like you can see in the picture (https://ibb.co/3cyYX01), the views are messing up when scrolling, and I think I know why.
After looking into those posts:
RecyclerView messes up when scrolling ,
Android: RecyclerView content messed up after scrolling
I assume the problem may be in the recycler view adapter in the function onBindViewHolder, because I am using the visibility option on some views(VIEW.GONE and VIEW.VISIBLE) and I think that these views are getting redrawn with wrong visibility.
In addition, I used holder.setIsRecyclable(false) in onBindViewHolder in order to check if it's the recycling part that cause the problem and when I used it, it worked perfectly.
This is the RecyclerView Adapter:
    private const val SEND_LAYOUT = 0
private const val RECEIVED_LAYOUT = 1

class ChatRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private lateinit var receiverUserPic: String
    private lateinit var messageList: List<Message>
    private lateinit var currentUserPic: String
    private lateinit var currentUserUID: String
    private lateinit var targetUID: String

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        val viewHolder: RecyclerView.ViewHolder
        val view: View

        viewHolder = if (viewType == SEND_LAYOUT) {

            view = LayoutInflater.from(parent.context)
                .inflate(R.layout.sent_message_row, parent, false)
            SentViewHolder(view)

        } else {

            view = LayoutInflater.from(parent.context)
                .inflate(R.layout.recieved_message_row, parent, false)
            ReceivedViewHolder(view)

        }

        return viewHolder

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

        //holder.setIsRecyclable(false)
        val currentMessage = messageList[position]

        if (holder.itemViewType == SEND_LAYOUT) {

            holder as SentViewHolder
            holder.bindSentRow(currentMessage)

        } else {

            holder as ReceivedViewHolder
            holder.bindReceivedRow(currentMessage)

        }

    }

    override fun getItemCount(): Int {
        return messageList.size
    }

    override fun getItemViewType(position: Int): Int {

        val currentMessage = messageList[position]

        return if (FirebaseAuth.getInstance().currentUser?.uid.equals(currentMessage.sender))
            SEND_LAYOUT
        else
            RECEIVED_LAYOUT

    }

    inner class SentViewHolder(private val itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindSentRow(message: Message) {

            val sentMessageTextView =
                itemView.findViewById<TextView>(R.id.sentMessage)
            val sentImage = itemView.findViewById<ImageView>(R.id.sentImage)
            val profileImage =
                itemView.findViewById<ImageView>(R.id.sentMessageProfilePicture)
            val sentIsSeenImageTextView =
                itemView.findViewById<TextView>(R.id.sentIsSeenImageTextView)
            val sentIsSeenTextView =
                itemView.findViewById<TextView>(R.id.sentIsSeenTextView)

            profileImage.setOnClickListener {

                val visitProfileIntent = Intent(it.context, VisitProfileActivity::class.java)
                visitProfileIntent.putExtra("targetUID", currentUserUID)
                it.context.startActivity(visitProfileIntent)

            }

            if (message.message.equals("Sent you an image") && !message.url.equals("")) {

                sentMessageTextView.visibility = View.GONE
                sentIsSeenImageTextView.visibility = View.VISIBLE
                sentIsSeenTextView.visibility = View.GONE
                sentImage.visibility = View.VISIBLE

                Glide.with(itemView.rootView).load(message.url)
                    .override(SIZE_ORIGINAL, SIZE_ORIGINAL)
                    .error(R.drawable.error_icon)
                    .placeholder(R.drawable.loading_icon)
                    .listener(object : RequestListener<Drawable?> {
                        override fun onLoadFailed(
                            @Nullable e: GlideException?,
                            model: Any,
                            target: Target<Drawable?>,
                            isFirstResource: Boolean
                        ): Boolean {
                            return false
                        }

                        override fun onResourceReady(
                            resource: Drawable?,
                            model: Any?,
                            target: Target<Drawable?>?,
                            dataSource: DataSource?,
                            isFirstResource: Boolean
                        ): Boolean {
                            return false
                        }
                    }).into(sentImage)

                if (adapterPosition == messageList.size - 1) {
                    sentIsSeenImageTextView.visibility = View.VISIBLE
                    sentIsSeenTextView.visibility = View.GONE

                    if (message.seen == true) {
                        sentIsSeenImageTextView.text = "Seen"
                    } else {
                        sentIsSeenImageTextView.text = "Sent"
                    }

                } else {
                    sentIsSeenImageTextView.visibility = View.GONE
                }

        } else {

            sentMessageTextView.visibility = View.VISIBLE
            sentMessageTextView.text = message.message
            sentIsSeenImageTextView.visibility = View.GONE

            if (adapterPosition == messageList.size - 1) {
                sentIsSeenTextView.visibility = View.VISIBLE
                sentIsSeenImageTextView.visibility = View.GONE

                if (message.seen == true) {
                    sentIsSeenTextView.text = "Seen"
                } else {
                    sentIsSeenTextView.text = "Sent"
                }

            }

        }

        Glide.with(itemView.rootView).load(currentUserPic).into(profileImage)

    }

}

inner class ReceivedViewHolder(private val itemView: View) : RecyclerView.ViewHolder(itemView) {

    fun bindReceivedRow(message: Message) {

        val receiveMessageTextView =
            itemView.findViewById<TextView>(R.id.receivedMessage)
        val receiveImage =
            itemView.findViewById<ImageView>(R.id.receivedImage)
        val receiveProfileImage =
            itemView.findViewById<ImageView>(R.id.receivedMessageProfileImage)

        receiveProfileImage.setOnClickListener {

            val visitProfileIntent = Intent(it.context, VisitProfileActivity::class.java)
            visitProfileIntent.putExtra("targetUID", targetUID)
            it.context.startActivity(visitProfileIntent)

        }

        if (message.message.equals("Sent you an image") && !message.url.equals("")) {

            receiveMessageTextView.visibility = View.GONE
            receiveImage.visibility = View.VISIBLE

            Glide.with(itemView.rootView).load(message.url).into(receiveImage)

        } else {

            receiveMessageTextView.visibility = View.VISIBLE
            receiveMessageTextView.text = message.message

        }

        Glide.with(itemView.rootView).load(receiverUserPic).into(receiveProfileImage)

    }

}

fun getMessageList(): List<Message> {
    return messageList
}

fun setMessagesList(
    newList: List<Message>,
    userProfilePic: String,
    userProfilePic1: String,
    currentUID: String,
    receiverUID: String
) {
    messageList = newList
    currentUserPic = userProfilePic
    receiverUserPic = userProfilePic1
    currentUserUID = currentUID
    targetUID = receiverUID
    notifyDataSetChanged()
}

}

Pastebin Link:
https://pastebin.com/Ri5pUAdk
Thank you !
Comment: What's "Messing up" exactly?
Comment: @IvanWooll You can see in the attached picture that the image is displaying over the text message
Answer: Working of the recyleView is based on that, it recycles views to show a list. When you scroll, views which go out of the screen, are not destroyed but are reused again to show the new list item. So, if you change visibility or any other property of a view and don't reset it again inside onBindViewHolder, then it would show all the properties which were set earlier before it got recycled.
fun bind(data: Data) {
    val textView = itemView.findViewById<TextView>(R.id.tvText)
    if(data.text.isEmpty()) {
        textView.visibility = View.GONE
    }
}

In the above method, we are hiding textView when text is empty, but we are not setting anything in the else condition. So when views, for which we've set visibility to gone would be recycled, they'd never show the textView as it is reusing the view. To deal with this, we've to set the properties of the views for true and false conditions each.
fun bind(data: Data) {
    val textView = itemView.findViewById<TextView>(R.id.tvText)
    if(data.text.isEmpty()) {
        textView.visibility = View.GONE
    } else {
        textView.visibility = View.VISIBLE
    }
}

In SentViewHolder and ReceivedViewHolder, you are setting the visibility of the ImageView to visible
sentImage.visibility = View.VISIBLE

receiveImage.visibility = View.VISIBLE

but you are never setting it to gone.
In the else condition of (message.message.equals("Sent you an image") && !message.url.equals("")), set the visibility of ImageView to GONE. Do the same for all other views too, so you don't get an unexpected UI.
Comment: Thank you very much for the detailed and accurate explanation!
Answer: Because the view holder is being recycled and reused that cause your views to be in the wrong state.
In SendViewHolder class you only handle the state of sentImage in if block by setting the visibility to visible. Therefore you also need to set its visibility to gone in else block.
Or you can reset the view visibility first then show it like below.
fun bindSendRow(message: Message) {
    sentMessageTextView.visibility = View.GONE
    sentImage.visibilty = View.GONE
    if(shouldShowImage){
        sentImage.visibility = View.VISIBLE
    } else if(shouldShowText){
        sentMessageTextView.visibility = View.VISIBLE
    }
}

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


This XML file does not appear to have any style information associated with it. The document tree is shown below.2

Question: When using the following code in django template:
  <!DOCTYPE html>

<link href="http://184.108.40.206/static/wiki/bootstrap/css/wiki-bootstrap.css" type="text/css" rel="stylesheet"/>
<link href="http://188.8.131.52/static/wiki/bootstrap/css/simple-sidebar.css" type="text/css" rel="stylesheet"/>
<title> Profile - Technology βιβλιοθήκη </title>

    {% for p in profiles %}
     {{p}}
    {% endfor %}

I receive the following error:
This XML file does not appear to have any style information associated with it. The document tree is shown below.

Why? And what can I do to fix it?
Solved: by change HttpResponse on render_to_response
   my_context={'profiles': profiles}
   c = RequestContext(request,{'profiles': profiles})
   return render_to_response('wiki/profile.html',
                      my_context,
                      context_instance=RequestContext(request))
   #return HttpResponse(t.render(c), content_type="application/xhtml+xml")

Comment: How can we reproduce this error?
Comment: skip {% for p in profiles %}
     {{p}}
    {% endfor %}
Comment: @AndreyEremchuk where did you see the error? simply opening HTML file in browser should never produce such error...
Comment: i use django template processor/ simple open in browser
Answer: You must replace your content html tag with this.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


Como incluir linhas em um data.frame?

Question: Considere o seguinte data.frame:
df <- data.frame(x=c("a","b"), y=c(1,2))

Como incluir uma nova linha com x="c" e y=3 no data.frame?
Answer: A função rbind faz uma cópia do data.framepara depois adicionar a linha, o que a torna ineficiente.
Uma alternativa é usar a função rbind_list do pacote dplyr:
linha <- data.frame(x="c", y=3)
library(dplyr)
df <- rbind_list(df, linha)

Neste caso, como estamos incluindo um novo nível do fator x, ela nos dá um aviso que está convertendo a variável para tipo character.
O benchmark está abaixo:
library(microbenchmark)
time <- microbenchmark(
  rbind_list(df, linha),
  rbind(df, linha)
  )
time
## Unit: microseconds
##                   expr     min      lq   median       uq     max neval
##  rbind_list(df, linha)  85.342  90.478  95.2195 100.9485 234.295   100
##       rbind(df, linha) 258.396 269.855 279.1390 294.7460 528.250   100

Answer: Uma forma de fazer isso é criar um novo data.frame com a linha que se deseja incluir e utilizar a função rbind:
linha <- data.frame(x="c", y=3)
df <- rbind(df, linha)
df
  x y
1 a 1
2 b 2
3 c 3

Answer: Uma outra possibilidade é usando a função add_row() do dplyr:
library(dplyr)

add_row(df, x="c", y=3)

  x y
1 a 1
2 b 2
3 c 3

Como incluir linhas em um data.frame?


Show that a Hausdorff space $X$ is regular if and only if $X/A$ is Hausdorff for all $A$ closed in $X$.

Question:
Show that a Hausdorff space $X$ is regular if and only if $X/A$ is Hausdorff for all $A$ closed in $X$.

Assume that $X$ is regular. Let $x, y \in X/A$ such that $x \ne y$. If $x \ne A$ and $y \ne A$, then $q^{-1}(\{x\})=x$ and $q^{-1}(\{y\})=y$. As $X$ is Hausdorff there exists open neighborhoods $U_1$ and $U_2$ of $x$ and $y$ respectively. Now $q$ being surjective implies that $q^{-1}(q(U_1))=U_1$ and $q^{-1}(q(U_2))=U_2$. Since each $U_i$ is open the quotient topology that $X/A$ has implies that $q(U_1)$ and $q(U_2)$ are both open. We also have that $$q^{-1}(q(U_1 \cap U_2))= \emptyset$$ but I don't know if we can derive the result that $q(U_1) \cap q(U_2) = \emptyset$ which would imply that $X/A$ is Hausdorff?
Answer: First of all recall the following:

Lemma. If $f:X\to Y$ is a surjective function and $A,B\subseteq Y$ are such that $f^{-1}(A)$ is disjoint from $f^{-1}(B)$ then $A,B$ have to be disjoint as well.

Proof. Assume otherwise that $x\in A\cap B$. Then $f^{-1}(x)\subseteq f^{-1}(A)$ and $f^{-1}(x)\subseteq f^{-1}(B)$. Since $f$ is surjective then $f^{-1}(x)$ is nonempty showing that $f^{-1}(A)$ and $f^{-1}(B)$ are not disjoint. Contradiction. $\Box$
This property reduces the problem "$q(U)$ is disjoint from $q(V)$" to "$q^{-1}(q(U))$ is disjoint from $q^{-1}(q(V))$", which is immediate if $q^{-1}(q(U))=U$ and $q^{-1}(q(V))=V$. However:

Now $q$ being surjective implies that $q^{-1}(q(U_1))=U_1$

That is unfortunately wrong. The real equality is $q(q^{-1}(F))=F$ for surjective functions. The equality you wrote is for injective functions. In fact consider what happens when $U_1$ intersects $A$ (nothing you wrote stops that from happening). Then $q^{-1}(q(U_1))=U_1\cup A$ which no longer has to be open. And if the same happens for $U_2$ then additionally their images are no longer disjoint, even though they still can be disjoint in $X$ (obviously $A$ has to have more than $1$ element in such scenario).
What you can show is that for a subset $B\subseteq X$ we have
$$q^{-1}(q(B))=\begin{cases}
B&\text{if }B\cap A=\emptyset\\
B\cup A&\text{otherwise}
\end{cases}$$
So how do we utilize all of that?
"$\Rightarrow$" Assume $[x],[y]\in X/A$, $[x]\neq[y]$. There are two cases:

$[x]\neq A$ and $[y]\neq A$. Then as you wrote $q^{-1}([x])=\{x\}$ and $q^{-1}([y])=\{y\}$. Since $X$ is Hausdorff then so is $X-A$ (which is open) and thus $x$ and $y$ can be be separated by open subsets $U$, $V$ of $X-A$. Therefore $U$, $V$ are open subsets of $X$ that do not intersect $A$. Thus $q^{-1}(q(U))=U$ and $q^{-1}(q(V))=V$ showing that $q(U)$ and $q(V)$ are open and (by our lemma) disjoint in $X/A$.

So my reasoning is almost the same as yours, except I had this one additonal step that my open neighbourhoods are taken in $X-A$ instead of whole $X$. In order to guarantee the $q^{-1}(q(B))=B$ property, which then gives us that images are open and disjoint.

One of them is $A$, e.g. $[y]=A$. Then $q^{-1}([x])=\{x\}$ but $q^{-1}([y])=A$. Since $X$ is regular than these can be separated by open neighbourhoods $U$, $V$ of $x$ and $A$ respectively. Note that $U$ doesn't intersect $A$ and thus $q^{-1}(q(U))=U$, while $q^{-1}(q(V))=V\cup A=V$ as well (because $A\subseteq V$). This shows that $q(U)$ and $q(V)$ are open and (by our lemma) disjoint in $X/A$.

"$\Leftarrow$" Let $A\subseteq X$ be a closed subset and $x\in X-A$. Since $X/A$ is Hausdorff then $A$ and $[x]$ can be separated by open subsets $U$, $V$ in $X/A$. It follows that $q^{-1}(U)$ and $q^{-1}(V)$ are open subsets separating $A$ from $x$ in $X$.
Comment: Thanks for a really great answer! Any advice on learning topology? It seems to be a lot about knowing the right definitions, but often in the end you usually need some "enlightment" to finish off the problems.
Comment: So first of all you have to focus on details. This is important in entire math, not only topology. Sometimes there are easy to miss nuances that have huge consequences, like the mistake you've made with preimage of image. But don't worry too much about it, we all make mistakes. Talk with people, ask questions. Do not give up. And I suppose that "learn by doing" is the best advice I can give you.
Answer: As $A$ is closed, we may assume that $U_i \cap A = \emptyset$, $i = 1$, $2$ (otherwise replace $U_i$ by $U_i \cap (X \setminus A)$). Then on both $U_i$ $q$ is a bijection, therefore
$$ q[U_1] \cap q[U_2] = q[U_1 \cap U_2] = q[\emptyset] = \emptyset$$
Note that this does not imply $X/A$ being Hausdorff, you still have to consider the case $x = A$, $y \ne A$. Use regularity here.


Issue decoding JSON after Ext.Ajax.Request

Question: I'm facing issues with ExtJS 4.1.3.
In my ExtJS controller, I call an ajax request like this :
Ext.Ajax.request(
    {
        url: '/my/url/method.do'
        ,timeout: 1800000
        ,jsonData: param
        ,success:function(response)
        {
            var jsonData = Ext.JSON.decode(response.responseText);
            alert(jsonData);
            // some code
        }
        ,failure:function(response)
        {
            // some code
        }
        ,scope:this
    }
);

This is the method called in spring :
@RequestMapping(value = "/my/url/method.do")
public @ResponseBody String method(Locale userLocale, @RequestBody Param[] param) {
    return "string" + "
" + "string";
}

It works well on Google Chrome and IE but not on Firefox. Indeed, I get the following error :
Ext.Error: You're trying to decode an invalid JSON String: string
string

And I don't know why it doesn't work because if I execute the following code in the Firefox console, it works :
Ext.JSON.decode("string
string")

So if anyone could help me, I would be grateful !
Comment: I would have to say that it shouldn't work because that is not a valid JSON string.  Looks to me like IE and Chrome are giving you a false positive.
Comment: I could not reproduce, [`Ext.JSON.decode("stringstring")`](https://fiddle.sencha.com/#fiddle/16p4) throws errors in all browsers for me. Could you please check whether the backend framework eventually produces different output between the browsers?
Answer: Thanks for your answers.
This website http://jsonlint.com/ indicates "string
string" as a valid JSON string. But it is a "false" JSON validation cause it is not proper JSON format.
I solved my problem adding produce="application/json" in the @EequestMapping annotation of the controller. So now Ext.JSON.decode() works even with Firefox.
I could also send back an object serializable with the ajax request and then decode the response to get the data (with my string in it) because Spring automatically serialize object to JSON.


Finite-dimensional vector spaces and vector components...

Question: Are the following remarks correct ?
We've got the vector space $\mathbb{R^n}$ (for the following it doesn't matter whether we identify it with $M_{1 \times n}$ or $M_{n \times 1}$). We define $e_1, e_2, \ldots, e_n \in \mathbb{R}^n$ by
$$
e_1 := (1, 0, \ldots, 0), \\ e_2 := (0, 1, 0, \ldots, 0), \\ \vdots \\e_n := (0, \ldots, 0, 1).
$$
Up to this point no basis is required. Now, with respect to the basis $\mathcal{C} := \{e_1, e_2, \ldots, e_n\}$, every vector $v \in \mathbb{R}^n$ satisfies
$$
v = [v]_{\mathcal{C}},
$$
where
$$
[v]_{\mathcal{C}} := (v_1, v_2, \ldots, v_n) \in \mathbb{R}^n \text{ such that } v = v_1 e_1 + v_2 e_2 + \cdots + v_n e_n.
$$
Let $\mathcal{D} := \{d_1, d_2, \ldots, d_n\}$ be a basis of $\mathbb{R}^n$ different from $\mathcal{C}$. Then, in general, if $v \neq 0 \in \mathbb{R}^n$,
$$
v \neq [v]_{\mathcal{D}}.
$$
When we talk about the matrix $A \in M_{n \times n}(\mathbb{R})$ describing the linear operator $T : \mathbb{R}^n \to \mathbb{R}^n$ with respect to the basis $\mathcal{D}$, we talk about the unique matrix $A \in M_{n \times n}(\mathbb{R})$ such that for all $v \in \mathbb{R}^n$,
$$
[T(v)]_{\mathcal{D}} = A [v]_{\mathcal{D}}.
$$
The case of the vector space $\mathbb{R}^n$ is quite singular, since we can always describe a vector in this vector space as an $n$-tuple of real numbers without ever mentioning a basis.
In general, however, when we identify a vector space $V$ of dimension $n$ over $\mathbb{R}$ to $\mathbb{R}^n$, we must, in all rigour, specify a reference basis for $V$, and we can't reduce the notation $[v]_{\mathcal{D}} \in \mathbb{R}^n$ to simply $v \in \mathbb{R}^n$ for vectors $v \in V$.
Conventionally, however, we do drop the heavy notation $[\cdot]_{\mathcal{D}}$, when the reference basis is understood. In fact even when the reference basis is not mentioned, we drop the notation and it is understood that the reference basis is the standard basis for $V$ (e.g. $\{1, x\}$ for the vector space of polynomials of degree at most 1).
Comment: Precisely your troubles come from not distinguishing from $M_{1\times n}$ and  $M_{n\times 1}$. Check the example in [ http://juanmarqz.wordpress.com/2012/02/16/change-of-basis-and-change-of-components/ ] to see an example of how you must think.
Answer: These kind of questions literally plagued me for a long while. So, I feel your pain when you feel like you need some outside affirmation that your remarks are correct or not.
Before moving on however let's define some notation. We define the set $\mathbb{R}^n$ as the set of n-tuples of real numbers. That is elements of $\mathbb{R}^n$ look like $(a_1,a_2,\dots, a_n)$ where the $a_i$ are in the set $\mathbb{R}$. We define $M_{n\times 1}(\mathbb{R})$ as the set of $n\times 1$ matrices with elements from the set $\mathbb{R}$. Also let's set $M_{m\times n}(F)$ to be the set of $m\times n$ matrices with entries from the underlying set of the field $F$. Also the little operator $^t$ is just matrix transpose.
The first thing that will help you understand the problem you're having is that you must remember that a vector space is so much more than a set. A vector space is a an ordered triple $(V, F, \cdot)$ such that $V$ is an abelian group and $F$ is a field, and $\cdot$ (scalar product) is a map from the underlying sets of $V$ and $F$ to the underlying set of $V$. There are also compatibility axioms regarding the addition operations in $V$ and $F$, and compatibility axioms regarding scalar multiplication with multiplication in $F$. The things that we call 'vectors' are the elements of the underlying set of $V$.
The most detail that one usually delves into when specifying a vector space is naming the underlying set of $V$ and the underlying set of $F$. This is because often the group, field, and scalar operations are self-evident and it's a pain to typeset. For example when say that $\mathbb{R}$ is a vector space over itself, we get that the group operation and the field addition is the same: real addition, and we get that scalar multiplication coincides with the field multiplication: real multiplication.
Now you should note that we can begin to discuss bases and dimensions. These discussions
do not depend on the representation of the vectors of your vector space---only the vectors themselves. And as the natural numbers can be built up set-theoretically, we can
talk about a vector space being finite dimensional (it has a basis equinumerous with a finite ordinal).
If all this layering was not bad enough, when we deal with finite dimensional vector spaces we often opt to write the vectors of a vector space not in their set theoretic representation but rather as a coordinate vector. This is where my hell began, and I think it is where yours is too.
Let's assume we are dealing with a finite dimensional vector space $V$ over some field $F$.
Let's say the dimension is $n$. Now we note that $M_{n\times 1}(F)$ also forms a vector space over $F$ (with matrix addition and pointwise multiplication as scalar multiplication). A coordinate representation of $V$ is a linear isomorphism from $V$ to $M_{n\times 1}(F)$. And the coordinate vector of a vector is the image of the vector under this linear isomorphism. Here the problems start because there are soooooo very many different linear isomorphisms from $V$ to $M_{n\times 1}(F)$. In fact, for each ordered basis of $V$ and each ordered basis of $M_{n\times 1}(F)$ there is an isomorphism which maps the first onto the other in the same order.
Although this might seem like a deterrent, it is extremely nice computationally---especially when we set up some rules-of-thumb. Some important rules of thumb: there is a canonical way to represent $\mathbb{R}^n$ as a coordinate vector. The 'canonical' coordinate representation of $\mathbb{R}^n$ takes the vector $(1,0,0...,0)$ and carries it onto the vector $[1,0,0,...,0]^t$ and we call the latter the coordinate vector of the former. Another rule of thumb: we assume that the ordered basis that we choose for $M_{n\times 1}(F)$ to be the images of the ordered basis of $V$ is in order: $[1,0,\dots,0]^t, [0,1,\dots,0]^t,\dots,[0,\dots,0,1]^t$.
What do I mean by 'it is nice computationally'? As I'm sure you've worked with, setting up a coordinate representation allows us to codify a linear transformation as a matrix in $M_{m\times n}(F)$. That is when we have two vector spaces $V$ and $W$ and a linear transformation $T:V\rightarrow W$ AND we have chosen a coordinate representation of $V$ with $M_{n\times 1}(V)$ and a coordinate representation of $W$ with $M_{m\times 1}(V)$ we can codify $T$ as an element of $M_{m\times n}(F)$. And we can realize the application of $T$ to an element in $V$ as matrix multiplication between an element of $M_{m\times n}(F)$ with the coordinate representation of the vector. This way of explanation also reveals that a matrix is dependent on the two ordered bases chosen for $V$ and $W$.
Another rule of thumb: when $V=W$ we assume that the basis we are using to represent the elements of $V$ as coordinate vectors does not change (but there is no reason a priori to assume it; it's just convention).
Now let's directly tackle your questions. It appears your operator $[\cdot]_\mathcal{C}$ is the linear isomorphism I talked about above which assigns an element of $\mathbb{R}^n$ to its coordinate vector representation. I personally do not codify $n\times 1$ matrices as ordered $n$-tuples. In my theory, you do not have $v=[v]_\mathcal{C}$. You do get things which look similar. To typify what I mean let's take an example. Let's take $(1,0,\dots, 0)\in\mathbb{R}^n$. Then
$$[(1,0,\dots,0)]_\mathcal{C}=[1,0,\dots,0]^t$$
And as I said, in my theory, I do not codify $n\times 1$ matrices as $n$-tuples. So this function is not the identity. Everything else in your post, I agree with however.
I hope I have explained enough and that I have saved you from future turmoil.
ADDENDUM
Perhaps if I give an example you can see why the conventions we use are important.
Lets take the vector space $V=\mathbb{R}^2$. There are many bases for $V$. The standard basis is $\{(1,0), (0,1)\}$ (in this order). But let's work with another basis. Let's set $\mathcal{B}=\{(2,0), (1,1)\}$ (in this order). This basis was not chosen for any particular reason rather than its different from the standard basis. Now let's take the vector $v=(3,1)$ in $\mathbb{R}^2$. What is $v$'s coordinate vector? That is, what is $[(3,1)]_\mathcal{B}$? We have that $[\cdot]_\mathcal{B}$ is the linear operator from $\mathbb{R}^2$ to $M_{2\times 1}(\mathbb{R})$ which takes the vector $(2,0)$ to the vector $[1,0]^t$ and the vector $(1,1)$ to the vector $[0,1]^t$. Thus
$$[(3,1)]_\mathcal{B}=[(2,0)+(1,1)]_\mathcal{B}=[(2,0)]_\mathcal{B}+[(1,1)]_\mathcal{B}=[1,0]^t+[0,1]^t=[1,1]^t$$
Thus when we work in the basis $\mathcal{B}$ the coordinate vector of $(3,1)$ is $[1,1]^t$.
This all works because there is a convention that operator $[\cdot]_\mathcal{B}$ carries $\mathcal{B}$ to $\{[1,0]^t,[0,1]^t\}$. But what if $[\cdot]_\mathcal{B}$ carried $\mathcal{B}$ to a different basis? Lets take $\{[2,0]^t,[1,1]^t\}$ for an example. Then we get something which does not follow convention:
$$[(3,1)]_\mathcal{B}=[(2,0)+(1,1)]_\mathcal{B}=[(2,0)]_\mathcal{B}+[(1,1)]_\mathcal{B}=[2,0]^t+[1,1]^t=[3,1]^t$$
You see that we don't get something very different. This is the reason you might think that $v=[v]_\mathcal{C}$ in your example (especially if you implement $n\times 1$ matices as $n$-tuples) because the conventions force us to take a basis for $\mathbb{R}^n$ onto the standard basis for $M_{n\times 1}(\mathbb{R})$. And when we have chosen the standard basis for $\mathbb{R}^n$ the coordinate vector representations of vectors look almost exactly alike.
Comment: Thank you very much for your post (I appreciate your efforts). If I understand properly, since you haven't defined a *vector space* $\mathbb{R}^n$, $\mathbb{R}^n$ is just a *set* for you. In coincides with the $l^n$ that Lion talked about in previous comments (see his answer). For Lion it seems like $\mathbb{R}^n$ *is* a vector space (Euclidean space), however, and as far as I can remember I've always seen $\mathbb{R}^n$ being talked about as a *vector space* in Linear Algebra. In the end, you say that when we talk about the vector space $\mathbb{R}^n$, we really talk about $M_{n \times 1}$.
Comment: $\mathbb{R}^n$ can be *made into* a vector space. And when we talk about it we usually assume it has been. $M_{n\times 1}$ is a different set that can also be made into a vector space. But we usually use $M_{n\times 1}$ to represent the elements of a vector space once we have chosen a basis for that vector space.
Answer: I am confuse why you mentioned $v\neq[v]_{\mathcal{D}}$. Did you want to say the coordinates of $v$ are different between $\mathcal{C}$ and $\mathcal{D}$?
In fact, basis is only a frame to show a vector in $\mathbb{R}^n$. It is true that one vector probably have different coordinates (say, $v_1,v_2,\dots v_n$ you mentioned in $[v]_{\mathcal{C}}$). But the coordinate is only a description of the vector. I mean, the vector's length, angle etc. is independent of coordinate, say basis. When we mention a operator from $\mathbb{R}^n$ to $\mathbb{R}^n$, we care its boundedness, continuity, duality .etc (See the analysis in matrix analysis or functional analysis). Obviously, as you care, the form of both operator and vector is depend on the basis. But the properties of operator which we care about is independent of the basis. What is more, we can also change the form in different basis by using transition matrix (See references about algebra).
For example, consider the following operator from $\mathbb{R}^2$ to $\mathbb{R}^2$:
\begin{equation}
\left(
\begin{array}{cc}
\cos\theta&-\sin\theta\\
\sin\theta&\cos\theta
\end{array}
\right)
\end{equation}
This operator transform vector $a=(1,0)^\top$ to $b=(\cos\theta,\sin\theta)^\top$ in $\mathcal{C}$ which you mentioned. Indeed, in another basis, such as $\{d_1=(0,1)^\top,d_2=(-1,0)^\top\}$, both $a$ and $b$ have different form. But no matter how you choose the basis, the meaning of the operator is to clockwise rotate the vector in $\theta$ degree. Thus the form and properties of the operator is invariable.
In summary, although the form of operator probably depend on the basis you choose, but the properties which we care about is independent of the basis (In geometry, it is so called geometric invariants).
This is what I think, please check it if I have something wrong.
Comment: Let me illustrate what I mean by $v \neq [v]_{\mathcal{D}}$. Let $v$ be a vector in $\mathbb{R}^2$, say $v := (1,2)$. On one hand, since $v = 1 e_1 + 2 e_2$, we have that $[v]_{\mathcal{C}} = (1,2)$ and in this case $v = [v]_{\mathcal{C}}$. However, if we take $\mathcal{D} := \{d_1 := (0,1), d_2 := (-1,0)\}$, then $v = 2 d_1 + (-1) d_2$ and $[v]_{\mathcal{D}} = (2,-1)$. Hence $[v]_{\mathcal{D}}  \neq v$ because $v = (1,2)$ and $(2,-1) \neq (1,2)$. I understand that many properties we investigate are basis-independent, e.g. the characteristic polynomial ($\det(P^{-1}AP) = \det(A)$).
Comment: The thing is, I distinguish between the vector $v \in \mathbb{R}^2$ and its basis representation, for a given basis. The basis representation is also a vector in $\mathbb{R}^2$, but does not coincide with the vector itself, in general, which is why I wrote that the case of $\mathbb{R}^n$ (in the general case) is, in a way, singular.
Comment: If you want to represent a vector in algebraic form, you must have a basis first. In your example, as you mentioned $(2,-1)\neq(1,2)$, $(2,-1)$ is a coordinate in basis $d_i$ but $(1,2)$ is a coordinate in basis $e_i$. These coordinate obviously different since they are in two different frame, say basis. The relationship between two representations is the transition matrix. In your example, the transition matrix is: $T=(0,1;-1,0)$ (I use the scheme in MATLAB). You can check that $T[v]_\mathcal{C}^\top=[v]_\mathcal{D}^\top$. Hope this is helpful for you.
Comment: I understand that if a vector is in some vector space different from $\mathbb{R}^n$, then you must have a basis first because otherwise you could not trace back the vector. But, my main concern is : if we *are* working in $\mathbb{R}^n$, say $\mathbb{R}^2$, then writing $v := (1,2)$ says that the vector is  $(1,2) \in \mathbb{R}^2$. This is *not* a basis representation, it is the vector in its vector space, independent of any basis. But, it just so happens that it is in fact the basis representation when the basis is $\mathcal{C}$. Does this make any sense or am I still wrong ?
Comment: I think you are confusing $\mathbb{R}^n$ with $l^n$. If we want to represent a vector in Euclidian space, the two representations $v:=e_1+2e_2$ and $v:=(1,2)$ is equivalent by given the basis $e_i$. The later one is just an abbreviation for the former one. So I think you said 'it is the vector in its vector space, independent of any basis' is wrong. The basis must be declared but we default they are $e_i$ in most time. If you want to investigate an n-tuple only which is independent of Euclidian space, I think that is $l^n$ space (see functional analysis).
Comment: Indeed, $\mathbb{R}^n$ and $l^n$ have a lot of relationships. But I think it is invalid by saying a two-tuple $(1,2)$ which is independent of Euclidian space is in $\mathbb{R}^2$. Obviously, in this case, it is in $l^2$.
Comment: Alright. When I talk about $v := (1,2)$ independent of any basis I talk about the element of the set $\mathbb{R}^2$ which is endowed with a vector space structure, but I shall talk about an element of $l^2$ instead. Thanks for your insights and for your time :).
Comment: I'm very glad to can help you. :)
Answer: well, I think the answers may become clearer when u see that the basis vectors $d_{1},d_{2},d_{3}$ when expressed in the basis D would be of the form $[1. 0 ..0]^{T},[0.1. 0 ..0]^{T},[0. 0 0 0.. 1]^{T}$. So in the basis D the vector can again be expressed as $v=v_{1}d_{1}+v_{2}d_{2}+v_{3}d_{3}+...v_{n}d_{n}$ and each vector $d_{i}$ will have the form that you had mentioned earlier for $e_{i}$. Of course the value of individual components $v_{1}, v_{2}$ will be different in each basis.The fact that the same vector is represented as the sum of different components $v_{1}, v_{2}.. v_{n}$ multiplied with vectors $d_{i}$ which seemingly  have the same representation as $e_{i}$ points to the fact that a basis vector such as $[1. 0 ..0]^{T}$ doesn't independently suggest on its own.It represent the first vector in our set of basis vectors,but says nothing more about the basis vectors themselves.
The elements of a vector space have an existence of their own and their identity is invariant regardless of the basis vector used to represent. This manifests in a variety of ways. The scalar invariants of a matrix can be perceived as the result of the independent existence of operators regardless of the choice of basis


Vshadow.exe error in Cygwin, but only over ssh with pubkey auth

Question: I'd like to create a volume shadow copy (vshadow 2.2) from within Cygwin over ssh:
$ ./vshadow.exe -p -nw C:
(...)
- Setting the VSS context to: 0x00000019
Creating shadow set {a5e0883e-9485-4243-8276-1ac7c569ab6a} ...
- Adding volume \\?\Volume{218a908d-1e3f-11df-a215-806e6f6e6963}\ [C:\] to the shadow set...
Creating the shadow (DoSnapshotSet) ...

ERROR: COM call "m_pVssObject->DoSnapshotSet(&pAsync)" failed.
- Returned HRESULT = 0x80070005
- Error text: Access is denied.

I guess that's because the local Windows user cyg_server that Cygwin runs as does not have permission of some kind.
Things I've tried:

the advanced options under the security tab when I right-click C: in My Computer, but I don't see anything that seems to be relevant
It says to rerun with /tracing.  I don't see much that's helpful around the failure point
I went to the directory in Windows where I'm creating the exposed mount point, and gave cyg_server Full Control.  No change.
created the VSSAccessControl key as described here.  No change.
made cyg_server a member of Domain Admins.  No change.
vshadow without the -nw switch, and got this instead:
$ ./vshadow.exe -p C:
(...)

Setting the VSS context to: 0x00000009
(Gathering writer metadata...)
(Waiting for the asynchronous operation to finish...)
Error during the last asynchronous operation.
Returned HRESULT = 0x80042318
Error text: VSS_E_WRITER_INFRASTRUCTURE

How can I make a snapshot over ssh with public key auth?
Update: I found this thread from 2007 mentioning that you can't if you use public key auth.  I have verified that if I rename my id_rsa file and use a password login, it works (with or without the -nw switch.)  But I need to use pubkey auth in order to make a backup script.  The author doesn't mention why it was that way, but I guess it hasn't been fixed in the last six years...is there a workaround?
Answer: Are you able to do a normal copy/connection using your public key?
You might also want to check the thread on the backupcentral site where one use posted what he'd set up using Windows 2003 as well as the scripts he used.
Using cygwin, public key and rsync to backup windows 2003
The crux of it is using the at command to run something as NT AUTHORITY\SYSTEM because logging in with a public key instead of a password for some reason gets you running as a different user under Cygwin.  Quote:
# Launches passed input via 'at' to get around $USERNAME=SYSTEM
# problem under ssh login where the shell lacks permsisions to run
# commmands like vshadow or dosdev
# from a script by Jeffrey J. Kosowsky
function at_launch ()
{
local h m s wait1 command
if [ $3 != "" ] ; then
command="${1} ${2} >> ${3}"
else
command="${1} ${2}"
fi

set -- $(date +"%H %M %S")
h=$((10#$1)) #Note explicitly use base 10 so that 08 and 09 not interpreted as bad octal
m=$((10#$2 +1)) #Advance minutes by 1
s=$((10#$3))
wait1=$((60 - $s))
[ $s -gt 55 ] && let "m += 1" "wait1 += 60" # Make sure >5 seconds left
[ $m -ge 60 ] && let "m %= 60" "h += 1" #Overflow minutes
let "h %= 24"
at $h:$m $(cygpath -w $(which bash.exe)) -c "$command"
# > /dev/null

echo Running '$command' at $h:$m
return $wait1
}

Comment: Yes, that's where I pasted the terminal output from.  I.e. I can log in fine with the public key, but once logged in, if I run vshadow I get a different result than if I do it from a Cygwin terminal on the Windows box locally, or if I log in with a password instead of a public key.  Only the "public key via ssh then run vshadow" fails, the other two ways succeed.  Yeah, that's what I figured, that I'd need some kind of Task Scheduler workaround...


Issues in setting up Authentication Flows project

Question: I tried different ways to import "https://github.com/OhadR/Authentication-Flows" project into eclipse, but none of the import type is working.
It will be of great help if you can guide me with the same.
Thanks,
Harika
Comment: Are you trying to import .zip file?? If yes then unzip your project and then try to import your project.
Comment: @Anshul Tyagi : I did an unzip and tried to import. I was able to import using "import" -> "import" -> Maven -> Existing Maven Project in workspace. Though the projects got imported, I feel its not the right way because I am not able to build them successfully.
Comment: please see my answer below.... let me know if it helps... note that you import the pom.xml.
Answer: "Authentication-Flows" is a maven project. After you clone it, you will find pom.xml in the root directory (Authentication-Flows/client).
If you want to import it to Eclipse, click File -> Import... -> Maven -> Existing Maven Project.
HTH
Comment: I selected sub project and imported, thats the reason I was not able to build successfully. Now I am able to build but unable to deploy to tomcat. From readme file that is in the project - it says war files can be deployed to tomcat. So, I should be able directly deploy to tomact from eclipse too right? Am I missing something?
Comment: no, you are not missing a thing. you should be able to deploy the war to tomcat. what is the problem that you see?
Comment: On right clicking on authentication-flows project -> Run as -> Not able to see Run on Server option. Also, I tried to right click on the tomcat server directly and trying to add "Add and Remove" throws an error "There are no resources that can be added or removed from the server.
Comment: are you sure that this is related only to auth-flows? if you create another WAR and try to deploy it to tomcat - it works?
Comment: I did not create a war file. I am trying to deploy to tomcat directly from eclipse. Both are same right? Either way should work. Yes, my other projects are working.
Comment: read here: http://stackoverflow.com/questions/4166882/run-on-server-option-not-appearing-in-eclipse for me, combination of the first 2 answers helped.


Grep to find lines starting at pattern A until pattern B is matched

Question: I have a log that contains bits like this:
[2012-04-16 15:16:43,827: DEBUG/PoolWorker-2] {'feed': {}, 'bozo': 1, 'bozo_exception': URLError(error(110, 'Connection timed out'),), 'entries': []}
[2012-04-16 15:16:43,827: ERROR/PoolWorker-2] get_entries
Traceback (most recent call last):
  File "/opt/myapp/app.py", line 491, in get_entries
    logging.getLogger(__name__).debug("Title: %s" % doc.title)
  File "build/bdist.linux-x86_64/egg/feedparser.py", line 423, in __getattr__
    raise AttributeError, "object has no attribute '%s'" % key
AttributeError: object has no attribute 'title'
[2012-04-16 15:16:43,828: INFO/MainProcess] Task myapp.do_task[4fe968ff-e069-4cfe-9a81-aece0d97c289] succeeded in 21.0481028557s: None

I would like to extract from it sections as follows:

When a line contains "ERROR" or "WARN" start filtering (and include this line)
When the next line starting with "[" is found, stop filtering (and don't include this line).

I'm pretty sure this is too much for Grep, so how to do it?
(Ok, instead of being lazy, I've figured it out - will post my solution.)
Answer: This worked for me - not exactly as described above, but close enough:
awk '/ERROR|WARN/,/DEBUG|INFO/ { if ($0 !~ /(DEBUG|INFO)/) { print } }' < logfile

Very convenient that awk supports this: /startpattern/,/stoppattern/ { }. Unfortunately if the stop pattern is matched on the same line as the start pattern, it prints out that line only, hence the need for a different stop pattern.
Answer: Try something like this:
cat importantstuff.log | grep 'File .*, line .*, in .*' -B 1 -A 2

Doesn't exactly answer the question, but I think it accomplishes the task.
The -A and -B flags for grep control lines of context after or before your match.
This works because grep groups adjacent matches, so you end up with nicely separated tracebacks:
Traceback (most recent call last):
  File "sfquest.py", line 9, in b
    c()
  File "sfquest.py", line 15, in c
    d()
  File "sfquest.py", line 20, in d
    raise Exception('important information')
Exception: important information
--
Traceback (most recent call last):
  File "sfquest.py", line 9, in b
    c()
  File "sfquest.py", line 15, in c
    d()
  File "sfquest.py", line 20, in d
    raise Exception('important information')
Exception: important information
--
Traceback (most recent call last):
  File "sfquest.py", line 9, in b
    c()
  File "sfquest.py", line 15, in c
    d()
  File "sfquest.py", line 20, in d
    raise Exception('important information')
Exception: important information

Here's the example code I used to generate the traceback example:
import traceback

def a():
    b()

def b():
    for i in range(10):
        try:
            c()
        except Exception, e:
            print 'bad stuff'
            print traceback.format_exc(e)

def c():
    d()

def d():
    for i in range(10):
        print 'random junk'
    raise Exception('important information')

a()


CMake gives undefined reference even if use `link_libraries` command

Question: I'm trying to link GLFW using git submodule. Here is my CMakeLists.txt:
cmake_minimum_required(VERSION 3.0.0)
project(guitest VERSION 0.1.0 LANGUAGES C CXX)

add_executable(guitest main.cpp)

add_subdirectory(glfw)
include_directories(glfw/include)
link_directories(glfw/src)
link_libraries(glfw)

I get no errors in CMake, but when I try to build my project I get
[build] C:/Users/Konstantin/Documents/sasha/guitest/main.cpp:7: undefined reference to `glfwInit'

Here is my code
#include <iostream>
#include <GLFW/glfw3.h>

int main(int, char**){
    GLFWwindow *window;
    if(!glfwInit()){
        std::cout << "Init failure!"<<std::endl;
        exit(EXIT_FAILURE);
    }
}

I'm using Visual Studio Code and GCC 6.3.0 MinGW compiler kit.
Comment: Please create a verbose makefile, and take a look at the commands being executed to see all the flags and options.
Comment: Also note that `include_directories`, `link_directories` and `link_libraries` are all discouraged, in favor of [`target_include_directories`](https://cmake.org/cmake/help/latest/command/target_include_directories.html#command:target_include_directories) and [`target_link_libraries`](https://cmake.org/cmake/help/latest/command/target_link_libraries.html).
Answer: The command link_libraries affects only on targets which are created after. Since your call to add_executable precedes link_libraries, your executable is not linked.
Correct (but not the best):
add_subdirectory(glfw)
link_libraries(glfw)
add_executable(guitest main.cpp)

It is preferred to use target_link_libraries instead of link_libraries.
add_subdirectory(glfw)
add_executable(guitest main.cpp)
target_link_libraries(guitest PRIVATE glfw)

In both cases include_directories call could be omitted, since linkage with glfw target also ships your executable with GLFW include directories.


How to change error-message displayed @ failed form-element validation to be different than the element's '#title" text?

Question: I'm writing a custom form module.
Using Drupal7's FormAPI, I create a checkbox, the label/text diplayed next to it is set as described here
<code>http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#checkbox
</code>
with the #title property,
<code>    $form['test'] = array(
    '#type'     => 'checkbox',
    '#title'    => t('This is the text that gets displayed next to the checkbox'),
    '#required' => TRUE,
    );
</code>
which then displays in the browser,
<code>[ ] This is the text that gets displayed next to the checkbox
</code>
Ih there's an error in submission that involves that checkbox, e.g. in the example above being required but not being checked, an error box is shown across the top content-area that says
<code>"X  The This is the text that gets displayed next to the checkbox field is required"
</code>
I want to change that displayed error message to something other than the label/text.  For example, on error,
<code>"X  Selecting the displayed checkbox is required."
</code>
or
<code>"X  You forgot to check the required checkbox.  Please try again."
</code>
How do I set the error-message text to be different that the assigned label/text?
Answer: Using a basic form in a custom module:
<code>    function customform_demo($form, $form_state) {
    $form['test'] = array(
        '#type' => 'checkbox',
        '#title'    => t('This is the text that gets displayed next to the checkbox'),
        '#required' => TRUE,
    );

    $form['test_submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );

    return $form;

}
</code>
You can set a custom error message in the form validation function. Here is a basic example with some comments:
<code>    function customform_demo_validate($form, &$form_state) {

    // Test for existing form errors
    if (form_get_errors()) {

        // Save errors
        $form_errors = form_get_errors();
        $drupal_errors = drupal_get_messages('error');

        // Clear form errors
        form_clear_error();

        foreach($drupal_errors['error'] as $key => $error) {
            if (in_array($error, $form_errors)) {
                // Unset form errors
                unset($drupal_errors['error'][$key]);
            }
        }

        // Rebuild drupal errors
        foreach($drupal_errors['error'] as $key => $message) {
            drupal_set_message($message, 'error');
        }

        // Validate form field and set error message
        if ( $form_state['values']['test'] === 0 ) {
            form_set_error('test', t('You forgot to check the required checkbox. Please try again.'));
        }

                // Add more validation tests and error messages

    }
}
</code>
Comment: Perfect!! I was looking in the completely wrong place for this solution!  THanks


How to integrate properly Kerberos based SSO in Drupal 7

Question: I'm trying to install Drupal with Single Sign On over Active Directory.
My customer does not have any SSO suite like CAS, and their general recommendation are to use Kerberos (or NTLM as a second choice). I am clearly agreed with that.
Each time I had to integrate SSO with Active Directory using Kerberos, I use "native" product facilities, or apache mod_auth_kerb with headers rewrite.
Does someone implemented such a working module ? Everything I read about that is around "on developpement modules" on "snapshots realeases". We are currently using a ldap module that allow authentication over LDAP, and it seems that it provide SSO features, but I don't have any feedback on it.
So : Should I implement SSO over Kerberos using Apache mod_auth_kerb, or is there a real functional module that would encapsulate all those tedious configuration and dialog ?
What is the best pratice, at this moment ?
Could you provide me "real" (anonymised) examples ?
As soon as I would installed it and put in in production (around the end of december), i would give you my feedback.
Thanks in advance
Answer: After some researches and tests, I finally made a choice.
In most cases, I'd prefer use native or add on features. This provide better integreation with the product (here Drupal) and it's more a Logic solution than a technical one (which is quite easier).
The LDAP_SSO module allow this kind of configuration.
Nevertheless, I was not able to configure it this time, mainly due to poor debug facilities. Even with watchdog, I am not able to know what is the matter. Moreover, my customer have clear procedure to install and use Kerberos, with Apache HTTP and mod_auth_kerb.
Hopefully, LDAP_SSO module allow this too.
After some tries, I will get back here to share with you more advanced comments, but at this time, we clearly go to apache+mod_auth_kerb+fowarded REMOTE_USER.
Edit a few monthes later :
That works great with Mod auth kerb on apache server and ldap module v1.0-beta12 on drupal.
Even if v2.0 is available, we were facing some issues because some fields were empty and this were causing troubleshootings.
But nevermind, we are able to authenticate et identify users, collect groups and map them to  drupal profiles etc.
Comment: I am trying to configure ldap sso modul for drupal 8 currently. It looks like users are authenticated in apache logs but drupal doesn't seem to think the same.
I know it's long ago since you have been at that topic but do you have any useful guides / hints maybe?
Comment: No idea at all ... sorry ... you should post another question to let community help you ... it's really too old for me.
Comment: Did that and fixed it https://serverfault.com/questions/963255/kerberos-authentication-not-working-with-apache-and-php-fpm


Migration from Flex 3 to Flex 4 Errors

Question: Hello I migrated my Flex 3 project to FLex 4: I am getting these errors:
Anyone has an idea about fixing this in Flex 4.
<code>1061: Call to a possibly undefined method activate through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method activate through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method activate through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method activate through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method addFocusManager through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method addFocusManager through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method addFocusManager through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method addFocusManager through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method removeFocusManager through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method removeFocusManager through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method removeFocusManager through a reference with static type mx.managers:ISystemManager.
1061: Call to a possibly undefined method removeFocusManager through a reference with static type mx.managers:ISystemManager.
1144: Interface method addPopUp in namespace mx.managers:IPopUpManager is implemented with an incompatible signature in class mx.managers:PopUpManagerImpl.
1144: Interface method addPopUp in namespace mx.managers:IPopUpManager is implemented with an incompatible signature in class mx.managers:PopUpManagerImpl.
1144: Interface method addPopUp in namespace mx.managers:IPopUpManager is implemented with an incompatible signature in class mx.managers:PopUpManagerImpl.
1144: Interface method addPopUp in namespace mx.managers:IPopUpManager is implemented with an incompatible signature in class mx.managers:PopUpManagerImpl.
1144: Interface method createPopUp in namespace mx.managers:IPopUpManager is implemented with an incompatible signature in class mx.managers:PopUpManagerImpl.
1144: Interface method createPopUp in namespace mx.managers:IPopUpManager is implemented with an incompatible signature in class mx.managers:PopUpManagerImpl.
1144: Interface method createPopUp in namespace mx.managers:IPopUpManager is implemented with an incompatible signature in class mx.managers:PopUpManagerImpl.
1144: Interface method createPopUp in namespace mx.managers:IPopUpManager is implemented with an incompatible signature in class mx.managers:PopUpManagerImpl.
</code>
Thanks for your help.
Comment: @Constantiner I hate when people downvote w/o saying why. ;)
Comment: You'd better list lines which highlighted with compiler errors.
Comment: @Constantiner Usually errors like this have no line numbers and relate to a version mismatch between a library and the main project.  ( See my answer ).  If you downvoted b/c of the lack of detail, I suggest you remove your downvote because I honestly believe the original poster had no more additional detail to provide.
Comment: @www.Flextras.com No, I did't downvoted and I supposed these errors hadn't particular lines but I thought it will be better if topic starter pointed that fact :)
Answer: Errors like this are usually due to version mismatch issues.  So, make sure that all your external libraries are compiled with the same version of the Flex SDK that your main project is.
If you are using frameworks, or other libraries you found on the web you may have to recompile them yourself if the source code is available.
Comment: Hello,

In fact in the flex 3 project there is a class called PopUpManagerImpl.as. It is from this file that am getting all these errors.

If possible to put some light on this.
Thanks
Comment: @FlexyBoz I'm not sure what else to tel you other than what I already said.  This problem usually doesn't relate to a specific class throwing errors; it usually relates to a library being compiled in a different version of the Flex SDK than the main project.  There isn't [as far as I know] code you can change to make this go away.  You need to recompile your libraries to use the same version of the Flex SDK.

Migration from Flex 3 to Flex 4 Errors


Remark in Hatcher's Algebraic Topology on Mapping Cylinders

Question: On p2 of Algebraic Topology, Hatcher defines mapping cylinders as follows:

For a map $f: X \to\ Y$, the mapping cylinder $M_f$ is the quotient space of the disjoint union $(X \times I) \cup Y$ obtained by identifying each $(x,1) \in X \times I$ with $f(x) \in Y$.

Then, he makes the following remark:

Not all deformation retractions arise in this simple way from mapping cylinders. For example, the thick $\bf{X}$ deformation retracts to the thin $X$, which in turn deformation retracts to the point of intersection of its two crossbars. The net result is a deformation retraction of $\bf{X}$ onto a point, during which certain pairs of points follow paths that merge before reaching their final destination.

I'm unclear as to why the deformation retraction described in the paragraph above does not arise from a mapping cylinder. Hatcher seems to hint that the merging of paths is the reason why, but I do not see how merging of paths is inconsistent with the definition of a mapping cylinder.
Any thoughts?
Answer: I am not entirely sure how to make it perfectly formal, but here are my thoughts.
In the letter $\mathbf X$ example, the space $X$ that would serve in our definition of the mapping cylinder is the outline of the thick $\mathbf X$, which is homeomorphic to $S^1$. The space $Y = \{P\}$ consisting of the point $P$ at the center of the $\mathbf X$ serves as the codomain in our mapping cylinder. Thus our mapping cylinder $M_f$ is the quotient of $(S^1\times [0,1])\sqcup Y$ obtained by identifying each point of $S^1\times\{1\}$ with $P$, and it is easy enough to see that the mapping cylinder is thus homeomorphic to a closed disk $D^2$.
Now I think the point of what Hatcher is getting at is that the overall deformation retraction $\{\tilde f_t\}$ consisting of the composition of first turning $\mathbf X$ to the thin $\mathsf X$, and then the thin $\mathsf X$ to the point $P$ is more complicated/has more information than the mapping cylinder of the map $f$ that sends all of $\mathbf X$ to $P$. If for each $t\in[0,1]$, you imagine the map $f_t\colon X\to (M_f)_t$ to be the map that sends $X$ to the horizontal $t$-slice $(M_f)_t$ of the mapping cylinder $M_f$, then together the family $\{f_t\}$ is not the same as $\{\tilde f_t\}$. Further, I think that you can make "more complicated/has more information" more precise by noting that for all $0\le t < 1$, the map $f_t$ is a homeomorphism, but the same is not true for the family $\{\tilde f_t\}$.


Sequelize: Many-To-Many relation between MariaDB and Postgres

Question: Little Background Story
Here is my scenario, I have a database named Location in my MariaDB, and I have a User database in my Postgres. I want to chain two of them in my Postgres DB. So I have two tables users and userLocations. Oh yeah, a nice thing to note is that I only have access to read (SELECT and CREATE VIEW) from LocationDB, and connecting to UserDB as root. Yes I have successfully authenticate() both of them. I even able to receive data from LocationDB however the only problem right now is creating that relation between User and Location. Error logs available on the bottom.
Here is my models:
models/user.js
// ... Connection to UserDB (uses Postgres)
const UserDB = require('../datasources/user-db')

const User = UserDB.define('user', {
  id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
  name: { type: Sequelize.STRING, allowNull: false }
})
module.exports = User

models/location.js
// Connection to LocationDB (uses MariaDB)
const LocationDB = require('../datasources/location-db')

const Location = LocationDB.define('ms_location', {
  id_Location: { type: Sequelize.INTEGER, primaryKey: true },
  name_Location: { type: Sequelize.STRING, allowNull: false }
}, { timestamps: false, freezeTableName: true })
module.exports = Location

models/user-location.js
// ... Connection to UserDB (uses Postgres)
const UserDB = require('../datasources/user-db')

const UserLocation = UserDB.define('userLocation', {
  id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }
})
module.exports = UserLocation

app.js
const Location = require('./models/location')
const User     = require('./models/user')
const UserLocation = require('./models/user-location')

User.belongsToMany(Location, { through: UserLocation })

This is a minified version of the case, if you need more information please do ask as I am still new to sequelize as well
The error log: (sorry I don't have any idea to beautify it)
{ SequelizeDatabaseError: relation "ms_location" does not exist
    at Query.formatError (<path-to-project>/node_modules/.registry.npmjs.org/sequelize/5.8.6/node_modules/sequelize/lib/dialects/postgres/query.js:354:16)
    at query.catch.err (<path-to-project>/node_modules/.registry.npmjs.org/sequelize/5.8.6/node_modules/sequelize/lib/dialects/postgres/query.js:71:18)
    at tryCatcher (<path-to-project>/node_modules/.registry.npmjs.org/bluebird/3.5.5/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (<path-to-project>/node_modules/.registry.npmjs.org/bluebird/3.5.5/node_modules/bluebird/js/release/promise.js:517:31)
    at Promise._settlePromise (<path-to-project>/node_modules/.registry.npmjs.org/bluebird/3.5.5/node_modules/bluebird/js/release/promise.js:574:18)
    at Promise._settlePromise0 (<path-to-project>/node_modules/.registry.npmjs.org/bluebird/3.5.5/node_modules/bluebird/js/release/promise.js:619:10)
    at Promise._settlePromises (<path-to-project>/node_modules/.registry.npmjs.org/bluebird/3.5.5/node_modules/bluebird/js/release/promise.js:695:18)
    at _drainQueueStep (<path-to-project>/node_modules/.registry.npmjs.org/bluebird/3.5.5/node_modules/bluebird/js/release/async.js:138:12)
    at _drainQueue (<path-to-project>/node_modules/.registry.npmjs.org/bluebird/3.5.5/node_modules/bluebird/js/release/async.js:131:9)
    at Async._drainQueues (<path-to-project>/node_modules/.registry.npmjs.org/bluebird/3.5.5/node_modules/bluebird/js/release/async.js:147:5)
    at Immediate.Async.drainQueues [as _onImmediate] (<path-to-project>/node_modules/.registry.npmjs.org/bluebird/3.5.5/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)
  name: 'SequelizeDatabaseError',
  parent:
   { error: relation "ms_location" does not exist
       at Connection.parseE (<path-to-project>/node_modules/.registry.npmjs.org/pg/7.11.0/node_modules/pg/lib/connection.js:602:11)
       at Connection.parseMessage (<path-to-project>/node_modules/.registry.npmjs.org/pg/7.11.0/node_modules/pg/lib/connection.js:399:19)
       at Socket.<anonymous> (<path-to-project>/node_modules/.registry.npmjs.org/pg/7.11.0/node_modules/pg/lib/connection.js:121:22)
       at Socket.emit (events.js:189:13)
       at addChunk (_stream_readable.js:284:12)
       at readableAddChunk (_stream_readable.js:265:11)
       at Socket.Readable.push (_stream_readable.js:220:10)
       at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
     name: 'error',
     length: 107,
     severity: 'ERROR',
     code: '42P01',
     detail: undefined,
     hint: undefined,
     position: undefined,
     internalPosition: undefined,
     internalQuery: undefined,
     where: undefined,
     schema: undefined,
     table: undefined,
     column: undefined,
     dataType: undefined,
     constraint: undefined,
     file: 'namespace.c',
     line: '426',
     routine: 'RangeVarGetRelidExtended',
     sql:
      'CREATE TABLE IF NOT EXISTS "userLocations" ("id"  SERIAL , "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "userId" INTEGER REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "msLocationIdLocation" INTEGER REFERENCES "ms_location" ("id_Location") ON DELETE CASCADE ON UPDATE CASCADE, UNIQUE ("userId", "msLocationIdLocation"), PRIMARY KEY ("id"));' },
  original:
   { error: relation "ms_location" does not exist
       at Connection.parseE (<path-to-project>/node_modules/.registry.npmjs.org/pg/7.11.0/node_modules/pg/lib/connection.js:602:11)
       at Connection.parseMessage (<path-to-project>/node_modules/.registry.npmjs.org/pg/7.11.0/node_modules/pg/lib/connection.js:399:19)
       at Socket.<anonymous> (<path-to-project>/node_modules/.registry.npmjs.org/pg/7.11.0/node_modules/pg/lib/connection.js:121:22)
       at Socket.emit (events.js:189:13)
       at addChunk (_stream_readable.js:284:12)
       at readableAddChunk (_stream_readable.js:265:11)
       at Socket.Readable.push (_stream_readable.js:220:10)
       at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
     name: 'error',
     length: 107,
     severity: 'ERROR',
     code: '42P01',
     detail: undefined,
     hint: undefined,
     position: undefined,
     internalPosition: undefined,
     internalQuery: undefined,
     where: undefined,
     schema: undefined,
     table: undefined,
     column: undefined,
     dataType: undefined,
     constraint: undefined,
     file: 'namespace.c',
     line: '426',
     routine: 'RangeVarGetRelidExtended',
     sql:
      'CREATE TABLE IF NOT EXISTS "userLocations" ("id"  SERIAL , "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "userId" INTEGER REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "msLocationIdLocation" INTEGER REFERENCES "ms_location" ("id_Location") ON DELETE CASCADE ON UPDATE CASCADE, UNIQUE ("userId", "msLocationIdLocation"), PRIMARY KEY ("id"));' },
  sql:
   'CREATE TABLE IF NOT EXISTS "userLocations" ("id"  SERIAL , "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "userId" INTEGER REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "msLocationIdLocation" INTEGER REFERENCES "ms_location" ("id_Location") ON DELETE CASCADE ON UPDATE CASCADE, UNIQUE ("userId", "msLocationIdLocation"), PRIMARY KEY ("id"));' }

Answer: You've told Sequelize that you have a table called user and a table called msLocation and that the two are related through another table called userLocation. (Or is it userLocations? Your code and error message are inconsistent.)
It looks like Sequelize is trying to create the userLocations table UserDB but it's failing because as part of the table definition, it's trying to create a foreign key reference to ms_location:
"msLocationIdLocation" INTEGER REFERENCES "ms_location" ("id_Location")
ON DELETE CASCADE ON UPDATE CASCADE

which fails because ms_location is not in the UserDB but rather in the other database.
I don't know if Sequelize can actually handle tables spanning multiple databases servers, but I doubt it. Creating a query that spans two tables in the same database is easy, Sequelize can just create a join. It's a totally different story if the tables are on two different servers; now Sequelize would have to run two different queries and do all the join logic in memory. That's a pretty big lift.
Some databases have a way to create a table in one database that replicates or forwards to a table in another database. If PostgreSQL supports that, you could try using that to replicate or shadow the MariaDB table, which would enable Sequelize to see all the tables as being part of UserDB.
Comment: Ah I see! I thought it would just left the `userLocations` table with the location's `id_Location` cause that's the only thing I wanted to do. Also, I think the error message isn't inconsistent, because I think it's one of Sequelize feature to add `s` to all table names. I have `user` table and it becomes `users` in the database.


Removing background with Open CV is not precise and some of pictures could not be done properly

Question: I am trying to remove background from images using OpenCV. Majority of operations are succesfull but some pictures cant be processed properly. Any help or suggestion will be appreciated.
my code:
<code>import os
import numpy
import cv2
import os
import glob
img_dir = r"C:\Users\kaan\Documents\Plant_Seedlings_Classification-master\Plant_Seedlings_Classification-master\data\osmancik"
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
data = []
for f1 in files:
    img = cv2.imread(f1)
    img = cv2.resize(img, (640, 480))
    data.append(img)

data2 = []
arr = numpy.array(data2)

for pict in data:

    gray_img = cv2.cvtColor(pict, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    img_contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
    img_contours = sorted(img_contours, key=cv2.contourArea)

    for i in img_contours:
        if cv2.contourArea(i) > 100:
             break
    mask = np.zeros(img.shape[:2], np.uint8)
    cv2.drawContours(mask, [i],-1, 255, -1)
    new_img = cv2.bitwise_and(pict, pict, mask=mask)
    name=randomString()+".jpg"
    path = r"C:\Users\kaan\Documents\Plant_Seedlings_Classification-master\Plant_Seedlings_Classification-master\segmentated\osmancik2"
    cv2.imwrite(os.path.join(path , name), new_img)
</code>
Image:

This is a good example:

This is a bad example:
Comment: Convert to saturation or to hue and threshold.
Comment: You rely on luminance, which is poor information compared to color. Try to threshold on saturation or hue.
Comment: I am new in image processing so I need some guide how to threshold on saturation or hue.
Answer: Use HSV filtering.

Change image colors from BGR to HSV (Hue Saturation Value).
Filter a certain range of saturation and hue.

Refer to this page for code https://pythonprogramming.net/color-filter-python-opencv-tutorial/


solve linear system Ax=b, when A is m.n matrix where m<n.

Question: Let $A=[a_{ij}]_{m\times n}$ where $m<n$ and $a_{ij}$ are some functions of parameter $t$. I would like to solve $Ax=b$. For example $A=[a_{ij}]_{2\times 10}$ and it cannot be simplified more. Now I want to determine $x=Gb$ where $G$ is a suitable matrix that give the solution. In general, finding $G$ as a generalized inverse of matrix $A$ such that $AGA=A$ is not easy.
Is there any idea to determine all the solutions of this system.
Thanks.
Answer: $\renewcommand{\vec}[1]{\mathbf{#1}}$Let the columns of $N$ be a basis for the nullspace of $A$, so that $AN=0$. Then the solution set of $A\vec{x}=\vec{b}$ is given by $\vec{x}=\vec{x}_0+N\vec{c}$, where $\vec{x}_0$ is any vector that satisfies $A\vec{x}_0=\vec{b}$ and $\vec{c}$ is any appropriately sized vector such that the matrix product is defined.
$N$ can be computed a number of ways. The easiest (but not necessarily most numerically efficient) method to compute this matrix on a computer is using an SVD decomposition.
Answer: If $A$ has rank $< m$, there may be no solutions, depending on $b$.
Assuming $A$ has rank $m$, $A A^T$ is invertible and you can take
$G = A^T (A A^T)^{-1}$.


Why does mysql_real_escape_string insert quotes where there shouldn't be?

Question: I have a php page that I use to import orders from a csv file into a mysql database. One varchar in the table is used for the txnid. I discovered that occasionally I'll come across a txnid that results in an "Illegal double value found during parsing" error. For example:
6L831105EP011602

is a fine value that doesn't cause any trouble.
71V72876YH791094

Again, no problems.
546635980E5898057

But this one causes the error, presumably because it is being parsed as a double.
I have tried using mysql_real_escape_string to sanitize the data, but this results in all values being prefixed with '' unless they would've been parsed as a double.
What is the correct way I should be sanitizing this data? How can I determine if a value is going to cause a parse error before I try to insert it into MySQL?
Comment: So, I think you need to show us how you map excel to mysql. Without that we can't tell much.
Comment: `mysql_*` functions are deprecated. Use `mysqli_*`.
Comment: We'll need to see some code. Expect some chiding if you're writing new code [using the mysql_* functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).
Comment: Do you know who is giving that error? I think it's MySQL.
Answer: mysql_real_escape_string() does NOT add quotes to a string. It ESCAPES sql metacharacters.
e.g.
$str1 = "Miles O'Brien";
$str2 = "546635980E5898057";
$str3 = 42;

echo mysql_real_escape_string($str1);   // output: Miles O\'Brien
echo mysql_real_escape_string($str2);   // output: 546635980E5898057
echo mysql_real_escape_string($str3);   // output: 42

in no case would ANY escaped string suddenly come out like 'Miles O\'Brien' unless you added those quotes yourself. e.g.
echo "'" . mysql_real_escape_string($str1) . "'";

Comment: Whoops, yeah it seems like I had single quotes in my query (`"INSERT INTO orders VALUES (0, {$fname}, {$lname}, {$address1}, {$address2}, {$town}, {$county}, {$postcode}, {$country}, {$tel}, {$email}, '', {$postage}, {$subtotal}, {$total}, {$basket},'', 'eBay', now(), 'GBP', 'paypal', 1, '', 1, '{$txnId}') ON DUPLICATE KEY UPDATE txnid=txnid, complete=complete, new=new, time=time;"`) - the problem is that if I remove them I get invalid syntax near `'\"6Y8143371T918184S\"`, which is a txnid value.