text:
Q: JPA Criteria API: JOIN - Why is join object not usable for both involved entities? there is something about the JPA Criteria API's Join which I don't get in my mind and didn't find any explanation. Fist I will show the wrong, then the correct implementation and then the questions regarding the wrong approach.
Let's assume we have the following situation:
EntityA has a @ManyToOne relation to EntityB. And I want to join them and filter entities based on both entities' attributes.
So we have a root of EntityA and we join this entity with EntityB.
The following approach shown is giving some error as you can see:

If we take a closer look on the returned Join object we see this. I can only use the target type (=EntityB)'s attributes on that Join object:

And the correct way would be this (using EntityA's Root object instead of the Join object):

Questions:

*

*For my understanding I'd say that if this Join object represents the two joined tables EntityA and EntityB (= a new combined table with all of their attributes/columns) then I should be able to the Join (and only that one) to create where-clauses which filter for attributes of both involved entities.
But it seems I cannot create where-clauses on that join for attributes of EntityA (the source type of the Join), only for EntityB (the target type of the Join).
Why is that so? It's confusing me. Unfortunately it's nowhere stated or explained (JEE / Hibernate documentation) that a Join object can only be used this way or why it works like this.
I mean if I write this down in SQL it would probably look like this:
SELECT ... FROM EntityA a join EntityB b ON a.joinColumn = b.id WHERE a.year='value' AND a.weeks=5 AND b.family='value' AND b.country='GB'
and that is clear and not confusing. Here I clearly specify which attribute from which entity is involved. Another example: JPA Criteria API Join

*

*Further lines of thought:
I don't really know about the DB behaviour in the background, but...
a) Let's assume the DB is evaluating the where clauses first on its individual entities/tables and then joining the remaining matching entities: Using JPA Criteria API why do I have to create a where clause on the Root object of EntityA while for the EntityB I have to use the join object to do the same? I just want to point out that it does not look consistent of what I do in SQL and this confused me. (I know that if I would also create a Root object for EntityB and apply where clauses on that root object I could make it "look" consistent to the SQL way but would end up in a cartesian product/cross join by doing that)
b) And if we assume the opposite it leads me to the origin question: Let's assume the DB is first joining the tables and then applying the filtering/where clauses: When using JPA Criteria API why can't I work (i.e. define where clauses) only on the join object then?

*That also leads me to the question: What actually does the returned Join object represent? It is typed with <EntityA, EntityB>. What is the "source type" and "target type"? As stated above I can only use it for EntityB.
Somewhere I am stuck with my way of thinking it seems. I appreciate bringing me back to the right track.

A: You are mistaken on what the 'join' object is. It is NOT a combination of entities, but a reference object giving you access to the joined entity. JPA criteria queries are entity based -so your criteria query is traversing your model and you've explicitly defined a join over the entityA.joinColumn relationship. IN your query root==EntityA while Join == EntityBs referenced from EntityA. This is akin to JPQL "SELECT root from EntityA root join root.joinColumn entityB where root.year = :year AND root.week = :week AND entityB.family = :family AND entityB.country = :country"
Joins, inner joins specifically, are the default and do not need to be explicitly defined. You can access 'week' from EntityB directly using JPQL:

SELECT entityA from EntityA entityA where entityA.joinColumn.week = :week"

The entityA.joinColumn forces an inner join according to the specification and would result in the same SQL as

SELECT entityA from EntityA entityA join entityA.joinColumn entityB where entityB.week = :week"

Criteria query follows 1:1 with JPQL for the most part, but can be confusing because of the abstraction. Generic and type safety on Join<EntityA, EntityB> allows compile time checks that you are only accessing properties of EntityB within it, so you don't confuse it with some other join on EntityC, or that the root is of some other type.


text:
Q: How to call array out from Java method I created an array Pages in method List.
Could you please advise how to call out one element Pages[1] when accessing method List() from other classes?
public List() {
String[] Pages = {
"www.cnn.com",
"www.bbc.com",
"www.yahoo.com",
};

Many thanks!

A: You can't call a localvariable from a method directly. You must return it somehow.
Btw, it looks like you don't understand really well how methods work in Java. You should check it.
Here's an example of what do you want to do:
public String[] listPages(){

     String [] pages = {"www.cnn.com", "www.bbc.com", "www.yahoo.com"};

     return pages;
}

Later if you want to use one of the elements of the array, you should do something like this:
public static void main(String[] args){

     String[] res = listPages();
     //now we want to print the element one: www.cnn.com

     System.out.println(res[0]);
}

A: You need to create a class named List and a constructor for that class.
Also there are redundant ;, between the elements of the array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to distribute hybrid app outside appstore I'm sure lots of users here have built apps using the Mobile SDK. How are you distributing them? I've built a hybrid-remote app to go with our managed package. I don't want the app to be available in the appstore but it will need to be provided to all of our package customers. Is the iOS developer enterprise program my only option for iOS?
I understand the Android version is much easier where you can just provide a link to the app for installation. Is that correct?

A: I wrote another answer along these lines that explores a few options.
tl;dr - You are almost certainly better-served, and your users will have a far superior install and update experience, if you list on the public app store.
Why do you not want to list publicly? I can see only a few good reasons why you wouldn't (and some of those reasons aren't good at all, like your app using private APIs).

A: Apple allows three types of installs. The first type is the AppStore. The second is ad hoc installs. This mode is limited to 100 devices. The third may be of interest to you. It's the b2b program, in which only authorized clients can see or install the app. It's separate from the main AppStore, sort of quasi-private.
Look here for more info. https://developer.apple.com/programs/ios/distribute.html
Android apps are definitely easier to distribute.

A: Public distribution will save you the most headaches. Apple's processes for Enterprise are of no use in this case, and although I've not used their B2B program I suspect it'll have more than it's fair share of caveats and complexities like the Enterprise route.
If your app requires a SFDC login then it's already protected against the general public. If you need to make it available to only select customers, you could just ensure that the target org has a managed package installed on first login, and use the LMA to control that side of things.


text:
Q: Leyendo archivos de texto en Textbox Estoy deseando trabajar mis aplicaciones con simples archivos de texto. Algo muy simple, colocar un botón y un TextBox.
El TextBox va a mostrar el contenido del .txt y el botón va a dar la instrucción de que lo cargue.
Trabajo con Visual Studio y con el lenguaje C#.
Ahora bien, logré hacer esto que cuento con el siguiente código:
private void btnShowTxt_Click(object sender, EventArgs e)
{
  string texto = File.ReadAllText("test.txt");
  txtShowTxt.Text = texto;
}

El problema es que noté que si el archivo test.txt no se encuentro dentro la ruta que me especifica el Visual Studio, me genera una excepción. Yo lo que deseo es que, quien tenga mi aplicación, pueda leer desde la ruta que yo coloque en el código, le cargue en el TextBox el contenido del archivo de texto.
Por ejemplo, el usuario coloca el archivo "test.txt" en Documents o lo mueve a Desktop, da igual. No sé por qué el Visual Studio me genera la excepción si no se encuentra el archivo dentro de la carpeta del proyecto.

A: El lenguaje (al igual que prácticamente todos) busca el archivo en donde le digas que lo busque. En este caso, si le dices que abra un archivo que está en la carpeta del proyecto, el lenguaje buscará el archivo ahí y lo abrirá. Si no está, lanzará una excepción.
Si quieres que el programa abra un archivo desde el escritorio, debes dar la ruta completa al escritorio; por ejemplo: File.ReadAllText("C:\Usuarios\User\Desktop\test.txt");.
Obviamente, hacerlo de ese modo no es lo ideal, porque la ruta puede variar entre computadores. En ese caso, el programa debe extenderse para que el usuario introduzca la ruta de su archivo (sea escribiéndola o usando una ventana de selección de archivos), de modo que el programa use esa ruta introducida por el usuario para buscar el archivo ahí.

A: Creo que no logro de comprender la necesidad, pero sin duda lo primero que se requiere es validar si el archivo existe en la ruta específicada usando el método File.Exists para que no te genere ninguna excepción:
using System.IO;

private void btnShowTxt_Click(object sender, EventArgs e)
{
    string texto = string.Empty;
    string path = "c:\\temp\\test.txt";

    if(File.Exists(path))
        texto = File.ReadAllText(path);
    else
        texto = "Archivo no encontrado";

    txtShowTxt.Text = texto;
}

Como tal, Visual Studio o el tipo de solución que uses (consola, escritorio, web, etc.) no cuenta con la funcionalidad para detectar si un archivo ha cambiado de ruta, y en este caso la tendrías que especificar para validar si el archivo existe o no.


text:
Q: Python - replace unicode emojis with ASCII characters I have an issue with one of my current weekend projects. I am writing a Python script that fetches some data from different sources and then spits everything out to an esc-pos printer. As you might imagine pos printers don't exactly like emojis...
So text like this:
可爱!!!!!!!!

gives me this character string:
'\u53ef\u7231!!!!!!!!\U0001f60d\U0001f60d\U0001f60d\U0001f60d\U0001f60d\U0001f60d\U0001f60d\U0001f61d'

The result that comes out of the printer is quite different than what I would like of course. So I need to replace these non-ASCII characters with something else. I don't really care for the first characters, but I do care about emojis. Using something like: unidecode(str(text)) will at least strip them out, but I want to convert them to something more useful. Either into classic smilies like [:-D] or into [SMILING FACE WITH HEART-SHAPED EYES].
My problem is... how would one go about doing this? Manually creating a lookup table for most common emojis seems a bit tedious, so I am wondering if there is something else that I can do.

A: With the tip about unicodedata.name and some further research I managed to put this thing together:
import unicodedata
from unidecode import unidecode

def deEmojify(inputString):
    returnString = ""

    for character in inputString:
        try:
            character.encode("ascii")
            returnString += character
        except UnicodeEncodeError:
            replaced = unidecode(str(character))
            if replaced != '':
                returnString += replaced
            else:
                try:
                     returnString += "[" + unicodedata.name(character) + "]"
                except ValueError:
                     returnString += "[x]"

    return returnString

Basically it first tries to find the most appropriate ascii representation, if that fails it tries using the unicode name, and if even that fails it simply replaces it with some simple marker.
For example Taking this string:

abcdšeđfčgžhÅiØjÆk 可爱!!!!!!!!

And running the function:
string = u'abcdšeđfčgžhÅiØjÆk \u53ef\u7231!!!!!!!!\U0001f60d\U0001f60d\U0001f60d\U0001f60d\U0001f60d\U0001f60d\U0001f60d\U0001f61d'
print(deEmojify(string))

Will produce the following result:

abcdsedfcgzhAiOjAEk[x] Ke Ai !!!!!!!![SMILING FACE WITH HEART-SHAPED
  EYES][SMILING FACE WITH HEART-SHAPED EYES][SMILING FACE WITH
  HEART-SHAPED EYES][SMILING FACE WITH HEART-SHAPED EYES][SMILING FACE
  WITH HEART-SHAPED EYES][SMILING FACE WITH HEART-SHAPED EYES][SMILING
  FACE WITH HEART-SHAPED EYES][FACE WITH STUCK-OUT TONGUE AND
  TIGHTLY-CLOSED EYES]

