Q:

parar un setinterval al presionar un botón

estoy tratando de parar este contador al hacer click en el boton stop, sin embargo no se como limpiar el intervalo ya que esta dentro de la funcion timer.
Gracias por la ayuda

 var stop = document.getElementById("stop");

              var seconds = 0;
              var minutes = 0
              var hours = 0;
            function timer(){
                let counting = setInterval(function(){
                    if(seconds == 60){
                        minutes++
                        console.log(minutes);
                        seconds = 0;
                        if(minutes == 60){
                            minutes = 00;
                            hours++
                            console.log(hours);
                        }
                    }
                    seconds++;
                    console.log(seconds);

                    }, 1000);
            }

            timer();

   stop.addEventListener("click", function(){
      clearInterval(counting);
   });
<button id="stop">Stop</button>

A:

Se te ha olvidado que let tiene un ambito de tipo bloque, en pocas palabras, solo existe dentro de tu función timer por que ahí la declaras, pero no fuera de ahí.
Para solucionarlo solo debes inicializar tu variable por fuera de la función y dentro de esta setear el setInterval:

var stop = document.getElementById("stop");

              var seconds = 0;
              var minutes = 0
              var hours = 0;
              //Declaramos a counting afuera...
              let counting;
            function timer(){
                counting = setInterval(function(){
                    if(seconds == 60){
                        minutes++
                        console.log(minutes);
                        seconds = 0;
                        if(minutes == 60){
                            minutes = 00;
                            hours++
                            console.log(hours);
                        }
                    }
                    seconds++;
                    console.log(seconds);

                    }, 1000);
            }

            timer();

   stop.addEventListener("click", function(){
      clearInterval(counting);
   });
<button id="stop">Stop</button>

Recordemos que var crea una referencia global que puede ser usada en cualquier parte siempre y cuando el código que la use haga uso de ella cuando esta ya este creada.
Mientras que let y const solo existiran dentro del bloque donde las hayas definido, donde un bloque consiste en cualquier cosa que este delimitada por llaves {}.


Q:

Default value for dropdown option in Yii

I have the dropdown option in Yii like this
<?php echo $form->dropdownList($students,'student_name', CHtml::listData(Students::model()->findAll(), 'student_name', 'student_name'), array('selected'=>'Choose One')); ?>

Which html output is something like this
<select selected="selected" name="Students[student_name]" id="Students_student_name">
<option value="Alex">Alex</option>
<option value="John">John</option>
<option value="Johny">Johny</option>
<option value="" selected="selected"></option>
</select>

But I want the Select One should be the default selected value for the dropdown options.So that by default there will be Select One when no option is selected.
[UPDATE]
It is taking Select One as a option when I tried array('prompt'=>'Choose One') and array('empty'=>'Choose One') also.

A:

I think you're using the wrong key for the default selected value.
Try:
// array('prompt'=>'Choose One')
echo $form->dropdownList($students,'student_name', CHtml::listData(Students::model()->findAll(), 'student_name', 'student_name'), array('prompt'=>'Choose One')); ?>


Q:

Why does light behave like a wave?

When discussing a single or double slit experiment, where light is shined through a very small slit, it is often compared to a water wave going through a similar, if larger, slit. It's my understanding that when a ripple hits a wall with a hole in it the reason the ripple "bends" and spreads out is because of internal attraction between the water molecules, which are polar. So the molecules on the far side of the slit with energy will pull on the ones without and create a diffraction pattern; and I believe that a similar argument could be made for sound waves, that the molecules the wave travels through are at least slightly polar, or at least they have mass and momentum, so they will push/pull each other and create a diffraction pattern . But as far as I know light exhibits none of these properties, So what property of light allows it to diffract? Shouldn't light which passes through the slit be completely unaffected by the light which hits the material?
Clearly light sometimes behaves like a physical wave; but I was wondering if this physical behavior can be explained with some intrinsic property of light. Similar to how a wave travelling through a physical medium can be explained with different attractive forces and momentum.

A:

Your question is a fantastic one!  It shows that you are inquisitive and unwilling to take a book's word for it.
To address your question, we could just as well ask the question like this:

In order for a wave to propagate, there either has to be some
  restoring force, or there has to be a way for one "unit" of the wave
  to push or pull on the next unit of the wave.  What force or
  phenomenon allows one "unit" of an electromagnetic wave to pull or
  push on the next "unit" of the wave such that an E/M wave can
  propagate through space, and do all of those "wave things" like diffraction?

The answer to this is that:
a.) a changing electric field gives rise to a magnetic field.
b.) a changing magnetic field give rise to an electric field.
Each of these, acting in turn, is an electromagnetic wave.  Oscillating "units" of the e/m wave give rise to other oscillating units of the wave through electromagnetic induction.  All wave behavior, including refraction and diffraction, follow from this.


Q:

DataGrid in WPF using VisualStudio C#

I have 3 TexBoxes,Buttons and DataGrid in my window. when I enter the data into the TextBox and click on the button it should add into the DataGrid .I need a code for how to add, delete and get data. I'm new to wpf please help me with the code.
This is my Xaml code
  <Window x:Class="simpledatagrid.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="IDDATA" Height="350" Width="525">
<Grid  >
    <DataGrid BorderBrush="Black" BorderThickness="2" AutoGenerateColumns="True" Name="dgsample" Margin="200,10,10,75"></DataGrid>

    <Label  Content="ID :" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="26" Width="27"/>
    <Label  Content="Name :" HorizontalAlignment="Left" Margin="10,60,0,0" VerticalAlignment="Top" Height="26" Width="48"/>
    <Label  Content="Salary :" HorizontalAlignment="Left" Margin="10,110,0,0" VerticalAlignment="Top" Height="26" Width="47"/>

    <TextBox Name="tb1" HorizontalAlignment="Left" Height="20" Margin="60,10,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>
    <TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>
    <TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>

    <Button Content="Get" HorizontalAlignment="Left" Margin="10,190,0,0" VerticalAlignment="Top" Width="75" Click="Get_Click" />
    <Button Content="Add" HorizontalAlignment="Left" Margin="10,230,0,0" VerticalAlignment="Top" Width="75" Click="Add_Click" />
    <Button Content="Delete" HorizontalAlignment="Left" Margin="10,270,0,0" VerticalAlignment="Top" Width="75" Click="Delete_Click" />
</Grid>

This is my .cs code
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
         List<User> users = new List<User>();
                    users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
                    users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
                    users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });

                    dgsample.ItemsSource = users;
            }

    private void Get_Click(object sender, RoutedEventArgs e)
    {

    }

    private void Add_Click(object sender, RoutedEventArgs e)
    {

    }

    private void Delete_Click(object sender, RoutedEventArgs e)
    {

    }
    }
}

A:

first , you can use ObservableCollection instead of List. because ObservableCollection has INotifyCollectionChanged defaultly. ObservableCollection is TwoWayBinding.
ObservableCollection<User> users = new  ObservableCollection<User>();
public MainWindow()
{
    InitializeComponent();

                users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
                users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
                users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });

                dgsample.ItemsSource = users;
}

private void Get_Click(object sender, RoutedEventArgs e)
{
     if (this.tb1.Text != string.Empty) { User currentUser = users.Single(select => select.Id == Int32.Parse(this.tb1.Text)); this.tb2.Text = currentUser.Name; this.tb3.Text = currentUser.Salary; }
}

private void Add_Click(object sender, RoutedEventArgs e)
{
      users.Add(new User() { Id = 105, Name = "gin5", Salary = 100 });
}

private void Delete_Click(object sender, RoutedEventArgs e)
{
   users.RemoveAt(0);
}


Q:

Castle Windsor: ResolveAll does not return services with constructor parameters

I have an interface and two classes that implements it. One of them has a parameter in its constructor. I have registered both of them as services in my app.config. Unfortunately I'm not able to resolve both of them in my code: the class with constructor is not returned.
E.g.:
interface ITest
{
}

class Test : ITest
{
    private string a;

    public Test(string a)
    {
        this.a = a;
    }
}

class Test2 : ITest
{
}

Here is my configuration:
<castle>
    <components>
        <component id="Test" type="XYZ.Test, XYZ" service="XYZ.ITest, XYZ"/>
        <component id="Test2" type="XYZ.Test2, XYZ" service="XYZ.ITest, XYZ"/>
    </components>
</castle>

And here is how I try to get my services in code:
ITest[] resolveAll = container.ResolveAll<ITest>(new {a ="aText" });

The array "resolveAll" only contains 'Test2' but no trace of 'Test'. How can I do to get these two classes ?
I note that if I resolve with id "Test":
object resolve = container.Resolve("Test", new { sessionId = "sessionId" });

I obtain my 'Test' class.
What am I doing wrong ?

A:

Actually I was on an old version of Castle Windsor. On last version (3.1), this works.


Q:

Assign a new image to UIImageView with Swift

I'm using Xcode 6 Beta 4, and I'm trying to retrieve a remote image and assign it to a UIImageView. I'm using an NSURLSession dataTask in order to make this asynchronous. Here is my code:
func dataTask(imageUrl: String, targetImage:UIImageView) {

    let nsURL = NSURL(string: imageUrl)

    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
        (data, response, error) in
        if !error {
            NSLog("No Error!")
            var image:UIImage = UIImage(data: data)
            targetImage.image = image
        }
        else {
            NSLog("Error!")
        }
    }

    task.resume()
}

this is how i make the call:
        self.dataTask("http://bicicletaspony.com/img/spn/TeamA.png", targetImage: image)

