lundi 31 août 2015

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

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

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

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

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

How can I increase performance of the active record iteration (rails)

I have the following code, but it takes approximately 3 minutes to process 1000 records. In production I am expecting to have 1 000 000 of records and this performance is unacceptable to process such amount of records. Any idea how to make this faster? I am new with Rails, so still learning the things on the go.

In the example below, I am trying to iterate all products for given supplier and if the product item_id is not in the xml feed, include the product id into array which I will be iterating in the next step and marking the products as "archived / inactive". The problem is mainly with the first part of the code, which takes too much time to process.

self.products.where( :archived => false ).find_each do |p|
   archive = !@xml_feed.css("ITEM_ID").to_s.downcase.include?("<item_id>#{p.item_id}</item_id>")
   archived_product_ids << p.id if archive
end

if archived_product_ids.size > 0
   # update all archived products
   Product.where('id IN (?)', archived_product_ids).update_all( :archived => true, :archived_at => Time.now, :active => false )
   logger.info "Products #{archived_product_ids.to_s} has been archived and deactivated."
end

This is the output in my console where you can see 3 minutes between processing each 1000 records:

[2015-08-31T22:28:18.090063 #28332] DEBUG -- :   Product Load (5.0ms)  SELECT  "products".* FROM "products" WHERE "products"."supplier_id" = $1 AND "products"."archived" = $2  ORDER BY "products"."id" ASC LIMIT 1000  [["supplier_id", 2], ["archived", "f"]]

[2015-08-31T22:31:14.767496 #28332] DEBUG -- :   Product Load (5.3ms)  SELECT  "products".* FROM "products" WHERE "products"."supplier_id" = $1 AND "products"."archived" = $2 AND ("products"."id" > 2513)  ORDER BY "products"."id" ASC LIMIT 1000  [["supplier_id", 2], ["archived", "f"]]



via Chebli Mohamed

How to detect printing app when splwow64.exe is involved?

We have a print driver that captures the name of the printing exe within the driver's UI module. It does this by using the GetModuleFileName function. This works well until a 32-bit prints on a 64-bit machine. In that scenario Windows invokes splwow64.exe to print on behalf of the 32-bit application, and so GetModuleFileName returns "splwow64.exe" as the printing app rather than the one that is actually doing the printing.

We attempted to solve this by capturing splwow64.exe's parent process with the Toolhelp32 API, but this is not reliable since splwow64 remains loaded once the first app finishes printing in order to service other apps. This means that the parent process may or may not be the process that's actually printing. So far, we have been unable find any files or named pipes or other IPC objects that connect splwow64 and the printing application.

Microsoft released a hot fix (KB2815716) that causes splwow64 to terminate after a user-specified timeout period, but that doesn't solve the problem because splwow64.exe remains in memory indefinitely as long as the first printing app that invoked it remains loaded. It completely ignores the timeout the hot fix provides. (I would consider this a Windows bug.)

My question is this:

We need a method of reliably determining which application is printing when it happens to be 32-bit and splwow64.exe is being used.

The solution can reside in a print driver or in a user-mode application -- either is fine. We would strongly prefer not to use techniques involving API hooking or code injection since those actions tend to be flagged by anti-virus software.



via Chebli Mohamed

How to add MVC pages to Asp.Net project in Visual Studio 2012?

I added Views and Controllers folder for now, but the action in the controller couldn't locate the view, what should I do?

The project I'm working on is a Asp.Net web form project, and currently we need to add log on pages using MVC, I'm not sure what else needs to be done to make the MVC routing work. Thank you very much!



via Chebli Mohamed

Using parent.parent inside setTimeout() function

Any idea why the function setTimeout() not working when I using in function

parent.parent(the function hide() fired but no delay).

setTimeout(parent.parent.ModalWindow.hide(), 5000);

Any idea what I am missing?



via Chebli Mohamed

Looking for a jQuery plugin for charts with dynamic multiple y-axis

I'm looking for a jQuery chart plugin that has the ability to have multiple y-axis. I know such plugins exist, like Highcharts, but mine will need to be a little more involved.

The page is a data log that allow the users to select multiple sensors to show the log history for. These sensors can have various data types. For example, one sensor may be temperature in F, another may be temperature in C, another may be an on/off switch...

Once the sensors are selected, I do an AJAX call to get the data. So I won't know the number of sensors that are selected, or what type of data the values will be. I know the x-axis will be a date/time stamp... that's it.

Currently I have the page working with the user only being able to select one sensor at a time, and I'm using Flot. That is working great right now, but the users want the ability to show multiple sensors at the same time.

Does anyone have any experience with this that can point me in the right direction? Thanks!



via Chebli Mohamed

Adding widgets to QGraphicsView

for(int i =0; i <shapes.size(); i++) // shapes is QList<QWidget*> of QShape
{
    shapes.at(i)->setShape(QShape::ellipse);
    QGraphicsProxyWidget* proxyWid = graphscene->addWidget(shapes.at(i));
}
view->setScene(graphscene);// view is a QGraphicsView object.

I have the above code that i am using to place a number of Qshapes on a Graphics view scene. looking a qt4.8 ressource i found that a QGraphicsProxyWidget need to be created to bridge the scene element with the different QWidget. the code works, but i have a concern wether the implementation is correct, is the proxywid pointer correctly allocated? is it safe to use a pointer this way? i am trying to avoid any memory problem.

Thanks in advance for assisting me



via Chebli Mohamed

Bundle Display Name only showing for some alerts iOS 9

Something weird is going on with this new iOS 9 update. I have some of the permission alerts displaying "(null)" and some of them displaying the actual name of the app:

"(null)" :

enter image description here

"MyAppName" :

enter image description here

Here's my Info.plist :

enter image description here



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

Not working Lang Changer in a Class Function PHP

Hello i try to implent a Language Changer in my Script.
But in my Class Function it is saying:
Notice: Undefined variable: lang in ......

I use a if else at begin of my Index.php which decide to includes the correct lang_xxx.php.

And in my lang_xx.php there is Array

    /* 
    -----------------
    Language: English
    -----------------
    */

    $lang = array();


$lang['welcome_msg'] = 'Welcome Guest';

And echo in my Class then

<?php echo $lang['welcome_msg']; ?>

So my Question why isnt this working and what is the correct way to implent this?

Its also not working when i include the lang_xx.php File directly in the Class Function.



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

Powershell parsing regex in text file

I have a text file:

Text.txt

2015-08-31 05:55:54,881 INFO   (ClientThread.java:173) - Login successful for user = Test, client = 123.456.789.100:12345
2015-08-31 05:56:51,354 INFO   (ClientThread.java:325) - Closing connection 123.456.789.100:12345

I would like output to be:

2015-08-31 05:55:54 Login Test 123.456.789.100
2015-08-31 05:56:51 Closing connection 123.456.789.100

Code:

$files = Get-Content "Text.txt"
$grep = $files | Select-String "serviceClient:" , "Unregistered" |  
Where {$_ -match '^(\S+)+\s+([^,]+).*?-\s+(\w+).*?(\S+)$' } |
Foreach {"$($matches[1..4])"} | Write-Host

How can I do it with the current code?



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

Formatting json data to group by items

I have angular application where I am trying to get json in particular format. I am pulling data from db and database has table data as

Country State 
China   chungchong
India   hyderabad 
USA     florida
India   delhi
USA     redmond

I am trying to get json with list of countries and each country having cities in an array.

angular.module('app')
.factory('CountyStatesService', [
    '$resource', function($resource) {
        return $resource('/api/GetCountryStates/');
    }
])

GetCountryStates() method is a csharp method which just returns list of all data from the table.

I am trying to get json sorted/grouped by in the below format

 data: [
               { text: "China", items: [
        {text: "chungchong"}
        ] },
               {
                   text: "India", items: [
                   { text: "Hyderabad" },
                   { text: "Delhi" }
                   ]
               },
               {
                   text: "USA", items: [
                   { text: "Florida" },
                   { text: "Redmond" }
                   ]
               }
            ]

But I am getting json with out grouping. How can I achieve json format as expected.

C# code

[HttpGet]
    public IEnumerable<CountrieStatesClass> GetCountryState()
    {
        return GetStructuredJson();
    }

public IEnumerable<CountrieStatesClass> GetStructuredJson()
    {
        List<CountrieStatesClass> locations = new List<CountrieStatesClass>();

        using (SqlConnection connection = new SqlConnection(MyConnectionString))
        {
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = "select * from tblCountryStateDetails";
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    CountrieStatesClass location = new CountrieStatesClass
                    {
                        CountryName = (string)reader["CountryName"],
            StateName=(string)reader["StateName"]
                    };
                    locations.Add(location);
                }
            }
            return locations;
        }
    }



