text:
Q: Save imported sound into a notebook (so I can e-mail it) At the end of my code I'd like to put an imported (wav) sound. I would then play it with EmitSound[my_sound] when this cell will be evaluated. I can upload my wav file by specifying its location and of course EmitSound works fine:
zvok = Import[
    "F:\\Users\\disk_F\\Documents\\FAKS\\MEHanika_konstrukcij\\vaja3\\\
                New folder\\maribor_cutwav.wav"]

EmitSound[%]

But when I e-mail all this (both nb and wav file) the destination folder won't be the same, so the sound cannot be emitted.
What can I do?
(I've also tried simply to copy the graphics that is displayed when I import a sound. But then I don't know how to get a sound out of it automatically (with EmitSound)

If I press the play icon (triangular one), the sound is emitted, so there must be a way!
Any suggestions are welcome !

A: In general, when you want to share a notebook and a data file, it is easier if you use reference the file from a well defined location that is either:

*

*An absolute path that depends on the OS/user such as $HomeDirectory or $TemporaryDirectory.

*A directory relative to the directory that the notebook is in (you can move up/down the tree starting from NotebookDirectory[]
For instance, with the second option, you could do something like:
Import[FileNameJoin[{NotebookDirectory[], "maribor_cutwav.wav"}]]

and as long as the recipient places the file in the same folder as the notebook, it will work.
An alternative (if you don't want to attach a WAV file) is to embed the data in the current notebook. I believe just having the Sound object in the notebook is sufficient (I haven't tried), but it might throw some "unsafe dynamic content" warnings. As a workaround, you could do this:
sound = First@Import["/path/to/file.wav"];
SetOptions[EvaluationNotebook[], TaggingRules -> {"SoundData" -> sound}]

followed by
Sound@CurrentValue[{TaggingRules, "SoundData"}]

to recreate the sound object. The first two lines can also be safely deleted before sending the notebook and the recipient should still be able to play it.

A: You comment: I've also tried simply to copy the graphics that is displayed when I import a sound. But then I don't know how to get a sound out of it automatically.
You can work with sound files by dragging and dropping, then extracting the desired parts from the sound objects. For example, you can type
snd =

and then drag and drop the .wav file into the notebook. What you see is:

Now, to access the data within, you can look at the parts. If you type
snd[[1]]

you see a "SampledSoundObject". If you type
snd[[1,1]]

you see a pair of lists that are the stereo (left and right) channels of data. Using
snd[[1,1,1]]

gives the sampled data in the left channel and snd[[1,1,2]] gives sound data in the right channel. You can deal with these latter exactly as you normally would any list. For example,
ListPlot[snd[[1,1,1]],PlotRange->All]

plots it. You can rebuild the sound object directly by reversing the above procedure:
Sound[SampledSoundList[snd[[1,1,1]], 44100]]

After evaluation it looks and acts just like the graphic above. When you save the notebook, all of these steps are saved and there is no need to import the sound file the next time you (or someone else) opens it -- the sound data is embedded in the notebook. You can tell this is happening by looking at the size of the notebook: sound objects can be large, and the size of the notebook (in MB) will grow rapidly if you import a bunch of long sound objects.


text:
Q: For which $n$ are there primitive Pythagorean triples with legs of lengths $a$ and $a+n$? For which n can $a^{2}+(a+n)^{2}=c^{2}$ be solved, where $a,b,c,n$ are positive integers?
I have found solutions for $n=1,7,17,23,31,41,47,79,89$ and for multiples of $7,17,23$...
Are there infinitely many prime $n$ for which it is solvable?

A: The general primitive solution to $x^2+y^2 = z^2$ is given by: $x=u^2-v^2$, $y=2uv$, $z=u^2+v^2$, with $u,v$ relatively prime and not both odd.
For $(a,a+n,z)$ to be a primitive triple, we'd have to have a $(u,v)$ such that: $|u^2 - v^2 - 2uv| = n$.  We can rewrite that as: $(u-v)^2 - 2v^2 = \pm n$
So, setting $w = u-v$, we want to find $(w,v)$ which are relatively prime and $w$ is odd, with:
$$w^2-2v^2 = \pm n$$
This means that $n$ must be odd.
In fact, we can use unique factorization in $\mathbb{Z}[\sqrt{2}]$ to show that $n$ can be any product of primes of the form $8k\pm 1$.  Since there are infinitely many primes of the form $8k\pm 1$, the answer to your question is, "yes."
(Oh, and once you find one solution $(w,v)$ for a particular $n$, you can find infinitely many solutions for that $n$.)

A: $2a^{2}+2na+n^{2}=c^{2}$ --> $a=-\frac{-n+\sqrt{2c^{2}-n^{2}}}{2}$ --> there are solutions iff $x^{2}+n^{2}=2c^{2}$ has solutions --> find the set of the squares of all integers 0 in the set such that $y=2x-n$ then there is a primitive pythagorean triple with a difference of n between legs, and also for any multiple An if n>1 since if $k^{2}\equiv x(\mod{n})$ then $(Ak)^{2} \equiv Ax(\mod{An})$ -->  $Ay=2Ax-An$.

A: There are infinitely many Pythagorean triples where the difference between two legs is either $1$ or any of the infinite prime numbers $P\equiv\pm 1 \mod 8\quad$ taken to any non-zero power.
Under $100\quad
P\in \{1,7, 17, 23, 31, 41, 47, 49, 71, 73, 79, 89, 97\}.\quad $
To find these, we begin with Euclid's formula
$ \quad A=m^2-k^2,\quad B=2mk,\quad C=m^2+k^2\quad$ solve the $\quad (B-A)$ difference equation for $m$ and generate the $(m,k)$ values needed to feed Euclid's formula. Each iteration uses a seed $k$ which is either given or is the $m$-value of the previous iteration. Here is the formula for $P=1$ with a seed $k=1$. Note that $(m,k)$ are Pell numbers.
\begin{equation}
\quad m=k+\sqrt{2k^2+(-1)^k}
\end{equation}
\begin{align*}
k=1\space &\implies m=(1+\sqrt{2(1)^2+(-1)^1}\space)\big)=2\quad & F(2,1)=(3,4,5)\\
k=2\space  &\implies m=(2+\sqrt{2(2)^2+(-1)^2}\space)\big)=5\quad & F(5,2)=(21,20,29)\\
k=5\space  &\implies m=(5+\sqrt{2(5)^2+(-1)^5}\space)\big)=12\quad & F(12,5)=(119,120,169)\\
k=12\space  &\implies m=(12+\sqrt{2(12)^2 (-1)^{12}}\space)\big)=29\quad  & F(29,12)=(697,696,985)
 \end{align*}
For $P>1$, the formula is
\begin{equation}
 m=k+\sqrt{2k^2\pm P}
 \end{equation}
and there is more than one seed $(s)$ in a set $(k_1)$ each of which generates a subset of the entire set of triples for that difference. There is one more seed than the power $n$ of the prime number that is P. For example, $1$ is a zero power so there is $1$ seed.
$$P=1\implies k_1=\{s1\}=\{1\}\quad
P=7^1\implies k_1=\{s1,s2\}=\{2,1\}\\
P=343=7^3\implies k_1=\{s1,s2,s3, s4\}=\{14,16,3,7\}$$
The elements of $k_1$ are generated as follows.
\begin{equation}
\end{equation}
\begin{align*}
\text{where}\quad s_i=\sqrt{\frac{j_i^2 + P}{2}}
\\  &\text{for}\space\space\space 1 \le i \le \bigg\lceil\frac{(n+1)}{2}\bigg\rceil \space
  \land \space \space                                      1 \le j_i                \le  \lfloor\sqrt{X}\rfloor\\
\text{where}\space s_i=\sqrt{\frac{j_i^2-P}{2}}
\\ &\text{for}\space    \bigg\lceil\frac{(n+1)}{2}\bigg\rceil + 1 \le i \le (n+1)\space
  \land \space    \lfloor\sqrt{P} +1 \rfloor \le j_i \le  \lfloor\sqrt{2P}\rfloor
\end{align*}
For example, we have $n=3, P=7^3=343\\$
\begin{align*}
 1 \le   & i \le   2
 \space             1 \le     & j \le \lfloor\sqrt{343}\rfloor=18
 \space  \\
s_1=\sqrt{\frac{7^2+343}{2}}=14\space\quad  &  s_2=\sqrt{\frac{13^2+343}{2}}=16  \\
3 \le  & i \le  4
\space  19 \le    &  j  \le \lfloor\sqrt{2(343)}\rfloor=26
 \space   \\
s_3= \sqrt{\frac{19^2-343}{2}}=3 \quad
&  s_4=\sqrt{\frac{21^2-343}{2}}=7  \
 \end{align*}
\begin{align*}
s_1= 14\quad
     &14+\sqrt{2(14)^2-343}=21\quad   &F(21,14)=(245,588,637)\\
     &21+\sqrt{2(21)^2+343}=56\quad   &F(56,21)=(2695,2352,3577)\\
s_2=16 \quad
      &16 +\sqrt{2(16)^2-343}=29\quad  &F(29,16)=(585,928,1097)\\
      &29 +\sqrt{2(29)^2-343}=74\quad  &F(74,29)=(4635,4292,6317)\\
s_3=3 \quad
      &3+\sqrt{2(3)^2+343}=22\quad  &F(22,3)=(475,132,493)\\
      &22+\sqrt{2(22)^2+343}=47\quad  &F(47,22)=(1725,2068,2693)\\
s_4=7 \quad
      &7 +\sqrt{2(7)^2+343}=28\quad  &F(28,7)=(735,392,833)\\
      &28+\sqrt{2(28)^2+343}=63\quad  &F(63,28)=(3185,3528,4753)\\
 \end{align*}
For $P=1$
These $(m,k)$-values
may be generated directly using a Pell-related equation as follows.
\begin{equation}
 m_n= \frac{(1 + \sqrt{2})^{n+1} - (1 - \sqrt{2})^{n+1}}{2\sqrt{2}}\qquad \qquad\qquad
 k_n= \frac{(1 + \sqrt{2})^n - (1 - \sqrt{2})^n}{2\sqrt{2}}
 \end{equation}
For example
{\small
\begin{align*}
\frac{(1 + \sqrt{2})^{2} - (1 - \sqrt{2})^{2}}{2\sqrt{2}}=2 \quad
     \frac{(1 + \sqrt{2})^1 - (1 - \sqrt{2})^1}{2\sqrt{2}}=1 \quad&  F(2,1)=(3,4,5)\\
 \frac{(1 + \sqrt{2})^{3} - (1 - \sqrt{2})^{3}}{2\sqrt{2}}=5 \quad
     \frac{(1 + \sqrt{2})^2 - (1 - \sqrt{2})^2}{2\sqrt{2}}=2 \quad&  F(5,2)=(21,20,29)\\
\frac{(1 + \sqrt{2})^{4} - (1 - \sqrt{2})^{4}}{2\sqrt{2}}=12 \quad
      \frac{(1 + \sqrt{2})^3 - (1 - \sqrt{2})^3}{2\sqrt{2}}=5 \quad& F(12,5)=(119,120,169)\\
\frac{(1 + \sqrt{2})^{5} - (1 - \sqrt{2})^{5}}{2\sqrt{2}}=29 \quad
     \frac{(1 + \sqrt{2})^4 - (1 - \sqrt{2})^4}{2\sqrt{2}}=12 \quad& F(29,12)=(697,696,985)
 \end{align*}
}