A: Try this
import unicodedata
print( unicodedata.name(u'\U0001f60d'))

result is
SMILING FACE WITH HEART-SHAPED EYES

A: I faced the same problem and solved it using the following in fuction:
import demoji

def deEmojify(inputString):
    return demoji.replace_with_desc(inputString.encode('utf-16', 'surrogatepass').decode('utf-16'))


text:
Q: sencha touch: vertical separator on toolbar I have a toolbar containing a set of buttons.
Now I want to insert a vertical separator in between these buttons.
But I am not able to find out a component in Sencha Touch which will get this for me.
Please check the below pics to get an idea of what exactly I want:

Please help me with this.
thanks.

A: Here is a work around. You can try this. First you add a button in between the button where you want to add separator like this:
                {
                    xtype: 'button',
                    ui: 'plain',
                    text: '|',
                    disabled: true,
                    cls: 'separator'
                }

and then add style to 'separator' class like this:
.separator {
    font-size: 30px;
    color: #6EA6CC;
}

Now you can customize the style according to your need.
I believe there can be better ways of doing this. Good luck.

A: I would avoid adding additional components as previously suggested, to avoid extra DOM.
This should be done in CSS/SASS, for best performance and reusability.
To mockup the above pictures, the best solution is probably to create a button style with a transparent background, a margin and a border-left property.


text:
Q: single session shairing in all browser In my website (php)  I want that if I have created session from IE browser then no need to login if i open site on other browser like mozilla etc in.
Is it possible to share single session on all sites ?

A: No. Session saves in a browser. You can use coockies for your situation.


