Q:

How to create texture coordinates for a spritesheet with lwjgl

Using lwjgl and slick-util I've been trying to use certain pieces of a spritesheet as textures. lwjgl uses glTexCoord2f(); to map coordinates to individual vertices, and the coordinates it takes in are normalized (between 1 and 0), so I've been using this code to make the coordinates only use a small piece of the full Texture:
glTexCoord2f(0 / 128, 0 / 128); glVertex2f(0, 0);
glTexCoord2f(0 / 128, 8 / 128); glVertex2f(0, 32);
glTexCoord2f(8 / 128, 8 / 128); glVertex2f(32, 32);
glTexCoord2f(8 / 128, 0 / 128); glVertex2f(32, 0);

but whenever I used normalized coordinates that are a fraction of the images size I just get a solid square that had 50% alpha.
My question is: what am I doing that's making the texture coordinates screw up? Is there a better way to go about this?
Any help is appreciated, thanks in advance!

A:

You are dividing an integer with an integer: 8 / 128, which results zero. Change it to floating point division: 8.0f / 128.0f.


Q:

Overriding App.Config settings

We have an app.config file that lists specific endpoint addresses and also some additional service settings.  We would like to change these settings using an external config file set by the environment that it is placed in.  What we would like it to do is dynamically read the external config file for that environment without hard coding values.
I know there is a way to specify an external file in the section specific to that section.  Is there a way to dynamically set this location?

A:

I ended up just setting it to an external config file by modifying the setting with:
    System.Configuration.AppSettingsSection appsettings = config.AppSettings;
    appsettings.File = Environment.CurrentDirectory + "\\configs\\" + configFile;
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appsettings");

That will allow you to dynamically set it to whatever config file you want it to be.

A:

Your first question - yes, you can "override" any configuration section (such as <client>, <bindings> etc. not section group such as <system.serviceModel>) with an external file:
<client configSource="yourCustomClient.config" />

Visual Studio will highlight this with errors - but it works! - it's just a deficiency of Visual Studio's editor here.
Your second question: no, I don't believe there's any way to make this truly dynamic - the best I can think of is having some sort of an XML transformation of your config file at build and/or install time.


Q:

How can I get Mocha's Unicode output to display properly in a Windows console?

When I run Mocha, it tries to show a check mark or an X for a passing or a failing test run, respectively. I've seen great-looking screenshots of Mocha's output. But those screenshots were all taken on Macs or Linux. In a console window on Windows, these characters both show up as a nondescript empty-box character, the classic "huh?" glyph:

If I highlight the text in the console window and copy it to the clipboard, I do see actual Unicode characters; I can paste the fancy characters into a textbox in a Web browser and they render just fine (✔, ✖). So the Unicode output is getting to the console window just fine; the problem is that the console window isn't displaying those characters properly.
How can I fix this so that all of Mocha's output (including the ✔ and ✖) displays properly in a Windows console?

A:

By pasting the characters into LinqPad, I was able to figure out that they were 'HEAVY CHECK MARK' (U+2714) and 'HEAVY MULTIPLICATION X' (U+2716). It looks like neither character is supported in any of the console fonts (Consolas, Lucida Console, or Raster Fonts) that are available in Windows 7. In fact, out of all the fonts that ship with Windows 7, only a handful support these characters (Meiryo, Meiryo UI, MS Gothic, MS Mincho, MS PGothic, MS PMincho, MS UI Gothic, and Segoe UI Symbol). The ones starting with "MS" are all fixed-width (monospace) fonts, but they all look awful at the font sizes typical of a console. And the others are out, since the console requires fixed-width fonts.
So you'll need to download a font. I like DejaVu Sans Mono -- it's free, it looks good at console sizes, it's easy to tell the 0 from the O and the 1 from the I from the l, and it's got all kinds of fancy Unicode symbols, including the check and X that Mocha uses.

Unfortunately, it's a bit of a pain to install a new console font, but it's doable. (Steps adapted from this post by Scott Hanselman, but extended to include the non-obvious subtleties of 000.)
Steps:

Download the DejaVu fonts. Unzip the files. Go into the "ttf" directory you just unzipped, select all the files, right-click and "Install".
Run Regedit, and go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont.
Add a new string value. Give it a name that's a string of zeroes one longer than the longest string of zeroes that's already there. For example, on my Windows 7 install, there's already a value named 0 and one named 00, so I had to name the new one 000.
Double-click on your new value, and set its value to DejaVu Sans Mono.
Reboot. (Yes, this step is necessary, at least on OSes up to and including Windows 7.)
Now you can open a console window, open the window menu, go to Defaults > Font tab, and "DejaVu Sans Mono" should be available in the Font list box. Select it and OK.

Now Mocha's output will display in all its glory.

A:

Update: this issue has now been fixed. Starting from Mocha 1.7.0, fallbacks are used for symbols that don't exist in default console fonts (√ instead of ✔, × instead of ✖, etc.). It's not as pretty as it could be, but it surely beats empty-box placeholder symbols.
For details, see the related pull request: https://github.com/visionmedia/mocha/pull/641


Q:

Distance percentage of a point relative to a line end in ArcGIS

I have a Polyline and a Points shapefile. I need to create a new Field in the Points shapefile with the distance percentage from the coordinate-priority of the line they belong to. The coordinate priority is the lowest-rightmost end of each line feature. I'm working with ArcGIS 10.2.2 (Advanced License). Here's an example:

Any suggestions?

A:

Create a unique ID for the lines
Create Routes from the lines - double check your line directions are the same
Locate features along routes (your points)
Divide the distance along the line by line length x 100%


Q:

Inverse Scalar Multiplication of a point over elliptic curve

I was implementing point arithmetic operation, and was exploring the properties of point arithmetic, and I am unable to conclude whether
$$ k^{-1}(kP) = P $$
where P is a point over elliptic curve $ F_p $ and
$ k^{-1}.k = 1 $ mod p
Please help me to understand its correct or not ?
And if it is correct how it can be proved ?

A:

No, this is not correct.
Let $E:y^2=x^3+1$ defined over $\mathbb{F}_5$. Let $P=(0,1)$. Then $2P=(0,4)$, but $3(2P)=6P=\mathcal{O}=[0,1,0]$, i.e., zero, or point at infinity, even though $2\cdot 3 \equiv 6 \equiv 1 \bmod 5$.
The reason for this is $|E(\mathbb{F}_5)|=6$ in this case, so $6P=\mathcal{O}$ for any point $P\in E(\mathbb{F}_5)$.
Perhaps what you are interested in is the following. Let $d=|E(\mathbb{F}_p)|$ and let $P\in E(\mathbb{F}_p)$. Then, $dP=\mathcal{O}$. Now, let $k\geq 1$ be relatively prime to $d$, i.e., $\gcd(k,d)=1$, and let $h$ be a natural number such that $kh\equiv 1 \bmod d$, i.e., there is some $n\geq 1$ such that $hk=1+nd$. Then:
$$h\cdot (kP)=(hk)P = (1+nd)P = P+n(dP)=P+\mathcal{O}=P.$$


Q:

OpsCenter cannot recognize Cassandra nodes in the same network

I am experimenting with Datestax OpsCenter 5.2 and Cassandra 2.1.7.  One trouble I encountered is that OpsCenter daemon (i.e., the server) seems to try to connect to the Cassandra agents using the broadcast_rpc_address, which is blocked by the security group (because broadcast_rpc_address is a public IP on AWS).
Details
The cluster has three nodes (10.0.0.0/24 is the subnet of a VPC on AWS, 52.x.x.x is a public IP)
Node0
cassandra.yaml: broadcast_address=10.0.0.100, rpc_address=10.0.0.100, broadcast_rpc_address=52.2.3.100
address.yaml: stomp_interface=10.0.0.99, local_interface=10.0.0.100, agent_rpc_broadcast_address=10.0.0.100
Node1
cassandra.yaml: broadcast_address=10.0.0.101, rpc_address=10.0.0.101, broadcast_rpc_address=52.2.3.101
address.yaml: stomp_interface=10.0.0.99, local_interface=10.0.0.101, agent_rpc_broadcast_address=10.0.0.101
Node2
cassandra.yaml: broadcast_address=10.0.0.102, rpc_address=10.0.0.102, broadcast_rpc_address=52.2.3.102
address.yaml: stomp_interface=10.0.0.99, local_interface=10.0.0.102, agent_rpc_broadcast_address=10.0.0.102
OpsCenter Node
Deployed in the same subnet
ip=10.0.0.99
Symptons
After adding "10.0.0.100, 10.0.0.101, 10.0.0.102" to the "Add Cluster" window on OpsCenter web console, I got the following in opscenterd.log:
2015-09-04 11:05:38+0000 []  INFO: New Cassandra host 52.2.3.100 discovered
2015-09-04 11:05:38+0000 []  INFO: New Cassandra host 52.2.3.101 discovered
...
2015-09-04 11:05:43+0000 []  WARN: [control connection] Error connecting to 52.2.3.100: errors=Timed out creating connection, last_host=None
2015-09-04 11:05:43+0000 [] ERROR: Control connection failed to connect, shutting down Cluster: ('Unable to connect to any servers', {'52.2.3.100': OperationTimedOut('errors=Timed out creating connection, last_host=None',)})

Notice OpsCenter tries to connect to nodes via their broadcast_rpc_address, which is blocked by the security group.  This is despite I have set agent_rpc_broadcast_address to subnet IPs.
Question 1
Is this the correct behavior of OpsCenter?  Why agent_rpc_broadcast_address is not used?
Question 2
If I change broadcast_rpc_address to subnet IPs, then OpsCenter connects fine.  But this prevents my clients from connecting, because non-seed nodes will have their subnet IP reported by seed nodes to the client, which is not reachable by the client.
I can also open up the security group to the OpsCenter server, but this is risky and requires going through the gateway.
So how should I solve the problem in this case?
Thoughts
The core of this problem is how to "intelligently" decide which IP to connect to depending on whether a client is inside or outside a subnet.  All documentation I have seen does not make it clear how this works.
Thanks for any help.
Addition 1
Would be grateful if you could also clarify how rpc(thrift) and native(binary) protocol are used by client and OpsCenter.
I have the impression that rpc is deprecated in favor of native protocol, but will this affect inter-node and client-node connection?

A:

Question 1
Is this the correct behavior of OpsCenter? Why agent_rpc_broadcast_address is not used?

It is at the moment. OpsCenter (via underlying python driver) gets rpc address from Cassandra itself, so it gets values of broadcast_rpc_address, which are not reachable. agent_rpc_broadcast_address is used to connect to the agents, not Cassandra nodes themselves.
I’m not sure why are you blocking access to the broadcast address from the same subnet (same security group even?) while also allowing access to it from outside the subnet.

Would be grateful if you could also clarify how rpc(thrift) and native(binary) protocol are used by client and OpsCenter.

As of 5.2 OpsCenter does not use thrift to communicate to Cassandra, relying on native protocol for opscenterd and native protocol + jmx for agents.


Q:

How to include filename when importing txt / csv file in postgres?

When I import a csv-file in postgres using psql I would like to add the filename in a column (before each row). Is this possible?
The command I am using:
psql.exe -h host-U user -d database -c "\COPY schema.table FROM filename.csv with csv

A:

