lundi 31 août 2015

Losing material when prefab is created

I have a game object with these properties:

So when I create the prefab, right after the creation, on the prefab the material is lost. The mesh renderer doesn't contain any material.

What is the problem? The other properties are set as default.



via Chebli Mohamed

Order by long Distance from Google Distance Matrix

Google Distance Matrix API for long distance between the origin and destination respond with a blank space when it's > 1000km: "1 865"

When I try to order the result using LINQ:

.OrderBy(g => Double.Parse(g.Distance, CultureInfo.GetCultureInfo("pt-PT")))

I get the error:

System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)

I tried to remove the blank space using g.Distance.replace(" ","") but it's not working.



via Chebli Mohamed

Find distinct values based upon multiple columns

I have a spreadsheet of sales with (to keep the example simple) 3 columns

NAME -- STATE -- COUNTRY 

It's easy to find how many sales. (sum all the lines) I can find out how many customers I have but how about finding out how many customers from a particular state (and country)

NAME -- STATE -- COUNTRY
p1----- CA------ USA
p2----- CA------ USA
p1----- CA------ USA
p1----- CA------ USA
p3----- NY------ USA
p3----- NY------ USA

The above example would give 2 unique customers from CA and 1 unique customer from NY and 3 from the USA

EDIT:

The desired result from the above table would be

STATE - UNIQUE CUSTOMERS 
CA ----  2
NY ----  1

COUNTRY - UNIQUE CUSTOMERS
USA ---- 3



via Chebli Mohamed

how to trim incoming values in a stored procedure in mysql?

I have my stored procedure defined as following:

CREATE PROCEDURE `customers`(
IN `in_customer_name` VARCHAR(255),
IN `in_primary_contact` VARCHAR(255), 
IN `in_phone` VARCHAR(255),
IN `in_email` VARCHAR(255), 
IN `in_address` VARCHAR(255),
IN `in_city` VARCHAR(255), 
IN `in_state` VARCHAR(255),
IN `in_zip` VARCHAR(255),
IN `in_tenant_id` INT(11),
IN `cus_id` INT(11),
IN `con_id` INT(11),
IN `loc_id` INT(11),
IN `usr_id` INT(11))


BEGIN

    DECLARE cont_name, cont_phone, cont_email, loc_address, loc_city, loc_state, loc_zip, cont_id VARCHAR(255);

the problem is that sometimes the incoming values have trailing spaces in left or right. I've heard of LTRIM and RTRIM, but I'm not sure if I can use them in incoming values and not just values selected from the database, and if so I can use them I don't know exactly how I can use them. Any ideas?



via Chebli Mohamed

Node.js - Log in to LinkedIn as an application vs client?

I'm trying to build an application that will read job postings from a LinkedIn site and load them into a database for future use - all back end.

Does anyone know where I can find a current working node.js example of signing in to LinkedIn as an "application", rather than as a "client/user"? Is there a difference?

I followed the tutorial here (http://ift.tt/1wF0QPo). I had to use passport-linkedin-oauth2 in order to retrieve an authorization token. After doing this, my passport.authentication fails - without any useful messages.

Here's all I get on the console before the app is routed back to the login screen:

c:\_Todd\_Projects\node-passport\aaa>node server
The magic happens on port 3000
GET / 304 26ms
GET /auth/linkedin 302 13ms - 264b
GET /auth/linkedin/callback?code=AQQe8cSBUaP8A_YRoB5FEncATOOvyMdsAoEsF_v_yYAvG0j2v3Q8ypE28ls5Yqqow6dkDtS16KQBrmhAYxvn9i4s36D6I4iQKSU
SBkaenuGhR7kIZSc&state=true 302 4ms - 35b
GET / 200 6ms - 1.13kb
GET /favicon.ico 404 1ms

My team lead said it looks like I'm trying to log in as a client (because I'm using the sign-in screen), and that I should log in as an application. Is there a difference??? I found some old tutorials that show "Consumer Key / API Key", but the current developer apps only have "Client ID".

Can someone please help?



via Chebli Mohamed

Async database creation with php

I am building a system where every account has its own databases. Creating these databases when the user is actually creating the account results in a long wait before the page is refreshed. Logically, since php is still busy, so the page cannot finish.

Therefore my idea is to 'buffer' up a few, like 5 of these packages, all named $DBNAME$number, where number is 1 to 5. So I just rename the databases at account creation time, thereby minimizing the wait. I think this will work pretty well, but off course, I need to replenish my buffer.

That's where I figured I'd need a method to just replenish the database buffer in the background, which could even run while the accounts database is prepared, and the user is already logging in. The thing is, I haven't found a solution to this, while looking aroung a lot. I tried pthread, which runs exactly as if I would run the code inline. I even gave ajax a shot, hoping the .php file will run async, but it will not.

Does anyone have a recommendation on how to achieve this goal I have? PS: if xy problem, you may notify me :)



via Chebli Mohamed

Determine Spring Version at runtime

Is there a way to determine my Spring Version at runtime? eg

log.info("I'm running spring version '{}'", SpringWhatever.getVersion());

Debug-level logging is not showing me anything.

Full background is that I can compile but am getting java.lang.NoSuchMethodError: org.springframework.context.support.PropertySourcesPlaceholderConfigurer.getAppliedPropertySources() at runtime.



via Chebli Mohamed

Is it possible to incorporate Ruby code into a lpsolve file?

I would like to know if it is possible for a file that is read by gem lpsolve in a rails app to read ruby code. If lpsolve can read ruby code then how can it do it?

Can gem lpsolve understand ruby code?

Just like how an html file can read ruby code when the file's name extension is "html.erb".