via Chebli Mohamed

Separate fill for each shape in Flex graphics

I am drawing a bunch of circles in 2 horizontal rows across a sprite and would like a gradient applied to each circle individually but flex is applying it to the entire graphics area. What do I need to change to draw each circle with its own gradient?

var s:Sprite = new Sprite();
var g:Graphics = s.graphics;
g.beginBitmapFill(bd, new Matrix(), false, false);
g.drawRect(0, 0, s.width, s.height);
g.endFill();
var m:Matrix = new Matrix();
g.lineStyle(1, 0x888888, 1);
for(var i:int = 0; i < numSpirals; i++) {
    g.beginGradientFill(GradientType.LINEAR, [0x666666, 0xFFFFFF], [1, 1], [0, 255], m);
    xc = i * spiralWidth + spiralHoleRadius;
    yc = bdCenter - (spiralBoxHeight / 2) + (spiralHoleRadius / 2);
    g.drawCircle(xc, yc, spiralHoleRadius);
    g.endFill();
}
for(i = 0; i < numSpirals; i++) {
    g.beginGradientFill(GradientType.LINEAR, [0x666666, 0xFFFFFF], [1, 1], [0, 255], m);
    xc = i * spiralWidth + spiralHoleRadius;
    yc = bdCenter + (spiralBoxHeight / 2) - (spiralHoleRadius / 2);
    g.drawCircle(xc, yc, spiralHoleRadius);
    g.endFill();
}