A: If you solve expression for $n$ you get
$n=\sqrt{c^2-a^2}-a$, let's denote $b=\sqrt{c^2-a^2}$,so we have that $n=b-a$
Now,take look at picture bellow.Note that $AD=a$,and $BD=b-a=n$
If you change value of $b$ and keep $a$ to be constant you will get a infinite number of right triangles,and therefore infinite number of values of $n=b-a$,so answer is yes, there are infinitely many primes $n$ for which equation is solvable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can referer header be trusted when using https? I understand that the referer header is trivial to spoof when using standard http. But when using https can you trust the referer or is that potentially faked as well?

A: No. Using HTTPS changes nothing; the referer can still trivially be spoofed; for example:
wget --referer=http://whitehouse.gov/ https://example.com/


text:
Q: Need help creating a multiplier using a method in iJVM I'm trying to create a program in iJVM using a .jas file with a MIC-1 ASSEMBLER to input two numbers by keyboard and multiply them together to get an out put
EX:
2*2=4
In the code below I just bipushed random numbers because when i used 'in' to get input it wasn't giving me an input
When I bipush 7 and bipush 2 just in main without a method the output is:
EX:
Input x: 20
Input y: 2
I get the ascii digit so Im assuming its taking hex 0x20 and 0x02 and multiplying that to get 0x40 and outputting the ascii character
.main
.var
x
y
sum
.end-var
    BIPUSH  7
    ISTORE  x
    BIPUSH  5
    ISTORE  y
    BIPUSH  0x40
    INVOKEVIRTUAL   imul
    out

.end-main

.method imul(x,y)
.var
x
y
temp
sum
.end-var
    BIPUSH  2
    ISTORE  x
    BIPUSH  20
    ISTORE  y
L1:
    BIPUSH  0
    ISTORE  sum
    GOTO    L2

L2: ILOAD   y
    IFEQ    exit

    POP
    ILOAD   x
    DUP
    IADD
    ISTORE  temp
    GOTO    L3

L3: ILOAD   y
    BIPUSH  2
    ISUB
    ISTORE  y
    GOTO    L4

L4: ILOAD   temp
    ILOAD   sum
    IADD
    ISTORE  sum
    GOTO    L2

exit:   ILOAD   sum
    IRETURN

.end-method


text:
Q: Gracefully handling ConstraintValidationExceptions in Hibernate There are a LOT of posts on S.O. an other sites related to performing Hibernate validation, catching exceptions, and so forth. However, all of them put me up against some very unideal design choices in the situation described below.  This seems like such a common situation I can't believe there's not a clean solution.

*

*I want to leverage Javax's (and Hibernate's) validation annotations,

*I want to correct, or throw out, invalid objects,

*I want to leverage javax's PrePersist, etc annotations to handle repetitive or time-based actions on my objects.

Using the three in concert doesn't seem to work.

*

*When an exception occurs Hibernate won't let you commit a transaction. I'll get a constraint violation exception anytime I have an invalid object. I can't find authoritatively if a ConstraintViolationException is included in this, or treated as a special case[1], however...

*I seem to be able to proceed if I catch a ConstraintViolationException and move on to the next object, but Hibernate complains when I try to flush or commit the transaction because I have objects which have not been assigned an id (by the database).

*

*I thought about trying to set the object to null or using session.evict(myObject) without success to "break" the knowledge Hibernate has about the object.

*I could [run the validation "manually"] before I try to save it(http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#d0e2697), at the cost of it being performed twice--which seems silly, but that doesn't call the @PrePersist hooks, leading to erroneous violations.

What does one do?
To be concrete, I have lots (10,000+) objects, a small handful of which are always going to be invalid.
@Entity
public class myPojo implements Serializable {

  @Id
  @GeneratedValue
  private long id;

  @NotBlank
  private String anotherString;

  @NotNull
  @Temporal(TemporalType.TIMESTAMP)
  private Date createdAt;

  @NotNull
  @Temporal(TemporalType.TIMESTAMP)
  private Date updatedAt;

  @NotNull
  @Temporal(TemporalType.TIMESTAMP)
  private Date postedDate;

  @PrePersist
  protected void onPrePersist() {
    this.createdAt = new Date();
    this.updatedAt = this.createdAt;
    if (this.postedDate == null)
      this.postedDate = this.createdAt;
  }
}

I want to save this function, and catch any objects with constraint violations:
void saveResource(MyPojo myPojp) {
  try {
    session.saveOrUpdate(mypojo);
  }
  catch (final ConstraintViolationException ex) {
     System.err.println("Could not save " + myPojo + " because " +
        this.getValidationErrors(myPojo));
  }
}

Where getValidationErrors() returns a String of all the ConstraintViolations that are found by manually creating and using a validation factory.
The only other possibilities I know of are performing a single transaction around each save (which seems like a bad idea since if real exceptions do occur I don't want ANY of the items to persist) or perhaps writing a custom validator to be run manually before I call save that calls the prepersist hooks (maintainability nightmare!).
[1]: I know that's a crummy reference, but I've been doing so much reading I can't find it again. Would be happy for someone to clarify in more technical details what errors cause a transaction to become invalid vs are recoverable.

A: Thought 1: why put application level validation annotations on fields you're managing yourself in the PrePersist, that aren't set by users?
Thought 2: You could use Validation groups so that you can pre-check only those fields that are set at the user level and ignore the system managed ones.

A:   public interface PersistValidationGroup { }

  @NotBlank
  private String anotherString;

  @NotNull(groups={PersistValidationGroup.class})
  @Temporal(TemporalType.TIMESTAMP)
  private Date createdAt;

  @NotNull(groups={PersistValidationGroup.class})
  @Temporal(TemporalType.TIMESTAMP)
  private Date updatedAt;

  @NotNull(groups={PersistValidationGroup.class})
  @Temporal(TemporalType.TIMESTAMP)
  private Date postedDate;

Then, when you validate manually:
validator.validate(object, javax.validation.groups.Default.class);

At this point, only those fields marked with the Default validation group (which by the way is what is used if you leave the "groups" attribute blank) will be validated.  Anything in the PersistValidationGroup would not be validated.
However, hibernate will call like this I believe:
validator.validate(object);

So all groups would be validated.


text:
Q: How do you ask about the struggle? Let's imagine we meet a scientist who has just invented a robot which according to him is a pretty great achievement. However, when we see it, it looks simple and doesn't look like someone has to do a great amount of analysis and modelling to make it. How do we ask the scientist about how this robot, which he claims to be one of his masterpieces, is so special when it doesn't look like a big deal to us? We could try:

Is this really difficult to invent?
Is this really such a big deal?

This sounds as if we are disparaging his efforts. What would be the right way to ask the same? I would like to know the challenges he faced while making it and why his product was noble. The question is not just limited to a scientist, it could be applicable to almost anyone who is in some or other profession and has done something great.

A: Since you have used the politeness tag...
You could ask:

What is it about this robot that makes it an advance?

That form of the question acknowledges that it may well be an advance over current art, while expressing the doubts you have based on the thing's rudimentary appearance.
An alternative construction

What makes this robot an advance?

is more like a challenge to its inventor, and could be taken as scoffing.
I assume we're talking about writing, where tone of voice is difficult to encode.  In speech, politeness is 80% tone of voice, 20% word choice.

A: "Is this really such a big deal?" might come off too harsh on him. He might get offended too. You should ask him in a polite way. If you offend him, it is very unlikely that he explains things to you properly. He might just swear the living hell out of you. So you have to be very careful, at the same time ask a question in a way that he doesn't find it annoying to answer. After all, we do not want to piss off a scientist. You could try a few questions like :

*

*How hard was building a robot ?

*What all did you have to sacrifice to create something revolutionary as this robot ?

*What does your robot posses that makes it unique ?

*How does your robot look so simple and yet be so complex ?

The main intention is to make him feel great about his work. A happy and proud scientist can go on and on about his work. From that, I'm sure you'll get to know all that you need to know. Even though it may look simple and is simple to create, you best talk to him as if he just gave life to the greatest invention on this planet. That way, he'll let you in on all the little things you can do to make things right and he'll pretty much give you a lot of tips to build your own robot. Its a bit sly, but that's pretty normal in this world. Cheers !


text:
Q: Using HTML in PHP If Statement I have a PHP file in Wordpress that has some HTML, "Login & Register" that I would only like to show when a member of the site is not logged in. When they are logged in I would like it to show "Welcome, [name]."
I'm just not sure how to use HTML in a PHP If statement. The condition is this:
<?php
      if ( member_is_logged_in() ) {
         print "Welcome [name]";
      } else {
         print "Login | Register";
      }
?>

That's how I think it should look, but it's not working. I'm not that great with PHP, but I would appreciate any help. Thanks!

A: You can use PHP variables in double quoted strings. so just replace [name] with $name or whatever the variable is. Note this will not work with single quotes.
Also, you have two sets of double quotes in the else case. This will result in a syntax error. Make one of them single quotes or escape the inside quotes.
<?php
      if ( member_is_logged_in() ) {
         print "Welcome $name";
      } else {
         print 'Login | Register';
      }
?>

You can also just end the PHP tag and write the HTML directly.
<?php
      if ( member_is_logged_in() ) {
         print "Welcome $name";
      } else {
?>
         Login | Register
<?php
      }
?>

There exists a better and easier to read syntax for this:
<?php if(<your evaluation here>): ?>
HTML for when true
<?php else: ?>
HTML for when false
<?php endif; ?>

Check out Alternative syntax for control structures for more information on this.
And while we're at it, print vs echo, which one is faster?

A: simply:
<?php
      if ( member_is_logged_in() ) {
         print "Welcome $name";
      } else { ?>
         Login | Register
      <?php }
?>

A: If you can use wordpress try below code:
See Utl:- http://codex.wordpress.org/Function_Reference/wp_get_current_user
E.g.: To determine if there is a user currently logged in, do this:
<?php
$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) {
    // Not logged in.
} else {
    // Logged in.
}
?>

A: Try this code chunk and let me know---
<?php
      if ( member_is_logged_in() ) {
    global $display_name;
    get_currentuserinfo();
         print "Welcome ".$display_name;
      } else {
         print "Login | Register";
      }
?>


text:
Q: Loop won't repeat only does one time through instead of repeatedly doing it I recently got assigned a homework to make code in a different language, the only language I have worked with in python. What my code should do is ask the user for an input, and then first set it as the high, low and start calculating an average. However, I'm having 2 problems right now. One, my line 24 says string can't convert to an integer. However, I though I already told the program to allow it. If someone could help me that would be greatly appreciated.
package hgp.pkg13.pkg16;

import java.util.Scanner;
public class HGP1316 {
//Declaration of variables
static int Running_total = 0;
static double Average = 0.0;
static int User_input = 0;
static double counter = 0.0 ;
static int Highest_input = -1;
static int Lowest_input = -1;
public static void main(String[] args) {
    //Intro Program (Optional)
    {
  System.out.println("This program will give you the highest, lowest, and average of the integers you \n"
          + "enter. To end enter a negative number ");
}
//2. Ask user to enter a positive integer (or a negative integer to stop)
//3. Record the user's input
//4. Test the input >= 0
while (User_input >=0){
Scanner user_input = new Scanner( System.in );
Integer User_input;
System.out.print("Please enter an integer: ");
 User_input = user_input.nextInt();
//4a. If it is true that input >= 0
if (User_input >= 0)
{

    //4a1Add the input to "running total"
Running_total = Running_total + User_input;
    //4a2. Increment "number of inputs counter"
counter = counter + 1;
//4a3. Test if "number of inputs counter" is equal to 1
if (counter == 1)
{
     //4a31. If true, replace both "highest input" and "lowest input" with the input
Highest_input = User_input;
Lowest_input = User_input; }

//4a5. If the input > "highest input" then replace "highest input" with input
if (User_input > Highest_input)
{
    Highest_input = User_input;
}
//4a6. If the input < "lowest input" then replace "lowest input" with input
if (User_input < Lowest_input)
{
    Lowest_input = User_input;
}
//4b. If false
    //4b1. Goto step 5
 else;
{
 //5. Calculate average (formula: "running total" /"number of inputs counter" )
    Average = (Running_total / counter);
 //6. Display/communicate "highest input", "lowest input" and average
   System.out.println ("The Highest value entered was : "+ Highest_input);
   System.out.println ("The Lowest value entered was : " + Lowest_input);
   System.out.println("The Average of enteries was : "+ Average);
//7. Terminate
}

 }
}
}
}

The problem that I have now encountered is it goes through the whole loop instead of reasking for the users input. It is probably to do with my {} but I'm not sure

A: You're taking in the user input as a User_input = user_input.next(); when instead in java you need to use User_input = user_input.nextInt();. This tell the program that is is expecting an Integer input instead of another datatype/string/parameter.
Hope this helps


text:
Q: Django many-to-many :how to get the id I have models with manytomany field:
class Brand(models.Model):
    Company_Group = models.ManyToManyField(Company)

class Company(models.Model):
    Pref_Company_Name_Flg = models.CharField(u'Preferred Name Flag',max_length=255, default="")
    Pref_Company_Name = models.CharField(u'Preferred Name',max_length=255, default="")

I want to filter the id of brands in containing "company_instance"
brands = Brand.objects.all()
company_instance=company.objects.filter(id =company_id)
for brand in brands:
    for i in Brand.Company_Group.through.objects.filter(Company_Group = brand):
        print i.id

I have found the Similar problem as follows: click here
but Report errors :
Cannot resolve keyword 'Company_Group' into field. Choices are: brand, brand_id, company, company_id, id

then I try this way,also Report errors:
type object 'Brand' has no attribute 'Company_id'

Thanks andvance

A: You could just use the reverse relation from Company instance like,
company = Company.objects.get(id=company_id)
company.brand_set.all() #this would return all Brand instances
                        #with company instance.


text:
Q: Dynamically set scss variables angular ionic I have an API call that would get a json with my scss colours, such as
dynamic-colour: #5260ff

but this variable doesn't get called until run time of the ionic app. Was setting scss variables dynamically before compile time even possible?
From most of the angular examples I've seen, they already have a preset colour set, and I don't see any examples of what I want to achieve. Is it possible to preset a variable, but override it when running the app?
Anyone know anyways to accomplish dynamically getting scss variables from an API call and setting global variable values? I believe it's possible to run a typescript function to override each page's scss with what I want.

A: SCSS is compiled to CSS during compile time, and SCSS variables are replaced with resolved value during compile time, which means there is no way to change the variable during run time. However css variables just sits there and you can easily change them,
for instance:
:root{
   --dynamic-colour: #5260ff
}

now you can change its value from your component like:
changeColor(color:string){
   document.documentElement.style.setProperty('--dynamic-colour', color);
}

Also you can assign --dynamic-colour to your scss variable as well so you wont have to do change in multiple places:
$dynamic-colour: var(--dynamic-colour);

STACKBLITZ WORKING DEMO


text:
Q: Using dom-to-image in an ionic react app (typescript) - "Uncaught TypeError: Cannot read properties of undefined (reading 'toPng')" I receive the error in the title when calling the following function in my app.
  let container = this.myRef.current!;

  DomToImage.toPng(container)
    .then(function (dataUrl) {
      var img = new Image();
      img.src = dataUrl;
      document.body.appendChild(img);
    })
    .catch(function (error) {
      console.error("something went wrong!", error);
    });
}