via Chebli Mohamed

tinymce setcontent getcontent, what is difference of default usage and format raw?

What is the difference

tinymce.activeEditor.setContent(foo);
tinymce.activeEditor.setContent(foo, {format:'raw'});

I know the documentation of tinymce.setContent/getContent but it does not explain too much. And i could not any detailed explanations or examples in stackoverflow or google. When should we use one and the other? Which drawbacks has each one? Can anyone give some more details? What I found so far is, i am using TinyMCE embedded in a java application and use it as mail reader and mail editor. When we receive an email written by outlook which contains numbered lists, the HTML of the mail contains mso tags. If we set the content which contains mso tags with default usage, setContent(foo), we can not see the numbered lists elements properly, they are left aligned. And other font problems occur. But if we use setContent(foo, {format:raw}) we can see the document properly. Why this difference occurs?



via Chebli Mohamed

Empty list bigger in size than corpus object in nltk

If some works with nltk and does a

from nltk.book import *

she will discover that text1 has object size of 64 bytes doing an

import sys
sys.getsizeof(text1)

If now she does a

text1 = []

the size of text1 increases to 72 ! Why is that? Why an empty list occupies more memory than its previous object form in my machine?

Does anyone know something about this? Thank you



via Chebli Mohamed

Do we still need to use `[...]` in Bash?

If don't care about compatibility, do we still need to use [...] in Bash? Many tutorial/book tell that [[...]] is more better/flexible than [...] e.g. [[...]] is support glob/regex, But today I still see many people prefer to use [...] as standard form, what is a reason behind this? What [[...]] can not do but [...] can do?



via Chebli Mohamed

dynamic task execution in java

I'd like to hear some advice on which technologies to use to solve this problem.

