text:
Q: Pegar uma variável de dentro de uma função Como consigo pegar uma variável de dentro de uma função.
meu código:
 function buscaGeralPessoas($buscaPessoas){
    $result_msg_contatos2 = "Select idGeralPessoas, cpf, nome, telefone1, telefone2, celular, email  from geralPessoas where idGeralPessoas in  ('$buscaPessoas')";

    $inforGeral = "";

    $resultado_msg_contatos2 = mysqli_query($conn, $result_msg_contatos2);
    while ($row_msg_contatos2 = mysqli_fetch_assoc($resultado_msg_contatos2)) {

        $idGeralPessoas = $row_msg_contatos2['idGeralPessoas'];
        $nome = $row_msg_contatos2['nome'];
        $telefone = isset($row_msg_contatos2['telefone1']) ? $row_msg_contatos2['telefone1'] : $row_msg_contatos2['celular'];
        $celular = isset($telefone) ? $telefone : $row_msg_contatos2['telefone2'];
        $email = $row_msg_contatos2['email'];
        $cpf = $row_msg_contatos2['cpf'];

        $inforGeral .= "ID: $idGeralPessoas, Nome: $nome, CPF: $cpf, Celular: $celular, Email: $email \n";

Nesse caso, eu preciso retornar a variavel $inforGeral, fora da minha função.

A: Ao final da sua função, após o fim do while, escreva a linha:
return $inforGeral;

Dessa forma, no local em que você chama a função, você consegue receber a sua variável dessa forma:
$inforGeral = buscaGeralPessoas($buscaPessoas);


text:
Q: MYSQL command line, import command override current database? If I use command
mysql -u root -pdb_pass testdb < database.sql

I was wondering if a database which already exist and has data, does it override current database? Or must to DROP DATABASE (and create it) before to import SQL? For example: I have database_one (origin) and database_two (copy of database_one), I want to update my database_two, but on database_one I created and edited some tables and indices/foreign keys and columns. If on database_two the table already exist does it create the new column which I created on database_one (or FK...)?

A: this is based on the sql in database.sql.
if it has drop database sql in it,it will doing drop database.
I suppose the database.sql is created by mysqldump,typically it will not include drop database sql.
but in case it has drop database,you could open the sql with editor check on it.
for tables,has the same logic with database,but typically it would drop table.
actually database.sql from mysqldump is purely sql we known,there is no mystery in it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lambda method is not getting called in the python program I am working on a project based on GUI working on python. In the button command on passing the method of the self class there is no effect i.e the method is not getting called. there is no compile time or runtime error showing up because of which it is very difficult to identify the problem. The source code is:
class PageTwo(tk.Frame):
def e_detail(self):
    soh_registeration.insert(u1.get(),p1.get(),s1.get(),m1.get(),em1.get(),ad1.get())
    messagebox.showinfo("DETAIL STORED", "YOUR INFORMATION IS STORED SECURELY")

def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    label = tk.Label(self, text="REGISTERATION DETAILS", font=LARGE_FONT)
    label.grid(pady=10,padx=10)
    label1 = tk.Label(self, text="USERNAME", font=TEXT)
    label1.grid(row=3,column=0)
    labelp = tk.Label(self, text="PASSWORD", font=TEXT)
    labelp.grid(row=4,column=0)
    cpdl = tk.Label(self, text="CONFIRM PASSWORD", font=TEXT)
    cpdl.grid(row=5,column=0)
    shopl = tk.Label(self, text="SHOP NAME", font=TEXT)
    shopl.grid(row=6,column=0)
    cl= tk.Label(self, text="MOBILE NO.:", font=TEXT)
    cl.grid(row=7,column=0)
    el = tk.Label(self, text="E-MAIL ID", font=TEXT)
    el.grid(row=8,column=0)
    al = tk.Label(self, text="AADHAR DETAIL", font=TEXT)
    al.grid(row=9,column=0)

    global u1,p1,p2,s1,m1,em1,ad1,button2
    u1=tk.StringVar()
    username= tk.Entry(self,textvariable=u1, bd=5)
    username.grid(row=3,column=1)

    p1=tk.StringVar()
    pd= tk.Entry(self,show='*',textvariable=p1, bd=5)
    pd.grid(row=4,column=1)

    p2=tk.StringVar()
    confpd= tk.Entry(self,show='*',textvariable=p2, bd=5)
    confpd.grid(row=5,column=1)

    s1=tk.StringVar()
    sn= tk.Entry(self,textvariable=s1, bd=5)
    sn.grid(row=6,column=1)

    m1=tk.StringVar()
    cn= tk.Entry(self,textvariable=m1, bd=5)
    cn.grid(row=7,column=1)

    em1=tk.StringVar()
    email= tk.Entry(self,textvariable=em1, bd=5)
    email.grid(row=8,column=1)

    ad1=tk.StringVar()
    an= tk.Entry(self,textvariable=ad1, bd=5)
    an.grid(row=9,column=1)

    button2 = tk.Button(self, text="SUBMIT YOUR DETAILS",
                        command=lambda: self.e_detail)
    button2.grid(row=10, column=0, padx=20, pady=20)

as the source code is too long the two blocks where i am finding the problem are mentioned below separately too:
def e_detail(self):
    soh_registeration.insert(u1.get(),p1.get(),s1.get(),m1.get(),em1.get(),ad1.get())
    messagebox.showinfo("DETAIL STORED", "YOUR INFORMATION IS STORED SECURELY")

and:-
 button2 = tk.Button(self, text="SUBMIT YOUR DETAILS",
                        command=lambda: self.e_detail)
 button2.grid(row=10, column=0, padx=20, pady=20)

i guess the problem would be very basic. I am still new to python programming someone please help me out.

A: The problem seems to be that self.e_detail is not called.
, command=lambda: self.e_detail

basically tells the button to call an anonymous method that mentions a method named self.e_detail. Instead make it call the method by replacing it with:
, command=lambda: self.e_detail()

or since the method is not passed any arguments, simply:
, command=self.e_detail


text:
Q: What's the benefit of using numbers as properties in a javascript object initialization? I'm learning javascript and after reading a tutorial on how to initialize an object, I found the following example:
var obj = {  property_1: value_1,   // property_# may be an identifier...
                      2: value_2,   // or a number...
                                    // ...,
           "property n": value_n }; // or a string

My doubt is in the property with a number as a name. I understand this, but I can't find a real benefice of using it. I read this question and, from my point of view, this kind of notation could lead to bad design or an unnecessary complexity in my code, so I would like to know why this syntax exist.
Do this kind of declaration is used frequently? In what kind of scenarios this could be an ideal alternative?

A: Arrays
JavaScript arrays are objects where some of the keys are integers(*).
[9, 8, 7] is similar to an object { 0: 9, 1: 8, 2: 7 }.
The main difference is that the array has a prototype of Array.prototype instead of Object.prototype.
(*) As Benjamin Gruenbaum points out, the array keys are coercible to UInt32. Keys of objects are always either strings or symbols. And as djechlin points out, arrays are allowed to have properties with any kind of key, but I do not recommend adding your own non-integer keys on an array.
Arguments
An array-like object called arguments is available within any function (*). Each argument received by the function will be a property on arguments, with an integer-like key.
In the following code, the example call returns an object like { 0: 9, 1: 8, 2: 7, length: 3 }.
function example(a, b, c) {
    return arguments;
}
example(9, 8, 7);

(*) In modern JavaScript, there is no arguments object in arrow functions.

A: Using integers as object keys is useful when creating sparse arrays and matrices, for instance mapping a 1000 element vector with 0 everywhere except the 10th element as
v = {10: 1}

JS arrays cannot be used here since you need to be able to specify the element position using the key.
In ECMAscript 6 using [Map]1 is better since it is actually made to be a mapping, but in codebases based on older ES standards, you would probably still see object being used for mappings like these.

A: That code is contrived to make the point.  But, since you asked for an example where it could be used, let me give you a couple.

*

*It can happen that if you receive JSON formatted data it will be like
this. Depends on details of the external system.

*Another might be for consistency.  E.g. suppose you had a data model
from which you would generate your HTML.  It might be that is uses
objects for the possible values for each field (assuming the field
can only take one of a number of possible values).  These fields
could then be rendered as radio buttons or as a select.  Some of
these fields will use strings as possible values, so the natural
thing is tyo make the possible values list into an object.  But some
will use integer keys - still probably better to stick to the list
always being an object.
E.g.
var prio_field_pos_vals = {
  0: 'Show Stopper',
  1: 'Urgent',
  2: 'High',
  3: 'Low'
}

Of course, this would probably not be defined as a standalone variable but as part of a model, but you get the idea.  I would avoid integer keys (and keys with spaces in the string) for objects unless you have a reason for them, but when you have a reason, use them.


text:
Q: Making a Linq query more efficient (.Net Core) This query produces a group data by month for a javascript graph. The API calling this query currently takes about 6 seconds to run if there are 3 or 4 years of data to group.
Is there a way to make this query more efficient?
pp3 is a list of projects and zz is the project budget data by day.
public static IQueryable<CombinedProjectFinancialSummary_Min> planned_bargraph(IQueryable<int> pp3, OneView_PPM db)
{
    var planned = from c in
                    (from x in pp3
                     join z in db.BudgetProfile on x equals z.ProjectRef
                     join bc in db.BudgetConfigs on z.ID equals bc.BudgetProfileId
                     join zz in db.Budgets on bc.Id equals zz.ConfigId
                     select new { SortDate = zz.MDate, Amount = zz.Cost }).ToList()
                     group c by
                              new { year = c.SortDate.Year, month = c.SortDate.Month }
                     into grp
                     select new CombinedProjectFinancialSummary_Min
                                {
                                    year = grp.Key.year,
                                    month = grp.Key.month,
                                    monthName = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(grp.Key.month),
                                    xSeries = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(grp.Key.month) + " " +  grp.Key.year,
                                    Amount = grp.Sum(t => t.Amount)
                                };

    return planned.AsQueryable();
}

Hoping to get this down to 2 or 3 seconds.

A: I've ended up reducing the query time by removing one of the joins
join z in db.BudgetProfile on x equals z.ProjectRef

This cut the execution time from 7 seconds to 1.5 seconds.


text:
Q: Cassandra performance on distinct query In Cassandra , I read that I need to design my table schema such that minimum number of partitions are hit. I have designed the schema to meet this requirement. But I am in a scenario where I need to get all the partition keys alone. So I am planning to use
Select Distinct <partitionKeys> from table
I ran a distinct query using cqlsh for around 15k rows .It was quite fast.
Questions

*

*Will there be any performance issues if I use distinct ?

*How cassandra fetches partition keys alone ?

*I need to know the limitations on distinct query.

A:
Will there be any performance issues if I use distinct?  How cassandra fetches partition keys alone?

Basically, Cassandra just has to rip through the nodes and pull back the partition (row) keys for that table.  Querying by these keys is how Cassandra was designed to work, so I am not surprised that this performed really well for you.  The drawback, is that it will probably have to hit all or most of your nodes to complete the operation, so performance could be slow if you have a large number of nodes.
This is where the difference between CQL rows and rows in the underlying storage comes into play.  If you look at your data with the cassandra-cli tool, you can see how partition keys are treated differently.  Here is an example where crew members of a ship are stored in a table, by their ship.
aploetz@cqlsh:presentation> SELECT * FROm shipcrewregistry ;

 shipname | lastname  | firstname | citizenid                            | aliases
----------+-----------+-----------+--------------------------------------+--------------------------------------
 Serenity |      Book |    Derial | 48bc975a-c9f2-474d-8a29-247503445877 |                       {'CLASSIFIED'}
 Serenity |      Cobb |     Jayne | 2d643fb1-54fb-4c98-8d2d-a5bb9c6c8354 |                   {'Hero of Canton'}
 Serenity |      Frye |    Kaylee | d556cf44-348b-4ea3-8c19-ba9d4877818c |                                 null
 Serenity |     Inara |     Serra | a25b7e02-8099-401a-8c41-d9d2ea894b72 |                                 null
 Serenity |  Reynolds |   Malcolm | 169382b7-21b0-47bf-b1c8-19bc008a9060 |             {'Mal', 'Sgt. Reynolds'}
 Serenity |       Tam |     River | af68201f-4135-413e-959c-dd81ea651e52 |                                 null
 Serenity |       Tam |     Simon | aa090e1a-7792-4d7b-bba9-bac66f8c1f15 |                          {'Dr. Tam'}
 Serenity | Washburne |     Hoban | 73f591df-c0dc-44c4-b3f3-9c37453c9537 |                             {'Wash'}
 Serenity | Washburne |      Zoey | 46bc77ad-53ad-4402-b252-a0543005c583 | {'Corporal Alleyne', 'Zoey Alleyne'}

(9 rows)

But when I query within the cassandra-cli:
[default@presentation] list shipcrewregistry;
Using default limit of 100
Using default cell limit of 100
-------------------
RowKey: Serenity
=> (name=Book:Derial:48bc975a-c9f2-474d-8a29-247503445877:, value=, timestamp=1424904853420170)
=> (name=Book:Derial:48bc975a-c9f2-474d-8a29-247503445877:aliases:434c4153534946494544, value=, timestamp=1424904853420170)
=> (name=Cobb:Jayne:2d643fb1-54fb-4c98-8d2d-a5bb9c6c8354:, value=, timestamp=1424904853492976)
=> (name=Cobb:Jayne:2d643fb1-54fb-4c98-8d2d-a5bb9c6c8354:aliases:4865726f206f662043616e746f6e, value=, timestamp=1424904853492976)
=> (name=Frye:Kaylee:d556cf44-348b-4ea3-8c19-ba9d4877818c:, value=, timestamp=1428442425610395)
=> (name=Inara:Serra:a25b7e02-8099-401a-8c41-d9d2ea894b72:, value=, timestamp=1428442425621555)
=> (name=Reynolds:Malcolm:169382b7-21b0-47bf-b1c8-19bc008a9060:, value=, timestamp=1424904853505461)
=> (name=Reynolds:Malcolm:169382b7-21b0-47bf-b1c8-19bc008a9060:aliases:4d616c, value=, timestamp=1424904853505461)
=> (name=Reynolds:Malcolm:169382b7-21b0-47bf-b1c8-19bc008a9060:aliases:5367742e205265796e6f6c6473, value=, timestamp=1424904853505461)
=> (name=Tam:River:af68201f-4135-413e-959c-dd81ea651e52:, value=, timestamp=1428442425575881)
=> (name=Tam:Simon:aa090e1a-7792-4d7b-bba9-bac66f8c1f15:, value=, timestamp=1424904853518092)
=> (name=Tam:Simon:aa090e1a-7792-4d7b-bba9-bac66f8c1f15:aliases:44722e2054616d, value=, timestamp=1424904853518092)
=> (name=Washburne:Hoban:73f591df-c0dc-44c4-b3f3-9c37453c9537:, value=, timestamp=1428442425587484)
=> (name=Washburne:Hoban:73f591df-c0dc-44c4-b3f3-9c37453c9537:aliases:57617368, value=, timestamp=1428442425587484)
=> (name=Washburne:Zoey:46bc77ad-53ad-4402-b252-a0543005c583:, value=, timestamp=1428442425596863)
=> (name=Washburne:Zoey:46bc77ad-53ad-4402-b252-a0543005c583:aliases:436f72706f72616c20416c6c65796e65, value=, timestamp=1428442425596863)
=> (name=Washburne:Zoey:46bc77ad-53ad-4402-b252-a0543005c583:aliases:5a6f657920416c6c65796e65, value=, timestamp=1428442425596863)

1 Row Returned.
Elapsed time: 86 msec(s).

This is intended to show how 9 CQL rows are actually only 1 row "under the hood."

I need to know the limitations on distinct query.

In CQL, DISTINCT will only work on your partition keys.  I am not sure as to how many rows will negate its usefulness.  15000 CQL rows should be fine for it.  But if you have millions of distinct partition keys (high cardinality) I would expect performance to drop off...especially with several nodes in your cluster.


text:
Q: Best practices for passing encrypted data between different programming languages I have read that if you want to encrypt a string using one programming language and decrypt that string using another programming language, then to ensure compatibility it is best to do some conversions prior to doing the encryption. I have read that it's a best practice to encrypt the byte array of a string rather than the string itself. Also, I have read that certain encryption algorithms expect each encrypted packet to be a fixed length in size. If the last packet to be encrypted isn't the required size, then encryption would fail. Therefore it seems like a good idea to encrypt data that has first been converted into a fixed length, such as hex.
I am trying to identify best practices that are generally useful regardless of the encryption algorithm being used. To maximize compatibility when encrypting and decrypting data across different languages and platforms, I would like a critique on the following steps as a process:
Encryption:

*

*start with a plain text string

*convert plain text string to byte array

*convert byte array to hex

*encrypt hex to encrypted string

*end with an encrypted string

Decryption:

*

*start with an encrypted string

*decrypt encrypted string to hex

*convert hex to byte array

*convert byte array to plain text string

*end with a plain text string

A: Your premise is correct, but in some ways it's a little easier than that. Modern crypto algorithms are meant to be language agnostic, and provided you have identical inputs with identical keys, you should get identical results.
It's true that for most ciphers and some modes, data needs to be a fixed length. Converting to hex won't do it, because the data needs to end on fixed boundaries. With AES for example, if you want to encrypt 4 bytes, you'll need to pad it out to 16 bytes, which a hex representation wouldn't do. Fortunately that'll most likely happen within the crypto API you end up using, with one of the standard padding schemes. Since you didn't tag a language, here's a list of padding modes that the AesManaged class in .NET supports.
On the flip side, encrypting data properly requires a lot more than just byte encoding. You need to choose the correct mode of operation (CBC or CTR is preferred), and then provide some type of message integrity. Encryption alone doesn't protect against tampering with data. If you want to simplify things a bit, then look at a mode like GCM, which handles both confidentiality, and integrity.
Your scheme should then look something like:

*

*Convert plain text to string to byte array. See @rossum's comment for an important note about character encoding.

*Generate a random symmetric key or use PBKDF2 to convert a passphrase to a key

*Generate a random IV/nonce for use with GCM

*Encrypt the byte array and store it, along with the Authentication Tag

*You might optionally want to store the byte array as a Base64 string.

For decryption:

*

*If you stored the byte array as a Base64 string, convert back to the byte array.

*Decrypt encrypted byte array to plaintext

*Verify the resulting Authentication Tag matches the stored Authentication Tag

*Convert byte array to plain text string.

A: Really the best practice for encryption is to use a high level encryption framework, there's a lot of things you can do wrong working with the primitives. And mfanto does a good a good job of mentioning important things you need to know if you don't use a high level encryption framework. And i'm guessing that if you are trying to maximize compatibility across programming languages, it's because you need other developers to inter-operate with the encryption, and then they need to learn the low level details of working with encryption too.
So my suggestion for high level framework is to use the Google Keyczar framework, as it handles the details of, algorithm, key management, padding, iv, authentication tag, wire format all for you. And it exists for many different programming Java, Python, C++, C# and Go. Check it out.
I wrote the C# version, so I can tell you the primitives it uses behind the scenes are widely available in most other programming languages too, and it uses standards like json for key management and storage.

A: I use HashIds for this purpose. It's simple and supports wide range of programming language. We use it to pass encrypted data between our PHP, Node.js, and Golang microservices whenever we need to decrypt data in the destination.

A:
I have read that it's a best practice to encrypt the byte array of a string rather than the string itself.

Crytographic algorithms generally work on byte arrays or byte stream, so yes. You don't encrypt objects (strings) directly, you encrypt their byte representations.

Also, I have read that certain encryption algorithms expect each encrypted packet to be a fixed length in size. If the last packet to be encrypted isn't the required size, then encryption would fail.

This is an implementation detail of the particular encryption algorithm you choose. It really depends on what the API interface is to the algorithm.
Generally speaking, yes, crytographic algorithms will break input into fixed-size blocks. If the last block isn't full then they may pad the end with arbitrary bytes to get a full chunk. To distinguish between padded data and data which just happens to have what-look-like-padding bytes at the end, they'll prepend or append the length of the plain text to the byte stream.
This is the kind of detail that should not be left up to the user, and a good encryption library will take care of these details for you. Ideally you just want to feed in your plain text bytes and get encrypted bytes out on the other side.

Therefore it seems like a good idea to encrypt data that has first been converted into a fixed length, such as hex.

Converting bytes to hex doesn't make it fixed length. It doubles the size, but that's not fixed. It makes it ASCII-safe so it can be embedded into text files and e-mails easily, but that's not relevant here. (And Base64 is a better binary→ASCII encoding than hex anyways.)

In the interest of identifying best practices for ensuring compatibility with encrypting and decrypting data across different languages and platforms, I would like a critique on the following steps as a process:
Encryption:

*

*plain text string

*convert plain text string to byte array

*convert byte array to hex

*encrypt hex to encrypted string

*encrypted string

*plain text byte array to encrypted byte array

Decryption:

*

*encrypted string

*decrypt encrypted string to hex

*convert hex to byte array

*encrypted byte array

*decrypt encrypted byte array to plain text byte array

*convert byte array to plain text string

*plain text string

To encrypt, convert the plain text string into its byte representation and then encrypt these bytes. The result will be an encrypted byte array.
Transfer the byte array to the other program in the manner of your choosing.
To decrypt, decrypt the encrypted byte array into a plain text byte array. Construct your string from this byte array. Done.


text:
Q: How to model pairwise preference with both strong and weak preferences? I have large comparison data in form
In a pairwise comparison data each data point compares two alternatives.
For instance:
A > B (A is preferred to B, A and B are classes, not numbers)
A > B
B > A
B > C
A > C
etc ...
In short we can write numbers of preferences in data set:
A vs B 999:1
X vs A 500:500
X vs B 500:500
Bradley-Terry model models pairwise preference by assigning on parameter to each class:
$ P(A > B\; |\; \vec{w} ) = \frac{w_A}{w_A + w_B} $
Parameters can be estimated from data through maximal likelihood.
I'm looking for extension of Bradley-Terry model (or a completely new model) that would be able to model situations like the one above. I.e. A is always strongly preferred to B: $P(A>B) = 0.999$ but $ P(X<A) = P(X<B) = 0.5 $.
B-T model cannot represent that. Do you have any ideas how to create better model ?
PS
The model will be applied to a data of size $10^8$ so it would be good to have simple maximal likelihood algorithm.

A: The difficulty with specifying a model to resolve this problem is one of how to interpret the strength of preference information.  Does A vs B 999:1 mean that 999 times out of 1000 people will prefer A, or, does it mean that a person prefers A by a large amount relative to B?
If we take the interpretation that the data means that A is preferred to B 999 out of 1000, then you can fit a Bradley-Terry(-Luce) model, but most people these days would instead estimate a logit model, or a generalization thereof, as their "choice model":
$ P(A > B\; |\; \vec{w} ) = \frac{e^w_A}{e^w_A + e^w_B} $
Maximum likelihood estimation with large data sets and aggregate data is straightforward as the sample size enters the log-likelihood as a weight for each pair.  Complication arises if one wants to take into account how people differ in their preferences, in which case some type of mixture is required (see Train, Kenneth E. (2009), Discrete Choice Methods with Simulation (Second ed.). Cambridge: Cambridge University Press.).
It is not unknown for researchers to take this frequency interpretation when modeling even if it is believed that it is not an accurate characterization of the problem.  This is because it is not a straightforward exercise to specify a good model which deals with degree, as you then have to find some way of working out what, precisely, 999:1 means and how it relates to 998:2 and so on.  There are lots of different models that have been developed for this problem (e.g., models designed for constant sum dependent variables, models designed to predict probabilities, diffusion models).  It is impossible to say with any exactitude which model is most appropriate as it really depends upon the appropriateness of the inherent assumptions to your data and how well it fits your data.


text:
Q: Are the polynomial remainder and factor theorems equivalent? Remainder theorem:
If the polynomial $P(x)$ is divided by $(x-a)$, then the remainder is $P(a)$.
Factor theorem:
If $P(a)=0$, then $(x-a)$ is a factor of $P(x)$
I am wondering if they are equivalent - if both imply the other, or one is a consequence of the other.
My intuition is that they are equivalent, but I am not sure how to prove. It seems clear that the remainder theorem implies the factor theorem (by definition of factor). I am not sure about the other direction.
Am I on the right track? Thank you.

A: Yes, both are equivalent to the Division algorithm with linear divisor $\,x\!-\!a$.  Below, if rings are unfamiliar, let $R[x] = $ polynomials whose coefficients are complex (or real or rational). As for integers, $\, f\bmod g :=\,$  remainder left in $f\div g = \,$  polynomial (long) division with remainder.
Theorem $\ $ TFAE for a polynomial $\,f\in R[x],\,$ and $\,a\in R\,$ a commutative ring.
$(0)\ \ \ f = (x\!-\!a)q + r\ $ for some $\,q\in R[x],\ r\in R\ \ \ $ [Monic Linear Division Algorithm]
$(1)\ \ \ f\bmod x\!-\!a = f(a)\ \ \ \ \ \ \ $ [Remainder Theorem]
$(2)\ \ \ f(a) = 0\,\Rightarrow\, x\!-\!a\mid f\ \ \ $ [Factor Theorem]
Proof $\ (0\Rightarrow 1)\ \ \ f = (x\!-\!a)q + r\,\overset{\large x\,=\,a}\Longrightarrow\, r=f(a)\,\Rightarrow\,f\bmod x\!-\!a = r = f(a) $
$(1\Rightarrow 2)\ \ \ f\bmod x\!-\!a = f(a) = 0\,\Rightarrow\, x\!-\!a\mid f$
$(2\Rightarrow 0)\ \ \ g := f-f(a)\,$ has $\,g(a) = 0\ $ so $\ g = f-f(a) = (x\!-\!a)q$
Remark $ $(Euclidean) polynomial division with (smaller) remainder is always achievable for divisors that are monic (lead coef $\color{#c00}{= 1}$ or a $\rm\color{#c00}{unit}$ = invertible), such as $\,\color{#c00}1x-a\,$ above, see here.

A: The Remainder Theorem implies the factor theorem as noted by John;
We can rewrite the statement 'If the polynomial $P(x)$ is divided by $(x-a)$, then the remainder is $P(a)$' as
$$P(x) = (x-a)Q(x)+P(a)$$
where $Q(x)$ is a polynomial of one degree less than $P(x)$. Now, if $P(a)=0$, what do you get?


text:
Q: Big data architecture for industry (sensor data ) A new project came to my hands and looks interesting for my own.
I need to stored all the coming data from industrial PLCs (control the machinery inside a factory) and every event in the plc generated a output that need to be saved for after data analysis.
I was wondering what will be the perfect match for this type of data (time series) to make a hole architecture to manage data IO and at the moment only querying it for graphics (later will be applied machine learning analysis for predictive maintenance).
I don't know if I working in the correct direction and will be good to have some knowledge from experts in that subject.

*

*IO producer (this a own made project and cant not be change)

*IO events layer --> Is apache kafka a option for manage a big amount of signal coming for a lot of different computers (collected to plcs) and also manage the data saving to a nosql database. (it is suitable for that?any better option)

*nosql database--> This point is more clear choosing Cassandra for time series storing.

*queryng nosql data--> We are choosing spark for make fast queries and later on some data analysis.

The layer where I have more doubts is the layer involved in administrate the io data before storing and I have serious doubts that kafka is the correct option.
Thanks for reading and sorry for my bad English ;) Feel free to give your point of view.

A: we have a similar project based on sensor data. we have about 30 GB of data coming per day. We use kafka to stream the data and store it in hdfs. we have a set up of python ( numpy , pandas and pyspark) along with spark for any data crunching basically for prediction part.
As far as your doubts on kafka goes ... its capable enuf to handle large datasets. The other benfit would be that kafka can handle multiple sources and will be easier to scale.
As far as data storage is concerned i would recommend you to go with HDFS as it can be used in multiple ways to consume the data. You can leverage hive or hbase if required in future.


text:
Q: What are the Stack Exchange goals in terms of anonymity or otherwise? I asked a question a while back on Stack Overflow, and there were comments on one of the answers that suggested that two users knew each other at least by username.
What are the Stack Exchange goals in terms of anonymity or otherwise?
I would say that social networks (such as Stack Exchange) fall on a spectrum between between very personal (such as Facebook) and being very impersonal. Stack Exchange has the potential to be more personal the longer a user is on the site - I've started to notice the same names answering my questions (I mostly post questions), and suspect that in a couple years if I continue using the site as I currently do, that I will be aware of a small number of users and what personal information they display about themselves.
Since Stack Exchange provides an API, would it be possible to analyze one's own network?

A:
What are the Stack Exchange goals in terms of anonymity or otherwise?

If you navigate to the edit profile & settings link (within your profile), you'll see within "Web presence" that you can (optionally) complete these fields:

*

*Website link

*Twitter link or username

*GitHub link or username

Apart from that, you've quite some flexibility about what you want to write in the "About me" section of that same page. Should you want to do so, you could mention some kind of contact info, such as your eMail ID. And you can optionally also include something in the "Location" field.
If however you don't want to provide/disclose such data, your profile will show something like "Apparently, this user prefers to keep an air of mystery about them."
With that, I think SE leaves it pretty much up to yourself about how much anonymity you want.

I've started to notice the same names answering my questions

There is also another way to look at what you noticed ... i.e. via the "top users" for any tag that you're using in your questions. As an example, have a look at some of these (Drupal.SE related) tags: group, notifications, rules, charts, forena, answers, goals (incomplete list ...).
Specific to those tags:

*

*I'm following these tags (not users!), i.e. I want to be eMailed when questions come up with these tags.

*It does happen that some users contact me to "ask for help" for questions with any of these tags, eg by posting a comment below some previous question they posted (and to which I answered).

*I'm a (co-)maintainer of some of these same named contributed Drupal modules (Charts, Forena, Answers, Goals), so by answering these questions I'm using SE as a partial alternative to provide support for these modules.


text:
Q: Writing Python code that works like the reverse() function I'm looking to break down the reverse() function and write it out in code for practice. I eventually figured out how to do it (step thru the original list backwards and append to the new 'reversed' list) but wondering why this doesn't work.
def reverse(list):
    newlist = []
    index = 0
    while index < len(list):
        newlist[index] = list[(len(list)) - 1 - index]
        index = index + 1
    return newlist

list = [1, 2, 3, 4, 5]
print(reverse(list))

A: In Python, you cannot access/update an element of a list, if the index is not in the range of 0 and length of the list - 1.
In your case, you are trying to assign to element at 0, but the list is empty. So, it doesn't have index 0. That is why it fails with the error,

IndexError: list assignment index out of range

Instead, you can use append function, like this
    newlist.append(list[(len(list)) - 1 - index])

Apart from that, you can use range function to count backwards like this
for index in range(len(list) - 1, -1, -1):
    newlist.append(list[index])

you don't even have to increment the index yourself, for loop takes care of it.

As suggested by @abarnert, you can actually iterate the list and add the elements at the beginning every time, like this
>>> def reverse(mylist):
...     result = []
...     for item in mylist:
...         result.insert(0, item)
...     return result
...
>>> reverse([1, 2, 3, 4, 5])
[5, 4, 3, 2, 1]

If you want to create a new reversed list, you may not have to write a function on your own, instead you can use the slicing notation to create a new reversed list, like this
>>> mylist = [1, 2, 3, 4, 5]
>>> mylist[::-1]
[5, 4, 3, 2, 1]

but this doesn't change the original object.
>>> mylist = [1, 2, 3, 4, 5]
>>> mylist[::-1]
[5, 4, 3, 2, 1]
>>> mylist
[1, 2, 3, 4, 5]

if you want to change the original object, just assign the slice back to the slice of the original object, like this
>>> mylist
[1, 2, 3, 4, 5]
>>> mylist[:] = mylist[::-1]
>>> mylist
[5, 4, 3, 2, 1]

Note: reversed actually returns a reverse iterator object, not a list. So, it doesn't build the entire list reversed. Instead it returns elements one by one when iterated with next protocol.
>>> reversed([1, 2, 3, 4, 5])
<list_reverseiterator object at 0x7fdc118ba978>
>>> for item in reversed([1, 2, 3, 4, 5]):
...     print(item)
...
...
5
4
3
2
1

So, you might want to make it a generator function, like this
>>> def reverse(mylist):
...     for index in range(len(mylist) - 1, -1, -1):
...         yield mylist[index]
...
...
>>> reverse([1, 2, 3, 4, 5])
<generator object reverse at 0x7fdc118f99d8>

So the reverse function returns a generator object. If you want a list, then you can create one with list function, like this
>>> list(reverse([1, 2, 3, 4, 5]))
[5, 4, 3, 2, 1]

if you are just going to process it one by one, then iterate it with a for loop, like this
>>> for i in reverse([1, 2, 3, 4, 5]):
...     print(i)
...
...
5
4
3
2
1

A: First off don't override build-ins (list in your case) second newlist has a len of 0 therefore cannot be accessed by index.
def reverse(mylist):
    newlist = [0] * len(mylist)
    index = 0
    while index < len(mylist):
        newlist[index] = mylist[(len(mylist)) - 1 - index]
        index = index + 1
    return newlist

mylist = [1, 2, 3, 4, 5]
print(reverse(mylist))

you can create a list with values of the same lenght as your input list like so
newlist = [0] * len(mylist)

A: You can't assign to an arbitrary index for a 0-length list. Doing so raises an IndexError. Since you're assigning the elements in order, you can just do an append instead of an assignment to an index:
newlist.append(l[(len(l)) - 1 - index])

Append modifies the list and increases its length automatically.
Another way to get your original code to work would be to change the initialization of newlist so that it has sufficient length to support your index operations:
newlist = [None for _ in range(len(l))]

I would also like to note that it's not a good idea to name things after built-in types and functions. Doing so shadows the functionality of the built-ins.

A: You need to use list.append. newlist[0] is a valid operation, if the list has atleast one element in it, but newlist is empty in this very  first iteration. Also, list is not a good name for a variable, as there is a python builtin container with the same name:
def reverse(lst):
    newlist = []
    index = 0
    while index < len(lst):
        newlist.append(lst[(len(list)) - 1 - index])
        index += 1
    return newlist

list = [1, 2, 3, 4, 5]
print(reverse(list))

A: To write the function you're trying to write, see thefourtheye's answer.
But that isn't how reverse works, or what it does. Instead of creating a new list, it modifies the existing list in-place.
If you think about it, that's pretty easy: just go through half the indices, for each index N, swap the Nth from the left and the Nth from the right.*
So, sticking with your existing framework:
def reverse(lst):
    index = 0
    while index < len(lst)/2:
        lst[index], lst[len(lst) - 1 - index] = lst[len(lst) - 1 - index], lst[index]
        index = index + 1

As a side note, using while loops like this is almost always a bad idea. If you want to loop over a range of numbers, just use for index in range(len(lst)):. Besides reducing three lines of code to one and making it more obvious what you're doing, it removes multiple places where you could make a simple but painful-to-debug mistake.
Also, note that in most cases, in Python, it's easier to use a negative index to mean "from the right edge" than to do the math yourself, and again it will usually remove a possible place you could easily make a painful mistake. But in this particular case, it might not actually be any less error-prone…

* You do have to make sure you think through the edge cases. It doesn't matter whether for odd lists you swap the middle element with itself or not, but just make sure you don't round the wrong way and go one element too far or too short. Which is a great opportunity to learn about how to write good unit tests…

A: probably check this out:
def reverse(lst):
     newList = []
     countList = len(lst) - 1
     for x in range(countList,-1,-1):

         newList.append(lst[x])
     return newList

def main():
    lst = [9,8,7,6,5,4,2]
    print(reverse(lst))

main()


text:
Q: Induction proof for Taylor series $e^x$ I need to prove by induction that the series
$$
1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} \cdots = e^x
$$
I tried two approaches, both of which showed to be a dead end. Does anyone know how?
EDIT: Here is the least objectionable approach.
Prove for x=0
$$
1 = e^0    true
$$
Assume true for x=p
$$
1 + p + \frac{p^2}{2!} + \frac{p^3}{3!} \cdots = e^p
$$
Prove for x=p+1
$$
1 + p+1 + \frac{(p+1)^2}{2!} + \frac{(p+1)^3}{3!} \cdots = e^{(p+1)}
$$
Expanding these espressions leads to complications.

A: If you can use that $f(x) = e^x$ verifies $f' = f$, you can prove easily by induction that
$$\forall n\in\Bbb N:\ f^{(n)} = f,$$
so the Taylor series of $f$ at $0$ will be
$$\sum_{n=0}^\infty\frac{x^n}{n!}.$$
But you also need prove that the Taylor series converges to $f$. In this case, this can be done easily studying the remainder, but there are examples of functions with convergent Taylor series that $\not\to$ function.

A: Another way to do this is to use the binomial theorem on
$$e^x=\lim_{n\to\infty}\left(1+\frac{x}{n}\right)^n$$
so you get
$$ e^x = \displaystyle\lim_{n\to\infty}\sum_{k=0}^n\displaystyle {n\choose k}\left(\frac{x}{n}\right)^k$$
It isn't pretty, but it's a way to recover $e^x$ without the use of Taylor series.


text:
Q: HQL related: How to create an ailias to an object instead a field This is a related question to another question:
Hibernate exception PropertyNotFoundException when using Transformer
I have several tables joining hql. The tables are like this:
A
- A_ID
- NAME

B
- B_ID
- A_ID

C
- C_ID
- B_ID
- LENGTH
- UNIT

Classes:
@Entity
@Table(name="A")
class A
{
    @Id
    @Column(name="A_ID", updatable=false)
    private Long id;

    @Column(name="NAME", nullable=false, length=10, updatable=false)
    private String name;

    @OneToMany(mappedBy="a", fetch=FetchType.LAZY, cascade={CascadeType.ALL})
    @JoinColumn(name="A_ID", nullable=false)
    private Set<B> bs;

    // Setters and getters
    ...
}

@Entity
@Table(name="B")
class B
{
    @Id
    @Column(name="B_ID", updatable=false)
    private Long id;

    @ManyToOne
    @JoinColumn(name="A_ID", nullable=false, insertable=true, updatable=false)
    private A a;

    @OneToMany(mappedBy="b", fetch=FetchType.LAZY, cascade={CascadeType.ALL})
    @JoinColumn(name="B_ID", nullable=false)
    private Set<C> cs;

    @Transient
    private Double length;

    @Transient
    private String unit;

    // Setters and getters
    ...
}

@Entity
@Table(name="C")
class C
{
    @Id
    @Column(name="C_ID", updatable=false)
    private Long id;

    @ManyToOne
    @JoinColumn(name="B_ID", nullable=false, insertable=true, updatable=false)
    private B b;

    @Column(name="LENGTH", nullable=false, updatable=false)
    private Double length;

    @Column(name="UNIT", nullable=false, length=10, updatable=false)
    private String unit;

    // Setters and getters
    ...
}

After solving that issue, it is like this now:
select b.id as id, sum(c.length) as length, min(c.unit) as unit
from B b
left outer join b.c as c
group by b.id

Now the problem is:
I don't know how to set the alias of A in the returned B object in the HQL. This is causing a NPE when I'm doing this:
b.getA().getName();

Because I don't know how to set the related object "A" with "B" since there is only an ID in the B table.
Please help. Thank you very much.

A: b.getA().getName(); This will throw a NPE because select b.id as id, sum(c.length) as length, min(c.unit) as unit from B b does not include A. When you use the select clause in a HQL query it will only return the fields mentioned.
Please refer to http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html for more information.
EDIT:
If you read through the documentation provided you would have see select cat.mate from Cat cat. This can be incorporated to your query. Add b.A in your select clause and it should work.
EDIT:
If select b.id as id, sum(c.length) as length, min(c.unit) as unit
from B b
left outer join b.c as c
group by b.id
work then
select b.id as id, sum(c.length) as length, min(c.unit) as unit, b.A
from B b
left outer join b.c as c
group by b.id, b.A
should as well.


text:
Q: Match Sketch(Drawing) face photo to digital color photo I'm going to match the sketch face (drawing photo) in to the color photo. so for the research i want to find out what are the challenges that matching sketch drawing in to color faces. for now i have find out that

*

*resolution pixel difference

*texture difference

*distance difference

*and color (not much effect)

I want to know (in technical terms) what are other challenges and what are available OPEN CV and JAVA CV method and algorithms to overcome that challenges?
Here is some example of the sketches and the photos that are known to match them:

A: This problem is called multi-modal face recognition. There has been a lot of interest in comparing a high quality mugshot (modality 1) to low quality surveillance images (modality 2), another is frontal images to profiles, or pictures to sketches like the OP is interested in. Partial Least Squares (PLS) and Tied Factor Analysis (TFA) have been used for this purpose.
A key difficulty is computing two linear projections from the image in modality 1 (and modality 2) to a space where two points being close means that the individual is the same. This is the key technical step. Here are some papers on this approach:

*

*Abhishek Sharma, David W Jacobs :  Bypassing Synthesis: PLS for
Face Recognition with Pose, Low-Resolution and Sketch. CVPR
2011.

*S.J.D. Prince, J.H. Elder, J. Warrell, F.M. Felisberti, Tied Factor
Analysis for Face Recognition across Large Pose Differences, IEEE
Patt. Anal. Mach. Intell, 30(6), 970-984, 2008. Elder is a specialist in this area and has a variety of papers on the topic.

*B. Klare, Z. Li and A. K. Jain, Matching forensic sketches to
mugshot photos, IEEE Pattern Analysis and Machine Intelligence, 29
Sept. 2010.

As you can understand this is an active research area/problem. In terms using OpenCV to overcome the difficulties, let me give you an analogy: you need to build build a house (match sketches to photos) and you're asking how will having a Stanley hammer (OpenCV) will help. Sure, it will probably help. But you'll also need a lot of other resources: wood, time/money, pipes, cable, etc.

A: I think that James Elder's old work on the completeness of the edge map (using reconstruction by solving the Laplace equation) is quite relevant here. See the results at the end of this paper: http://elderlab.yorku.ca/~elder/publications/journals/ElderIJCV99.pdf

A: You could give Eigenfaces a try, though i never tested them with sketches i think they could a least be a good starting point for your research.
See Wiki: http://en.wikipedia.org/wiki/Eigenface and the Tutorial for OpenCV: http://docs.opencv.org/modules/contrib/doc/facerec/facerec_tutorial.html (including not only Eigenfaces!)

A: OpenCV can be used for feature extraction and machine learning required for this task. I guess you can start with the papers in the answers above, start with some basic features and prototype a classifier with OpenCV.
I guess you might also want to detect and match feature points on the faces. If you use this approach, you will have to do the feature point detectors on your own (training the Viola-Jones detector in OpenCV with your own data is an option).


text:
Q: Format 24h hour in Local no GMT moment("2013-12-31T19:51:57.000-0800").format("HH:mm") yields a 24hr hour format in GMT but I would like it in local time "11:51".
Is this possible with moment's format method?

A: That is incorrect.  The code you gave will not show the the value in GMT.  It will first adjust using the offset you gave it (-08:00), and then it will convert it to the correct offset as your own local time zone.  So if you're time zone offset happens to be -08:00 for that particular time, you will see no conversion at all.
Also, you seem to be misunderstanding how the offset is applied.  When you have an offset on an ISO8601 formatted string (like the one you supplied here), that means the time is already in the offset that is supplied.  19:51 is the local time that is in effect at the -8:00 offset.
To convert to UTC / GMT - you need to first invert the sign, then apply it.  So the UTC time here is 3:51:57 AM on 2014-01-01.
Your requested output of 11:51 is not valid for this timestamp, no matter how you look at it.


text:
Q: Apply vlookup all the way to the last cell of previous column I am quite new to VBA and tried some different approaches but not getting the result I need though.
The task is to develop a macro that runs a formula in column L (IF and a VLOOKUP) all the way until the last cell of the previous column, K. It cannot be a fixed cell since every day the data changes, i.e., more rows of data are added.
Any input is appreciated, thank you!
Sub ZBR_Users_Review()
'
' ZBR_Users_Review Macro
' Analysis to ensure all current ZBR users have equally assigned the corresponding Tagetik role
'

    Range("L5").Select
    ActiveCell.FormulaR1C1 = _
        "=IF(VLOOKUP(RC[-11],'Tagetik CCO role users assigned'!R5C1:R1048576C6,6,FALSE)=0, ""No"", ""Assigned"")"
    Range("L5").Select
    Selection.AutoFill Destination:=Range("L5:L160")
    Range("L5:L160").Select
    Range("L4").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ColorIndex = 15
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Selection.Borders(xlEdgeTop).LineStyle = xlNone
    Selection.Borders(xlEdgeBottom).LineStyle = xlNone
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
    With Selection
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlTop
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    ActiveCell.FormulaR1C1 = "Check"
    Rows("4:4").Select
    Selection.AutoFilter
    ActiveSheet.Range("$A$4:$L$100000").AutoFilter Field:=12, Criteria1:="#N/A"
    Range("L161").Select
End Sub

UPDATE:
With the advice of @Toddleson, I got the answer to this case, sharing the code below in case someone ever needs something similar.
Sub ZBR_Users_Review()
'
' ZBR_Users_Review Macro
' Analysis to ensure all current ZBR users have equally assigned the corresponding Tagetik role
'

    Dim lRow As Long

            'Find the last non-blank cell in column A(1)
            lRow = Cells(Rows.Count, 1).End(xlUp).Row

    Range("L5").Select
    ActiveCell.FormulaR1C1 = _
        "=IF(VLOOKUP(RC[-11],'Tagetik CCO role users assigned'!R5C1:R1048576C6,6,FALSE)=0, ""No"", ""Assigned"")"
    Range("L5").Select
    Selection.AutoFill Destination:=Range("L5:L" & lRow)
    Range("L5:L" & lRow).Select
    Range("L4").Select

#Rest of the code is the same as above


text:
Q: transition for background of ImageButton I have an ImageButton which I'd like to highlight - eg. flash when a download is finished.
I'm trying to set the background to a TransitionDrawable and reset it back when the transition is finished, but I get weird results:

*

*The padding of the button disappears once the transition is activated and isn't restored when I restore the original drawable when it is finished.

*The transition only happens on the stroke (border) of the button but not the gradient that fills the area of the background.

This is the Java code I am using to activate the transition, reverse it and restore the original drawable background:
downloadButton.setBackgroundResource(R.drawable.animate_background);
Drawable background = downloadButton.getBackground().getCurrent();
if (background instanceof TransitionDrawable) {
  TransitionDrawable transition = (TransitionDrawable) background;
  transition.startTransition(300);
  downloadButton.postDelayed(new Runnable() {
    @Override
    public void run() {
      // reverse the transition after it completes
      Drawable background = downloadButton.getBackground().getCurrent();
      if (background instanceof TransitionDrawable) {
        TransitionDrawable transition = (TransitionDrawable) background;
        transition.reverseTransition(200);
        downloadButton.postDelayed(new Runnable() {
          @Override
          public void run() {
            // restore original background
            downloadButton.setBackgroundResource(R.drawable.custom_button);
          }
        }, 200); // after reverse transition
      }
    }
  }, 300); // after transition
}

This is the button in the layout xml:
<ImageButton
    android:id="@id/download_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button"
    android:padding="14dp"
    android:src="@drawable/download_icon" />

This is the xml of the the custom_button drawable:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
    <shape>
        <solid android:color="#343434" />
        <stroke  android:width="1dp" android:color="#171737" />
        <corners android:radius="5dp" />
    </shape>
</item>
<item>
    <shape>
        <gradient  android:startColor="#343434"  android:endColor="#171737" android:angle="270" />
        <stroke    android:width="1dp"     android:color="#171717" />
        <corners   android:radius="5dp" />
    </shape>
</item>

The transition "animate_background" xml:
<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/animate_start" />
  <item android:drawable="@drawable/animate_end" />
</transition>

Animate start xml (animate end is very similar, just different colors for gradient and stroke)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <gradient  android:startColor="#34F434"  android:endColor="#174717" android:angle="270" />
    <stroke    android:width="2dp"  android:color="#17F717" />
    <corners android:radius="5dp" />
</shape>

A: Solved by setting padding manually after setting the background to transition - and I had to use twice the padding value that was set in the xml for the button.
eg.
downloadButton.setBackgroundResource(R.drawable.animate_background);
downloadButton.setPadding(28, 28, 28, 28);


text:
Q: problems in installing python packages in qpython3 I'm intermediate in python and I started learning about ML. I use qpython3 app on my android phone and as I need to use some packages such as numpy, I have to install them.
when I run the command
pip install numpy

I get an error that says that my
python version needs to be updated.
I tried many other compilers that run python 3.9 but still can't install libraries.
In Pydroid app, it requires to install an additional plugin app but I can never install it and many others have the same problem as me.
Collecting scipy

Downloading scipy-1.9.3.tar.gz (42.1 MB)
━━━━━━━━━━━━━━━━━━━━━ 42.1/42.1 MB 1.8 MB/s eta 0:00:00ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/data/data/ru.iiec.pydroid3/cache/pip-unpack-ddqhn5z9/scipy-1.9.3.tar.gz'
that's the error message
I think if I find a way to install python 3.9 and run it on qpython3 it'll work


text:
Q: What're the key codes for "Alt+Q Alt+Q"? I want to create a script that triggers when pressing Q twice while holding Alt, but couldn't figure out what're the correct key codes for that, could someone please shed some light?
P.S. I want to bind this shortcut to Ctrl+F12, which I assigned Sogou IME to turn on the Chinese input mode.

A: I didn't test this and there's probably a more concise way to do it, but I think something like this should work.
!Q::
If(keyPressed = 1){
   ...Do a thing...
}
keyPressed := 1
SetTimer, altQTimer, 50
return

altQTimer:
keyPressed := 0
return

A: TL;DR

In conclusion, even if I do all kinds of hacks and get the script working as intended, it's likely to break in the future, which is really not worth the trouble.

After hours of experimenting, the current conclusion is Sogou IME which uses Ctrl+F12 won't trigger the bound action i.e. switching to the Chinese input mode if it was sent by Alt+[Any Other Key], it can be triggered if it was sent by other shortcuts such as Ctrl+C, which is really unfortunate.
And the weirdest thing is the following code works:
^c::Send !q
!q::Send ^{F12}

And to rule out the potential extra simulated keystrokes (Ctrl by default) effect, the following code also works:
^!q::Send ^{F12}

But the following doesn't (tested on several machines):
!q::Send ^{F12}

Update
After much effort, I did get Alt+Q to turn on the Chinese input mode with the following code, not sure why:
!q::Send ^{F6}
^F6::Send ^{F7}
^F7::Send ^{F12}

But because I also need to trigger a VSCode command using Alt+Q at the same time, I had to modify the above code to the following:
~!q::Send ^{F6} ; with ~ prefixed
^F6::Send ^{F7}
^F7::Send ^{F12}

Now Alt+Q does trigger the VSCode command, but it won't turn on the Chinese input mode...
At last, if I take a step back and bind the VSCode command to Ctrl+C (which could turn on the Chinese input mode with just ^c::Send ^{F12}), I still have to prefix ^c with ~, otherwise it won't trigger the VSCode command, now I'm repeating the cycle all over again...
After all of these attempts, I have to say Sogou IME's logic for determining whether to enable the Chinese input mode is quite indeterminate, making the script for enabling the Chinese input mode very unreliable.
In conclusion, even if I do all kinds of hacks and get the script working as intended, it's likely to break in the future, which is really not worth the trouble.


text:
Q: How to correctly organize a set of concrete classes implementing an interface in different packages? I have defined an interface my system will depend on:
IMethodCall

and I've created a bunch of classes that implement IMethodCall:
AbstractMethodCall
ConstructorCall
TargetConstructorCall
VoidMethodCall
TargetVoidMethodCall
NonVoidMethodCall
TargetNonVoidMethodCall

They are details of implementation, and my system doesn't know about them (or at least, doesn't need to know).
There is some tricky logic behind choosing which implementation to instantiate, based on a set of data I'll have at hand at the time, so I decided to create a factory to have all that logic grouped in a single place:
MethodCallFactory

I'm trying to understand what should be the package structure used here. My original idea was to put all the concrete classes in a methodCalls package, and set them as package-protected, so no-one would know about their very existance. Then I'd let IMethodCall and MethodCallFactory outside, so users of my system could use them. The problem is that if I put the concrete classes as package-protected then the factory must also be in their package, which in its turn would seem kinda odd, as for an outside viewer it would look as that's a package that only exists to contain a factory.
At the moment the best trade-off I see is to put the concrete classes as public, but I'm wondering how you guys usually handle this kind of situations?

A: When I am faced with this situation, I would put the concrete implementation classes and the factory in the same package, and make the implementation classes package private.
You mentioned that this approach seems odd, because of the outside viewpoint. I disagree that the outside user wouldn't know there are implementation classes. Most IDE's will show the classes within the package, even if they are not accessable.  Also, if a programmer tries to use your implementation classes, the compiler will imply that the class exists while disallowing access.
I also would disagree that it's odd to have a package containing only a factory and it's private implementations. This group of classes are tightly related, which makes it logical to group them together in a single place.

A: You can put your factory class and interface in a public package, and put the implemented classes in an internal package.
The internal package is discouraged, the classes in the internal package may be changed anytime. User should call the api in the public package.
for example:
a public package is org.feeling.ui.dialogs
an internal package is org.feeling.internal.ui.dailogs


text:
Q: how to integrate a saw tooth signal in matlab i want to solve a problem 2.24 in Haykin communications systems using matlab, it wants to modulate a sawtooth signal using fm modulation and pm modulation, the pm is easy but the problem is in fm when i need to integrate the sawtooth to modulate it so any help and i dont want to use fmmod function in matlab i want it with equations. thank you
here is my used code
fs=100000;
fm=2;
fc=1000;
t=0:1/fs:6/fm;
m=sawtooth(2*pi*fm*t);
plot(t,m);

A: First option:
A simple implementation of the fmmod can be found here.
Second option:
Using MATLAB you can get the results easily. However, I do not know what you mean by "I want the equations".

*

*fs is the sampling rate of the signal (fs must be at least 2*fc)

*fc is the carrier frequency

*t is the sampling time of the signal

*x is the signal (sawtooth here)

*dev is the frequency deviation in modulated signal

*y is the modulated signal

*z is the demodulated signal

You can use the following code:
fs=3000;
fm=20;
fc=1000;
t=[0:fs-1]/fs;
x=sawtooth(2*pi*fm*t);
subplot(3,1,1);plot(x);
xlabel('main signal');
dev = 20;
y = fmmod(x,fc,fs,dev);
subplot(3,1,2);plot(y);
xlabel('modulated signal');
z = fmdemod(y,fc,fs,dev);
subplot(3,1,3);plot(z);
xlabel('demodulated signal');

The result is shown in the following image:

A: fs=10000;
fm=1;
fc=10;
t=0:1/fs:6/fm;
kf=25;
kp=30;
m=1+sawtooth(2*pi*fm*t);
m_int=cumtrapz(t,m);
s_fm=2*cos((2*pi*fc*t)+kf*m_int);
s_pm=2*cos((2*pi*fc*t)+kp*m);
subplot(3,1,1);plot(t,m);
title('wave form of sawtooth modulating signal');
xlabel('time (sec)');
ylabel('amplitude');

subplot(3,1,2);plot(t,s_fm);
title('wave form of FM modulated signal');
xlabel('time (sec)');
ylabel('amplitude');

subplot(3,1,3);plot(t,s_pm);
title('wave form of PM modulated signal');
xlabel('time (sec)');
ylabel('amplitude');


text:
Q: MockMVC jUnit Spring test I need help with the jUnit testing, my result is json file, and I need to test the length of that file, the problem is there is no such method inside the jsonPath function.
@Test
@Transactional
    public void getMunicipalitiesByCity() throws Exception {

        restSampleMockMvc.perform(get("/api/insurancePlan/municipalities/city/{cityName}", "esc"))
                .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.length").value(7));

Here is my test method the expected length is 7.
any help would be appreciate, thanks

A: Try using hamcrest matcher:
.andExpect((jsonPath("$", Matchers.hasSize(7))));


text:
Q: Connecting to Hyper-V Virtual Machines Running CentOS 7 via SSH is Slow I'm running Windows 10. I have the Hyper-V enabled. I've created three Hyper-V virtual machines running Centos 7; specifically:

Linux version 3.10.0-693.21.1.el7.x86_64
  (builder@kbuilder.dev.centos.org) (gcc version 4.8.5 20150623 (Red Hat
  4.8.5-16) (GCC) ) #1 SMP Wed Mar 7 19:03:37 UTC 2018

I have a NAT network setup. All three VM's are on that network. When I ssh from the host (my Windows 10 machine) to one of the VM's, it is PAINFULLY slow.
After issuing the ssh command, I wait for over 15 seconds for a password prompt. I then enter the password and wait for over 15-seconds again:
root@192.168.40.5's password:
Connection to 192.168.40.5 closed by remote host.
Connection to 192.168.40.5 closed.

When I establish the ssh connection with the -vvv switch, this is what I see:
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
...waits...
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 60
debug1: Server accepts key: pkalg rsa-sha2-512 blen 535
debug2: input_userauth_pk_ok: fp SHA256:3+l2I9j+Gv/Y2i3ksm00X3lIBjFEepj7uOCN4kQuy2A
debug3: sign_and_send_pubkey: RSA SHA256:3+l2I9j+Gv/Y2i3ksm00X3lIBjFEepj7uOCN4kQuy2A
debug3: send packet: type 50
debug3: receive packet: type 52
debug1: Authentication succeeded (publickey).
Authenticated to ***.***.***.7 ([***.***.***.7]:22).
debug1: channel 0: new [client-session]
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug3: send packet: type 90
debug1: Requesting no-more-sessions@openssh.com
debug3: send packet: type 80
debug1: Entering interactive session.
debug1: pledge: network
...waits...
debug3: receive packet: type 80
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug3: receive packet: type 91
debug2: callback start
debug2: fd 3 setting TCP_NODELAY
debug3: ssh_packet_set_tos: set IP_TOS 0x10
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1
debug3: send packet: type 98
debug1: Sending environment.
debug3: Ignored env SHELL
debug3: Ignored env TERM
debug3: Ignored env USER
debug3: Ignored env NAME
debug3: Ignored env LS_COLORS
debug3: Ignored env HOSTTYPE
debug3: Ignored env PATH
debug3: Ignored env PWD
debug1: Sending env LANG = en_US.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env SHLVL
debug3: Ignored env HOME
debug3: Ignored env LOGNAME
debug3: Ignored env LESSOPEN
debug3: Ignored env LESSCLOSE
debug3: Ignored env _
debug2: channel 0: request shell confirm 1
debug3: send packet: type 98
debug2: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
...waits...
debug3: receive packet: type 99
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0

My machine's sshd_config:
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
SyslogFacility AUTHPRIV
AuthorizedKeysFile      .ssh/authorized_keys
PasswordAuthentication yes
ChallengeResponseAuthentication no
GSSAPIAuthentication no
GSSAPICleanupCredentials no
UsePAM yes
X11Forwarding yes
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
Subsystem       sftp    /usr/libexec/openssh/sftp-server

*

*I experience the slowness when connecting to any of the CentOS VMs

*The described slowness occurs when connecting from the host (Windows 10 box) or one of the other CentOS VMs

*The VMs are on the same subnet

*The VMs are assigned static IP addresses

I want to resolve the slowness issue. Any tips or ideas?
Adding details of one of the CentOS VM's:
ParentCheckpointId                  : a76e4644-66c3-4d8a-b252-1e671f2c3c7c
ParentCheckpointName                : sbx-misc-app01 - (5/3/2018 - 12:20:00 AM)
VMName                              : sbx-misc-app01
VMId                                : a283e141-b32b-428d-8d3b-a64cf08b1ee8
CheckpointFileLocation              : C:\Hyper-V\Virtual Machines
ConfigurationLocation               : C:\Hyper-V\Virtual Machines
SmartPagingFileInUse                : False
SmartPagingFilePath                 : C:\Hyper-V\Virtual Machines
SnapshotFileLocation                : C:\Hyper-V\Virtual Machines
AutomaticStartAction                : StartIfRunning
AutomaticStartDelay                 : 0
AutomaticStopAction                 : Save
AutomaticCriticalErrorAction        : Pause
AutomaticCriticalErrorActionTimeout : 30
AutomaticCheckpointsEnabled         : True
CPUUsage                            : 0
MemoryAssigned                      : 1612709888
MemoryDemand                        : 1031798784
MemoryStatus                        : OK
NumaAligned                         : False
NumaNodesCount                      : 1
NumaSocketCount                     : 1
Heartbeat                           : OkApplicationsUnknown
IntegrationServicesState            :
IntegrationServicesVersion          : 0.0
Uptime                              : 18:23:29.4550000
OperationalStatus                   : {Ok}
PrimaryOperationalStatus            : Ok
SecondaryOperationalStatus          :
StatusDescriptions                  : {Operating normally}
PrimaryStatusDescription            : Operating normally
SecondaryStatusDescription          :
Status                              : Operating normally
ReplicationHealth                   : NotApplicable
ReplicationMode                     : None
ReplicationState                    : Disabled
ResourceMeteringEnabled             : False
CheckpointType                      : Standard
EnhancedSessionTransportType        : VMBus
Groups                              : {}
Version                             : 8.3
VirtualMachineType                  : RealizedVirtualMachine
VirtualMachineSubType               : Generation2
Notes                               :
State                               : Running
ComPort1                            : VMComPort (Name = 'COM 1', VMName = 'sbx-misc-app01') [Id = 'Microsoft:A283E141-B32B-428D-8D3B-A64CF08B1EE8\8E3A359F-559A-4B6A-98A9-1690A6100ED7\0', VMId =
                                      'a283e141-b32b-428d-8d3b-a64cf08b1ee8']
ComPort2                            : VMComPort (Name = 'COM 2', VMName = 'sbx-misc-app01') [Id = 'Microsoft:A283E141-B32B-428D-8D3B-A64CF08B1EE8\8E3A359F-559A-4B6A-98A9-1690A6100ED7\1', VMId =
                                      'a283e141-b32b-428d-8d3b-a64cf08b1ee8']
DVDDrives                           : {DVD Drive on SCSI controller number 0 at location 1}
FibreChannelHostBusAdapters         : {}
FloppyDrive                         :
HardDrives                          : {Hard Drive on SCSI controller number 0 at location 0}
RemoteFxAdapter                     :
VMIntegrationService                : {Guest Service Interface, Heartbeat, Key-Value Pair Exchange, Shutdown...}
DynamicMemoryEnabled                : True
MemoryMaximum                       : 8589934592
MemoryMinimum                       : 536870912
MemoryStartup                       : 8589934592
ProcessorCount                      : 2
BatteryPassthroughEnabled           : True
Generation                          : 2
IsClustered                         : False
ParentSnapshotId                    : a76e4644-66c3-4d8a-b252-1e671f2c3c7c
ParentSnapshotName                  : sbx-misc-app01 - (5/3/2018 - 12:20:00 AM)
Path                                : C:\Hyper-V\Virtual Machines
SizeOfSystemFiles                   : 69632
GuestControlledCacheTypes           : False
LowMemoryMappedIoSpace              : 134217728
HighMemoryMappedIoSpace             : 536870912
LockOnDisconnect                    : Off
CreationTime                        : 5/2/2018 10:23:06 PM
Id                                  : a283e141-b32b-428d-8d3b-a64cf08b1ee8
Name                                : sbx-misc-app01
NetworkAdapters                     : {Network Adapter}
CimSession                          : CimSession: .
ComputerName                        : Thinger
IsDeleted                           : False

Here is the network setup code...
$switch_name = 'sbx-ext01'
$nat_name = 'net-sbx-ext01'
$nat_subnet_prefix_length = 24
$gateway_ip_address = '192.168.40.0'

New-VMSwitch -SwitchName $switch_name -SwitchType Internal

$interface_index = $(Get-NetAdapter -Name "*${switch_name}*").ifIndex

New-NetIPAddress `
    -IPAddress 192.168.40.1 `
    -PrefixLength 24 `
    -InterfaceIndex $interface_index

New-NetNat -Name $nat_name `
    -InternalIPInterfaceAddressPrefix $gateway_ip_address/$nat_subnet_prefix_length

A: It is not clear what "painfully slow" means. Do you mean that once you are connected via ssh that it is slow? Or do you mean that, once you enter you password and hit enter that it takes a long time, 30 seconds, to get a prompt?
If it is that it takes you 30-60 seconds to get a prompt this may be due to the SSH server attempting to reverse resolve the IP address of the connecting client. I have seen this happen when there is an issue with the DNS servers configured in resolv.conf on the server, e.g., they timeout.
One solution is to set the following in ssd_config on each of the machines:
UseDNS no

This is enabled by default.
Another solution is to correct the nameserver entries in resolv.conf
If this does not fix your issue would you please add more detail about what "painfully slow" means?


text:
Q: how to use Facebook share button in my web page to share or post something to facebook page? i am added a facebook share button to my website it is sharing or posting things to profile timelines but it is not sharing or posting anything to my page(like fans page in facebook).Is there anyway to choose to post to your fan page? any one can help me? plz..

A: Considering whatever is the "things" in your website, say a product with id 123, for example.
You can make users like it/share it using the standard fb-like button.
When they do like it and/or share it, it comes up as a thing they liked on your website. If that object of yours, has a proper URL with proper meta-tags, it will show up nicely on FB as a story. Good guide here
You can also use the facebook debug tool for testing if the sharing, meta tags are all working as expected here.
If you want your page to be the object of sharing, the only thing that can be done is users can like your page from your website. You cannot share stories from the API to the page, as the page is not an entity. Meaning its not a user.
So, if the page said,
User XYZ liked item ABC on yourwebsite.com
it won't make much sense to the people who see this.
Instead if userXYZ liked an itemABC on your site, the following update on FB will make much more sense.
UserXYZ liked itemABC on yourwebsite.com
(This will have a proper pictorial representation and a clickable link to your website if the like button and the destination url are configured correctly)


text:
Q: PL/SQL: Assign a data type to a variable Is there anyway to do this? I want it to be done like this:
create or replace
package SOME_PACKAGE as
  filetype type is clob%type; --assign clob's filetype to a variable
end SOME_PACKAGE;
/

declare
  clb SOME_PACKAGE.filetype;
begin
  dbms_lob.writeappend(clb, 1, 's');
end;

Thanks!

A: You can do it like this:
create or replace
package SOME_PACKAGE as
  subtype filetype is clob; --assign clob's filetype to a variable
end SOME_PACKAGE;
/

But why ??


text:
Q: In Acumatica, can you have a graph/page using an unbound DAC? Is it possible to have a Graph and page utilize an completely unbound DAC?
When attempting this currently in 4.20 I'm receiving the following error message:
Incorrect syntax near the keyword 'FROM'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'FROM'.

If I create a table in the database and change my DAC fields from say PXInt to PXDBInt, then the page loads however for what I'm attempting to do I have no need to actually store the data.
DAC sample:
    namespace Acumatica1
{
    [PXPrimaryGraph(typeof(UnboundDataTest))]
    [System.SerializableAttribute()]
    public class UnboundDAC : PX.Data.IBqlTable
        {
        public abstract class unboundKey : PX.Data.IBqlField
        {
        }
        protected int _UnboundKey;
        [PXInt(IsKey = true)]
        [PXUIField(Visible = false)]
        public virtual int UnboundKey
        {
            get
            {
                return this._UnboundKey;
            }
            set
            {
                this._UnboundKey = value;
            }
        }

        #region UnboundText
        public abstract class unboundText : PX.Data.IBqlField
        {
        }
        protected string _UnboundText;
        [PXString]
        [PXUIField(DisplayName = "Text")]
        public virtual string UnboundText
        {
            get
            {
                return this._UnboundText;
            }
            set
            {
                this._UnboundText = value;
            }
        }
        #endregion
    }
}

Graph Sample:
public class UnboundDataTest: PXGraph<UnboundDataTest>
{
    public PXSelect<UnboundDAC> UnboundInfo;
}

A: To take control of the select process, you need to create a delegate that will be invoked when the UnboundInfo view is selected:
public IEnumerable unboundInfo()
{
    //TODO: Put your logic to return a new instance of UnboundDAC here
}

Inside this delegate, you are free to use whatever mechanism you want to retrieve the record(s) that should be returned by this unbound select. For example, you can create one or more objects on the fly and return them:
public IEnumerable unboundInfo()
{
    yield return new UnboundDAC() { UnboundKey = 1, UnboundText = "A" };
    yield return new UnboundDAC() { UnboundKey = 2, UnboundText = "B" };
}

If you somehow need to allow the user to edit the values in your UnboundDAC, you could leverage the Cache, and insert the records in the cache the first time the view is selected:
public IEnumerable unboundInfo()
{
    PXCache cache = _Graph.Caches[typeof(Table)];
    cache._AllowInsert = true;
    cache._AllowUpdate = true;

    if(cache.Current == null)
    {
        cache.SetStatus(new UnboundDAC() { UnboundKey = 1, UnboundText = "A" }, PXEntryStatus.Held);
        cache.SetStatus(new UnboundDAC() { UnboundKey = 2, UnboundText = "B" }, PXEntryStatus.Held);
    }

    return UnboundInfo.Cache.Cached;
}

Finally, you could take a look at the internal implementation of PXFilter; PXFilter is a specialized PXSelect that doesn't actually select anything from the database; all it does it insert one row in the cache the first time it is selected, and prevent persisting of this row. You could use a similar technique to create a PXUnboundSelect class that could be reused easily in multiple graphs.


text:
Q: Discord bot playing a game I have recently created a discord bot with the "playing a game" status and there is the code that I have set:
bot.on('ready', () => {
    console.log('Client is online!');
    bot.user.setActivity('osu!');

The problem is that it can't add an icon or whatever it called with only the name of the game that I wanted to show

I watched some old tutorials and explaining the same thing but bot.user.setGame(' '); instead of bot.user.setActivity(' ') and it shows this on those videos:

At least with an icon on it.
Is there any way I can add an icon of my choice or only the mark interrogation one?

A: As far as I'm aware, in discord.js V12 you cannot set a game icon for your bot. There may be third party apps or libraries that allow you to do so but nothing that I'm aware of.

A: for v13 its
client.user.setActivity('<the game you want the bot to play>')


text:
Q: grequests - too many open files error I'm trying to perform about 100k GET requests and parse the response body of each request. I thought grequests would be a good way to go, but I'm getting errors related to 'too many open files'. Here's the code:
import grequests

with open("./100k-sites.csv", "r") as f:
    urls = ["http://" + line.rstrip() for line in f]

rs = (grequests.get(u, timeout=1) for u in urls)
responses = grequests.map(rs)

for r in responses:
    try:
        # do something with the response body
    except:
        pass

anyone got experience with this? The error I'm getting is:

requests.packages.urllib3.connection.HTTPConnection object at
  0x7f817ab36898>: Failed to establish a new connection [Errno 24] Too
  many open files

A: Maybe it's only a workaround (as somebody in the discussion mentioned above says), but IMHO it's worth of writing here, that one can fix it by the two lines:
import resource
resource.setrlimit(resource.RLIMIT_NOFILE, (110000, 110000))


text:
Q: What is the best way to set up my intranet server for MVC 4? I have recently started programming with Asp.Net MVC 4. I have downloaded Visual Studio 2010 from Microsoft DreamSpark and a "Standard" Microsoft Server 2008 R2. Now I installed the Server into a VirtualBox on Promiscuous Network (thus allowing it to talk to my whole network) and next I want to use it to test my applications.
Can you point me to good resources that tell me how to set up the server best for this?
Thank you so much for your help.

A: This link is for MVC 3, but it still applies to you. http://www.asp.net/mvc/mvc3
It includes everything including the Razor engine.
Installation and Help
•Install ASP.NET MVC 3 using the Web Platform Installer (recommended) http://www.microsoft.com/web/gallery/install.aspx?command=getinstallerredirect&appid=MVC3
•Install ASP.NET MVC 3 using the installer executable http://go.microsoft.com/fwlink/?LinkID=208140

A: This is a walk-through about creating an intranet site using asp.net MVC, IIS 7 and visual studio 2010.
It worked out for me great.
regards


text:
Q: How to decode/unescape HTML in Dynamics AX I have some HTML encoded within an XML request I get through an AIF web service.
The text I'm getting is of course escaped - I get <br> instead of
 .
Is there a proper way to decode it? I don't want to write something for the basic stuff, then deal with bug reports for the next decade, because I forgot an accented character I never knew existed...
The lame part is, that when I feed special HTML/XML characters to XMLTextWriter, it will properly encode them, but if I feed that same XML to XMLTextReader, it will not decode them.
Thanks.

A: static void HtmlDecode(Args _args)
{
    str input   = '<br>';
    str output  = System.Web.HttpUtility::HtmlDecode(input);
    ;

    info(output);
}

Result:


text:
Q: Name is null from apple sign in. its a new user, firebase react native Hi I cannot get the user's name via APPLE SSO.
Im using react native firebase. It logs in fine.
I made sure its a new account for the app.

*

*in firebase console > auth > removed my apple user email.

*https://appleid.apple.com/account/manage > sign in with security > sign in with Apple > and "Stop using sign in with apple" on that app. the private relay email matches in firebase and is removed.

how do i get the name from apple SSO?
import auth from '@react-native-firebase/auth';
import { appleAuth } from '@invertase/react-native-apple-authentication';

async function onAppleButtonPress() {
  const appleAuthRequestResponse = await appleAuth.performRequest({
    requestedOperation: appleAuth.Operation.LOGIN,
    requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
  });

  if (!appleAuthRequestResponse.identityToken) {
    throw new Error('Apple Sign-In failed - no identify token returned');
  }

  const { identityToken, nonce } = appleAuthRequestResponse;
  const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);

  const res = await auth().signInWithCredential(appleCredential);

  console.log('res', res) //  <-- see next code block

  // below, displayname is null, i do see firebase Id, and the private email relay address.
  console.log('auth().currentUser?', auth().currentUser )

  return res
}

// res response
{
  "additionalUserInfo": {
    "profile": {
      "is_private_email": "true",
      "sub": "000630.afe8c07332204888...",
      "exp": 1666292000,
      "real_user_status": 2,
      "iss": "https://appleid.apple.com",
      "c_hash": "yXmD5j_37t1F...",
      "email_verified": "true",
      "aud": "com.mydemo.app",
      "iat": 1666205600,\
      "email": "kgszm...@privaterelay.appleid.com",
      "auth_time": 1666205600,
      "nonce": "77e6cd4bfca826abc77a179f15b0a8...",
      "nonce_supported": true
    },
    "username": null,
    "providerId": "apple.com",
    "isNewUser": true             <---- shows its a new user
  },
  "user": {
    "isAnonymous": false,
    "emailVerified": true,
    "providerData": [
      {
        "providerId": "apple.com",
        "uid": "000630.afe8c0733220488889977a5c9...",
        "email": "kgszm...@privaterelay.appleid.com",
      }      ],
      "uid": "4VpWSNUxVAeNzuEu4IQrLKq5Mw43",
      "email": "kgszm...@privaterelay.appleid.com",
      "refreshToken": "AOEOulaKPm6HzbT....",
      "displayName": null,             <--- why is this null?
      "tenantId": null,
      "phoneNumber": null,
      "photoURL": null,
      "metadata": {
      "creationTime": 1666205601897,
      "lastSignInTime": 1666205601897
    },
    "providerId": "firebase"
    }
  }}'

"@react-native-firebase/auth@^12.9.0": version "12.9.3"

A: AS described in invertase readme file, apple API provide fullName only the first time, you need to save it in signup the first time.
For testing purpose you can delete using apple account form settings/security and password/delete apple account of your application.
const appleAuthRequestResponse = await appleAuth.performRequest({
  requestedOperation: appleAuth.Operation.LOGIN,
  requestedScopes: [appleAuth.Scope.FULL_NAME, appleAuth.Scope.EMAIL],
});
// Create a Firebase credential from the response
const { identityToken, nonce, fullName } = appleAuthRequestResponse;
const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);
let fullName_ = '';
if(fullName.namePrefix) fullName_ = fullName_ + fullName.namePrefix + ' ';
if(fullName.givenName) fullName_ = fullName_ + fullName.givenName + ' ';
if(fullName.familyName) fullName_ = fullName_ + fullName.familyName + ' ';
if(fullName.nickname) fullName_ = fullName_ + fullName.nickname + ' ';
if(fullName.middleName) fullName_ = fullName_ + fullName.middleName + ' ';
if(fullName.nameSuffix) fullName_ = fullName_ + fullName.nameSuffix + ' ';


text:
Q: Как правильно воспользоваться StackPanel? Хочу расположить на форме пары Label + какой-нибудь Combobox.
В принципе, если располагать все через Grid, то все весьма красиво получается:
   <Grid >
        <Grid.Resources >

        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition ></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="50"></RowDefinition>
        </Grid.RowDefinitions>
        Тип БД
        <ComboBox Grid.Row="0" Grid.Column="1"></ComboBox>
        База данных
        <ComboBox Grid.Row="1" Grid.Column="1"></ComboBox>
        Таблица
        <ComboBox Grid.Row="2" Grid.Column="1"></ComboBox>
        Ключ таблицы
        <ComboBox Grid.Row="3" Grid.Column="1"></ComboBox>
        Значение таблицы
        <ComboBox Grid.Row="4" Grid.Column="1"></ComboBox>
        Идентификатор привязки к справочнику
        <ComboBox Grid.Row="5" Grid.Column="1"></ComboBox>
    </Grid>

Но мне не нравится то, что в разметке парные-элементы никак не группируются между собой...
Я попробовал попарно их засунуть каждый в свой StackPanel, но в итоге не все так красиво получается, как в Grid... Как я могу решить проблему, чтобы элементы занимали по 50% рабочей области окна?

A:
Но мне не нравится то, что в разметке парные-элементы никак не группируются между собой...

Сгруппировать то легко, запихнуть каждую пару в свой Grid, да и все тут. Поведение в отношении размера стобцов у одного Grid и последовательности однострочных Grid идентично. Но, глядя на вашу разметку, смущает скорее дублирование строк и элементов. Если у вас в разметке куча однотипных пар Label + (что-то), которые ходят вместе и образуют строку таблицы, должны ли они быть отдельными элементами? По моему, это отличный повод для создания своего элемента управления.
Раз нам нужно поведение Grid в плане изменения размеров столбцов, этот элемент управления можно сделать производным от Grid:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace WpfTest
{
    public class ControlPair : Grid
    {
        UIElement first;
        UIElement second;

        public UIElement First
        {
            get { return this.first; }
            set
            {
                this.first = value;
                UpdateChildren();
            }
        }

        public UIElement Second
        {
            get{ return this.second; }

            set
            {
                this.second = value;
                UpdateChildren();
            }
        }

        void UpdateChildren()
        {
            this.Children.Clear();

            if (this.first != null)
            {
                this.Children.Add(this.first);
                Grid.SetColumn(this.first, 0);
            }

            if (this.second != null)
            {
                this.Children.Add(this.second);
                Grid.SetColumn(this.second, 1);
            }
        }

        public ControlPair() : base()
        {
            this.ColumnDefinitions.Clear();
            this.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = new GridLength(0.5, GridUnitType.Star)
            });

            this.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = new GridLength(0.5, GridUnitType.Star)
            });

            this.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
        }
    }
}