And this is the error i get :(

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread.'

It's a very simple image assignment. Why does it crash that way?! any help will be much appreciated!

A:

The closure run at the end of dataTaskWithURL is called on a background thread. UIKit (like most other toolkits) can only be called from the main thread. You'll need to set the image on the main thread with something like this:
if !error {
    NSLog("No Error!")
    var image:UIImage = UIImage(data: data)
    dispatch_async(dispatch_get_main_queue(), {
        targetImage.image = image
    })
}


Q:

Equivalence of Rolle's theorem, the mean value theorem, and the least upper bound property?

How to show that Rolle's theorem, the Mean Value Theorem are equivalent to the least upper bound property?
I'm thinking of starting like this: Let F be an ordered field that does not satisfy the least upper bound property, and then deduce that F does not satisfy either Rolle's or MVT. But I'm not sure how to continue, any help please? thanks!

A:

Suppose $F$ is an ordered field, and $A \subset F$ is bounded above but has no least upper bound. Define a function $f \colon F \to F$ by $f(x)=1$ if $x$ is an upper bound of $A$, $f(x)=0$ otherwise.
I claim that for every $x$, there is an open interval around $x$ on which $f$ is constant. If $x$ is an upper bound of $A$, then since $x$ is not a least-upper-bound there exists an upper bound $y$ of $A$ with $y < x$, and so $(y,x+1)$ works. If $x$ is not an upper bound of $A$, then there exists an element $a$ of $A$ such that $a>x$, and so $(x-1,a)$ works.
The existence of these intervals shows that $f$ is everywhere differentiable with derivative $0$. Since $f$ is not constant, this contradicts the mean value theorem. Thus the MVT implies the least-upper-bound property.

The fact that the least-upper-bound property implies Rolle's theorem, and that Rolle's theorem implies the MVT, is proved in every first course of analysis.

A:

The purpose of this answer is to provide some supplementary insight into Chris Eagle's answer and to show in particular that his proof of MVT $\implies$ LUB is a very natural one.
In $\S 4$ of this note, I discuss the notions of completeness and Dedekind completeness in linearly ordered sets in terms of the induced order topology.  (Recall an ordered set is Dedekind complete if it satisfies LUB -- every nonempty subset which is bounded above has a least upper bound -- and is complete if it is Dedekind complete and has a minimal element and a maximal element.)  In particular, I show that a linear order is dense and Dedekind complete iff it is connected in the order topology.  Every ordering on a field (compatible with the field structure, of course) is dense, so we see that an ordered field satisfies LUB iff it is connected in the order topology.
(In fact Chris Eagle's answer gives a snappy proof of "connected $\implies$ LUB": if LUB does not hold, take a nonempty set $A$ which is bounded above but has no least upper bound.  Then the set of upper bounds of $A$ is nonempty, proper, open and closed.  The other implication is the one which is more familiar from real analysis, and is not quite so easy.  In the above note, I take the perspective that a very natural proof is given using the technique of real induction.)
So if we want to show that MVT $\implies$ LUB (as Chris Eagle points out, LUB $\implies$ Rolle's Theorem $\implies$ MVT is part of the standard honors calculus / elementary real analysis curriculum), it is natural to go by contrapositive: if an ordered field $(F,+,\cdot,<)$ does not satisfy LUB, then it is not connected, i.e., there exists a nonconstant continuous function $f: F \rightarrow \{0,1\}$.  It follows immediately from the definition of the order topology that for each $x \in F$, there exists an open interval $I$ containing $x$ such that $f|_I$ is constant.  Thus $f$ is a nonconstant function which is everywhere differentiable with derivative identically zero, contradicting MVT.

A:

First lets prove equivalence of the Mean Value Theorem (MVT) and Rolles theorem.
$\text{MVT}\iff \text{Rolles}$:
Clearly MVT implies Rolles.  For the converse, consider a differentiable function $f$ on the interval $[a,b]$ with $$\frac{f(b)-f(a)}{b-a}=c.$$  Then set $g(x)=f(x)-c(x-a)$.  Then $g(a)=f(a)$ and $g(b)=f(b)-(f(b)-f(a))=f(a)$ so we can apply rolles theorem to find a point such that $g'(x)=0$.  Since $$g'(x)=f'(x)-\frac{f(b)-f(a)}{b-a}$$ we have proven the MVT.
Chris Eagle showed why the MVT implies the least upper bound property.  Lets do the other direction:
$\text{Least Upper Bound}\Rightarrow \text{Rolles}$:
Suppose $f$ is differentiable on the interval $(a,b)$ with $f(a)=f(b)$, and continuous on $[a,b]$.  Since it will be uniformly continuous, it attains a maximum and minimum in $[a,b]$.  These cannot both be endpoints (otherwise it is constant), so assume WLOG the maximum occurs in $(a,b)$ at the point $\gamma$.  Then look at the difference quotients.
In some neighborhood of $\gamma$, if $x\lt \gamma$ then $$ \frac{f(x)-f(\gamma)}{x-\gamma }\geq  0$$ and if $x\gt\gamma$ then  $$\frac{f(x)-f(\gamma)}{x-\gamma}\leq 0$$ since $f(\gamma)$ is a maximum.  Since $f$ is differentiable, the right and left hand limits must be equal.  Hence $f'(\gamma)=0$ as desired.


Q:

XML ResultMap in MyBatis with association

I see this issue very strange descibed on google or stack. Let me explain.
I have Result Maps in annotations in my interface method. Only in this particular case I need dynamic query, and that is the reason I decided to write the whole mapper for interface in xml file. Below I paste the whole file. The select query should be ok, but I am occuring some difficulties with <resultMap>.
On the different websides I was searching for a good explanation of one to one, one to many, many to one association and construct of this result map in general.
I saw there is some kind of possibility to part it into subqueries, subresultmaps. But I have that already done with myBatis annotations, and I want to use it.
Could you direct me, how should the resultMap be constructed? I dont see need for constructor, discriminator, but it is still shouting... (that is why I added <collection> mark) - IntelliJ is underscoring the whole <resultMap>saying: "The content of element type "resultMap" must match "(constructor?,id*,result*,association*,collection*,discriminator?)"
I know it seems obvious, but I have completly no idea how to do it correctly. Please help me.
xml mapper file:
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="pl.net.manager.dao.UsageCounterDAO">
    <select id="getUsageCounterList" resultType="pl.net.manager.domain.UsageCounter"
            resultMap="getUsageCounterListMap">
        SELECT * FROM usage_counter WHERE
        <if test="apiConsumerIdsList != null">
            api_consumer IN
            <foreach item="item" index="index" collection="apiConsumerIdsList"
                     open="(" separator="," close=")">
                #{item}
            </foreach>
            AND
        </if>
        <if test="serviceConsumerIdsList != null">
            service IN
            <foreach item="item" index="index" collection="serviceConsumerIdsList"
                     open="(" separator="," close=")">
                #{item}
            </foreach>
            AND
        </if>
        <if test="dateFrom != null">
            date >= #{dateFrom} AND
        </if>
        <if test="dateTo != null">
            date <= #{dateTo} AND
        </if>
        <if test="status != null">
            status = #{status}
        </if>
    </select>
    <resultMap id="getUsageCounterListMap" type="">

                    ofType="pl.net.manager.domain.UsageCounter">
            <id property="id" column="id"/>
            <result property="date" column="date"/>
            <result property="apiConsumer" column="api_consumer"
                    javaType="pl.net.manager.domain.ApiConsumer"/>
            <association property="apiConsumer" column="api_consumer"
                         resultMap="pl.net.manager.dao.ApiConsumerDAO.getApiConsumer"/>
            <result property="service" column="service" javaType="pl.net.manager.domain.Service"/>
        <association property="service" column="service"
                     resultMap="pl.net.manager.dao.ServiceDAO.getService"/>

            <result property="counterStatus" column="counter_status"/>
            <result property="ratingProcessId" column="rating_process_id"/>
            <result property="value" column="value"/>
            <result property="createdDate" column="created_date"/>
            <result property="modifiedDate" column="modified_date"/>

    </resultMap>
</mapper>

A:

The XSD for the Mapper XML expects that in a <resultMap>:
the <association> must come after all the <result> tags, which means you need to group <result> tags and then add <association> tags after that.
Secondly, You dont need both resultType and resultMap in the getUsageCounterList. Use any one which in your case is resultMap
Third, Your WHERE clause in getUsageCounterList is broken. What if ONLY first condition is met, then in that case your SELECT will be something like:
SELECT * FROM usage_counter WHERE api_consumer IN (1,2,3) AND

So as I mentioned in my previous answer to your query you can use <where> tags and follow the syntax mentioned in that answer.
Fourth, In the resultMap getUsageCounterListMap you just need type which will be your Java class you are trying to populate, so you can move the ofType to type.
For One-One mapping, you can just use a <association> tag, or there's another approach, suppose you have a Java POJOs as given below:
public class Country{
    private String name;
    private City capital;
    //getters and setters
}
public class City{
    private String name;
    //getters and setters
}

You can write a Mapping in XML as shown below:
<select id="getCountries" resultType="Country">
    SELECT c.name, cy.name "capital.name"
    FROM country c
    JOIN city cy ON cy.name = c.capital
</select>

So Mybatis will make sure to create an instance of City and assign the value in capital.name to that instance's name property.
For One to Many OR Many to Many Mapping you can explore the <collection> tag of the MyBatis result map. For more information check Advacned Result Maps section in the link provided.


Q:

Set Proxy on the Office and Automatic Outside

I am in a situation where I need the computers to  use my proxy server for internet access but I still want laptops to be able to connect outside of the Office.
right now I push the proxy on the computers via GPO, works fine, but mobile users cannot connect to the Internet because of the proxy.
Any alternatives?
thanks in advance...

A:

You could try doing a transparent proxy, which should not need any client side configuration and you can freely control who gets proxied and who does not at the firewall level. Alternatively, assuming that your mobile users are connected via WiFi, you may want to move the wireless network onto another network segment that by-passes the proxy.


Q:

Approach to reduce Cyclometic Complexity

I work on a big java project(mobile application), and got the "thankful" job to review and optimize/refactore code, because of the poor performance(high complexity).
Note: I'm totally new to Java(my background is C/C++), therefore I applogize for any dumb question.
The first thing I did, was to use Findbugs and fix all reported issues. Afterwards I used the metric tool Understand to get an overview, which
methods have a high cyclomatic complexity. Unfortunately there were a lot of methods with a cyclometic complexity above the 2^20 range :-(
And one of them is where I would need some help or good ideas...
Short description:
For the communication with a server data has to be serialized. There is no Serializable interface available on this mobile framework.
Therefore, the colleague, who wrote all of the code(alone) implemented a Serializable interface containing one method called toByteArray().
E.g., the class Customer:
class Customer
{
    Address address;
    AttributeCollection attributes;
    LocationCollection locations;
    int recId;
    int recStatus;
    DateTime recCreated;
    String recCreatedBy;
    String recCreatedByProg;
    DateTime recChanged;
    String recChangedBy;
    String recChangedByProg;
    int refAddressesId;
    int refMandatorsId;
    CustomerPropertyUsage usage;

    /**
    * Serialize the properties of a class into a byte array.
    * @param destData Byte array, where the serialized data should be stored. Minimum 2 bytes.
    * @param serializationIndex Offset within the passed byte array, from which the serialized data of the class
    * should be entered. The offset is increased by the registered number of bytes so that after this method the
    * next call points to the serialized data subsequent byte.
    */
    void toByteArray(byte[] destData, IntClass serializationIndex)
    {
        if (this.address == null)
            this.usage.value &= ~CustomerPropertyUsage.ADDRESS;
        if (this.attributes == null)
            this.usage.value &= ~CustomerPropertyUsage.ATTRIBUTES;
        if (this.locations == null)
            this.usage.value &= ~CustomerPropertyUsage.LOCATIONS;

        this.usage.toByteArray(destData, serializationIndex);

        CatrString catrString = null;

        if ((this.usage.value & CustomerPropertyUsage.RECORD_HEADER) != CustomerPropertyUsage.NONE)
        {
            // Call static method getBytes from SerializationHelper class
            SerializationHelper.getBytes(this.recId, 4, destData, serializationIndex.value);
            serializationIndex.value += 4;

            SerializationHelper.getBytes(this.recStatus, 4, destData, serializationIndex.value);
            serializationIndex.value += 4;

            // recChanged is a DateTime object. For the serialization we need minimum a 7 bytes array,
            // Call method toByteArray() from DateTime class.
            this.recChanged.toByteArray(destData, serializationIndex);

            // call toByteArray of CatrString class
            catrString = new CatrString(this.recChangedBy);
            catrString.toByteArray(destData, serializationIndex);

            catrString.setValue(this.recChangedByProg);
            catrString.toByteArray(destData, serializationIndex);

            // Same as recChanged
            this.recCreated.toByteArray(destData, serializationIndex);

            catrString = new CatrString(this.recCreatedBy);
            catrString.toByteArray(destData, serializationIndex);

            catrString.setValue(this.recCreatedByProg);
            catrString.toByteArray(destData, serializationIndex);

            SerializationHelper.getBytes(this.refAddressesId, 4, destData, serializationIndex.value);
            serializationIndex.value += 4;

            SerializationHelper.getBytes(this.refMandatorsId, 4, destData, serializationIndex.value);
            serializationIndex.value += 4;
        }

        if (next property...)
        {
            ... Serialization ...
        }

        if (next property...)
        {
            ... Serialization ...
        }
    }
}

To keep the GPRS dues low, the server sets a value in this.usage.value and therefore only a specific property will be serialized and transmitted back to the server -->
transmitted messages are small.
This approach creates a lot of if-cases, depending on how much properties are in the class and therefore the path count gets higher and higher.
I think that's not a beatiful solution but it's okay. What I would like to change is the serialization calls inside the if-cases.
At the moment they look like this:
---- class SerializationHelper ----

    static void getBytes(long valueToConvert, int numOfBytesToConvert, byte[] destinationBytes, int destinationBytesOffset)
    {
        destinationBytes[destinationBytesOffset] = (byte)(valueToConvert & 0x000000FF);
        destinationBytes[destinationBytesOffset + 1] = (byte)((valueToConvert & 0x0000FF00) >> 8);

        if (numOfBytesToConvert > 2)
        {
            destinationBytes[destinationBytesOffset + 2] = (byte)((valueToConvert & 0x00FF0000) >> 16);
            destinationBytes[destinationBytesOffset + 3] = (byte)((valueToConvert & 0xFF000000) >> 24);

            if (numOfBytesToConvert > 4)
            {
                destinationBytes[destinationBytesOffset + 4] = (byte)((valueToConvert & 0x000000FF00000000L) >> 32);
                destinationBytes[destinationBytesOffset + 5] = (byte)((valueToConvert & 0x0000FF0000000000L) >> 40);
                destinationBytes[destinationBytesOffset + 6] = (byte)((valueToConvert & 0x00FF000000000000L) >> 48);
                destinationBytes[destinationBytesOffset + 7] = (byte)((valueToConvert & 0xFF00000000000000L) >> 56);
            }
        }
    }

---- class CatrString  ----

    void toByteArray(byte[] destData, IntClass serializationIndex)
    {
        //  Number of unicode characters
        SerializationHelper.getBytes(this.textLength, 2, destData, serializationIndex.value);
        serializationIndex.value += 2;

        // Text UTF-16 unicode characters
        for (int charIndex = 0; charIndex < this.textLength; charIndex++)
        {
            destData[serializationIndex.value] = (byte)(this.charCodes[charIndex] & 0x00FF);
            serializationIndex.value++;
            destData[serializationIndex.value] = (byte)((this.charCodes[charIndex] & 0xFF00) >> 8);
            serializationIndex.value++;
        }

        // Code End of string as UTF-16 unicode character
        destData[serializationIndex.value] = 0x00;
        serializationIndex.value++;
        destData[serializationIndex.value] = 0x00;
        serializationIndex.value++;
    }

---- class DateTime  ----

    void toByteArray(byte[] destData, IntClass serializationIndex)
    {
        destData[serializationIndex.value + 0] = (byte) (m_year % 0x0100);  // year low-Byte.
        destData[serializationIndex.value + 1] = (byte) (m_year / 0x0100);  // year high-Byte.
        destData[serializationIndex.value + 2] = (byte) (m_month);
        destData[serializationIndex.value + 3] = (byte) m_day;

        destData[serializationIndex.value + 4] = (byte) m_hour;
        destData[serializationIndex.value + 5] = (byte) m_minute;
        destData[serializationIndex.value + 6] = (byte) m_second;

        serializationIndex.value += 7;
    }

It should be possible to write a more "general" class which does all the serialization stuff, where I say serialize xy
bytes and that's it. But what I don't understand is what about "special" toByteArray() methods like for Strings(UTF-16 encoding)
or Date and Time? If I pack them in a class is that a good solution? Did I gain something with that? Maintable code? High-Performance code??
What would be your approach?
Thx

A:

May be it's better to create a Map of properties for each class. By default the set is empty but on call e.g. setAddress(address) we call fieldsMap.put(ADDRESS_KEY_STRING,address) instead of assigning to the class' field.
To store all acesses (existing) properties we just go through the fieldsMap storing each Entry.


Q:

Vim: viewing file structure - classes, methods, functions

So I have this dream, right: I'm doing incredible wizardry in PHP, in vim, and every once in a while I'd want to press some fancy button combination (the longer the better) to be able to navigate through the file, not in boring, line-by-line mode, but in a magnificent overview mode. Feast my eyes on a tree-like list of classes, methods, functions, variables and other wonders of code. Jump from function to function in sheer merriment.
Know ye a way to fulfill my desires?
Sort of like any file structure dialog/view in any arbitrary IDE. Anything?

A:

TagBar is similar to the aforementioned TagList, in a different way, but it's not that good with PHP.
This very new plugin claims to fix the issue. I've never tested it, though.

A:

This is reminiscent of ack and Ack.vim regarding jumping to functions amongst many files. There's also FuzzyFinder or command-t or NERDTree for file browsing and Taglist for source code browsing. You can also use :help foldmethod to fold all the functions and see them in a "tree-like" fashion that's expandable. Get familiar with gf and * or # to jump around between files and variables.


Q:

List all files without 775 or 777 permissions

How can I list all files without 777 or 775 file permissions?

A:

find <some dirs> \! \( -perm 0777 -o -perm 0775 \)


Q:

Getting OpenCV2.4.2 with GIT for Windows

I want to get the OpenCV2.4.2 source files for windows in order to generate the libraries myself. I run the command
git clone git://code.opencv.org/opencv.git

This actually gets the 2.4.9 repository which I don't want. There is a GIT option
git reset  --hard <commit code>
that is supposed to get back to the desired commit. The thing is that I found that there are way too many commits and I don't know which one is the version 2.4.2!

How can I download version 2.4.2 from GIT?

A:

Just look for the tags using:
git tag

Look for OpenCV 2.4.2, or whatever you want, and then checkout with your election:
git checkout 2.4.2

in your case.

If you want to pull the latest 2.4 branch, then you can do:
git clone -b 2.4 --single-branch https://github.com/Itseez/opencv.git Opencv-2.4


Q:

How to move all elements that are zero to the end of an array?

Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.
Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.
NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.
I tried this:
function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}

input:
[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

Expected:
[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Actual:
[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Result is coming as correct but I need to do it without array.push() or array.splice()

A:

Take length of original array
Filter nonZero values from original array
add zeros at the end as per difference in length of filtered array and original array

function removeZeros(nums) {
   let originalLen = nums.length
   let nonZero = nums.filter(Boolean)
   return [...nonZero,...new Array(originalLen-nonZero.length).fill(0)]
}

console.log(removeZeros([7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]))

Also not allowed to use any Array.prototype or Object.prototype
  methods

function removeZeros(nums) {
   let originalLen = nums.length
   let final = []
   for(let i=0;i<nums.length; i++){
    if(nums[i]) final = [...final, nums[i]]
   }
   let lenDiff = originalLen-final.length
   while(lenDiff){
    final = [...final,0]
    lenDiff--
   }
   return final
}

console.log(removeZeros([7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]))


Q:

GWT i18n changing locale

I want GWT to first determine the locale of the user by using
<set-configuration-property name="locale.useragent" value="Y"/>
The URL should be appended with that locale value. Then I'd like to let the user change the language with a listbox and change the URL accordingly.
Is this approach possible and does a change of the URL then result in changing the locale or won't this work because of the locale.useragent property?

A:

The default value for the locale.searchorder configuration property is queryparam,cookie,meta,useragent, so a query-string parameter will override the user-agent's locale (i.e. what you, and most people, would expect).


Q:

How to setup MichaelMackus/SyliusSubscriptionBundle in Sylius 1.3

How to setup MichaelMackus/SyliusSubscriptionBundle in Sylius 1.3
I have already setup this repo
but I don't know how to make product subscribable from the admin dashboard.
This implementation is for Sylius v1.0, a lot has been changed now.
I want to see this work for either version of sylius.

A:

I had a look into the bundle once and came to the conclusion that it never worked.  I might be wrong but for sure I can say, it will not work for 1.3 because Sylius migrated to Symfony Flex.
It accesses properties which are not there nor will be implemented by the bundle like OrderItem::getSubscription() used here but is not defined.

There is an PR on Github to integrate this bundle into Sylius and takes care of the aforementioned issue but the PR is outdated as well.
I assume you have integrate Subscription on your own.


Q:

Are multiple calls to java SaxParser.parse(String, Handler) Legal?

I have a java SAX parser which I would like to call multiple times on the same Handler with different XML files. I am using this in conjunction with iText to create a multi-page PDF document where some pages have one XML tag map and other pages have another. For example,
parser.parse("xmlFile1", handler);
parser.parse("xmlFile2", handler);

When I try to do this, I get a java.lang.RuntimeException thrown with the following stacktrace:
DocumentException: java.lang.RuntimeException: The document is not open.
at com.lowagie.text.pdf.PdfWriter.getDirectContent(PdfWriter.java:695)
at com.lowagie.text.pdf.PdfDocument.newPage(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.carriageReturn(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.add(Unknown Source)
at com.lowagie.text.Document.add(Unknown Source)
at myClass.myCode(Unknown Source)
org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:223)
at myClass.myCode(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)

Does the SaxParser.parse method implicitly call document.close()? Or is there some other problem in my code which I need to isolate and correct?

A:

Reusing the same parser is legal (as long as it is not used concurrently)
The parser triggers an "endDocument". This seems to close the iText document here.. But this is not done by the parser - this is code from your handler.


Q:

Cant Retrieve the values of Structure fields (i.e. text boxes) through Remix IDE

I am giving the values to structure field through Remix IDE, then I am putting ‘0’ as the index of people array, then I click transact and then I click call, but Remix does not show me the value I gave as input to the structure fields (encircled in blue box).
However, previously it worked:
Understanding array of structure
The code is:
    pragma solidity 0.5.4;
    contract MyContractOwnerAddr {
        uint256 public peopleCount = 0;
        mapping(uint => Person) public people;

        address owner;

        modifier onlyOwner() {
            require(msg.sender == owner);
            _;
        }

        struct Person {
            uint _id;
            string _firstName;
            string _lastName;
        }

        constructor() public {
            owner = msg.sender;
        }

        function addPerson(
            string memory _firstName,
            string memory _lastName)
            public
            onlyOwner
        {
            incrementCount();
            people[peopleCount] = Person(peopleCount, _firstName, _lastName);
        }

        function incrementCount() internal {
            peopleCount += 1;
        }
    }

Some body please guide me.
Zulfi.

A:

The increment people count is added before adding the person to the mapping. So nothing is added to the people[ 1 ] spot in the mapping. As is, the first spot in the mapping that gets filled is people[ 0 ]. Move incrementCount() to after adding the person to the mapping.


Q:

How to work with and query dynamic column families in Phantom for Cassandra?

I have recently started working with heavy and massive data which also needs to go through regular transaction.
Choosing Cassandra, my data model uses dynamic columns. I understand that with CQL one can alter tables and insert or query columns to get required data.
However, I was using Phantom client with Scala for Cassandra and reading through the documentation I could not find a way to write to or query from dynamic column families.
Given that we use case classes, how can one work with dynamic columns with Cassandra in Scala?

A:

I would suggest that you not dynamically alter table schemas as part of your data model. Cassandra is a row oriented database with partitioning and clustering of rows within partitions. So whatever you are trying to represent by adding or removing columns would be better handled by setting values in a fixed set of columns.
Although Cassandra allows table definitions to be altered to add and remove columns, this would normally be done only when adding a new feature to an application, so you would have an operator manually alter the schema, and then use modified application code to make use of the new schema.
I consider it dangerous for a client application to modify the schema by creating or altering tables since you run the risk of having multiple clients make changes at the same time.


Q:

Spark (scala) issue iterators

I'm creating a function for mappartitions to calculate the maximum and minimum per partition. I created the function in pyspark but I'm not able to translate it into scala successfully. I apply this function two times and I want to run a zip in the result. This is the errot that I get:
result.zip(res)
type mismatch;
[error]  found   : org.apache.spark.rdd.RDD[(Int, Int)]
[error]  required: scala.collection.GenIterable[?]

Here you have my function in python:
def minmaxInt(iterator):
    firsttime = 0
    min = 0
    max = 0
    for x in iterator:
    if(x!= '' and x!='NULL' and x is not None):
        y=int(x)
            if (firsttime == 0):
                    min = y;
                    max = y;
                    firsttime = 1
            else:
                    if y > max:
                        max = y
                    if y < min:
                        min = y
    return (min, max)

And here my code in Scala
def minmaxInt(iterator: Iterator[String]) : Iterator[(Int,Int)]={

    var firsttime = 0
    var min = 0
    var max = 0
    var res=List[(Int,Int)]()
    for( x <- iterator){
      if(x!= "" && x!= null){
    var y=x.toInt

        if(firsttime == 0){
            min = y
            max = y
            firsttime = 1}
        else{
            if (y > max){
                max = y}
            if (y < min){
                min = y}
        }
       }
     }

    res.::=(min,max)
    return res.iterator

}

Thank you in advance
Update:
Thanks for your quick response! The code is great, but still I have issues for the zip. I have twice your last code for rdd.mapPartitions and then I execute the zip:
 [error]  found   : org.apache.spark.rdd.RDD[(Int, Int)]
[error]  required: scala.collection.GenIterable[?]
[error]             result.zip(res)

A:

Here's a simpler (and more idiomatic) implementation of minMaxInt:
def minMaxInt(iterator: Iterator[String]) : Iterator[(Int,Int)]= {
  val tuple = iterator
    .filter(_ != null).filter(!_.isEmpty)
    .map(_.toInt).map(i => (i, i))
    .reduce[(Int, Int)] { case ((min, max), (i1, i2)) => (Math.min(min, i1), Math.max(max, i2)) }

  Seq(tuple).iterator
}

Which can be applied to an RDD[String] as follows:
// some sample data
def col = sc.parallelize(Seq("1", "4", "12", "3", "", null, "2"))

// "use twice" and zip
var result: RDD[(Int, Int)] = col.mapPartitions(minmaxInt)
var res: RDD[(Int, Int)] = col.mapPartitions(minmaxInt)

result.zip(res).foreach(println)
// prints:
// ((1,1),(1,1))
// ((2,2),(2,2))
// ((3,3),(3,3))
// ((4,12),(4,12))


Q:

Getting a null SearchView

I know this already has been asked many times but I've read all of them and tried changing lot's of thing and none of them has worked.
I'm writing an app which supports only android 4 and more so I don't need support library v7 (formerly it was included though). My code is very straight forward:
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

    searchView.setOnQueryTextListener(new SearchViewQueryTextListener());
    return super.onCreateOptionsMenu(menu);
}

I'm getting NullPointerException on 4th line. Here is a link to my repo so you can see anything you want. I think myself, that problems lies in MainActivity class or menu.xml or in application Manifest.
Please help, I'm stucked.

A:

You have a small typo in your main.xml menu file resource. You wrote android.widget.searchview, this should be android.widget.SearchView(case matters as there isn't any searchview widget in the android SDK explaining the missing(null) widget).


Q:

Deriving the special form of the number of edges in a Turan graph given in Bondy / Murty

I'm working through Bondy and Murty, the old version which is available online. In exercise 1.2.9a they want to prove the following equality
$$\epsilon(T_{m,n})=\binom{n-k}{2}+(m-1)\binom{k+1}{2}\tag{1}$$
where $ k = [\frac{n}{m}]$ the biggest integer $\le \frac{n}{k}$ and $T_{m,n}$ denoting the Turan graph with $n$ vertices and being a complete and simple $m$-partite graph.
I think I solved the problem, at least I derived an expression for
$$\epsilon(T_{m,n})=k^2\frac{(m-p)(m-p-1)}{2}+k(k+1)(m-p)p+(k+1)^2\frac{p(p-1)}{2}\tag{2}$$
which gives the same results as in the solution provided by Brian M. Scott in this MSE question.
I derived $(2)$ as follows: Write $n=mk+p$, then there are $p$ groups of $k+1$ vertices and $m-p$ groups of $k$ vertices. Thus,

$k^2\frac{(m-p)(m-p-1)}{2}$, $k^2$ edges between two groups of size $p$ and there are $\frac{(m-p)(m-p-1)}{2}$ of this $k^2$ connection for the $m-p$ groups.
$k(k+1)(m-p)p$, $k(k+1)$ edges between one group of size $k$ and a group of size $k+1$ and there are $(m-p)p$ of these group connections
$(k+1)^2\frac{p(p-1)}{2}$, same as point one, just within the $p$ groups each of size $k+1$.

Assuming my derivation is correct, by manipulating $(2)$ we can derive the expression $(1)$. However, I would like to know the motivation of $(1)$ as it seems they solved the problem differently, i.e. two questions:

Is my expression $(2)$ correct
What is the interpretation / motivation of $(1)$ as it is in a very specific forumla.

A:

I spent a long month typing up all of the B&M problems I could solve in LaTex.  here's my solution for this problem, which I think will illustrate how the formula was conceived.  I'll take a look at your answer shortly and try to work it out, but I wanted to kick off with the part of the problem I could solve quickly.

First, note that if $m=1$ then $k=n$ and the formula predicts
$\left({0\atop 2}\right)=0$ edges as desired. For the remainder of
the problem, we will assume $m>1$. We will create $T_{m,n}$ in a
slightly peculiar way and call it combinatorics. Start with an empty
graph with $n$ vertices and partition them as evenly as possible
into $m$ parts so that some are "small" parts with $k=\left\lfloor \frac{n}{m}\right\rfloor $
vertices and perhaps (but not necessarily) others are "large"
parts with $k+1$ vertices. There is at least one small part, so choose
one and call it "special".
The first step is to create a complete
graph on the $n-k$ vertices that aren't in the special part, and this takes $\left({n-k\atop 2}\right)$
edges (by Problem 1.2.7). Now, let one of the $m-1$ non-special parts
be given. We need to remove all of the edges connecting two vertices
in this part, and then add all of the edges from every vertex in that
part to every vertex in the special part. This is a net increase of
$x=ak-\left({a\atop 2}\right)$ edges where a is the number of vertices
in the part. If the part is small, then $a=k$ and
$$x=k^{2}-\left({k\atop 2}\right)=\frac{2k^{2}}{2}-\frac{k(k-1)}{2}=\frac{k(k+1)}{2}=\left({k+1\atop 2}\right)
$$
and if the part is large then $a=k+1$ and
$$x=k(k+1)-\left({k+1\atop 2}\right)=\frac{2k(k+1)}{2}-\frac{k(k+1)}{2}=\frac{k(k+1)}{2}=\left({k+1\atop 2}\right)$$
So, we are adding $\left({k+1\atop 2}\right)$ edges in either case.
Repeating this for the remainder of the $m-1$ non-special parts,
we come up with a total of $\left({n-k\atop 2}\right)+(m-1)\left({k+1\atop 2}\right)$
edges. But every vertex is now joined to every vertex except the ones
in its part (whether that vertex was a part of the special part or
another one), so we have created $T_{m,n}$ as desired.


Q:

Django REST: Auth user is not passed to the serialiser error - Field is required

I'm not sure what I'm doing wrong, but the authenticated user is not registered in the serialiser.
Models.py
class Post(models.Model):
    posted_by = models.ForeignKey('auth.User', on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        super(Post, self).save(*args, **kwargs)

Serializers.py
class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = '__all__'

    def create(self, validated_data):
        post = Post.objects.create(**validated_data)
        # extra code to add images

views.py
class PostViewSet(viewsets.ModelViewSet):

    serializer_class = PostSerializer

    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
        IsOwnerOrReadOnly, )

    def perform_create(self, serializer):
        serializer.save(posted_by=self.request.user)

I don't understand why serializer.save(posted_by=self.request.user) doesn't work as intended. It should pass the required information about the field.
When I do a POST request, I get the error that
{
    "posted_by": [
        "This field is required."
    ]
}

I think it's something to do with the create method in the serialiser. For some reason, posted_by is not present in validated_data (or something similar). I would like to know what exactly is happening behind the scenes.

A:

just specify posted_by as read only field.
class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = '__all__'
        read_only_fields = ('posted_by', )


Q:

How to see who kills execution of the script?

There's a complicated script that starts other scripts. It all runs for about 6 hours. But I've noticed that one or two child scripts are being killed from time to time.
All I get is a line in log saying that script is killed.
How do I get some info on who kills it? Is it possible?

A:

The nature of killing a process does not provide an originator. A bit is set in a kernel structure associated with the process, indicating a signal is pending. If the signalling process does not indicate it is signalling, there's no way to find out.
Some processes do in fact announce their signalling. On Linux, the OOM (Out of Memory) killer might write a log entry to /var/log/messages. If the reason for the signalling to your script is an OOM condition, this might be the place to look.
See also Who "Killed" my process and why?


Q:

Is it possible to show interpolated data using dygraphs?

I have been working for the last months with dygraphs. It is a incredible library and I have got great results but I´m having some problems to find the way of interpolating data from different signals to be shown in the same chart.
The data I received from different sensors have not the same timestamp for the different samples, so for the most of the points of the x axe timestamps I have only the value of one signal. The chart is plotted perfectly, but I would like to see the interpolated value of the rest of the signals in that x point I am pointing over. Below I have the chart I get.

Reading on the dygraph documentation I have seen that when you have independent series, it is possible to see at least the value "undefined" for the signals without data in that point of the x axe.
The csv I use to plot the data is shown below. It has the same structure indicated in the dygraph documentation but I don´t get this undefined label neither.
TIME,LH_Fuel_Qty,L_Left_Sensor_NP
1488801288048,,1.4411650490795007
1488801288064,0.478965502446834,
1488801288133,,0.6372882768113235
1488801288139,1.131315227899919,
1488801288190,1.847605177130475,
1488801288207,,0.49655791428536067
1488801288258,0.45488168748987334,
1488801288288,,1.3756073145270766
1488801288322,0.5636921255908185,
1488801288358,,1.1193344122758362
Thanks in advance.

A:

This is an approach that does not add any data to your csv data and still provides interpolated values for all the columns as you move your mouse around. It adds a listener to the mousemove event within dygraph and interpolates the closest points for all of the data. At the moment I have simply shown it in an extra DIV that is after the graph but you can display it however you like:

function findNextValueIndex(data, column, start) {
  var rows = data.length;

  for (var i = start; i < rows; i++) {
    if (data[i][column] != null) return (i);
  }
  return (-1);
}

function findPrevValueIndex(data, column, start) {

  for (var i = start; i >= 0; i--) {
    if (data[i][column] != null) return (i);
  }
  return (-1);
}

function interpolate(t0, t1, tmid, v0, v1) {
  return (v0 + (tmid - t0) / (t1 - t0) * (v1 - v0));
}

function showValues(headers, colors, vals) {
  var el = document.getElementById("info");
  var str = "";
  for (j = 1; j < headers.length; j++) {
    str += '
' + headers[j] + ": " + vals[j] + "
";
  }
  el.innerHTML = str;
  document.getElementById("hiddenDiv").style.display = "none";
}

function movecustom(event, dygraph, point) {
  var time = dygraph.lastx_;
  var row = dygraph.lastRow_;
  var vals = [];
  var headers = [];
  var colors = [];
  var cols = dygraph.rawData_[0].length;

  // draw a line on the chart showing the selected location
  var canvas = dygraph.canvas_;
  var ctx = canvas.getContext("2d");

  ctx.beginPath();
  ctx.lineWidth = 1;
  ctx.strokeStyle = "rgba(0,200,200,0.1)";
  ctx.moveTo( dygraph.selPoints_[0].canvasx, 0);
  ctx.lineTo( dygraph.selPoints_[0].canvasx, 1000);
  ctx.stroke();

  for (var j = 1; j < cols; j++) {
    colors[j] = dygraph.colors_[j - 1];
    if (dygraph.rawData_[row][j] == null) {
      var prev = findPrevValueIndex(dygraph.rawData_, j, row - 1);
      var next = findNextValueIndex(dygraph.rawData_, j, row + 1);
      if (prev < 0)
        vals[j] = dygraph.rawData_[next][j];
      else if (next < 0)
        vals[j] = dygraph.rawData_[prev][j];
      else {
        vals[j] = interpolate(dygraph.rawData_[prev][0], dygraph.rawData_[next][0], time, dygraph.rawData_[prev][j], dygraph.rawData_[next][j]);
      }
    } else {
      vals[j] = dygraph.rawData_[row][j];
    }
  }

  headers = Object.keys(dygraph.setIndexByName_);

  showValues(headers, colors, vals);
}

window.onload = function() {

  new Dygraph(
    document.getElementById('graph'), document.getElementById('csvdata').innerHTML, {
      connectSeparatedPoints: true,
      drawPoints: true,
      labelsDiv: "hiddenDiv",
      interactionModel: {
        'mousemove': movecustom
      }
    }
  );
}

TIME,LH_Fuel_Qty,L_Left_Sensor_NP
1488801288048,,1.4411650490795007
1488801288064,0.478965502446834,
1488801288133,,0.6372882768113235
1488801288139,1.131315227899919,
1488801288190,1.847605177130475,
1488801288207,,0.49655791428536067
1488801288258,0.45488168748987334,
1488801288288,,1.3756073145270766
1488801288322,0.5636921255908185,
1488801288358,,1.1193344122758362


Q:

Is a picture of my e-ID on my resume a good idea?

I recently redesigned my resume to make it easier to read and edit, by removing nested tables, moving certain areas, and combining others. Part of what I did was replace some of my personal information with a scan of my e-ID. They look like this:

This replaced my gender, my name, my date and place of birth and my nationality, and also meant I had a picture of myself on my resume. I also partially put it on there because it is sort of an eye-catcher, while still being somewhat neutral. Since Belgian e-ID cards require you to have a card reader and a pin code to do anything remotely useful with them, I don't think it's a huge security risk.
However, I'm wondering if putting it on there might bring other risks along. Other questions on here mention that putting a picture of yourself in your resume could lead to you being discarded right away to avoid any potential discrimination lawsuits, but also that some regions actually expect a photo, and that men are more likely to get a callback if they put one in. That's also specific to putting a picture of yourself, and the effect could be different (for better or for worse) if the image actually contains crucial information for my resume.

A:

Don't do it.
Apart from the obvious standard "don't include your photo unless it's a model/actor CV" rule, like listed in Will putting my picture on my resume help me get the job easier while I'm not clearly asked to include it?, consider the fact that you're replacing good indexable, copy-pasteable, searchable text content with non-computer-readable images.
You'd be doing yourself a disservice by making all that text notably less accessible, whether from a jobsite indexing point of view, a recruiter or HR department CTRL+F searching for content hidden in the image, or simply site SEO.

A:

I personally would worry about identity theft (they have your name, your birthdate and nationality) using this approach aside from the fact that it is a bad choice to use a picture unless it is the cultural norm in your country. Why would they care about your birthdate? That could cause discrimination as well. You are reaching the age whene age discrimination can be very real.
Plus if the information is actually needed in your country for the resume to get past HR, putting it into a photo means that it will get discarded by many automated systems because it is not in text.
Personally I would not recommend this approach.

A:

It just feels weird and you have no reason to do so, I don't think it stands out positively. Scanned documents don't look good anyway.
Scanning documents is in general a bad thing. You're exposing your signature, your document number, your birth location, the validity dates. That's all unnecessary information, and exposing your signature when not necessary is not a good practice considering that it can still be used in certain cases to pay with a credit card. The same goes for other information, it can be abused.
Text on a photo is not searchable and copy-pasteable, that's horrible and might make a pdf CV in the archive unsearchable or cause HR extra work since they have to copy the information by hand.
If it's a custom in your country too (probably considering that it's almost the same on most of continental Europe), you'd still have to write about your civil status, so you'd have one single information standing alone.

Just put the photo on the CV and write the data in normal text. You can play around with formatting if you want.


Q:

Agrupar parcelas mostrando o valor da primeira e da última parcela

Tenho uma tabela de parcelas com os seguintes campos (entre outros): inscricao (Inscrição do Cliente), nrparcela (Número da Parcela), dt_vencimento (Data de Vencimento) e vlrparcela (Valor da Parcela).
Se o cliente tiver 10 parcelas, haverá 10 registros na tabela com a coluna nrparcela numerada de 1 a 10, com as respectivas datas de vencimento e valores (variados) para aquele cliente.
Como agrupar esses registros, selecionando o número da primeira parcela (geralmente '1'), o número da última parcela, o valor da primeira parcela e o valor da última parcela?
O valor de cada parcela pode variar, havendo casos onde o valor de cada parcela é diferente dos demais valores daquele parcelamento.
Consegui apenas isso:
SELECT inscricao, MIN(nrparcela) AS primeira_parcela,
       MAX(nrparcela) AS ultima_parcela
  FROM parcelas
 GROUP BY inscricao
 ORDER BY inscricao

A:

Aqui está a minha solução:
Estrutura:
create table PARCELA (
  inscricao int not null,
  nrparcela int not null,
  dt_vencimento datetime,
  vlrparcela decimal(15,2)
);

alter table PARCELA add constraint PARCELA_PK primary key (inscricao, nrparcela);

insert into PARCELA values (1, 1, '2014/01/01', 10.01);
insert into PARCELA values (1, 2, '2014/01/02', 10.02);
insert into PARCELA values (1, 3, '2014/01/03', 10.03);
insert into PARCELA values (1, 4, '2014/01/04', 10.04);

insert into PARCELA values (2, 1, '2014/02/01', 110.01);
insert into PARCELA values (2, 2, '2014/02/02', 110.02);
insert into PARCELA values (2, 3, '2014/02/03', 110.03);
insert into PARCELA values (2, 4, '2014/02/04', 110.04);
insert into PARCELA values (2, 5, '2014/02/05', 110.05);

SQL
select
  a.inscricao, min(a.nrparcela),
  (select b.vlrparcela from PARCELA b where b.inscricao = a.inscricao and b.nrparcela = min(a.nrparcela)),
  max(a.nrparcela),
  (select b.vlrparcela from PARCELA b where b.inscricao = a.inscricao and b.nrparcela = max(a.nrparcela))
from
  PARCELA a
group by
  a.inscricao

http://sqlfiddle.com/#!3/23410f
Usei SQL Server pois não lembro dos tipos no postgresql


Q:

How to fix " sqlite3.OperationalError: incomplete input " when the error is regarding ''')

This is the error I am getting:

Traceback (most recent call last):   File "/Users/My
  Documents/Independent Learning/BBA Coding Related Work/Creating a
  Database with SQLite3 for Python/MarketCo1.py", line 89, in
      '''); sqlite3.OperationalError: incomplete input

Below is the code I used:
cursor.execute('''CREATE TABLE ContactEmployee(
   ContactEmployeeID INTEGER PRIMARY KEY,
   ContactID INTEGER, EmployeeID INTEGER,
   ContactDate NUMERIC,
   Description TEXT,
   FOREIGN KEY(ContactID) REFERENCES Contact(ContactID),
   FOREIGN KEY(EmployeeID) REFERENCES Employee(EmployeeID)
   ''')
db.commit()

A:

You are missing a closing brace, as mentioned by glibdud in the comments:
cursor.execute('''CREATE TABLE ContactEmployee(
  ContactEmployeeID INTEGER PRIMARY KEY,
  ContactID INTEGER, EmployeeID INTEGER,
  ContactDate NUMERIC,
  Description TEXT,
  FOREIGN KEY(ContactID) REFERENCES Contact(ContactID),
  FOREIGN KEY(EmployeeID) REFERENCES Employee(EmployeeID))
  ''')
db.commit()


Q:

Conversion of a 2011 vintage Unibody Macbook Pro to Linux

I've got a Late 2011 17" MacBook Pro that got as far as High Sierra 10.13.6. My thought was to remove the SSD that's currently installed, replace it with another SSD, then install Linux Mint on this new SSD.
I'd like to be able to restore High Sierra if Linux Mint doesn't work out. Swapping SSDs is easy enough, but I want to avoid burning any bridges. Are there any NVRAM/firmware/other issues I should watch for... that is to say any changes that could render my machine un-bootable should I ever wish to return to High Sierra?

A:

There's nothing in NVRAM or in the EFI firmware that make your 2011 MacBook Pro unbootable should you ever want to return to a previous macOS.
As I explained in another answer, NVRAM holds your preboot environment like boot volume.  The worst thing that will happen is it will look for a bootable file where one no longer exists resulting in the infamous flashing question mark or prohibitory sign.  Reinstallation of your OS will fix the problem.
As far as your EFI goes, it's equivalent to your BIOS, just much more advanced.  There's nothing an OS installation is going to do that irreparably harms your EFI firmware.
Doing installations on separate SSDs is actually a good idea.  I do that myself as SSD prices are now very low that it's more economical (in time) to just swap out a drive than it it is to format and install.  The Macs (of varying vintages and models) don't complain at all.  NVRAM is never reset or variables modified for any reason.
Now, for applicable models with the T2 Security Chip (the 2011 MBP is not), users have to be aware of Secure Boot.  Basically, it will prevent unsigned operating systems from being installed or booted.  However, that restriction can be turned off.  It's basically the same thing as UFEI Secure Boot found on PCs.


Q:

Can i put text after  tag?

I'm wondering, can I put text after Li tag and will it be correct?
Example

Text

    Text here after tag

Text

    Text here after tag

Writing such a code will return dots from li tags indented and that's what I want to achieve.

A:

Regarding your screenshot - the following code does what you want

Text

    Text here after tag

Text

    Text here after tag

css
span {
    margin-left: -15px;
}

And here is a fiddle: http://jsfiddle.net/P2CXF/
Note that the W3C markup validator will throw errors. The  tag is not allowed as child of

EDIT:
This one will validate (thank you @Ma3x)

Text

    Text here after tag

Text

    Text here after tag

You can also use
 instead of .


Q:

Proving that this Game on Polygons Ends

About two years ago, I started thinking about the following problem: You're given an $N$ and an $S$, positive integers. You start with an $N$-gon that has positive integer labels at each vertex, such that the labels sum to $S$. A "move" is replacing the label at some vertex with the positive difference of the labels at its two adjacent vertices. You win if you can exhibit a sequence of moves such that all of the vertex labels are zero at the end.
This is a generalization of 2003 USAMO problem B3,
"A positive integer is written at each vertex of a hexagon. A move is to replace a number by the (non-negative) difference between the two numbers at the adjacent vertices. If the starting numbers sum to $2003^{2003}$, show that it is always possible to make a sequence of moves ending with zeros at every vertex."
The USAMO problem itself can be answered in the affirmative by doing a modified greedy algorithm for most of the moves, showing there's always a move where you can reduce the problem to a smaller sum while changing the parities systematically, then doing casework for the "end game" to show that each configuration of 1's and 0's (or k's and zeros, the cases are of course equivalent) can be gotten down to all zeros.
It's easy to check that for $n=4$ and $S$ odd, there's a winning strategy. I have lots of simulation/numerical evidence and some half baked ideas to suggest that, in general, there's a winning strategy if and only if $N$ and $S$ have opposite parities. But in two years of coming back to it on and off, I haven't really made progress. It's open, as far as I know, though I knew that more surely two years ago than I do now.
Ideas?

A:

I like your problem. But your opposite parity conjecture doesn't seem to handle the case N=3 and S=2 (even when corrected as in Mau's comment by gcd), with a triangle labeled as follows:

        1

     1     0

This position appears to be invariant under any move, so you cannot reach all 0s.
More generally, a similar obstacle works for any 3n-gon, with S=2n. If you repeat the pattern 1 1 0 all the way around, it is stable under any move. If $n$ is odd, these will have opposite parities.


Q:

Visualize git branch topology only, with no commit history

I would like to see the branch topology of my git repository in a nutshell, without visualizing the whole commit history at the same time, which makes the branch visualization hard to read.
For example, here is what I get by following the command given here
$ git log --graph --full-history --all --pretty=format:"%h%x09%d%x20%s"
* 822458d        (HEAD -> branch2) revision 5
* 1057127        revision 4
| * ae46e7e      (branch1a) revision 3
| * 39cd7e2      (branch1) revision 2
| * 6802061      revision 1
|/
* f8c8522        (master) start

While what I want is just the topology of the branches, without the commit historym i.e. something like this
branch2
|          branch1a
|         /
| branch 1
|/
(master)

Do you guys know how to achieve this in git?
Thank you.

A:

git log --all --decorate --oneline --graph --simplify-by-decoration

The --simplify-by-decoration option allows you to view only the big picture of the topology of the history, by omitting commits that are not referenced by tags. Commits are marked as !TREESAME (in other words, kept after history simplification rules described above) if (1) they are referenced by tags, or (2) they change the contents of the paths given on the command line. All other commits are marked as TREESAME (subject to be simplified away).


Q:

How do I make my JavaScript function stop after finding the first parent with a certain class?

I'm currently making a Drag-and-Drop engine in JavaScript. I'm currently working on making "bounds" for some "drag-able" objects. A drag-object has bounds if its parent (or a parent of a parent ect.) has the class .bound. The function I am using to find out if the drag-object is bounded is (Yes, this function also creates the drag-object.):
function makeObj(e) {
    obj = new Object();
    obj.element = e;

    obj.boundX = e.parentNode.offsetWidth - e.offsetWidth;
    obj.boundY = e.parentNode.offsetHeight - e.offsetHeight;

    obj.posX = event.clientX - e.offsetLeft;
    obj.posY = event.clientY - e.offsetTop;

    var curleft = curtop = 0;
    if (e.offsetParent) {
        do {
            curleft += e.offsetLeft;
            curtop += e.offsetTop;
            //alert(e.id + ":" + e.innerHTML);
            if(~e.className.search(/bound/)) {
                obj.boundX = curleft - obj.element.offsetLeft;
                obj.boundY = curtop - obj.element.offsetTop;
                return obj;
            }

        } while (e = e.offsetParent);
    }

    return obj;
}

For clarification: This function MAKES the drag-object. My problem lies in the loops. The loops don't find the first parent node with a .bound class.
This html "should" affect the function:

Hello World!

 One

 Two

As much as this html:

Hello World!

 One

 Two

However, the first html affects the loops (and how the drag objects behave), and I don't know why.
P.S. The function is slightly broken. I haven't managed to set the "correct" value for obj.boundX and obj.boundY without using this inferior (because it makes the parentNode the bound element regardless of class) function:
function makeBoundlessObj(e) {
    obj = new Object();
    obj.element = e;

    obj.boundX = e.parentNode.offsetWidth - e.offsetWidth;
    obj.boundY = e.parentNode.offsetHeight - e.offsetHeight;

    obj.posX = event.clientX - e.offsetLeft;
    obj.posY = event.clientY - e.offsetTop;

    return obj;
}

I will post the entire engine below (and a jsfiddle link) just in case it is useful:
http://jsfiddle.net/Upvdm/1/
// JavaScript Document

var dragObj;

document.addEventListener("mousedown", down, false);

function down(event) {
    if(~event.target.className.search(/drag/)) {
        dragObj = makeObj(event.target);
        dragObj.element.style.zIndex="100";
        document.addEventListener("mousemove", freeMovement, false);
    }
}

function freeMovement(event) {

    if (typeof(dragObj.element.mouseup) == "undefined")
        document.addEventListener("mouseup", drop, false);
    //Prevents redundantly adding the same event handler repeatedly

dragObj.element.style.left = Math.max(0, Math.min(event.clientX - dragObj.posX, dragObj.boundX)) + "px";
    dragObj.element.style.top = Math.max(0, Math.min(event.clientY - dragObj.posY, dragObj.boundY)) + "px";
}

function drop() {
    dragObj.element.style.zIndex="1";

    document.removeEventListener("mousemove", freeMovement, false);
    document.removeEventListener("mouseup", drop, false);
    //alert("DEBUG_DROP");
}

function makeBoundlessObj(e) {
    obj = new Object();
    obj.element = e;

    obj.boundX = e.parentNode.offsetWidth - e.offsetWidth;
    obj.boundY = e.parentNode.offsetHeight - e.offsetHeight;

    obj.posX = event.clientX - e.offsetLeft;
    obj.posY = event.clientY - e.offsetTop;

    return obj;
}

function makeObj(e) {
    obj = new Object();
    obj.element = e;

    obj.boundX = e.parentNode.offsetWidth - e.offsetWidth;
    obj.boundY = e.parentNode.offsetHeight - e.offsetHeight;

    obj.posX = event.clientX - e.offsetLeft;
    obj.posY = event.clientY - e.offsetTop;

    var curleft = curtop = 0;
    if (e.offsetParent) {
        do {
            curleft += e.offsetLeft;
            curtop += e.offsetTop;
            //alert(e.id + ":" + e.innerHTML);
            if(~e.className.search(/bound/)) {
                obj.boundX = curleft - obj.element.offsetLeft;
                obj.boundY = curtop - obj.element.offsetTop;
                return obj;
            }

        } while (e = e.offsetParent);
    }

    return obj;
}

function findPos(obj) { // Donated by `lwburk` on StackOverflow
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
}

In case the problem was not clear:
My JavaScript function makeObj() isn't setting the correct boundX and boundY because elements with the class .bound are affecting the function when they shouldn't be.
Thank you all for reading and helping!

A:

As far as I can tell, the loop is functioning as you desire. It is finding the first element tagged with the bound class. The problem you're seeing is related to the position:relative that comes along with the bound class.
Consider the following HTML:

Hello World!

 One

 Two

It functions identically to your "first" HTML (the one where center is tagged with the bound class).
The important thing here is that tagging an element with position:relative or position:absolute makes the child elements see its upper left corner as (0,0). In CSS, child elements look up to their first ancestor that is tagged with a relative or absolute position. Elements that are not tagged as such are not seen by the child as having an upper left corner at (0,0).
The trouble here is that you're using the offsetLeft and offsetTop of the desired bound (the nearest ancestor with the bound class; in this case box), which varies when that element's nearest ancestor tagged with relative/absolute changes. In the first case, the nearest positioned ancestor is center... in the second case it's the document. In the first case makeObj returns (0, 22). In the second it returns (108,82).
Unless you're doing this as an academic exercise or a fun project, consider just using an existing DnD library like the one that comes with Dojo: http://docs.dojocampus.org/dojo/dnd


Q:

Recursively creating a JSON tree, adding only at the deepest level

I want to create a JSON hierarchy structure of unknown objects, so it must be handled recursively.
Here's my function, where angular.element.isEmptyObject() is inherited from jQuery, and angular.copy() is a function that creates a deep copy of the object (I'm using AngularJS).
function recurseTree(tree, newKey, newId) {
    if(angular.element.isEmptyObject(tree)) {
        tree[newKey] = {_id: newId};
    } else {
        for(var key in tree) {
            if(typeof tree[key] == 'object') recurseTree(tree[key], newKey, newId);
            else tree[newKey] = {_id: newId};
        }
    }
    return angular.copy(tree);
}

Now run this:
var testT = {};
console.log(recurseTree(testT, 'a', '1'));
console.log(recurseTree(testT, 'b', '2'));
console.log(recurseTree(testT, 'c', '3'));
console.log(recurseTree(testT, 'd', '4'));
console.log(recurseTree(testT, 'e', '5'));

You'll notice that the first and second ones return as expected:
{
    a: {
        _id: '1',
        b: {
            _id: '2'
        }
    }
}

but the third one is where I run into trouble.
{
    a: {
        _id: '1',
        b: {
            _id: '2',
            c: {
                _id: '3'
            }
        },
        c: {
            _id: '3'
        }
    }
}

What do I need to fix to get the c object appended ONLY as a child of b, rather than also as a child of a?  I'm stumped.
Here's a JSFiddle of it in action, check your console for the results.  http://jsfiddle.net/winduptoy/Mjq5D/2/

A:

Try this:
function recurseTree(tree, newKey, newId) {
    if(angular.element.isEmptyObject(tree)) {
        tree[newKey] = {_id: newId};
        return;
    }

    var child = null; // find current tree's child
    for(var key in tree) {
        if (key != '_id') {
            child = tree[key]; // found a child
            break;
        }
    }
    if (child) { // recursively process on child
        recurseTree(child, newKey, newId);
    } else { // no child, so just fill the tree
        tree[newKey] = {_id: newId};
    }
}

Test:
var testT = {};
recurseTree(testT, 'a', '1');
console.log(testT);
recurseTree(testT, 'b', '1');
console.log(testT);
recurseTree(testT, 'c', '1');
console.log(testT);
recurseTree(testT, 'd', '1');
console.log(testT);
recurseTree(testT, 'e', '1');
console.log(testT);

Please be noted that I have not used angular.copy(tree) for the performance's sake.
If you don't want to change the tree, copy it before passing it to the function recurseTree. Please try it on jsFiddle.


Q:

Importing existing git based projects into eclipse

I have a number of projects using git for version control. Some are python modules others are C++ projects developed using Xcode4. However, I seemed to be struggling to import the project via git. I can easily import the actual source directories.
I tried doing the following:
1)I add my git repositories to the Egit repository browser.
2) Right click on the repository and click import project ...
3) Create the appropriate project
At this stage there is no source code in the project. I feel like I am missing a step somewhere.