I would like a task executor based on events. These tasks are created by the user (in this moment I am thinking that a task would be a java class that implements the interface task, but I'm open to suggestions). Then the user could load a "jar" or "ear" in the application and using java reflection could execute new tasks.

Another approach I can think of would be that the user creates these tasks in a ejb, deploy the ear and make the ejb loockup to run tasks.

I appreciate any advice. sorry for my english



via Chebli Mohamed

Getting Specific Values from string

If i have a string that is

string Text="@Time:08:30PM,@Date:08/30/2015,@Duration:4,"

How would one go about extracting each of those starting with "@" and ending with the ",". I've searched and I've seen people get one pair with substring, but not how I need it. I want to say:

string Time = "08:30PM" //However i can extract it from that string
string Date = "08/30/2015" //etc...

Could it be done with Regex?

Thanks!



via Chebli Mohamed

Why am I not getting any data using these HQL queries?

I use this query to pull the highest encounter from the highest chapter a user has reached:

SELECT COUNT(hc.s) as users, highest_chapter, highest_encounter
FROM
(SELECT s, MAX(l) as highest_chapter
FROM appl9_evt
WHERE month = "201508" AND st1 = "player" AND st2 = "level_progression" AND n = "level_start"
GROUP BY s
ORDER BY highest_chapter) hc
INNER JOIN
(
SELECT s, l, MAX(get_json_object(json_data, '$.CurrentEncounter')) as highest_encounter 
FROM appl9_evt
WHERE month = "201508" AND st1 = "player" AND st2 = "level_progression" AND n = "level_start"
GROUP BY s, l
ORDER BY highest_encounter
) he
ON hc.s = he.s AND hc.highest_chapter = he.l 
GROUP BY highest_chapter, highest_encounter

Then I save it as a table and try to get only version 2.2.1 (or whatever version, a self-join I think it's called) with this:

SELECT COUNT(DISTINCT highest.s) as users, highest_chapter, highest_encounter FROM
(SELECT users as s, highest_chapter, highest_encounter 
FROM augusers221 ) highest
JOIN
(SELECT s 
FROM appl9_cpu
WHERE v_maj = '2.2.1') ver
ON highest.s = ver.s
GROUP BY highest_chapter, highest_encounter
ORDER BY highest_chapter, highest_encounter

But there's something wrong with this second stage, because I can't pull any data... Thank you in advance for looking at this wall of text.



via Chebli Mohamed

Sending to Multiple Emails in PHP

There is something off in this php, after the Reply-To email address in an email - I am getting a Cc afterward and it's not getting send to both the CC & BCC. This tells me I am making an error somewhere in this code and it's probably really obvious.

// Create email 
$email_subject = "Subject";
$email_body = "You have received interest. \n\n".
              "Name: $name \nEmail: $email \n";
$headers = "From: 1-email@email.com\n";
$headers .= "Reply-To: $email";
$headers .= "Cc: 2-email@email.com\r\n";
$headers .= "Bcc: 3-email@email.com\r\n";

mail($to,$email_subject,$email_body,$headers); // Post message



via Chebli Mohamed

bootstrap datepicker won't load from javascript

When I load the datepicker through the data-provide="datepicker", it will show up but not in safari. I also need to block out dates, such as the weekend. I was thinking both problems could be solved loading it through javascript and throwing in some config variables but I'm getting an error:

ReferenceError: $ is not defined

I'm thinking it's because maybe the jquery is being loaded in the wrong order, but other functionality is working.

Test site is here: http://ift.tt/1IAc7WZ

Field for datepicker is under "Select your prefered day & time"

Any help would be greatly appreciated!



via Chebli Mohamed

Select mismatch column values from database

I want to select and fetch all mismatch value of two table having same Column Name But Id, Name and City are different. I am Using Sql Server Management Studio

Table A:

id   Name   City

1    John   karachi

2    smith  Capetown

3     liza   Washington        

Table B:

id   Name   City

7    Grey   Dubai

8    Clarke  Texas

9     liza   Washington

OUTPUT:

7    Grey   Dubai

8    Clarke  Texas



via Chebli Mohamed

Can't Match Dates in VBA

My code is:

Application.Match(DateValue(x),dat,0)

and it's returning Error 2042

In the Watches I can see that:

The value of x is 02/01/2015 and it is a Variant/Date

The values ox DateValue(x) is 02/01/2015 and it is a Variant/Date

The value of dat(0) is #02/01/2015# and it is of the type Date

Any insights on why I'm getting th #N/A error ?

Thanks !

enter image description here



via Chebli Mohamed

Firebase Angularfire and Angular-nvD3

please visit this link. I used firebase as a backend data store. the front end is Angular. I try to draw chart by Angular-nvD3.js. when I try to read the data from firebase it is take time. So, the array come empty Array[]. then the data come but no update to the chart.

can someone help PlZ



via Chebli Mohamed

How to update a table with values coming from another table?

I found similar ones at here, but not exactly the same.

Here is what I need:

I have two tables a and b, with the following structures:

Table a:

id  b_id    b_col2 b_col3 col5
1   NULL    NULL   NULL   NULL
2   XXX     XXX    XXX    XXX

Table b:

id    col2 col3
101   ABC  DEF
102   XXX  XXX

UPDATE: The goal is that with three given inputs (id, b_id, col5), one row of table a should be updated accordingly. Specifically, b_col2 and b_col3 are extracted from table b with that b.id = b_id. For example, I want to update the first item of a with b_id=101 and col5 = ZZZ. Notice that b_col2 = ABC and b_col3 = DEF in this case, the updated row should be:

id  b_id    b_col2 b_col3 col5
1   101     ABC    DEF    ZZZ

I know there is at least a not-so-effective way which I don't like:

update a set 
    a.b_id = some-id, 
    a.b_col2 = (SELECT col2 FROM b WHERE b.id = some-id),
    a.b_col3 = (SELECT col3 FROM b WHERE b.id = some-id),
    ...
    where a.`id` = xxx

As I said, this is not a very good method, and I am just wondering if there is any better method?



via Chebli Mohamed

CakePHP dynamic form inputs

I'm using CakePHP 2.3.8 and I'm trying to create a form with dynamically added inputs from this tutorial but I'm having some issues. The adding and removing of inputs works just fine, but when I submit the form I get a black hole error message. Upon inspecting the inputs, it doesn't appear as if the key value isn't properly set and causing some issues with the id's of the inputs.

For example, with this code in an element

//Elements/users.ctp
$key = isset($key) ? $key : '<%= key %>';

<tr>
    <td><?php echo $this->Form->input("Role.{$key}.user_id", array('options' => $users, 'label' => false)); ?></td>
    <td class="actions">
        <a href="#" class="remove">Remove User</a>
    </td>
</tr>

this is the select that is generated

<select name="data[Role][0][user_id]" id="Role<%=Key%>UserId">

Edit

The value of $key is being set correctly on /Elements/users.ctp. I can create a row and echo the output of $key, and a number for the row appears correctly. As you can see above, the name of the element is set correctly, but the id is still being set strangely.

The name of the select element is being set properly, but not the id. What is causing the select id to be Role<%=Key%>UserId rather than Role0UserId?



via Chebli Mohamed

Django TemplateDoesNotExist at (but file exists)

I have an issue with template rendering.

Indeed django finds my templates files but each of them uses {% extends "base.html" %} and django does not find "base.html"

Django tried this path :

/home/gi-karna/hellodjango/tfjm2/inscription/templates/base.html (File does not exist)

and my template file is in :

/home/gi-karna/hellodjango/tfjm2/inscription/templates/inscription/home.html, error at line 2

It is real weird as the file "base.html" does exist at the first path. I don't know where the problem is.

I look forward to hearing from you soon



via Chebli Mohamed

Memory Leak - Socket or String related?

I have a simple function that allows me to get contents of a file on a server. It works just the way I want but "Visual Leak Detector" points out there is a memory leak on line closeSocket(...).

Code below:

string executeUrl(const char *url)
{
    SOCKET sConnection;
    char szHeader[500];

    sprintf(szHeader, "GET %s HTTP/1.0\r\n"
    "Host: %s\r\n"
    "User-Agent: Agent\r\n"
    "\r\n", url, HTTPSERVER);

    sConnection = HTTPConnectToServer(HTTPSERVER);
    if (sConnection == 0)
    {
        return "";
    }
    send(sConnection, szHeader, strlen(szHeader), 0);
    char reply[1024];
    ZeroMemory(reply, 1024);
    if (recv(sConnection, reply, 1024, 0) == SOCKET_ERROR)
    {
        return "";
    }
    string returnString(reply);
    closesocket(sConnection);
    WSACleanup();
    return returnString;
}

The data leaked is the string returnString. So it's either string related or something with closesocket().

I did some reading and I can't figure it out. Apparently strings should take care of themselves and not cause memory leaks, should they?



via Chebli Mohamed

NODEJS [electron io.js] send input to spawned process child.stdin.write();

I have a set of scripts in PowerShell. I built a GUI with a .HTA, but I am migrating over to a NODE.js like approach.

I have a working script, but I had to make a modification to work around the lost functionality to get input from the command line. I used to have the CMD prompt window appear where I would see all output and, if there was a prompt (Read-Host), the user could interact with it. To work around that, I am now using [Microsoft.VisualBasic.Interaction]::InputBox() to get input from the user when needed.

I have had issues trying to use child.stdin.write(); because my PowerShell process just hangs. It will not respond to my input.

I have tried every answer I have found on the net, with no success. The script that is called in production is a long running process, depending on the task selected it will take from 20 min to 3 hours.

So, issue is I cannot get the child.spawned process to send the input, or maybe PowerShell does not accept input from sdin.

Thanks for your help in advance.

CODE:

HTML:

<button type="button" id="btn_ExecuteReport">Run Report</button>
<button type="button" id="btn_StopReport" >Stop Report</button>
<button type="button" id="btn_SendInput" >Send this...</button>
<h2>Results:</h2>
<p id="result_id">...</p>
<br/>

JS (using Electron v 0.31.0, io.js v 3.1.0, jQuery v 1.7.2):

$(document).ready(function () {
    $("#btn_ExecuteReport").click(function (event) {
        event.stopPropagation();
        global.$ = $;

        var remote = require('remote');
        // to get some paths depending on OS
        var app = remote.require('app');
        //clipboard
        var clipboard = require('clipboard');
        var shell = require('shell');
        // for choosing a folder
        var dialog = remote.require('dialog');
        var spawn = require('child_process').spawn;
        sCmd = "powershell.exe ";
        sCmdArg = '&' + "'" + __dirname + "/app.ps1' " ;
        // omit parameters for the purpose of this example
        //    + "-ODir '" + sOutputDirectory 
        //    + "' -WDir '" + sWorkingDirectory + "'" 
        //    + " -Report " + sReport 
        //    + " -pSendEmail " + sSendEmail 
        //    + " -pSendEmailHTMLBody " + sSendEmailHTMLBody 
        //    + " -pCreateReport " + sCreateReport 
        //    + " -pCheckReport " + sCheckReport 
        //    + " -pEmailAction " + sEmailAction
        //    ;
        $("#result_id").html("<p><font color='magenta'>Command: </font>" 
                                          + sCmdConcat + "</p>");
        // try again with spawn and event handlers
        var psSpawn = spawn(sCmd, [sCmdArg]);
        // add a 'data' event listener for the spawn instance
        psSpawn.stdout.on('data', function(data) { 
            console.log('stdout: ' + data); 
        });
        // add an 'end' event listener to close the writeable stream
        psSpawn.stdout.on('end', function(data) {
            console.log('Done with psSpawn...' );
        });
        psSpawn.stderr.on('data', function (data) {
            console.log('stderr: ' + data);
        });
        // when the spawn child process exits, check if there were any errors and close the writeable stream
        psSpawn.on('exit', function(code) {
            if (code != 0) {
                console.log('[EXIT] Failed: ' + code);
            }
            //Collect result from PowerShell (via clipboard)
            sResultData = clipboard.readText("Text");
        });

        psSpawn.on('close', function(code) {
            if (code != 0) {
                console.log('[ISSUE] code: ' + code);
            }
            console.log('[CLOSE]');
        });
        //sending the input with button #btn_sendInput
        $("#btn_SendInput").click(function (event) {
            psSpawn.stdin.setEncoding('utf8');
            psSpawn.stdin.write('ok');
            psSpawn.stdin.write('\n');
            psSpawn.stdin.write(os.EOL);
            //uncomment following line to end stdin on first button press
            //psSpawn.stdin.end();
        });

        // killing process
        $("#btn_StopReport").click(function (event) {
            event.stopPropagation();
            psSpawn.kill('SIGTERM');
            console.log('killed ' + psSpawn.pid);
        });
    });
});

PowerShell:

#work around to lack of Read-Host functionality
Write-Host "waiting"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$computer = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a computer name", "Computer", "$env:computername") 
#
Write-Host "[Done] waiting"
#workaround END works 
Write-Host "Computer: [$computer]"
# START omit ----------------
#if we remove the following lines, all works but we lose the functionality to ask for input from the command line
Write-Host "Propmt for OK" 
$ok = Read-Host 
#
Write-Host "Prompt. Value of 'ok': [$ok]"
# END omit ----------------
#Copy new message to clipboard
"we want to see this maessage on the browser. $computer" | clip

#Exit script returning the appropriate value
[Environment]::Exit(0)
exit

My console output is:

stdout: waiting
daily_deviation.js:103 stdout: 

daily_deviation.js:103 stdout: [Done] waiting
Computer: [0199HR10A]
Propmt for OK

The script hands no matter how many times I press Send this.... The console output is (after pressing the #buton_StopReport):

killed 2548
daily_deviation.js:107 Done with psSpawn...
daily_deviation.js:115 [EXIT] Failed: null
daily_deviation.js:140 [ISSUE] code: null
daily_deviation.js:142 [CLOSE]



via Chebli Mohamed

Stop Loading Nodes in Ajax Loading / Lazy Loading in JSTree

I am using JSTree with Ajax Loading / Lazy Loading functionality in my application.

Now I am trying to Open All nodes. So in Loaded event i write open_all method to open all nodes.

$('#DIVTree').jstree({
        'core': {
            'multiple': false,
            'data': {
                'url': appRootDir + 'Tree/GetFilterList',
                'data': function (node) {
                    return { 'ID': node.id};
                }
            }
        },
        'plugins': ['state'],
}).on('loaded.jstree', function (node) {
    $('#DIVTree').jstree(true).open_all();
});

Now this starts opening all node which i actually wanted.

But now i am having one more button Cancel.

I want to allow user to stop loading nodes when the cancel button is pressed.

I tried lots of ways. I tried to implement recursion with "after_open" event and "load_node" event.

$('#DIVTree').jstree({
        'core': {
            'multiple': false,
            'data': {
                'url': appRootDir + 'Tree/GetFilterList',
                'data': function (node) {
                    return { 'ID': node.id };
                }
            }
        },
        'plugins': ['state'],
}).on('loaded.jstree', function (node) {
        if (recrusiveStop == false) {
            OpenNodes();
        }
}).on('after_open.jstree', function (node) {
        if (recrusiveStop == false) {
            OpenNodes();
        }
});

var OpenNodes = function () {
    var nodeID = '';

    $('#DIVTree .jstree-closed').each(function () {
        if ($('#DIVTree').jstree(true).is_loaded(this.id) == false) {
            nodeID = this.id;
            return false;
        }
    });

    if (nodeID != '') {
        $('#DIVTree').jstree(true).open_node(nodeID);
    }
}

But still unable to implement.

In "after_open" event is fired only once. So only one node is expanded (not having sub-node) so not staying in loop. while i still want to expand siblings.

Is there any clear way to implement this?

I want to Open all nodes and also stop loading when user hits cancel button.



via Chebli Mohamed

Does New Macbook 12inch is able to run php with mysql?

I have a database class, and it needs to run php , mysql, tomcat. I just want to know does the new Macbook 12inch should be able to do that ?

I might need to do some programing exercise for fun... just want to know if this new mac can handle it....



via Chebli Mohamed

Swift - check if JSON is valid

let data = NSData(contentsOfFile: "myfile")
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonData: NSData! = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
var validJson = false

if (NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) != nil) {
    validJson = true
}

I want the code above to only set validJson true when the contents of jsonData is actually valid JSON. At the moment if I pump anything into the "myfile" file which can be seen in the code, validJson is always true.

How can I fix this so validJson is only true when it's actually valid JSON?



via Chebli Mohamed

Firefox is blocking insecure content

I am running a UI automation script on a https site. I get 'Firefox is blocking insecure content" warning every-time on a particular page. for now i am manually disabling protection from options but, how to set protection disabled permanently so that my scripts won't break when i run them for regression?

enter image description here



via Chebli Mohamed

SQL query to make distinct lines with case being used

Here is what my data looks like on the table I am querying

Table 1

ITEM     SEQUENCE     CODE
Item1       1            A 
Item1       2            B
Item2       1            B
Item2       2            C
Item2       3            D

My current Query looks like

  Select Distinct Table1.ITEM, 
  case when Table1.SEQUENCE = '1' Then Table2.DSC end As FirstDSC,
  Case When Table1.SEQUENCE = '2' then Table2.DSC End As SecondDSC,
  Case When Table1.SEQUENCE = '3' Then Table2.DSC End As ThirdDSC
    From Table1
    Join Table2 on Table2.Code = Table1.Code
    Where Table1.Item In (Subquery here to find distinct values that Item can be)

It currently returns the data looking like

ITEM  FIRSTDSC SECONDDSC THIRDDSC
Item1   DSC-A     NULL      NULL
Item1   NULL     DSC-B      NULL 

I was wondering how to make the data return looking like

ITEM FIRSTDSC  SECONDDSC  THIRDDSC
Item1  DSC-A      DSC-B       NULL
Item2  DSC-B      DSC-C       DSC-D

Is there a good way to do this or am I going in the completely wrong direction with my query currently?



via Chebli Mohamed

On mouseout animate line to disappear

Right now, I've got it to draw a line when you mouseon but I want it so that when you mouseout the line disappears left to right.

http://ift.tt/1IA9dl9

$( "#name" ).mouseover(function() { 

$('.slider').animate({
    width: $('#name').width()
}, 1000);

});



via Chebli Mohamed

Access to GitHub only possible with

I can successfully add files to a local repository and push it to github using github desktop. When I try to commit to github using the git commandline or GitExtensions I get an error

"C:\Program Files\Git\bin\git.exe" push --recurse-submodules=check --progress "origin" refs/heads/master:refs/heads/master
remote: Invalid username or password.
fatal: Authentication failed for 'http://ift.tt/1EtNNuM'
Done

I dont have 2fa enabled. What is github desktop doing different that it can login?



via Chebli Mohamed

Are there Powershell cmdlets that install and remove Windows drivers?

Note: For this question, when I refer to "Windows drivers" I mean .inf and associated files which can otherwise be installed by right-clicking the .inf and clicking "Install" in Windows Explorer. I do not mean any kind of setup.exe-style executable which might install a driver.


There exists the following:

I have not, however, found a corresponding Powershell Cmdlet that supports installing and uninstalling drivers on the running system. I'm sure I could wrap dpinst.exe in some powershell, but I'd like to avoid mapping command line parameters and parsing output if a more Powershell-native method exists.

Do Powershell Cmdlets exist that install and uninstall Windows drivers on the running system? Is there some other way to install and uninstall Windows drivers using Powershell that does not involve dpinst.exe?



via Chebli Mohamed

Accessing audio input while loading a project from file://

I wonder to know if it is possible to somehow prevent Chrome from blocking my project audio input because I'm not loading it from a local host but from file://... a.k.a. my HDD. I'm asking about this because I've understood that when the script is non-server but loaded from file:// Chrome automatically blocks it and it can't reach the asking for mic usage permission step. I'm playing around with annyang, so yeah, if someone knows how to enable the described above, please share, as I still have no idea of php, mysqul and others for establishing a local host environment.



via Chebli Mohamed

Which index is needed for a Mongoid order_by and find_by query?

To find the most recently created user named "Jeff",

User.order_by(created_at: :desc)
    .find_by(name: "Jeff")

Which indexes should be created for this query? Would it be 2 indexes, on created_at and name?

Or a compound index on both?



via Chebli Mohamed

Dynamically resize columns based on how many there are in a row

I'm trying to make a responsive column layout that resizes depending on the number of columns.

Link to JsFiddle

<div class="row">
<div class="box half">1/2</div>
<div class="box quarter">1/4</div>
<div class="box quarter">1/4</div>
</div>

<div class="row">
<div class="box half">1/2</div>
<div class="box quarter hidden">1/4</div>
<div class="box quarter">1/4</div>
</div>

So, what I'm trying to do is if I add the class "hidden" to one of the boxes, the other boxes will resize and fill up the row. For example, in the first row we have one column 50% and two columns 25%; If I hide one 25% column, the first column will have 66% and the 2nd one will have 33%.

I have to do this without adding any other classes to html and work in IE8+.



via Chebli Mohamed

Subtraction/dfference between bytes in Java

I'm trying to subtract one byte from another while making sure no overflow happens, but get unexpected results.

In the following code, I expect data2 array to be subtracted from data1 array. However I get low values when I am sure there should be high ones.

    for (int i = 0; i < data1.length; i++) {
        if (data1[i] > data2[i]) {
            dest[i] = (byte) (data1[i] - data2[i]);
        } else {
            dest[i] = 0;
        }
    }

I figured I should make sure data2 byte isn't negative and being added to data1. So I came to:

    for (int i = 0; i < data1.length; i++) {
        if (data1[i] > data2[i]) {
            dest[i] = (byte) (data1[i] & 0xff - data2[i] & 0xff);
        } else {
            dest[i] = 0;
        }
    }

However this also doesn't give the right results.

I hope I'm doing something stupidly wrong here, or my problem resides somewhere else of which I can't figure out where.



via Chebli Mohamed

Check if pointer object created is less than today Parse.com

hey guys i have a table A which has a pointer to Table B. I am trying to query Table A where Table B created At is less than today

Table A (columns)

Name, Table B pointer, ....

Table B CreatedAt

So far I have this

    let query = PFQuery(className:Globals.ParseObjects.ProLeagueWinnings)
    query.fromLocalDatastore()
    query.fromPinWithName("XXX")

    query.includeKey("TableB")

    query.whereKeyExists("TableB")
    query.whereKey("TableB.CreatedAt", lessThanOrEqualTo: NSDate())
    query.findObjectsInBackground().continueWithSuccessBlock {
        (task: BFTask!) -> AnyObject! in

        let leagues = task.result as? [ProLeagueWinnings]
        if (completion != nil){
            if leagues != nil{
                completion!(leagues!)
            }else{
                completion!([])
            }
        }

        return task
    }

But it returns everything.



via Chebli Mohamed

Implementation of method accepting lambda

I'm interested to understand how are implemented LabelFor, EditorFor... methods that accept lambda expressions in MVC.

Lets say I have a class Person and I want to print the name and the value of a property. How must be implemented Label() and Editor() methods?

  class Person
  {
     public int Id { get; set; }
  }

  void Label(Expression<Func<Person, int>> expression)
  {
     //...
  }

  void Editor(Expression<Func<Person, int>> expression)
  {
     //...
  }

  public void Test()
  {
     Person p = new Person
     {
        Id = 42
     };

     Label(x => x.Id );  // print "Id"
     Editor(x => x.Id); // print "42"

  }



via Chebli Mohamed

Panel sliding from the bottom

I want to implement panel, that by default appears from the bottom only by 1/4. And when i tap on this part, or swipe it, it should roll out on full screen.

exactly what i want was implemented in this app

So what i tried already: Making UIView and trying to apply tap and swipe gestures. UIView didn't catch it. But it caught touchesMoved, touchesEnded etc. UITableView. Same. Making UIViewController. Ended without any idea how to handle it to right way.

So any ideas or links are appreciated. Thanks in advance.



via Chebli Mohamed

Finding and replacing strings with certain character patterns in array

I have a pretty large database with some data listed in this format, mixed up with another bunch of words in the keywords column.

BA 093, RJ 342, ES 324, etc.

The characters themselves always vary but the structure remains the same. I would like to change all of the strings that obey this character structure : 2 characters A-Z, space, 3 characters 0-9 to the following:

BA-093, RJ-342, ES-324, etc.

Be mindful that these strings are mixed up with a bunch of other strings, so I need to isolate them before replacing the empty space.

I have written the beginning of the script that picks up all the data and shows it on the browser to find a solution, but I'm unsure on what to do with my if statement to isolate the strings and replace them. And since I'm using explode it is probably turning the data above into two separate arrays each, which further complicates things.

<?php

require 'includes/connect.php';

$pullkeywords = $db->query("SELECT keywords FROM main");

while ($result = $pullkeywords->fetch_object()) {

    $separatekeywords = explode(" ", $result->keywords);
    print_r ($separatekeywords);
    echo "<br />";
}

Any help is appreciated. Thank you in advance.



via Chebli Mohamed

Autocomplete: from pure JS to ReactJS

I am working on an auto-complete, right now I have it in pure JS

here I have this example in JSFiddle

<input type="text" onkeyup="changeInput(this.value)">

<div id="result"></div>

the js part

var people = ['Steven', 'Sean', 'Stefan', 'Sam', 'Nathan'];

function matchPeople(input) {
  var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
  return people.filter(function(person) {
    if (person.match(reg)) {
      return person;
    }
  });
}

function changeInput(val) {
  var autoCompleteResult = matchPeople(val);
  document.getElementById("result").innerHTML = autoCompleteResult;
}

but I need to translate it to ReactJS, and I am not getting good results

let people = ['Steven', 'Sean', 'Stefan', 'Sam', 'Nathan'];

class Login extends Component {

  render () {
    return (
      <Grid>
          <input type="text" onkeyup={this._changeInput(this.value)} />
          <div id="result"></div>
      </Grid>
    );
  }

  _matchPeople = (input) => {
    var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
    return people.filter(function(person) {
      if (person.match(reg)) {
        return person;
      }
    });
  }

  _changeInput = (val) => {
    var autoCompleteResult = this._matchPeople(val);
    document.getElementById("result").innerHTML = autoCompleteResult;
  }  

}

Error in the console:

Uncaught TypeError: Cannot read property 'split' of undefined

what am I missing ?



via Chebli Mohamed

Matching values from different columns, GOOGLE SHEETS

Google sheets,

I have columns a with 5000 rows and column b with 3000 rows.

How to check if value from A1,A2,A3 ETC is in B1:B3000 so I would see 5000 rows in column C with either True or False?



via Chebli Mohamed

Send a bitmap image in an email

I looked over similar questions and tried to write this simple code. This code takes an bitmap image of the view then allows the user to attach it to email. for some reason I get the message "can't attach an empty file" in the email application. I'm fairly new to this and I read a few examples and tried different things but non worked. I suspect that something might be wrong with my path.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
package="com.example.asamater.myapplication" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"   android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/scrollView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/linearLayout">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText"
            android:text="Q1" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton2" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText2"
            android:text="Q2" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton3" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton4" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText3"
            android:text="Q3" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton5" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton6" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText4"
            android:text="Q3" />


        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton7" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton8" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText5"
            android:text="Q4" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton10" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton9" />
        </RadioGroup>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Email"
            android:id="@+id/button"
            android:layout_alignTop="@id/radioButton9"
            android:onClick="email" />

    </LinearLayout>



</ScrollView>

</RelativeLayout>

.

 package com.example.asamater.myapplication;

 import android.app.Activity;
 import android.content.Intent;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.BitSet;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public void email(View view){
    ScrollView z = (ScrollView) findViewById(R.id.scrollView);
    int totalHeight = z.getChildAt(0).getHeight();
    int totalWidth = z.getChildAt(0).getWidth();
    Bitmap bitmap = getBitmapFromView(z,totalHeight,totalWidth);
    String path = saveImageToStorage(bitmap);

    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "ammar5001@gmail.com");
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "report");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, " ");

    emailIntent.setType("image/jpeg");
    File bitmapFile = new File(Environment.getExternalStorageDirectory()+
            "/"+ path);
    Uri myUri = Uri.fromFile(bitmapFile);
    emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);


    startActivity(Intent.createChooser(emailIntent, "Send your email in:"));

}