text:
Q: GITK with Angular 2 has issues on redirects using fragments (# hash) The Google Identity Toolkit workflow has issues if integrate with Angular or other javascript frameworks.
Angular is using URL fragments (#) to navigate among the views. It is also possible to navigate using the HTML5 style and avoiding to use hashes but unfortunately Angular 2 has an issue in properly handling fragments, https://github.com/angular/angular/issues/6595.
Because URL fragments are internally used by Angular and similar frameworks it is preventing GITK to work properly in some circumstances:
During the login workflow if the user is successfully authorized by a third party sing-in service the user is redirected back to the GITK widget page.
The redirect URL will include a state parameter. In case of Twitter or Facebook the state parameter is added as query param to the URL (e.g. ...login/?state=AFD_5tlxzU...).
However other services like Google Account are adding the state parameter has fragment to the redirect URL (e.g. ...login/#state=AFD_5tlxzU...).
Due to the fact that Angular is using the URL fragments to navigate, the state fragment (e.g. ...login/#state=AFD_5tlxzU...) of the redirect URL is removed by the framework preventing GITK widget to successfully complete the authentication.
Is there any option to instruct Google Accounts or GITK to use query params instead of fragments? Also I was wondering what is the rational of using fragments instead of query params for the redirect URL?

A: I am answering to my self.
One way to solve the issue as mentioned here is to move the sing-in logic outside the Angular routing paths.
For instance by creating a separate static .html file that is only responsible for the sing-in. An alternative solution would be to use ng2-ui-router.


text:
Q: Changing the directory of the shell through a C++ program I'm trying to write a simple C++ program to execute Linux commands. I'm stuck at changing the directories (commands like chdir and cd don't work). This is what I have so far:
system("echo -n '1. Current Directory is '; pwd");
system("chdir Desktop");

A: This is not possible, if you want to change the directory (i.e. cd, that is chdir(2) ...) of the shell which has invoked your program. So cd has to be a bash(1) builtin.
The reason is that chdir affects only the calling process (which would be your C program) not the parent process. Each process has its own current directory. See also getcwd(3), errno(3), credentials(7), proc(5) and path_resolution(7).
If you call system(3) it will fork(2) a new shell and execve(2) /bin/sh -c so only the forked shell can change its current directory.
You need to read Advanced Linux Programming and syscalls(2).
Perhaps you want to call chdir directly inside your C program. This will affect the current process and all future child processes (including those started with system or popen library functions inside your C code) till their termination or some further call to chdir. But it won't affect the shell in your terminal (where you started your C program).


text:
Q: Sorting a vector of objects alphabetically in c++ So I've created a vector which contains product objects.
The product has a int ID, string manufacturer and string productname.
Lets say I've stored a few products by doing this
vector<product*>productlist;
 Product*p = new Product(123, "Sony", "C vaio laptop")
 Product*p1 = new Product(1234, "LG", "D 54 inch TV")
 Product*p2 = new Product(1235, "Lays", "A potato chips")
productlist.push_back(p);
productlist.push_back(p1);
productlist.push_back(p2);

I have a method called getproductname(){return productname;} which can be used to get the productname, and I can sort the productnames, but after that I have no idea how to continue as I don't know how to print the whole object by alphabetically of their productname.
Now I want to sort/print the 3 products by alphabetical order of their productname. How can I do that(the sorting part)?
Sample output:
Products sorted alphabetically
Product ID1: 1235
Product manufacturer: Lays
Product name:A potato chips  //name starts with A so it's the first output
Product ID2: 123
Product manufacturer: Sony
Product name: C vaio laptop
Product ID3: 1234
Product manufacturer: LG
Product name: D 54 inch TV //name starts with D so it's the last
I've tried inserting sort(productlist.begin(), productlist.end()); but it only works on vectors with string and not objects.
question asked was too vague/simple at first. Edited!

A: The easiest way is to use std::sort() function from the standard library.
You can try something like this:
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

bool compareFunction (std::string a, std::string b) {return a<b;}
//compare any way you like, here I am using the default string comparison

int main ()
{
  std::string myNames[] = {"Henry","Tom","Jafar","Alice","Bob","Cindy","Clara","Michael"};

  std::vector<std::string> myvector (myNames, myNames+8); //create vector from array

  std::sort(myvector.begin(),myvector.end(),compareFunction);//sort the vector

  std::cout << "Sorted vector:";
  for (std::vector<std::string>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

I would recommend you look into the documentation for more details on std::sort

A: The way to make sorting happen using STL containers is to define a comparator function that tells the std::sort algorithm how to compare the elements to place them in order. So we need to define a less than relationship which we can do by creating a less than operator for our Product class like this:
struct Product
{
    int ID = 0;
    std::string manuf;
    std::string name;

    Product(int ID, const std::string& manuf, const std::string& name)
    : ID(ID), manuf(manuf), name(name) // initialize members here
    {
    }

    // overloading the < operator enables functions
    // like std::sort to compare Product objects to
    // order them accordingly
    bool operator<(const Product& p) const
    {
        return name < p.name; // order by name
    }
};

Now if we send a container full of Product objects to std::sort they will be sorted according to name.
However, we need to sort Product objects through their pointers so we need another less than operator to hand to the std::sort function that dereferences the pointers before making the comparison using our comparator function.
// Function object to sort pointers
struct SortProductPointers
{
    // overload the function call operator
    bool operator()(const Product* lhs, const Product* rhs) const
    {
        // dereference the pointers to compare their targets
        // using the Product class's operator<(...) function
        return *lhs < *rhs;
    }
};

Now we have those two we can call our std::sort algorithm:
int main()
{
    std::vector<Product*> products;

    products.push_back(new Product(1, "Lays", "A potato chips"));
    products.push_back(new Product(3, "LG", "D 54 inch TV"));
    products.push_back(new Product(2, "Sony", "C vaio laptop"));

    // std::sort takes a third parameter which is the
    // comparator function object
    std::sort(products.begin(), products.end(), SortProductPointers());

    for(const auto* p: products)
        std::cout << p->ID << ": " << p->manuf << ", " << p->name << '\n';

    // Don't forget to delete all your Products
    for(auto* p: products)
        delete p;
}

A: You can also do it with a lambda implementation
    std::string myNames[] = {"Henry","Tom","Jafar","Alice","Bob","Cindy","Clara","Michael"};

  std::vector<std::string> myvector (myNames, myNames+8); //create vector from array

    std::sort(myvector.begin(), myvector.end(), [](const std::string & a, const std::string & b) -> bool
    {
        return a < b;
    });

    std::cout << "Sorted vector:";
  for (std::vector<std::string>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;


text:
Q: jsp safari browser windows file download content disposition file name became - below code is used for the download attachment encoding chinese character for file name.
w_inf_src = new File(p_filepath);
   w_inf = new FileInputStream(w_inf_src);
   p_response.setContentType(w_mime+";charset=UTF-8");
   p_response.setContentLength(new Long(w_inf_src.length()).intValue());
   p_response.setCharacterEncoding("UTF-8");
   p_request.setCharacterEncoding("UTF-8");

   p_response.setHeader("Content-disposition",
             "attachment;filename=\"" + (new java.net.URI(null, null, p_request, p_filename, null)).toASCIIString() + "\"");

   // Download File In Progress
   w_outf = p_response.getOutputStream();
   w_bof = new BufferedOutputStream(w_outf);
   while ( (w_bytes_read = w_inf.read(w_buffer, 0, w_buffer.length)) != -1)
     w_bof.write(w_buffer, 0, w_bytes_read);
   w_bof.flush();

I also tried the filename*=UTF-8''< encoded file name > but does not work

A: If you are using at least java 7 and Sevlet API 3.0, this is the way to go:
File w_inf_src = new File(p_filepath);
String encoding = StandardCharsets.UTF_8.name();
String w_disposition = String.format("%s;filename=\"%3$s\"; filename*=%2$s''%3$s",
    Part.ATTACHMENT,
    encoding,
    URLEncoder.encode(p_filename, encoding).replace("+", "%20"));

p_response.setContentType(w_mime);
p_response.setContentLengthLong(w_inf_src.length());
p_response.setCharacterEncoding(encoding);
p_response.setHeader("Content-Disposition", w_disposition);

byte[] w_buffer = new byte[p_response.getBufferSize()];
try(FileInputStream w_inf = new FileInputStream(w_inf_src);
    OutputStream w_outf = p_response.getOutputStream())
{
    int n;
    while((n = w_inf.read(w_buffer)) != -1)
    {
        w_outf.write(w_buffer, 0, n);
    }
}

Some notes:

*

*this is the most accurate disposition form you'll get, since it's urlencoded and space-sanitized.

*it's redundant to set the encoding in both content-type and content-encoding

*it's superfluous to set the request encoding: you are not reading.

*it's redundant to use a BufferedInputStream because the response has an internal buffering

*use your own buffer of the max available size (respose.getBufferSize())

*use try-with-resources where possible (if you are on Java 7+)

*if you are on Servlet API 3.0+ you have response.setContentLengthLong(), they finally understood that an integer is not enough

*alternatively use: response.setHeader("Content-Length", String.valueOf(w_inf_src.length()));: this ensures that large lengths are not cutted to int size


text:
Q: @return description in magento-coding-standard I am currently working on bringing my extensions to the current coding standard.
So, when writing a function, normally I would describe it the following way:
protected function exampleFunction(string $name): string|null
{
   return $name;
}

But there are some cases, where I dont know, how to "describe" the return value.
For example:
protected function getParentProduct(int $id): ??????
    {
        $parentByChild = $this->catalogProductTypeConfigurable->getParentIdsByChild($id);
        if (isset($parentByChild[0])) {
            //set id as parent product id...
            $parentid = $parentByChild[0];
            return $this->ProductFactory->create()->load($parentid);
        }
    }

So, the function returns a loaded product (built with ProductFactory. But as the Product-class is not explicity at the begin of the class (Magento\Catalog\Model\Product), I dont know, what I should use for the description or if its ok, to just write:
protected function getParentProduct(int $id): Product|null

I know, this is nothing, that would break the code, but I want to use more good habits, when coding my extensions.

A: You can do something like this one :

protected function getParentProduct(int $id): Json

And then return your data into the Json format.


text:
Q: Avoiding having SIP permanently disabled to permit kernel extension I'm looking to work around the lack of support for a wireless adapter in Big Sur by using https://github.com/chris1111/Wireless-USB-Big-Sur-Adapter/. Unfortunately it requires SIP to be disabled not just during installation, but permanently. I'm trying to understand why that is, and whether there might be alternatives?
For instance, HoRDNS which faced similar problems you only need to temporarily disable it (https://github.com/jwise/HoRNDIS/issues/132)
Does anyone have any suggestions? My understanding of how all the kext stuff works is a little limited.

A: You can selectively enable parts of System Integrity Protection.
For example, you can enable all of SIP except kernel extension protection with
csrutil enable --without kext

Some other options to try listed in https://developer.apple.com/forums/thread/17452, but the kext option sounds the most promising.


text:
Q: Migration Update Laravel 5 How do I update my schema within the php artisan migrate. I already have the tables created, but I want to be able to update a column to cascade on delete.
I have the schema updated, but it keeps saying nothing to migrate. When I use migrate:refresh I get an error saying a table is not found.
public function up()
{
    Schema::table('invoices', function($table)
    {
          $table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
    });
}

A: Try to
php artisan migrate:rollback

and
php artisan migrate

another one. If you'll get some errors try
composer dumpautoload

I had same issue and it helps


text:
Q: Error on installing downloaded Chrome .deb I have downloaded Chrome on 14.04 as .deb package. Whenever I try to install it, it gives error  "Dependency is not satisfiable".

A: Make sure that you have all checked under Software & Updates --> Update tab, then do
sudo apt-get update && sudo apt-get upgrade

An easier way to install, just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command(s) below:

wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
sudo apt-get update
sudo apt-get install google-chrome-stable

Or use synaptics
Source:TecAdmin


text:
Q: Formally prove some results for countable and uncountable sets Prove that:
$a)$ the set of all rational numbers is countable;
$b)$ the set of all real numbers is uncountable;
$c)$ any subset of a countable set is countable;
$d)$ the union of countably many countable sets is countable.
I have no idea how to formally prove this.
For $a)$, I think, the idea would be to notice that any rational number can be expressed like fraction. Taking the number of the denominator $n$ for establishing a relation to set of integers there would be $n-1$ numbers for each integer. So it would be a  union of countably many countable sets. But then I would need to prove $d)$ first.
Could anyone show me an example of this type of proofs or give any advice.

A: Hints:
For (d) you need (a fragment of) the axiom of choice to choose for each of the countable sets a function witnessing its countability.  Then use the fact that $\mathbb{N} \times \mathbb{N}$ is countable.
For (a) you don't need the full strength of (d).  Just write the rational numbers out in a two-dimensional array and find a linear path that covers them all.  Then work out an equation that describes the path.
For (b), for any set $X$ there is no surjection from $X$ onto the power set of $X$.  (If $f$ were such a surjection, considering $\{x \in X : x \notin f(x)\}$ leads to a contradiction.)  Then let $X = \mathbb{N}$ and consider binary expansions of real numbers.
For (c), if there is a surjection from $X$ to $Y$ and $Y'$ is a nonempty subset of $Y$ then there is a surjection from $X$ to $Y'$.  (You can modify the given surjection somehow using the fact that $Y'$ is nonempty.)


text:
Q: Avoid class instances to overwrite default values I am dealing with issues regarding initialization of classes. Here is a reproducing example highlighting the underlying issue (I did not manage to make it much smaller):
Classes
We have two classes A,B. The hierarchy goes

*

*A: First class - instances have two attributes link;name

*B: This class has an A-instance as one of its attributes.

In order to faster declare instances of B I considered the following: B(name=name) which behind the curtains does B(a=A(name=name)).
Here is the code
 class A(object):
    def __init__(self, link='', name=''):
        self.name = name
        self.link = link

class B(object):
    def __init__(self, a=A(), value=0, link='', name=''):
        # Two ways to initialize "self.a":
        # 1. If "name" or "link" provided
        # 2. With "a" provided
        if {name, link}.difference({''}):
            self.a = A(name=name, link=link)
        else:
            self.a = a
        # Rest
        self.value = value

    def __str__(self):
        return 'Instance:\nname:\t{}\nlink:\t{}\nvalue:\t{}'.format(self.a.name, self.a.link, self.value)

Test
Here are two small tests:

*

*The first one defines two instances b1;b2 using __init__.

*The second one defines the instances as empty (B()) and then proceeds to populate/overwrite the fields.

As one can see below, the second option is problematic as it overwrites the classe's default values.
# 1. Set it all inside init
b1 = B(link=link, name=name, value=value)
b2 = B(value=value)
print(b1)
# Instance:
# name: world
# link: hello
# value:    1
print(b2)
# Instance:
# name:
# link:
# value:    1

# NO PROBLEM

# 2. Define empty instances and populate
b1 = B()
b1.a.link = link
b1.a.name = name
b1.value = values[0]
b2 = B()
b2.value = values[1]
print(b1)
# Instance:
# name: world
# link: hello
# value:    1
print(b2)
# Instance:
# name: world
# link: hello
# value:    2

# PROBLEM

How can I guarantee for this problem not to occurr? Should I overwrite the __new__ method, add getters/setter, work with copies (copy.deepcopy), etc. ?


text:
Q: Adjusting display geometry in a virtual machine? Running 11.04 beta in a Parallels 5.0 virtual machine, but this question will apply to any virtualization software.
Parallels 5 Linux tools (guest additions) don't work for 10.10 and 11.04 and I don't want them. I like how the VM is integrated as is. The only thing that needs tuning is the screen geometry.
None of the options in the Systems -> Preferences -> Monitors fit my display perfectly. I need it at 1080 x 1920 (9:16) or 1920 x 1080 (16:9).
Many different resolutions work (see screen-shot bellow), among which are:

*

*1680 x 1080 (too narrow horizontally and a bit too short vertically)

*1920 x 1200 (perfect horizontally, but a bit too tall vertically)

How can I adjust the screen resolution (display/monitor size) manually?
What I tried so far
$ cvt 1920 1080
# 1920x1080 59.96 Hz (CVT 2.07M9) hsync: 67.16 kHz; pclk: 173.00 MHz
Modeline "1920x1080_60.00"  173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync
$ sudo xrandr --newmode "1920x1080"  173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync
xrandr: Failed to get size of gamma for output default

$ cvt 1080 1920
# 1080x1920 59.96 Hz (CVT) hsync: 119.26 kHz; pclk: 176.50 MHz
Modeline "1080x1920_60.00"  176.50  1080 1168 1280 1480  1920 1923 1933 1989 -hsync +vsync
$ sudo xrandr --newmode "1080x1920"  176.50  1080 1168 1280 1480  1920 1923 1933 1989 -hsync +vsync

$ sudo xrandr -q
xrandr: Failed to get size of gamma for output default
Screen 0: minimum 640 x 480, current 1920 x 1200, maximum 1920 x 1200
default connected 1920x1200+0+0 0mm x 0mm
   1920x1200       0.0*
   1600x1200       0.0
   1680x1050       0.0
   1400x1050       0.0
   1280x1024       0.0
   1440x900        0.0
   1280x960        0.0
   1280x800        0.0
   1024x768        0.0
   800x600         0.0
   640x480         0.0
  1920x1080 (0x11d)  173.0MHz
        h: width  1920 start 2048 end 2248 total 2576 skew    0 clock   67.2KHz
        v: height 1080 start 1083 end 1088 total 1120           clock   60.0Hz
  1080x1920 (0x11e)  176.5MHz
        h: width  1080 start 1168 end 1280 total 1480 skew    0 clock  119.3KHz
        v: height 1920 start 1923 end 1933 total 1989           clock   60.0Hz

The 2 new resolutions do not show up in the Monitor Preferences GUI:

Trying Takkat's Solution
Here is what I do and get:
$ gtf 1920 1080 60 -x

  # 1920x1080 @ 60.00 Hz (GTF) hsync: 67.08 kHz; pclk: 172.80 MHz
  Modeline "1920x1080_60.00"  172.80  1920 2040 2248 2576  1080 1081 1084 1118  -HSync +Vsync

$ sudo xrandr --newmode "1920x1080_60.00"  172.80  1920 2040 2248 2576  1080 1081 1084 1118  -HSync +Vsync

$ sudo xrandr --addmode default 1920x1080_60.00

$ xrandr
xrandr: Failed to get size of gamma for output default
Screen 0: minimum 640 x 480, current 1680 x 1050, maximum 1920 x 1200
default connected 1680x1050+0+0 0mm x 0mm
   1920x1200       0.0
   1600x1200       0.0
   1680x1050       0.0*
   1400x1050       0.0
   1280x1024       0.0
   1440x900        0.0
   1280x960        0.0
   1280x800        0.0
   1024x768        0.0
   800x600         0.0
   640x480         0.0
   1920x1080_60.00   60.0

I also tried gtf 1920 1080 60 -x.
In both cases I can't switch to that resolution and get:

*

*Could not set configuration for CRTC 262

All the other resolutions work.

A: In VirtualBox I use a minimal version of the good old xorg.conf:
Section "Monitor"
    Identifier      "Monitor0"
    HorizSync       30.0 - 96.0
    VertRefresh     50.0 - 160.0
EndSection

Section "Device"
    Identifier      "Device0"
    Driver          "vesa"
EndSection

Section "Screen"
    Identifier      "Screen0"
    Monitor         "Monitor0"
    Device          "Device0"
    DefaultDepth    24
    SubSection "Display"
        Depth       24
        Modes       "1280x1024"
    EndSubSection
EndSection

Section "ServerLayout"
    Identifier      "Layout0"
    Screen          "Screen0"
EndSection

I don't know if you need to provide HorizSync and VertRefresh for a TFT, but in any case don't copy my values!

A: Display Geometry Settings in Virtual Box
In Oracle Virtual Box you can adjust the virtual screen resolution after having installed the Guest Additions simply by dragging the window with the mouse or by choosing full screen mode. No need to do anything with xorg.conf. XServer 1.10 (included in   11.04) and thus Unity 3D runs only in Virtual Box >=4.0.6.
1. Use Mouse to adjust screen size
Adjusting the screen by resizing the Virtual Box Windows with the mouse allows for any screen resolution up to the host screen resolution.
2. Use predefined standard screen sizes
If you need a fixed (standard) resolution you may also choose System Settings -> Monitors (for 11.04) or Displays (for 12.04) for a selection of fixed resolutions (here shown for 12.04):

*

*For maximum host screen resolution you will need to run Virtual Box in Fullscreen mode (Host + F)

*For a fixed host screen resolution we need to disable Auto-resize Guest Display (HOST+G) from Virtual Box Manager View menu.

3. Define new geometry with xrandr
If you need a fixed geometry that is not in the list of resolutions for monitors you will have to use xrandr to define a new resolution:
First we use gtf for calculating the modeline of possible resolutions:
gtf <xres> <yres> <refresh> [-x]

Give the desired values for x-resolution, y-resolution and refresh rate. The flag -x is default and can be omitted. For a portrait resolution 480x640 at 60 Hz you will get the following output:
$ gtf 480 640 60 -x
$ 480x640 @ 60.00 Hz (GTF) hsync: 39.78 kHz; pclk: 24.82 MHz Modeline "480x640_60.00" 24.82 480 504 552 624 640 641 644 663 -HSync +Vsync

From this we can copy & paste the modeline to add it to xrandr list of known resolutions:
xrandr --newmode "480x640_60.00" 24.82 480 504 552 624 640 641 644 663 -HSync +Vsync

and add this for the Virtual Box Monitor:
xrandr --addmode VBOX0 480x640_60.00

Replace VBOX0 with the appropriate monitor if you have setup Virtual Box with multiple monitors (or any other output name the driver reports).
We can now switch to the newly defined geometry as described above (2.).

A: Possible one could try the commands and xorg.conf snippets that are listed here:
http://wiki.debian.org/XStrikeForce/HowToRandR12
I haven't tried that yet and don't know if there is enough information to get it working.

A: Just to summarize a working answer succinctly. Tested in 18.04 with lubuntu-desktop:

*

*Install guest additions on the VM: sudo apt-get install virtualbox-guest-dkms

*Restart the VM: sudo shutdown -r now

*After logging into the VM, resize the VirtualBox window to the desired size. (The VM screen inside the window does not resize automatically yet.)

*On the VM, go to Preferences -> Monitor Settings -> select Auto -> Apply -> OK

(You could skip step 1 if guest additions are already installed. Check if sudo lsmod | grep vbox returns anything first.)

A: I am running ubuntu 10.10 on Virtualbox i had the same problem . couldn't adjust the resolution and also the full screen mode was not working. After a bit googling i found this article
http://tutorial.downloadatoz.com/how-to-fix-ubuntu-10-10-virtualbox-guest-additions-problems.html
This really worked for me.

A: I had this problem with Windows8 (Host Ubuntu). It wouldn't scale to the external monitor's size.
In the Virtualbox, File, Preferences [CTRL]+[G], Display, choose Maximum Guest Screen Size - Automatic.
Solved.


text:
Q: Replacing part of string in python pandas dataframe I have a similar problem to the one posted here:
Pandas DataFrame: remove unwanted parts from strings in a column
I need to remove newline characters from within a string in a DataFrame. Basically, I've accessed an api using python's json module and that's all ok. Creating the DataFrame works amazingly, too. However, when I want to finally output the end result into a csv, I get a bit stuck, because there are newlines that are creating false 'new rows' in the csv file.
So basically I'm trying to turn this:
'...this is a paragraph.
And this is another paragraph...'
into this:
'...this is a paragraph. And this is another paragraph...'
I don't care about preserving any kind of '\n' or any special symbols for the paragraph break. So it can be stripped right out.
I've tried a few variations:
misc['product_desc'] = misc['product_desc'].strip('\n')

AttributeError: 'Series' object has no attribute 'strip'

here's another
misc['product_desc'] = misc['product_desc'].str.strip('\n')

TypeError: wrapper() takes exactly 1 argument (2 given)

misc['product_desc'] = misc['product_desc'].map(lambda x: x.strip('\n'))
misc['product_desc'] = misc['product_desc'].map(lambda x: x.strip('\n\t'))

There is no error message, but the newline characters don't go away, either. Same thing with this:
misc = misc.replace('\n', '')

The write to csv line is this:
misc_id.to_csv('C:\Users\jlalonde\Desktop\misc_w_id.csv', sep=' ', na_rep='', index=False, encoding='utf-8')

Version of Pandas is 0.9.1
Thanks! :)

A: You could use regex parameter of replace method to achieve that:
misc['product_desc'] = misc['product_desc'].replace(to_replace='\n', value='', regex=True)

A: strip only removes the specified characters at the beginning and end of the string.  If you want to remove all \n, you need to use replace.
misc['product_desc'] = misc['product_desc'].str.replace('\n', '')


text:
Q: track state reversal in Pandas by comparing two columns This is a follow-on to my previous question: detecting value crossing between columns in Pandas
Let's assume I have two columns, df['a'] and df['b'], called 'a' and 'b' here to simplify
In the previous question, I was trying to detect indices where: a[i - 1] < b[i] and a[i] >= b[i]
now, I am trying to track two changes:
a[i - 1] < b[i] and a[i] >= b[i]

and
a[i - 1] >= b[i] and a[i] < b[i]

and create a column with a value set based on the LAST change that occurred.
Here is some pseudo code:
state = 0
result = []
for i in myIndex:
    if a[i - 1] < b[i] and a[i] >= b[i]:
        state = 1
    elif a[i - 1] >= b[i] and a[i] < b[i]:
        state = 0

result.append(state)

is there an idiomatic (non-looping) way to achieve this in Pandas?

Edit:
I realize this question has caused some confusion, so I didn't word it properly. An example here:
Let's assume I have two columns for the outputs of the two conditions I'm tracking:
 cond_A    cond_B
 false     false
 false     true
 false     false
 false     false
 true      false
 false     false

then the output should be (if we set 0 and 1 as output values):
cond_A    cond_B    output
false     false     0
false     true      1
false     false     1
false     false     1
true      false     0
false     false     0

so, if both conditions are false, we reuse the last state, if a condition is true, we set the state.

A: this is the equation of a RS flip flop: https://en.wikipedia.org/wiki/Flip-flop_(electronics)
using the example given as a dataframe:
print(df)

   cond_A  cond_B
0   False   False
1   False    True
2   False   False
3   False   False
4    True   False
5   False   False

UPDATE
df['state']=df.any(axis=1).where(df['cond_B'].cumsum().ge(1),0).cumsum()%2
print(df)

   cond_A  cond_B  state
0   False   False      0
1   False    True      1
2   False   False      1
3   False   False      1
4    True   False      0
5   False   False      0

If you have two independent series
(cond_A | cond_B).where(cond_B.cumsum().ge(1),0).cumsum()%2

A: You can try
>>> df['c'] = pd.Series((df.a.shift(-1) < df.b) & (df.a >= df.b)).replace({False : 0, True : 1})
>>> df
    a   b  c
0   8  17  0
1   2  86  0
2  93  42  0
3  49   1  0
4  35  62  0
5   3  39  0
6  25  21  0
7  54  24  1
8   3  77  0
9  41  42  0


text:
Q: Where to put calculation executed regularly that updates actor's internal state? I am learning Scala and Akka.
In the problem I am trying to solve I want an actor to be reading a real-time data stream and perform a certain calculation that would update its state.
Every 3 seconds I am sending a request through a Scheduler for the actor to return to its state.
While I have pretty much everything implemented, with my actor having a broadcaster and receiver and the function to update the state right. I am not entirely sure how to do it, I could potentially put the calculations always running in a separate thread inside the actor but I would like to now if there is a more elegant way to make this in scala.

A: I would suggest to divide the work between two actors. The parent actor would manage child worker actor and would track the state. It sends a message to the child worker actor to trigger data processing.
The child worker actor processes the data stream - don't forget to wrap the processing into a Future so that it doesn't block the actor from processing messages. It also periodically sends messages to the master with current state. So the child worker is stateless, it sends notifications when its state changes.
If you want to know the current state of the work overall, you ask the master. In principle, you can merge this into one actor which sends the status message to itself. I wouldn't update the state directly to avoid concurrency issues. The reason is that the data processing work running in the Future can possible run on a different thread than message processing.


text:
Q: How can I write my IEqualityComparer without checking for nulls? I'm running my project in a nullable enabled context and I wish to simplify my code because it's internal and I KNOW that the references passed in are non-null. The IEqualityComparer interface gives warnings if I make the parameters not nullable.
class FileInfoComparer : IEqualityComparer<FileInfo>
{
    // Round up timestamp to the next 2 seconds
    const long interval = 20_000_000;
    DateTime RoundUp(DateTime time) => time.AddTicks(interval - (time.Ticks - 1) % interval - 1);

    public bool Equals(FileInfo? fi1, FileInfo? fi2)
    {
        return fi1.Name == fi2.Name &&
            RoundUp(fi1.LastWriteTime) == RoundUp(fi2.LastWriteTime) && fi1.Length == fi2.Length;
    }

    public int GetHashCode(FileInfo fi)
    {
        return HashCode.Combine(fi.Name, RoundUp(fi.LastWriteTime), fi.Length);
    }
}

As it stands I'm getting squigglies under various fi1 and fi2 references whenever I try to make them not nullable. I've tried adding various attributes like [NotNull] in places but nothing works. I've also tried writing like this:
return fi1?.Name == fi2?.Name &&
    RoundUp(fi1.LastWriteTime) == RoundUp(fi2.LastWriteTime) && i1.Length == fi2.Length;

but the squigglies just move somewhere else. Are there any Null attributes like [DisallowNull] etc. that I can add in the right places to remove the warnings?

A: /// <remarks>
/// <see cref="Equals"/> rejects <see langword="null"/> values.
/// </remarks>
class FileInfoComparer : IEqualityComparer<FileInfo>
{
    // Other parts as before

    public bool Equals(FileInfo? fi1, FileInfo? fi2)
    {
        if (fi1 is null)
        {
            throw new ArgumentNullException(nameof(fi1));
        }

        if (fi2 is null)
        {
            throw new ArgumentNullException(nameof(fi2));
        }

        return fi1.Name == fi2.Name &&
            RoundUp(fi1.LastWriteTime) == RoundUp(fi2.LastWriteTime) && fi1.Length == fi2.Length;
    }

    // GetHashCode as before
}

It is possible to make the argument validation a single line if desired by turning it into a method that takes a parameter and throws if it is null.
Alternative using the null forgiving operator:
/// <remarks>
/// <see cref="Equals"/> rejects <see langword="null"/> values.
/// </remarks>
class FileInfoComparer : IEqualityComparer<FileInfo>
{
    // Other parts as before

    public bool Equals(FileInfo? fi1, FileInfo? fi2)
    {
        return fi1!.Name == fi2!.Name &&
            RoundUp(fi1.LastWriteTime) == RoundUp(fi2.LastWriteTime) && fi1.Length == fi2.Length;
    }

    // GetHashCode as before
}


text:
Q: Families of pairwise incomparable subsets of the integers Certain maximal objects whose existence follows from Zorn's Lemma have received some
set-theoretic attention.
Examples are maximal independent families and maximal almost disjoint families.
There is quite a bit of information out there about the two cardinal invariants $\mathfrak i$
and $\mathfrak a$, the minimal sizes of maximal independent families of subsets of $\omega$
and of maximal almost disjoint families of subsets of $\omega$.
However, I have not seen anything concerning maximal incomparable families:
Let $\mathcal A$ be a family of subsets of $\omega$ that are both infinite and coinfinite.
We call $\mathcal A$ incomparable if the elements of $\mathcal A$ are pairwise incomparable with respect to the relation $\subseteq^*$ where $A\subseteq^*B$
if $A\setminus B$ is finite.  Note that both independent families and almost disjoint families are incomparable.
Question:  What is the minimal size of a maximal incomparable family of subsets of $\omega$?
I am guessing that this cardinal invariant is equal to $2^{\aleph_0}$ or equal to $\mathfrak i$, but mostly for psychological/social reasons:  It should have been looked at before, unless it is equal to one of the known invariants.

A: Michael Hrusak has recently answered my question:  The cardinal invariant that I am looking for is indeed $2^{\aleph_0}$.
We are looking for the minimal size of a maximal infinite family of pairwise incomparable elements of the Boolean algebra $\mathcal P(\omega)/fin$.  We can ask the same question for any infinite Boolean algebra $B$.  For a Boolean algebra $B$ and $b\in B$ let $B\upharpoonright b=\{a\in B:a\leq b\}$.  Let $d(B)$ be the minimal size of a dense subset of $B$.
The following is true for any infinite Boolean algebra $B$:  The minimal size of a maximal infinite family of pairwise incomparable elements of $B$ is at least $\min\{d(B\upharpoonright b):b\in B\setminus\{0\}\}$.  Note that in the case of $B=\mathcal P(\omega)/fin$ we have $d(B\upharpoonright b)=2^{\aleph_0}$ for all non-zero $b\in B$, hence this fact solves the original problem.
To see this fact, let $A$ be an infinite set of pairwise incomparable elements of $B$
of size $<\min\{d(B\upharpoonright b):b\in B\setminus\{0\}\}$ and let $a\in A$.  Since $A$ is infinite, both $a$ and $-a$ are different from $0$.
Let $\langle A\rangle$ denote the Boolean algebra generated by $A$.
Since $A$ is infinite, $\langle A\rangle$ is of the same size as $A$.  By the size of $A$,
there are $x\in B\upharpoonright -a$ and $y\in B\upharpoonright a$, both non-zero,
such that no non-zero element of $\langle A\rangle$ is below $x$ or $y$.
Let $a'=x\vee(a-y)$.  An easy computation shows that $a'$ is incomparable with all elements of $A$, showing that $A$ was not maximal.


text:
Q: Sonata User Admin - Custom field dependency I have extended the SonataAdmin class for FOSUser and added 2 custom fields (choice type from external data source): Company and Sector
I'd like to make Sector dependent on Company, so if the user selects a Company it filters the available Sectors.
I though about using FormEvents for filtering at page load, but I don't even know how to get the Company value of the current form.
Here is a part of my custom SectorType
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->addEventListener(FormEvents::PRE_SET_DATA
    , function(FormEvent $event) {
        $data = $event->getData();
        $form = $event->getForm();
        // Need to get the company value here if set
    });
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'choices' => $this->getSectors(),
    ));
}

public function getSectors()
{
    $sects = array();
    // Need to pass the selected company value to my getList
    // (which gets the list of sector as you can imagine)
    if (($tmp_sects = $this->ssrs->getList('Sector'))) {
        foreach ($tmp_sects as $sect) {
            $label = $sect['id'] ? $sect['label'] : '';
            $sects[$sect['id']] = $label;
        }
    }
    return $sects;
}

So the question is:
How to get the selected Company from my custom SectorType ?

After that I'll need to be able to refresh the Sector with Ajax, but that will be another question

A: I had a similar problem. I needed to create a sale entity that needed to be associated in a many to one relationship with an enterprise entity and a many to many relationship with services entities.  Here is the Sale Entity:
The thing is that services where available depending on the companies chosen.  For instance services a and b could only be provided to company x.  And services b and c could only be provided to company y.   So in my admin, depending on the chosen company I had to display the available services.  For these I needed to do 2 things:
First create a dynamic form with my sale admin, so that on the server side I could get the right services available for the company specified in my sale record.  And second, I had to create a custom form type for my company form element, so that when it was changed by the user on the client side, It would send an ajax request to get the right services for the company chosen.
For my first problem, I did something similar to what you were trying to achieve, but instead of creating an specific custom type for my services element, I added de event listener directly in the admin.
Here is the Sale entity:
/**
 *
 * @ORM\Table(name="sales")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class Sale
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
     public $id;
    /**
     * @ORM\ManyToOne(targetEntity="Branch")
     * @ORM\JoinColumn(name="branch_id", referencedColumnName="id", nullable = false)
     * @Assert\NotBlank(message = "Debe especificar una empresa a la cual asignar el precio de este exámen!")
     */
    private $branch;

    /** Unidirectional many to many
     * @ORM\ManyToMany(targetEntity="Service")
     * @ORM\JoinTable(name="sales_services",
     *      joinColumns={@ORM\JoinColumn(name="sale_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="service_id", referencedColumnName="id")}
     *      )
     * @Assert\Count(min = "1", minMessage = "Debe especificar al menos un servicio a realizar!")
     */
    private $services;

    public function __construct() {
        $this->services = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set branch
     *
     * @param Astricom\NeurocienciasBundle\Entity\Branch $branch
     */
     //default value always have to be null, because when validation constraint is set to notblank,
     //if default is not null, before calling the validation constraint an error will pop up explaining
     //that no instance of Branch was passed to the $branch argument.
    public function setBranch(\Astricom\NeurocienciasBundle\Entity\Branch $branch = null)
    {
        $this->branch = $branch;
    }

    /**
     * Get branch
     *
     * @return Astricom\NeurocienciasBundle\Entity\Branch
     */
    public function getBranch()
    {
        return $this->branch;
    }

     /**
     * Add service
     *
     * @param \Astricom\NeurocienciasBundle\Entity\Service|null $service
     */
    public function addServices(\Astricom\NeurocienciasBundle\Entity\Service $service = null)
    {
        $this->services[] = $service;
    }

    /**
     * Get services
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getServices()
    {
        return $this->services;
    }

    /**
     * Sets the creation date
     *
     * @param \DateTime|null $createdAt
     */
    public function setCreatedAt(\DateTime $createdAt = null)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * Returns the creation date
     *
     * @return \DateTime|null
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Sets the last update date
     *
     * @param \DateTime|null $updatedAt
     */
    public function setUpdatedAt(\DateTime $updatedAt = null)
    {
        $this->updatedAt = $updatedAt;
    }

So then in the Admin form builder:
protected function configureFormFields(FormMapper $formMapper)  {
    $em = $this->container->get('doctrine')->getEntityManager();
    $branchQuery = $em->createQueryBuilder();

    $branchQuery->add('select', 'b')
       ->add('from', 'Astricom\NeurocienciasBundle\Entity\Branch b')
       ->add('orderBy', 'b.name ASC');

    $formMapper
      ->with('Empresa/Sucursal')
         ->add('branch','shtumi_ajax_entity_type',array('required' => true, 'label'=>'Empresa/Sucursal','error_bubbling' => true, 'empty_value' => 'Seleccione una empresa/sucursal', 'empty_data'  => null, 'entity_alias'=>'sale_branch', 'attr'=>array('add_new'=>false), 'model_manager' => $this->getModelManager(), 'class'=>'Astricom\NeurocienciasBundle\Entity\Branch', 'query' => $branchQuery))
      ->end()
    ;

    $builder = $formMapper->getFormBuilder();
    $factory = $builder->getFormFactory();
    $sale = $this->getSubject();
    $builder->addEventListener(FormEvents::PRE_SET_DATA,
        function(DataEvent $event) use ($sale,$factory, $em) {

            $form = $event->getForm();
            $servicesQuery = $em->createQueryBuilder();
            $servicesQuery->add('select','s')
                ->add('from','Astricom\NeurocienciasBundle\Entity\Service s');

            if (!$sale || !$sale->getId()) {
                $servicesQuery
                    ->where($servicesQuery->expr()->eq('s.id', ':id'))
                    ->setParameter('id', 0);
            }
            else {
                $servicesQuery
                    ->join('s.branch', 'b')
                    ->where($servicesQuery->expr()->eq('b.id', ':id'))
                    ->setParameter('id', $sale->getBranch()->getId());
            }

            $form->add($factory->createNamed('services','entity',null,array('required' => true, 'label'=>'Servicios','error_bubbling' => true, 'attr'=>array('show_value_label'=>true),'class'=>'Astricom\NeurocienciasBundle\Entity\Service','multiple'=>true,'expanded'=>true,'query_builder'=>$servicesQuery)));
        }
    );
}

The trick thing was to pass the forms data.  It doesn't work to use evet->getData() in the event listener's function.  Instead I passed it through the admin->getSubject() method.  Then instead of adding a sonataadmin form type, inside the event listener's function, I had to use a plain symfony form type.
The Ajax part as you mentioned is another question. All the weird things on the branch add method in the form builder is related to a customized field type for this matter.  Don't worry about it.


text:
Q: PHP composer download signature validation I need to get PHP composer installed, but I'm not prepared to curl | php, and I want to validate the downloaded packages against a signature or checksum.
The download links on the site are the way I want to go.  The devs have also published their public keys on the site.  And there are package signatures available at ${download}.sig (found them by just looking for them), however I can't figure out how to verify with these signatures.
For example these are the current latest PHAR and sig files:

*

*https://getcomposer.org/download/1.0.0-beta1/composer.phar

*https://getcomposer.org/download/1.0.0-beta1/composer.phar.sig
The sig file contains:
{"sha384":"FGC1jaYN4TCnaaeha3aeHx1W8gn/GyBaNk09TEOxLXjhWdwFb7psJBtZgXEsrq1Sm0J91j3l2AZDWofQ1s1FHD6A4cZY5H2KQ7KleqIFmDWDVyASHc6tjvaPtlQJ4BCVJEOPsRHX2NTH1roCs48t7S+MbVj5j5K8oVggEw9IOG4uurABUiadOLj/gQ3UpXz1+oflkr358qCkQuUW2upMuHDto8BNLSDYrCLgct1i8aCTCgKo6BYMBGSZxQdGY/dDyRX6rHbR1/CzfJmECgA9qGgeXxDRyjFg/93wsQfuFPCijd6vTpRmsFKYpwfQXMult8t+0mPh4PcvX1GzKtYcLxmsA2MmyPVfX80KtGp2EF5ExRAxOqZtd3ZtwqqOxUeNUfESKrXif1v0PxVGlER4KX5MBvCH9UvwwUPOzyplJ8N+4ybtNGfHiOD3MpPsiVBVoWkQouI5qbHRT39kAGKfMQBDWounrwMGGQV2Ca2/bFMcnInYkXFyLD12yekluoktpBcyFyZcHOJXXbbMGeXLZn3cepBwneUPklB4Q6zkouIdCkZZIzyOkLp4XgCP55idmD+DNmeoaGNlqDJmN+2wTWQv5GBj9DEEXBFHZ5f4hfn6ZEYWO7GlgOz0YeijuknvtvdCR+Iqr3Vn72UKhtoBQd2L74YwzCG/4CBYhGtknMc"}

The body of this signature seems to be base64 encoded, but decoded it's too long to be an sha384 checksum.  It also doesn't appear to be a GPG signature.
How can I validate the package?

A: The sign script can be found on github and contains the following code:
openssl_sign(file_get_contents($_SERVER['argv'][1]), $sha384sig, $pkeyid, OPENSSL_ALGO_SHA384)
// ...
$sha384sig = trim(base64_encode($sha384sig), '=');

So the signature is indeed a base64 encoded sha384 checksum.

Please note that the installer used to download the composer phar does also check the signature. It's code can also be found on GitHub:
$signature = $httpClient->get($url.'.sig');
if (!$signature) {
    out('Download failed: '.$errorHandler->message, 'error');
} else {
    $signature = json_decode($signature, true);
    $signature = base64_decode($signature['sha384']);
}

// ...

if (false === $disableTls) {
    $pubkeyid = openssl_pkey_get_public('file://'.$home.'/' . ($version ? 'keys.tags.pub' : 'keys.dev.pub'));
    $algo = defined('OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 : 'SHA384';
    if (!in_array('SHA384', openssl_get_md_methods())) {
        out('SHA384 is not supported by your openssl extension, could not verify the phar file integrity', 'error');
        exit(1);
    }
    $verified = 1 === openssl_verify(file_get_contents($file), $signature, $pubkeyid, $algo);
    openssl_free_key($pubkeyid);
    if (!$verified) {
        out('Signature mismatch, could not verify the phar file integrity', 'error');
        exit(1);
    }
}


text:
Q: How to safely bypass tabs in RegEx I'm using C to do my regular expressions. Things work except for when the input string contains tabs.
This is my RegEx I plug into the regcomp function:
(DROP).*(tcp).*([\\.0-9]+).*0\\.0\\.0\\.0.*dpt:([0-9]+)(.*)

Regcomp returned OK with no issues.
I then used the following string to do the matching with:
DROP\ttcp\t--\t202.153.39.52\t0.0.0.0/0\ttcp dpt:21

I'm using such string to simulate output of iptables because I want to make a program to see which IPs are already listed.
When I execute my program, I receive the following pieces of output after executing the RegEx where the first line is data from the first offset:
DROP   tcp     --      202.153.39.52   0.0.0.0/0       tcp dpt:21
DROP
tcp
2
21

Everything is correct except the second-last value. It shows 2, but I expect it to be 202.153.39.52. and I used ([\\.0-9]+) in my RegEx to try to specifically state I only want numbers and dots to match.
How do I fix my RegEx?
UPDATE
I then proceeded to use this RegEx instead in hopes I get each individual octet of the IP address
(DROP).*(tcp).*([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+).*(0\\.0\\.0\\.0).*dpt:([0-9]+)

This is my result:
DROP   tcp     --      202.153.39.52   0.0.0.0/0       tcp dpt:21
DROP
tcp
2
153
39
52
0.0.0.0
21

Now this means the first ([0-9]+) isn't processing properly. I should receive a 202, not a 2. Is there something I'm doing wrong? Do I need a special flag for any RegEx function?

A: I think you're confused about the difference between regex syntax and that syntax encoded as a string (in languages like Java that don't have first class regexes).
Try something more robust and commonsense:
DROP\s+tcp\s+\S+\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+0\.0\.0\.0/0\s+tcp\s+dpt:(\d+)

This will capture the ip address and the port number only. Why would you want to capture a fixed string like DROP?
As a string, this is:
"DROP\\s+tcp\\s+\\S+\\s+(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s+0\\.0\\.0\\.0/0\\s+tcp\\s+dpt:(\\d+)"

Use an online regex tester like this one for testing and to convert from regex to string automatically.


text:
Q: Generating the System.ServiceModel configuration section for WCF Data Service client When I use the "Add Service Reference" utility in Visual Studio to connect to a WCF Data Service (OData), visual Studio doesn't generate an App.config file with the System.ServiceModel section for me. (The proxy class is generated fine). Is this normal?
Is there still a way to have this config generated automatically? The WCF service in question is secured and I therefore struggle with authentication issues if I try to to use the command line svcutil.exe with the /config option.

A: svcutil.exe cannot be used with WCF Data Services (OData), there's a datasvcutil.exe which is used instead.
The Add Service Reference for OData should not generate anything into your app.config as it doesn't need it. To use it, you just new up the generated context class and pass in the URI of the service.
If your OData endpoint required authentication though, the Add Service Reference doesn't support that though, so I'm surprised it works for you.


text:
Q: Put request to /api/controller/:id instead of /api/controller?id=:id I'm currently doing this:
[HttpPut]
public void Edit(int id, Model model)
{
    ...
}

Which gives me the endpoint /api/controller?id=66 instead of what I want: /api/controller/66

A: To get what you want -- api/controller/66 on your PUT request, your HTTP verb attribute should be modified to [HttpPut("{id}")]
And the further reason why your id is obtained from the query string by default is that the parameter binding in the case of PUT request works in such a way that the primitive type is bound from request query string and the complex type from request body.
A brief of the parameter binding rules is listed out in this answer.


text:
Q: Regex expression in apache configuration file I need to make sure that if a user hits "//" instead of "/", it should be handled by regex in apache config for some urls. For ex -
"http://www.mysite.com//home/index.jsp" URL should be redirected or treated as "http://www.mysite.com/home/index.jsp"
Can you please throw some light on what regex I should be using in the apache config to make sure this works perfectly?

A: Taken from this answer:

If you're using Apache with mod_rewrite, there is a pretty simple fix:
# remove multiple slashes anywhere in url
RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]

This will issue a HTTP 301 Moved Permanently redirect so that any double slashes are stripped out of the URL.


text:
Q: What is a good tool/method for version controlling a part of a live database? Sometimes if a database gets corrupted, a replicated database could also replicate that same corruption.
What is the best way to replicate/backup a database and prevent something like this from happening?
(specifically for MySQL)

A: If the "corruption" is at a level where it will be replicated, then the only solution is frequent backups and a good means of detecting such corruption so you can quickly recover.  You'd need to define how to detect the corruption based on your specific application, because from the database's point of view, everything is as it should be.

A: This covers everything you want in depth: http://dev.mysql.com/doc/refman/5.1/en/backup-methods.html
Basically, what you probably want is a slave that you can do daily and/or weekly full backups on, then do incremental backups by saving the binary logs since the full backup. You can re-play the binary logs to any command you want.

A: and to add more information about what opsguy said, there is a few scripts known as to replay binary logs and so, you can check maatkit documentation: http://www.maatkit.org/


text:
Q: Quagga bgp_accept code I am trying to understand what the following (code below) is doing, and am struggling to understand the concept of sockunions. Can anyone help me out? What has this got to do with threads and thread file descriptors?
Appreciate your help in advance, and would be open to any resources you can recommmend!
Sarah

static int
bgp_accept (struct thread *thread)
{
int bgp_sock;
int accept_sock;
union sockunion su;
struct bgp_listener *listener = THREAD_ARG(thread);
struct peer *peer;
struct peer *peer1;
char buf[SU_ADDRSTRLEN];

/* Register accept thread. */
accept_sock = THREAD_FD (thread);

    if (accept_sock < 0)
    {
    zlog_err ("accept_sock is nevative value %d", accept_sock);
    return -1;
    }

listener->thread = thread_add_read (master, bgp_accept, listener, accept_sock);

/* Accept client connection. */
bgp_sock = sockunion_accept (accept_sock, &su);
    if (bgp_sock < 0)
    {
...

A: bgp_accept is a self calling (thread_add_read) function.(read quagga thread concept don't confused with linux thread concept).
Every call of bgp_accept it will establish a tcp connection with other peers.


text:
Q: Replace a xml tag or change the value of a xml tag in java Iam new to java . Iam having my xml content as below
<Configuration>
    OFF
    OFF
    <C>OFF</C>
    <D>OFF</D>
    <E></E>
    <F>200</F>
    <AB>
         <G>10001</G>
         <H>10002</H>
         10003
         <J>10004</J>
    </AB>    .............    ......

I want to change the value of  tag to ON . How can i achieve this? I am using the below code
String config2=config;
if(config2.contains("OFF"))
{
    config2=config2.replace("OFF","ON");
    return config2;
}
else
{
    return true;
}

thanks in advance

A: Your method can not return two different types at same time.
return config2 in else part too if the return type of your method is String.
else
{
return config2;
}
If the string contains the chars then edit the config2 and return it else return same String without editing


text:
Q: Highcharts - gap between series in stacked area chart I've created a stacked area chart in Highcharts, which you can see in the image below and in the following jsfiddle: http://jsfiddle.net/m3dLtmoz/

I have a workaround for the gaps you see, which is to group the data for each series by month so that each series looks something like this instead:
    series: [{
        data: [
            [1464739200000,2471],
            [1467331200000,6275],
            [1470009600000,2574],
            [1472688000000,7221],
            [1475280000000,3228]
        ]}
    ]

While the above isn't exactly what I'm going for, the way the series above is structured does give me what I ultimately want, which is this:

I'm really dying to know why the original setup isn't working appropriately, however.  I've tested other instances where datetimes group and aggregate properly based on a single datetime x axis value.  I'm stumped as to why this particular data set isn't working.  I've tried using the dataGrouping option in the Highstock library, but wasn't able to integrate that effectively.  I've messed with options as far as tickInterval goes to no avail.  I tried setting the "stacking: 'normal' option in each series instead of in the plotOptions, but that made no difference.  I've seen issues on github dealing with the stacked area charts, but nothing seems to exactly match up with what I'm seeing.  Any help is appreciated - thank you much!

A: You receive the error in the console. Most of the series require data to be sorted in ascending order. Stacking has nothing do to it, see example.
Series which do not require data to be sorted are scatter or polygon. No error in scatter
You should sort and group the points on your own. If you want to group them by months you have to prepare the data before you put them in a chart. The example below takes averages from the same datetime.
function groupData(unsortedData) {
    var data = unsortedData.slice();
    data.sort(function (a, b) {
      return a[0] - b[0]
    });

    var i = 1,
      len = data.length,
      den = 1,
      sum = data[0][1],
      groupedData = [[data[0][0], sum]],
      groupedData = [];

  for (; i < len; i++) {
    if (data[i - 1][0] === data[i][0]) {
      sum += data[i][1];
      den++;
    } else {
      groupedData.push([data[i - 1][0], sum / den]);
      den = 1;
      sum = data[i][1];
    }
  }

  groupedData.push([data[i-1][0], sum / den]);
  return groupedData;
}

example: http://jsfiddle.net/e4enhw9a/1/


text:
Q: elasticsearch: optimal performance for searching over lots of fields? We are using elasticsearch with rails using the retire gem. Currently we index lots of fields (30+) of which only 6 are currently full text searchable (user name, user email, user title, etc.).
We want to move towards all fields being searachable. So, instead of just those 6 main fields being searchable all 30 (and potentially more) are searchable. By searchable I mean exact matches, prefixes, fuzzy matching and substring matches.
There are two strategies we are considering:
1) Index each field individually using a correct analyzer and tokenizer (already have that part figured out) to meet the searchability requirements desired.
2) Create an indexed text blob of all other fields and index that blob as a whole.
I am curious what the trade-offs are for the two above solutions. We are looking for:
1) Decent write performance. Our objects change often (this is an index of searchable users with profiles).
2) Ease of adding new fields to the index over time.
3) Of course, read performance.