A:

Eclipse has a git plugin: http://eclipse.org/egit/
Just install EGit and import the actual source code directories. Then you can edit the source code in Eclipse, and use the Eclipse team provider interface to access version control facilities, and you're operating out of the same git repositories as you always were.


Q:

Improve Performance of VBA String Comparison

I was wondering if this code could be sped up at all using another technique. The code doesn't take too long, but seeing as how how quickly something operates is usually what is wanted, I was curious if there is something I could do to increase the speed of it. The code is simply used to check every column against a template table to see if the value matches, if it doesn't it creates a report displaying information about the part and what the incorrect/correct value is.
Option Explicit

'Check values of table against template table
Sub checkTemplate(shnam1 As Worksheet, shnam2 As Worksheet, shnam3 As Worksheet)

    'Initalizes integers that will be used
    Dim rwIndex As Long             '"Item Attributes" row index
    Dim colIndex As Long            '"Item Attributes" column index
    Dim rowEnd As Long              'Last row in "Item Attributes"
    Dim colEnd As Long              'Last column in "Item Attributes"
    Dim tempIndex As Integer

    Dim resRow As Long              'Current row in "Report" to paste
    Dim resCol As Long              'Current column in "Report" to paste
    Dim temp1 As String
    Dim temp2 As String

    'Gets bounds for "Item Attributes" table
    rowEnd = shnam1.Cells(Application.Rows.Count, 1).End(xlUp).Row
    colEnd = shnam1.Cells(1, Application.Columns.Count).End(xlToLeft).Column

    'Report Heading
    shnam3.Cells(1, 1).Value = "Oracle Part Number"
    shnam3.Cells(1, 2).Value = "Description"
    shnam3.Cells(1, 3).Value = "Attribute Name"
    shnam3.Cells(1, 4).Value = "Incorrect Value"
    shnam3.Cells(1, 5).Value = "Correct Value"

    resRow = 2                  'Set row for Results

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

    'From 2nd row to last row
    For rwIndex = 2 To rowEnd

        tempIndex = 3       'Template table index
        resCol = 1          'Set column for results

        temp1 = shnam1.Cells(rwIndex, 1)
        temp2 = shnam1.Cells(rwIndex, 2)

        'From 3rd column to last column
        For colIndex = 3 To colEnd

            'Compare selection in data to template table
            If (shnam1.Cells(rwIndex, colIndex).Value) <> (shnam2.Cells(tempIndex, 1).Value) Then

                shnam3.Cells(resRow, resCol) = temp1
                shnam3.Cells(resRow, resCol + 1) = temp2

                'Copy attribute name
                shnam2.Cells(tempIndex, 2).Copy shnam3.Cells(resRow, resCol + 2)

                'Copy incorrect attribute value
                shnam1.Cells(rwIndex, colIndex).Copy shnam3.Cells(resRow, resCol + 3)

                'Copy correct attribute value
                shnam2.Cells(tempIndex, 1).Copy shnam3.Cells(resRow, resCol + 4)

                resRow = resRow + 1                 'Move down a row in the "Report" table

            End If

            tempIndex = tempIndex + 1           'Increment through template table

        Next colIndex

    Next rwIndex

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True