I realize you stated "before each row" but you probably need to modify the .CSV contents in the language of your choice to do that.
Otherwise you could send a followup psql command after your first command to create the new column and update it with the filename:
psql.exe -h host-U user -d database -c "ALTER TABLE schema.table ADD COLUMN filename character varying(255);UPDATE schema.table SET filename='filename.csv' WHERE filename IS NULL;"


Q:

Is the CUDA Occupancy Calculator provided by NVIDIA out of date?

The CUDA Wikipedia page lists the "Maximum number of threads per block" as 1024 for compute capability 2.x.
Is this information incorrect as I have read elsewhere that 512 is always the max number of threads per block? Also the CUDA occupancy calculator won't allow more than 512 for the "Threads Per Block" setting.
Edit: The Occupancy Calculator I was looking at was out of date. The newest version can be found on this page.

A:

There is a newer version available. Go to the CUDA 4.0 download page, and select "Documentation". Scroll down to find the CUDA Occupancy Calculator v. 2.4 (yours is 2.1, right?)


Q:

Getting Parse Error during installation of Drupal 8

I am getting the following error while Installing Drupal 8.

Parse error: parse error, expecting T_CONSTANT_ENCAPSED_STRING' or'('' in var\www\html\core\includes\bootstrap.inc on line 3

When I checked the line number 3 in index.php I saw following two lines.
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

I don't know what is the meaning of above two lines and why these are creating the above error.

A:

Hopefully you're not installing Drupal 8 in the hope of using it as a stable website...it's nowhere near ready yet :)
That said, the reason you're getting the error is because the PHP const keyword has only been available for use in the global scope since PHP 5.3. Drupal 8 uses const in the global scope in a lot of places (correctly, as Drupal 8 will require at least PHP 5.3).
My guess is you have PHP 5.2 or lower installed on your server.
Some helpful links:

const docs
Drupal change record for using const instead of define()
Migrating from PHP 5.2.x to PHP 5.3.x


Q:

Error when trying to load library(ggplot2) in R

I'm having trouble loading the ggplot2 library in R. Below is the code that I type in. Anyone have any ideas on how to make this work?
> library(ggplot2)
Error in get(x, envir = this, inherits = inh) :
  unused argument(s) (envir = this, inherits = inh)

Error : unable to load R code in package 'ggplot2'

Error: package/namespace load failed for 'ggplot2'

Edit 1: More Info
> sessionInfo()
 R version 2.13.0 (2011-04-13)
 Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

 locale:
 [1] en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8

 attached base packages:
 [1] grid      stats     graphics  grDevices utils     datasets  methods   base

 other attached packages:
 [1] quantmod_0.3-15 TTR_0.20-2      xts_0.8-0       zoo_1.6-5   Defaults_1.1-1
 [6] reshape2_1.1    proto_0.3-9.2   reshape_0.8.4   plyr_1.5.2

 loaded via a namespace (and not attached):
 [1] lattice_0.19-26 stringr_0.4     tools_2.13.0

Edit 2:
The version of ggplot2 that I'm trying to use is 0.8.9. When I call the traceback function I get the following result:
> traceback()
  2: stop(gettextf("package/namespace load failed for '%s'", package),
       call. = FALSE, domain = NA)
  1: library(ggplot2)

A:

Quit R. Go into your /Library/Frameworks/R.framework/Versions/2.13/Resources/library/ directory and trash the entire folder. If you have any other libraries make sure they don't have any copies, either. Restart R and reinstall and make sure you install all dependencies. There is a check mark option in the GUI Package Installer or you can use (at the command line: install.packages("ggplot2", dependencies=c("Depends", "Imports", "Suggests") ).
Further thought:
Obscure errors in the MacOS can sometimes be resolved by repairing disk permissions. The Disk Utility.app program is the way I usually do it. Some people run it on a regular basis although I only do so when a problem arises that seems to be a file access issue.


Q:

How to add multiple SQL rows to an PHP array

I have $view_data['auth_info'] which is populated with a query row, that works fine. But i need to add an additional row to this array. How is this possible? All the variables are unique, so theres no change i will have to identical definitions.
I tried following:
$view_data['auth_info'] = $myFirstSQLRow
array_push($view_data['auth_info'],$mySecondSQLRow);

But it failed:
Message: array_push() [function.array-push]: First argument should be an array

But isnt the first var an array or have i misunderstood something?

A:

You are looking for array_merge. Use it like this:
$view_data['auth_info'] = $myFirstSQLRow;
$view_data['auth_info'] = array_merge($view_data['auth_info'], $mySecondSQLRow);

As it says in the documentation, you may need to type-cast (by putting (array) in front of your variables.)


Q:

Mac Dynamic Library Craziness (May be Fortran Only)

I have this fortran 90 file (will add the code to the bottom of the question) which I have compiled into a dynamic library on OS X Mavericks using the following command: gfortran -dynamiclib trianglepy.f90 -o libtriangle.dylib. This produces libtriangle.dylib which is stored on my desktop. I can than make a C++ file using this library(code attached at bottom). I than compile the code using g++ main.cpp -o main -std=c++11 -L ~/Desktop/ -ltriangle. This compiles the code perfectly. But when I run the produced executable, I get the following error:
dyld: Library not loaded: libtriangle.dylib
  Referenced from: /Users/zacharykraus/./main
  Reason: image not found
Trace/BPT trap: 5

When I run otool -L main I get
main:
    libtriangle.dylib (compatibility version 0.0.0, current version 0.0.0)
    /opt/local/lib/libgcc/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.20.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1)
    /opt/local/lib/libgcc/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)

If I try and export the correct path to LD_LIBRARY_PATH or DYLD_LIBRARY_PATH. I get the same error. The only way to get the executable main to run is to move the file main to the desktop. This runs successfully to produce:
the angles are 33.5496 61.5496 28
the sides are 2.2 3.5 1.86885

Note: I dont think that triangle actually exists, but on to the actual question.
Can some one please explain to me how I can get the executable to run from a different directory than the one libtriangle.dylib is in? Additinally, why does my executable only run when I move the executable to the same directory libtriangle.dylib is in?
The Fortran 90 code that produces libtriangle.dylib is:
!post all functions here
!double precision function area(side,angle)
!   double precision side(3),angle(3)
!end

double precision function sidelos(angle1,angle2,side2)
    double precision angle1, angle2, side2
    !law of sines to calculate the missing side
    sidelos=side2*sin(angle1*3.141593d0/180d0)/sin(angle2*3.141593d0/180d0)
end

double precision function anglelos(side1, side2, angle2)
    double precision side1, side2, angle2
    !law of sines to calculate the missing angle
    anglelos=asin(side1*sin(angle2*3.141593d0/180d0)/side2)*180d0/3.141593d0
end

double precision function sideloc(side1, side2, angle3)
    double precision side1, side2, angle3
    !law of cosines to calculate side 3
    sideloc=sqrt(side1**2 + side2**2 - 2d0*side1*side2*cos(angle3*3.141593d0/180d0))
end

double precision function angleloc(side1, side2, side3)
    implicit none
    double precision side1, side2, side3
    !law of cosines to calculate angle3
    angleloc=acos((side1**2 + side2**2 - side3**2) / 2d0/side1/side2)*180d0/3.141593d0
end

!post all subroutines here
subroutine asa(angle1, side3, angle2, angle, side)
    double precision angle(3), side(3), sidelos
    double precision angle1, side1, angle2
    integer i
    !f2py intent(out) angle
    !f2py intent(out) side
    angle(1) = angle1
    angle(2) = angle2
    side(3) = side3
    !calculate the third angle
    angle(3)=180-angle(1)-angle(2)
    do i=1,2
    !calculate the missing sides using law of sines
        side(i)=sidelos(angle(i),angle(3),side(3))
    end do
end

subroutine sas(side1, angle3, side2, angle, side)
    double precision angle(3), side(3), sideloc, anglelos
    double precision side1, angle3, side2
    integer i
    !f2py intent(out) angle
    !f2py intent(out) side
    side(1) = side1
    side(2) = side2
    angle(3) = angle3
    !calculate the missing side with law of cosines
    side(3)=sideloc(side(1),side(2),angle(3))
    do i=1,2
        !calculate the missing angles with the law of sines
        angle(i)=anglelos(side(i), side(3), angle(3))
    end do
end

subroutine sss(side1, side2, side3, angle, side)
    double precision angle(3), side(3), angleloc, anglelos
    double precision side1, side2, side3
    integer i
    !f2py intent(out) angle
    !f2py intent(out) side
    side(1) = side1
    side(2) = side2
    side(3) = side3
    !calculate the missing angle with law of cosines
    angle(3)=angleloc(side(1),side(2),side(3))
    do i=1,2
        !calculate the missing angles with the law of sines
        angle(i)=anglelos(side(i), side(3), angle(3))
    end do
end

subroutine aas(angle1, angle2, side1, angle, side)
    double precision angle(3), side(3), sidelos
    double precision angle1, angle2, side1
    integer i
    !f2py intent(out) angle
    !f2py intent(out) side
    angle(1) = angle1
    angle(2) = angle2
    side(1) = side1
    !calculate the third angle
    angle(3)=180-angle(1)-angle(2)
    do i=2,3
        !calculate the missing sides using law of sines
        side(i)=sidelos(angle(i),angle(1),side(1))
    end do
end

The C++ code that links to the dynamic library is:
extern "C" void sas_(double*, double*, double*, double*, double*);
#include <iostream>
using namespace std;
int main()
{
  double side1 = 2.2, side2= 3.5, angle3 = 28;
  double angle[3], side[3];
  sas_(&side1, &angle3, &side2, angle, side);
  cout << "the angles are ";
  for (double value : angle)
    cout << value <<" ";
  cout << endl;

  cout<<"the sides are ";
  for (double value : side)
    cout << value << " ";
  cout << endl;
  return 0;
}

A:

The answer has to do with how dynamic libraries work in mac os x. Dynamic libraries in os x always store a path in the library. When you compile the dynamic library the default path is the name of the library. When you link the dynamic library at compile time, the path in the library gets stored in the executable. Consequently, when you attempt to run main, the executable is looking for libtriangle.dylib in the current directory. This is why if you copy libtriangle.dylib to the current directory, the program runs correctly.
To fix the issue, add -install_name and the absolute path to the compilation. Than recompile the c++ file linking to libtriangle.dylib. After the recompile rerunning otool -L main gives:
main:
/Users/zacharykraus/Desktop/libtriangle.dylib (compatibility version 0.0.0, current version 0.0.0)
/opt/local/lib/libgcc/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.20.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1)
/opt/local/lib/libgcc/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)

Now the executable runs correctly without having to copy the dynamic library to the current path.


Q:

Which libraries/frameworks in Java rely on client-defined classes to have static members?

There are libraries and frameworks in Java that rely on static members in the class. Usually, they inspect certain static fields of the class via reflection.
As example, I know that AtomicReferenceFieldUpdaters usually need to be saved in a static field of the class it is modifying, if put in another class they will lack a security permission to do it.
My questions are:

Can you list dominant Java frameworks/libraries that rely on certain static fields being present in the class? In what way?
Are there any important Java frameworks/libraries which rely on the presence of static methods in the class?

A:

Just comes to my mind:
Whenever a client class must implement Serializable it relies on serialVersionUID static field.

A:

Spring 3.1's JUnit support will inspect the test class's static nested classes, to find an annotated configuration class. But I wouldn't say it relies on it; it's purely an example of convention over configuration.
JUnit also relies on static methods for its @BeforeClass and similar annotations.
In both cases the static members need to be annotated.


Q:

Why do we use Laplace transforms to analyse transient circuits?

I just learned transient circuits and we solved them both in the time domain and the Laplace domain and I can't understand why we would use the Laplace domain as it seems it is a lot more simple to use the time domain especially in series RLC circuits.

A:

It's easy to solve simple filter circuits in the time domain but there becomes a tipping-point where most engineers would prefer to solve problems in the frequency domain and apply (for example) a step-function. Finding the inverse Laplace is fairly straightforward because of Laplace tables.
As an example of an RLC low pass filter, engineers become accustomed to the transfer function: -
$$H(s) = \dfrac{\omega_n^2}{s^2+2\zeta\omega_n^2 s + \omega_n^2}$$
And, applying (for example) a step function is as simple as multiplying by 1/s: -
$$\dfrac{1}{s}\cdot\dfrac{\omega_n^2}{s^2+2\zeta\omega_n^2 s + \omega_n^2}$$
Engineers who are familiar with this get to recognize that this converts to a standard form and the next step is just using the tables to derive the transient response.
In addition, the term \$\omega_n\$ (the natural resonant frequency) can be is factored out a lot of the time so that solving the step-function formula for \$\omega_n=1\$ begins with: -
$$\dfrac{1}{s}\cdot\dfrac{1}{s^2+2\zeta s + 1}$$
This is rearranged to a standard form such as this (underdamped resonance): -
$$\dfrac{1}{s[(s+a)^2 + b^2]}$$
Where \$a =\zeta\$ and \$b=\sqrt{1-\zeta^2}\$
The Laplace tables give us this: -
$$H(t) = 1+\dfrac{1}{\sqrt{1-\zeta^2}}\cdot e^{-\zeta t}\cdot \sin(t\cdot\sqrt{1-\zeta^2}+\phi)$$
Where \$\phi = \arccos(\zeta)\$
But you will probably only be convinced when you are dealing with slightly more complex situations or really do need to analyse the frequency spectrum.

A:

In this context, the Laplace transform is simply a tool that we use to deal with differential equations.  I think it provides a slightly more intuitive feel for how responses change with frequency, but really, it's just a tool for dealing with differential equations.
The transform really starts to shine when you're cascading signals.  A variety of properties of the transform really become very useful then.  For example, convolutions in the time domain become simple multiplications in the frequency domain.  There are also a variety of frequency domain tools  that make control easier.
You start using the transforms for simple systems, so you're facile when you start using them for more advanced situations -- not because they're so intuitively easy.  In fact, the understanding is very quantal.  You'll be able to "do" problems successfully, but it may take many iterations, even years, before you grok the transforms.


Q:

How to ignore deprecation warnings in Python

I keep getting this :
DeprecationWarning: integer argument expected, got float

How do I make this message go away? Is there a way to avoid warnings in Python?

A:

You should just fix your code but just in case,
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

A:

I had these:
/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/persisted/sob.py:12:
DeprecationWarning: the md5 module is deprecated; use hashlib instead import os, md5, sys

/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/python/filepath.py:12:
DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha

Fixed it with:
import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    import md5, sha

yourcode()

Now you still get all the other DeprecationWarnings, but not the ones caused by:
import md5, sha

A:

From documentation of the warnings module:
 #!/usr/bin/env python -W ignore::DeprecationWarning

If you're on Windows: pass -W ignore::DeprecationWarning as an argument to Python. Better though to resolve the issue, by casting to int.
(Note that in Python 3.2, deprecation warnings are ignored by default.)


Q:

Cargar un Combobox apartir de una lista consumida de WebService