text:
Q: JavaScript: Tips on how to use onblur to get info from another server and auto populate other textbox entries? I'm trying to make a web page using primarily HTML, CSS and JavaScript (I'm fairly new to making websites, so these are the only three I am fairly decent with). This web page will be a form that will interface with an enterprise software (BMC Remedy ITSM) that will enforce validation and make all of our tickets precise when submitted.
One of the few static textboxes on the web page will be an ID number field, a full-name field and a phone-number field.
My goal is to have the user put in their ID number, and have this ID number communicate with the enterprise software, look up the ID number, and auto-populate the full name and phone number from the ID number given.
I want this to be a lostfocus event on the ID number textbox, so therefore I guess it would be under onblur for JavaScript.
Can someone chime in and give me some pointers on how I would achieve this?
Thanks!

A: A quick example of using the blur event is below in pure JavaScript. Top example shows JSON return and bottom example shows XML.
Fiddle: http://jsfiddle.net/9dpxmpru/2/
HTML:
<input id="empid" type="text" placeholder="Employee ID" />
<input id="name" type="text" placeholder="Full Name" />
<input id="phone" type="text" placeholder="Phone" />

JS:
var empid = document.getElementById('empid');
empid.addEventListener('blur',
    function (event) {
        var idVal = this.value;
        // make some ajax call
        // perhaps it returns this
        var response = {
            name: "John Doe",
            phone: "555-5555"
        };
        var name = document.getElementById('name');
        var phone = document.getElementById('phone');
        name.value = response.name;
        phone.value = response.phone;
    }, true
);