End Sub

A:

See if this runs any faster for you:
Sub checkTemplate(shnam1 As Worksheet, shnam2 As Worksheet, shnam3 As Worksheet)

    Dim lCalc As XlCalculation
    Dim arrResults(1 To 65000, 1 To 5) As Variant
    Dim arrTable() As Variant
    Dim varCriteria As Variant
    Dim rIndex As Long
    Dim cIndex As Long
    Dim ResultIndex As Long

    With Application
        lCalc = .Calculation
        .Calculation = xlCalculationManual
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    On Error GoTo CleanExit

    arrTable = shnam1.Range("A1").CurrentRegion.Value
    For rIndex = 2 To UBound(arrTable, 1)
        For cIndex = 3 To UBound(arrTable, 2)
            varCriteria = shnam2.Cells(cIndex, "A").Value
            If arrTable(rIndex, cIndex) <> varCriteria Then
                ResultIndex = ResultIndex + 1
                arrResults(ResultIndex, 1) = arrTable(rIndex, 1)
                arrResults(ResultIndex, 2) = arrTable(rIndex, 2)
                arrResults(ResultIndex, 3) = shnam2.Cells(cIndex, "B").Text
                arrResults(ResultIndex, 4) = arrTable(rIndex, cIndex)
                arrResults(ResultIndex, 5) = varCriteria
            End If
        Next cIndex
    Next rIndex

    If ResultIndex > 0 Then
        With shnam3.Range("A1:E1")
            .Value = Array("Oracle Part Number", "Description", "Attribute Name", "Incorrect Value", "Correct Value")
            .Font.Bold = True
        End With
        shnam3.Range("A2:E2").Resize(ResultIndex).Value = arrResults
        shnam3.Range("A1").CurrentRegion.Sort shnam3.Range("A1"), xlAscending, Header:=xlYes
        shnam3.Range("A:E").EntireColumn.AutoFit
    End If