I installed the library with
npm install dom-to-image
and then ran the following to add the types necessary for using the library with typescript
npm i --save-dev @types/dom-to-image-more
The console.log of container correctly outputs the HTML I expect.
No errors show in VSCode and intellisense can find the interface for DomToImage and toPng
  toSvg(node: Node, options?: Options): Promise<string>;
  toPng(node: Node, options?: Options): Promise<string>;
  toJpeg(node: Node, options?: Options): Promise<string>;
  toBlob(node: Node, options?: Options): Promise<Blob>;
  toPixelData(node: Node, options?: Options): Promise<Uint8ClampedArray>;
}

Here is the full error if that is helpful
Summary.tsx:345 Uncaught TypeError: Cannot read properties of undefined (reading 'toPng')
    at Summary.exportToPng (Summary.tsx:345:1)
    at onClick (Summary.tsx:617:1)
    at newProps.onClick (createComponent.tsx:96:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237:1)
    at invokeGuardedCallback (react-dom.development.js:292:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:306:1)
    at executeDispatch (react-dom.development.js:389:1)
    at executeDispatchesInOrder (react-dom.development.js:414:1)
    at executeDispatchesAndRelease (react-dom.development.js:3278:1)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:3287:1)
    at forEachAccumulated (react-dom.development.js:3259:1)
    at runEventsInBatch (react-dom.development.js:3304:1)
    at runExtractedPluginEventsInBatch (react-dom.development.js:3514:1)
    at handleTopLevel (react-dom.development.js:3558:1)
    at batchedEventUpdates$1 (react-dom.development.js:21871:1)
    at batchedEventUpdates (react-dom.development.js:795:1)
    at dispatchEventForLegacyPluginEventSystem (react-dom.development.js:3568:1)
    at attemptToDispatchEvent (react-dom.development.js:4267:1)
    at dispatchEvent (react-dom.development.js:4189:1)
    at unstable_runWithPriority (scheduler.development.js:653:1)
    at runWithPriority$1 (react-dom.development.js:11039:1)
    at discreteUpdates$1 (react-dom.development.js:21887:1)
    at discreteUpdates (react-dom.development.js:806:1)
    at dispatchDiscreteEvent (react-dom.development.js:4168:1)

Any idea where I am going wrong? I don't understand how 'ToPng' can be undefined. Thank you!

A: I am using Ionic with Angular.
I import domToImage:
import domToImage from 'dom-to-image-improved';

Then instatiate it in the method:
const domToImageOptions = { bgcolor: 'white', height: this.heightOfDom + 10, width: this.widthOfDom + 10 };

const result = await domToImage.toPng(this.printableArea, domToImageOptions);

The result is a base64 image


text:
Q: Proving or disproving a statement about discontinuity
I'm trying to disprove this statement, but as spend more time on it I'm beginning to think it might actually be true.
How should I approach on proving/disproving this statement?

A: Im not giving a complete solution but something to start with. Assume $g=fD$ is continous at $x_0$. Then for $\epsilon>0$ there exists $\delta_{\epsilon}>0$, such that
$$|g(x)-g(x_0)|<\epsilon \;\text{for all}\; |x-x_0|<\delta_{\epsilon}\tag{1}$$
Take $r\notin\mathbb{Q}$ with $|r-x_0|<\delta_{\epsilon}$. Plugging $r$ into (1) we get that $\epsilon>|g(r)-g(x_0)|=|g(x_0)|$. Since $\epsilon$ was arbitrary we have that $g(x_0)=0$. From there try to argue that $f(x_0)=0$.
The other direction is also straight forward using epsilon-delta criterion.

A:
Let $\;f\;$ be a function that is continuous at $\;x_0\in\mathbb{R}\;.$ Then $\;g=f\cdot D\;$ is continuous at $\;x_0\;$ if and only if $\;f(x_0)=0\;,\;$ where $\;D(x)=\begin{cases}1\quad x\notin\mathbb{Q}\\0\quad x\in\mathbb{Q}\end{cases}.$

First I prove that
$g(x)\;$ continuous at $\;x_0\;\implies\;f(x_0)=0\;.$
If $\;f(x_0)\;$ were $\;\neq0\;,\;$ since $\;f(x)\;$ and $\;g(x)\;$ are continuous at $\;x_0\;$, the function $\;D(x)=\dfrac{g(x)}{f(x)}\;$ would be continuous at $\;x_0\;$ too, but it is impossible because $\;D(x)\;$ is a nowhere continuous function.
Now, I prove that
$f(x_0)=0\;\implies\;g(x)\;$ continuous at $\;x_0\;.$
$\begin{align}\bigl|g(x)-g(x_0)\bigr|&=\bigl|f(x)D(x)-f(x_0)D(x_0)\bigr|=\\&=\bigl|f(x)D(x)\bigr|\leqslant\bigl|f(x)\bigr|= \bigl|f(x)-f(x_0)\bigr|\;.\end{align}$
Since $\;f(x)\;$ is continuous at $\;x_0\;$, then
$\forall\;\varepsilon>0\;$ there exists $\;\delta>0\;$ such that
$\;\bigl|x-x_0\bigr|<\delta\implies \bigl|g(x)-g(x_0)\bigr|\leqslant\bigl|f(x)-f(x_0)\bigr|<\varepsilon\;.$
Hence, by definition, $\;g(x)\;$ is continuous at $\;x_0\;.$

A: Counter-example:
Let $f(x)=x$ for every $x.$ Let $x_0=0.$ Let $\epsilon =1/3.$
For any $\delta >0$ there exist $x'$ and $x''$ in $(-\delta +x_0,\,\delta +x_0)$ with $x'\in \Bbb Q$ and $x''\not\in \Bbb Q.$ Then $g(x')=f(D(x'))=f(1)=1$ and $g(x'')=f(D(x''))=f(0)=0.$
So it cannot be true that $|g(x)-g(x_0)|<\epsilon$ for all $x\in (-\delta +x_0,\,\delta +x_0),$ else we would have $1= |g(x')-g(x'')|\le |g(x')-g(x_0)|+|g(x_0)-g(x'')|<2 \epsilon=2/3. $
So $g$ is not continuous at $x_0$ but we still have $f(x_0)=f(0)=0.$


text:
Q: How to recreate /var/lib/dpkg/status? When I run sudo apt update in Ubuntu 18.10 I get this error message:
E: flAbsPath on /var/lib/dpkg/status failed - realpath (2: No such file or directory)
E: Could not open file  - open (2: No such file or directory)
E: Problem opening
E: The package lists or status file could not be parsed or opened.