As for the ajax call you can do something like this:
// Make Ajax Call
var requestObject = new XMLHttpRequest();
requestObject.open('POST', 'someurl', true);
requestObject.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
// XML: requestObject.setRequestHeader('Content-Type', 'text/xml');
requestObject.onload = function () {
    if (this.status >= 200 && this.status < 400) {
        // Success!
    }
    else {
        // Handle some server error
    }
};
requestObject.onerror = function () {
    // Handle some server error
};
requestObject.send(JSON.stringify('idValueFromField'));

This is of course very rough but the general idea.
Here is fiddle parsing xml: http://jsfiddle.net/9dpxmpru/4/
var empid = document.getElementById('empid');
empid.addEventListener('blur',
    function (event) {
        var idVal = this.value;
        // make some ajax call
        // perhaps it returns this
        var response = "<response><name>John Doe</name><phone>555-5555</phone></response>";
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(response, 'text/xml');
        var name = document.getElementById('name');
        var phone = document.getElementById('phone');
        name.value = xmlDoc.getElementsByTagName('name')[0].childNodes[0].nodeValue;
        phone.value = xmlDoc.getElementsByTagName('phone')[0].childNodes[0].nodeValue;
    }, true
);

jQuery Examples:
$("#empid").on("focusout",
    function (event) {
        var idVal = $(this).val();
        // make some ajax call
        // perhaps it returns this
        var response = {
            name: "John Doe",
            phone: "555-5555"
        };
        $("#name").val(response.name);
        $("#phone").val(response.phone);
    }
);