Thanks for your help!

Edit - I forgot this part (may or may not be relevant). Before drawing the circles I drew the BitmapData from an ImageSnapshot of some UI elements onto the sprite as well.



via Chebli Mohamed

When to use RecyclerView?

Is it recommended to use a RecyclerView if i only have different Content or should I use a Layout as Container then?

What are the Pros/Cons of using RecyclerView in this Situation?



via Chebli Mohamed

Should I extend std::less for a comparison functor?

I want to create a shared_ptr content-comparison functor to stand in for std::less<T> in associative containers and std algorithms. I've seen several examples of custom comparators that use the following (or similar) model:

template <typename T>
struct SharedPtrContentsLess {
  bool operator()(const boost::shared_ptr<T>& lhs, 
      const boost::shared_ptr<T> rhs) const {
    return std::less<T>(*lhs, *rhs);
    //or: return (*lhs) < (*rhs);
  }
  //defining these here instead of using std::binary_functor (C++11 deprecated)
  typedef boost::shared_ptr<T> first_argument_type;
  typedef boost::shared_ptr<T> second_argument_type;
  typedef bool return_type;
};

But why wouldn't I want to instead extend std::less? Like so:

template <typename T>
struct SharedPtrContentsLess : public std::less< boost:shared_ptr<T> > {
  bool operator()(const boost::shared_ptr<T>& lhs, 
      const boost::shared_ptr<T> rhs) const {
    return std::less<T>(*lhs, *rhs);
  }
};

Does this buy me anything at all?

I would think this gets me the typedefs for free, as though I was extending the deprecated std::binary_function. In C++03, I actually would be extending it through std::less. However, this would also be portable from C++03 to C++11/14 and even C++17 when std::binary_function will be removed, as it just follows the changes in std::less.