After running sudo cp /var/lib/dpkg/status-old /var/lib/dpkg/status it's showing this error message:
cp: cannot stat '/var/lib/dpkg/status-old': No such file or directory

A: Restore the /var/lib/dpkg/status file from its backup file (/var/lib/dpkg/status-old). Open the terminal and type:
sudo cp /var/lib/dpkg/status-old /var/lib/dpkg/status

Then run sudo apt update again.

If that doesn't work run the following commands:
sudo touch /var/lib/dpkg/status
sudo apt update && sudo apt upgrade
sudo reboot
sudo apt full-upgrade

A: Run the following commands:
sudo mkdir -p /var/lib/dpkg/{alternatives,info,parts,triggers,updates}
sudo cp /var/backups/dpkg.status.0 /var/lib/dpkg/status
sudo apt-get download dpkg
sudo dpkg -i dpkg*.deb
sudo apt-get download base-files
sudo dpkg -i base-files*.deb
sudo apt-get update
sudo apt-get check

A: My /var/lib/dpkg/status file got deleted and according to apt I had no packages installed, as it determines them from the status file. I used the following method to regenerate the /var/lib/dpkg/status file. The method worked very fine for me in Kali GNU/Linux, which is Debian-based.
NOTE:

*

*This method assumes that all installed packages have created entries in the /usr/share/doc directory.

*This method starts from an empty /var/lib/dpkg/status file.

*This method may not work if you have more than 1 repository providing the same package. If you do have more than 1 repository providing the same package, temporarily disable the subsidiary repo, then delete the package cache lists for the repo in /var/lib/apt/lists/.

*

*Delete the current status and status-old files. Make a backup of the files before deletion incase you get errors.
mkdir ~/dpkg-status-backup
cp /var/lib/dpkg/{status,status-old} ~/dpkg-status-backup
rm /var/lib/dpkg/{status,status-old}

*Get list of all packages installed, one package per line.
Note: it's 1 (one) not l (lower-case L).
ls -1 /usr/share/doc > installed-packages.list

*Rewrite the packages list into one line.
tr '\n' ' ' < installed-packages.list > installed-packages-one-line.list

*Create an empty status file to enable apt-cache to run.
touch /var/lib/dpkg/status

*Generate package records using apt-cache.
cat installed-packages-one-line.list | xargs apt-cache show > raw-status-file

*The raw-status-file may contain Status: fields for some packages. Delete them to avoid duplication.
sed -i '/^Status:/d' raw-status-file

*Add the Status:  field for every package to indicate to apt & dpkg that they're installed.
sed -i 's/^Package:.*/&\nStatus: install ok installed/' raw-status-file

*Remove fields unwanted by dpkg in status file: SHA1:, SHA256:, MD5sum:, Description-md5:, Size: & Filename: .
sed -i '/^MD5sum:/d' raw-status-file
sed -i '/^SHA1:/d' raw-status-file
sed -i '/^SHA256:/d' raw-status-file
sed -i '/^Size:/d' raw-status-file
sed -i '/^Filename:/d' raw-status-file
sed -i '/^Description-md5:/d' raw-status-file

*The resultant raw-status-file after running the above commands is now the actual dpkg status file.
mv raw-status-file status

*Copy the status file to /var/lib/dpkg/ as status and status-old.
cp status /var/lib/dpkg/status
cp status /var/lib/dpkg/status-old

*Now run dpkg to validate your new status file. If you get errors, take hints from dpkg's error report, & solve accordingly. If you get no errors, then the status file has the correct syntax.
dpkg --get-selections

*Re-enable the disabled repos then run apt to update package cache lists to prevent the error packages have unmet dependencies.
apt update

*If you run into packages have unmet dependencies error in apt, then make sure you've enabled the subsidiary repos that provide the dependencies, then run aptitude. I prefer aptitude because it's better at solving package installation errors.
aptitude full-upgrade

If you get no errors/your errors have been resolved from apt or dpkg, and get "PACKAGE is already the newest version..." when you try to install a program you're sure is already installed, such as coreutils, then you've successfully regenerated the dpkg status file.
Clean-up the temp files created and the backup.
rm installed-packages.list installed-packages-one-line.list status
rm -r ~/dpkg-status-backup


text:
Q: Browserify gives me Uncaught TypeError: Cannot read property 'prototype' of undefined I have tried installing npm browserify globally with a command npm i -g browserify. Then I wrote in terminal browserify app.js -o bundle.js command, which created bundle.js file, and then I went to my index.html and I changed my script to <script defer src="bundle.js"/> . I went to check and indeed error Uncaught referenceError: require is not defined is gone, but I have this new error:
bundle.js:41149 Uncaught TypeError: Cannot read property 'prototype' of undefined
    at Object.<anonymous> (bundle.js:41149)
    at Object.236../utils (bundle.js:42251)
    at o (bundle.js:1)
    at bundle.js:1
    at Object.232../application (bundle.js:40389)
    at o (bundle.js:1)
    at bundle.js:1
    at Object.230../lib/express (bundle.js:39717)
    at o (bundle.js:1)
    at bundle.js:1
(anonymous) @ bundle.js:41149
236../utils @ bundle.js:42251
o @ bundle.js:1
(anonymous) @ bundle.js:1
232../application @ bundle.js:40389
o @ bundle.js:1
(anonymous) @ bundle.js:1
230../lib/express @ bundle.js:39717
o @ bundle.js:1
(anonymous) @ bundle.js:1
(anonymous) @ bundle.js:36124
206._process @ bundle.js:36133
o @ bundle.js:1
r @ bundle.js:1
(anonymous) @ bundle.js:1

A: This is my app.js file, index html has nothing in it. And bundle.js has like 60k lines of code, I can't show it.
const express = require("express");
const app = express();

const PORT = process.env.PORT || 5500;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});


text:
Q: Solve $T(n)=2T(\frac{n}3)+\log_3(n)$ for n>1, n a power of 3 Solve the following recurrence equation using the characteristic equation.
$T(n)=2T(\frac{n}3)+\log_{3}n$ for $n>1$, $n$ a power of $3$
$T(1)=1$
I'm not quite sure I understand exactly what to do here. I've done this much on my own
Let $n=3^k$, $k=\log_{3}n$
$T(3^k)=2T(\frac{3^k}{3})+k$
$T(3^k)=2T(3^{k-1})+k$
Let $t_{k}=T(3^k)$
$t_{k}=2t_{k-1}+k$
But that's as far as I can get. After that, I'm completely lost. Even when I'm trying to follow the example in the book, it seems like either a lot of intermediate steps are skipped or the example doesn't fit my question. Any assistance would be appreciated.

A: We can actually solve this recurrence exactly and not just for powers of three, at any rate one that is very close. Consider
$$T(n) = 2 \; T(\lfloor n/3\rfloor) + \lfloor\log_3 n\rfloor+1$$
with $T(0) = 0$ and which has $T(1) = 1.$ The constant one has lower order than the logarithm so the complexity is the same as in the original query. (Note $|\lfloor\log_3 n\rfloor-\log_3 n | < 1$ and that $|\lfloor\log_3 n\rfloor+1-\log_3 n | < 1$ so adding in one introduces the same error as using the floor alone.)
The key observation is that the answer does not depend on $n$ but only on the number of digits in base three that it has, i.e. the logarithm.
If $$n= \sum_{k=0}^{\lfloor\log_3 n\rfloor} d_k 3^k
\quad\text{then}\quad
T(n) = \sum_{k=0}^{\lfloor\log_3 n\rfloor} 2^k \; (\lfloor\log_3 n\rfloor+1-k)
= 4 \times 2^{\lfloor\log_3 n\rfloor} -\lfloor\log_3 n\rfloor -3.$$
This formula is exact for all $n.$
Now clearly the dominant term is the exponential one which gives the following complexity:
$$\Theta\left(2^{\lfloor\log_3 n\rfloor}\right) =
\Theta\left(3^{\log_3 2 \times \lfloor\log_3 n\rfloor}\right) =
\Theta(n^{\log_3 2}).$$
This is of course the same as what the Master theorem would produce. Here is another calculation of the same type  that is a bit more advanced.

A: Look carefully and I think you can see that $t_{n+1}$ = $t_n + 3$.  Now run that observation back to T(1)  = 1 $\Rightarrow t_1 = 1$.  At this point you should be able to write $t_n$ just in terms of n and without any other t's.

A: You have $t_k - 2t_{k-1} = k$ with the condition $t_0 = 1$ (why?)
The characteristic equation would have been  $x-2 = 0$ if the equation was homogeneous (i.e. RHS was $0$). This would have given us the solution $t_k = a 2^k$.  However given that there is a linear function in the RHS, we should explore solutions of form $t_k = a 2^k + (bk + c)$.
Substitute in the recurrence and see if we can find values for $b, c$ s.t. the recurrence holds for all $k$.  Then use the initial condition to find $a$...


text:
Q: Word Mover's distance calculation between word pairs of two documents According to WMD paper, travel cost or Euclidean distance between word pairs is calculated the way shown in the figure below.

Is this distance calculated in pair wise in a specific order? Such that the first, second and so on from each document as shown in the figure Or Obama's distance is calculated from all four words in D0 and then the minimum of these four is shown in the figure only.
Can someone explain how this works?
Also, why is then all three words in D3 compared with President in D0?