CleanExit:
    With Application
        .Calculation = lCalc
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    If Err.Number <> 0 Then
        MsgBox Err.Description, , "Error: " & Err.Number
        Err.Clear
    End If

    Erase arrResults
    Erase arrTable

End Sub


Q:

Getting "error: GraphQL schema file should contain a valid GraphQL introspection query result" after apollo schema:download

So I set up the graphql server described here
Now, I want to generate android queries against this server using apollo android as per these instructions.
I've tried different folder configurations for the location of the generated schema against this sample server and no matter what I do I get an error at compile time saying "GraphQL schema file should contain a valid GraphQL introspection query result"
Any advice?

A:

Turns out the solution is to use the apollo-codegen cli command and not apollo schema:download


Q:

Ignore collisons between objects with the same collision group in Cocos2D

I have a basic rocket game that collects meteorites. Very basic. The game works fine except there is a real annoyance that i've been trying to iron out but can't.
When the rocket collides with a meteorite:
-(void)ccPhysicsCollisionPostSolve:(CCPhysicsCollisionPair *)pair rocket:(CCNode *)nodeA meteorite:(CCNode *)nodeB{
[self meteoriteRemoved:nodeB];
[self spawnMeteorite];
score ++;
_scoreLabel.string = [NSString stringWithFormat:@"%d", score];
}