jQuery Ajax:
$.ajax({
    method: "POST",
    url: "someurl",
    dataType: 'json',
    // XML: dataType: 'xml',
    data: {
        empid: idVal
    }
}).done(
    function (msg) {
        // success!
    }
);

jQuery XML example:
$("#empid").on("focusout",
    function (event) {
        var idVal = $(this).val();
        // make some ajax call
        // perhaps it returns this
        var response = "<response><name>John Doe</name><phone>555-5555</phone></response>";
        var xmlDoc = $.parseXML(response),
        var xml = $(xmlDoc),
        $("#name").val(xml.find("name").text());
        $("#phone").val(xml.find("phone").text());
    }
);

A: As far as your idea goes, you're on the right track. But since you said you're newer to web development, I'll explain more. You're going to have a text input that listens for a blur. The blur event will then send an XMLHttpRequest to your ITSM software, supplying a response handler that will execute as soon as the request completes.
If you haven't looked into it yet, and if you have the option, I would suggest jQuery, because it provides traversal functionality for HTML that also [mostly] works on XML. It'll also make your calls a bit easier.
HTML:
<input id="employeeId" type="text" placeholder="Employee ID">
<input id="fullName" type="text">
<input id="phone" type="text">

Assuming your XML is something like this:
<lotsOfResponseParentNodes>
      <person>
          <fullName>John Doe</fullName>
          <phoneNumber>5555551212</phoneNumber>
      </person>