A: Each word in a document is matched against all other words, but weighted by a flow matrix $\bf{T}$ (with constraints $d_i$, viz., $d_j$ for each row/column). That ensures the resulting distance will be symmetric, even when there is an unequal number of words that need to be matched. The idea for the WMD is based on the "Earth Mover's Distance" (EMD), originally published by Rubner et al. (2000), for measuring image similarities.
If both sentences have an equal number of words to compare (like $D_1$ and $D_0$), that leads to a flow [matrix] that pairs up (or "moves") only the words with the closest distances. I.e., leading to a solution for the matrix $\bf{T}$ where each row and column will have only one non-zero value, namely exactly the constraint's value (here, the sum of flow weights in every row and column must be 0.25, $d_i = d_j = 1/4 = 0.25$, because there are four words), for the best matching pair. Then, the distance between two sentences is the sum over the Euclidian distances [1] between closest word pairs, divided by the number of words. Put differently, the contribution of each pair to the overall distance "sum" is weighted by the flow matrix $\bf{T}$, that is, with 0.25 for each of the closest pairs and zero for all other possible pairings. That means, the flow matrix will only have a single non-zero value in each row and column in cases when both documents have the same number of words. Rather trivial, indeed - so far...
However, for the $(D_0, D_3)$ pair, figuring out the flow matrix $\bf{T}$ gets far more tricky: Each word in $D_3$ now has to be paired with more than one word in $D_0$. That is, because this time the flow constraints are $d_i = 1/4 = 0.25$ and $d_j = 1/3 = 0.33\dot3$, the resulting flow matrix must have more than one non-zero values in each of its three columns (words from $D_3$). Indeed, for a truly proper solution of this flow problem, you might expect that hardly any word pairing will have a flow of exactly zero.
Taking a "relaxed" approach to figuring out the flow matrix, we can simply move each word in $D_3$ to some unique match in $D_0$, with a weight of 0.25 (NB: Keep in mind, the words must not necessarily be paired with their best matches, only some unique match; You will understand why in a bit.) Then, for the remaining flow from each word in $D_3$ ($0.3\dot3 - 0.25 = 0.08\dot3$ here), we simply assign it to the only word in $D_0$ that was not yet matched (here, "President"). Therefore, each of the three columns in $\bf{T}$ (for the three words in $D_3$) will sum to $0.33\dot3$, just as the constraint $d_j$ requires. And each of the four rows (words in $D_0$) will sum to 0.25, either because the word is uniquely matched with that particular weight to a word in $D_0$, or because the word gets "divided up" among all three words in $D_3$, each with a weight of $0.08\dot3$ (because $0.08\dot3 \times 3 = 0.25$), thereby fulfilling the constraint $d_i$ (for each row, including the one for "President").
The interesting (or hard, depending on how you see it) part now is how to choose the unique matches and the remainder word(s). Note the arrows in Figure 2, bottom, seems to not represent the most logical flow; It seems counter-intuitive that "speaks" is not moved onto "greets" at all and only gets moved to "press" and "President", and that "Obama" is not primarily assigned to "President". However, this is a great example to highlight the core issue with this "relaxed" approach. The pairing of "speaks" with "greets", and of "Obama" with "President", which one might expect, would imply that "press" would have to receive all the remaining flows (just like "President" does in the figure), but that probably would have lead to a larger WMD than the one resulting from the assignments as shown in the figure (and described above). But then, given how "speaks" is not moved to "greets" at all, and "President" is not the unique pair for "Obama", you might expect that this "relaxed" way of solving the flow matrix does not work terribly well.
Now, as we already understand, the main problem that WMD needs to solve is that of assigning the weights in the flow matrix for cases where the number of words are different between the two documents. As the authors point out, via the referenced paper by Pele & Werman (2009), finding the best flow matrix (where "speaks" probably would be mostly assigned to "greets" and "President" to "Obama", but with weights lesser than 0.25) has a computational cost of $O(p^3 \log p)$, where $p$ denotes the number of unique words in the documents. Hence, the the paper discusses possible approximations, the best of which, Relaxed WMD (RWMD), as explained above, can bring the optimization cost down to a quadratic problem (in the number of words being compared), i.e., to $O(p^2)$. Those optimization savings result because you only need to trial all reasonable ways of assigning unique pairs while dividing up the remaining flow evenly among the words you did not pair. As it turns out, that relaxed approach comes at hardly any increase in test error - shown in Figure 7 in the paper!
[1] Yes, WMD indeed uses Euclidean distances, not the Cosine similarity (distance), as one might expect; See the WMD paper, section 4, "Word travel cost".


text:
Q: R pivot_wider Error: `times` can't be missing. Location 1 is missing I receive the error

Error: times can't be missing. Location 1 is missing. In addition:
Warning message: In nrow * ncol : NAs produced by integer overflow

when calling:
data_indicator <- data_pivoted %>% select(ID, var) %>%
  mutate(val = TRUE) %>%
  pivot_wider(id_col=ID, names_from = var, values_from = val, values_fill = FALSE)

data_pivoted is 8292624 obs. of 3 variables
summary(data_pivoted)

       ID             var                 val
 Min.   :     1   Length:8292624     Min.   :  -743
 1st Qu.: 98342   Class :character   1st Qu.:     6
 Median :197353   Mode  :character   Median :    10
 Mean   :196777                      Mean   :    58
 3rd Qu.:295272                      3rd Qu.:    18
 Max.   :392696                      Max.   :330318
                                     NA's   :8000821

Any suggestion what is wrong here?
> dput(head(data_pivoted))
structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L), var = c("239",
"200", "229", "100", "101", "102"), val = c(5, NA, NA, NA, NA,
NA)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))

A: I got the same error. The dataset I was using was very large, so I used split and pivot_wider in a map_dffunction.
Using your example
data_pivoted %>%
select(ID, var) %>%
mutate(val = TRUE) %>%
split(.$ID) %>%
map_df(~ pivot_wider(.x,
                   names_from = var,
                   values_from =  val,
                   values_fill = FALSE))


text:
Q: JavaScriptSerializer Deserialize with DateTime or DateTimeOffset VB2012 compiled against .NET4.5: This has been boggling my head for the last couple days. I have json data that I am parsing with the JavaScriptSerializer.Deserialize class. One of the fields is presented as follows:
depart 2017-09-22T00:45:00-07:00

Which is the local time of the departure (this is in Los Angeles).
In my wrapper class I have written
Public Class JsonLeg
    Public depart As DateTime
    Public blah...many more fields
End Class

I ingest the json data and use JavaScriptSerializer.Deserialize to parse it. After this I debug the output and it looks like this
depart                 [Kind=Local] 2017-09-22T02:45:00
depart.ToLocalTime     [Kind=Local] 2017-09-22T02:45:00
depart.ToUniversalTime [Kind=Utc  ] 2017-09-22T07:45:00

That looks all well but the ToLocalTime just converts it to my computer's time zone which is in Dallas. What I need is the local time in LA 2017-09-22T00:45:00 to compare against a list of dates that do not have a Kind. How would I pull out the original location's local time rather than my computer's local time?
I did test using DateTimeOffset as the variable but am afraid I don't understand what the deserializer is doing when it parses the json data.
The debug for that looks like:
depart.DateTime      [Kind=Unspecified] 2017-09-22T00:45:00
depart.LocalDateTime [Kind=Local      ] 2017-09-22T02:45:00
depart.UtcDateTime   [Kind=Utc        ] 2017-09-22T07:45:00

In this case the DateTimeOffset.DateTime gives me what I need. But why? I am trying to understand what the differences are and how each one gets parsed by the deserializer.

A: Your data is in the ISO 8601 extended format, with offset.  This is also covered by RFC3339.
When you deserialize a string in this format into a DateTime using the JavaScriptSerializer, it is making a rather grand assumption that it was generated from another DateTime with Kind=Local.  Since the offsets may or may not match between your machine and the one that generated the data, it first applies the supplied offset to get to UTC, then it converts back to your local time zone.  This is probably not the behavior you want, and there isn't a very good way to get JavaScriptSerializer to behave differently.  Parsing into a DateTimeOffset makes much more sense.  The resulting date, time, and offset portions then match exactly what were supplied.
Once you have a DateTimeOffset, calling .DateTime that gives you back just the date and time portion, with the resulting kind to Unspecified.  This is the standard behavior for all DateTimeOffset instances, not just those that come through parsing.  The reason is that the offset could be anything, and mapping it to either Local or Utc would be in error.
Likewise, the .LocalDateTime converts to local time taking the offset into account (similarly to as if you parsed directly to a DateTime).  The .UtcDateTime takes the offset into account and converts to UTC, similarly to if you called .ToUniversalTime() on the DateTime version.
Also, you should consider using Json.NET instead of JavaScriptSerializer.  The majority of the .NET community, including Microsoft, now uses this library for JSON serialization. It is much more flexible, and tends to do the right thing out-of-the-box when it comes to dates and times.


text:
Q: Properly exit a wpf plugin for Revit I'm working on a plugin for Revit. Revit permits only dll type addins and I chose c# and wpf for gui. I couldn't initialize wpf natively so I needed to contain it in a system.windows.window as content.
Now if I close that window with upper right X program continues (looping processing etc.) it doesn't get terminated. Window.close() again just closes the window not the application it self.
How should I exit my app and not keep it lurking in the shadows?
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
public class FDNMain : IExternalCommand
{
    public Result Execute(ExternalCommandData CommandData, ref string message, ElementSet elements)
    {
        FDNControl wpfControl = new FDNControl();
        return Result.Succeeded;
    }
}

Above is the Revit external command class which cannot initialize (show up) the wpfControl. So I need to wrap the wpfcontrol with a System.Windows.Window as below:
Window hostWindow = new Window();
hostWindow.Content = wpfControl;
hostWindow.Show();

A: OK, I see. There is no XAML Window template in Visual Studio for a class library, but you can create an UserControl as you did and then change the UserControl tag in your XAML to a Window one.
You also need to change it in the .xaml.cs (you can also remove it, because it is a partial class and the parent class is implicit with the XAML). After that, you will be able to call ShowDialog on your window.

A: I defined global static variable which is set to true while host window is closing. And set this condition to be check in the while statement in order the loop to be continued. such as:
...
    Global.hostWindow.Closing += hostWindow_Closing;
...

    private void hostWindow_Closing(object sender, EventArgs e)
    {
        Global.Closing = true;
    }
...

    while (Nodes.Count > 0 && Global.Closing == false)
    {
    ...
    }


text:
Q: JavaScript Polymer change variable value depending on global variable I don't know how to explain myself or if it is even possible, so here it goes an example:
I want the "hidden" variable to take the value of the global variable depending on the "tag" value.
var sport = false;
var music = true;

Polymer({
    publish: {
        tag: "sport",
        hidden: xxxxxx
    }
});

So if tag is "sport", I want "hidden" to be "false"; and if tag is "music", I want "hidden" to be "true".
EDIT:
The thing is that there are several variables (categories, such as music, sport, culture, job...) that will be true or false depending on whether the user enables them with toggle buttons or not. Then, there is information about several events, each of which is of a different category (e.g.: "Football match tomorrow" is a "sport" event, etc.). So, I want these events entries to disappear if the user disables its corresponding toggle button.
So, imagine there are 2 events of sport, 1 of music and 1 of job. When the toggle button for sport is disabled, I only want to see the 2 events of job and music, the sports ones should disappear.
To do so, I had thought of these variables with true or false, as I thought it would be easy to assign their value to the hidden attribute by default in Polymer. But it turns out it was not that easy. If you come with any other easy way to implement this, let me know!
Thanks!

A: Not sure if I understood your question, but there are some ways to hide an element based on the value of a variable. If you are just starting with your Polymer project, check out version 0.9 (there has been a lot of changes).
Direct:

Hey I'm the sport category

With code:

Hey I'm the sport category

Polymer({
  publish: {
    tag: "sport",
    hidden: xxxxxx
  },
  // The ready function gets called when the Polymer element is ready.
  ready:{
    if (this.tag == "xyz"){
      this.hidden = false;
      // Do other things..
    }
  }
});

In Polymer version >= 0.8 you can use computed properties:

Hey I'm the sport category

Polymer({
  is: 'my-element',
  properties: {
      tag: String,
  },
  computeHidden: function() {
    if (this.tag == "xyz"){
      return false;
    }else{
      return true;
   }
 }
});

OR as a property declaration:

Hey I'm the sport category

Polymer({
    // define element prototype here
    is:'my-element',

    properties:{
        hidden:{
            type:Boolean,
            value:function() {
              if (this.tag == "xyz"){
                  return false;
              }else{
                  return true;
              }
            }
        }
    }
  });


text:
Q: Retrieve the compressed (binary format) of the big column As remembered here, when  storing documents (suppose text or xml datatypes and EXTENDED storage) with more than 2k, it is compressed.
About table columns that was compressed, how to retrieve the compressed (binary format) of the column?

NOTE - Typical applications:

*