Здесь у элемента управления есть два свойства, First и Second, которым можно присвоить любой элемент управления. Элементы помещаются в ячейки Grid, для которых задан определенный процент доступного пространства. Тогда мы можем в разметке делать так:
<local:ControlPair>
    <local:ControlPair.First>

    </local:ControlPair.First>
    <local:ControlPair.Second>
        <ComboBox/>
    </local:ControlPair.Second>
</local:ControlPair>

И элементы сгруппированы, и не нужна куча RowDefinition.
Более развернутый пример, как это можно применить на практике:
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTest" x:Class="WpfTest.MainWindow"
        Height="250" Width="400" >
    <Grid>
        <StackPanel>

            <local:ControlPair HorizontalAlignment="Stretch">
                <local:ControlPair.First>

                </local:ControlPair.First>
                <local:ControlPair.Second>
                    <ComboBox ItemsSource="{Binding Path=DatabaseTypeValues}"
                        Text="{Binding Path=DatabaseTypeSelected,Mode=TwoWay}"/>
                </local:ControlPair.Second>
            </local:ControlPair>

            <local:ControlPair HorizontalAlignment="Stretch">
                <local:ControlPair.First>

                </local:ControlPair.First>
                <local:ControlPair.Second>
                    <TextBox Text="{Binding Path=Database,Mode=TwoWay}"/>
                </local:ControlPair.Second>
            </local:ControlPair>

            <Button x:Name="myButton" Content="Save" HorizontalAlignment="Left" Height="40" Margin="10,10,10,10"
                VerticalAlignment="Top" Width="100" Click="Button_Click" />

        </StackPanel>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace WpfTest
{
    public partial class MainWindow : Window
    {
        Options optionsData;

        public MainWindow()
        {
            InitializeComponent();
            optionsData = new Options();
            optionsData.DatabaseTypeValues = new string[] { "SQL Server", "Access" };
            this.DataContext = optionsData;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //show selected options
            MessageBox.Show("Selected " +
                "\nDatabaseType: " + optionsData.DatabaseTypeSelected +
                "\nDatabase: " + optionsData.Database
                );
        }
    }

    public class Options
    {
        public string[] DatabaseTypeValues { get; set; }
        public string DatabaseTypeSelected { get; set; }
        public string Database { get; set; }
    }
}