</lotsOfResponseParentNodes>

JavaScript (place at bottom of body):
function setFieldVals(fullName, phoneNumber) {
  $("#phone").val(phoneNumber);
  $("#fullName").val(fullName);
}

$("#employeeId").blur(function(e) {
  $.ajax({
    type: "POST",    //or GET, depending on your api spec
    url: ENDPOINT_URI,  //Again, depending on your software
    data: {employeeId: $(e.target).val()}
    dataType: "xml",
    success: function(xml) {
      setFieldVals($(xml).find("fullName").text(), $(xml).find("phoneNumber").text());
    },
    error: function() {
      alert("An error happened.");
    }
  });
});

What's key here is how you're parsing your XML. In the XML example I have above, find("nodeName") works. But if the XML were, say, <person phone="xxx"> then you'd have to $(xml).find('person').attr('phone') instead.


text:
Q: tag-it selection issue using mouse on bootstrap modal pop up I have two forms use tag-it auto complete. One sit in a page, and one in modal box. Both are calling the same array list and have same target class. The one in the page works beautifully. However, the one in modal box has weird issue: when I use mouse to select tag from drop down list, it always put first letter in the input box with highlight but I am able to select item using down arrow key.
May I request for any solution for the same.

A: do you have a sample of your code please to have a look at it ?
Can do nothing without it :)


text:
Q: AWS SES python sqs.receive_message returning only one message output I am using amazon ses python sdk to see how many messages are there in the queue for a given queue URL. in amazon GUI console i can see there are 3 messages within the queue for the queue URL. However i do not get more than 1 message as output everytime i run the command. Below is my code
import boto3
import json
from botocore.exceptions import ClientError

def GetSecretKeyAndAccesskey():
    #code to pull secretkey and access key
    return(aws_access_key,aws_secret_key)
# Create SQS client
aws_access_key_id,aws_secret_access_key = GetSecretKeyAndAccesskey()
sqs = boto3.client('sqs',aws_access_key_id=str(aws_access_key_id),aws_secret_access_key=str(aws_secret_access_key) ,region_name='eu-west-1')

response = sqs.receive_message(
    QueueUrl='my_queue_url',
    AttributeNames=[
        'All',
    ],
    MaxNumberOfMessages=10,

)
print(response["Messages"][0])

Every time i run the code i get a different message id, and if i change my print code to check for the next list i get list index out of bound meaning that there is only one message
print(response["Messages"][1])

C:\>python testing.py
d4e57e1d-db62-4fc5-8233-c5576cb2603d

C:\>python testing.py
857858e9-55dc-4d23-aead-3c6622feccc5

A: First, you need to add "WaitTimeSeconds" to turn on long polling and collect more messages during a single connection.
The other issue is that if you only put 3 messages on the queue, they get separated on the backend systems as part of the redundancy of the AWS SQS service.  So when you call to SQS, it connects you to one of the systems and delivers the single message that's available.  If you increase the number of total messages, you'll get more messages per request.
I wrote this code to demonstrate the functionality of SQS and allow you to play around with the concept and test.
import json

session = boto3.Session(region_name="us-east-2", profile_name="dev")
sqs = session.client('sqs')

def get_message():
    response = sqs.receive_message(QueueUrl='test-queue', MaxNumberOfMessages=10, WaitTimeSeconds=10)
    return len(response["Messages"])

def put_messages(seed):
    for message_number in range(seed):
        body = {"test": "message {}".format(message_number)}
        sqs.send_message(QueueUrl='test-queue', MessageBody=json.dumps(body))

if __name__ == '__main__':
    put_messages(2)
    print(get_message())


text:
Q: How to remove the highlighting bar when typing code in Netbeans 11? In Apache Netbeans 11.1, I use Nimbus and Netbeans light theme. This light theme has a problem that I find really annoying.
As shown in pictures below, when I type pub (for public) and stop half way, the row turns black, which makes the code not readable. If I finish the public keyword, the row will turn to a color set at Highlight Caret Row.
So how can I remove the black row when typing?
When Typing:

Finished:

A: I found the answer. It's quite simple but I did not look up carefully. So here is the trick.
This black color bar comes from the Fixable Error of Annotations. So just changing the background of this Fixable Error category from dark color to any color will do the work. (Have to close and re-open the code editor to see the change) .
Here I changed to white background, and it's gone.

A: Try playing with these settings:

*

*Auto Popup Completion Window

*Auto Popup Documentation Window

*Display Documentation Next to Completion


text:
Q: How to instantiate a HttpPostedFile I'm trying to communicate with a system which I have no control over, however one of its methods takes in a HttpPostedFile were in my code I have a byte array. Does anybody have an example of instantiating a HttpPostedFile as I know its constructor is internal?
The best I've found is Creating an instance of HttpPostedFile with Reflection which uses reflection, however they were steered into another direction which I can't take because I am unable to modify the third party systems method signature.