*Operations as "long-term checksum of the document", like SHA256(compressed).PS: as it is a matter of convention, not needs complementar compression, inheriting the condition, SHA256(less2k? text: compressed).

*Coping or downloading compressed documents directally (without CPU consume). PS: complementing operation (for "less than 2k row") with on-the-fly compression, when uniformity is required.

A: If this is possible at all, it would require writing a function in C.
Instead of going that way, I would recommend that you use EXTERNAL rather than EXTENDED storage and compress the data yourself before you store them in the database. That way you don't waste any space, and you can decide when to retrieve the compressed data and when to uncompress them.


text:
Q: Circle mask acts like rectangle I'm trying to draw an object masked with a circle, but the mask applied is more like a circle's bounding rectangle
I tried using circle drawn with drawCircle method:
private function squareToRound(ability:MovieClip):MovieClip
{
    var container:MovieClip = new MovieClip();
    var newAbility:MovieClip = ability;
    var newMask:MovieClip = new MovieClip();

    newAbility.width = 43;
    newAbility.height = 43;
    newMask.x = newAbility.x + newAbility.width / 2;
    newMask.y = newAbility.y + newAbility.height / 2;

    container.addChild(newAbility);
    newMask.graphics.beginFill();
    newMask.graphics.drawCircle(0, 0, 8);
    newMask.graphics.endFill();
    container.addChild(newMask);

    newAbility.mask = newMask;
    return container;
}

... and as an asset from SWF:
private function squareToRound(ability:MovieClip):MovieClip
{
    var container:MovieClip = new MovieClip();
    var newAbility:MovieClip = ability;
    var newMask:MovieClip = new CircleAbilityMask();

    newAbility.width = 43;
    newAbility.height = 43;
    newMask.x = newAbility.x + newAbility.width / 2;
    newMask.y = newAbility.y + newAbility.height / 2;

    container.addChild(newAbility);
    container.addChild(newMask);

    newAbility.mask = newMask;
    return container;
}

The results are equal.
I checked what the mask looks like by commenting "newAbility.mask = newMask;" line

A: This should be resolved in the current OpenFL release:
https://github.com/openfl/openfl/blob/develop/CHANGELOG.md#650-11102017
You can also use Cairo (on native platforms) or Canvas (on HTML5) for smoother/better masking support:
openfl test html5 -Dcanvas
openfl test windows -Dcairo

These are also used when you bitmapData.draw, sprite.cacheAsBitmap = true or other APIs that trigger a software render rather than GL.


text: Q: Why do Macs not save your unsaved work from a 3rd party app during a shutdown? In Windows, if any app is prompting you to save your work, a shutdown is prevented to save work. However, on macOS, if a 3rd party app (like MS word) prompts you to save your work, macOS just kills the app, thus losing any unsaved work after a shutdown. Why?


text:
Q: If i put UIView B on UIView A and hide/show them by using Segmented Control is it Professional way? I am trying to handle UIViews hide/show by using (isHidden) UISegmented Control is it professional way how can i handle this.
@IBOutlet weak var flightTypeSegCont: UISegmentedControl!
@IBAction func flightType(_ sender: UISegmentedControl) {

    if(flightTypeSegCont.selectedSegmentIndex == 0)
    {
        self.direcrCard.isHidden = false
        self.ViaCardView.isHidden = true
    }
    else
    {
        self.direcrCard.isHidden = true
        self.ViaCardView.isHidden = false
    }
}

A: You can do it like that:
@IBOutlet weak var flightTypeSegCont: UISegmentedControl!
@IBAction func flightType(_ sender: UISegmentedControl) {
    let shouldHide = flightTypeSegCont.selectedSegmentIndex == 0
    self.direcrCard.isHidden = !shouldHide
    self.ViaCardView.isHidden = shouldHide
}


text:
Q: Float Overflow Error en while loop El objetivo de mi codigo es calcular F(xi) hasta que su valor sea >= a 0.9995, mientras sea menor, se seguira generando la iteracion del while y del for.
from decimal import Decimal
import math
import pandas as pd

lambda_ = int(input("Ingresa el valor de lambda_: "))
e = 2.718281828459
search = {"f(xi)": [], "F(xi)": []}

count = 0
up = 0.9995
F_xi = 0
while up >= F_xi:
    if count == 0:
        operation = ((pow(e, -(lambda_)) * pow(lambda_, count)) /
                     math.factorial(count))
        search["f(xi)"].append(round(operation, 7))
        search["F(xi)"].append(round(operation, 7))
    else:
        operation = ((pow(e, -(lambda_)) * pow(lambda_, count)) /
                     math.factorial(count))
        search["f(xi)"].append(round(operation, 7))
        new_F = search["f(xi)"][count] + search["F(xi)"][-1]
        search["F(xi)"].append(round(new_F, 7))
        F_xi = search["F(xi)"][-1]
    count += 1

result = pd.DataFrame(search)
print(result)

Me da el error: OverflowError: int too large to convert to float
El error esta en:
operation = ((pow(e, -lambda) * pow(lambda, + (count))) /
                     math.factorial(count))

Si el valor de lambda fuese 5, el resultado de la tabla deberia de ser el siguiente:
       f(xi)       F(xi)
0     0.00673     0.00673
1     0.03368     0.04041
2     0.08422     0.12463
3     0.14037     0.26500
4     0.17546     0.44046
.
.
.
.                >= 0.9995

A: Ojo que los factoriales crecen muy rapido, el último valor que puede soportar un factorial casteado a float es:
float(math.factorial(170))

Si haces:
float(math.factorial(171))

Te tirará el error en cuestión.
Como estas usando el factorial de divisor se castea implicitamente a float, lanzando el error.
Por lo que veo dos soluciones distintas, o intentas reducir el valor de count o puedes utilizar el tipo Decimal para manejar numeros de esta magnitud a costa de rendimiento y rapidez.
from decimal import Decimal
import math
import pandas as pd

lambda_ = int(input("Ingresa el valor de lambda_: "))
e = 2.718281828459
search = {"f(xi)": [], "F(xi)": []}

count = 0
up = 0.9995
F_xi = 0
while up >= F_xi:
    if count == 0:
        operation = Decimal(((pow(e, -lambda_) * pow(lambda_, -(count)))) /
                     math.factorial(count))
        search["f(xi)"].append(operation)
        search["F(xi)"].append(operation)
    else:

        for i in range(0,count):
            operation = Decimal(((pow(e, -lambda_) * pow(lambda_, -(count)))) /
                     math.factorial(count))
            search["f(xi)"].append(operation)
            new_F = search["f(xi)"][i] + search["F(xi)"][i-1]
            search["F(xi)"].append(new_F)
            F_xi = search["F(xi)"][-1]
    count += 1

result = pd.DataFrame(search)
print(result)

Solución inspirada en esta.


text:
Q: What could cause this bizarre Lion behavior? This is a Core i7 MacBook Pro that was upgraded to Lion from Snow Leopard, retaining the legacy FileVault encryption on the home directory.
I've been getting these strange lockups, three or four times now over the course of two weeks, where some part of the system suddenly breaks, producing the following behavior:

*

*Can still make new SSH connections into the machine

*The display is completely frozen, except that the trackpad still moves the cursor around

*Nothing happens when I close the lid

*Music from a Flash app in Safari continues to play

It doesn't appear to be triggered by any specific action from me.
This has never happened to me on my Core i7 MacBook Air at home, which was preloaded with Lion. The only major difference I can think of is the FileVault difference. Could that cause this? What else I should investigate? I can't imagine that a hardware issue would cause such a specific combination of symptoms.


text:
Q: How to control for multiple comparisons when using zero-inflated poisson models? I'm modeling the relationship between demographic variables and resource use (resource use ~ demo1+ demo2 + ...). I am doing this for 56 different resources -- so I have 56 models.
A zero-inflated poisson (ZIP) fits my data the best, however I will need to run 56 of these models and I'd like a way to control for type 1 errors in running so many tests. In doing similar modeling for regular LMs, I usually use a Holm correction, however ZIP models don't provide overall p-values, so I have nothing to put into a p.adjust command. So, I'm a bit stuck.
Thoughts?


text:
Q: Maximal sum of unique vertices' weights in a grap I'm given a directed graph with weights assigned to vertices, not edges. My goal is to find the maximal weight of a path in this graph. A path's weight is a sum of weights of all unique vertices it contains. A vertex may be visited multiple times on a path, though it counts only once.
Cycles may and probably will be present.
Weights are positive integers.
Reconstructing the path isn't necessary.
Because of the size of the graph, it cannot be represented as adjacency matrix (this may have an impact on the time complexity).
The graph doesn't have to be neither strongly nor weakly connected.
Example:

1 -> 20 -> 5
A    |
|   \/
14 <- 33

The best path will be
1 -> 20 -> 33 -> 14 -> 1 -> 20 -> 5
with sum 73.

A: Step one: eliminate all cycles. You can find a cycle by picking any node and doing a DFS from there. If you don't find a cycle find another node that you haven't visisted in the previous DFS and do a DFS from that node. If you find a cycle collapse all the nodes into a single one. Basically if you reach any of the nodes in the cycle, you will go through the cycle to get all the weights. Since you can reuse nodes and edges you will always be able to continue on your path as before. After you found a cycle repeat the algorithm, until you have collapsed all cycles.
Step two: find a path through the collapsed graph. Now there are no cycles, so you can use Bellman Ford and find the longest route (you need to change the conditions to look for longer paths instead of shorter). Because every collapsed node has the weigth of the cycle it represents you get the weight you are looking for. If you want to reconstruct the path then you also need to look at the cycles you collapsed and expand them in place, taking care to add the path from the input point to the exit point in the cycle (Say you have a cycle with 10 nodes, the input edge goes to node 1 but the exit edge goes from node 5, so you need to add the entire cycle 1,2,3,4,5.. 10 starting from the input edge and then add the part of the cycle that takes you to the exit edge, in this case 1,2,3,4,5).
Complexity is O(N^2). A DFS is O(N) (including picking other nodes in case you don't find from the current one) and every time you eliminate at least one node (you can't have a cycle with a single node) so you will run it at most N times. BellmanFord algorithm is also O(N^2). Reconstruction should be at most O(N).


text:
Q: Overleaf: Is it possible to copy and paste one or multiple files(folders, tex, images....) in overleaf project? I am trying to copy many tex. files from one folder to another (tex. files will have same name but a little different content which I would change after copy/paste) at a same project but nothing happens. When I hold "alt" on keyboard to move and copy that file to another folder, it does not working.
Have somebody experience with this?
Thanks guys!


text:
Q: Developing an OpenSocial Gadget within Visual Studio We are about to implement a bunch of OpenSocial gadgets. They are not going to be run on Facebook or any other social network but rather on our own internal Apache Shindig server. (We embed these gadgets using iframes in a normal ASP.NET MVC cshtml view)
According to http://docs.opensocial.org/display/OSREF/OpenSocial+Tutorial, the structure of a gadget is like so:
<?xml version="1.0" encoding="UTF-8" ?>
 <Module>
   <ModulePrefs title="Hello World!">
     <Require feature="opensocial-0.8" />
   </ModulePrefs>
   <Content type="html">
     <![CDATA[
       Hello, world!
     ]]>
   </Content>
 </Module>