private String saveImageToStorage(Bitmap bitmap) {
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/req_images");
    myDir.mkdirs();
    String fname = "Image-Report.jpg";
    File file = new File(myDir, fname);
    Log.i("myActivity", "" + file);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
        return root + "/req_images" + fname;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}


public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
    Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}

}



via Chebli Mohamed

How to convert Multilevel numbering list from Word document into text value in HTML

I am reviewing multiple Rich Text Editors to find the right one for a VB.NET web application which has IE11 incompatible Rich Text Editor.

With the IE11 compatibility, the most important requirement from clients is a functionality that copies contents from Word documents over into text editor without losing it Word formatting. (The content will be saved into database and be read by MS Word again)

However, all the Rich Text Editors that I have reviewed do not support the multilevel list formatting correctly. They change the multi-level numbers into single level numbers when coping the multi-level list from Word into them. - Rad Editor, CKEditor, tiny-mce and Rich Text Editor and so on.

Example,

1. A
  1.1. B
  1.2. B
    1.2.1. C
2. A
  2.1. B
  2.2. B

becomes

1. A
  1. B
  2. B
    1. C
2. A
  1. B
  2. B

I found a CSS trick to display <li> tag as multilevel numbers in the browser, but the numbers are not actual text values that can be saved into database. So, I need another solution that can save numbers and their format into the database like the current Rich Text Editor in my VB.Net web application. (It is a DLL, but not JavaScript library)

