vendredi 11 septembre 2015

How can I write this relatively simple criteria query involving three domains?

Just for background, let us have these three domain classes:

class Group {
    Long id
    Person person
}

class Person {
    Long id
    Country country
    String name
}

class Country {
    Long id
}

So, with these classes in mind, I am given a Group object's id as well as a Country object's id. I would like to get the list of Person objects based on these two.

It seems relatively simple, but I am new to criteria queries and so I am struggling to figure out what I am doing wrong. This is what I have so far:

def c = Group.createCriteria()
def names = c.list (order: "asc") {
    createAlias('person', 'p')
    createAlias('p.country', 'c')
    and {
        eq ('c.id', Long.valueOf(countryId))
        eq ('id', groupId)
    }
    projections {
        property('p.name')
    }
}

Of course, this is wrong as it is throwing errors. Can someone please let me know what I am doing wrong?

Thanks for your help!



via Chebli Mohamed

CSS Overflow in Chrome 45 and Edge

In MS Edge and Chrome 45, using overflow:auto on one of my site's DIVs hides all the contents. I can resolve this by switching to overflow:visible. But why are these two browsers rendering differently, and how can I avoid the problem in my CSS?



via Chebli Mohamed

How to call a ClearQuest REST API from Visual Studio (C# or VB.Net)

I am trying to find some C#/VB.Net code samples showing how to make ClearQuest Restful API calls.



via Chebli Mohamed

How to implement navigation controller/tab bar controller in React/Flux?

I'm creating a SPA mobile app using React. I'm wondering how I would create a navigation controller or a tab bar controller using the Flux way. Basically I'm wondering how I handle ownership of children and who/what handles the actual transitions.

Right now I have a navigationController component that has a push method to add pages to the stack and transition them in our out. All of this is stored in the state, and the parent component knows nothing about this.

For my tab bar controller, the parent component passes in some tabBar items with the children of the tabBar item being the content to show when the tab is active. The tab bar controller handles when a tab is active and what content to show based on the active tab. The parent doesn't know anything about which tab is active. the active tab is stored in the tab bar controller's state.

Stuff like this just doesn't seem to be easily implemented in Flux. How would I, from the parent, tell a navigation controller to add an element, and then handle the transition from within controller. Also, how would added pages to the controller be able to push new pages if they have to go all the way up to the root?

I guess my problem might be that I don't fully understand Flux.

Any help would be greatly appreciated.



via Chebli Mohamed

Tickspot API: Get token using jQuery ajax

I'm testing the API V2 of tickspot http://ift.tt/1K2gIFM but I'm having some troubles trying to get the token.

$.ajax({
    url: 'http://ift.tt/1O5MB41',
    type: 'GET',
    //jsonp: "callback",
    dataType: 'jsonp',
    crossDomain: true,
    beforeSend: function(xhr) {
        xhr.withCredentials = true;
        xhr.setRequestHeader ("Authorization", "Basic " + btoa(username+":"+password));
        xhr.setRequestHeader('UserAgent','Project (email@company.com)');
    }
})
.done(function(response) {
    callback(response);
})
.fail(function(response) {
    callback(response);
})
.always(function() {
    console.log("complete");
});

I have tried with https and http but I always receive 401 Unauthorized and my credentials are correct.

Hope you can help me.



via Chebli Mohamed

How to run node app behind proxy using Node as delegation container

All:

I am new to Node, say if I want to run an node js app to visit internet behind a proxy, but this app does not support proxy, I wonder how can I use node as its delegation app to get through the proxy?

Thanks



via Chebli Mohamed

Converting my response to JsonObject format

I am fetching LinkedIn profile information upon logging in with your LinkedIn account and trying to send it to my server so I can store it. The response comes back to me in the form of an ApiResponse.

public void onApiSuccess(ApiResponse apiResponse) {
...
serverInteractionManager.sendLinkedInData(dummyJson, PreferenceManager.getPreference("eventId"), PreferenceManager.getPreference("personId"));
...    
}

The ApiResponse class has a getResponseDataAsJSON() method but that returns a JSONObject type as opposed to the JsonObject that I need.

public Future<JsonObject> sendLinkedInData(JsonObject jsonObject, String eventId, String personId) {
        try {
            return sendRequest("api/event/" + eventId + "/signup/" + personId, "").setJsonObjectBody(jsonObject).asJsonObject().setCallback(new FutureCallback<JsonObject>() {
                @Override
                public void onCompleted(Exception e, JsonObject result) {
                }
            });
        } catch (Exception e) {
            return null;
        }
}

Above is the method that sends a post request to my server, where I want to store the LinkedIn information I get after login.
Is there any way to convert between these two types? or convert a String to JsonObject somehow? (I can parse the ApiResponse to a String). I tried using Gson to not much success but I'm not very experienced with it. Cheers!



via Chebli Mohamed

Pausing execution for animation

I am making a simple Simon Says game for practice, but I am having a little trouble.

When the AI plays out the pattern that the user is to immitate, I want it to press the buttons one at a time. There needs to be a little pause between each button press, to allow for the sound and animation to complete.

I am storing the pattern in an array, and using a for loop to cycle through it, like this:

var computerPattern = [1, 2, 3, 4];

for (i=0; i<computerPattern.length; i++){
    setTimeout(function() {
        switch(computerPattern[i]) {
            case 1:
                    beep($("#green"));
                    break;
            case 2:
                    beep($("#red"));
                    break;
            case 3:
                    beep($("#blue"));
                    break;
            case 4:
                    beep($("#yellow"));
                    break;
            default:
                    break;
        }
    }, 250);
}
// Where 'beep' is a function that plays a sound and animation.

As you can see, I am using setTimeout because that's what Ive been able to find throught my research. But it's not working, so maybe my whole approach is wrong.

I would appreciate any suggestions as to how to go about this. Thanks!



via Chebli Mohamed

Jquery Click send doesn't work

Hi everyone i have one question about jquery click send function. I have created this demo from jsfiddle. So if you visit the demo then you can see there is one smiley and textarea. When you write some text and press enter then the message sending successfully. But i want to add also when you click the smiley then it need to send (w1) from the image sticker="(w1)" like click to send. But click send function doesn't work. What is the problem on there and what is the solution ? Anyone can help me in this regard ?

JS

$('.sendcomment').bind('keydown', function (e) {
    if (e.keyCode == 13) {
        var ID = $(this).attr("data-msgid");
        var comment = $(this).val();

        if ($.trim(comment).length == 0) {
            $("#commentload" + ID).text("Plese write your comment!");
        } else {
            $("#commentload" + ID).text(comment);
            $("#commentid" + ID).val('').css("height", "35px").focus();
        }
    }
});
/**/
$(document).ready(function() {
$('body').on("click",'.emo', function() {

        var ID = $(this).attr("data-msgid");
        var comment = $(this).val();

        if ($.trim(comment).length == 0) {
            $("#commentload" + ID).text("nothing!");
        } else {
            $("#commentload" + ID).text(comment);
            $("#commentid" + ID).val('').css("height", "35px").focus();
        }

 });
});
    $('body').on('click', '.sm-sticker', function(event) {
        event.preventDefault();
        var theComment = $(this).parents('.container').find('.sendcomment');
        var id = $(this).attr('id');
        var sticker = $(this).attr('sticker');
        var msg = jQuery.trim(theComment.val());

        if(msg == ''){
            var sp = '';
        } else {
            var sp = ' ';
        }

        theComment.val(jQuery.trim(msg + sp + sticker + sp));
    });

HTML

<div class="container one">
 <div class="comments-area" id="commentload47">comments will be come here</div>
 <div class="user-post" id="postbody47">
    <textarea class="sendcomment" name="comment" id="commentid47" data-msgid="47"></textarea>
    <div class="stiemo">
     <img src="http://ift.tt/1O5MANz" class="sm-sticker emo" sticker="(w1)"> click smiley to send (w1)</div>
   </div>
  </div>
</div>



via Chebli Mohamed

Javascript: Automaticly Count and Display the Number of Words on a Web Page

I was wondering if anyone can assist me with this problem: I am trying to type in code that Automaticly Counts and Displays the Number of Words on a Web Page using JavaScript.

I have searched stack overflow and the internet in general, and there does not seem to be any examples on this that can help. :(

Thank you, any help will be appreciated.



via Chebli Mohamed

Using typecasting to remove gcc compiler warnings

I am doing embedded ARM programming with gcc 4.9. I've been using the -Wconversion switch because it's in my company's default dev tool configuration. I'm using the stdint.h types (uint8_t, uint32_t, etc).

The compiler creates warnings every time I perform a compound assignment or even simple addition. For example:

uint8_t u8 = 0;
uint16_t u16;

// These cause warnings:
u8 += 2;
u8 = u16 >> 8;

The "common method" to fix this is to use casts, as discussed here and here:

u8 = (uint8_t)(u8 + 2);
u8 = (uint8_t)(u16 >> 8);

In addition to this being ugly, I keep running into convincing evidence that casting is generally bad practice.

My questions:

  1. Why is it bad to use typecasts in this way?
  2. Do I lose anything by simply omitting -Wconversion and letting the compiler do implicit conversions for me?


via Chebli Mohamed

PHP background sync using http requests

I have a php coded that is suppose to sync data from thousands of http links every 2 minutes and update the database.

However, some of the websites are too slow, and my current approach which is using foreach and going over the links one by one takes around 15 minutes.

Is there a better way to achieve this task in a shorter time?

foreach($email as $emails) {

imap_open(......);

// update db

}

Thanks



via Chebli Mohamed

Calling non .Net Web service from a .Net application

I'm working on a .Net client application that will consume a non .Net web service via SOAP standard, to calculate and post Sales Tax information for items. There is no .asmx. The web service is authored and maintained by a different group. They provided a WSDL url and said all the XSD schemas I need are present in it. The problem is, it is nested and daisy chained using xsd:import tags, a few levels deep.

I have the web service added to my Visual Studio 2012 Windows Forms project by "Add Service Reference". Calling this web service was not straight forward as it had some additional security requirements.

The web service has 3 operations - HeartBeat, Calculate, Post.

With my very limited knowledge of WCF and some help from another expert, I was able to call the heartbeat function successfully; this was the easiest because it takes no parameters.

My struggle is, how to structure the input to call the other two functions - Calculate and Post ? They both take a strongly typed object as input. How do I construct such a strongly typed object? At the moment, as an experiment, I'm constructing an object based on the proxy classes VS2012 created for the service reference, initializing and populating them with some values manually. Should I use XSD.exe to generate classes for the schemas from WSDL and populate them with the input by deserializing?

Below is the SOAP call to the calculate function. This works when invoked from SoapUI.

<soap:Envelope xmlns:soap="http://ift.tt/18hkEkn" xmlns:v1="http://ift.tt/1O5KI7k">
    <soap:Header/>
    <soap:Body>
        <v1:calculate>
            <CalculateRequest>
                <Context>
                    <!--Optional:-->
                    <SendingApplication>SoapUI</SendingApplication>
                    <!--Optional:-->
                    <UserId>SoapUI</UserId>
                    <!--Zero or more repetitions:-->
                    <LocaleCode>en</LocaleCode>
                    <!--Optional:-->
                    <ApplicationName>SoapUI</ApplicationName>
                </Context>
                <TaxRequestor>
                    <Name>Person X</Name>
                    <!--Optional:-->
                    <!--Optional:-->
                    <AdministrativeAddress>
                        <Line1>888 River Dr</Line1>
                        <City>Queens</City>
                        <County>Queens County</County>
                        <State>NY</State>
                        <PostalCode>11001</PostalCode>
                        <CountryISO3Char>USA</CountryISO3Char>
                    </AdministrativeAddress>
                    <CompanyNumber>1</CompanyNumber>
                </TaxRequestor>
                <Transaction>
                    <!--1 or more repetitions:-->
                    <LineItem>
                        <LineNumber>1</LineNumber>
                        <!--Optional:-->
                        <Item>
                            <!--Optional:-->
                            <Identifier>10134</Identifier>
                            <!--Zero or more repetitions:-->
                            <Name LocaleCode="en-US">Product X</Name>
                            <!--Optional:-->
                            <TaxCode>9876</TaxCode>
                            <Department>
                                <!--Optional:-->
                                <Code>99</Code>
                                <!--Zero or more repetitions:-->
                                <Name LocaleCode="en-US">?</Name>
                            </Department>
                        </Item>
                        <!--Optional:-->
                        <Quantity>10</Quantity>
                        <!--Optional:-->
                        <UnitPrice>
                            <Amount>1000</Amount>
                        </UnitPrice>
                        <ShipFromAddress>
                            <Line1>888 River Dr</Line1>
                            <City>Queens</City>
                            <County>Queens County</County>
                            <State>NY</State>
                            <PostalCode>11001</PostalCode>
                            <CountryISO3Char>USA</CountryISO3Char>
                        </ShipFromAddress>
                        <ShipToAddress>
                            <Line1>1041 New York Rd</Line1>
                            <City>Newark</City>
                            <County>Essex</County>
                            <State>NJ</State>
                            <PostalCode>07054</PostalCode>
                            <CountryISO3Char>USA</CountryISO3Char>
                        </ShipToAddress>
                        <!--Zero or more repetitions:-->
                        <LineItemIdentifier>1</LineItemIdentifier>
                    </LineItem>
                    <LineItem>
                        <LineNumber>1</LineNumber>
                        <!--Optional:-->
                        <Item>
                            <!--Optional:-->
                            <Identifier>98765</Identifier>
                            <!--Zero or more repetitions:-->
                            <Name LocaleCode="en-US">Product X</Name>
                            <!--Optional:-->
                            <TaxCode>Some Tax Code</TaxCode>
                            <Department>
                                <!--Optional:-->
                                <Code>99</Code>
                            </Department>
                        </Item>
                        <!--Optional:-->
                        <Quantity>10</Quantity>
                        <!--Optional:-->
                        <UnitPrice>
                            <Amount>1000</Amount>
                        </UnitPrice>
                        <ShipFromAddress>
                            <Line1>888 River Dr</Line1>
                            <City>Queens</City>
                            <County>Queens County</County>
                            <State>NY</State>
                            <PostalCode>11001</PostalCode>
                            <CountryISO3Char>USA</CountryISO3Char>
                        </ShipFromAddress>
                        <ShipToAddress>
                            <Line1>1008 3rd St</Line1>
                            <City>Lewisville</City>
                            <County>Denton</County>
                            <State>TX</State>
                            <PostalCode>75010</PostalCode>
                            <CountryISO3Char>USA</CountryISO3Char>
                        </ShipToAddress>
                        <!--Zero or more repetitions:-->
                        <LineItemIdentifier>1</LineItemIdentifier>
                    </LineItem>
                </Transaction>
            </CalculateRequest>
        </v1:calculate>
    </soap:Body>
</soap:Envelope>

Please help with your advice and recommendations. Thank you. Using VS2012, .Net 4.5, C#



via Chebli Mohamed

ProcessBuilder results in cannot run programm

Following command works directly in console (debian):

xvfb-run --server-args="-screen 0, 1024x768x24" cutycapt --url='https://www.google.com' --out=/home/admin/screenshot_name_new.png

Now i'm trying to make this work in ProcessBuilder, i tried following two things:

List<String> processArguments = new ArrayList<String>();
processArguments.add("/usr/bin/xvfb-run");
processArguments.add("--server-args=\"-screen 0, 1024x768x24\" /usr/bin/cutycapt");
processArguments.add("--url=https://www.google.com");
processArguments.add("--out=/home/admin/screenshot_name_new.png");
ProcessBuilder pb = new ProcessBuilder(processArguments);
Process p = pb.start();

Not working: /home/admin/screenshot_name_new.png (No such file or directory)

ProcessBuilder pb = new ProcessBuilder("/usr/bin/xvfb-run --server-args=\"-screen 0, 1024x768x24\" /usr/bin/cutycapt --url='https://www.google.com' --out="/home/admin/screenshot_name_new.png);

results in:

 Cannot run program "\usr\bin\xvfb-run --server-args="-screen
 0,1024x768x24" \usr\bin\cutycapt --url='https://www.google.com'
 --out=/home/admin/screenshot_name_new.png": error=2, No such file or directory

What am i doing wrong?



via Chebli Mohamed

Entity Framework is not providing me IDs when calling back

I'm using a ViewModel (RoleVM) with a collection of ViewModels (RolePermissionVM) for this particular edit view. The view displays the RoleVM fields, and a checkbox list of RolePermissionVM. Each row in the checkbox list has a hiddenFor for the ID of the RolePermission.

When I save the form, my controller correctly writes the data to the database, adding or updating records. However, I would like the user to remain on the page, so I call the View again, but trying to get an updated model so that I have the IDs for any newly created RolePermissionVM objects. I am not getting the new IDs into the HiddenFor fields.

Here's my class:

public class RolePermissionVM
{
    public int? RolePermissionId { get; set; }
    public int RoleId { get; set; }
    public int PermissionId { get; set; }
    public string PermissionName { get; set; }

    public bool IsActive { get; set; }
}

My controller code:

    private RoleVM GetRoleVm(int id)
    {
        var thisRoleVm = (from r in db.Role
            where r.RoleId == id
            select new RoleVM
            {
                RoleId = r.RoleId,
                RoleName = r.RoleName,
                RoleDescription = r.RoleDescription,
                OwnerId = r.OwnerId,
                IsActive = r.IsActive
            }).FirstOrDefault();
        thisRoleVm.RolePermission = (from p in db.Permission
                                     join rPerm in
                                         (from rp in db.RolePermission
                                          where rp.RoleId == id
                                          select rp)
                                         on p.PermissionId equals rPerm.PermissionId into pp
                                     from rps in pp.DefaultIfEmpty()
                                     select new RolePermissionVM
                                     {
                                         RolePermissionId = (int?)rps.RolePermissionId,
                                         RoleId = id,
                                         PermissionId = p.PermissionId,
                                         PermissionName = p.PermissionName,
                                         IsActive = (rps.IsActive == null ? false : rps.IsActive)
                                     })
                                     .OrderBy(p => p.PermissionName).ToList();
        return thisRoleVm;
    }

    [HttpPost, ActionName("_roleedit")]
    [ValidateAntiForgeryToken]
    public ActionResult _RoleEdit(RoleVM editedRole)
    {
        //...

        if (ModelState.IsValid)
        {
            var dbRole = db.Role.Find(editedRole.RoleId);
            dbRole.RoleName = editedRole.RoleName;
            dbRole.RoleDescription = editedRole.RoleDescription;
            dbRole.OwnerId = editedRole.OwnerId;

            foreach (var thisPerm in editedRole.RolePermission) // RolePermission here is the ViewModel, not the actual model
            {
                if (thisPerm.RolePermissionId != null && thisPerm.RolePermissionId > 0)
                {
                    // We have a record for this, let's just update it
                    var thisRolePerm =
                        dbRole.RolePermission.FirstOrDefault(rp => rp.RolePermissionId == thisPerm.RolePermissionId);
                    thisRolePerm.IsActive = thisPerm.IsActive;
                    db.Entry(thisRolePerm).State = EntityState.Modified;
                }
                else
                {
                    if (thisPerm.IsActive)
                    {
                        // New and active, so we add it
                        dbRole.RolePermission.Add(new RolePermission
                        {
                            RoleId = editedRole.RoleId,
                            PermissionId = thisPerm.PermissionId,
                            IsActive = true
                        });
                    }
                }
            }

            db.Entry(dbRole).State = EntityState.Modified;
            db.SaveChanges(User.ProfileId);

            var newEditedRole = GetRoleVm(editedRole.RoleId); // We don't get the new IDs here, but I would like to
            newEditedRole.ResponseMessage = "Saved Successfully";

            return View(newEditedRole); // This should have the new RolePermissionId values, but it doesn't.
        }
    editedRole.ResponseMessage = "Error Saving";
        return View(editedRole);
    }

The partial view used for each row of the CheckBox list:

@using PublicationSystem.Tools
@model PublicationSystem.Areas.Admin.Models.RolePermissionVM

<li class="editorRow ui-state-default removable-row">
    @using (Html.BeginCollectionItem("RolePermission"))
    {
        <div class="row">
            @Html.HiddenFor(model => model.RolePermissionId)
            @Html.HiddenFor(model => model.RoleId)
            @Html.HiddenFor(model => model.PermissionId)
            @Html.HiddenFor(model => model.PermissionName)

            <div class="col-md-7">
                @Html.DisplayFor(model => model.PermissionName, new {htmlAttributes = new {@class = "form-control"}})
            </div>
            <div class="col-md-3">
                @Html.CheckBoxFor(model => model.IsActive, new { htmlAttributes = new { @class = "form-control" } })
            </div>
    </div>
    }
</li>

So, why do the new database generated IDs not get pulled back? How can I fix that? Is there a more efficient way to do this?



via Chebli Mohamed

Oracle Spool using Dynamic SQL

I'm trying to pass a dynamic SQL statement to spool out to a text file using SQL*Plus, but I can't seem to execute the select statement I'm generating.

set linesize 10000 pagesize 0 embedded on
set heading off feedback off verify off trimspool on trimout on  termout off
set underline off

COLUMN gen_sql   NEW_VALUE gen_sql_
SELECT 'SELECT * FROM USER_TAB_COLS WHERE ROWNUM < 10' gen_sql_ FROM DUAL;

SPOOL 'myfilename.csv'

EXECUTE IMMEDIATE &gen_sql_

SPOOL OFF
/

I can't seem to use EXECUTE IMMEDIATE. Is there another way to execute the results of the select statement??

MORE DETAIL:

I have a set of views whose output I'd like to generate as formatted CSV files. I'm using dynamic SQL to create the formatting essentially. I generate something similar to:

SELECT TRIM(col1)||','||TRIM(col2)...FROM {myview}

I'm using the following to generate it this way:

COLUMN gen_sql   NEW_VALUE gen_sql_
SELECT 'SELECT ' || LISTAGG ('TRIM('||COLUMN_NAME||')', '||'',''|| ') 
     WITHIN GROUP (ORDER BY COLUMN_ID) gen_sql FROM...

Anyway, I'm able generate this SQL statement and store into a SQL*PLUS variable, but I just need to execute it after the SPOOL statement so that it will print to the file. I'm not sure how to execute it. Normal statements work, such as:

SPOOL 'myfilename.csv'
SELECT 1 col1 FROM DUAL;
SPOOL OFF
/

So, it would seem reasonable that I could something similar but executing the contents of my variable like:

SPOOL 'myfilename.csv'
--- RUN MY DYNAMIC SQL ----
SPOOL OFF
/



via Chebli Mohamed

Merge multiple data tables with the same column names

I am trying to merge multiple data tables (obtained with fread from 5 csv files) to form a single data table. I get an error when I try to merge 5 data tables, but works fine when I merge only 4. MWE below:

# example data
DT1 <- data.table(x = letters[1:6], y = 10:15)
DT2 <- data.table(x = letters[1:6], y = 11:16)
DT3 <- data.table(x = letters[1:6], y = 12:17)
DT4 <- data.table(x = letters[1:6], y = 13:18)
DT5 <- data.table(x = letters[1:6], y = 14:19)

# this gives an error
Reduce(function(...) merge(..., all = TRUE, by = "x"), list(DT1, DT2, DT3, DT4, DT5))

Error in merge.data.table(..., all = TRUE, by = "x") : x has some duplicated column name(s): y.x,y.y. Please remove or rename the duplicate(s) and try again.

# whereas this works fine
Reduce(function(...) merge(..., all = TRUE, by = "x"), list(DT1, DT2, DT3, DT4))

    x y.x y.y y.x y.y 
 1: a  10  11  12  13 
 2: b  11  12  13  14 
 3: c  12  13  14  15 
 4: d  13  14  15  16 
 5: e  14  15  16  17 
 6: f  15  16  17  18

I have a workaround, where, if I change the 2nd column name for DT1:

setnames(DT1, "y", "new_y")

# this works now
Reduce(function(...) merge(..., all = TRUE, by = "x"), list(DT1, DT2, DT3, DT4, DT5))

Why does this happen, and is there any way to merge an arbitrary number of data tables with the same column names without changing any of the column names?



via Chebli Mohamed

D3-After Loading different data, clicking the brush makes line-graph disappear

I've made a line graph with a brush to zoom in. The first time I load the csv file, the brush works correctly. Problem is, after I load a different csv file from the dropdown menu, just clicking on the brush makes the line disappear. I haven't seen any examples showing something like that, so can anyone help? Here is the result plunker

And here is the code of the graph:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>D3 Test</title>
        <script type="text/javascript" src="../d3/d3.js"></script>
        <script type="text/javascript" src="../d3/d3-tip.js"></script>
        <style type="text/css">
            body{
                font: 16px Calibri;
            }

            .line{
                fill: none;
                stroke: steelblue;
                stroke-width: 2px;
            }

            .brushLine{
                fill: none;
                stroke: steelblue;
                stroke-width: 2px;
            }

            .brush .extent{
                strokg: #fff;
                fill-opacity: .125;
                shape-rendering: crispEdges;
            }

            .axis path,
            .axis line{
                fill:none;
                stroke: black;
                stroke-width: 1px;
                shape-rendering: crispEdges;
            }

            .axis text{
                font-family: sans-serif;
                font-size: 14px;
                stroke: black;
                stroke-width: 0.5px;
            }

        </style>
        <!--...this code will be used on an external html file and instered-->
        <?php
            include('../dropdownMetrics.php');
        ?>
        <!--...............................................................-->
    </head>
    <body>
        <script type="text/javascript">


var margin = {top: 60, right: 20, bottom: 40, left: 40},
    margin2 = {top: 430, right: 20, bottom: 20, left: 40},
    width = 800 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom,
    height2 =900 - margin2.top,
    height3= 500 - margin2.top - margin2.bottom;

var x = d3.scale.linear()
    .range([0, width]);

var x1 = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var y1 = d3.scale.linear()
    .range([height3, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var x1Axis = d3.svg.axis()
    .scale(x1)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var brush = d3.svg.brush()          
            .x(x1)
            .on("brush", brushed);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height2 + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

//-------------------------defining focus and context------------------------
var focus = svg.append("g")
            .attr("class","focus");

var context = svg.append("g")
            .attr("class","context")
            .attr("transform", "translate(" + 0 + "," + margin2.top + ")");

//-------------------------defining the focus and brush lines----------------           
var line = d3.svg.line()
        .x(function(d) { return x(d.trID);})
        .y(function (d) {return y(d.newT);})
        .interpolate("basis");

var brushLine = d3.svg.line()
        .x(function(d) { return x(d.trID);})
        .y(function (d) {return y1(d.newT);})
        .interpolate("basis");

//---------------------------------------------------------------------------

var dsv = d3.dsv(";", "text/plain");    //setting the delimiter
var dataset = []                        //defining the data array
var datapath="../CSV/atlas/results/metrics.csv";
    dsv(datapath, function(data){   //------------select the file to load the csv------------

        var label = document.getElementById('opts')[document.getElementById('opts').selectedIndex].innerHTML;//takes the name of the f
        console.log(label);

        dataset= data.map(function(d){      //parse
            return {                        //insert parsed data in the array
                trID: +d["trID"],
                newT: +d["#newT"]
            };
        });

        console.log(dataset);
        x.domain(d3.extent(dataset, function(d) { return d.trID; }));
        x1.domain(x.domain());
        y.domain(d3.extent(dataset, function(d) { return d.newT; }));
        y1.domain(y.domain());

        focus.append("path")
            .datum(dataset)
            .attr("class", "line")
            .attr("d", line);


        focus.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis)
            .append("text")
            .attr("class", "label")
            .attr("x", width)
            .attr("y", -6)
            .style("text-anchor", "end")
            .text("trID");

        focus.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("class", "label")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text("num of tables");

        context.append("path")
            .datum(dataset)
            .attr("class", "brushLine")
            .attr("d", brushLine);


        context.append("g")
            .attr("class", "x1 axis")
            .attr("transform", "translate(0," + height3  + ")")
            .call(x1Axis)
            .append("text")
            .attr("class", "label")
            .attr("x", width)
            .attr("y", -6)
            .style("text-anchor", "end")
            .text("trID");

        context.append("g")
            .attr("class","x brush")
            .call(brush)
            .selectAll("rect")
                .attr("y", -6)
                .attr("height", height3 +7);

        svg.append("text")
            .attr("class","simpletext")
            .attr("x", (width/2))
            .attr("y", 0 - (margin.top/2))
            .attr("text-anchor", "middle")
            .style("font-size", "20px")
            .style("text-decoration", "underline")
            .text(label);
    });

    d3.select('#opts')
        .on('change', function(){
            var dataset=[]
            var datapath = eval(d3.select(this).property('value'));
            label = document.getElementById('opts')[document.getElementById('opts').selectedIndex].innerHTML;


            dsv(datapath, function(data){   //------------select the file to load the csv------------
                dataset= data.map(function(d){      //parse
                    return {                        //insert parsed data in the array
                    trID: +d["trID"],
                    newT: +d["#newT"]
                    };
                });


            x.domain(d3.extent(dataset, function(d) { return d.trID; }));
            x1.domain(x.domain());
            y.domain(d3.extent(dataset, function(d) { return d.newT; }));
            y1.domain(y.domain());

            d3.selectAll(".line")
                .transition()
                .duration(1000)
                .attr("d", line(dataset));

            //Update Axis
            //Update X axis
            focus.select(".x.axis")
                .transition()
                .duration(1000)
                .call(xAxis);

            //Update Y axis
            focus.select(".y.axis")
                .transition()
                .duration(1000)
                .call(yAxis);

            focus.selectAll("path")
                .data(dataset)
                .exit()
                .remove();
                console.log(label);

            d3.selectAll(".brushLine")
                .transition()
                .duration(1000)
                .attr("d", brushLine(dataset));

            context.select(".x1.axis")
                .transition()
                .duration(1000)
                .call(x1Axis);

            context.select(".x.brush")
                .call(brush);

            svg.selectAll(".simpletext")
                .transition()
                .text(label);


        });
    });

function brushed(){
        x.domain(brush.empty()? x1.domain() : brush.extent());
        focus.select(".line")
            .attr("d", line);
        focus.select(".x.axis").call(xAxis);
}
        </script>
    </body>
</html>   



via Chebli Mohamed

SQL Server insert missing record with select distinct or left join

I have a table where is some case we are missing the location record for location = 'WHS1'. You will notice the bottom 2 "TCODE's" do not have a location = WHS1 record I was thinking of doing a select distinct on TCODE InvYear and to get unique records then checking to see if the Location 'WHS1' NOT Exist.

I'm very green at this that you for any help

TCODE   InvYear Location    StartingInv Adjustments Damages EndingInv
NY530-1 2015    BRX         625         NULL        NULL    709
NY530-1 2015    LAN         365         NULL        NULL    365
NY530-1 2015    WHS1        432         NULL        NULL    442
NY530-2 2015    BRX         309         NULL        NULL    413
NY530-2 2015    LAN         94          NULL        NULL    96
NY530-2 2015    WHS1        1310        NULL        NULL    1344
NY547-1 2015    BRX         0           NULL        NULL    0
NY547-2 2015    BRX         0           NULL        NULL    0



via Chebli Mohamed

Python - Trying to use a list value in an IF statment

I need to ask a user to input a question that will be compared to a list. The matched word will be displayed and then linked to an option menu. I have added the code below. I have managed to get the the program to search the input and return the word in the find list if a match appears. However I can not figure out how to use the result in an if statement as it is not a string value. I know there is a long way of doing this but is there a simple way of changing 'result' to a string value?

import re
question = input("Please enter your problem:")
find=["display","screen","battery"]
words=re.findall("\w+",question)
result=[x for x in find if x in words]
print (result)
if result in find:
    print("Is your display not working?")
else:
    print("Hard Luck")

Sorry I forgot to say that the outcome of the match will result in a different if statement being selected/printed. For example - If the 'question' used the word 'display' then an IF statement suggesting a solution will be printed, elif the 'question' used the word 'screen' then I elif for a solution to a broken screen will be printed and elif 'question' used 'battery' elif solution to charge the battery will be printed. The problem is I can not change 'result' to a str value to use in an IF statement. I can not check - if result=="display".. or if result=="screen".. or if result=="battery"...



via Chebli Mohamed

Unable to build in Appcelerator Studio

I have a problem with Appcelerator Studio. The build process stucks for a little to:

[INFO] :   Running dexer: C:\Program Files\Java\jdk1.8.0_60\bin\java.exe "-Xmx512M" "-XX:-UseGCOverheadLimit" "-Djava.ext.dirs=C:\android-sdk-win\platform-tools" "-jar" "C:\android-sdk-win\build-tools\23.0.1\lib\dx.jar" "--dex" "--output=C:\Users\vasilis\Documents\Titanium Projects\pop\build\android\bin\classes.dex" "C:\Users\vasilis\Documents\Titanium Projects\pop\build\android\bin\classes" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\lib\titanium-verify.jar" "C:\ProgramData\Application Data\Titanium\modules\android\ti.map\2.2.3\map.jar" "C:\ProgramData\Application Data\Titanium\modules\android\ti.map\2.2.3\lib\google-play-services.jar" "C:\ProgramData\Application Data\Titanium\modules\android\ti.cloudpush\3.4.0\cloudpush.jar" "C:\ProgramData\Application Data\Titanium\modules\android\ti.cloudpush\3.4.0\lib\aps-cloudpush-1.1.4.jar" "C:\ProgramData\Application Data\Titanium\modules\android\ti.cloudpush\3.4.0\lib\google-play-services-base.jar" "C:\ProgramData\Application Data\Titanium\modules\android\ti.cloudpush\3.4.0\lib\google-play-services-gcm.jar" "C:\Users\vasilis\Documents\Titanium Projects\pop\modules\android\ti.sq\0.2\tisq.jar" "C:\Users\vasilis\Documents\Titanium Projects\pop\modules\android\com.gbaldera.titouchgallery\1.1\titouchgallery.jar" "C:\Users\vasilis\Documents\Titanium Projects\pop\modules\android\com.rkam.swiperefreshlayout\0.5\swiperefreshlayout.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\kroll-v8.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-analytics.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\aps-analytics.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-android.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\jaxen-1.1.1.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\ti-commons-codec-1.3.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\kroll-common.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\titanium.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-app.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-ui.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\nineoldandroids-appc-2.4.0.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-filesystem.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-media.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-appcompat.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\android-support-v4.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\android-support-v7-appcompat.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-locale.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-network.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\thirdparty.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-xml.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-utils.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-geolocation.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-accelerometer.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-contacts.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-map.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-calendar.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-gesture.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-platform.jar" "C:\ProgramData\Titanium\mobilesdk\win32\3.5.1.GA\android\modules\titanium-database.jar"

and then reuturns me an error

"Failed to run dexer"

I've tried to uninstall everything, including the Android SDK and install again but with no success

My system has Windows 8.1 OS 64-bit, an i run both 32bit and 64bit versions of Java because I'm learning this period Android Studio.



via Chebli Mohamed

Heroku migrate app to private space

Heroku introduced "private spaces", is it possible to migrate an existing app to a private space? http://ift.tt/1VPLEhF



via Chebli Mohamed

Laravel hide files on server

Currently I've put my laravel site online (just for testing). But when I go to for example www.mysite.nl/.env it shows my password etc. for my database. How can I prevent this?



via Chebli Mohamed

Split up latest commits into multiple branches

I'm aware of several questions on the subject, but I didn't find any that address this situation. The trick is that I need to pull one commit out from between two others.

My repo looks like this:

A - B - C     <- master
          \
            D  <- devel

and I want it to look like this:

    C  <- feature1
  /
A
  \
    B - D  <- feature2

I know I can probably use rebase for this, but after a year of using Git I'm still not clear on all the jargon.



via Chebli Mohamed

Handling text containing both quote types

I want to append the following text to a file in Linux:

echo He said "I can't append this" >> file.txt
cat file.txt
He said I can't append this

How do I include both sets of quotes in the appended string?



via Chebli Mohamed

Angular ng-repeat best practice to only watch for updates inside the specific iteration

I need to render a table in which the user is allowed to edit some fields for each row, fields that will affect other fields in the same row.

For this reason I could not use bind-once on all the data I'm rendering.

If I got it right, simply using a code like the following

<table class="table table-bordered table-condensed table-hover">
  <thead>
    <tr class="info">
      <th>Header</th>
      <th>Header</th>
      <th>Header</th>
      <th>Header</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="a in alist">
      <td>{{::a.id}}</td>
      <td>{{::a.cod}}</td>
      <td>
        <input
          ng-model="a.sel"
          type="checkbox"
          class="input-sm"></input>
      </td>
      <td ng-if="a.sel">
        {{::a.desc}}
      </td>
      <td ng-if="!a.sel">
        "Other Content"
      </td>
    </tr>
  </tbody>

will cause that for each time a user checks or uncheks the a.sel checkbox, all the angular {{vars}} in the page (not the {{::vars}}) will be watched for changes.

If this is true (and therefore that's the reason why page is slow when hundreds of rows are loaded) how could I tell angular I only want it to check if something has changed inside that specific row, that specific ng-repeat iteration?

Not sure how to proceed to get good performances, any other tips are appreciated.

Thank you for your help.



via Chebli Mohamed

Accessing environment variables in python

Why does this not print out 'xxx'?

$ SECRET_KEY='xxx' python -c 'import os; print os.environ['SECRET_KEY']'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'SECRET_KEY' is not defined



via Chebli Mohamed

Groovy half-exclusive range strange behaviour

Why is Groovy showing this behaviour when using half-exclusive range. It is supposed to return all but the last element in the range but it sometimes show all elements in the range plus one.

This is the sample.

 class Weekday implements Comparable {
    static final DAYS = [
        'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
    ]
    private int idx = 0

    Weekday(index)     { idx = index }
    Weekday next()     { new Weekday(idx+1) }
    Weekday previous() { new Weekday(idx+1) }
    int compareTo(Object other) { this.idx <=> other.idx }

    String toString() {
        def index = idx % DAYS.size()
        while (index < 0 ) index += DAYS.size()
            DAYS[index]
    }
}

def mon = new Weekday(1)
def fri = new Weekday(5)

7.times { mon++ } // Monday following week

println fri.idx   //  5
println mon.idx   //  8

println 5 .. 8    // [5, 6, 7, 8]
println fri..mon  // [Fri, Sat, Sun, Mon] Ok without half-exclusive
println 5 ..< 8   // [5, 6, 7]
println fri..<mon // [Fri, Sat, Sun, Mon, Tue] ????????



via Chebli Mohamed

ui-router: intermediate templates

We are building a website with Angular Material and ui-router, and all our content page share the same "container", because we always want the same responsive behaviour.

The code of this generic container would be something like:

  <div class="layout-content">
    <div layout="column" layout-align="center">
      <div layout="row" layout-align="center center">
        <section class="layout-fixed-width md-whiteframe-z1" flex-sm="100" flex-gt-sm="90">

        {{content placed here}}

        </section>
      </div>
    </div>
  </div>

The header can differ in all pages, so the structure we have would basically be:

enter image description here

The question is, how can this be achieved in ui-router? We have done some nested views, but I don't see how to do a generic template so the code could be something like:

<form>
  <md-toolbar>
      <div ui-view="generic-template">
          <div ui-view="my-content"></div>
      </div>
  </md-toolbar>
</form>

Ideally we would want to define only one time the generic-template view, and use it in all our modules.

In the nested states and nested views documentation I see mostly nested state stuff, but what we want is really only a plain html template, so maybe we are over-complicating this, and an easier way is possible (I'm quite sure it's the case). I've also checked this issue, where one of the answers say that ui-router should be the solution, but not much more.

Maybe we should do a directive instead?



via Chebli Mohamed

open source html rendering engine suitable for java webbrowser

is There any rendering engine which support HTML5 css3 and javascript etc , I want to use it in my web browser project in java or any other suggestion for me ?



via Chebli Mohamed

Checkbox true if two values match in ng-repeat loop

Does anyone have an example, or know how to check a checkbox within an ng-repeat if two or more values are true?

Example:

<div ng-repeat="x in retults">
     <input type="checkbox" ng-checked="x.val1 == true && x.val2 == true" />
<div>

Thanks!



via Chebli Mohamed

Modifying Array Data

I have to constantly add data to my NSMutableArray to index 0.

  MyVariables.MutableChatUser.insertObject(MyVariables.username, atIndex: 0)

Goal: I'm copying NSArray to NSMutableArray. If the array contains indexes 0,1,2,3. I then write a new object to index 0. I still have index 0,1,2,3 but I now lost the previous value on index 3 because everything got shifted over. Why isn't index 4 being created?



via Chebli Mohamed

Changing a class variable within __init__

I was looking at the Stack Overflow question Counting instances of a class?, and I'm not sure why that solution works and one using simple addition doesn't. I guess this is more of a question of how class vs. instance variables are stored and accessed.

Here's the code I think should work, but instead produces 4 for every id:

class foo():
      num = 3    # trying 3 instead of 0 or 1 to make sure the add is working

      def __init__(self):
        self.num += 1
        self.id = self.num

f = foo()
g = foo()

print f.id    # 4
print g.id    # 4

The self.num +=1 statement is somewhat working (the addition is happening, but not the assignment).

What is happening under the hood that's making this assignment fail here, while the itertools.count assignment succeeds in the other question's solution?



via Chebli Mohamed

How do I store changed values into a JavaScript object?

I have this JS object that is stored in a file called garage.js:

var myObject = {
 "cars": [
       {
        "type": "mustang",
        "body": {
          "length": 10.7,
          "width": 5.8,
          "color" : "#fff"
          }
        },
       {
        "type": "corvette",
        "body": {
          "length": 11.9,
          "width": 5.6,
          "color": "#000"
         }
   }]
};

When I make changes to the width wtihin a JS function within html, like this:

myObject.cars[0].body.width = 6

and then check the variable to see if the value has been updated, like this:

console.log(myObject.cars[0].body.width = 6)

the console prints 6... but it does not change the value in the stored object in garage.js... (how do I do this?)

The value appears to be represented locally but I need it to actually write this updated value back to the garage.js file so that it is stored permanently, so that when I refresh the html in the browser, the new value, 6, will have replaced the old value, 5.8, in the myObject object.

Do I need to use JSON.stringify and JSON.parse? ... or is it much simpler than that?



via Chebli Mohamed

Bluetooth LE restricting availability in Play Store

My app uses Bluetooth LE but it's not required, I've added:

 <uses-feature
  android:name="android.hardware.bluetooth_le"
  android:required="false" />

Into the manifest but I'm still seeing it listed as a feature when uploading the apk to play store.

Eligibility of devices has plummeted since adding this permission and not sure if this is a bug in the android framework or I'm missing something.



via Chebli Mohamed

Rspec - how do I call a GET and send flash message?

I know it is strange to be passing this data via flash, but there's some (likely flawed) logic for why it's happening and rather than rewire it right now, I wanted to try to get this test working. The test keeps returning the :error template when it should return the :success based on a legit flash[:thing_id] (the actual app behavior works).

From Controller:

def post_multiple_new
  @thing = Thing.find_by_id(flash[:thing_id].to_i)
  unless @thing
    render :error
  else
    render :success
  end
end

From Spec:

context 'when valid id' do
  let(:thing) { create(:thing) }
  let(:flash) { {thing_id: thing.id.to_s} }
  it 'renders correctly' do
    get :post_multiple_new
    expect(response).to render_template(:success)
  end
end



via Chebli Mohamed

homestead.yaml not found in homestead folder

I follow the tutorial in laracast about configuring homestead.

I created folder called myprojects in c:/ drive then I do cd myprojects, once I get inside I issue the following command in cmd git clone http://ift.tt/SBuys2 Homestead

After downloading the file, the tutoirial says edit the homestead.yaml but I could not find in the directory. I am installing this in windows 8.1.

Thank you in advance.



via Chebli Mohamed

Iterating efficiently through indices of arbitrary order array

Say I have an arbitrary array of variable order N. For example: A is a 2x3x3 array is an order 3 array with 2,3, and 3 dimiensions along it's three indices.

I would like to efficiently loop through each element. If I knew a priori the order then I could do something like (in python),

#for order 3 
import numpy as np
shape = np.shape(A)
i = 0
while i < shape[0]:
  j = 0
  while j < shape[1]:
    k = 0
    while k < shape[2]:
      #code using i,j,k
      k += 1
    j += 1
  i += 1

Now suppose I don't know the order of A, i.e. I don't know a priori the length of shape. How can I permute the quickest through all elements of the array?



via Chebli Mohamed

DriveApp.getFileById returns cannot find PDF

I've been using the below coding for months with no problems. But this month, I am getting a return of a message that the PDF file cannot be found. I checked the execution transcript and it does find the files but gets stuck with the below coding. Can you help me to correct this issue?

//uses the excelFiles (name of file) to get the unique ID for each so that Gmail app can attach to each email     
    while (excelFiles.hasNext()) {
      var excelFile = excelFiles.next();
      var excelFileIds = (excelFile.getId());
      var excelAttachFiles = DriveApp.getFileById(excelFileIds);
    };
  //uses the pdfFiles (name of file) to get the unique ID for each so that Gmail app can attach to each email  
    while (pdfFiles.hasNext()) {
      var pdfFile = pdfFiles.next();
      var pdfFileIds = (pdfFile.getId());
      var pdfAttachFiles = DriveApp.getFileById(pdfFileIds);
    };

   //if the pdf and excel file match vendor number, then Gmail will send email with both attachments and will log a 'Success!'
    if (pdfFile == "V" + vendorNumber + " P" + period + " 2015 Import Retail.pdf" && excelFile == "v" + vendorNumber + ".xlsx") { 
    Logger.log("V" + vendorNumber + " Success!");

    sentWithoutException.push(vendorNumber);



via Chebli Mohamed

Make regex betterer

I need an expression that covers two eventualities:

www.example.com
knowledge.example.com

There are many other possible subdomains so it needs to be specifically either the root domain or the knowledge domain.

I did have a go and this appears to work. But it looks long and unsightly and I wondered if there was a more elegant regex:

(www\.)?(knowledge\.)?(example\.com)

It's not that long and ugly, I suppose. I'm just curious if I'm approaching it right or if there's a shorter way of writing it.



via Chebli Mohamed

Pymongo not parsing like JSON

I have a JSON doc like the following:

x = {'ALPHA':{'A':{ 'T1':{ 'L':{'a':1,
                                    'b':2,
                                    'c':3,},

                                'S':{'a':1,
                                     'b':2,
                                     'c':3,}},

                        'T2':{'L':{'a':1,
                                   'b':2,
                                   'c':3,},

                               'S':{'a':1,
                                    'b':2,
                                    'c':3,}},

                        'T3':{'L':{'a':1,
                                    'b':2,
                                    'c':3,},

                               'S':{'a':1,
                                    'b':2,
                                    'c':3,}}
                        }
              }
     }

Where I can parse normally getting 'A', with a standard x['ALPHA']['A']. I thought the mongoDB equivalent would be mongo.find_one({'ALPHA':'A'}), but I am confused about this. Maybe I am creating the documents incorrectly?

Here is the case:

import pymongo

mong  =  pymongo.Connection()['ALPH']['AZ']

letter_dict = ('A','B','C','D')
for letter in letter_dict:
    x = {'ALPHA':{letter :{ 'T1':{ 'L':{'a':1,
                                        'b':2,
                                        'c':3,},

                                    'S':{'a':1,
                                         'b':2,
                                         'c':3,}},

                            'T2':{'L':{'a':1,
                                       'b':2,
                                       'c':3,},

                                   'S':{'a':1,
                                        'b':2,
                                        'c':3,}},

                            'T3':{'L':{'a':1,
                                        'b':2,
                                        'c':3,},

                                   'S':{'a':1,
                                        'b':2,
                                        'c':3,}}
                            }
                  }
         }

    mong.insert(x)

But when I try searching for 'A', It is either finding None, or returning a cursor, or an object id:

mong.find_one({'ALPHA':'A'})
>>>None
mong.find_one({},{'A':1})
>>>{u'_id': ObjectId('55f2eeb7c8b582120834de8f')}

Can someone give a hand?



via Chebli Mohamed

How to get frame rate and stream count information of video files into a text file with using MediaInfo?

I have a problem with a console command executed from within a batch file in a command prompt window on Windows 7. I want to get the frame rate and the number of audio streams of a video and write them into a text file. For the frame rate there is no problem, I run this command from a batch file:

for %%a in (C:\Documents) do (
    echo.
    Mediainfo --Inform=Video;%%FrameRate%% %%a
)>> "D:\TestFrame2.txt"

But for the number of audio streams, it returns an empty text and there is no error message. I use exactly the same batch file, but I replaced Video by Audio and FrameRate by StreamCount.

I see these parameters when I run Mediainfo --Help-Inform.

And also a lot of others options like Mediainfo --Inform=General;%%AudioCount%% don't work.

I have tested already to replace Inform by Output and there is no change. And I have tested also to use this command directly in the console window without redirecting the results into a text file and it's the same thing.

What is the reason for not getting number of audio streams written to the text file?



via Chebli Mohamed

Data points shifting when I change X-axis to dates

I am trying to have my plot show dates for the X axis I posted pictures showing how the graph is supposed to look and what I would like to change.

This is with integers for the X axis

How do I get the figure below to have the error bars as the figure above to cover the figure below.

Dates as X axis



via Chebli Mohamed

Search form issues

I need to build a search form for on a WP website, and I've been struggling with it for a week now, can't seem to find the right solution.

I have this code now:

<form role="search" method="get" id="searchform" action="http://ift.tt/1FBZoTY">
<div class="filterbox">
 <div class="search_group1">
    <label class="screen-reader-text-1" for="s">Country</label>
 <input type="text" value="" placeholder="" name="s" id="s" class="text_box_country"/>
</div>
<div class="search_group2">
 <label class="screen-reader-text-2" for="f">Expertise</label>
 <input type="text" value="" placeholder="" name="f" id="f" class="text_box_expertise"/>
</div>
 <div class="search_group3"> 
 <input type="submit" class="btn_double_search" id="searchsubmit" value="Search" />
 </div>
</div>
</form>

I already narrowed the search results down by only letting it search in the titles instead of content aswell.

But it displays all results with the first or second searchword in it, where I want it to display only the results where it has both.

Website is http://ift.tt/1FBZoTY

I also tried to change the first search box into a dropdown with categories (as all the countries are different categories, but then the outputted search results get really weird:

http://ift.tt/1MgMPF6

<form role="search" method="get" id="searchform" action="http://ift.tt/1FBZoTY">
  <div>
    <label class="screen-reader-text" for="s">In what country do you want to start your business?<br>Which expertise are you looking for?</label><br><br>
    <?php wp_dropdown_categories( 'show_option_all=Select a country&exclude=1'); ?>
     <input type="text" value="e.g. lawyer" name="s" id="s" class="text_box_expertise"/>
    <input type="submit" class="btn_double_search" id="searchsubmit" value="Search" />
  </div>
</form>

This second search option would was my first idea, but I can't get it to work, so I switched to the search form as it is now on the website.

So ideally, I want a drop-down box with countries (categories) and a type-seach box next to it. So it only searches in the selected categorie.

I am sorry for the long question, but I tried to describe it as good as possible (not really that into coding )

Hope anyone has an idea.



via Chebli Mohamed

How can I get a component's position on screen (screen coordinates)

I want to show a window at a position relative to a given component.

Is there a way to determine a component's screen coordinates?

So I can then use those to set the window's position:

window.setPosition(x, y);



via Chebli Mohamed

How can we convert .rdf report to .jrxml file?

I have never used oracle reports and I need to convert the .rdf from oracle reports to .jrxml in jasper so is there any way possible.



via Chebli Mohamed

Presence insight server unstable

The presence insight server on bluemix has been quite unstable now. Cannot get access to the server.

Is there any way to deploy the instance on softlayer server for production?



via Chebli Mohamed

Why does extracting file a file using TZipFile in iOS Simulator raise access violation?

I'm using TZipFile to extract a zip file and it's works ok in win32 but raise this exception in ios simulator. I dont know why , i've checked the location for the extraction is ok, passed the open file but when come to the extract it still raise that exception. Currently i'm not having any ios device for the real testing but please help on simulator, i'm frustrating with this.

ZipFile.Open(filePath, zmRead);//this line passed, 
ZipFile.Extract(0,dirPath );//raise EAccess exception in this line
ZipFile.Close;
//the filePath and the dirPath is the location of file and location i want to extract, it's all correct.

Or use

Zipfile.ExtractZipFile(filePath,dirPath) //still that exception

Update: OH i think i'm missing the information about my project, my working is to download a zip file which contain a .csv file from a server. I've downloaded it to the a folder in the ios simulator, the value of folder i put in to variable dirPath = Tpath.GetHomePath() + SeparatorChar + 'csv' and the variable 'fileName' is the dirPath' + name of file zip i downloaded. And i about to extract it right in that folder. So i use TZipFile to extract it and it cause up the access violation error in ZipFile.Extract line. I putted my download and extract section code to a new project and it works perfectly. I dont know why but my main project is a large prj which contain many function come up before my download section.Thanks



via Chebli Mohamed

count length of filenames in batch

my problem is I want to count the length of multiple filenames and save this numbers into a file.

My approach is this:

@echo off
for %%i in (*.txt) do (
    set Datei=%%~ni
    call :strLen Datei strlen

    :strLen
    setlocal enabledelayedexpansion

    :strLen_Loop
    if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
    (endlocal & set %2=%len%)

    echo.%strlen%>> tmp
)

The problem here is it only works for the first filename and after that it is stuck and does not go on to the next filename.



via Chebli Mohamed

SQL Server Database Design - multiple columns in one table reference single column is another table

I'm designing my first SQL Server database and wonder if there's a better way to accomplish what I'm trying to do.

The goal is to be able to create one of 14 documents based on 200+ different document sections (titles, headings, paragraphs, lists, etc). Each document section is part of 1 or more documents.

My application does a single database lookup for a particular document and retrieves the data stored in the 50 text fields.

To do this, I first stored each unique document section in a "sections" table, giving each section a unique identifier (sectionID) and made the identifier a primary key, for example:

dbo.sections
sectionID(pk)       sectionText
iv1                 this is the text for the first section
AHv1                this text is for another section
APv2                more text to include
.
.
.
EFv3                another text section
GHv2                this is the last section text in the table

I then created a second table called "documents" to store each document name and the sections that belong to it. There are 51 columns in this table. The first column is the document name and the other 50 columns store the id's of the sections (they're named section1, section2, ...) that make up that particular document. Each of the section columns are foreign keys that reference the primary key in the "sections" table, for example:

dbo.documents
docID         section1(fk)   section2(fk)   ... section50(fk)
option1         iv1           AHv1          ...   GHv2
option2         iv1           APv2          ...   EFv3

All of this seems straightforward to me. However, in order to get the text for each document to be part of a given record, I have to create a view that does 50 joins of the sections table. By doing that, each document id and its text are stored in one row of a table.

Is there a better way to get the same end result? Or a better design? It seems like there may be a lot of overhead to join the data between tables.

Any input would be greatly appreciated!



via Chebli Mohamed

mardi 4 août 2015

How do I prevent backbone remove() from removing "el" in a view?

I want remove a view before creating a new one. But my requirement is view.remove() should remove the view but not delete the el element. Having said this, I do not want to set tagName as it crates a new element which is unnecessary. Is there any way to remove a view from the memory leaving the el content cleared?

Why does asm.js deteriorate performance?

Just to see how it performs, I wrote a very short asm.js module by hand, which simulates the 2D wave equation using 32-bit integer math and typed arrays (Int32Array). I have three versions of it, all as similar as possible:

  1. Ordinary (i.e. legible, albeit C-style) JavaScript
  2. Same as 1, with asm.js annotations added so that it passes the validator, according to Firefox and other tools
  3. Same as 2, except with no "use asm"; directive at the top

I left a demo at http://ift.tt/1M8UwwH which lets you switch between modules to see the effects of using each one. All three work, but at different speeds. This is the hotspot (with asm.js annotations):

for (i = 0; ~~i < ~~h; i = (1 + i)|0) {
    for (j = 0; ~~j < ~~w; j = (1 + j)|0) {
        if (~~i == 0) {
            index = (1 + index) | 0;
            continue;
        }
        if (~~(i + 1) == ~~h) {
            index = (1 + index) | 0;
            continue;
        }
        if (~~j == 0) {
            index = (1 + index) | 0;
            continue;
        }
        if (~~(j + 1) == ~~w) {
            index = (1 + index) | 0;
            continue;
        }
        uCen = signedHeap  [((u0_offset + index) << 2) >> 2] | 0;
        uNorth = signedHeap[((u0_offset + index - w) << 2) >> 2] | 0;
        uSouth = signedHeap[((u0_offset + index + w) << 2) >> 2] | 0;
        uWest = signedHeap [((u0_offset + index - 1) << 2) >> 2] | 0;
        uEast = signedHeap [((u0_offset + index + 1) << 2) >> 2] | 0;
        uxx = (((uWest + uEast) >> 1) - uCen) | 0;
        uyy = (((uNorth + uSouth) >> 1) - uCen) | 0;
        vel = signedHeap[((vel_offset + index) << 2) >> 2] | 0;
        vel = vel + (uxx >> 1) | 0;
        vel = applyCap(vel) | 0;
        vel = vel + (uyy >> 1) | 0;
        vel = applyCap(vel) | 0;
        force = signedHeap[((force_offset + index) << 2) >> 2] | 0;
        signedHeap[((u1_offset + index) << 2) >> 2] = applyCap(((applyCap((uCen + vel) | 0) | 0) + force) | 0) | 0;
        force = force - (force >> forceDampingBitShift) | 0;
        signedHeap[((force_offset + index) << 2) >> 2] = force;
        vel = vel - (vel >> velocityDampingBitShift) | 0;
        signedHeap[((vel_offset + index) << 2) >> 2] = vel;
        index = (index + 1)|0;
    }
}

The "ordinary JavaScript" version is structured as above, but without the bitwise operators that asm.js requires (e.g. "x|0", "~~x", "arr[(x<<2)>>2]", etc.)

These are the results for all three modules on my machine, using Firefox (Developer Edition v. 41) and Chrome (version 44), in milliseconds per iteration:

  • FIREFOX (version 41): 20 ms, 35 ms, 60 ms.
  • CHROME (version 44): 25 ms, 150 ms, 75 ms.

So ordinary JavaScript wins in both browsers. The presence of asm.js-required annotations deteriorates performance by a factor of 3 in both. Furthermore, the presence of the "use asm"; directive has an obvious effect- it helps Firefox a bit, and brings Chrome to its knees!

It seems strange that merely adding bitwise operators should introduce a threefold performance degradation that can't be overcome by telling the browser to use asm.js. Also, why does telling the browser to use asm.js only help marginally in Firefox, and completely backfire in Chrome?

d3 function(d) return value from object not from the first index(0)

why d3 function(d) return value from object not from the first index(0)

tr.append('td').html(function(m) { console.log(m.INDEX) ;return m.INDEX; })

from this function i have value from index 1 to m.INDEX.length ?

Can't understand a javascript .call() usage

I'm trying to learn the three.js library by reading the "WebGL Up And Running" book and the problem for me is that the author made his own javascript framework called 'sim.js' which is a "higher-level set of reusable objects build upon three.js that wraps the more repetitive Three.js tasks" as he said but for a beginner like me i'd prefer more experiencing the raw three.js first.. So now i have to understand what his framwork does to understand what happens under the hood.

this is the sim.js

// Sim.js - A Simple Simulator for WebGL (based on Three.js)

Sim = {};

// Sim.Publisher - base class for event publishers
Sim.Publisher = function() {
    this.messageTypes = {};
}

Sim.Publisher.prototype.subscribe = function(message, subscriber, callback) {
    var subscribers = this.messageTypes[message];
    if (subscribers)
    {
        if (this.findSubscriber(subscribers, subscriber) != -1)
        {
            return;
        }
    }
    else
    {
        subscribers = [];
        this.messageTypes[message] = subscribers;
    }

    subscribers.push({ subscriber : subscriber, callback : callback });
}

Sim.Publisher.prototype.unsubscribe =  function(message, subscriber, callback) {
    if (subscriber)
    {
        var subscribers = this.messageTypes[message];

        if (subscribers)
        {
            var i = this.findSubscriber(subscribers, subscriber, callback);
            if (i != -1)
            {
                this.messageTypes[message].splice(i, 1);
            }
        }
    }
    else
    {
        delete this.messageTypes[message];
    }
}

Sim.Publisher.prototype.publish = function(message) {
    var subscribers = this.messageTypes[message];

    if (subscribers)
    {
        for (var i = 0; i < subscribers.length; i++)
        {
            var args = [];
            for (var j = 0; j < arguments.length - 1; j++)
            {
                args.push(arguments[j + 1]);
            }
            subscribers[i].callback.apply(subscribers[i].subscriber, args);
        }
    }
}

Sim.Publisher.prototype.findSubscriber = function (subscribers, subscriber) {
    for (var i = 0; i < subscribers.length; i++)
    {
        if (subscribers[i] == subscriber)
        {
            return i;
        }
    }

    return -1;
}

// Sim.App - application class (singleton)
Sim.App = function()
{
    Sim.Publisher.call(this);

    this.renderer = null;
    this.scene = null;
    this.camera = null;
    this.objects = [];
}

Sim.App.prototype = new Sim.Publisher;

Sim.App.prototype.init = function(param)
{
    param = param || {};    
    var container = param.container;
    var canvas = param.canvas;

    // Create the Three.js renderer, add it to our div
    var renderer = new THREE.WebGLRenderer( { antialias: true, canvas: canvas } );
    renderer.setSize(container.offsetWidth, container.offsetHeight);
    container.appendChild( renderer.domElement );

    // Create a new Three.js scene
    var scene = new THREE.Scene();
    scene.add( new THREE.AmbientLight( 0x505050 ) );
    scene.data = this;

    // Put in a camera at a good default location
    camera = new THREE.PerspectiveCamera( 45, container.offsetWidth / container.offsetHeight, 1, 10000 );
    camera.position.set( 0, 0, 3.3333 );

    scene.add(camera);

    // Create a root object to contain all other scene objects
    var root = new THREE.Object3D();
    scene.add(root);

    // Create a projector to handle picking
    var projector = new THREE.Projector();

    // Save away a few things
    this.container = container;
    this.renderer = renderer;
    this.scene = scene;
    this.camera = camera;
    this.projector = projector;
    this.root = root;

    // Set up event handlers
    this.initMouse();
    this.initKeyboard();
    this.addDomHandlers();
}

//Core run loop
Sim.App.prototype.run = function()
{
    this.update();
    this.renderer.render( this.scene, this.camera );
    var that = this;
    requestAnimationFrame(function() { that.run(); });  
}

// Update method - called once per tick
Sim.App.prototype.update = function()
{
    var i, len;
    len = this.objects.length;
    for (i = 0; i < len; i++)
    {
        this.objects[i].update();
    }
}

// Add/remove objects
Sim.App.prototype.addObject = function(obj)
{
    this.objects.push(obj);

    // If this is a renderable object, add it to the root scene
    if (obj.object3D)
    {
        this.root.add(obj.object3D);
    }
}

Sim.App.prototype.removeObject = function(obj)
{
    var index = this.objects.indexOf(obj);
    if (index != -1)
    {
        this.objects.splice(index, 1);
        // If this is a renderable object, remove it from the root scene
        if (obj.object3D)
        {
            this.root.remove(obj.object3D);
        }
    }
}

// Event handling
Sim.App.prototype.initMouse = function()
{
    var dom = this.renderer.domElement;

    var that = this;
    dom.addEventListener( 'mousemove', 
            function(e) { that.onDocumentMouseMove(e); }, false );
    dom.addEventListener( 'mousedown', 
            function(e) { that.onDocumentMouseDown(e); }, false );
    dom.addEventListener( 'mouseup', 
            function(e) { that.onDocumentMouseUp(e); }, false );

    $(dom).mousewheel(
            function(e, delta) {
                that.onDocumentMouseScroll(e, delta);
            }
        );

    this.overObject = null;
    this.clickedObject = null;
}

Sim.App.prototype.initKeyboard = function()
{
    var dom = this.renderer.domElement;

    var that = this;
    dom.addEventListener( 'keydown', 
            function(e) { that.onKeyDown(e); }, false );
    dom.addEventListener( 'keyup', 
            function(e) { that.onKeyUp(e); }, false );
    dom.addEventListener( 'keypress', 
            function(e) { that.onKeyPress(e); }, false );

    // so it can take focus
    dom.setAttribute("tabindex", 1);
    dom.style.outline='none';
}

Sim.App.prototype.addDomHandlers = function()
{
    var that = this;
    window.addEventListener( 'resize', function(event) { that.onWindowResize(event); }, false );
}

Sim.App.prototype.onDocumentMouseMove = function(event)
{
    event.preventDefault();

    if (this.clickedObject && this.clickedObject.handleMouseMove)
    {
        var hitpoint = null, hitnormal = null;
        var intersected = this.objectFromMouse(event.pageX, event.pageY);
        if (intersected.object == this.clickedObject)
        {
            hitpoint = intersected.point;
            hitnormal = intersected.normal;
        }
        this.clickedObject.handleMouseMove(event.pageX, event.pageY, hitpoint, hitnormal);
    }
    else
    {
        var handled = false;

        var oldObj = this.overObject;
        var intersected = this.objectFromMouse(event.pageX, event.pageY);
        this.overObject = intersected.object;

        if (this.overObject != oldObj)
        {
            if (oldObj)
            {
                this.container.style.cursor = 'auto';

                if (oldObj.handleMouseOut)
                {
                    oldObj.handleMouseOut(event.pageX, event.pageY);
                }
            }

            if (this.overObject)
            {
                if (this.overObject.overCursor)
                {
                    this.container.style.cursor = this.overObject.overCursor;
                }

                if (this.overObject.handleMouseOver)
                {
                    this.overObject.handleMouseOver(event.pageX, event.pageY);
                }
            }

            handled = true;
        }

        if (!handled && this.handleMouseMove)
        {
            this.handleMouseMove(event.pageX, event.pageY);
        }
    }
}

Sim.App.prototype.onDocumentMouseDown = function(event)
{
    event.preventDefault();

    var handled = false;

    var intersected = this.objectFromMouse(event.pageX, event.pageY);
    if (intersected.object)
    {
        if (intersected.object.handleMouseDown)
        {
            intersected.object.handleMouseDown(event.pageX, event.pageY, intersected.point, intersected.normal);
            this.clickedObject = intersected.object;
            handled = true;
        }
    }

    if (!handled && this.handleMouseDown)
    {
        this.handleMouseDown(event.pageX, event.pageY);
    }
}

Sim.App.prototype.onDocumentMouseUp = function(event)
{
    event.preventDefault();

    var handled = false;

    var intersected = this.objectFromMouse(event.pageX, event.pageY);
    if (intersected.object)
    {
        if (intersected.object.handleMouseUp)
        {
            intersected.object.handleMouseUp(event.pageX, event.pageY, intersected.point, intersected.normal);
            handled = true;
        }
    }

    if (!handled && this.handleMouseUp)
    {
        this.handleMouseUp(event.pageX, event.pageY);
    }

    this.clickedObject = null;
}

Sim.App.prototype.onDocumentMouseScroll = function(event, delta)
{
    event.preventDefault();

    if (this.handleMouseScroll)
    {
        this.handleMouseScroll(delta);
    }
}

Sim.App.prototype.objectFromMouse = function(pagex, pagey)
{
    // Translate page coords to element coords
    var offset = $(this.renderer.domElement).offset();  
    var eltx = pagex - offset.left;
    var elty = pagey - offset.top;

    // Translate client coords into viewport x,y
    var vpx = ( eltx / this.container.offsetWidth ) * 2 - 1;
    var vpy = - ( elty / this.container.offsetHeight ) * 2 + 1;

    var vector = new THREE.Vector3( vpx, vpy, 0.5 );

    this.projector.unprojectVector( vector, this.camera );

    var ray = new THREE.Ray( this.camera.position, vector.subSelf( this.camera.position ).normalize() );

    var intersects = ray.intersectScene( this.scene );

    if ( intersects.length > 0 ) {      

        var i = 0;
        while(!intersects[i].object.visible)
        {
            i++;
        }

        var intersected = intersects[i];
        var mat = new THREE.Matrix4().getInverse(intersected.object.matrixWorld);
        var point = mat.multiplyVector3(intersected.point);

        return (this.findObjectFromIntersected(intersected.object, intersected.point, intersected.face.normal));                                                 
    }
    else
    {
        return { object : null, point : null, normal : null };
    }
}

Sim.App.prototype.findObjectFromIntersected = function(object, point, normal)
{
    if (object.data)
    {
        return { object: object.data, point: point, normal: normal };
    }
    else if (object.parent)
    {
        return this.findObjectFromIntersected(object.parent, point, normal);
    }
    else
    {
        return { object : null, point : null, normal : null };
    }
}


Sim.App.prototype.onKeyDown = function(event)
{
    // N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
    event.preventDefault();

    if (this.handleKeyDown)
    {
        this.handleKeyDown(event.keyCode, event.charCode);
    }
}

Sim.App.prototype.onKeyUp = function(event)
{
    // N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
    event.preventDefault();

    if (this.handleKeyUp)
    {
        this.handleKeyUp(event.keyCode, event.charCode);
    }
}

Sim.App.prototype.onKeyPress = function(event)
{
    // N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
    event.preventDefault();

    if (this.handleKeyPress)
    {
        this.handleKeyPress(event.keyCode, event.charCode);
    }
}

Sim.App.prototype.onWindowResize = function(event) {

    this.renderer.setSize(this.container.offsetWidth, this.container.offsetHeight);

    this.camera.aspect = this.container.offsetWidth / this.container.offsetHeight;
    this.camera.updateProjectionMatrix();

}

Sim.App.prototype.focus = function()
{
    if (this.renderer && this.renderer.domElement)
    {
        this.renderer.domElement.focus();
    }
}


// Sim.Object - base class for all objects in our simulation
Sim.Object = function()
{
    Sim.Publisher.call(this);

    this.object3D = null;
    this.children = [];
}

Sim.Object.prototype = new Sim.Publisher;

Sim.Object.prototype.init = function()
{
}

Sim.Object.prototype.update = function()
{
    this.updateChildren();
}

// setPosition - move the object to a new position
Sim.Object.prototype.setPosition = function(x, y, z)
{
    if (this.object3D)
    {
        this.object3D.position.set(x, y, z);
    }
}

//setScale - scale the object
Sim.Object.prototype.setScale = function(x, y, z)
{
    if (this.object3D)
    {
        this.object3D.scale.set(x, y, z);
    }
}

//setScale - scale the object
Sim.Object.prototype.setVisible = function(visible)
{
    function setVisible(obj, visible)
    {
        obj.visible = visible;
        var i, len = obj.children.length;
        for (i = 0; i < len; i++)
        {
            setVisible(obj.children[i], visible);
        }
    }

    if (this.object3D)
    {
        setVisible(this.object3D, visible);
    }
}

// updateChildren - update all child objects
Sim.Object.prototype.update = function()
{
    var i, len;
    len = this.children.length;
    for (i = 0; i < len; i++)
    {
        this.children[i].update();
    }
}

Sim.Object.prototype.setObject3D = function(object3D)
{
    object3D.data = this;
    this.object3D = object3D;
}

//Add/remove children
Sim.Object.prototype.addChild = function(child)
{
    this.children.push(child);

    // If this is a renderable object, add its object3D as a child of mine
    if (child.object3D)
    {
        this.object3D.add(child.object3D);
    }
}

Sim.Object.prototype.removeChild = function(child)
{
    var index = this.children.indexOf(child);
    if (index != -1)
    {
        this.children.splice(index, 1);
        // If this is a renderable object, remove its object3D as a child of mine
        if (child.object3D)
        {
            this.object3D.remove(child.object3D);
        }
    }
}

// Some utility methods
Sim.Object.prototype.getScene = function()
{
    var scene = null;
    if (this.object3D)
    {
        var obj = this.object3D;
        while (obj.parent)
        {
            obj = obj.parent;
        }

        scene = obj;
    }

    return scene;
}

Sim.Object.prototype.getApp = function()
{
    var scene = this.getScene();
    return scene ? scene.data : null;
}

// Some constants

/* key codes
37: left
38: up
39: right
40: down
*/
Sim.KeyCodes = {};
Sim.KeyCodes.KEY_LEFT  = 37;
Sim.KeyCodes.KEY_UP  = 38;
Sim.KeyCodes.KEY_RIGHT  = 39;
Sim.KeyCodes.KEY_DOWN  = 40;

in another script he wrote a new class called earth-basic based on the sim class so, the begining of the earth-basic.js script looks as the following :

// Constructor
EarthApp = function()
{
    Sim.App.call(this);
}

// Subclass Sim.App
EarthApp.prototype = new Sim.App();

// Our custom initializer
EarthApp.prototype.init = function(param)
{
    // Call superclass init code to set up scene, renderer, default camera
    Sim.App.prototype.init.call(this, param);

    // Create the Earth and add it to our sim
    var earth = new Earth();
    earth.init();
    this.addObject(earth);
}

// Custom Earth class
Earth = function()
{
    Sim.Object.call(this);
}

Earth.prototype = new Sim.Object();

1) what does the function call in the line "Sim.App.call(this);" written in the constructor (by passing "this" as parameter which i suppose is referring to the EarthApp variable)? all what i can guess is that EarthApp will inherit the Sim.App properties (the renderer, the camera ...). The same "technique" was used inside the "Sim.App" function itself by calling "Sim.Publisher.call(this);"

2) in 1) i supposed he just used the sim.App class as a super-Class but then all of a sudden, i found he added a new instance of sim.App() to the EarthApp's prototype by writting "EarthApp.prototype = new Sim.App();" PLease guys tell me what the heck is going on in there.

Using AJAX response in Javascript Array? [duplicate]

This question already has an answer here:

I'm not entirely sure if this is possible but I am trying to use an ajax response in a javascript array in my page.

this is what I have:

var interval = 5000;
function doAjax() {
    jQuery.ajax({
            type: 'POST',
            url: 've.php',
            dataType : 'json',
            success: function (data) {


            //var arr = data.split('|');
                    jQuery('#counterint').html(data);

                    var res = $.parseJSON(data);   



//test: simulated ajax

var testLocs = {

<<<<<<<<<<<<<< I NEED TO USE THE "data" HERE >>>>>>>>>>>>>>>>>

    };


setMarkers(testLocs); 

The ajax response looks like this when I outputs it on my page in the browser:

1: { info: '1. rooz', lat: 51.5033630, lng: -0.1276250 },2: { info: '1. Rooz555', lat: 51.5033567, lng: -0.1276444 },3: { info: '1. david', lat: 51.5033777, lng: -0.1276777 },4: { info: '1. sam', lat: 51.5033555, lng: -0.1276543 },

any help would be appreciated.

Most efficient way to restructure complex array of objects in javascript?

I have a large set of data that looks similar to this:

var original = [
  { country : 'us', date : '2014-10-29', cost : 45.3 },
  { country : 'africa', date : '2014-10-29', cost : 60.5 },
  { country : 'south_america', date : '2014-10-30', cost : 10 },
  { country : 'us', date : '2014-10-30', cost : 30 }
];

I need to rearrange this data so that it looks more like this:

var newData = [
  { date : '2014-10-29', us : 45.3, africa : 60.5, south_america : 0 },
  { date : '2014-10-30', us : 30, africa : 0, south_america : 10 }
]

I'm new to dealing with datasets like this and I'm struggling to find any efficient way to handle this... The only thing I can come up with uses multiple for loops and just looks gross. Does anyone have any ideas or suggestions?

jQuery - end setinterval after X rund

I have a little slider im working on which is almost there im jsut having some trouble with me jQuery.


So first off: I want my slider to reset after the interval has run x amount of times. It was my understanding that the following would work but it doesn't seem to take. 6000, slides, function() { homesliderend();

so lets say slides = 2 set interval should call homesliderend(); but it doesn't the interval just keeps running.


Second Issue: I'm also trying to get it to add 100% to lengther every 6 seconds. But instead of adding 100 each time its just setting it to 100 its not multiplying.

jQuery(document).ready(function($) {
  "use strict";

  function homesliderend() {
    $(".lengther").animate({
      left: "0%"
    }, 500);
  }

  function homeslider() {
    var slides = $(".slide.t-align").length,
      lwidth = slides * 100,
      n = 0;

    $(".lengther").css("width", lwidth + "%");

    setInterval(function() {
      var tn = n + 100;
      $(".lengther").animate({
        left: "-" + tn + "%"
      }, 500);
    }, 6000, slides, function() {
      homesliderend();
    });


  }
  homeslider();
});

how to populate select box with jquery?

i have a requirement in which when i click on a element of a list , the element gets shown as a selected option in the select box

i need to use native select box only , not to mention the elements in the list are present in the select dropdown

<button class="quick">QuickLink</button>

<div class="list">
<ul class="apps">
    <li>CAPM</li>
    <li>GCS</li>
    <li>GRS</li>
</ul>
</div>

<select class="xyz">
<option>CAPM</option>
<option>GRS</option>
<option>BDS</option>
<option>CCAS</option>
<option>WEDAT</option>
<option>SDP</option>
</select>

jsfiddle link --> http://ift.tt/1JJS2mI

Pass ng-model as argument in directive angualjrs

I am writing a directive in angularjs and I want to pass ng-model as argument.

<div class="col-md-7"><time-picker></time-picker></div>

Directive is ,

    app.directive('timePicker', function () {
    return {
        restrict: 'E',
        replace: true,
        template: '<input type="text" class="form-control time-picker" ng-model="emp.signin">',
        link: function ($scope, element, form) {
            $(element).timepicker({'timeFormat': 'H:i:s'});
        }
    }
})

It is working find, and here ng-model is emp.signin and I put this directly. I want able to pass this ng-model dynamically as argument

how it is possible?

Highcharts with DHTMLX menu appearance

I use dhtmlx menu on my charts. (legendItemClick event). It was working well when i use highcharts 3.0.1 . Today, I upgraded to 4.1.7 but dhtmlx menu's legendMenu_<?=$id?>.showContextMenu(x,y) function does not work like old one.

When i inspect the menu element on firebug, i see display: "none". I tried to change it manually. However, Id is randomly generated.

legendMenu_<?=$id?> = new dhtmlXMenuObject();
legendMenu_<?=$id?>.renderAsContextMenu();

How can i fix?