It is removed and respawned. This works fine, but if the meteorite is close to another meteorite and the rocket slams into one, it knocks the other one out of the way like snooker balls. I want them to remain stationary until the rocket collides with them.
Is there any way to tell sprites in the same collision group to ignore each other?
EDIT**
I'm loading the meteorites in a loop from a class which has:
@implementation Meteorite

- (void)didLoadFromCCB {
self.physicsBody.collisionType = @"meteorite";
}

@end
They are then spawned using:
-(void)spawnMeteorite{
CCNode *meteorite = [CCBReader load:@"Meteorite"];

CGFloat randomX = ((double)arc4random() / ARC4RANDOM_MAX);
CGFloat randomY = ((double)arc4random() / ARC4RANDOM_MAX);
CGFloat rangeX = 320 - 48;
CGFloat rangeY = 2880 - 200;

meteorite.position = ccp((randomX * rangeX)+24, (randomY * rangeY)+ _ground.contentSize.height + _rocket.contentSize.height);
meteorite.physicsBody.velocity = ccp(0,0);
[_physicsNode addChild:meteorite];

}

The following code gives a log of Meteorite Hit extremely often when flying into a group, and most of them fly off into oblivion!
-(void)ccPhysicsCollisionPostSolve:(CCPhysicsCollisionPair *)pair meteorite:(CCNode *)nodeA meteorite:(CCNode *)nodeB{
NSLog(@"Meteorite HIT");
}