Can I get some helps/advices how to resolve this problem when copying over multi-level numbering list from Word into the RichTextEditor?

Thanks for answering in advance.



via Chebli Mohamed

Bootstrap column reordering on at least three screen sizes

I have problem with Bootstrap column rendering when I try to specify column reordering for three different screen sizes.

XS devices:

  • A
  • B
  • C
  • D

SM and MD devices:

  • B A
  • D C

LG devices:

  • D C B A

I can achieve XS and LG pattern or XS and MD pattern, but unfortunately not all three options at the same time. Is this possible with Bootstrap's classes?

Solution for XS and LG:

<div class="container">
    <div class="row">
        <div class="col-xs-12 col-lg-3 col-lg-push-9">
            <div class="form-group">
                <label>Label1</label>
                <input type="text" class="form-control" />
             </div>
        </div>

        <div class="col-xs-12 col-lg-3 col-lg-push-3">
            <div class="form-group">
                <label>Label2</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-lg-3 col-lg-pull-3">
            <div class="form-group">
                <label>Label3</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-lg-3 col-lg-pull-9">
            <div class="form-group">
                <label>Label4</label>
                <input type="text" class="form-control" />
            </div>
        </div>
    </div>
</div>

Now when I add middle view classes all get messed up. Is there an option to fix this?