text:
Q: SQL query to tell when server no longer has the requested starting point I have a master-slave setup using postgres 9.5.3 and got the following error in my postgres log
"could not start WAL streaming: ERROR:  requested starting point 0/D000000 on timeline 2 is not in this server's history"
I would like to know if there is sql query that can tell me that my server no longer has the requested starting point so I will be able to automatically start full copy of the master data directory.
Thanks
Avi

A: I don't think that you can get this information with SQL; you'd have to examine the contents of pg_xlog.
Wouldn't it be a better solution to use a replication slot to ensure that WAL is kept long enough?


text:
Q: Div Float with Image When I float a div with text it in the behavior is what I want but when I put an image inside, the float dosen't behave the same way and the image then goes down one line. Why is that?

A: Put the image before the text if you want the text on the right side of the img.
to make sure the text flows to the right of the img float:left.

Text will pop on right

if you first want text then image

Text will pop on left

A: Dug these up from my favorites as they've helped me in the past. Galchen is right - we need some markup / CSS to better understand your issue.
The Image might go down if it's being set to a block element in a style - which would do this.
http://css.maxdesign.com.au/floatutorial/
http://www.tizag.com/cssT/float.php


text:
Q: Call message dialog inside a thread (python + gtk3) I tried to call a message dialog inside a thread (use python3 and gtk3), in the next example when I pressed the button the label start to change the text every 1 seconds, this part work fine, the problem appear when I uncomment the line self.Mensage_Falla("final"), the application close for itself, here is the code to see if somebody can show me the light:
import threading
import time
import serial
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Pango, GLib, GdkPixbuf, GObject

class GridWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="TEST")
        self.set_border_width(15)
        self.grid = Gtk.Grid()
        self.grid.set_column_spacing(25)
        self.grid.set_row_spacing(25)
        self.add(self.grid)

        self.label1 = Gtk.Label("NUMERO DE SERIE")
        self.txtSerialNumber = Gtk.Entry()

        btnStartTest=Gtk.Button("Iniciar Prueba")
        btnStartTest.connect("clicked",self.StartTest_Tread)

        self.grid.add(self.label1)
        self.grid.attach(btnStartTest, 0, 1, 1, 1)

    def StartTest_Tread(self,widget):
        self.thread = threading.Thread(target=self.StartTest)
        self.thread.daemon = True
        self.thread.start()

    def StartTest(self):
        self.label1.set_text("xxxx")
        time.sleep(1)
        self.label1.set_text("yyyy")
        time.sleep(1)
        self.label1.set_text("zzzz")
        time.sleep(1)
        self.label1.set_text("aaaa")
        self.Mensage_Falla("final")

    def Mensage_Falla(self, UUT_Failure):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
            Gtk.ButtonsType.OK, "UUT")
        dialog.format_secondary_text(
            "LA UUT A FALLADO LA PRUEBA " + UUT_Failure)
        dialog.run()
        dialog.destroy()
        print("fALLA")