Whereas the HTML, CSS and JS are embedded within the  in the  tag. If we want to develop a file like this in XML format in Visual Studio, it renders Syntax Highlighting, IntelliSense, IntelliTrace and JavaScript debugging impossible. That's not very comfortable.
Question 1: Do you know of any usable(!) extension for Visual Studio that re-enables all these features for these OpenSocial XML gadgets?
Question 2: Or if not, have any of you ever tried the same and found a good way to work around these hurdles?

Update: We have done a proof-of-concept of using a post build step that takes a plain HTML file, a plain JS file, and an XML skeleton and merges them into a gadget. In debug mode we might conceivably include the plain files directly while in the deployment process we call Shindig with the merged XML file from the post build step:
if (@Html.IsDebugMode())
{
    <iframe src="/Gadgets/HelloWorld.html"/>
}
else
{
    <iframe src="http://example.org/shindig?url=http://example.org/Gadgets/Merged/HelloWorld.xml"/>
}

This is how the solution works:

*

*Add a Gadgets\HelloWorld.js file

*Add a Gadgets\HelloWorld.html file that includes the js file.

*Add a Gadgets\HelloWorld.xml file with the gadget XML but with an empty <Content> tag.

*Create a CSHTML page with an iframe that includes the plain HTML file in Debug mode but includes the Gadget in Release mode.

*Define a Post Build Event that reads the contents of HelloWorld.html and pastes it into the Content tag of the XML. In addition it reads the JS code from the JS file and replaces the script inclusion <script src="HelloWorld.js" /> in the HTML by an inline JavaScript <script>...</script> with the respective code.

Advantages:

*

*Clean separation of logic (JS file), presentation (HTML file) and metadata (XML file).

*Complete Visual Studio HTML authoring support when working on the HTML.

*Complete Javascript authoring support when working on the JS.

*Tools such as JSLint can be used to check the JavaScript style.

Caveats:

*

*In Debug mode, if we call Shindig to render the gadget, we don't have a way to open the JavaScript in Visual Studio and setting a breakpoint. However, if any error occurs in the JS code, Visual Studio will open a view on the JS code and mark the erroneous line. Once that view is open, we can use it for setting break points, too. Live editing is not possible though because the original JS file only gets merged into the XML in the course of the build process.

*On the other hand, if we include the plain HTML file as an iframe instead of having Shindig render it, we gain the possibility of live-editing and debugging directly in the respective files. But of course all of the Shindig features are not effective. In particular, all the scripts automatically added by Shindig are missing or have to be included by hand.

Ideally every change in the HTML or JS file while running the application in debug mode would immediately update the merged Gadget XML file, thus allowing life editing even when using Shindig.

A: A2: You can develop your javascript in a separated js file and just include it in the gadget xml as you would with html file contain a js include. Further more, you can use frames inside your gadget html, but that will may prevent you from using some of the js API available from Shindig.


text:
Q: Authenticating Username and Password in nodejs with mongodb I am creating a login page and need to authenticate user's username and password whenever he logs in. My Database is mongodb and i am using expressjs in nodejs. Signup functionality is working well and i am able to sign up users but Log In functionality is not working. Kindly help me with knowledge of MongoDB to authenticate users and store their cookies.
Here's my server code..
//------------modules used-------------//
const express = require("express");
const path = require("path");
const helmet = require("helmet");
const cookieparser = require("cookie-parser");
const mongoose = require("mongoose");
//------------modules used-------------//

const app = express();
app.use(helmet());
// allow the app to use cookieparser
app.use(cookieparser());
// allow the express server to process POST request rendered by the ejs files
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//-------------------mongodb-----------------//
mongoose.connect("mongodb://localhost:27017/loginDB", { useNewUrlParser: true });
const userSchema = new mongoose.Schema({
    email: String,
    pass: String,
})
const User = new mongoose.model("User", userSchema);
//-------------------mongodb-----------------//

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

app.get("/", (req, res) => {
    // check if user is logged in, by checking cookie
    let username = req.cookies.username;
    if(username){
        return res.render("mainpage", {
            username,
        });
    }else{
        res.redirect("/login");
    }

});
app.get("/mainpage", (req, res) => {
    // check if user is logged in, by checking cookie
    let username = req.cookies.username;
    if(username){
        return res.render("mainpage", {
            username,
        });
    }else{
        res.redirect("/login");
    }

});
app.get("/register", (req, res) => {

    return res.render("signup");

});

app.get("/login", (req, res) => {
    // check if there is a msg query
    let bad_auth = req.query.msg ? true : false;

    // if there exists, send the error.
    if (bad_auth) {
        return res.render("login", {
            error: "Invalid username or password",
        });
    } else {
        // else just render the login
        return res.render("login");
    }
});

app.post("/login", (req, res) => {
    // get the data
    let { username, password } = req.body;

    User.find({email: username},(err)=>{
        if(err){
            res.redirect("/");
        }else{
            res.cookie("username", username, {
                maxAge: 30 * 24 * 60 * 60 * 1000,
                secure: true,
                httpOnly: true,
                sameSite: 'lax'
            });
            res.redirect("/mainpage");
        }
    })

    // fake test data
    // let userdetails = {
    //     username: "Bob",
    //     password: "123456",
    // };

    // // basic check
    // if (
    //     username === userdetails["username"] &&
    //     password === userdetails["password"]
    // ) {
    //     // saving the data to the cookies
    //     res.cookie("username", username, {
    //         maxAge: 30 * 24 * 60 * 60 * 1000,
    //         secure: true,
    //         httpOnly: true,
    //         sameSite: 'lax'
    //     });
    //     // redirect

    //     return res.redirect("/");

    // } else {
    //     // redirect with a fail msg
    //     return res.redirect("/login?msg=fail");
    // }
});

app.post("/register",(req,res)=>{
    let { given_username, given_password } = req.body;

    const newUser = new User({
        email: given_username,
        pass: given_password,
    });

    newUser.save((err)=>{
        if(err){
            console.log(err);
        }else{
            console.log('saved');
        }
    })

    res.cookie("username", given_username, {
        maxAge: 30 * 24 * 60 * 60 * 1000,
        secure: true,
        httpOnly: true,
        sameSite: 'lax'
    });

    res.redirect("/")
})

app.get("/logout", (req, res) => {
    // clear the cookie
    res.clearCookie("username");
    // redirect to login
    return res.redirect("/login");
});

app.listen('3000', () => console.log(`server started`));

A: Use this code for login API

const bcrypt = require("bcryptjs")

app.post("/login", async (req, res) => {
  let { username, password } = req.body;
  const user = await User.findOne({ email: username }).lean()
  if (!user) {
    res.status(404).send({message: "No  User Found"})
  } else {

    var validatePassword = await bcrypt.compare(password, user.password)

    if (!validatePassword) {
      res.status(400).send({message: "Invalid Password"})
    } else {
      res.cookie("username", username, {
        maxAge: 30 * 24 * 60 * 60 * 1000,
        secure: true,
        httpOnly: true,
        sameSite: 'lax'
    });
      res.redirect("/mainpage");

    }
  }


text:
Q: Average and expected value in a biased coin toss Not sure on which SE site to ask this. It is essentially a math question however I am looking for a practical code solution.
I have a loop with an integer i which changes (according to a predefined set of rules) every time tails comes up in a biased coin toss. For the sake of simplicity, let's assume this number increments on every tails. The loop runs n times, or until heads comes up. If heads does not come up in n tosses, i = -n.
I am trying to find both the average value of i (not counting the case where i = -n), and the expected value.
Consider the following example C# code:
const int n = 10;      //loops n times
const double p = .25;  //probability of heads
int i = 1;             //variable number

Random rnd = new Random();

for (int j = 0; j < n; j++)
{
    if (rnd.NextDouble() < p) break;
    i++;
}
if (i > n) i = -n;

To get the average value I figured I'd have to calculate a weighted average, with weight w=p^(j+1), and simply run the loop n times.
const int n = 10;      //loops n times
const double p = .25;  //probability of heads
int i = 1;             //variable number
double i_avg = 0.0;    //average
double total_w = 0.0;  //weight

for (int j = 0; j < n; j++)
{
    double w = Math.Pow(p, j + 1.0);
    total_w += w;
    i_avg += i * w;
    i++;
}
i_avg /= total_w;

But this seems incorrect. On p = 0.25 and n = 10, the result is ~2.33. But in a simulation, I get an average value of ~3.40, and expected value of ~2.65.
What is the correct way to calculate these values? If possible, please include example code in a procedural programming language, as I find this easier to understand.

A: I think I figured it out.
The probability of heads coming up on the first toss is p.
On the second toss, we've already hit tails, which has a probability of 1-p, so the prob. of heads would be (1-p)*p. On the third it would be (1-p)*(1-p)*p = (1-p)^2*p, etc. So for every toss, the probability of heads coming up is
w = (1-p)^j*p

To get the expected value, add -n to the sum with probability (1-p)^n.
ev = (i_avg + (1-p)^n * (-n)) / (total_w + (1-p)^n)

And since total_w + (1-p)^n = 1,
ev =  i_avg + (1-total_w) * (-n)

So the final program would be:
const int n = 10;      //loops n times
const double p = .25;  //probability of heads
int i = 1;             //variable number
double i_avg = 0.0;    //average
double ev = 0.0;       //expected value
double total_w = 0.0;  //weight

for (int j = 0; j < n; j++)
{
    double w = Math.Pow(1.0 - p, j) * p;
    total_w += w;
    i_avg += i * w;
    i++;
}
ev = i_avg + (1.0 - total_w) * (-n);
i_avg /= total_w;

I'd love to turn this into fancy Latex expressions but I have no idea how to do that.


text:
Q: wpf how to fix listbox xaml items order, from left to right, from top to bottom i create a system of get images from folder in my project and put it in the listbox like ItemsSource, and i want arrange it like this :

1 2 3
4 5 6
7 8 9

if i resize window like big window, This is what will happen :
1 2 3 4
5 6 7 8
9 .. ..

but i have a problem arranging the list. and how to get text selectedItem from ItemsSource how?.
here the code :
<Window.Resources>

        <DataTemplate x:Key="TileTemplate">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="55"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Image Grid.Row="0" Source="Images/folder.png" Margin="10" Height="40" Width="35"/>
                <TextBlock Grid.Row="1" Margin="3,0,0,5" TextAlignment="Center" Text="{Binding Names}" Width="70"/>
            </Grid>
        </DataTemplate>

        <ItemsPanelTemplate x:Key="TilePanel">
            <WrapPanel/>
        </ItemsPanelTemplate>

        <Style TargetType="local:LayoutListBox">
            <Style.Triggers>
                <Trigger Property="ViewLayout" Value="Tile">
                    <Setter Property="ItemsPanel" Value="{StaticResource TilePanel}"/>
                    <Setter Property="ItemTemplate" Value="{StaticResource TileTemplate}"/>
                </Trigger>
            </Style.Triggers>

        </Style>

    </Window.Resources>

A: You can do something like this:
    <ListBox ItemsSource="{Binding YourList}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="3"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>

Then even when you enlarge the window you will be left with 3 items in each column


text:
Q: Extract href value which endsWith pdf I want to get direct links of pdf from webpage, I tried this regex pattern but did not work with me:
href=.*\.pdf$

data to test:
eng1

eng2

A: The main problem is the end of string $ anchor, the href values are not at this position. I can only recommend using a parser of sort to extract these values and if you want to use regex, I propose something like the following.
href=(["'])([^"']+\.pdf)\1

The values that you want as the match result can be accessed by capturing group #2

A: You can use this regex.
href=".*?([\w-]+\.pdf)"

Working demo

The idea of this regex is to look for all href witch contains X.pdf at the end.

A: Try this.
use group 1 and get the exact value.
href="([^"]+\.pdf)"

DEMO:http://regex101.com/r/nR8gY4/1


text:
Q: How to catch keyboard input without visible input field in JavaScript Situation:

*

*HTML5 with jQuery Mobile on iPad (EDIT: HTML5 page in a PhoneGap app)

*external keyboard attached

*text input field is hidden, no visible input field

*no focus on text input field -> no soft keyboard shown

Goal:

*

*catch keyboard input without showing & focusing on a text input field

*Keyboard input is are variable phrases (e.g. name1, object2, phrase3)

*Just start typing and the page should capture that typing

--> How can I detect the keyboard input into the hidden input field?
I know the keydown / keypress / keyup events, however they seem to require a visible input field

A: You can bind the event to the document like this:-
$(document).bind('keyup', function(e) {
    alert('testing');
});

A: You can also simply position the element off-canvas, without needing to alter its DOM/CSS visibility state.
<style> .inputValue{position:absolute;left:-99999px} </style>
<input type="text" class="inputValue" autofocus="autofocus"/>

And then at any given point when you require the input's value you call the below script.
<script> $('.inputValue').val(); </script>


text:
Q: Using Method changing a Variable, then unable to assign value to another variable I have a method to change a variable (declared =0) into an integer (eg: 10), then I would like to assign this integer to another variable (int playerOneIcon)
SomeActivity:
public class SomeActivity extends AppCompatActivity implements View.OnClickListener {

Integer playerOneIcon= 0, playerIcon = 0;

onCreate(Bundle savedInstanceState) {

Button btn_test = findViewById(R.id.btn_test);
    btn_test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(ii_PlayerSetting.this, String.valueOf(playerOneIcon), Toast.LENGTH_SHORT).show();
        }
    });

}

