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 to add "you save" option in the shopping cart of opencart?

I am trying to create a you save option in the shopping cart of opencart.com. I have done the same feature of you save to be displayed in the product page using vqmod. But i am finding it difficult to do it for the shopping cart. here is my vqmod code for adding you save option in the product page.

<modification>
    <id><![CDATA[@tik Savings Note]]></id>
    <version><![CDATA[1.1]]></version>
    <vqmver><![CDATA[2.1.7]]></vqmver>
    <author><![CDATA[OC2PS]]></author>
    <file name="catalog/view/theme/default/template/product/product.tpl">
        <operation>
            <search position="before" offset="2" error="log"><![CDATA[<?php if ($tax) { ?>]]></search>
            <add><![CDATA[<br /><span class="you-save" style="color:red;"><?php echo $text_yousave; ?> <?php echo $yousave; ?></span>]]></add>
        </operation>
    </file>
    <file name="catalog/language/english/product/product.php">
       <operation>
            <search position="replace" error="log"><![CDATA[// Entry]]></search>
            <add><![CDATA[$_['text_yousave']        = 'You save:';// Entry]]></add>
       </operation>
    </file>
    <file name="catalog/controller/product/product.php">
        <operation>
            <search position="replace" error="log"><![CDATA[$data['text_tax'] = $this->language->get('text_tax');]]></search>
            <add><![CDATA[$data['text_tax'] = $this->language->get('text_tax');
                 $data['text_yousave'] = $this->language->get('text_yousave');]]></add>
        </operation>
        <operation>
            <search position="replace" error="log"><![CDATA[$data['special'] = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));]]></search>
            <add><![CDATA[$data['special'] = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                $data['yousave'] = $this->currency->format($this->tax->calculate($product_info['price']-$product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                $data['yousavepercent'] = round(($product_info['price']-$product_info['special'])*100/$product_info['price'],0);]]></add>
        </operation>
        <operation>
            <search position="replace" error="log"><![CDATA[$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));]]></search>
            <add><![CDATA[$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                    $yousave = $this->currency->format($this->tax->calculate($result['price']-$result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                    $yousavepercent = round(($result['price']-$result['special'])*100/$result['price'],0);]]></add>
        </operation>        
    </file>
</modification>

Signing JSON objects

I have to exchange JSON objects between different platforms and implementations of a service and make its integrity verifiable via digital signatures. So a platform A would create such an object and create a digital signature. Said signature is then included into the object and sent to platform B. The JSON objects can contain arbitrary attributes and data.

E.g. in PHP:

function signObject($jsonObjectToSign, $privateKey) {
    $jsonObjectToSign->signature = "";
    $msgToSign = json_encode($jsonObjectToSign);

    openssl_sign($msgToSign, $jsonObjectToSign->signature, $privateKey, OPENSSL_SLGO_SHA1);

    return $jsonObjectToSign;
}

Problem is, that e.g. in Java, there is no way to tell whether the attributes of a JSON object will be in the same order you added them (via JSONObject.put()). So, if I do a

$json = json_encode('{"a":1, "b":2}');

in PHP, sign this object as stated above, transfer it to a java based server, decode the json object and then try to verify the signature, I'd probably get a different order of the object's attributes.

So what I need, is a reliable way to create a String from a JSONObject, independent of the language or platform used.

The example object above needs always to output {"a":1, "b":2} and NEVER {"b":2, "a":1}. Unfortunately, this is the usual case e.g. in Java.

Is there any "best practice" to sign JSON Objects in a secure way?

But let me describe the problem in another way:

Let's say I want to do this in Java (or any other language):

JSONObject j = new JSONObject();
j.put("a", 1);
j.put("b", 2);

Now, I need a serialization function, that outputs always the same string representation for this object, no matter how and with what language this object is created.

MySQL trigger: updating column depending of a submitted value

Ths my trigger but it doesn't work.

CREATE TRIGGER events_events_a BEFORE INSERT ON events_events
FOR EACH ROW
BEGIN 
IF NEW.public = 1 THEN
UPDATE events_cats SET etotal=etotal+1, etotal_NEW.region=etotal_NEW.region+1 WHERE id=NEW.category;
END IF;
END;

I need to update column depending of a submitted value.

if NEW.region value is 1, I need to update column etotal_1=etotal_1+1
if NEW.region value is 2, I need to update column etotal_2=etotal_2+1
if NEW.region value is 3, I need to update column etotal_3=etotal_3+1

etc. Is there any way how to update column depending of NEW.region value?

How to write NULL instead of 0 when I leave a field empty

I have a problem with inserting data. When I leave a field empty then he writes a 0 in my db instead of 0. What I have to do that he writes NULL.

<?php

if ($date == '' || $name_home == ''|| $name_away == '')
{

$error = 'Please enter the details!';

valid($date, $name_home, $name_away, $score_home, $score_away, $error);
}
else
{

mysql_query("INSERT name_matches SET date='$date', name_home='$name_home', name_away='$name_away', score_home='$score_home', score_away='$score_away'")
or die(mysql_error());

header("Location: view.php");
}
}
else
{
valid('','','','','','');
}
?>

Divs, including php to appear next to each eachother

Using Bootstrap to layout the page and at first I had images in a grid, like on Facebook, there were 4 in a row and as the page shrunk so did the number of images in a row. Now I have added php so it is easier to update the page but the images all appear under each other. How can I have it the way it was?

Code used:

<section  id="alf40">
   <div class="container-fluid no-padding ">
<div class="row">

        <div class="col-lg-3 col-md-4 col-xs-6 thumb" style="display:inline-block; float:left; position:relative;" >
        <?php $SQL = "SELECT * FROM nw_photo";
        $result = mysql_query($SQL);
        while ( $db_field = mysql_fetch_assoc($result) ) { ?>

            <a class="thumbnail" href="#"><img class="img-responsive" src="
    <?php echo $db_field['image']; ?>" style="display:inline-block; float:left; position:relative;">
            <?php } ?></a>
        </div>

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

Alternative to strtotime() in MySQL

I have an EventSet table with those fields:

  • start_day (ex. Monday)
  • start_time (ex. 14:20:00)

I want to create a query that selects specific records by comparing their day an time with the current ones.

So, using a little help from the PHP's strtotime() method I am aiming at something similar to:

SELECT * 
FROM 
   `EventSet` 
WHERE 
    DATE_FORMAT(NOW(), '%W %H:%i:%s') <= 
    date('%W %H:%i:%s', strtotime('start_day start_time'))

*the last date() part is of course pure PHP


So far I've tried using DATE_FORMAT with CONCAT_WS and also TIMESTAMP() / UNIX_TIMESTAMP() but am clearly messing something up.

SELECT * 
FROM 
    `EventSet` 
WHERE 
    DATE_FORMAT(NOW(), '%W %H:%i:%s') <= 
    DATE_FORMAT(CONCAT_WS(' ', start_day, start_time), '%W %H:%i:%s')

I've looked through many similar questions here and in the net, but they all already have a date field to work with and there's no need to concatenate anything, so I can't use any of them.

How to access protected variable form given response [duplicate]

This question already has an answer here:

I want to retrieve _href:protected from given response but i don't know How i can access it .

 Recurly_Subscription Object
(
    [_values:protected] => Array
        (
            [subscription_add_ons] => Array
                (
                )

            [account] => Recurly_Stub Object
                (
                    [objectType] => account
                    [_href:protected] => http://ift.tt/1MJI9ao
                    [_client:protected] => Recurly_Client Object
                        (
                            [_apiKey:Recurly_Client:private] => 
                            [_acceptLanguage:Recurly_Client:private] => en-US
                        )

                    [_links:protected] => Array
                        (
                        )

                )






)
)

i try $sub->account->href for account href but not success. Please provide solution .

CakePHP - How to continue saving if associated model fails validation

Let's say I have an array:

array(
    'Foo' => array(
        'field1' => 'value1',
        'field2' => 'value2'
    ),
    'Bar' => array(
        'field1' => 'value1',
        'field2' => 'value2'
    )
)

Where Foo and Bar have model relationships set up and have their own validation conditions in he model.

How can I make it so if I am doing $this->Foo->save(); even if Bar fails its validation then it will still go ahead and save Foo only

Codeigniter Deprecated: mysql_real_escape_string():

Got below error while using codigniter 3.0

FYI using PHP Version 5.5.12,Apache Version Apache/2.4.9 (Win64) PHP/5.5.12

A PHP Error was encountered

Severity: 8192

Message: mysql_real_escape_string(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

Filename: models/common_model.php

Line Number: 21

Backtrace:

File: C:\wamp\www\Codeigniter\application\models\common_model.php Line: 21 Function: mysql_real_escape_string

get total price of configurable product according to size swatch

I am new in magento.I have created a store and managed some configurable products in it.What I want to do now is show total price in the size swatch dropdown but in default magento gives the individual size price in the dropdown with + or - sign with it.Can anyone suggest me any idea so i can show total price instead of unit price?Any help is appreciated!!Thanks

Wordpress get_permalink doesn't work

I've got some trouble with unclickable images and post titles in my Wordpress blog template. Get_permaling doesn't work (according to what I've read it's because that function should be in loop.php but my template doesn't have that file).

The weird thing is, there's a "read more" link under each post and it has get_permalink attribute - and it works, but when I try to make post image or title clickable the same way, nothing changes. It's a little annoying when people can't open blog posts by clicking on image or header :(

Could you help me with that?

Here's the list of files my template contains, maybe that will be helpful?

404.php

bootstrap_tests.php

class.redux-plugin.php

index.php

kill-travis.php

redux-framework.php

uninstall.php

archive.php

author.php

category.php

comments.php

content-audio.php

content-gallery.php

content-quote.php

content-video.php

content.php

footer.php

class-tgm-plugin-activation.php

color.php

post_type.php

wp_bootstrap_navwalker.php

functions.php

header.php

index.php

(page-templates/alt-header.php)

(page-templates/blog-timeline.php)

(page-templates/blog1.php)

(page-templates/blog2.php)

(page-templates/blog_sidebar1.php)

(page-templates/blog_sidebar2.php)

(page-templates/blog_sorting.php)

(page-templates/template-canvas.php)

(page-templates/template-portfolio.php)

page.php

search.php

shortcodes.php

sidebar-footer.php

sidebar.php

single-portfolio.php

single.php

tag.php

vc_shortcode.php

vc_column.php

vc_row.php

vc_tab.php

vc_tabs.php

Style

style.css

rtl.css

DRAG and DROP file upload work like multiple file upload

I want to make a form with informations such as "name, type, etc.." and i want to make a 'Drag and Drop' image uploader with click fuction. SO drag and drop or click to select the images. Max is 5 images. I found some script and divs but it alway upload the file whzen you drag and drop it or choose it. I want to submit the upload with the whole form, because it is connected to a mysql database. I did't find a solution for this.

Getting date value with find() and Checking if the date is < 30 mins

I try to make an app. that sends e-mail to the user. Whenever i run the code, the current time and date is saved to the database under the name of "created" (column). There are 2 conditions. I could make the first one in that if loop. Second condition is sending e-mail after 30 mins from the previous e-mail. To do this, I try to get those saved values by using find() and compare them to do 30 mins condition. (Btw I am very newbie at programming. I ve been learning for 3 weeks)

Here is the code;

class TemperatureReading extends AppModel {

    function afterSave($created, $options = array()) {

    $temperature = $this->data['TemperatureReading']['temperature'];

    $result = $this->Location->find('first' , array(
            'conditions' => array(
                    'Location.id' => $this->data['TemperatureReading']['location_id']
            )));

    $high_threshold = $result['Location']['high_threshold'];

    $low_threshold = $result['Location']['low_threshold'];

    $created = $this->data['TemperatureReading']['created'];

    $id = $this->data['TemperatureReading']['id'];

    $models_Temp_Loc = $this->find('first' , array(
            'conditions' => array(
                    'TemperatureReading.id' => $id
            )));

    $prev_created_time = $models_Temp_Loc['TemperatureReading']['created'];

// The part, where I have problems. I want to get the values of created (time and date) and compare them to check 30 mins condition. (ex: Assume that app. ran and e-mail sent for the first time at specific time. The application can be run 100 or 241 or 4144.. times in 10 mins after the first e-mail, so there are many date and time data saved in created in 10 mins to be compared for 30 mins condition.)

    $deneme = $this->find('all' , array(
        'conditions' => array(
                'created.id' => $id
                ), 
                    'condition' => array(
                        'created' <30
                )));

    //The part where i can make the first condition without problem

    if ($temperature > $high_threshold || $temperature < $low_threshold) {

        $Email = new CakeEmail('gmail');
        $Email->from(array('xxxxxxx@gmail.com' => 'My Site'));
        $Email->to('xxxxxxxxxx@gmail.com');
        $Email->subject('Temperature Warning!');
        $Email->send('Temperature is at critical value of');

    }

Excuse me for any meaningless things, i am very noob and trying to do hard things.

This is what goes on there without $deneme (wrong part). for every id, there is a date and time to be compared for the 30 min condition.

Temperature is: 12
High_threshold is: 90
Low_threshold is: 0
Created is: 2015-08-04 14:47:52
Id is: 340

Array
(
    [TemperatureReading] => Array
        (
            [id] => 340
            [created] => 2015-08-04 14:47:52
            [temperature] => 12
            [location_id] => 1
        )

    [Location] => Array
        (
            [id] => 1
            [name] => Spor Salonu
            [high_threshold] => 90
            [low_threshold] => 0
            [send_warning_to] => onurcucen@gmail.com
        )

)

2015-08-04 14:47:52

ty for any possible recommendations, comments, answers.

PHP - How to merge foreach arrays into one loop

Here is my code:

$url = "http://ift.tt/1IDweUE";

libxml_use_internal_errors(true); 
$doc = new DOMDocument();
$doc->loadHTMLFile($url);

$xpath = new DOMXpath($doc);

$n = $xpath->query('//td[@data-column-name="Model"]');
$r = $xpath->query('//td[@data-column-name="RAM"]');

foreach ($n as $entry) {
    $Name = $entry->nodeValue;
    $RAM  = $r->nodeValue;
    echo " $Name - RAM: $RAM<br>";
}

I successfully echo $Name but i can not get the value for $RAM because i do not have it in my array. My question is how i can add $r into this foreach loop and make it work ?

Thanks in advance!

How to use Different Button in bootstrap Form

i have used Bootstrap and created form.my form Looks like

  <form action="default_results.php"   method="post" class="calculator"  name="frmCalculator">  

i have put this code begin of the code and end of the page i have used three button Looks like

                            <button id="button2" class="dont-compare shadow-inset" value="reset" >
                                    Reset</button>
                            <button id="button3" data-toggle="pop" class="dont-compare shadow-inset" class="update" >
                                    Update MI</button>
                            <button id="Button4"  class="dont-compare shadow-inset" class="calculator" >
                                    Calculate Scenarios</button>
                        </div>

i have another page its called default_ results.php page. i want load that page when i click Calculate Scenarios button . i used href tag that button. but that three button also load default_results page. how to set particular button? please any idea about it?

Redis scan skipping keys

I'm using predis (with laravel if it makes any difference) php client to work with Redis.

I need to fetch all the keys from Redis that match certain prefix and I do it like this:

$keys = [];
    foreach (new Iterator\Keyspace($this->redis(), Cache::KEY_PREFIX.'*') as $key) {
        $keys[] = $rate_key;
    }

After the work with those keys is done, operation repeats - I'm getting those keys again in again in a loop. I noticed that after a few iterations some keys are not included in $keys array.

The strangest thing is that keys that disappear never appear in next iterations. Restart of the php process (it's a daemon) fixes the problem.

I'm using Redis 3.0.2 with Predis 1.0 and PHP 5.4

P.S. Within the loop over keys, I change values for some of them. I'm not deleting any keys, however.

How to upload image and save URL in database in php

In this php code i want to customize the image upload destination. with this php file, i have directory called uploads. i want to add all my uploaded images to this directory and store path in db. how can i do this?

<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "image_upload";
$username_connect= "root";
$password_connect= "";

$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR); 
@mysql_select_db($database_connect) or die (mysql_error()); 

if($_POST) { 
    // $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.

    if ($_FILES["file"]["error"] > 0) {
        // if there is error in file uploading 
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

    } else {
        // check if file already exit in "images" folder.
        if (file_exists("images/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
        } else {  
            //move_uploaded_file function will upload your image.  if you want to resize image before uploading see this link http://ift.tt/UVKZR0
            if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"])) {
                // If file has uploaded successfully, store its name in data base
                $query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
                if(mysql_query($query_image)) {
                    echo "Stored in: " . "images/" . $_FILES["file"]["name"];
                } else {
                    echo 'File name not stored in database';
            }
       }
   } 

}
}
?>

currently when i run the upload i am getting warnings

Warning: move_uploaded_file(images/1409261668002.png): failed to open stream: No such file or directory in D:\xampp\htdocs\image-upload\index.php on line 29

Warning: move_uploaded_file(): Unable to move 'D:\xampp\tmp\php1C1F.tmp' to 'images/1409261668002.png' in D:\xampp\htdocs\image-upload\index.php on line 29

MySQL - One table of each client or Single table with all clients

I am beginning a project where there will be multiple clients. In the database, each client can potentially have hundreds of thousands of rows.

Instead of having all of the clients in a single table, would it make sense to split the clients so that each has their own table? To me this makes sense since each time you query for a client, you would only be looking up a table with their data.

POST a series of products in Laravel / PHP

I'm using Laravel to post a series of products. The user can choose a quantity of each product.

Now I'm wondering how I can post a series, but still have the names of the products.

I have tried the following.

This result gives me an undefined offset error

<input name="{{ $products[$product->id] }}" />

This result doesn't include the name, but does make it a series

<input name="products[]" />

Any idea how I might end up with an array that's called $products, and has all the products in there by name

How to package PHP code like jar or exe or dll?

How to package PHP code like jar in java or exe and dll in visual studio ?

such that when i host it my source code isn't directly available.

Access to config in static method

How can I get access to config in static method of controller? I have Phalcon 1.3 . This method is not working:

$offerSource = $this->config->offerSource;

How to create a tiny Prolog compiler?

Now, I want to create a very tiny Prolog compiler. But, I don't know much about a tiny compiler.

Can you help me to write a very tiny Prolog compiler? Please don't delete or close this question.

I will use your code for my private programming learning only. So, please keep your source code be private. (see at the end of this question: Note.)


Your own compiler must works as these features:

  • Simple as these code (http://ift.tt/1ImnCm8, or http://ift.tt/1KNGMqM) only: (as in Description section).
  • Allow space insensitive.
  • Some replaces for syntax rules:
    • Connection (is comma) (,) is replaced by star (*).
    • Djsjuntion (is semicolon) (;) is replaced by plus (+).
    • Rule (is :-) (:-) is replaced by colon (:).
    • Query/question (is ?-) is replaced by question mark (?).
  • Lexical scope: global.
  • Allow these variables: _ABC, abc, Abc ...
  • Allow use brackets (such as: ()) to change the order of precedence.
  • Cut and list are not required.
  • String type is not required.
  • Show all possible solution.

Your code must be:

  • Written in PHP, and compatible with PHP 4, PHP 5.
  • Please don't write your code in object oriented programming.
  • Your code be tested with QuickPHP).
  • Please don't test your code with online IDEs, such as: ideone.com, eval.in ...

Here is my own HTML interface:

<?php

$source_code_box = $_POST['source_code_box'];

?>
<form action="compiler.php">
<textarea name="source_code_box"></textarea>
<br />
<input type="submit" name="compile_button" />
</form>
<hr />
<?php

yourfunction($source_code_box);

?>


Here are some useful source code:


Sorry about my English, it is so bad. If my question is not clear, please comment bellow this question.


Note: Your complete source code must be uploaded, at here (http://ift.tt/1ImnBi6). Then, if your file is uploaded, it will return an MD5 string. Please copy this MD5 string, and paste it into Stack Overflow as your answer. I will read your code later, and give my own 500 score bounty for you.