<div class="container" style="background-color: pink">
    <div class="row">
        <div class="col-xs-12 col-md-6 col-md-push-6 col-lg-3 col-lg-push-9 col-lg-pull-0">
            <div class="form-group">
                <label>Label1</label>
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-md-6 col-md-pull-6  col-lg-3 col-lg-push-3 col-lg-pull-0">
            <div class="form-group">
                <label>Label2</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-md-6 col-md-push-6 col-lg-3 col-lg-pull-3 col-lg-pull-0">
            <div class="form-group">
                <label>Label3</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-md-6  col-md-pull-6 col-lg-3 col-lg-pull-9 col-lg-push-0">
            <p>empty</p>
        </div>
    </div>
</div>

The following code is my best try but it simply does not work... Any ideas?



via Chebli Mohamed

Why does my OneToOne mapping through a JoinTable not work?

I've searched but cannot seem to find the answer.

I have two tables:

select ts_id, tsjoin_id, workdate from TimeSheets
select e_id, lastname from Employees

I also have a join table:

TSJoin
tsjoin_id, employee_id

There is only one Employee to a TimeSheet. So with any given TimeSheet entity, I'd expect to be able to:

TimeSheet ts = tsService.getTimeSheet(123);
String lastName = ts.getEmployee().getLastName();