A: you can try
 var constructorInfo = typeof(HttpPostedFile).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
 var obj = (HttpPostedFile)constructorInfo
           .Invoke(new object[] { "filename", "image/jpeg", null });

obj would of type HttpPostedFile .I'm setting the last parameter to null but it has to be a HttpInputStream though.

A: This is really really hacky code, but the following seems to work for me:
public HttpPostedFile ConstructHttpPostedFile(byte[] data, string filename, string contentType) {
  // Get the System.Web assembly reference
  Assembly systemWebAssembly = typeof (HttpPostedFileBase).Assembly;
  // Get the types of the two internal types we need
  Type typeHttpRawUploadedContent = systemWebAssembly.GetType("System.Web.HttpRawUploadedContent");
  Type typeHttpInputStream = systemWebAssembly.GetType("System.Web.HttpInputStream");

  // Prepare the signatures of the constructors we want.
  Type[] uploadedParams = { typeof(int), typeof(int) };
  Type[] streamParams = {typeHttpRawUploadedContent, typeof (int), typeof (int)};
  Type[] parameters = { typeof(string), typeof(string), typeHttpInputStream };

  // Create an HttpRawUploadedContent instance
  object uploadedContent = typeHttpRawUploadedContent
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, uploadedParams, null)
    .Invoke(new object[]{data.Length, data.Length});

  // Call the AddBytes method
  typeHttpRawUploadedContent
    .GetMethod("AddBytes", BindingFlags.NonPublic | BindingFlags.Instance)
    .Invoke(uploadedContent, new object[] {data, 0, data.Length});

  // This is necessary if you will be using the returned content (ie to Save)
  typeHttpRawUploadedContent
    .GetMethod("DoneAddingBytes", BindingFlags.NonPublic | BindingFlags.Instance)
    .Invoke(uploadedContent, null);

  // Create an HttpInputStream instance
  object stream = (Stream)typeHttpInputStream
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, streamParams, null)
    .Invoke(new object[] {uploadedContent, 0, data.Length});

  // Create an HttpPostedFile instance
  HttpPostedFile postedFile = (HttpPostedFile)typeof(HttpPostedFile)
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null)
    .Invoke(new object[] {filename, contentType, stream});

  return postedFile;
}


text:
Q: return sub-directory name using PHP
Possible Duplicate:
PHP Get all subdirectories of a given directory

Is it possible to do this, using PHP and/or Jquery/Javascript:
1) open one folder from,say, a List-menu, then
2) select the sub-folder inside it.
I do not need the contents, but just the sub-folder name only.
Any help will be greatly appreciated!

A: Yes, it is possible. No, not via javascript (at least not when you want to get folderlistings from a machine which is not same as the client). This can be achieved by PHP. See http://www.php.net/manual/en/function.opendir.php. By using is_dir() you can check if a file in a dir is a dir.
Note, if you want to get all subfolders from a certain folder you should create a function to get the folders from a folder (as mentioned above). Then use this function recursively each time you find a folder within the folder you're searching. See for example What is a RECURSIVE Function in PHP?

A: this may be helpful
if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";

    /*  to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }
}

also
$dir    = '/tmp';
$files1 = scandir($dir);
list all files and folders in side tmp


text:
Q: I want to send a confirmation email when a user attempts to change their email address within my MVC3 application . . . but I am not sure of the proper work-flow to make this happen.
I already send a confirmation email to the user's email address when they register - they are marked as 'inactive' until they click a link they receive in their email.
I want my users to be able to change their email when they please, and currently they can, but I would also like to be able to confirm the email address by having the user receive an email at their new email address with a link they have to click before the email change happens.
What is the proper work-flow to get this to happen?


text:
Q: How can I get my countdown timer, to stop starting over every time i refresh in JavaScript Hi guys thank you for your time , and sorry i'm kind of new.
So i have this JavaScript file in my html work ,its suppose to be a countdown (kind of timer ) .
i want it to be ( the time left till 3 June ) but i allays get the same result or not result at all . every time i refresh the browser the counter start again .I been looking videos on YouTube to try to find a way to change that but it only get worst . i have looking to other question here too but the answers are always a different code i would like to know if i can modify this one to do so
pleas don't be to hard on me i only have 32 points i don't want to lose my right to vote and down vote
,this is the code and thanks in advance .

Days

Hours

Mins

Secs

A: The date you're counting down to is always being incremented whenever the page loads, because it's initialized to the current time plus an offset:
var target_date = new Date().getTime() + (1000*3600*772)

Use an absolute date instead of a relative time:
var target_date = new Date('June 3 2018');
// or
var target_date = new Date(2018, 6, 3);

A: Because the target_date variable is Dynamic so the countdown will always be the same.
The first line to:
var target_date = new Date("01,06,2018").getTime();

A: First, note that you have several errors in your code; and there are also some improvements that can be done to improve the question as well:

*

*The HTML is not valid.

*The target date is being initialized with the current time plus a constant offset into the future -- so you always see the same counter at every refresh.

*The scope of several variables can be reduced -- always a good idea.

*No need for pad to show the problem of your code (always strive for minimal examples).

*As a general rule, you should avoid adding elements using innerHTML -- if you manage to do so, you will be able to use textContent to just edit the contents of existing elements.

*The timer should be at least as low as half of that of the smallest time increment (in this case, a second) -- otherwise you will miss updates (i.e. you will see jumps in time that skip one full second).
A simplified, corrected version of your snippet is:

function getCountdown() {
  let target_date = new Date("June 3, 2018");
  let current_date = new Date();
  let seconds_left = (target_date - current_date) / 1000;

  let days = parseInt(seconds_left / 86400);
  seconds_left = seconds_left % 86400;

  let hours = parseInt(seconds_left / 3600);
  seconds_left = seconds_left % 3600;

  let minutes = parseInt(seconds_left / 60);
  let seconds = parseInt(seconds_left % 60);

  document.getElementById("tiles").textContent =
    days + " days, " +
    hours + " hours, " +
    minutes + " minutes and " +
    seconds + " seconds";
}

setInterval(function() {
  getCountdown();
}, 500);


text:
Q: yeoman: automatically install npm modules I've created a yeoman generator.
Once I've created a project scaffold using my generator, I run the command "npm install grunt-contrib-watch grunt-contrib-connect"
I've been following the doc here: http://yeoman.io/generators.html
It seems to indicate that npm dependencies can be installed automatically. But I can't quiet figure out how to make this happen.
So, how do I define npm depencies in my generator, so that the node modules get installed automatically when the scaffold gets created?

A: You can generate a package.json as part of your scaffolding just as any other file. It can even contain template markup, as in generator-webapp.
If you scaffold out a package.json in the root directory of your generated project, you can run installDependencies() of the generator object at the end:
this.on('end', function () {
  this.installDependencies();
});

This will take care of installing bower and npm dependencies that the project declares.


text:
Q: Unable to removeEventListener in angular directive I'm trying to prevent the whole page from reloading when I press f5.
I have created a directive that when pressing f5 a button is clicked, this works, however I am not able to remove this event
https://stackblitz.com/edit/angular-wpok2b
HTML:
<button appClickf5 disabled *ngIf="show">will be clicked if f5</button>

<button (click)="show = !show">toggle init/destroy</button>

Directive:
import { Directive, ElementRef, OnDestroy, OnInit } from '@angular/core';

@Directive({
  selector: '[appClickf5]'
})
export class Clickf5Directive  implements OnInit, OnDestroy {

  constructor(private _el: ElementRef) { }

  ngOnInit() {
    this.log("init")
    document.addEventListener("keydown", this.callback.bind(this));
  }

  ngOnDestroy() {
    this.log("ngOnDestroy")
    document.removeEventListener("keydown", this.callback.bind(this));
  }

  callback(e: KeyboardEvent) {
    if ((e.code === "F5" || e.key === "F5") && e.ctrlKey === false) {
      e.preventDefault();
      this._el.nativeElement.click();
      this.log("element clicked");
    }
  }

  private log(txt){
    document.getElementById("output").innerHTML+="
"+txt;
  }
}

Any idea?

A: It's easier to achieve that with a reactive approach:
@Directive({
  selector: '[appClickf5]',
})
export class Clickf5Directive implements OnInit, OnDestroy {
  private destroyed$: Subject<void> = new Subject();

  constructor(private _el: ElementRef) {}

  public ngOnInit() {
    fromEvent(document, 'keydown').pipe(
      filter(
        (e: KeyboardEvent) =>
          (e.code === 'F5' || e.key === 'F5') && e.ctrlKey === false
      ),
      tap((e: KeyboardEvent) => {
        e.preventDefault();
        this._el.nativeElement.click();
      }),
      takeUntil(this.destroyed$)
    ).subscribe();
  }

  public ngOnDestroy() {
    this.destroyed$.next();
    this.destroyed$.complete();
  }
}

I've made a live demo with rxjs only, for the first 5 seconds it does catches the events and prevent the refresh. After 5s you can refresh the page:
https://stackblitz.com/edit/rxjs-rfylfi?file=index.ts
To try it, you have to use:

otherwise the stackblitz app will be reloaded, not the app itself


text:
Q: Laplacian in polar coordinates (idea) As we know using chain rule, we can compute the Laplacian in polar coordinates: for $u=u(r,\theta)$ it holds
$$\Delta u=u_{rr}+\frac{1}{r}u_r+\frac{1}{r^2}u_{\theta \theta}$$
There is something behind this formula that I don't get. If we forget about Cartesian coordinate system and transformation formulas, considering $u=u(r,\theta)$ "independently" then why shouldn't we have $\Delta u=u_{rr}+u_{\theta \theta}$. Isn't this how the Laplacian is defined? What fails here? Thank you.

A: The Laplacian is initially defined in Cartesian coordinates. If you switch to polar coordinates, then you are still dealing with the same operator, so you need to use the chain rule to get a form which only involves derivatives with respect to $r$ and $\theta$. Thus the operator $u \mapsto u_{rr} + u_{\theta \theta}$ is completely different from the Laplacian. It's also a pretty physically useless operator, because usually $r$ has units of length, so usually $u_{rr}$ and $u_{\theta \theta}$ have different units, and therefore cannot be added.
It is a bit confusing that we use the same name for the function $u$ in Cartesian and polar coordinates. But the two are not actually the same mathematical function (even though they represent the same physical quantity in different coordinate systems). Using the same name is really an abuse of notation. If we were being really precise, we would introduce $w(r,\theta)=u(r \cos(\theta),r \sin(\theta))$. Here $w$ is "the polar coordinate representation of $u$". Then the chain rule is really telling us that
$$\Delta u(r \cos(\theta),r\sin(\theta)) = w_{rr}(r,\theta) + \frac{1}{r} w_r(r,\theta) + \frac{1}{r^2} w_{\theta \theta}(r,\theta).$$