Thanks for looking into this, hope it helps

A:

Objects with the same collision group do not collide with each other.
The documentation states:
/**
 *  The body's collisionGroup, if two physics bodies share the same group id, they don't collide. Defaults to nil.
 */
@property(nonatomic, assign) id collisionGroup;

Could you share the code that assigns the collision group to your physics objects? You need to be careful here, because the "same" collision group means the exact same pointer to the same object!


Q:

How is this Typescript class compatible with this interface

I am new to typescript(and OOP). I found the following example in their official documentation:
class Student {
    fullName: string;
    constructor(public firstName: string, public middleInitial: string, public lastName: string) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person : Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}

let user = new Student("Jane", "M.", "User");

document.body.innerHTML = greeter(user);

The way I see it, class Student doesn't have the property lastname and thus shouldn't be compatible with the interface Person when the function greeter is being called.
What am I missing here?

A:

The class does have a field lastName. public lastName: string is a shorthand field declaration. This is both a public field and a parameter declaration. That is the meaning of the modifier in the constructor parameter. See the docs for more information


Q:

Migrating a C program from Linux to Windows

I want to open a file in C with the open() function,and this is the code I use:
int lire(){
    char buf[1024];
    int bytesRead;
    int fildes;
    char path[128];
    mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
    int flags = O_RDONLY;
    printf("\n%s-->Donner l'emplacement du fichier :%s ", CYAN_NORMAL, RESETCOLOR);
    scanf("%s", path);
    fildes = ouvrir(path, flags, mode);
    if(fildes == -1){
        return 0;
    }
    while ((bytesRead = read(fildes, buf, sizeof buf)) > 0)
    {
        write(STDOUT_FILENO, buf, bytesRead);
    }
    close(fildes);
    return 1;
}