In SQL, to get the employee of a TimeSheet:

select e.lastname from TimeSheets t
    join TSJoin x on (x.tsjoin_id = t.tsjoin_id)
    join Employees e on (e.e_id = x.employee_id)
where t.ts_id = 123

In my Hibernate mapping, I have:

@OneToOne
@JoinTable(
        name = "TSJoin",
        joinColumns = {
                @JoinColumn(name = "tsjoin_id", nullable = false)
        },
        inverseJoinColumns = {
                @JoinColumn(name = "e_id", nullable = false)
        }
)

However, the SQL it's generating is:

select * from TimeSheet t
    left outer join TSJoin x on (t.ts_id = x.tsjoin_id)

Which returns null for the Employee.

It's taking the primary key of the TimeSheet and trying to match the primary key of the join table.

What am I doing wrong?

EDIT

I also want to state that I have only setup one direction at this point. Which is a TimeSheet -> Employee (OneToOne) and that Employee is not mapped to TimeSheet yet. Not sure if this makes a difference but I wanted to mention it.

EDIT 2 I also want to state that I believe the error might be because my join table does not contain a reference to the TimeSheet. And Hibernate is assuming that a join table is going to contain the primary keys of each entity involved (legacy database). I could probably create a mapping of TimeSheet -> JoinTable -> Employee and access it as: ts.getJoin().getEmployee() but that's pretty ugly.