ShowPop1(View v) {  }
//Will paste it below

ShowPop2(View v) {  }
//Will paste it below

public void onClick(View v){     }
//Will paste it below

}

The "ShowPop1(View v) will run when user clicked on a button, it will call a pop up dialog, hence calling the onClick() within:
ShowPop1(View v)
ShowPop1(View v) {
playerIcon = playerOneIcon;

ChangeHeadDialog.setContentView(R.layout.somelayout);

onClick(v);

playerOneIcon = playerIcon;
}

ShowPop2(View v)
ShowPop2(View v) {
playerIcon = playerTwoIcon;

ChangeHeadDialog.setContentView(R.layout.somelayout);

onClick(v);

playerTwoIcon = playerIcon;
}

onClick(v)
onClick(v){
playerIcon = 10;
ChangeHeadDialog.dismiss();
//if i put "playerOneIcon = playerIcon;" here, it will work, but I can't since it may be playerTwoIcon that should assign instead

}

Then when I pressed the btn_test, result is 0,. Please help, thanks you so much!

A: I have solved it by adding one more variable in showpop1() & showPop2(), then running a method inside onClick().

ShowPop1(View v)

ShowPop1(View v) {
playerIcon = playerOneIcon;

//New Line
String playerSelected = "player1"
//New Line

ChangeHeadDialog.setContentView(R.layout.somelayout);

onClick(v);

}

ShowPop2(View v)

ShowPop2(View v) {
playerIcon = playerTwoIcon;

//New Line
String playerSelected = "player2"
//New Line

ChangeHeadDialog.setContentView(R.layout.somelayout);

onClick(v);

}

applyPlayerIconToPlayer(Integer playerIcon)

private void applyPlayerIconToPlayer(Integer playerIcon) {
    switch (playerSelected){
        case "player1":
            playerOneIcon = playerIcon;
            break;
        case "player2":
            playerTwoIcon = playerIcon;
            break;
}}

Run applyPlayerIconToPlayer(Integer playerIcon) inside onClick():
onClick(v){
playerIcon = 10;
ChangeHeadDialog.dismiss();
applyPlayerIconToPlayer(Integer playerIcon)
}

Done!


text:
Q: Ifinstring: locate variable number after text then randomly Send new number +/- 20 of that # I have a very simple AHK script that reads a log.txt every so often and then randomly generates numbers within a range when the triggering text is found then Sends the random number as my guess.  It's for a stupid lottery type thing.
The thing is, if the previous winning number was, for instance, 40, then it's seemingly never within 20 numbers of 40 again the next time around, so I'm trying to figure out how to locate the number 40 immediately after my Ifinstring trigger, then randomly generate (and then Send,) a single number between 0 and 20 as well as 60 to 100.  I'm sure there's plenty of efficient ways to do this but I'm new and would like a simple way.  It's just a macro really, and I'm just a newbie trying to optimize my one script.
Thanks for the patience and help :)


text:
Q: Sounds in Turbo pascal. How do they work? I've been trying for some time to learn how does sound work and how can i implement it to pascal. No succes. I started using 8 bit sound (i believe that they're 8 bit) and tried to copy some songs (like Mario song). I have some questions.
1. How can i use programs to play a song (a real song)
2. Is there any site that gives 8 bit songs but in code (frequency and duration)
 And one unrelated question.... is there any way to copy a code from a browser to free pascal....? I really new to free pascal.

A: TP hasn't been updated in 20 years, I'd suggest using Freepascal which is far better and constantly updated.
That aside though, in TP you won't be able to natively play a song (mp3, ogg) unless you write the code to do it yourself. You may find some old DOS mp3 playing programs out there that have source code, but good luck on that.
If you intend to play simple tones then sound() and delay() is all you need, but I guess you've already done this? Simply a case of reading a list of tones and durations. If you want to do other stuff in your code while this is happening you'll need to keep a check of time elapsed since the tone started and once it reaches the tone length or greater then switch to the next tone.
pseudo-code below:
var tlength : integer;
    starttime : integer;

procedure readtone;
var tone: byte;
begin
  if (starttime+nowtime >= tlength) then
  begin
    tone:=read from file
    tlength:=read from file
    starttime:=now
    sound(tone)
  end;
end;

begin
  repeat
    readtone;
    do something else
  until done
end.

In Freepascal you can take the easy route: http://wiki.freepascal.org/Multimedia_Programming


text:
Q: Recover from failed etcd2 / CoreOS cluster I've got a cluster of 3 CoreOS machines running on Azure. I rebooted two at the same time and the cluster failed as expected.
I need to replace the discovery token, cloud-config is read on every bootup, but according to the CoreOS docs:

Once an instance is provisioned on Azure, the cloud-config cannot be
  modified.

Is there a method to recover from this, short of destroying and then deploying a new cluster ?

A: there configuration file exists in location
/var/lib/waagent/CustomData

Using
sudo vim /var/lib/waagent/CustomData

You should be able to edit it. After the reboot configuration will pick up.

A: You could try modifying the etcd service definition in /run/systemd/system/etcd.service.d/20-cloudinit.conf - you should see something like
[Service]
Environment="ETCD_ADDR=10.1.1.1:4001"
Environment="ETCD_DISCOVERY=https://discovery.etcd.io/47fabddb4eed191a09bf5b70ba93426a"
Environment="ETCD_PEER_ADDR=10.1.1.1:7001"

Modify the discovery URL to your new one, then restart it
systemctl daemon-reload
systemctl restart etcd

You will need to test if this survives a reboot on Azure though!

A: If you remove two nodes in three node cluster, you loose the quorum, with 3 nodes you can only with lose one node, for more information about the fault tolerance for the CoreOS:
Fault Tolerance Table

It is recommended to have an odd number of members in a cluster. Having an odd cluster size doesn't change the number needed for majority, but you gain a higher tolerance for failure by adding the extra member. You can see this in practice when comparing even and odd sized clusters:
Cluster Size    Majority    Failure Tolerance
1   1   0
3   2   1
4   3   1
5   3   2
6   4   2
7   4   3
8   5   3
9   5   4

https://coreos.com/etcd/docs/latest/admin_guide.html


text:
Q: Did the original Drax have trouble with metaphors? As described in this answer, the Drax we see in the Guardians of the Galaxy movie is quite different than the original Earth-616 version from the comics.
That original version was a human spirit attached to a magically-created one-of-a-kind body. The new Drax is an alien who has no concept of metaphor, and interprets all statements literally. This is particularly pronounced when he hears an idiom. Here's the most famous example from the movie:

Rocket Raccoon: [about Drax] His people are completely literal. Metaphors go over his head.
Drax the Destroyer: Nothing goes over my head...! My reflexes are too fast, I would catch it.

And here's an example from the game Avengers Alliance 2, with characters based on the movie:

Hawkeye : Drax! Did Star-Lord send you? It'd be swell if you could lend us a hand right about now.
Drax : I will not loan you either of my hands! I like the way they are attached to me with muscle and bone. Why do you not use your own hands?
Hawkeye : Oh, right. Good idea. So... completely unrelated question: would you like to use your hands to fight alongside us for the purpose of beating up a large alien cat?
Drax : I would enjoy this very much.

Other aspects of the character seem similar: both characters have a vendetta against a major villain (Thanos, Ronan), both characters had their families attacked, both characters use knives and have red body markings (later version of comics Drax).
Where did this problem with metaphors and idioms come from? Did the original Drax ever display this behavior?

A: No
Here we see Drax having no trouble with metaphors whatsoever:

Drax says that he has relived his memories "as many times as there are stars in the cosmos." This seems like an obvious metaphor (well, a simile really, but who's keeping track): "as numerous as the stars in the sky," "as many as the sands of the sea."
He certainly cannot be speaking literally, since conservative estimates of how many stars there are in the cosmos are around 100 octillion. If we assume that Drax has lived for the entire lifetime of the universe (which he certainly has not, being in his original storyline an altered human from Earth), and that he was thwarted by Thanos at the beginning of the universe (which he also was not), he would have to relive the memories of being thwarted by Thanos over 221 billion times a second in order to have relived the memories of his defeat "as many times as there are stars in the cosmos." Of course, it is possible that Drax severely underestimates the number of stars in the cosmos, but given that he is a spacefaring super-being, I doubt it.
This seems like a clear example of Drax understanding (and employing) a metaphor, and in an early form no less.

A: Having read a lot of comics with Drax in them over the course of my life, there's no one occurrence that I can recall where Drax had issues with metaphors. In fact, on his very first panel in Iron Man #55, he already uses metaphors:

So this sets the stage for Drax. Even 43 years later, he seems to have no issue interpreting and reacting to people's emotions and abstract concepts. This is from Drax #1:

So the behaviour of Drax not understanding emotions and concepts is apparently exclusive to the MCU.