try:
    GObject.threads_init()
    win = GridWindow()
    win.set_position(Gtk.WindowPosition.CENTER)
    win.set_default_size(100,100)
    win.set_type_hint(Gdk.WindowTypeHint.MENU)
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()
except ValueError as Argument:
    print ("The argument does not contain numbers\n", Argument)
    print("error " + str(Exception.args))
    time.sleep(30)


text:
Q: DNN 9 Module only displays in Edit Mode We recently upgraded an old DNN site to the latest version (9.8.00).  Everything has been running fine for the most part, but today I have ran into an issue I can't figure out how to resolve.  Once of my users dropped an HTML module on the page but we can not get it to display outside of edit mode.  I have tried adding an HTML module to other pages as well to see if it was isolated to an individual page, but it's doing the same thing across the entire site.  I have tried all of the following things to no avail.

*

*Debugged the page to make sure no errors where being thrown and none are.

*Stopped inheriting permissions and made the module visible to all users.

*Changed the Cache settings for the module to 0.

*Verified the site was running on .Net 4.5.1 (I'm actually on 4.7.1).

*Tested two other modules (link and event), both of these modules display outside of edit mode.

I am at a loss at this point.  The HTML module is showing as version 9.8.0, but has an upgrade version as 10.0.3.  So I'm not sure if that means it needs to be upgraded or it has already been upgraded.
Any help would be greatly appreciated.

A: Recents versions of the HTML module have this behaviour: they doesn't appear when they haven't any content. After you add some content, they keep displayed.
I think this feature is related to the default template which is containing an empty HTML module.


text:
Q: How to remove time from dateTime in kunena1.7 I use kunena in my site and I want remove time from datetime in latest post by user in main page or in post page.
I delete %H:%i from its variable in language file but time is shown still.
How can I remove this?

A: Edit code of kunena core.
For example in this path:
components/com_kunena/template/yourTemplate/view/message.php

I edited this:
<span class="kmsgdate kmsgdate-left" title="<?php echo CKunenaTimeformat::showDate($this->msg->time, 'config_post_dateformat_hover') ?>">
<?php echo CKunenaTimeformat::showDate($this->msg->time, 'config_post_dateformat'); ?>

To:
<span class="kmsgdate kmsgdate-left" title="<?php echo CKunenaTimeformat::showDate($this->msg->time, 'config_post_dateformat_hover') ?>">
<?php
     $dateTime = CKunenaTimeformat::showDate($this->msg->time, 'config_post_dateformat');
     $date = explode(" ", $dateTime);
     echo  $date[1];
?>

And just date will be shown.

A: In the Joomla backend:

*

*Go to the Kunena Configuration page

*Go to the "Frontend" tab

*There is a parameter called "Message Time Format" which you can set to "hide"

Update:
Having said that, I realised I am using Kunena 2.0.x which you should also do. So I recommend upgrading to the latest version of Kunena, which is still Joomla 1.5 compatible.