via Chebli Mohamed

Odd Errors Displayed Only in Console When Trying to Run Program

So I'm watching a tutorial to learn how to program in Java using Eclipse. So I got a few episodes in and I had to clear out all out the errors. I looked around and found no more errors so I tried to run the program and I got errors in that were only displayed in the console, and was being displayed next to the lines it was referencing. I have completely no idea how to solve these errors I haven't seen anything like them before. Also my program is fairly simple it is just the code to display and window and then have pixels of a random colour fill that window. I really would appreciate any help I can get, because I have no clue how to fix this error.

Thanks, Nova

Tutorial

Error:

`Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar` 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 65536 
at cpm.mime.GameP1.graphics.Screen.<init>(Screen.java:14) 
at com.mime.GameP1.Display.<init>(Display.java:29) 
at com.mime.GameP1.Display.main(Display.java:92)`



via Chebli Mohamed

Linq Expression in Case Statement

I'm using LINQ with Expression trees and a case Statement in my Select. I'm doing this because the Where Condition is build dynamically and in my Result, I need to know, which part of the where was true.

This works fine:

ParameterExpression peTbl = Expression.Parameter(typeof(MyTbl), "mytbl");

Expression left = Expression.Property(peTbl, "Col1");
Expression right = Expression.Constant((ulong)3344, typeof(ulong));
Expression e1 = Expression.Equal(left, right);

left = Expression.Property(peTbl, "Col2");
right = Expression.Constant((ulong)27, typeof(ulong));
Expression e2 = Expression.Equal(left, right);

Expression predicateBody = Expression.Or(e1, e2);

Expression<Func<MyTbl, bool>> whereCondition = Expression.Lambda<Func<MyTbl, bool>>(predicateBody, new ParameterExpression[] { peTbl });

var query = myTbl.Where(whereCondition)
            .Select(s => new { mytbl = s, mycase = (s.Col1 == 3344 ? 1 : 0) });

But now, I want to use the Expression e1 in my case Statement.

Something like this:

var query = myTbl.Where(whereCondition)
            .Select(s => new { mytbl = s, mycase = (e1 == true ? 1 : 0) });

Any idea how to do this?



via Chebli Mohamed

Python One-Liner: Sorting by multiple, interdepending keys

Disclaimer: This question is about me and hopefully others understanding Python better. My problem can be solved easily in more than one line, I know that.

Suppose I have two functions f(x), g(x,y) so that I can compute the tuple ( f(x), g(x,f(x)) ) as a function of x. I want to sort a list X by these two keys but computing f(x) is expensive so I want to do it only once per x. My current solution is:

X_s = sorted( X , key =  lambda x: (lambda y: ( y , g(x,y) ) )( f(x) ) )

Can I achieve the same without using two lambda functions?



via Chebli Mohamed

Database for user Accounts ionic framework

I need to incorporate a simple user profile for each person who uses my ionic android app. That way they can login and access or edit personal information unique to their personal accounts.

I've been browsing all over the net for a day, and especially the ionic documentation for any info on how to make such a feature on my app. I can do that using php and mysql but don't know about ionic's approach. Please advice.



via Chebli Mohamed