Affichage des articles dont le libellé est Recent Questions - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Recent Questions - Stack Overflow. Afficher tous les articles

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