I've read a bunch of answers on StackOverflow regarding std::less use, custom comparison functors, and even some of the Standard specs and proposals. I see specializations of std::less and guidance not to extend STL containers, but I can't seem to find any examples of extending std::less or guidance against it. Am I missing an obvious reason not to do this?

EDIT: Removed C++11 tag, as it is causing confusion to the answerers.



via Chebli Mohamed

Search multiple keywords in string

I'm looking for a way to complete this task as efficient as possible. Here is how I want it to work.Say user inputs

"My screen is broken"

The script finds the two keywords "screen" and "broken" and then prints an appropriate string. Being a noob I thought I might be able to use a dictionary like this

{"screen", "broken", "smashed":"use a repair kit"}

Then I would just search all the keys in the dictionary. But upon further research it seems this is not possible.

So what would be the best way to do this? I thought maybe sql but I was wondering if there was a better way which would involve just python.Thanks



via Chebli Mohamed

recall the construct in codigniter

How to recall the construct as it contains all the required data for the page?

class Abc extends CI_Controller
{
       public function __construct()
       {
            parent::__construct();
            $this->load->model('xyz_m');
            $this->data['info'] = $this->xyz_m->get(); //get data
       }

       public function 123()
       {
          /*view page code*/
       }

       public function 456()
       {
          /*insert code here*/

          $this->123(); // redirect, need to load 123() with updated data from construct.
       }
}

So, how do you make the __construct initiate again so you get a new updated results from database?



via Chebli Mohamed

Spirit Qi Parsing multilines from Console

I am using the Console as an input source. I looked for a way qi would parse a line and then it'd wait for the next line and continue parsing from that point. for example take the following grammar

start = MultiLine | Line;
Multiline = "{" *(Line) "}";
Line = *(char_("A-Za-z0-9"));

As an input

{ AAAA
Bbbb
lllll
lalala
}

Taking the whole thing from a file is easy. But what should i do if i need to have the input to come from the console instead? That i want to have it process what its given already and wait for the rest of the lines.



via Chebli Mohamed

Find the biggest palindrome in multiple integers

I have a problem with some algorithm. I must write a java app, which find the biggest palindrome for the product of a predetermined amount of numbers (l) of a predetermined number of digits (n). For example for l=2 and n=2 the biggest palindrome is 9009 (91 * 99).

A palindrome checker I was writed, but I have no idea how to multiply the appropriate amount of numbers with a given number of digits.

Can anybody help me?

Sorry for my English.



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 dynamicly 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

how to imlement a SOAP handler in JAX-WS client

I'm triing to implement a SOAP Handler to a client. I'm using Wildfly8.2 java8 and JAX-WS and Maven

I have generated the client interface class with eclipse from the endpoint WSDL

The handler-chain.xml file is placed in the same package as the client interface.

When I call the web service it executes ok but the handler is not invoked. If I put a brake point in the handler it is never invoked

the client interface is like this:

@WebService(targetNamespace = "********************", name = "WorkflowEditor")
@XmlSeeAlso({ ObjectFactory.class })
@HandlerChain(file = "handler-chain.xml")
public interface WorkflowEditor {

the handler is like this:

package si.arctur.services.handlers;

import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class PrintEnvelopeHandler implements javax.xml.ws.handler.soap.SOAPHandler<SOAPMessageContext> {

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        System.out.println("Client : handleMessage()......");
        SOAPMessage soapMessage = context.getMessage();
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        System.out.println("Client : handleFault()......");
        return true;
    }

    @Override
    public void close(MessageContext context) {
        System.out.println("Client : close()......");
    }

    @Override
    public Set<QName> getHeaders() {
        // TODO Auto-generated method stub
        return null;
    }

}

and the handler-chain.xml file is like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<javaee:handler-chains 
 xmlns:javaee="http://ift.tt/nSRXKP" 
 xmlns:xsd="http://ift.tt/tphNwY">
<javaee:handler-chain>
<javaee:handler>
  <javaee:handler-class>si.arctur.services.handlers.PrintEnvelopeHandler</javaee:handler-class>
</javaee:handler>
 </javaee:handler-chain>



via Chebli Mohamed