Buenas quisiera que me puedan ayudar estoy realizando es consumir un webservice que me retornar una lista y esos valores agregarlo en un combobox
Este es mi Webservice
public List<Combos> D_LlenarCombo(Int32 Opt, Int32 Id_Tipo)
        {
            SqlDataReader reader;

            SqlConnection cn = new SqlConnection(ObtenerCadenaConexion());
            cn.Open();
            SqlCommand cmd = new SqlCommand("llenarcombos", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@opt", SqlDbType.Int).Value = Opt;
            cmd.Parameters.Add("@Id_Tipo", SqlDbType.Int).Value = Id_Tipo;

            reader= cmd.ExecuteReader();
            List<Combos> Combo = new List<Combos>();
            try
            {
                while (reader.Read())
                {
                    Combo.Add(new Combos { Id = reader.GetInt32(0), Nombre = reader.GetString(1) });
                }
                reader.Close();
                cmd.Dispose();
                cn.Close();
                return Combo;
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }

        }

Esta es la clase Combo.
 public class Combos
    {
        public Int32 Id { get; set; }
        public String Nombre { get; set; }
    }

Esta es la pagina web que va consumir al webservice.
void LLenarCombo()
        {

         //Cargar al combobox ViaIncidencia
                var varViaIncidencia = Obj.Ws_LlenarCombo(4, 0).ToList();
     CboViaIncidencia.DataSource = varViaIncidencia;
                CboViaIncidencia.DataTextField = "ViaIncidencia";
                CboViaIncidencia.DataValueField = "Id_ViaIncidencia";
                CboViaIncidencia.DataBind();
                CboViaIncidencia.SelectedIndex = -1;

}

Si me podrían ayudar porfavor

A:

El problema reside en que estas intentando seleccionar como value el campo Id_ViaIncidencia y como text el ViaIncidencia pero dicho objeto no tiene estas propiedades.
Pueba así:
void LLenarCombo()
        {

         //Cargar al combobox ViaIncidencia
                var varViaIncidencia = Obj.Ws_LlenarCombo(4, 0).ToList();
     CboViaIncidencia.DataSource = varViaIncidencia;
                CboViaIncidencia.DataTextField = "Nombre";
                CboViaIncidencia.DataValueField = "Id";
                CboViaIncidencia.DataBind();
                CboViaIncidencia.SelectedIndex = -1;

}


Q:

SQL Server: Is it possible to pin a query to the toolbar?

I run a query very often and was wondering if it's possible to pin that query to the menu bar or toolbars of SQL Server for easy access?
Or does anyone have an alternate solution they use?
EDIT:  Using Microsoft SQL Server 2012

A:

Create a custom template and then you can easily access it from the Template Explorer in SSMS

To create a custom template

In Template Explorer, navigate to the node where you would like to
  store the new template.
Right-click the node, point to New, and then click Template.
Type the name for your new template and then press ENTER.
Right-click the new template, and then click Edit. In the Connect to
  Database Engine dialog box, click Connect to open the new template
  in Query Editor.
Create a script in Query Editor. Insert parameters in your script in
  the format . The data type and
  value areas must be present, but can be blank.
On the toolbar, click Save to save your new template.

https://technet.microsoft.com/en-us/library/ms179334(v=sql.105).aspx


Q:

How to create spreadsheet and install add-on or attach app script to the spreadsheet in google drive using php

I'm creating a website that requires the functionality to create a spreadsheet in google drive and install a sheets add-on to the created spreadsheet on click of a button.
I'm able to create spreadsheet using the below code
// $client is the Google_Client() object with required properties
$service = new Google_Service_Sheets($client);

$spreadsheet = new Google_Service_Sheets_Spreadsheet([
    'properties' => [
        'title' => 'Spreadsheet Title'
    ]
]);

$spreadsheet = $service->spreadsheets->create($spreadsheet, [
    'fields' => 'spreadsheetId'
]);

May I know if there is a way to install an add-on or attach app script to that created spreadsheet through PHP?
If the above is not possible, is it possible to copy a spreadsheet that already has add-on installed in my google drive to user's google drive?
thanks,

A:

It is important to distinguish between an Add-on and a bound script

An Add-on "is installed for a particular user after he or she chooses the add-on in the store". And "If two people collaborate on a document, and one of them uses an add-on, it is installed for the one user and enabled for the document."

This means that if you use an Add-on and share your document with
  other users, those users will be able to use the Add-on on the
  specific document you share with them. However, if you make a copy of
  this document to a user's drive, and this copy will be only used by
  the user, but not by you - the user can use the Add-on, unless he
  manually installs it.

A bound script is attached to a document. If you make a copy from
your drive to the user's drive - the document will be copied
including the bound script.

To copy file including bound script to user's drive, you can create a WebApp with the content
function doGet() {
  DriveApp.getFileById('INSERT ID OF THE FILE ON YOUR DRIVE').makeCopy();
}

and deploy it as "User accessing the web app" and "Who has access to the app" -> "Anyone"

Keep in mind that this works only if you assign to the file on on your
  drive viewing permissions, i.e. you need to share the file with your
  domain or public users - depending on your intentions. In the last
  step you copy the URL of the Web App and set-up your Website in such a
  way that you redirect to the Web App URL, when a user clicks a button.

Instead of copying a file with an Apps Script, you can also attach posteriourly a script to any created or existing document. For this, you can use the Apps Script API, as proposed by Diego. You need to create an empty script project, following the sample in the quickstart, but make sure to specify the parentId of the file to which you want to bind the script. Subsequently, update the content of the file with a file.source


Q:

why doesn't the second rectangle stay visible in my SVG code

I have this piece of code which as I understand it should draw the first rect tangle and then the second. The second has animation which simply expands the width. So with this code I see the blue bar appear then I see the yellow bar appear and it grows as expected but when it finishes it disappears.The both have the same start points and width so it making a progress bar. The blue bar is 400 pixels in length, the yellow is only 250 so I should see 150 pixels of blue at least that is what I think should be happening
<svg xmlns='http://www.w3.org/2000/svg'>
    <rect x='10' y='10' height='20' width='400' style='stroke:#ff0000; fill: #0000ff'>
    </rect>
    <rect x='10' y='10' height='20' width='0' style='stroke:#ff0000; fill: #ffff00'>
<animate attributeName='width' attributeType='XML'
    to='250'
    begin='0s'
    dur='2s' />
    </rect>
</svg>

I am still new to SVG but this should work from what I have read the yellow bar is done last so it be on top.

A:

Your animate tag have to include an explicit fill parameter with the value 'freeze'. Otherwise, the default fill='remove' is used, which means the animated parameter reverts back to the value it had before the animation (in this case, "0").
<svg xmlns='http://www.w3.org/2000/svg'>
    <rect x='10' y='10' height='20' width='400' style='stroke:#ff0000; fill: #0000ff'>
    </rect>
    <rect id="r1" x='10' y='10' height='20' width='0'  style='stroke:#ff0000; fill: #ffff00'>
<animate attributeName='width' attributeType='XML'
    from='0'
    to='250'
    begin='0s'
    dur='2s'
    fill='freeze'
         />
    </rect>
</svg>

(full reference at: https://www.w3.org/TR/SVG/animate.html#ValueAttributes)


Q:

Sampling from a product of two Multivariate Gaussians

I have a multivariate Gaussian defined as follows:
$$
p(x) = \omega(x)\gamma(x)
$$
where $\omega$ and $\gamma$ both are multivariate Gaussians and from which I can sample very efficiently given due to special structure in their covariances: one is diagonal, of the other I know the diagonalization, which is very sparse.
I wonder if there is a way to sample from $p$, given samples from $\omega$ and $\gamma$. The standard way of doing a Cholesky on the joint covariance is not efficient enough.

A:

Rejection sampling  might work: sample from one distribution and accept based on the other density

Sample $x$ from $\omega(x)$.
Return $x$ with probability $\gamma(x) / \gamma(\mu_\gamma)$, otherwise goto 1.

The roles of $\gamma$ and $\omega$ may be switched due to symmetry, so one could try both to see which is more efficient.
However, if neither component distribution is 'close' to the joint distribution, this will not be efficient as most samples get rejected.


Q:

iOS app lifecycle 4/3GS/iPad vs 2G/3G

I've read the Apple's documentation about application lifecycle and  made some tests to figure out what is the applications life cycle on different devices. (All running iOS 4.x except the 2G)
I've tested "multitasking" capable devices vs some that do not support this feature :
iPhone 2G/3G app lifecycle :
(START)
- didFinishLunchingWithOptions
- applicationDidBecomeActive

(HOME PRESSED)
- applicationDidEnterBackground
- appWillTerminate

iPad / iPhone 4 app lifecycle:
(START)
- didFinishLunchingWithOptions
- applicationDidBecomeActive

(HOME PRESSED)
- appWillResignActive
- appDidEnterBackGround

(RESART app in the "Taskbar")
- appWillEnterForeGround
- appDidBecomeActive

I've tried to kill the App from the "taskbar" but the debugger received a SIGKILL ! What happens when you kill and app in that way ?
When is appWillTerminate called on the "multitasking" capable device ? Are my results correct ?
EDIT:
Quote from apple's doc about appWillTerminate :

For applications that support background execution, this method is generally not called when the user quits the application because the application simply moves to the background in that case. However, this method may be called in situations where the application is running in the background (not suspended) and the system needs to terminate it for some reason.

What do they mean by "generally not called". " the system needs to terminate it.." means that the method appWillTerminate will be invoked ?

A:

I think you're right. When you kill an app from the taskbar (or when your device is running low on memory and the OS kills the app for you), it just sends a SIGKIL signal. As you note, it never calls any of the callbacks.
According to the documentation:

For applications that support
  background execution, this method is
  generally not called when the user
  quits the application because the
  application simply moves to the
  background in that case. However, this
  method may be called in situations
  where the application is running in
  the background (not suspended) and the
  system needs to terminate it for some
  reason.

So, iOS can call the applicationWillTerminate: method but probably won't. (I've never seen it.)
If you want to save any state before your app is killed, you need to do it as it goes into the background.


Q:

Can clang warn about undefined behavior at compile-time?

#include <iostream>

int main()
{
    int n = -1000;
    for (int i(0); i != n; ++i)
    {
    }
}

In gcc the following error is caught at compile-time:
main.cpp:6:5: warning: iteration 2147483647u invokes undefined behavior [-Waggressive-loop-optimizations]

     for (int i(0); i != n; ++i)

Clang's -fsanitize=undefined is a run-time mechanism. What is clang's compile-time equivalent?

A:

Undefined behaviour is often described as such in the standard because it is difficult if not impossible for the compiler to check this in all situations.
You just run into one case that is handled by GCC and not Clang. If you look, you'll be able to find cases that are handled by one but not another compiler. That's because they're not the same compiler, and have different analyses that they perform.

A:

Clang can't catch this one yet, at least not as part of compiling (I haven't checked the clang static analyzer, and if it also can't, please file a bug).
GCC has decided that it's okay to emit warnings from the middle of the optimizer:
$ g++ -Waggressive-loop-optimizations a.cc
$ g++ -Waggressive-loop-optimizations a.cc -O2
a.cc: In function ‘int main()’:
a.cc:6:5: warning: iteration 2147483647u invokes undefined behavior [-Waggressive-loop-optimizations]
     for (int i(0); i != n; ++i)
     ^
a.cc:6:5: note: containing loop

This is actually really tricky and potentially finicky. The clang developers believe that changing what warnings you emit based on optimization level is bad behaviour, we don't think users expect to miss warnings when building at -O0 or to discover new bugs days later when doing a release build. Secondly, the way that the optimizer is designed is such that it keeps one representation of the program around at any point in time and transforms it from saying one thing to another without keeping a history trail of what it's done versus what's in the original code. This LLVM blog article talks about the problem. Clang's warnings are built on top of clang's ASTs which have a complete representation of the original source code, including template and macro histories so we can always point to the right code and filter on properties like "was it a template argument".
It might be possible to add this to clang, I haven't figured out an efficient way to do it after only 30 seconds of thinking about it. The problem is that we're willing to spend a lot more time proving things in the optimizer than we are as part of warning generation. We don't want to pay the compile time twice. The static analyzer on the other hand, doesn't have this restriction and will happily do very expensive work to find your bugs.
Finally, the way you phrased your question makes it sound like you think that clang either does or doesn't catch all undefined behaviour at compile time. We do catch as much as we can efficiently, and provide dynamic checkers for as much of the rest as possible, but neither gcc nor clang will promise to catch all undefined behaviour either at compile time nor at run time. There's too much of it, and there is no list of what it all is (some operations are explicitly UB in the standard, some are UB simply because the standard fails to define what the behaviour is!).


Q:

How to use a method from another class on an object of an array?

For starters, I have two classes that are relevant: Enemies.java and Sarz.java. Enemies extends Sarz.
public class Enemies extends Sarz {

It has an array with some enemy objects inside.
enemies[0] = new Enemies("Dragon", 100, 100, "Cave");
enemies[1] = new Enemies("Saturn Fly Trap", 10, 15, "Forest");

In Sarz, I make an array of type Sarz and in it I store some randomly generated enemies.
Enemies e = new Enemies();
e.generateEnemies();

Sarz[][] map = new Sarz[5][5];

while (count < 4){
  row = r.nextInt(5);
  column = r.nextInt(5);
  if (map[row][column] == null){
    map[row][column] = e.enemies[r.nextInt(8)];
    System.out.println(map[row][column].getName() + " at " + row + "," + column);
    count++;
  }
}

My problem is that when I use that println statement to test, they have been stored correctly in random spots, but I cannot seem to get anything to return the enemy name to me. I have tried using Arrays.toString() and the getters and setters of the Enemies class, but they will not work on the map array because it is of type Sarz. I would like to be able to use map[row][column].getEnemyName() or at least something to return a String instead of Enemies@14ae5a5 at 1,0.

A:

Since Enemies extends Sarz, hence you can cast a Sarz to an object of Enemies (if it is a valid one.) So, you can do:
System.out.println(((Enemies)map[row][column]).getEnemyName() + " at " + row + "," + column);


Q:

Get date from ISO week number in Python

Possible Duplicate:
What’s the best way to find the inverse of datetime.isocalendar()?

I have an ISO 8601 year and week number, and I need to translate this to the date of the first day in that week (Monday). How can I do this?
datetime.strptime() takes both a %W and a %U directive, but neither adheres to the ISO 8601 weekday rules that datetime.isocalendar() use.
Update: Python 3.6 supports the %G, %V and %u directives also present in libc, allowing this one-liner:
>>> datetime.strptime('2011 22 1', '%G %V %u')
datetime.datetime(2011, 5, 30, 0, 0)

Update 2: Python 3.8 added the fromisocalendar() method, which is even more intuitive:
>>> datetime.fromisocalendar(2011, 22, 1)
datetime.datetime(2011, 5, 30, 0, 0)

A:

With the isoweek module you can do it with:
from isoweek import Week
d = Week(2011, 40).monday()

A:

%W takes the first Monday to be in week 1 but ISO defines week 1 to contain 4 January. So the result from
datetime.strptime('2011221', '%Y%W%w')

is off by one iff the first Monday and 4 January are in different weeks.
The latter is the case if 4 January is a Friday, Saturday or Sunday.
So the following should work:
from datetime import datetime, timedelta, date
def tofirstdayinisoweek(year, week):
    ret = datetime.strptime('%04d-%02d-1' % (year, week), '%Y-%W-%w')
    if date(year, 1, 4).isoweekday() > 4:
        ret -= timedelta(days=7)
    return ret


Q:

Is there supplementary material that improves the adept NPC class?

The NPC class adept is considered a tier 4 class, so it's theoretically more versatile than tier 5 classes like the fighter, monk, paladin, soulknife, and so on, and the class is a reasonable choice for a PC caster in a low-tier campaign. However, I've not seen any material that makes adepts any better except stuff that improves familiars and the prestige class hexer from Masters of the Wild. (Entering the prestige class requires that a creature be able to cast lightning bolt as a divine spell, and the adept is the only SRD class that can do that.) Even though they're tier 6—like the commoner!—, there's material devoted to the aristocrat NPC class like The Quintessential Aristocrat. But, apparently, no material devoted to the poor adept.
Searching the Web for help with adept is tough: results tend to be about the green star adept, dragonfire adept, and other classes with adept in their names instead.
What additional options are available to the adept? I'm interested in answers like those to this question
P.S. Both D&D 3e and D&D 3.5e material are acceptable. Official material preferred but content from licensed material is acceptable as is third-party material.

A:

The Eberron Campaign Setting introduces the religious adept
The adept's spell list is expanded a little by a variant adept presented in the Eberron Campaign Setting on—appropriately enough—Adepts:

A religious adept is identical to the adept NPC class presented in the Dungeon Master’s Guide (see page 107), with one important exception: The adept can select a single cleric domain. An adept does not gain bonus domain spells as a cleric does, but she adds the spells of her domain to her regular adept spell list and can prepare these domain spells in place of her usual spells.…
If a cleric takes a level in the adept class, he does not get to select a new domain, but he can add the spells from one of his current domains to his adept spell list. Likewise, an adept who takes cleric levels must use her adept domain as one of her two cleric domains. (256)

This allows some significant variation between otherwise generic adepts.
Other texts add a few spells
The following spells are added to the adept spell list by other sources:

2nd Level: bewildering substitution [illus] (Complete Champion 116), bewildering visions [illus] (Complete Champion 116), invoke the cerulean sign [evoc] (Lords of Madness 211).
4th Level: lesser spell turning [abjur] (Mintiper’s Chapbook Web column “Part 10: Chronicler's Compendium”).
5th Level: bewildering mischance [ench] (Complete Champion 116).

There are probably a few other extra spells added to the adept list floating around in other texts, too, but this is what I had at hand.

A:

I am not aware adept handbooks.  @HeyICanChan got the additional spells, though I'll note Lords of Madness does not actually list invoke the cerulean sign as an adept spell but specifically says "its magic is nearly universal and can be mastered by all spellcasting classes."
If you're willing to go 3.0 instead of 3.5, Masters of the Wild recommended the following spells be added to the adept list.  I've listed the 3.5 sources for when I could fine them.
More Spells for Adepts sidebar, Masters of the Wild, p81  (DotF-Defenders of the Faith, MotW-Masters of the Wild, TaB-Tome and Blood):
0 - dawn (MotW) - SpC, p59
1 - hawkeye (MotW) - SpC, p110
1 - lesser cold orb (TaB) - SpC, p151, (orb of cold, lesser)
1 - scarecrow (MotW) -
2 - choke (TaB) -
2 - decomposition (MotW) - SpC, p61
2 - owl's wisdom (TaB) - PH, p259
3 - beastmask (DotF) -
3 - embrace the wild (MotW) - SpC, p79
3 - enhance familiar (TaB) - SpC, p82
4 - false bravado (MotW) -
4 - languor (MotW) - SpC, p130
4 - weather eye (DotF) - SpC, p238
5 - big sky (MotW) -
5 - ghostform (TaB) - SpC, p103
Here are the other alternate class features I've dug up for adepts from WotC sources:
Adept Alternate Class Features:
Familiar – Dragon 280, p60 - Alternative starting familiars.  (3.0ED)
Familiar – Dragon 323, p88 - Specialist familiars.  (3.5ED)
Familiar – Dragon 341, p96 - Specialist familiars.  (3.5ED)
Familiar - Dragon 348, p88 - Unfamiliar territory: focus caster; (arcane reabsorbtion isn't valid as it specifically calls out arcane spells).  (3.5ED)
Goblin of Grodd - Into the Dragon's Lair, p86 – An adept of Grodd can rebuke or command shadows as a cleric of the same level.  (3.0ED)
Goblin of Grodd - Into the Dragon's Lair, p90-91 – Alternate spell list.  (3.0ED)
Kobold - Races of the Dragon, p48 - Alternate spell list:  Swap animal trance and daylight with lesser restoration and create food & water, respectively.  (3.5ED)
More Spells for Adepts sidebar - Masters of the Wild, p81 - Additional spells from Defenders of the Faith, Masters of the Wild, Tome and Blood.  (3.0ED)
Religious Adept – Eberron Campaign Setting, p256 – Add ability to choose a domain from the god worshipped; add domain spells to spell list and gain domain power, treating adept level as cleric level.  (3.5ED)
Religious Urban Adept – Sharn: City of Towers, p167 – Alternate spell list, add ability to choose a domain from the god worshipped; add domain spells to spell list and gain domain power, treating adept level as cleric level.  (3.5ED)
Urban Adept – Sharn: City of Towers, p167 – Alternate spell list.  (3.5ED)


Q:

Logging events in Flurry outside an active session

Does Flurry only log custom events if a session is active? or does it also log custom events outside the scope of a session? I ask this because we let the user decide to enable/disable data tracking, and I would like to know if encapsulating the Sessions around an if-statement is sufficient, or if I should place if-statements around each FlurryAgent.logEvent(...) call.

A:

From my usage of Flurry, you need to make logEvent calls within the scope of a session. So failing to call the session will prevent the logEvent from working.
In my case I was simply trying to track when a user enabled or disable an app widget which I didn't want tracked as a session because it would skew my stats as these "sessions" would not even last a second.
In your case it would represent desired behaviour.
But considering the Flurry library is not transparent, I wouldn't trust the current behaviour. Since the call is static, it really wouldn't be that taxing to surround with static call.
public static void logEvent(Context context){
    boolean userWantsPrivacy = PreferenceManager bla bla...
    if(!userWantsPrivacy){
        FlurryAgent.logEvent(...)
    }
}

If the access to the sharedpreference causes some kind of perceived performance hit, consider storing the preference in some sort of singleton.


Q:

How to dynamically move  into a newly created ?

I have the following HTML structure:

      .......

The  tags are being populated with a parsed XML response.
I usually have 20 or so tr tags.
I want that after the 4th, 8th, 12, etc  tag to create a  and insert the 4  tags into it.
Here is my jquery so far:
var i = 1;
var j = 2;
var margin = 0;
var max = $('.innerContent tr').length;
  for(i = 1; i<=max; i++)
  {
  var child1 =  i - 3;
  var child2 =  i - 2;
  var child3 =  i - 1;
  var hotel1 =  $('.innerContent tr:nth-child('+child1+')');
  var hotel2 =  $('.innerContent tr:nth-child('+child2+')');
  var hotel3 =  $('.innerContent tr:nth-child('+child3+')');
  var hotel4 =  $('.innerContent tr:nth-child('+i+')');
    if(i%4 == 0)
    {
    $('.innerContent tbody').prepend('

');
    $('.line_wrapper').append(hotel1,hotel2,hotel3,hotel4);
}
  }
  for(j =2; j<=max ;j++)
  {
  var hotel =  $('.innerContent tr:nth-child('+j+')');
    margin = margin + 280;
    hotel.css('margin-left',margin+'px');
    //$('.line_wrapper').append(hotel);
  }

This just does not quite work as I would have expected. I want to add the divs in order for me to use bootstrap fluid layout.

A:

You can do it using each:
$('#mytable tr').each(function (i) {
    i%4?$(this).prev('div').append(this):$(this).wrap('
');
});


Q:

Precise measurement of time interval in CocoaTouch

I have a class which must have a property of some kind of timestamp, representing the moment of time when the instance of this class was created. And then when having multiple objects of this class I need to find the time interval between the creation of these objects.
And the usual interval is going to be up to 10 seconds, so I need precision of at least 1 second, but something like 0.1-0.001 second would be much better.
What is the best option to use for this property?
As far as I know, NSDate has precision up to 1 second.
I believe that I need something related to CFTimeInterval. I've used it for view animation with CADisplayLink. It provided the CFTimeInterval value for each moment of screen update and I could calculate the time interval between two CFTimeInterval's very easily.
But how do I assign the value to this CFTimeInterval at any moment of time?

A:

NSDate will work, as Matthias Bauch's comment indicates. You can also just use CFTimeIntervals though:
CFTimeInterval currentTime = CFAbsoluteTimeGetCurrent();

Do note that this function and NSDate are both based on an absolute reference date (Jan 1, 2000 in this case). This means that if the system's clock is changed while your app is running, values obtained before the clock change won't correctly compare to values obtained afterward.


Q:

Remove a confirm() dialog via javascript/jquery

In a javascript function, I do this for quick prototyping:
if(confirm("are you sure you want to do this")) {
  // do something
} else {
  // do something else
}

If I get a specific event over a websocket, I want to remove this dialog in javascript/jquery. Any ideas how to do that? Is there a DOM id or something for that? Extra-Points if not even the else-block is executed when removing the dialog :)

A:

You can't. All javascript execution is halted while a confirm, alert, or prompt is displayed.

Dialog boxes are modal windows - they prevent the user from accessing
  the rest of the program's interface until the dialog box is closed.
  For this reason, you should not overuse any function that creates a
  dialog box (or modal window).

https://developer.mozilla.org/en/DOM/window.confirm


Q:

number of 6 digit combination using M 0s and N 1s.

I have seen this question which lead me ask this following question.
What is the number of unique possibilities to generate a binary string that has M 0s and N 1s.?
For example,
If M=3, N=4, then possible combinations are
0001111
0101010
etc.

A:

I think this is equivalent to say, we have $M+N$ positions from where we choose $N$ positions to fill with $1$. The number of ways is clearly then
$$
\binom{M+N}{N} = {(M+N)! \over M! \cdot N!}
$$


Q:

PL/SQL to Select a Partition Window of Data

Working with Oracle 11g here.
I'm trying to figure out how to write a specific query against a sample table below:
 ID TYPE   PRIORITY    STATUS   DATE
 ----------------------------------------------------
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 2  R      B           NEW      01-OCT-2009
 2  R      B           NEW      01-OCT-2009
 2  R      B           NEW      01-OCT-2009
 2  R      B           NEW      01-OCT-2009
 3  R      A           NEW      01-OCT-2009
 3  Q      A           NEW      01-OCT-2009
 3  Q      A           NEW      01-OCT-2009

Here is the pseudo-PL/SQL of what I want the query to do:
 SELECT ID, TYPE
 FROM DATA_TABLE
 WHERE ROWNUM = 1 AND STATUS = 'NEW'
 GROUP BY ID, TYPE
 ORDER BY PRIORITY, DATE

I want to grab the next group of ID, TYPE that has a status NEW ordered by priority and date.
In the case above the statement should return either 1 Q or 3 Q, but not both, since they have the same priority and date. If 3 Q was set to STATUS='DONE' then the query should return 1 Q.
For the second step I'm going to join this data back in to the table to grab the rows for the set I want to process (eg: 1 Q). This doesn't have to be a two-step process; if I can grab the set of rows to process without the join that would be ideal.
I hope I'm just missing something really simple, but I'm open to using analytic functions for partitioning if need be.

A:

SELECT * FROM (SELECT ID, TYPE FROM DATA_TABLE WHERE STATUS = 'NEW' ORDER BY PRIORITY, DATE) WHERE ROWNUM = 1

That ought to work. You don't want to group by ID and TYPE because you're not actually trying to perform any sort of aggregation on the rows matching a given ID and TYPE. If you only cared about one column (say DATE) you could say
SELECT ID, TYPE FROM DATA_TABLE WHERE DATE = (SELECT MIN(DATE) FROM DATA_TABLE) AND ROWNUM = 1

and avoid sorting the whole table. But I don't see how to make that work here.


Q:

Trying to make flexbox tabbed content, and my tabs will not sit on top of the border from the content div below

I'm trying to make the bottom of the active tab (class=windowTabs 'a' element) overlap the border of class=windowContent like shown in this photo, the bottom of Tab #1:

No matter what I do, I can't get it to go on TOP of the white border on class=windowContent
Take a look at my pen: http://codepen.io/agm1984/pen/vyRoYy
The problem is right here in the code:

HTML

  London
  Paris
  Tokyo

London

London is the capital of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

CSS

 /* adamProperties Window Tabs */
.windowTabs {
  padding-top: 1.0em;
  flex: 0;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  height: 1.0em;
  min-height: 1.0em;
}
.windowTabs a {
  border-bottom: red;
}
.windowTabs a:after {
  border-bottom: medium solid black;
}
.windowTabs {
  margin: 10px;
  border-right: red;
}

/* adamProperties Window Content */
.windowContent {
  flex: 1;
  border-left: thin solid white;
  border-top: thin solid white;
  border-right: thin solid black;
  border-bottom: thin solid black;
}

If anyone ever searches this later from Google, just google the code from the city examples. You'll find the virgin example code.
I'm confused why I can't just put a 2px border on the bottom of the  element and make the z-index a larger number. According to my research, that should work when display: flex is on.
I also had a hard time trying to use to my advantage:

CSS

.windowTabs a:after {
  any kind of shifting wasnt applying any change
}

I can see the div with the white border is on top of the buttons. How can I make it go below my `a' tags or how can I force something on top of them. I am trying to make it as responsive as possible, so I havent been looking too close at crazy methods of positioning, margins, absolute values. I feel like something simple is interrupting or missing, and probably related to flexbox.
Just to be super clear, here is a photo in which I am pointing to the problematic white border (I intentionally set the height on class=windowTabs to accentuate the issue):

Any help would be greatly appreciated. Thanks.

A:

I'm not sure I've fully understood your question.  But I think a simple reason the window content div is not covering the tabs is because it has no background colour.
Try:
.windowContent {
  background-color: #C0C0C0;
}

Codepen: http://codepen.io/sol_b/pen/LbmPjm
Apologies if I've misunderstood your question!
EDIT: updated codepen: http://codepen.io/sol_b/pen/RoywKN


Q:

In R, how do I link parameter with set of values from JSON data?

The following JSON data
       "parameters": [
            {
                "parameterName": "IntervalToIgnoreDuringTransitions",
                "values": [
                    {
                        "createdByTimestamp": "2014-09-22T14:39:25.717Z",
                        "createdByUser": "tis",
                        "modifiedByUser": "",
                        "analyticParameterValueId": 502,
                        "analyticParameterNameId": 502,
                        "analyticParameterValue": "0"
                    }
                ]
            },
            {
                "parameterName": "DateRange",
                "values": [
                    {
                        "createdByTimestamp": "2014-09-22T14:38:25.297Z",
                        "createdByUser": "tis",
                        "modifiedByUser": "",
                        "analyticParameterValueId": 501,
                        "analyticParameterNameId": 501,
                        "analyticParameterValue": "12"
                    }
                ]
            }
        ]

creates the following data.frame structure in R
'data.frame':   2 obs. of  2 variables:
 $ parameterName: chr  "IntervalToIgnoreDuringTransitions" "DateRange"
 $ values       :List of 2
  ..$ :'data.frame':    1 obs. of  6 variables:
  .. ..$ createdByTimestamp      : chr "2014-09-22T14:39:25.717Z"
  .. ..$ createdByUser           : chr "tis"
  .. ..$ modifiedByUser          : chr ""
  .. ..$ analyticParameterValueId: int 502
  .. ..$ analyticParameterNameId : int 502
  .. ..$ analyticParameterValue  : chr "0"
  ..$ :'data.frame':    1 obs. of  6 variables:
  .. ..$ createdByTimestamp      : chr "2014-09-22T14:38:25.297Z"
  .. ..$ createdByUser           : chr "tis"
  .. ..$ modifiedByUser          : chr ""
  .. ..$ analyticParameterValueId: int 501
  .. ..$ analyticParameterNameId : int 501
  .. ..$ analyticParameterValue  : chr "12"

Is there anyway that simple way to link the parameterNames with their respective values?
For example, if the data.frame is called df, I'd like to use df$DateRange$analyticParameterValue to return "12".

A:

This should do it:
library(jsonlite)

tmp <- fromJSON('{"parameters": [
{
  "parameterName": "IntervalToIgnoreDuringTransitions",
  "values": [
{
  "createdByTimestamp": "2014-09-22T14:39:25.717Z",
  "createdByUser": "tis",
  "modifiedByUser": "",
  "analyticParameterValueId": 502,
  "analyticParameterNameId": 502,
  "analyticParameterValue": "0"
}
]
},
{
  "parameterName": "DateRange",
  "values": [
{
  "createdByTimestamp": "2014-09-22T14:38:25.297Z",
  "createdByUser": "tis",
  "modifiedByUser": "",
  "analyticParameterValueId": 501,
  "analyticParameterNameId": 501,
  "analyticParameterValue": "12"
}
]
}
]}')

dat <- tmp$parameters$values
names(dat) <- tmp$parameters$parameterName

dat$DateRange$analyticParameterValue
## [1] "12"


Q:

Printing a list justified with format

I just learned from this answer this answer I can use format with a list:
li = [2, 3, 5, 7, 11]
print '{0} {2} {1} {4}'.format(*li) # => 2 5 3 11

Now I want to justify every element of a list. What I'm doing is:
print "{0:>12}{1:>12}{2:>12}{3:>12}".format(*PROPERTIES)

However, this isn't really convenient as the list may get larger. I am curious is this possible by using only print and format (no loops)?

A:

li = [2, 3, 5, 7, 11]
print ('{:>12}'*len(li)).format(*li)
        2           3           5           7          11


Q:

How can I allocate a piece of memory from a certain physical memory in embedded arm processor?

I am using zynq device, trying to transfer data from DRAM to the peripheral of ARM by a piece of standalone program (without OS). In the example code, I found this code to statement the source address and destination address of the transaction.
volatile static u8 SrcBuffer[BUFFER_BYTESIZE] __attribute__ ((aligned (64)));
volatile static u8 DestBuffer[BUFFER_BYTESIZE] __attribute__ ((aligned (64)));

Since there's no OS, what's the value of address from? How can I change it?

A:

You need to define a section a in the linker file and then place the data in it using (for GCC):
__attribute__ (( section ( "your_section" ) ) )
In the linker file (will have other stuff in it already as well) something like:
MEMORY
{
   ....will be other stuff here
   ....
   YOUR_MEMORY_NAME : ORIGIN = 0xWhatever, Length = a_length // Creates a memory region
}

SECTIONS
{
   ...
   ...

   .something_data :
   {
      *(your_data)
   } > YOUR_MEMORY_NAME

   ...

}


Q:

Concatenating Strings: "Multiplication" of two list of strings

For list of strings,
define the multiplication operation in as concatenating here:
l1 = ['aa', 'bb', 'cc']
l2 = ['11', '22']
l3 = l1 op l2

Expected output:
l3 = ['aa11', 'aa22', 'bb11', 'bb22', 'cc11', 'cc22']

Simply we can use
for l in l1:
    for ll in l2:
        l3.append(l+ll)

But I'd be grateful to hear a pythonic solution.

A:

from itertools import product

l1 = ['aa', 'bb', 'cc']
l2 = ['11', '22']

l3 = [x+y for (x,y) in product(l1,l2)]

print(l3)

But it's effectively the same thing as what you're doing (provided you fix the typo :P)


Q:

command to conditionally add character at line beginning

in vim, I need to add * at the beginning of lines that starts with
XMMN2@xxxxx

where xxxxx means number ranging from 200 to 400
what I've been using (compromised solution) is
:g/^XMMN2@2\d\d/d
:g/^XMMN2@3\d\d/d

it would be really beneficial if they can be commented out (instead of being deleted)
Thanks!

A:

I would do
:g/your pattern/s/^/*/

Or equivalently
:%s/^your pattern/*&/


Q:

IsAfter Usage of Local Date Time In JAVA

I am facing the issue with localDateTime in JAVA.
I am using the isAfter function to compare the two date time but only returns correct value if there was a variation in time but not the date.
Program:
import java.time.LocalDateTime;

public class LocalDatTimeVerificaiton {

    public static void main(String[] args) throws Exception {

        LocalDateTime dateTime=LocalDateTime.now();
        System.out.println(dateTime);
        Thread.sleep(10000);
        LocalDateTime dateTime1=LocalDateTime.now();
        System.out.println(dateTime1);
        if(dateTime1.isAfter(dateTime)){
            System.out.println(dateTime+" After "+dateTime1);
        }

        if(dateTime1.isAfter(dateTime)){
            System.out.println(dateTime1+" After "+dateTime);
        }else{
            System.out.println(dateTime1+" Not After "+dateTime);
        }

    }
}

Output
Actual
2017-08-11T18:32:00.466
2017-08-11T18:32:10.467
2017-08-11T18:32:00.466 After 2017-08-11T18:32:10.467
2017-08-11T18:32:10.467 After 2017-08-11T18:32:00.466

Expected
2017-08-11T18:32:00.466
2017-08-11T18:32:10.467
2017-08-11T18:32:00.466 After 2017-08-11T18:32:10.467
2017-08-11T18:32:10.467 Not After 2017-08-11T18:32:00.466

Is this the expected behavior or is am I missing something?

A:

Why do you expect 18:32:10 to be before 18:32:00?
You may be misled by a typo in your code:
if (dateTime1.isAfter(dateTime)) {
  System.out.println(dateTime + " After " + dateTime1);
                            ^^^                   ^^^
}

Should probably be:
if (dateTime1.isAfter(dateTime)) {
  System.out.println(dateTime1 + " After " + dateTime);
                            ^^^                    ^^^
}


Q:

Dynkin's Theorem and expectation

Suppose I have the following SDE.
$dX_t=-k\cdot X_tdt+\sigma\sqrt{X_t}dB_t$
If I want to find a bound at any $t$ ofthe expectation of $X_t^2$, given $X_0=0$, is it legitimate to do the following? I use Dynkin's Theorem.
$\mathbb{E}^x\left(X_t^2 \right)=x+\mathbb{E}^x\int_0^t\left( -2k+\sigma^2\right)X_s^2+\sigma^2ds$
Then I take the expectation inside the integral by Fubini's Theorem and conclude that the integral is bounded for $-2k+\sigma^2<0$ .

A:

I think you missed to transfer the square root in the diffusion term. By Ito,
$$
d(X_t^2)=2X_tdX_t + d\langle X_t\rangle = [-2kX_t^2\,dt + 2σX_t^{3/2}\,dB_t] + σ^2X_t\,dt\tag1
$$
so that under expectations
$\newcommand{\E}{\mathbb E^x}$
$$
d\E(X_t^2)=-2k\E(X_t^2)\,dt + σ^2\E(X_t)\,dt.\tag2
$$
We need to compute the expectation formula of $X_t$ first,
$$
d\E(X_t)=-k\E(X_t)\,dt\implies \E(X_t)=xe^{-kt}.\tag3
$$
By using the integrating factor $e^{2kt}$ in the first order ODE (2) we get to
$$
e^{2kt}\E(X_t^2)=\frac{σ^2x}{k}(e^{kt}-1)\implies \E(X_t^2)=\frac{σ^2x}{k}e^{-kt}(1-e^{-kt})
$$
All this under the assumption that $X_t>0$ for all $t>0$.


Q:

provide a link to download file

I am using python flask. I want to provide a url in template which varies in filename.
Folder structure:
project_folder/download/pdf <-images in this folder
url_for('download/pdf/filenameXYZ.pdf') didnt worked.

A:

If you want to return static content you should tell Flask that you want static content :)
As you can see in this example: http://flask.pocoo.org/docs/patterns/jquery/?highlight=static
You need something like this:
url_for('static', filename='download/pdf/filenameXYZ.pdf')


Q:

PHP Undefined variable $_LIT["something"]

In my config.php, I have this array:
$_LIT = array(
    /* Адрес сайта */
    "url" => "http://learnit.loc/", // Адрес сайта
....
);

The problem is, that I cant use this array in code below:
For example, I have a mail-method and I have to put $_LIT["url"] in my special link variable.:
function testMethod($username, $email) {
$link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";
}

And... I cant use it ($_LIT["url"]). It just put nothing, where the site url should be.
What I can also say, that I use my config.php in my ohter .php files using "require_once" "config.php". So I can get $_LIT["something"] there, but not directly in confing.php. Why?
Thanks for every help.

A:

The variables that are outside of functions scope cannot be accessed directly.
You need to use the keyword global inside function.
like  global $_LIT
$link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";

Link to Documentation.
http://php.net/manual/en/language.variables.scope.php
---- update----
function testMethod($username, $email) {
    global $_LIT;

     $link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";
}


Q:

Techniques for forming square factorizations

Say you have the polynomial
$$ x^4 + 2 + x^{-4} $$
Looking at it, you see you can do
$$\begin{align*}
x^4 + 1 + 1 + x^{-4} & =x^2( x^2 + x^{-2} ) + x^{-2}( x^2 + x^{-2} )\\
&= \left( x^2 + x^{-2} \right)^2.
\end{align*}$$
Another one is
$$\begin{align*}
 x^2 + \frac{1}{2} + \frac{1}{16x^2} &=
 x^2 + \frac{1}{4} + \frac{1}{4} + \frac{1}{16x^2} \\
&=x^2\left( 1 + \frac{1}{4x^2} \right) + \frac{1}{4}\left( 1 + \frac{1}{4x^2} \right)\\
&=\left( x^2 + \frac{1}{4}\right) \left( 1 + \frac{1}{4x^2} \right)\\
 (x^2) \left( 1 + \frac{1}{4x^2} \right)^2.
\end{align*}$$
So the question is, I've been doing this by "inspection" - are there any techniques for recognizing when this type of factorization is possible or how to do more easily?

A:

For trinomials:

If you have $(p(x))^2 + K + (q(x))^2$, then check to see if $K = \pm 2p(x)q(x)$. if so, then $(p(x))^2 + K + (q(x))^2 = (p(x)\pm q(x))^2$.

In your first example, you have
$$x^4 + 2 + x^{-4} = (x^2)^2 + 2 + (x^{-2})^2.$$
Taking $p(x) = x^2$, $q(x) = x^{-2}$, we have $2p(x)q(x) = 2$, which is precisely the middle term, so $x^2+2+x^{-4} = (x^2 + x^{-2})^2$.
In your second example, you have
$$x^2 + \frac{1}{2} + \frac{1}{16x^2} = (x)^2 + \frac{1}{2} + \left(\frac{1}{4x}\right)^2.$$
Taking $p(x) = x$ and $q(x) = \frac{1}{4x}$, you have $2p(x)q(x) = \frac{2x}{4x} = \frac{1}{2}$, again exactly the middle term, so you get
$$x^2 + \frac{1}{2} + \frac{1}{16x^2} = \left(x + \frac{1}{4x}\right)^2.$$

More generally, if you have $(p(x))^2 + Kp(x) + L$, then see if you can find two expressions, $s(x)$ and $t(x)$, which when multiplied give $L$ and when added give $K$, $s(x)t(x) = L$, $s(x)+t(x) = K$. Then $(p(x))^2 + Kp(x) +L = (p(x)+s(t))(p(x)+t(x))$.

For example,
$$2x^4 + (\sqrt{2}-1)x^2 + x.$$
You may notice that the leading term is $(\sqrt{2}x^2)^2$, and that you have a "middle term" of $\sqrt{2}x^2$. So rewriting a bit you get
$$(\sqrt{2}x^2)^2 + (\sqrt{2}x^2)1 + (x-x^2).$$
This suggests looking for $s(x)$ and $t(x)$ with $s(x)+t(x) = 1$ and $s(x)t(x)=x-x^2 = x(1-x)$. This in turn quickly suggests $s(x) = x$ and $t(x)=1-x$, which gives
$$2x^4 + (\sqrt{2}-1)x^2 + x = \left(\sqrt{2}x^2 + x\right)\left(\sqrt{2}x^2 + (1-x)\right).$$

But generally, there is some substantial amount of "inspect and notice" going on. The more of these you do, the more you will notice patterns and be able to "notice" the things that one needs to notice.


Q:

Transactions within orphaned blocks

Scenario:
You are running a bitcoind node and listening to the incoming blocks/transactions.  You receive TX 1 which is put into your mempool.  Block A is mined, and includes TX 1, which is subsequently removed from your mempool.  Blocks B and C are mined, orphaning Block A.  Neither Block B, nor C include TX 1, so it is put back into the mempool to be included in a new Block
Question:
How exactly does the node find out that it needs to include TX1 in the mempool again?  Is TX 1 broadcast and received in the same way as when it was first broadcast to the node?  Or in other words, if I'm listening for receiving incoming blocks/transactions, will it be relayed to me a second time or does the client "know" just to put it back in the mempool?
Let me know if any of my understanding is incorrect or if you need any more clarification!

A:

Bitcoin Core includes code which rolls back a block from the chain when it is orphaned.  All transactions from that block are checked against the new best block chain to see if they've already been added to a block or if they spend the same input as a transaction already added to a block; if they aren't---meaning they're valid transactions on the new best block chain---they're re-added to the memory pool.
The re-added transactions will not be automatically rebroadcast like a newly-received transaction, but if a remote peer sends the mempool message to the local peer, the local peer will tell the remote peer about the transaction (using a standard inventory).


Q:

Pegar nome da coluna com chave estrangeira

Tenho uma tabela produtos que faz referência ao id da tabela categorias, mas não quero pegar o número id da tabela estrangeira, e sim o nome dessa referência.
Meu controlador está assim:
public function index()
{
    $prod = Produto::all();
    return view('produtos', compact('prod'));
}

Dai na minha view eu chamo o nome da categoria_id mas só recebo o número do ID.
@foreach ($prod as $p)

    {{$p->id}}
    {{$p->nome}}
    {{$p->estoque}}
    {{$p->preco}}
    {{$p->categoria_id}}

@endforeach

Como faço para retornar o nome da categoria que faz referência ao id da tabela produtos?

A:

O que falta realmente colocar na sua pergunta são as relações de suas duas tabelas, e também os Models que são configuradas para essas tabelas, onde um Produto tem Categoria e uma Categoria está em vários Produto, ou seja, um relacionamento 1:N. Um exemplo fictio sobre uma tabela de produtos e uma tabela de categorias onde as duas se relacionam, exemplo:

Classes:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Produto extends Model
{
    protected $table = 'produtos';
    protected $fillable = ['categoria_id','descricao'];

    public function categoria()
    {
        return $this->belongsTo(App\Categoria::class,'categoria_id','id');
    }
}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Categoria extends Model
{
    protected $table = 'categorias';
    protected $fillable = ['nome'];

    public function produtos()
    {
        return $this->hasMany(App\Produto::class,'categoria_id','id');
    }
}

Como utilizar:
public function index()
{
    $prod = Produto::with('categoria')->get();
    return view('produtos', compact('prod'));
}

@foreach ($prod as $p)

    {{$p->id}}
    {{$p->descricao}}
    {{$p->categoria->nome}}

@endforeach

Nesse exemplo tem vários pontos importantes:

Criar relação das entidades sendo explicito as chaves (se seguir a nomenclaturas de nomes não precisa colocar, mas, é um boa conduta colocar principalmente para manutenção)
Carregar a relação adianta (comando with('categoria')), porque, existe a otimização de somente 2 consultas SQL diferente da outra que a cada interação e feita uma nova consulta SQL causando lentidão e um erro muito comum no desenvolvimento com Laravel.

Ref.

Como usar o relacionamento hasmany no laravel 5.2?
Salvar relacionamento 1:1 no Laravel 5.3
Como usar o relacionamento hasmany no laravel 5.2?
Laravel / Eloquent - Consulta em mais de uma tabela


Q:

Chebyshev-like polynomials with integral roots

Chebyshev polynomials have real roots and satisfy a recurrence relation. I was wondering if one can find a sequence of polynomials with integral or rational roots with similar properties. More precisely, one is looking for a sequence of polynomials $(f_n),f_n\in\mathbf{Q}[t]$ such that

$\deg f_n\to\infty$ as $n\to\infty$;
$\sum_{n=0}^\infty f_n(t) x^n$ is (the Taylor series of) a rational function $F$ in $x$ and $t$.
All roots of any $f_n$ are integer and have multiplicity 1. (A weaker version: the roots are allowed to be rational and are allowed to have multiplicity $>1$ but there should be an $a>0$ such that the number of distinct roots of $f_n$ is at least $a\deg f_n$.)

A:

I can satisfy conditions 1, 3 and almost satisfy condition 2.  Letting $f_n(t) = {t+n-1 \choose n}$ we have the well-known generating function
$\displaystyle \sum_{n \ge 0} f_n(t) x^n = \frac{1}{(1 - x)^{-t}}$
which is rational in $x$ for any fixed integer value of $t$.  I think condition 2 will end up being the hardest to satisfy because rational functions are quite rigid.

Edit 1:  My current opinion is that the conditions are not satisfiable.  Based on the analogous situation with linear homogeneous recurrences on the integers I am going to conjecture that any polynomial sequence which obeys a polynomial linear recurrence and is not essentially a geometric series has terms divisible by irreducible polynomials of arbitrarily high order.
Edit 2:  A very strong result available in the integer case is Zsigmondy's theorem, but we don't need a result this strong.  Here's a nice result in the integer case.  Suppose an integer sequence $a_n$ satisfies a linear homogeneous recurrence with integer coefficients, and let $p$ be a prime not dividing those coefficients.  Then the sequence $a_n \bmod p$ is periodic (not just eventually periodic) $\bmod p$ by Pigeonhole.  If in addition there exists $n$ such that $a_n = 0$ and $a_n$ is unbounded, then it follows that there is a nonzero term of the sequence divisible by $p$.  For example, this is true of the Fibonacci sequence; in fact we have the much stronger result that for $p > 5$, either $p | F_{p+1}$ or $p | F_{p-1}$.
My guess is that a result like this holds in the polynomial case with $p$ replaced by a monic irreducible polynomial (say, of degree $2$), although the argument above breaks down as written.

A:

Here's one thought.  For each integer k, f_n(k) satisfies a recurrence relation.  If the roots of f_n are all integers, then f_n(k) and f_n(k+1) have to be "in sync" in the sense that they never have opposite sign.  This is a strong condition!  For instance, suppose the sequences f_n(k) and f_n(k+1) each have unique largest eigenvalue:  then these eigenvalues would have to have the same argument.
Update:  Qiaochu's answer suggests that in fact working mod p would be just better than the "archimedean" picture sketched above, since it is really F_q[t], not Z[t] or Q[t], that is analogous to the integers.  Let F_n(t) be the reduction of f_n(t) to F_p[t].  If f_n(t) has all roots rational for every n, then the reduction of f_n(t) mod p has the same property.  But now we are saying something quite strong; that f_n(t) lies in a finitely generated subgroup of F_q(t)^*!  This is presumably ruled out by Mason's theorem (ABC for function fields.)  Indeed, you could probably prove in this way that not only are the roots of f_n(t) not rational, but f_n(t) has irreducible factors of arbitrarily large degree.
I don't think this approach would touch a harder question along the same lines like this one.


Q:

Add missing members to a table from other table SQL Server

i have 2 tables:
First table is [Table_Time]:
Month Number    Week Number
------------    -----------
1               01
1               02
1               03
1               04
2               05
2               06
2               07
2               08
3               09
3               10
3               11
3               12

The second table is [Sales]:
Product         Store           Month Number    Week Number
------------    -----------     ------------    -----------
P1              ST1             1               03
P1              ST1             1               04
P1              ST1             2               05
P1              ST1             3               09
P1              ST1             3               11
P1              ST1             3               12

My question is:
How to add missing weeks to the table [Sales]?
My expected result should be:
Product         Store           Month Number    Week Number
------------    -----------     ------------    -----------
P1              ST1             1               01
P1              ST1             1               02
P1              ST1             1               03
P1              ST1             1               04
P1              ST1             2               05
P1              ST1             2               06
P1              ST1             2               07
P1              ST1             2               08
P1              ST1             3               09
P1              ST1             3               10
P1              ST1             3               11
P1              ST1             3               12

Thanks in advance!

A:

Here's a way of doing it, you need to create a cartesian product between your products and dates. Using EXCEPT you can only bring the needed values so you can insert them in your Sales table.
WITH AllProducts AS( --This can be avoided if you already have a list of them outside of Sales
    SELECT DISTINCT Product, Store
    FROM Sales
)
SELECT p.Product,
       p.Store,
       t.MonthNumber,
       t.WeekNumber
FROM AllProducts p
CROSS JOIN Table_Time t
EXCEPT
SELECT s.Product,
       s.Store,
       s.MonthNumber,
       s.WeekNumber
FROM Sales s;


Q:

Guidance choosing tools for developing cross-platform mobile app

I have no mobile application development experience, I don't even own a rich mobile device (I can send text messages with my cellphone :) I have strong web, .NET, and Java experience but am open to develop with any language / platform. I need to target at least iPhone, Android, and Blackberry devices. I am seeking some guidance on the right set of tools for developing an application targeting these devices given my requirement. An easy deployment model would be a big plus. I have some notion of the difference between native apps and mobile apps on devices, and the later seems like it may be a good choice in terms of cross-platform support and easy deployment, but I do need access to some device information.
I currently have a fairly simple Java Swing application which is backed by JSON web services. The application is launched automatically when a user logs into their computer via a login script (it's deployed on corporate-like network). The user is presented with some html formatted information, and they click a button to answer a question. That's about it!
Core Requirements

Must be able to get user identification information from the mobile device and send it to the server; the Swing client sends the Windows account and domain name.
Would very much like to retrieve the local date and time of the mobile device and send it to the server
Must be able to have the GUI workflow described previously: present content to user, user "clicks" a button to respond.
Must be able to communicate with the JSON web service; if needed, could use some other data encoding, but just need to be able to communicate over HTTP (unless things are very different in the mobile world and I don't know what I'm talking about!)

Nice to Have Requirements

Render HTML fragments for the content (if not possible, could strip it down to plain text)
Be able to "click" on a link to send an email someway for help / feedback
"Click" link to a web site with information on how well the user is responding to their questions; could also build this into the app if it is a mobile app.
Be able to build some kind of user options "dialog"
Render small pictures along with the content; currently the pictures are just http resources.

Thanks in advance!

A:

It looks like your needs are pretty limited in terms of access to the device itself. I would suggest one of the cross-platform, web-ish platforms. There's a couple of them out there, such as PhoneGap http://www.phonegap.com/.
See http://mashable.com/2010/08/11/cross-platform-mobile-development-tools/ for some other options, and to make sure it supports the platforms you require.


Q:

What does "rect1 += rect2" mean in Swift?

Is this the same as UnionRects(rect1, rect2)? I'm trying to translate some Swift code to Objective C. I can't find this in the references or Googling.
After looking at this again, I think I see my problem. It's an array of rects, not a rect. Apparently, the "+=" is for the array.
This is straight out of Apple's sample code for Photos:
fileprivate func differencesBetweenRects(_ old: CGRect, _ new: CGRect) -> (added: [CGRect], removed: [CGRect]) {
        if old.intersects(new) {
            var added = [CGRect]()
            if new.maxY > old.maxY {
                added += [CGRect(x: new.origin.x, y: old.maxY, width: new.width, height: new.maxY - old.maxY)]
            }
...
}

A:

The edited question makes it clear that you're asking about using += on two Arrays. This appends the contents of the right array to the left array, as you'd imagine. It's described in the docs under "Accessing and Modifying an Array".
Below is my original answer, preserved for anyone who stumbles onto this question looking for += between CGRects.

If rect1 and rect2 are CGRect rectangles, then rect1 += rect2 is invalid in standard Swift.
If you see this in working code, it means that they overloaded the += compound assignment operator (see documentation) to accept CGRects and perform their own custom function. The only way to know what that does is to find it in the code.
Here's what the code looks like to overload += with a function that unions the CGRects:
func += (left: inout CGRect, right: CGRect) {
    left = left.union(right)
}

If you search your codebase for "inout CGRect" and various permutations thereof, you'll probably turn up the code responsible, which will help a lot in figuring out what it does.


Q:

Bash convention for if ; then

From this web page :
http://tldp.org/LDP/abs/html/abs-guide.html
It's mentioned the usage of the if bracket then convention which need a space after the semicolon :

;
Command separator [semicolon]. Permits putting two or more commands on the same line.

echo hello; echo there

if [ -x "$filename" ]; then    #  Note the space after the semicolon.
#+                   ^^
  echo "File $filename exists."; cp $filename $filename.bak
else   #                       ^^
  echo "File $filename not found."; touch $filename
fi; echo "File test complete."

Note that the ";" sometimes needs to be escaped.

Does anyone know where is this coming from and if this is needed at all by certain shells?

A:

This has become the style in the last few years:
if [ -x "$filename" ]; then
   echo "hi"
fi

However, back when dinosaurs like Burroughs and Sperry Rand ruled the earth, I learned to write if statements like this:
if [ -x "$filename" ]
then
    echo "hi"
fi

Then, you don't even need a semicolon.
The new style with then on the same line as the if started in order to emulate the way C and other programming languages did their if statements:
if (! strcmp("foo", "bar")) {
   printf "Strings equal\n";
}

These programming languages put the opening curly brace on the same line as the if.

A:

Semicolon ; is an operator (not a keyword, like braces { }or a bang !) in Shell, so it doesn't need to be delimited with white space to be recognized in any POSIX-compliant shell.
However, doing so improves readability (for my taste).
Semicolon needs to be escaped if you mean a symbol "semicolon", not an operator.


Q:

What is the advantage of linspace over the colon ":" operator?

Is there some advantage of writing
t = linspace(0,20,21)

over
t = 0:1:20

?
I understand the former produces a vector, as the first does.
Can anyone state me some situation where linspace is useful over t = 0:1:20?

A:

It's not just the usability. Though the documentation says:

The linspace function generates linearly spaced vectors. It is
  similar to the colon operator :, but gives direct control over the
  number of points.

it is the same, the main difference and advantage of linspace is that it generates a vector of integers with the desired length (or default 100) and scales it afterwards to the desired range. The : colon creates the vector directly by increments.
Imagine you need to define bin edges for a histogram. And especially you need the certain bin edge 0.35 to be exactly on it's right place:
edges = [0.05:0.10:.55];
X = edges == 0.35

edges =   0.0500    0.1500    0.2500    0.3500    0.4500    0.5500
X =  0     0     0     0     0     0

does not define the right bin edge, but:
edges = linspace(0.05,0.55,6);   %// 6 = (0.55-0.05)/0.1+1
X = edges == 0.35

edges =   0.0500    0.1500    0.2500    0.3500    0.4500    0.5500
X =  0     0     0     1     0     0

does.
Well, it's basically a floating point issue. Which can be avoided by linspace, as a single division of an integer is not that delicate, like the cumulative sum of floting point numbers. But as Mark Dickinson pointed out in the comments:
You shouldn't rely on any of the computed values being exactly what you expect. That is not what linspace is for. In my opinion it's a matter of how likely you will get floating point issues and how much you can reduce the probabilty for them or how small can you set the tolerances. Using linspace can reduce the probability of occurance of these issues, it's not a security.
That's the code of linspace:
n1 = n-1
c = (d2 - d1).*(n1-1) % opposite signs may cause overflow
if isinf(c)
    y = d1 + (d2/n1).*(0:n1) - (d1/n1).*(0:n1)
else
    y = d1 + (0:n1).*(d2 - d1)/n1
end

To sum up: linspace and colon are reliable at doing different tasks. linspace tries to ensure (as the name suggests) linear spacing, whereas colon tries to ensure symmetry
In your special case, as you create a vector of integers, there is no advantage of linspace (apart from usability), but when it comes to floating point delicate tasks, there may is.
The answer of Sam Roberts provides some additional information and clarifies further things, including some statements of MathWorks regarding the colon operator.

A:

linspace and the colon operator do different things.
linspace creates a vector of integers of the specified length, and then scales it down to the specified interval with a division. In this way it ensures that the output vector is as linearly spaced as possible.
The colon operator adds increments to the starting point, and subtracts decrements from the end point to reach a middle point. In this way, it ensures that the output vector is as symmetric as possible.
The two methods thus have different aims, and will often give very slightly different answers, e.g.
>> a = 0:pi/1000:10*pi;
>> b = linspace(0,10*pi,10001);
>> all(a==b)
ans =
     0
>> max(a-b)
ans =
   3.5527e-15

In practice, however, the differences will often have little impact unless you are interested in tiny numerical details. I find linspace more convenient when the number of gaps is easy to express, whereas I find the colon operator more convenient when the increment is easy to express.
See this MathWorks technical note for more detail on the algorithm behind the colon operator. For more detail on linspace, you can just type edit linspace to see exactly what it does.

A:

linspace is useful where you know the number of elements you want rather than the size of the "step" between them. So if I said make a vector with 360 elements between 0 and 2*pi as a contrived example it's either going to be
linspace(0, 2*pi, 360)

or if you just had the colon operator you would have to manually calculate the step size:
0:(2*pi - 0)/(360-1):2*pi

linspace is just more convenient
For a simple real world application, see this answer where linspace is helpful in creating a custom colour map


Q:

openGL FBO copy to texture results in black/dark image

In my program it is necessary for me to do off-screen rendering. For that purpose I use a FBO. In order to see if the image I draw is the correct for testing purposes I copy it from the FBO to a texture then render the texture to a quad. The problem is that when I copy from the FBO into the texture and render it the image appears dark/get a black color but the shapes are correct. I have tried using a texture as attachment in the FBO and rendering it directly (without copying it into another texture) and the colors are correct.
Below is the code for texture creation
//initial texture which works when rendered to a quad
glGenTexturesEXT(3, &textureID[0]);
glBindTextureEXT(GL_TEXTURE_2D, textureID[0]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 600, 512, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
//second one which should be a copy of the above but has tha dark color mentioned
glBindTextureEXT(GL_TEXTURE_2D, textureID[1]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); // automatic mipmap
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 600, 512, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTextureEXT(GL_TEXTURE_2D, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,GL_COLOR_ATTACHMENT0_EXT,GL_TEXTURE_2D,textureID[0],0);
  //Attach depth buffer to FBO
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb);
st1=glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);

Now in the rendering function
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb); //biding FBO
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
 //render code
unsigned char *pixels= new unsigned char [600*512*4];
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0);  //unbiding
glBindTextureEXT(GL_TEXTURE_2D,textureID[1]); //if I change to textureID[0] result is fine
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA8,600,512,0,GL_RGBA,GL_UNSIGNED_BYTE,pixels);
glBindTextureEXT(GL_TEXTURE_2D,0);
glViewport(0, 0, 600, 512);
glClearColor(1.0,1.0,1.0,1.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glBindTextureEXT(GL_TEXTURE_2D, textureID[1]);
  //setting the correct matrixes + render a quad
 //before rendering a quad I set the color with
glColor3f(1.0, 1.0, 1.0);
delete[] pixels;
glutSwapBuffers();

I'm using glut for the setup. I have tried other functions such as glGetTexImage2D after unbiding the FBO and biding the texture  as an alternative to  glReadPixels(...) but with no success.

A:

I don't understand this call to glTexImage2D in your second code snippet. pixels will contain just garbage. What do you expect it to do?

Textures have been core OpenGL for a very, very long time. It's just glGenTextures and glBindTexture not ...EXT. Also I recommend to either use ...ARB versions of the FBO functionality, or just using OpenGL core framebuffer support (of later OpenGL versions).