int ouvrir(char *path, int flags, mode_t mode)
{
        return open(path, flags, mode);
}

I've wrote this code for the first time in Linux, and It was working, but when I run it in Windows I got this error message:
error: 'S_IRUSR' undeclared (first use in this function)|
error: 'S_IWUSR' undeclared (first use in this function)|
error: 'S_IRGRP' undeclared (first use in this function)|
error: 'S_IROTH' undeclared (first use in this function)|

These are the headers I included:
#include <sys/types.h> //Specified in man 2 open
#include <sys/stat.h>
#include <stdio.h>
    #include <fcntl.h> // open function
    #include <unistd.h> // close function
    #include "colors.h"
    #include "const.h"
    #include <ctype.h>
    #include <errno.h>
    #include <string.h>

How can I solve that problem?

A:

With Windows you need to include sys\stat.h, and the mode flags available are _S_IREAD and _S_IWRITE, which can be combined if needed.  Documentation can be found here.
Note in particular this comment:

If a value other than the above is specified for pmode (even if it would specify a valid pmode in another operating system) or any value other than the allowed oflag values is specified, the function generates an assertion in Debug mode and invokes the invalid parameter handler as described in Parameter Validation. If execution is allowed to continue, the function returns -1 and sets errno to EINVAL.


Q:

Intercepting GSM communications with an USRP and Gnu Radio

I would like to know what is needed to intercept GSM communications with an USRP (Universal Software Radio Peripheral) and using Gnu Radio.

Is there tutorial about that ?
What type of USRP is recommended ?
Where to find technical documentation about the GSM protocols ?
Is there already existing tools to break the A5/1 encryption ?
...

All in one, my question is more about looking for advices about "where to start ?" when trying to understand GSM communication.

A:

As mentioned above by 0xea, @domi007 published 4 blog posts (1,2,3,4) detailing his experience with GSM sniffing and cracking. He also published his recorded presentation about GSM security (slides).
On the same topic, there's also Sniffing GSM with HackRF, Analyzing GSM with Airprobe and Wireshark, three Chaos Computer Club presentations (One discussing Wideband GSM sniffing, another discussing the functioning of GSM networks) and the one mentioned above about GSM Cracking. Last but not least, there's also a Black Hat 2008 Presentation called "Intercepting Mobile Phone/GSM Traffic", by David Hulton and Steve video (.mov).
Observation : There's also this tutorial by Srlabs, which uses their own tool, Kraken, that covers decrypting GSM using Airprobe and the Airprobe's own tutorial on decoding GSM.
When choosing your SDR, I suggest you read this comparison about HackRF, bladeRF and the USRP B210. There is also RTL-SDR . They are all quite nice. I also suggest using Gqrx as it's built on Gnuradio and has a neat interface.
Architecture and theory wise, I'd recommend About GSM Dm Channels, which is a quite complete and detailed beginner paper that explains the GSM Architecture and how it works. I also recommend GSM - Architecture, Protocols and Services and 4G: LTE/LTE-Advanced for Mobile Broadband (if considering LTE), which provide further information and details about the functioning of GSM for those that want to delve into it.
Regarding GSM Encryption and its flaws, I suggest Instant Ciphertext-Only Cryptanalysis of GSM Encrypted Communication, which discusses ciphertext attacks on A5/(1,2,3), Hardware-based Cryptanalysis of the GSM A5/1 Encryption Algorithm - includes a 2 page brief on A5/1 and then goes on to the cryptoanalysis - and A Practical-Time Attack on the A5/3 Cryptosystem Used in Third Generation GSM Telephony - discusses attacks on A5/3. Finally, there is also Real Time Cryptanalysis of A5/1 on a PC, a very nice document called Security of 3G and LTE that discusses the security architecture and the attacks on it's flaws, and Software Hardware Trade-offs - Applications to A5/1 Cryptanalysis - another nice paper on A5/1. Observations : You can find the specifications for A5/3 in the middle of this page. There are also two Blackhat presentions that cover part of those papers in a succinct way Attacking Phone Privacy and Breaking Phone Privacy. If you like animations, there is an A5/1 Cipher Animation on YouTube. @matthew_d_green deserves to be mentioned, considering he wrote a small synthesis of cellular communications crypto flaws in his blog.
Important observation : The GSM specifications are located in 3GPP's website. To find them, you need to determine the numbering of the part you're looking for. Then, you browse into their ftp server and look for the date and release you fancy. (Releases prior to 2012-13 need to be solicited through their contact mail). Supposing you want the latest "3G and Beyond / GSM" Signalling Protocols specifications, you'll need to browse to their "latest" folder, descend to the release you're looking for (i.e. Release 12), and finally download the "Series" that contain the information you need - which in this case would be "Series 24". Therefore, the result of your endeavor would be : ftp://ftp.3gpp.org/specs/latest/Rel-12/24_series/ .
It's not a good user experience, especially because there are several empty directories, but with patience, you can find what you're looking for.
@gat3way deserves a special mention for documenting his experiments in cracking GSM A5/1 in his blog (1,2,3)  - includes a brief description of the A5/1 mechanism - and the fact that he has implemented support for cracking A5/1 using Pornin's attack in his password recovery tool, hashkill - git commit.
An existing tool to crack A5/1 is Kraken, by srlabs (available through git://git.srlabs.de/kraken.git), which should be used after recording the data with Gnuradio/Gqrx and parsing it with Airprobe. It needs GSM rainbow tables, available at the jump.
Another tool that can be considered is hashkill, which takes the key to be cracked in a "frame_number:keystream" format - it's author published the code for converting a bin burst into the required input format here. He also published a php script to locate suitable SI5/SI6 encrypted bursts for cracking - you'll need to change the hardcoded values for SI5 frames to fit your location -, which, together with Kraken's xortool, gsmframecoder (that will be used to calculate Timing Advance changes) and Airprobe should be sufficient to crack GSM.

A:

@domi007 recently published a series of blog posts detailing his efforts on snooping and decrypting GSM. Insted of USRP, he used rtlsdr. He also used an osmocomBB enabled phone. His efforts build upon the research done by Karsten Nohl on cracking GSM (you can see the video too) and his ~1.5 terabyte of rainbow tables.


Q:

Bigquery Improving the accuracy problems

We have a problem to improve the accuracy of BigQuery, our case of use is the following, we are using a table of 1,600 million record, a table not to large for our issues, and we are trying to find unique users.
Firstly we thought to use a "count distinct", but as the documentation told for a large amount of data you obtain an estimate result. In order to improve this, we are tried "count + group by"  in place of "count distinct" statement. But the result of bigquery is too large response. We have grouped by UserID firstly, and we have continued with this idea but reducing the number of data, choosing a specific campaing, decrementing considerably the amount of data. But the result is the same, response too large.
Any idea or opinion about how to obtain unique users, with accuray in bigQuery?

A:

COUNT(DISTINCT field) returns an approximate answer, as you've realized. You can improve the accuracy by using COUNT(DISTINCT field, n) for a large value of N. The larger this value, the more accurate the result will be, although it may run into 'result too large' errors if you set it too high.
You can get the exact unique count by using GROUP EACH BY. This may make it difficult to calculate other values in the same query, but GROUP EACH BY will work on any size table. For example:
select count(*) from (select field from dataset.table GROUP EACH BY field)


Q:

Call another action from one action of the same controller

I am new to YII. How to call an action from another action of the same controller.
Suppose I am in action A. I need to call action B with two parameters. My controller name is Master Controller. How will I perform this. Please say me a solution. Thanks in advance.
My controller:
class NimsoftController extends Controller
{
    public function actionStore_action($action,$data_id)
    {
          $model= new NimsoftUserLoginAction;
          $model->user_id=Yii::app()->user->id;
          $model->action=$action;//"Deleted";
          $model->affected_data_id=$data_id;//"22";
          $model->save();
    }

    public function actionSearch($id)
    {
        $cust_id = $id;
        $criteria = new CDbCriteria();
        $criteria->condition = "host_customer_id = '$cust_id'";
        $details = NimsoftHost::model()->find($criteria);

        $criteria2 = new CDbCriteria();
        $criteria2->condition = "cust_id= '$details->host_customer_id'";
        $name = MasterCustomers::model()->find($criteria2);

        $dataProvider = new CActiveDataProvider('NimsoftHost', array(
            'criteria' => $criteria,
            'pagination'=>array('pageSize'=>40)
        ));
        $model = new NimsoftHost();
        $this->actionStore_action(array('action'=>'search', 'data_id'=>$cust_id));
        $this->render('index',array(
            'dataProvider' => $dataProvider,
            'details' => $details,
            'name' => $name->cust_name,
            'model' => $model
        ));
    }
}

A:

You can simply call the function directly, or,
$this->actionMyCustomAction(); exit;

you can perform a redirect to the action:
$this->redirect('anotherControllerName/myCustomAction');

or this if you are in the same controller:
$this->redirect('myCustomAction');

UPDATE:
You are passing the variables wrongly:
$this->actionStore_action(array('action'=>'search', 'data_id'=>$cust_id));

It should be two separate variables:
$this->actionStore_action('search', $cust_id);

This has NOTHING to do with Yii. It's only basic function calling.