lundi 31 août 2015

PortAudio: Playback lag at default frames-per-buffer

I'm trying to play audio in Go, asynchronously, using PortAudio. As far as I'm aware PortAudio handles its own threading, so I don't need to use any of Go's build-in concurrency stuff. I'm using libsndfile to load the file (also Go bindings). Here is my code:

type Track struct {
    stream   *portaudio.Stream
    playhead int
    buffer   []int32
}

func LoadTrackFilesize(filename string, loop bool, bytes int) *Track {
    // Load file
    var info sndfile.Info
    soundFile, err := sndfile.Open(filename, sndfile.Read, &info)
    if err != nil {
        fmt.Printf("Could not open file: %s\n", filename)
        panic(err)
    }
    buffer := make([]int32, bytes)
    numRead, err := soundFile.ReadItems(buffer)
    if err != nil {
        fmt.Printf("Error reading from file: %s\n", filename)
        panic(err)
    }
    defer soundFile.Close()

    // Create track
    track := Track{
        buffer: buffer[:numRead],
    }

    // Create stream
    stream, err := portaudio.OpenDefaultStream(
        0, 2, float64(44100), portaudio.FramesPerBufferUnspecified, track.playCallback,
    )
    if err != nil {
        fmt.Printf("Couldn't get stream for file: %s\n", filename)
    }
    track.stream = stream

    return &track
}

func (t *Track) playCallback(out []int32) {
    for i := range out {
        out[i] = t.buffer[(t.playhead+i)%len(t.buffer)]
    }
    t.playhead += len(out) % len(t.buffer)
}

func (t *Track) Play() {
    t.stream.Start()
}

Using these functions, after initialising PortAudio and all the rest, plays the audio track I supply - just. It's very laggy, and slows down the rest of my application (a game loop).

However, if I change the frames per buffer value from FramesPerBufferUnspecified to something high, say, 1024, the audio plays fine and doesn't interfere with the rest of my application.

Why is this? The PortAudio documentation suggests that using the unspecified value will 'choose a value for optimum latency', but I'm definitely not seeing that.

Additionally, when playing with this very high value, I notice some tiny artefacts - little 'popping' noises - in the audio.

Is there something wrong with my callback function, or anything else, that could be causing one or both of these problems?

Thanks.



via Chebli Mohamed

DockerHub Private Repo Login. More secure way?

I've seen articles such as this one about pulling from private repos and the "best" way to do it. What I understand is, if I want to automate any infrastructure to pull my docker images from dockerhub I need to:

  • Have a user I can login with.
  • Save the users creds in some application that will spin up my infrastructure (be it EC2 User data, a config file for ansible, or ENV variables in some API).
  • When the machine spins up it uses this user's credentials to login and place a token on the machine. All is well.

I'm wondering if there is any functionality to use application keys / tokens instead of needing to tie this to a user. It seems like it would be more secure/convenient if I could manage application keys to do have access to my user/organization's DockerHub account. Then I could yank the keys or change my password and not worry about the sky falling.

Is something like this available, coming, or is there a solution I haven't come across yet?

Thanks!



via Chebli Mohamed

Android Studio. Can i use startLockTask() on app X from app Y knowing the packageName of X?

The titles says it all. I want to start the LockTask introduced in lollipop on an app from another app. Can i do such thing ? Ty.



via Chebli Mohamed

How to add placeholder text to yii inputfield?

iam using clevertech an extension for YII, dose anybody know how i can add my own custom placeholder text inside the input. Below is an example of the input filed:

<?php echo $form->textFieldGroup(
            $model,
            'textField',
            array(
                'wrapperHtmlOptions' => array(
                    'class' => 'col-sm-5',
                ),
                'hint' => 'In addition to freeform text, any HTML5 text-based input appears like so.'
            )
        ); ?>



via Chebli Mohamed

Object prototype and class in Javascript

I'am working with javascript but I've doubts with my code because the function does not work as I want. This is my code:

classDescuentos = function () {
};

classDescuentos.prototype = {
var cellsEditar = function (row, column, columnfield, value, defaulthtml, columnproperties) {
            var data = grid.jqxGrid('getrowdata', row);
            var style = "";

            if (data.editar == 't' && data.apr_ger == 'f') {
                style = "display:block";
            } else {
                style = "display:none";
            }

            var html = "";
            var activarBotEnv = actBtn;
            html = "<div id='activarEdicion_" + row + "' style='width:99%;text-align:center;" + style + "' ><a href='#' id='editarHora' name='editarHora' title='Editar Total horas descontar' onclick=classDescuentos.prototype.editarHora(" + row + ");><img style='padding-bottom: 0px' height='17px' width='17px' src=../../../media/img/edit.png></a></div>";
            return html;
        };

editarHora: function (row) {
        var grid = $(this.gridData);
        grid.jqxGrid('setcolumnproperty', 'des_hor_ger_format', 'editable', true);
        grid.jqxGrid('begincelledit', row, "des_hor_ger_format");

        grid.on('cellendedit', function () {
            grid.jqxGrid('setcolumnproperty', 'des_hor_ger_format', 'editable', false);
        });
    }
};

Should allow edit the data of a cell of a jqxGrid of JQWidget and take the data that is entered but still leaves the original data before modifying it.

What am I doing wrong does not work?



via Chebli Mohamed

How to find the source table rows used by a big complex query

We have a huge Oracle SQL query in our project which is using many views and tables for source data.

Is there any way to find the list of rows fetched from each source table by this big query when I run it?

Basically what we are trying to do is to create the bare minimum number of rows in the source tables so that the outer most big query returns at least a single record.

I have tried to run the smaller queries individually. But it is really time consuming and tedious. So I was wondering if there is a smarter way of doing this.



via Chebli Mohamed

How do I use try, except?

I am currently making a program for the raspberry pi2 I just brought and with the help from some other members, have got it to work most of the time. however there are some case where it won't work because a field doesnt exist in the json if im correct. the code i have is:

import urllib.request
import json

r = urllib.request.urlopen("http://ift.tt/1NTgHGN").read()
rr = r.decode()

obj = json.loads(rr)

# filter only the b16 objects
b16_objs = filter(lambda a: a['routeName'] == 'B16',  obj['arrivals'])

if b16_objs:
# get the first item
b16 = next(b16_objs)
my_estimatedWait = b16['estimatedWait']

my_destination = b16['destination']
print(my_estimatedWait)

My problem is that when routeName B16 is not in the json, an error comes up. I've tried to use the try and catch feature but I could not get this to work. Is there another way of catching this error and displaying a message saying its not present?

The try and catch

try:
b16 = next(b16_objs)
except:
print("there are no records of this")



via Chebli Mohamed

Orchard 1.9.1 Duplicating Menu

I just upgraded an Orchard website from 1.7.1 to 1.9.1 and it seems like a number of things were broken in the process. I managed to fix all of them except for one - all of my navigation items in the menu lost the links to their associated content items, so when I started adding them back in for some reason the front-end start duplicating everything. I'm on a custom theme and the menu started showing up properly, but it's duplicating all menu items right in the root with <option /> tags. I can hide those through CSS easily enough, but it's also adding "undefined" in here too, something I can't seem to target and hide.

Bad Site Navigation

Any idea why this is happening?

Update I figured out the "undefined" part - it's more of the content menu items being blown out, but this time it was a custom link (just a #, since it didn't go anywhere) that didn't have a URL, so it was showing as undefined. The rogue <option /> values are still here, though I can hide them via CSS. I just don't like that they are in the markup at all.



via Chebli Mohamed

Can not get All Post from Json API to ionic

i have this steps to get posts of category from Json API WordPress, And my problem is cannot print post title and content in page but in console i get it.

My code:-

     myApp.factory('Allposts',['$http', '$q',function($http,$q){
        var allposts = [];
        var pages = null;
        return {

        GetAllposts: function (id) {
            return $http.get("http://localhost/khaliddev/azkarserv/?json=get_category_posts&id="+id+"&status=publish",{params: null}).then(function (response) {
               items = response.data.posts;
               console.log(items); 
                allposts = items;
                return items;
            });
        }
        }
}]);

The http://localhost/khaliddev/azkarserv/?json=get_category_posts&id=16&status=publish is like

{"status":"ok","count":1,"pages":1,"category":{"id":16,"slug":"%d8%a3%d8%b0%d9%83%d8%a7%d8%b1-%d8%a7%d9%84%d8%a7%d8%b3%d8%aa%d9%8a%d9%82%d8%a7%d8%b8","title":"\u0623\u0630\u0643\u0627\u0631 \u0627\u0644\u0627\u0633\u062a\u064a\u0642\u0627\u0638","description":"","parent":0,"post_count":1},"posts":[{"id":31,"type":"post","slug":"%d8%a3%d8%b0%d9%83%d8%a7%d8%b1-%d8%a7%d9%84%d8%a7%d8%b3%d8%aa%d9%8a%d9%82%d8%a7%d8%b8","url":"http:\/\/localhost\/khaliddev\/azkarserv\/2015\/08\/28\/%d8%a3%d8%b0%d9%83%d8%a7%d8%b1-%d8%a7%d9%84%d8%a7%d8%b3%d8%aa%d9%8a%d9%82%d8%a7%d8%b8\/","status":"publish","title":"\u0623\u0630\u0643\u0627\u0631 \u0627\u0644\u0627\u0633\u062a\u064a\u0642\u0627\u0638","title_plain":"\u0623\u0630\u0643\u0627\u0631 \u0627\u0644\u0627\u0633\u062a\u064a\u0642\u0627\u0638","content":"<p>\u0627\u0644\u062d\u0645\u0640\u062f \u0644\u0644\u0647 \u0627\u0644\u0630\u064a \u0623\u062d\u0640\u064a\u0627\u0646\u0627 \u0628\u0639\u0640\u062f \u0645\u0627 \u0623\u0645\u0627\u062a\u0640\u0646\u0627 \u0648\u0625\u0644\u064a\u0647 \u0627\u0644\u0646\u0640\u0634\u0648\u0631.<\/p>\n","excerpt":"<p>\u0627\u0644\u062d\u0645\u0640\u062f \u0644\u0644\u0647 \u0627\u0644\u0630\u064a \u0623\u062d\u0640\u064a\u0627\u0646\u0627 \u0628\u0639\u0640\u062f \u0645\u0627 \u0623\u0645\u0627\u062a\u0640\u0646\u0627 \u0648\u0625\u0644\u064a\u0647 \u0627\u0644\u0646\u0640\u0634\u0648\u0631.<\/p>\n","date":"2015-08-28 23:14:11","modified":"2015-08-28 23:14:11","categories":[{"id":16,"slug":"%d8%a3%d8%b0%d9%83%d8%a7%d8%b1-%d8%a7%d9%84%d8%a7%d8%b3%d8%aa%d9%8a%d9%82%d8%a7%d8%b8","title":"\u0623\u0630\u0643\u0627\u0631 \u0627\u0644\u0627\u0633\u062a\u064a\u0642\u0627\u0638","description":"","parent":0,"post_count":1}],"tags":[],"author":{"id":1,"slug":"azkarserv","name":"azkarserv","first_name":"","last_name":"","nickname":"azkarserv","url":"","description":""},"comments":[],"attachments":[],"comment_count":0,"comment_status":"open","custom_fields":{}}]}

and view is

<ion-view view-title="">

<ion-nav-title>
  <img class="logo" src="img/logo.png">
</ion-nav-title>


<ion-content class="padding" lazy-scroll>
<div class="row no-padding HomeRowsList">

<dive class="item itemfull" ng-repeat="post in allposts">

<div class="item item-body">
<div>
{{ post.title }}
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
</div>
</div>
</div>
</div>
</div>
</ion-content>

</ion-view>



via Chebli Mohamed

How to save user preferences in Core Data?

I am using Core Data to save my data. I preloaded the data from a .csv file. I have an entity named places, with an attribute isFavorite. I am populating the data in UITableViewController. TableViewCell consists of some labels and a button. When the user taps the button the value of isFavorite changes from false to true and vice-versa. I want to show the list of favorite places of the user in a separate tableView. Only those places are shown in favorite tab whose isFavorite value is true.

The problem I am facing is, when the value of isFavorite changes on the click of the button say from false to true and the user closes the app. Upon relaunch the isFavorite value changes back to the one that is saved in the .csv file. How can I save the user changes? So that the favorite places remain in the favorite list.

I read a few articles about NSUserDefaults but couldn't understand properly. If anyone can help me considering my app's scenario, would be appreciated.



via Chebli Mohamed

How can I tell if IPython is running?

I have an IPython notebook. I have a long-running loop that produces no output in one of the code blocks. It's not this, but imagine it was this:

for i in range(100):
    time.sleep(2)

I started the code block running a while ago, and now I can't tell whether it's finished, or whether it's still running.

All the IPython status bar says at the top is Last Checkpoint: 23 minutes ago (autosaved). There's nothing in the browser tab to show whether it's running code, either.

I don't want to start the next block because I don't know if this block has finished.

And I don't want to stop the kernel and add print statements to this block, because if it's 80% of the way through, I don't want to kill it and restart it!

Is there anything in IPython - either the browser window or the console - that indicates what code is running right now?



via Chebli Mohamed

unit testing angularjs app with ocLazyLoad

What is the setup I need to run unit tests for an AngularJS app using ocLazyLoad?

What should karma.conf.js look like? I assume I need test-main.js like examples using Karma, Jasmine, and RequireJS, but maybe I'm wrong.

I'm using Webstorm to run the tests, or command line.

I'm starting with testing my services, but eventually I want to run end-to-end tests with Protractor to test the DOM.



via Chebli Mohamed

Recursive call in the try-catch statement without StackOverflowError exception

I have the following snippet of code:

public static void main(String[] args) {
    foo();
}
public static void foo() {
    try {
        foo();
    } catch (Throwable t) {
        foo();
    }
}

Can anyone explain me what's going on here? In details, please.


I have changed this piece and added println methods to show something:

...
try {
    System.out.println("+");
    foo();
} catch (Throwable t) {
    System.out.println("-");
    foo();
}
...

I'm getting something like this (the process hasn't stopped):

+
+
+
+
+--
+--
+
+--
+--
+
+
+--
+--
+
+--
+--
+
+
+
+--
+--

I haven't had any exception (like StackOverflowError).



via Chebli Mohamed

HSQL DB SQL function calculation gives different results between HSQLDB and Oracle

I am getting different results between HSQLDB and Oracle. Am I missing anything in the query?

      SELECT   (-300 / (24*60)) AS resultVal FROM DUAL;
      ---0.2083333333333333333333333333333333333333 oracle
      --0 hsqldb

Thanks Jugunu



via Chebli Mohamed

Fetch data from multiple tables in django views

In Django views, I want to fetch all details(Workeraccount.location,Workeravail.date, Workerprofile.*) for any particular wid=1.

SQL Query:

select * from Workeraccount,Workeravail,Workerprofile where Workerprofile.wid=1 and Workerprofile.wid=Workeravail.wid and Workeraccount.wid=Workerprofile.wid;

The corresponding models are as follows:

class Workeraccount(models.Model):
    wid = models.ForeignKey('Workerprofile', db_column='wid', unique=True)
    location = models.ForeignKey(Location, db_column='location')
    class Meta:
        managed = False
        db_table = 'workerAccount'

class Workeravail(models.Model):
    wid = models.ForeignKey('Workerprofile', db_column='wid')
    date = models.DateField()
    class Meta:
        managed = False
        db_table = 'workerAvail'

class Workerprofile(models.Model):
    wid = models.SmallIntegerField(primary_key=True)
    fname = models.CharField(max_length=30)
    mname = models.CharField(max_length=30, blank=True, null=True)
    lname = models.CharField(max_length=30)
    gender = models.CharField(max_length=1)
    age = models.IntegerField()
    class Meta:
        managed = False
        db_table = 'workerProfile'`



via Chebli Mohamed

cronjob to remove file where the name contains the date of 7 days ago

I have created a cronjob to backup a database into a sql file with a date in the file name:

5 0,10,15,20 * * * /usr/syno/mysql/bin/mysqldump -u<user> -p<password> --opt DATABASE > "/volume5/DATABASE$(date +\%F).sql"`

I am trying to have an other cronjob to delete the file of 7 days ago

0 0 * * * rm /volume5/DATABASE$(/bin/date -D "%s" -d $(( $(/bin/date +\%s ) - 604800 )) +\%F).sql

for example, if the actual date is 2015-08-31, the file of 7 days ago is DATABASE2015-08-24.sql, which should be deleted.

the removal does not work by cron, but does by manual command, so I guess it is only a missing "escape", but I can't figure out where.

Does anybody know where is the problem ?

The "X days ago" option does not work with this date bin.



via Chebli Mohamed

SPARQL-Query doesn't yield expected results

I have a Virtuoso Server and run a SPAQRL-Query against it, which doesn't yield the expected results. I'm not quiet sure, what the problem might be, so I hope some of you have an idea where to look.

This is my SPARQL-Endpoint

The query

select * where {?s ?p
   &lt;http://ift.tt/1KzV6lR;. }

yields one result:

http://ift.tt/1JxDF3j    http://ift.tt/1KzV5ON

When I use the result for ?p in the query like:

select * where {?s &lt;http://ift.tt/1JxDF3l; &lt;http://ift.tt/1KzV6lR;. }

I don't get any result.

For other objects, it works perfectly, like:

select * where {?s &lt;http://ift.tt/1JxDF3l; &lt;http://ift.tt/1KzV6lW;. }

I have no idea, why it works for one Uri but not for the other. Any help pointing me towards the answer is appreciated!



via Chebli Mohamed

For will not iterate through entire list in Python

so I'm learning Python and having trouble with this small program I've designed to try and take my Codecademy skills further.

car_models = ["Ferrari", "Lamborghini", "Aston Martin", "BMW"]
bad_cars = ["Toyota", "Mazda", "Ford", "Hyundai"]

for gcar, bcar in zip(car_models, bad_cars):
    ask = input("What is your favorite car brand? ")
    if ask == gcar:
        print("Yes!")
    elif ask == bcar:
        print("Ew!")
    else:
        print("The model is not listed")
    break

When I run this, it will only pop up with an answer if the model is the first one on the list, otherwise, it just tells you that the model is not listed even though it is.

Thanks!



via Chebli Mohamed

What can I do so that the program is not starting to draw from the last point added?

I am trying to create a program such that there is a square going inside another square (slightly rotated), and another square going inside and so on. I've managed to create a program that does that. But I want the program to make several boxes like that. Take a look at the illustration to get a better idea:

My problem is that after drawing the first box, and then trying to draw the second, the "cursor" drawing the lines is kind of stuck at the last point, so it's drawing the line from the last point of my first square to the first point in the second square, like this:

So as you can see inside pointPanel-constructor I've tried clearing the list, and resetting the counter and i-variable, but no luck. Is there any modifications I can do such that I don't have this problem? I've tried placing the clear()-instruction other places. But maybe I'm missing something.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;




public class Art {
    ArrayList<Point> points = new ArrayList<>();
    int i =0;
    public static void main(String[] args) {
        new Art();
    }

    public Art() {
        JFrame frame = new JFrame("Art");
        frame.add(new pointPanel());

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);


    }

    public class pointPanel extends JPanel{
        //Constructor
        public pointPanel(){
            points(0, 100);
            //points.clear();
            points(500, 200);

        }

        @Override
        //Dimension
        public Dimension getPreferredSize() {
            return new Dimension(800, 600);
        }



        public void points(double x, double y){
            double t=0.1;   //constant
            final int side = 100;
            int counter=0;

            while (counter<20){
                 //Init the first points-->
                Point p  = new Point((int)(x),      (int) (y)           );
                Point p1 = new Point((int)(x+side), (int)(y)            );
                Point p2 = new Point((int)(x+side), (int) (y-side)      );
                Point p3 = new Point((int)(x),      (int)(y-side)       );
                Point p4 = new Point((int)(x),      (int)(y)            );
                //-->and adding them to the list
                if (counter == 0) {
                    points.add(p);
                    points.add(p1);
                    points.add(p2);
                    points.add(p3);
                    points.add(p4);
                }


                //Dynamic part: 
                //If the method has been run earlier - place points making it possible to draw lines
                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i+1).x;
                    y=(1-t)*points.get(i).y + t * points.get(i+1).y;
                    points.add(  new Point( (int) x, (int) y)  );
                    i++;    
                }

                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i+1).x;
                    y=(1-t)*points.get(i).y + t * points.get(i+1).y;
                    points.add(  new Point( (int) x, (int) y)  );
                    i++;
                }

                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i+1).x;
                    y=(1-t)*points.get(i).y + t * points.get(i+1).y;
                    points.add(  new Point( (int) x, (int) y)  );
                    i++;
                }

                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i+1).x;
                    y=(1-t)*points.get(i).y + t * points.get(i+1).y;
                    points.add(  new Point( (int) x, (int) y)  );
                    i++;
                }

                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i-3).x;
                    y=(1-t)*points.get(i).y + t * points.get(i-3).y;    
                    points.add(  new Point( (int) x, (int) y)  );       
                    i++;
                }



                counter++;

            }//while
        //counter=0;
        //i=0;
        x=0;
        y=0;

        }//metode

        //Paint-method
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;

            g2d.setColor(Color.RED);
            for (int i = 0; i < points.size()-1; i++) {
                g2d.drawLine(points.get(i).x, points.get(i).y, points.get(i+1).x, points.get(i+1).y);
            }

           g2d.dispose();
        }   
    }
}



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 do I push a view controller onto the nav stack from search results when presenting them modally?

I want to recreate the search UI shown in the iOS 7/8 calendar app. Presenting the search UI modally isn't a problem. I use UISearchController and modally present it just like the UICatalog sample code shows which gives me a nice drop down animation. The issue comes when trying to push a view controller from the results view controller. It isn't wrapped in a navigation controller so I can't push onto it. If I do wrap it in a navigation controller then I don't get the default drop down animation when I present the UISearchController. Any ideas?

EDIT: I got it to push by wrapping my results view controller in a nav controller. However the search bar is still present after pushing the new VC onto the stack.



via Chebli Mohamed

Tokenizing a string in Prolog using DCG

Let's say I want to tokenize a string of words (symbols) and numbers separated by whitespaces. For example, the expected result of tokenizing "aa 11" would be [tkSym("aa"), tkNum(11)].

My first attempt was the code below:

whitespace --> [Ws], { code_type(Ws, space) }, whitespace.
whitespace --> [].

letter(Let)     --> [Let], { code_type(Let, alpha) }.
symbol([Sym|T]) --> letter(Sym), symbol(T).
symbol([Sym])   --> letter(Sym).

digit(Dg)        --> [Dg], { code_type(Dg, digit) }.
digits([Dg|Dgs]) --> digit(Dg), digits(Dgs).
digits([Dg])     --> digit(Dg).

token(tkSym(Token)) --> symbol(Token). 
token(tkNum(Token)) --> digits(Digits), { number_chars(Token, Digits) }.

tokenize([Token|Tokens]) --> whitespace, token(Token), tokenize(Tokens).
tokenize([]) --> whitespace, [].  

Calling tokenize on "aa bb" leaves me with several possible responses:

 ?- tokenize(X, "aa bb", []).
 X = [tkSym([97|97]), tkSym([98|98])] ;
 X = [tkSym([97|97]), tkSym(98), tkSym(98)] ;
 X = [tkSym(97), tkSym(97), tkSym([98|98])] ;
 X = [tkSym(97), tkSym(97), tkSym(98), tkSym(98)] ;
 false.

In this case, however, it seems appropriate to expect only one correct answer. Here's another, more deterministic approach:

whitespace --> [Space], { char_type(Space, space) }, whitespace.
whitespace --> [].

symbol([Sym|T]) --> letter(Sym), !, symbol(T).
symbol([])      --> [].
letter(Let)     --> [Let], { code_type(Let, alpha) }.

% similarly for numbers

token(tkSym(Token)) --> symbol(Token).

tokenize([Token|Tokens]) --> whitespace, token(Token), !, tokenize(Tokens).
tokenize([]) --> whiteSpace, [].

But there is a problem: although the single answer to token called on "aa" is now a nice list, the tokenize predicate ends up in an infinite recursion:

 ?- token(X, "aa", []).
 X = tkSym([97, 97]).

 ?- tokenize(X, "aa", []).
 ERROR: Out of global stack

What am I missing? How is the problem usually solved in Prolog?



via Chebli Mohamed

Find all numbers in a list integer that add up to a number

I was asked this question on an interview. Given the following list:

[1,2,5,7,10,13]

Find the numbers that add up to 5.

My solution was the following:

#sort the list:
l.sort()
result = ()
for i in range(len(l)):
    for j in range(i, len(l)):
         if l[i] + l[j] > 5:
             break
         elif l[i] + l[j] == 5:
             result += (l[i], l[j])

The idea I presented was to sort the list, then loop and see if the sum is greater than 5. If so, then I can stop the loop. I got the sense the interviewer was dissatisfied with this answer. Can someone suggest a better one for my future reference?



via Chebli Mohamed

Woocommerce Show default variation price

I'm using Woocommerce and product variations and all my variations have a default variation defined. I would like to know, how I can find the default variation and display it's price.

This is the code I got so far, but it displays the cheapest variation price, and I'm looking for my default variation product price instead.

// Use WC 2.0 variable price format, now include sale price strikeout
add_filter( 'woocommerce_variable_sale_price_html', 'wc_wc20_variation_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'wc_wc20_variation_price_format', 10, 2 );
function wc_wc20_variation_price_format( $price, $product ) {
// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice ) {
    $price = '<del>' . $saleprice . '</del> <ins>' . $price . '</ins>';
}
return $price;

}

I found the code example here Woocommerce variation product price to show default



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 user = Test, client = 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

How to preprocess high cardinality categorical features?

I have a data file which has features of different mobile devices. One column with categorical data type has 1421 distinct types of values. I am trying to train a logistic regression model along with other data that I have. My question is: Will the high cardinality column described above affect the model I am training? If yes, how do I go about preprocessing this column so that it has lower number of distinct values?



via Chebli Mohamed

Meteor cursor counts and forEach

I need to add min and max fields into collection items in publish function and filter items by this fileds. I found the solution by using forEach for cursor:

Meteor.publish 'productsWithMinMax', (filter, options) ->
    Products.find(filter, options).forEach (p) =>
        p.min = Math.min p.price1, p.price2, p.price3, p.price4
        p.max = Math.max p.price1, p.price2, p.price3, p.price4

        if p.min && p.max && (p.max < p.mainPrice || p.min > p.mainPrice )
            @added "products", p._id, p

    Counts.publish @, 'numberOfProductsWithMinMax', Products.find(filter), {noReady: true}

    @ready()

But now Counts.publish returns wrong count for my cursor. How to count my cursor in this case?



via Chebli Mohamed

ES6 Import Folder

Does the ES6 module syntax allow you to import something from a folder?

For example if I have ./sub/main.js and I try import foo from './sub in the ./main.js file, will this work?

Could I get this sort of importing from a folder to work with babel and webpack?

Basically this would be the equivalent of __init__.py in Python.



via Chebli Mohamed

Is there a custom of distributing a key description with databases, like it is done with maps?

For a project with a more complicated relational database structure, one of the requirements is long-term stability of the SQL database. To achieve this, I did some searching for a standard way of describing certain paths through a relational database. For example, this would include a description on how to combine related tables or a hierarchy of the keys/IDs used in the database.

What I am trying to do is a description of the database, so that someone who just imports the database dump to a SQL server will know how what queries to write and what fields to use as keys. (This situation could arise if, for example, the software used with the database can no longer be run at some point in time.)

While I am aware this could be done with UML, I'd like to ask whether there is some sort of standard or custom of distributing databases in open source software with a description, like the key always printed on maps so that people know what each color and line type means. Thanks!



via Chebli Mohamed

Download Google Sheet as CSV and keep numbers values as text

When I download one of my Google Sheets to csv, it removes the proceeding "0" from my values. For example, "0666666" will become "666666". How can I modify the code below so that it keeps that front zeros? Thanks!

def static_tabs():
    static_tabs = ('Locating Media','Schedules')
    for tab in static_tabs:
        edit_ws = edit.worksheet(tab)
        print ("EDIT"+format(edit_ws))
        filename = str(tab) +'.csv' 
        with open('C:/Users/A_DO/Dropbox/2. The Machine/10. Edit and QC Google Doc/Edit/Static Tabs/' + filename, 'wb') as f:
            writer = csv.writer(f,quoting=csv.QUOTE_ALL)
            writer.writerows(edit_ws.get_all_values())

static_tabs()



via Chebli Mohamed

NpmInstallDir parameter not found with MSBuild of Apache Cordova project

I'm using VS2015 to build an Apache Cordova project. This builds fine using the editor itself, however when I run the build using MSBuild:

"C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe" /p:Configuration=Release MySolution.sln"

I encounter the following error:

(InstallMDA target) -> C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(287,5): error MSB4044: The "RunMdaInstall" task was not given a value for the required parameter "NpmInstallDir".

Opening the Microsoft.MDA.FileMirrorring.targets file, I see the reference to NpmInstallDir. How is this supposed to get set during an MSBuild? (Needless to say, running echo %NpmInstallDir% on my commandline does not return a path, so I don't have this set.)

Doing a search for NpmInstallDir in the directory where my Visual Studio lives, I see that it is retrieved through some arguments. Do I need to pass in a specific argument to MSBuild to locate NpmInstallDir?



via Chebli Mohamed

Pythpn Regex Select Element

I've got an array with elements which are different names such as and

[abc, def, agh § dsd, sdse, 12a § asd].

I would like to select only those that have § in it and erase the other elements from the array.

The names change in length and also the position of § in the name changes]

Does anybody have an idea?

Mine was

    names = [re.findall(r'(?<=>)[^><]+(?=<)', str(i).strip()) for i in select('§')]

However, my regex skills are below zero...so...help is much appreciated!



via Chebli Mohamed

How to set PHPStorm get existed word to autocomplete?

In Sublime Text, when I have helloWorldTesteStringLong written in an open file, it will show in auto complete list, independence if I in their file or not

How to can I set this configuration in PHPStorm? For show written word in autocomplete list



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.

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

maven builds fails inside ubuntu vagrant machine as well as docker instance

I am developing an api using jaxb. The maven build (using jdk-7) works on my local windows machine. Now if I try to build it on my vagrant box (ubuntu/trusty64) after setting up maven and openjdk7 on the vm, I get following error on performing mvn clean install:

java.io.FileNotFoundException (operation not permitted)

However, if it is a simple java app, I am able to do perform maven builds on the same machine without error (from http://ift.tt/1COWknQ)

Detailed error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.4:war (default-war) on project '<app>' : Could not copy webapp classes [/usr/src/<app>/target/classes]: /usr/src/<app>/target/<app>-03.00.00.01-SNAPSHOT/WEB-INF/classes/<my-app-src>/rest/config/ResourceConfig.class (Operation not permitted) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.4:war (default-war) on project <my-app>: Could not copy webapp classes [/vagrant_data/<my-app-src>/<my-app>/target/classes]
[/vagrant_data/<my-app-src>/<my-app>/target/classes]
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:622)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Could not copy webapp classes [/vagrant_data/<my-apps-src>/target/classes]
    at org.apache.maven.plugin.war.packaging.ClassesPackagingTask.performPackaging(ClassesPackagingTask.java:80)
    at org.apache.maven.plugin.war.packaging.WarProjectPackagingTask.handleClassesDirectory(WarProjectPackagingTask.java:207)
    at org.apache.maven.plugin.war.packaging.WarProjectPackagingTask.performPackaging(WarProjectPackagingTask.java:104)
    at org.apache.maven.plugin.war.AbstractWarMojo.buildWebapp(AbstractWarMojo.java:505)
    at org.apache.maven.plugin.war.AbstractWarMojo.buildExplodedWebapp(AbstractWarMojo.java:433)
    at org.apache.maven.plugin.war.WarMojo.performPackaging(WarMojo.java:213)
    at org.apache.maven.plugin.war.WarMojo.execute(WarMojo.java:175)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: java.io.FileNotFoundException: /vagrant_data/<my-apps-src>/target/<my-app>-03.00.00.01-SNAPSHOT/WEB-INF/classes/<my-app-src>/rest/config/ResourceConfig.class (Operation not permitted)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:160)
    at org.codehaus.plexus.util.FileUtils.doCopyFile(FileUtils.java:1068)
    at org.codehaus.plexus.util.FileUtils.copyFile(FileUtils.java:1049)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask.copyFile(AbstractWarPackagingTask.java:334)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask$1.registered(AbstractWarPackagingTask.java:154)
    at org.apache.maven.plugin.war.util.WebappStructure.registerFile(WebappStructure.java:207)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask.copyFile(AbstractWarPackagingTask.java:149)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask.copyFiles(AbstractWarPackagingTask.java:104)
    at org.apache.maven.plugin.war.packaging.ClassesPackagingTask.performPackaging(ClassesPackagingTask.java:75)
    ... 27 more



via Chebli Mohamed

Controlling web application user access to file system

First, a preface: I'm new to Stack Overflow, recently reintroduced to programming, and very new to security, so please go easy on me. I'm hoping someone can point me in the right direction.

We are a large multi-site nonprofit organization with a small programming team supporting an obsolete Administration/Accounting software that was programmed in-house. In the last few years, part of our Human Resources module has been rewritten as an ASP.NET MVC web application (C#, Javascript, HTML) so that remote sites can install it and access employee information. The eventual plan is to move it all to RESTful Web Api, so I'm spending time on Pluralsight learning REST as well as the programming languages referenced above.

Where we've hit a snag is in security. Right now an authorized user in this web application has carte blanche access to data, so we can't make certain sensitive data available until we can employ authorization on a more granular level.

Our most pressing issue is document management. Documents on our old system are saved in a series of folders in .doc or .pdf format. Our web application needs to be able to authenticate a given user, access that same file structure and limit his/her access to only the folders he/she is authorized to view.

I've been searching stackoverflow and the internet, but haven't come across any clearcut information on how to proceed.

I would appreciate any input on strategies you may have used to tackle a similar problem. Thanks in advance for your help!



via Chebli Mohamed

How to dynamically traverse a global array without creating any copy of it?

For example something like this:

function POSTTraverse($key0 [, $key1 [, $key2 ...]]) {
    ...
    return $value;
}

The usage would be for example:

POSTTraverse('document', 'item', 'quantity', 5);



via Chebli Mohamed

XAML Binding: Combobox populating textbox in one scenario, but not another? WPF

I have one set of code working properly. It loads the "address" field from a database of user records containing stuff like [ID, Fname, Lname, address, zip, etc] into a ComboBox's selection set. Once a user selects an address it displays that selection in a corresponding textbox as well.

working code:

<Window x:Class="CC_Ticketing_WPF.MainWindow"
       xmlns:local="clr-namespace:CC_Ticketing_WPF"
       Title="MainWindow">
    <Window.Resources>
        <DataTemplate x:Key="orderheaderTemplate">
            <StackPanel>
                <TextBlock Text="{Binding XPath=address}"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ComboBox x:Name="cb_Address" 
                  DataContext="{StaticResource orderheaderDataSource}" 
                  ItemsSource="{Binding XPath=/dataroot/orderheader/address}"  
                  IsEditable="True"/>
        <TextBlock x:Name="tb_Address" 
                   Text="{Binding ElementName=cb_Address,Path=Text}"/>
    </StackPanel>
</Window>

The problem is I know that's very limited as it relies on defining everything in the stack panel. I am trying this something along these lines instead:

broken code

<Window x:Class="CC_Ticketing_WPF.MainWindow"
        xmlns:local="clr-namespace:CC_Ticketing_WPF"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow">
    <Window.Resources>
        <DataTemplate x:Key="orderheaderTemplate">
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ComboBox x:Name="cb_Address" 
                  DataContext="{StaticResource orderheaderDataSource}" 
                  ItemsSource="{Binding XPath=/dataroot/orderheader}" 
                  DisplayMemberPath="address" 
                  SelectedValuePath="Content" 
                  IsEditable="True"/>
        <TextBlock x:Name="tb_Address" 
                   Text="{Binding ElementName=cb_Address,
                                  Path=SelectedItem.Content,
                                  Mode=OneWay}"/>
    </StackPanel>
</Window>

This loads the addresses and allows selection in the combobox, but sends nothing to the textbox. Eventually I'd want selecting an address from this combox to not only send the selection to the textbox, but also send the other relevant data from that record to other textbox's (like you select just an address and it populates a bunch of textboxes with the address, name, zip, etc.) Pretty common business need. Could someone put me on the right track here to accomplish this?



via Chebli Mohamed

Javascript Math.pow() returning Uncaught TypeError: Cannot read property '0' of undefined

I can't seem to figure out why this:

Populations[0] = Math.round(Math.pow((Populations[0] * Math.E), (popGrowth * 5)));
Populations[1] = Math.round(Math.pow((Populations[1] * Math.E), (popGrowth * 5)));
Populations[2] = Math.round(Math.pow((Populations[2] * Math.E), (popGrowth * 5)));

returns this:

Uncaught TypeError: Cannot read property '0' of undefined

JSFiddle:http://ift.tt/1MYsAut



via Chebli Mohamed

Animate a div sliding with a toggle button

I can't seem to figure out how to animate my div sliding with a toggle button.

I tried using variables but I have multiple of these and I am creating too many variables to keep track of the clicks on each of them.

$(document).ready(function() {
  
  $('#toggle-sidebar').click(function() {
    $('#sidebar').animate({
      left: '200'
    }, 500);
  });
  
});
#sidebar {
  position: absolute;
  top: 0;
  left: 0;
  width: 20em;
  height: 70vh;
  background:#333;
}

#toggle-sidebar {
  float: right;
}
<script src="http://ift.tt/1oMJErh"></script>

<div id="sidebar"></div>

<a href="#" id="toggle-sidebar">Toggle</a>


via Chebli Mohamed

SQL update with sub-query takes too long to run

I have a SQL update query that runs with my test data, but doesn't complete (2 hours or more) with my production data.

The purpose of the query

I have an ADDRESSES table that uses code strings instead of IDs. So for example ADDRESSES.COUNTRY_CODE = "USA" instead of 3152. For referential integrity, I am changing these code strings to code IDs.

Schema

ADDRESSES

  • ADDR_ID (PK)
  • COUNTRY_CODE (varchar)
  • Address line 1 (varchar)
  • etc.

COUNTRY_CODES

  • CODE_ID (PK)
  • CODE_STRING (varchar)
  • etc.

Steps

First, I create a temporary table to store the address records with the appropriate code ID:

CREATE TABLE ADDRESS_TEMP
AS
   SELECT ADDR_ID, CODE_ID
     FROM    ADDRESSES
          LEFT JOIN
             COUNTRY_CODES
          ON ADDRESSES.COUNTRY_CODE = CODE_STRING

Second, I null the COUNTRY_CODE column and change its type to NUMBER.

Third I set the COUNTRY_CODE column to the code IDs:

UPDATE ADDRESSES
   SET COUNTRY_CODE =
          (SELECT ADDRESS_TEMP.CODE_ID
             FROM ADDRESS_TEMP
            WHERE ADDRESS_TEMP.ADDR_ID = ADDRESSES.ADDR_ID)

It is this third step that is taking hours to complete (2 hours and counting). The ADDRESSES table has ~356,000 records. There is no error; it is still running.

Question

Why isn't this update query completing? Is it dramatically inefficient? I think I can see how the sub-query might be an N2 algorithm, but I'm inexperienced with SQL.



via Chebli Mohamed

swap image and toggle div onclick

I have a dynamically populated unordered list. Every other list item is hidden. First list item contains an image, when clicked displays the list item immediately following. That part of my code is working fine. What I can't seem to figure out is how to swap the toggle image onclick. Right now the image stays the same

thank you for any help you can provide

$(document).ready(function () {
  $(".slidingDiv").hide();

  $('.show_hide').click(function (e) {
    $(".slidingDiv").slideToggle("slow");
    var val = $(this).src() == "http://ift.tt/1FdgyXH" ? "http://ift.tt/1MYsyCI" : "http://ift.tt/1FdgyXH";
    $(this).hide().src(val).fadeIn("slow");
    e.preventDefault();
  });
});
<script src="http://ift.tt/1qRgvOJ"></script>
<ul id="storeTable">
  <li id="one" class="alwaysVisable">
    <h3>Title</h3>
    <p class="descript">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    <img src="http://ift.tt/1MYsyCI" class="show_hide" width="32" height="32">
  </li>
  <li class="slidingDiv">
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum.
  </li>
  <li id="two" class="alwaysVisable">
    <h3>Title</h3>
    <p class="descript">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    <img src="http://ift.tt/1MYsyCI" class="show_hide" width="32" height="32">
  </li>
  <li class="slidingDiv">
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum.
  </li>
</ul>


via Chebli Mohamed

How to go back to an already launched activity in android

I want to go back to an already launched activity without recreating again.

  @Override
    public void onBackPressed() {
     Intent i = new Intent(SecondActivity.this, FirstActivity.class);
     this.startActivity(i);

    }

Instead of doing is there any other way to go back to another activity which is already created, which I get back with " Back button "



via Chebli Mohamed

how to shorten source code using whenall in order to optimize speed

I have used following code and its supposed to be used for calling more than 100,000 urls .

As its taking long time to finish the process , I am trying to find a better way to optimize the code.

I have read other questions like mine and few people suggested to remove toarray but there were example of how to do it.

Any comments would be appreciated.

private async Task ProcessAllURLSAsync(List<string> urlList)
{
    IEnumerable<Task> CallingTasksQuery =
        from url in urlList select ProcessURLAsync(url);

    Task[] CallingTasks = CallingTasksQuery.ToArray();

    await Task.WhenAll(CallingTasks);
}

private async Task ProcessURLAsync(string url)
{
    await CallURLAsync(url);
}

private async Task CallURLAsync(string url)
{
    var content = new MemoryStream();
    var webReq = (HttpWebRequest)WebRequest.Create(url);
    using (WebResponse response = await webReq.GetResponseAsync())
    {
    }
}



via Chebli Mohamed

How to map a Perforce depot's folder to an arbitrary local folder?

I have the following structure on the Perforce server:

MyDepot
  + MyProject
    + MySubProject
      + trunk
        + ... trunk folders/files ...

I have my Eclipse workspace for MySubProject in:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject

If I get the latest revision with a Perforce workspace of:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject

I get:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject\
  + MyDepot
    + MyProject
      + MySubProject
        + trunk
          + ... trunk folders/files ...

I'd prefer:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject\
  + ... trunk folders/files ...

Can I achieve this and if, how?

I found the P4V manual page Defining a Workspace View but it doesn't seem to cover what I want. (There's a garbled sentence under point 2. but this isn't essential in this respect, is it?)



via Chebli Mohamed

Git issues with shared folders in Vagrant

I have never seen this issue before while using Vagrant, so I'm hoping this makes sense to someone. I have a folder that contains a git repository, that is being synced with a Vagrant machine running CentOS 6.5, and seeing some inconsistencies with Git.

On my host machine (Mac OSX) if I run git status I get the following:

 ~/Folder/repo$ git status
 On branch master
 Your branch is up-to-date with 'origin/master'.
 nothing to commit, working directory clean

But if I run the same command within my vagrant box, I get the following:

vagrant@localhost ~/repo$ git status                                                                                                                 master
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   .codeclimate.yml
#   modified:   .gitattributes
#   modified:   .gitignore
#   modified:   CONTRIBUTING.md
#   modified:   app/commands/.gitkeep
#   modified:   app/commands/CreateModule.php
#   modified:   app/commands/FbAdRevenue.php
....

And the list goes on, basically git locally seems to think that every single file has been modified and not committed which is not true. Any idea why this would be the case and how to fix it?



via Chebli Mohamed

Sparql insert data not working

I'm a newbie to Sparql, but I am unable even to make a simple insert data query, or so it seems.

I'm using Apache Fuseki as working server; I'm in a graph, and I'm trying to make this query work:

PREFIX oa: <http://ift.tt/1FdgyHl;
PREFIX rdfs: <http://ift.tt/1cmhdKn;

INSERT DATA{             
  [ a 
    oa:Annotation ;                    
    rdfs:label "Title";                    
  ] .                    
}

But it doesn't matter what I do, I keep getting this error:

Error 400: SPARQL Query: No 'query=' parameter

This is even a semplified code, I tried many queries even more complex, but the result doesn't change...



via Chebli Mohamed

Ionic Changes Content-Type

Ok I have to make a simple GET request that work in Postman but not in the Ionic code. I have determined that the reason is that the API treats incoming requests differently based on Content-Type. application/json works text doesn't.

    headers: {
      "Content-Type": 'application/json; charset=UTF-8',
      "Accept": 'application/json; charset=UTF-8'
    },

As you can see I'm setting the header to try to force application/json but when I sniff the request it has changed to text/html somehow. How do I force Ionic to take my Content-Type as definitive?



via Chebli Mohamed

user authentication methods for apple watch app

I have an iPad and iPhone application,which runs on user session and requires login and session to be maintained throughout application life cycle. Now I want to create Apple watch app for same app. What are the best ways to do login and maintain session on Apple watch. User session expires if app is idle for more than 20 minutes.



via Chebli Mohamed

Using FileReader.readAsArrayBuffer() on changed files in Firefox

I'm running into an odd problem using FileReader.readAsArrayBuffer that only seems to affect Firefox (I tested in the current version - v40). I can't tell if I'm just doing something wrong or if this is a Firefox bug.

I have some JavaScript that uses readAsArrayBuffer to read a file specified in an <input> field. Under normal circumstances, everything works correctly. However, if the user modifies the file after selecting it in the <input> field, readAsArrayBuffer can get very confused.

The ArrayBuffer I get back from readAsArrayBuffer always has the length that the file was originally. If the user changes the file to make it larger, I don't get any of the bytes after the original size. If the user changes the file to make it smaller, the buffer is still the same size and the 'excess' in the buffer is filled with character codes 90 (capital letter 'Z' if viewed as a string).

Since this code is so simple and works perfectly in every other browser I tested, I'm thinking it's a Firefox issue. I've reported it as a bug to Firefox but I want to make sure this isn't just something obvious I'm doing wrong.

The behavior can be reproduced by the following code snippet. All you have to do is:

  1. Browse for a text file that has 10 characters in it (10 is not a magic number - I'm just using it as an example)
  2. Observe that the result is an array of 10 items representing the character codes of each item
  3. While this is still running, delete 5 characters from the file and save
  4. Observe that the result is still an array of 10 items - the first 5 are correct but the last 5 are all 90 (capital letter Z)
  5. Now added 10 characters (so the file is now 15 characters long)
  6. Observe that the result is still an array of 10 items - the last 5 are not returned
function ReadFile() {
  var input = document.getElementsByTagName("input")[0];
  var output = document.getElementsByTagName("textarea")[0];

  if (input.files.length === 0) {
    output.value = 'No file selected';
    window.setTimeout(ReadFile, 1000);
    return;
  }

  var fr = new FileReader();
  fr.onload = function() {
    var data = fr.result;
    var array = new Int8Array(data);
    output.value = JSON.stringify(array, null, '  ');
    window.setTimeout(ReadFile, 1000);
  };
  fr.readAsArrayBuffer(input.files[0]);

  //These two methods work correctly
  //fr.readAsText(input.files[0]);
  //fr.readAsBinaryString(input.files[0]);
}

ReadFile();
<input type="file" />
<br/>
<textarea cols="80" rows="10"></textarea>

In case the snippet does not work, the sample code is also available as a JSFiddle here: http://ift.tt/1MYsymg



via Chebli Mohamed

vendredi 8 mai 2015

Boost::geometry query returning indexes

I want to have class, which uses boost::geometry::index::rtree for spatial indexers. This class alone should know about boost, so I use something like this:

struct VeryImportantInfo
{
    ...
    float x;
    float y;
}

class Catalogue
{
    ...
public:
    std::vector<std::shared_ptr<VeryImportantInfo> > FindIn(float x1, float x2, float y1, float y2);

protected:
    using point = bg::model::point<float, 2, bg::cs::cartesian>;
    using value = std::pair<point, std::shared_ptr<VeryImportantInfo> >;
    using box = bg::model::box<point>;        

    boost::geometry::index::rtree< value, bgi::quadratic<16> > rtree;
}

std::vector<std::shared_ptr<VeryImportantInfo> > Catalogue::FindIn(float x1, float y1, float x2, float y2)
{
    box query_box(point(x1, y1), point(x2, y2));
    ???
}

I don't know how to do query properly (Please don't look at this awful vector return by copy, it is just for example sake). I can do this:

std::vector<std::shared_ptr<VeryImportantInfo> > Catalogue::FindIn(float x1, float y1, float x2, float y2)
{
    box query_box(point(x1, y1), point(x2, y2));
    std::vector<value> result_s;
    rtree.query(bgi::intersects(query_box), std::back_inserter(result_s));
    std::vector<std::shared_ptr<VeryImportantInfo> > results;
    results.reserve(result_s.size());
    for( auto& p : result_s)
    {
        results.emplace_back(p.second);
    }
    return results;
}

I want to know, how can I get rid of internal copy(not return copy, results.emplace_back(p.second); - this one). Because I can have more that 10k results in result_s and it will be a waste.

Thank you!

field ‘value’ has incomplete type

I have a C++ interdependence problem and i can not understand where the problem is...

Here are my headers:

json.array.h

#ifndef __JSON_ARRAY__
#define __JSON_ARRAY__

#include "json.object.h"

class JSON_OBJECT;

/* JSON_ARRAY */
class JSON_ARRAY {
    int size;
    custom_list<JSON_OBJECT> * container;

...
};

#endif

json.object.h

#ifndef __JSON_OBJECT__
#define __JSON_OBJECT__

#include "hash.h"
#include "elem_info.h"
#include "json.type.h"

class JSON_TYPE;
class elem_info;

/* JSON_OBJECT */
class JSON_OBJECT {
    custom_list<elem_info> *H;
    int HMAX;
    unsigned int (*hash) (std::string);
...
};

#endif

json.type.h

#ifndef __JSON_TYPE__
#define __JSON_TYPE__

#include "json.object.h"
#include "json.array.h"

class JSON_OBJECT;
class JSON_ARRAY;

class JSON_TYPE {
    JSON_ARRAY * _JSON_ARRAY_;
    JSON_OBJECT * _JSON_OBJECT_;
    std::string _JSON_OTHER_;
    std::string _JSON_TYPE_;
...
};

#endif

elem_info.h

#ifndef __ELEM_INFO__
#define __ELEM_INFO__

#include "json.type.h"
class JSON_TYPE;

class elem_info {
public:
    std::string key;
    JSON_TYPE value;
...
}; 

#endif

main.cpp

#include <iostream>
#include <string>

#include "custom_list.h" // it inculdes cpp also
#include "json.type.h"
#include "elem_info.h"
#include "json.object.h"
#include "json.array.h"
#include "json.type.cpp"
#include "elem_info.cpp"
#include "json.object.cpp"
#include "json.array.cpp"


int main()
{
    JSON_ARRAY * root = new JSON_ARRAY;
    JSON_OBJECT obj;
    JSON_OBJECT obj1;
    JSON_OBJECT * obj2 = new JSON_OBJECT;
    JSON_TYPE * type = new JSON_TYPE;
...
}

When i try to compile my code, i have this error:

elem_info.h:10:15: error: field ‘value’ has incomplete type JSON_TYPE value;

It looks like it cant find JSON_TYPE. I cant understand where is the problem. Thanks for your help.

WINAPI cursor click position on application window

I need to write a small program that can know where the user click the button or somehow on a application windows whatever the application windows change the size .

Through use the windows API, now I can only get the global cursor click position.

I find a small program from china that have similar function using AHK to implement it. Maybe the author use this (WinGetPos) see the image below:

enter image description here

So, Is the any windows api or other QT5, C++ function can help me get the application windows cursor click position. (I develop in QT5)

post some code on here:

GetCursorPos (&screenpoint);
hwndFoundWindow = WindowFromPoint (screenpoint);
mp.DisplayInfoOnFoundWindow(QString::fromLocal8Bit("L"), hwndFoundWindow, pMouseStruct->pt.x, pMouseStruct->pt.y);

Compilation and execution when code is not dislosed; use of ellipsis in code

In an interview I was asked following question

Given the code fragments below, where the ellipsis (…) represents code that has not been disclosed to you:

class X { … };  class Y { public: explicit Y(const X& x); … }; 

what can you say about the compilation and execution of each of the following statements? Describe each of the operations that occur as this code executes.

Y func(Y y) { … }
X x;
Y y = func(Y(x));

I could not understand the question properly hence was not able to answer. if some one could explain me what answer was expected of me or share any link which I can go through, that would be really nice. Many Thanks.

How to embed a custom font in my application

I want to add a custom font to my application, and I have already added to my resource file.

And my code as the following:

int id = QFontDatabase::addApplicationFont(":/fonts/ae_AlMateen.ttf");
QMessageBox::information(this,"Message",QString::number(id));

But the problem is that the addApplicationFont always returns -1.

Note that when change the :/fonts/ae_AlMateen.ttf to direct path ex:C://ae_AlMateen.ttf it works fine.

I dont know what is the problem.

A segmentation fault

I have try the following code to judge prime:

const int N = 200000;
long prime[N] = {0};
long num_prime = 0;
int is_not_prime[N]={1,1};
void Prime_sort(void)
{
    for( long i = 2 ; i<N ; i++ )
    {
        if( !is_not_prime[i] )
        {
            prime[num_prime++] = i;
        }
        for( long j = 0; j<num_prime && i*prime[i]<N ; j++ )
        {
            is_not_prime[i*prime[j]] = 1;
        }   
    }   
}

But when I run it, it cause a segmentation fault! That fault I have never meet.And I searched Google,and it explain segmentation fault as follow:

A segmentation fault (often shortened to segfault) is a particular error condition that can occur during the operation of computer software. In short, a segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed

But I don't know where cause this fault in my code.Please help me.

Finding all parents from node to the root in a tree by recursion

I have a class Graph, modelling a Tree. Graph contain a pointer Graph* to the parent of my current instance (my current node).

class Graph
{
private:

    Graph*           parent;
public:
    Graph*           getparent();
}

Graph*          Graph::getparent()
{
    return this->parent;
}

parent is at nullptr if root.

I'm trying to find the distance from a node to the root, starting from the node.

Here is my try :

int Graph::howManyParents(Graph* unparent)
{
    int nbParents(0);
    if(unparent != nullptr)
    {
        nbParents++;
        nbParents =+ howManyParents(this->parent);
    }
    return nbParents;
}

It compiles but crashes. Debbugger show me lots of call to the method, but end up SegFaulting. Is there something wrong with my algorithm ?

Accessing Private Members with Cin inside Class

I'm little confused.. My Code is Below

#include <iostream>
using namespace std;
class Test {
    private:
    int x, y;
  public:
    void get(){
        cin>>x;
        cin >>y;
        cout << x;
        cout << y;
    }
};

int main ()
{
  Test obj;
  obj.get();
  return 0;
}

In this code I'm accessing private members using cin..!! Is it fine? because I think user can send values or access private members directly after program run..!!

std::reference_wrapper on MS Visual Studio 2013

I try to compile some code which is very similar to:

#include <string>
#include <unordered_map>

class A{
};

int main(int argc, char* argv[]){
  std::unordered_map<std::string, std::reference_wrapper<const A>> stringToRef;
  A a;
  const A& b = a;
  stringToRef.insert(std::make_pair("Test", b));
  return 0;
}

But can't figure out, why it's not compiling. I'm pretty sure, that the same code compiled fine on MS Visual Studio 2012 - but on Visual Studio 2013, it reports the following compilation error:

error C2280: std::reference_wrapper<const A>::reference_wrapper(_Ty &&): attempting to reference a deleted function

I tried to add copy, move, assignment operators to my class - but couldn't get rid of this error. How can I find out exactly, which deleted function this error refers to?

Permute rows of a eigen matrix with specific indexes

Following the indications published in this previous question, I'm trying to permute the rows of a Eigen matrix using specific indexes.

Basically I have a function that performs the next steps:

    PermutationMatrix<Dynamic, Dynamic, size_t> perm(indices.size());
    copy(indices.begin(), indices.end(), perm.indices().data());
    return perm * mat; // permute rows

But writing some unit tests I realized that in most of the cases the permutation is done incorrectly. This unit tests can corroborate what I just stated (fmatrix_t is a type defined by myself which basically wrap a eigen dynamic mat with float values):

    fmatrix_t m;
    m.resize(8,1);
    m << 0, 1, 2, 3, 4, 5, 6, 7;

    indices_t indices {2,1,4,0,3,7,6,5};
    fmatrix_t m2 = apply_permutation(m, indices);
    BOOST_CHECK_NE(m, m2);
    for (size_t i = 0; i < indices.size(); ++i)
    {
            BOOST_CHECK_EQUAL(m2(i,0), indices[i]);
    }

However when indices is {0,1,2,3,4,5,6,7} or {7,6,5,4,3,2,1,0} the permutation is done correctly. Am I doing something wrong or it could be a Eigen bug?

Why isn't std::condition_variable templated by lock type?

It's useful to have the ability to assert in debug mode, with reasonably small overhead, whether a mutex is locked. Viewing the known options, I've chosen to implement this using an std::mutex subclass due to the low overheads.

The interface of the subclass is a superset of that of std::mutex, and so most things work well with it. E.g., std::unique_lock is templated to utilize any lock type that has a specific interface.

The problem is with std::condition_variable, in particular the wait members, e.g.:

template<class Predicate>
void wait(std::unique_lock<std::mutex> &lock, Predicate pred);

As can be seen, the method requires a very specific unique_lock/mutex combination. Unfortunately, also, the Liskov principle doesn't extend for container<derived> being converted into container<base>.

I don't understand

  1. why this is so?

Even if the intent was to enforce the use of std::unique_lock, then why couldn't the following be used:

template<class Predicate, class Lock=std::mutex>
void wait(std::unique_lock<Lock> &lock, Predicate pred);

  1. how to reasonably get around this?

Edit

As explained by @Lingxi, and further pointed out by @T.C, the absolutely correct and very simple solution here is to use condition_variable_any, which was designed for stuff like this.

Qt OpenCV - SIGSEGV when displaying transformed frames

I have an app that has to pull frames from video, transform one a little, transform one a lot, and simultaneously display them in GUI. In a worker thread, there's an OpenCV loop:

while(1) {
    cv::VideoCapture kalibrowanyPlik; 
    kalibrowanyPlik.open(kalibracja.toStdString()); //open file from url
    int maxFrames = kalibrowanyPlik.get(CV_CAP_PROP_FRAME_COUNT);
    for(int i=0; i<maxFrames; i++) //I thought it crashed when finished reading the first time around
    {
        cv::Mat frame;
        cv::Mat gray;
        cv::Mat color;

        kalibrowanyPlik.read(frame);
        cv::cvtColor(frame, gray, CV_BGR2GRAY);
        cv::cvtColor(frame, color, CV_BGR2RGB);

        QImage image((uchar*)color.data, color.cols, color.rows,QImage::Format_RGB888);
        QImage processedImage((uchar*)gray.data, gray.cols, gray.rows,QImage::Format_Indexed8);

        emit progressChanged(image, processedImage);
        QThread::msleep(50);
    }
}

And this is how frames are placed in GUI

void MainWindow::onProgressChagned(QImage image, QImage processedImage) {
    QPixmap processed = QPixmap::fromImage(processedImage);
    processed = processed.scaledToHeight(379);
    ui->labelHsv->clear();
    ui->labelHsv->setPixmap(processed);

    QPixmap original = QPixmap::fromImage(image); //debug points SIGSEGV here
    original = original.scaledToHeight(379);
    ui->labelKalibracja->clear();
    ui->labelKalibracja->setPixmap(original);
}

The RGB image always crashes, grayscale image never crashes (tested). Why is the RGB image crashing?

edit: I've just discovered that if I change msleep(50) to msleep(100) it executes perfectly. But I don't want that. I need at least 25 frames per second, 10 is not acceptable... why would that cause a SIGSEGV

Detect geometric object on video stream and reconstruct its contours

I'm trying to detect a plastic object on video stream using OpenCV 2.4.9 on C++. The object has six angles and its contour looks like :original image.
For each frame I'm doing some kind of segmentation and edges detection. After these operations i got some binary image containing corrupted contours of the object and some noise from background.
For example: enter image description here or enter image description here

I need somehow to detect my object here and restore contours. Could you advise some methods? I need a fast method since I want to run this program on android phone.

I know the proportions of my object. And the camera is always approximately at normal angle to the object's surface.
Sometimes when the contour is not corrupted much i can find the correct bounding box, but in other cases I can't.
I think that I need to use somehow the information about object's geometry here. I will appreciate any help!

UPD:
If I have found a partial contour of the object, is it possible to fit My shape somehow inside found contour to obtain missing lines?

About the local variables of functions in c++

I have been reading the C++ primer 5th edition. In the third paragraph of Function Parameter List of Chapter 6.1 . It writes "Moreover, local variables at the outermost scope of the function may not use the same name as any parameter". What does it mean?

I am not native English speaker. I don't understand the actual meanings of "outermost scope" of the function.

C++ ODB USB Interface

i want to to connect a OBD-USB (http://ift.tt/1EUU0gd) Device to my Laptop and stream the received data to c++ program. Problem is i have no idea how i can communicate with Tool via USB, if there is any library or protocol-standard that describes the way the datas are sent from such OBD-Usb-Tools.

Does anyone have some experience or can name some tools/sites that can help me?

Thanks in advance

Edit: Wow getting many downvotes but not even a comment what's wrong ...

EMGU CV Face Recognition from Image

I've been working with OpenCV before for C++ work and It was working great. Now, I'm developing a C# project and using EMGU CV for gender recognition. I've got problem with predict function. Every time I ran it, program crashed. Here's my code:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
     FaceRecognizer face = new FisherFaceRecognizer(0, 3500);
     face.Load("colorFisherFaceModel.yml");                
     Image<Bgr, Byte> img1 = new Image<Bgr, Byte>("C:\\Users\\sguthesis\\Pictures\\me.jpg");
     cascade = new CascadeClassifier("C:\\Users\\sguthesis\\documents\\visual studio 2013\\Projects\\EmguCV FFR with Image\\EmguCV FFR with Image\\haarcascade_frontalface_alt_tree.xml");
     FaceRecognizer.PredictionResult predictedLabel = face.Predict(img1);
}

Also, I want to get an output, 1 or 2. 1 for male and 2 for female. I have trained many data that saved on colorFisherFaceModel.yml. It was run well on OpenCV. But I don't know how to use it in EMGU CV.

Setting up GLEW with QOpenGLWidget

community,

I have a Problem Setting up GLEW in Qt. Here is my class

#ifndef MYQOPENGLWIDGET_H
#define MYQOPENGLWIDGET_H

#define QT_NO_OPENGL_ES_2

#define GLEW_STATIC
#include <GL/glew.h>
#include <QOpenGLWidget>
#include <QMessageBox>

#include <iostream>


class MyQOpenGLWidget : public QOpenGLWidget{

public:
MyQOpenGLWidget(QWidget *parent = 0): QOpenGLWidget(parent){}

void initializeGL()
{



    GLenum err = glewInit();

    if(err != GLEW_OK)
    {
        QMessageBox::information(0, "Error!", QString("Failed to initialize GLEW ") + reinterpret_cast<const char*>(glewGetErrorString(err)), QMessageBox::Yes );
        exit(1);
    }
    else
    {
        QMessageBox::information(0, "Success!", QString("Succeded to initialize GLEW! "), QMessageBox::Yes );

    }

    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glEnable(GL_DEPTH_TEST);

    std::cout << "Leaving initializeGL" << std::endl;
}

void paintGL()
{
    std::cout << "paintGL()" << std::endl;
}


void resizeGL(int w, int h)
{
    if(h == 0)
      h=1;
    glViewport(0,0,w,h);

    std::cout << "resizeGL()" << std::endl;

    glOrtho(-1, 1, -1, 1, -1, 1);

}

};

#endif // MYQOPENGLWIDGET_H

In my pro-file I succesfully link to GLEW (which is included in gltools.lib which Comes form the OpenGLSuperbible )

QT       += core gui widgets

QT += opengl

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = untitled2
TEMPLATE = app

INCLUDEPATH += "C:/Users/fin/Documents/GLEWTEst/include"
LIBS += "C:/Users/fin/Documents/GLEWTEst/lib/gltools.lib"

SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h \
    myqopenglwidget.h

FORMS    += mainwindow.ui

DISTFILES += \
    ../build-untitled2-Desktop_Qt_5_4_1_MSVC2012_OpenGL_32bit-Debug/debug/untitled2.exe

Now what happens is, the Programm starts, and initializes GLEW correctly and calls initializeGL(), resizeGL() and then paintGL() Then it says the Programm was terminated with Exit code 1. So just a program Crash without any error message. Can anyone help me solve this?

Are there any alternatives to using OpenCV's imdecode? It is too slow

I have created a DLL where the user can either read an image from a file name or from a stream as follows:

std::string filePath = "SomeImage.bmp";

// (1) Reading from a file
Image2D img1;
img1.readImage(filePath);

// (2) Reading from a stream
std::ifstream imgStream (filePath.c_str(), std::ios::binary);
Image2D img2;
img2.readImage(imgStream);

The first readImage(filePath) is implemented using cv::imread(filePath) which is reasonably fast (on average 0.001 seconds for a 600 x 900 image). However, the second version readImage(fileStream) is implemented using cv::imdecode which is considerably slower (on average 2.5 seconds for the same image).

Are there any alternatives to cv::imdecode where I can decode an image from a memory buffer without taking such a long time? This is for the core component of an application that is frequently used, so it has to be quick.

Any assistance would be appreciated. Thanks in advance.

EDIT:

I measure the timings using a timer. It didn't make sense to me too. I don't understand why there is such a large disparity in the time. Image2D is just a class that has an OpenCV matrix as a member. The implementation of the readImage functions are simplified as follows:

int Image2D::readImage(std::ifstream& input)
{       
    input.seekg(0, std::ios::end);
    size_t fileSize = input.tellg();
    input.seekg(0, std::ios::beg);

    if (fileSize == 0) {
        return 1;
    }

    std::vector<unsigned char> data(fileSize);
    input.read(reinterpret_cast<char*>(&data[0]), sizeof(unsigned char) * fileSize);

    if (!input) {
        return 1;
    }

    StopWatch stopWatch;
    mImg = cv::imdecode(cv::Mat(data), CV_LOAD_IMAGE_COLOR);
    std::cout << "Time to decode: " << stopWatch.getElapsedTime() << std::endl;

    return 0;
}


int Image2D::readImage(const std::string& fileName)
{
    StopWatch stopWatch;
    mImg = cv::imread(fileName, CV_LOAD_IMAGE_COLOR);

    std::cout << "Time to read image: " << stopWatch.getElapsedTime() << std::endl;
    return 0;
}

Choose between template function and auto type deduction

I have a generic question about template functions versus auto type deduction for functions.

For years, we have have been able to write template function :

template <class T> T add(T a,T b){
    return a+b;
}

There is a TS for using auto for function's parameters deduction

auto add(auto a,auto b){
    return a+b;
}

I though with auto, one had no way to get to the actual type and for instance use static members, but this works just fine :

#include <iostream>

struct foo
{
    static void bar(){std::cout<<"bar"<<std::endl;}
    static int i ;
};
int foo::i{0};
void t(auto f){
    decltype(f)::bar();
    std::cout<<    decltype(f)::i<<std::endl;
}
int main(int argc, char *argv[])
{
    t(foo());
    return 0;
}    

So is there any reason to choose one instead of the other ?

Refreshing List Control with F5 key press C++

I have a List Control that shows a list of my database users. I also have a function that refreshes the list control (currently it is mapped to a "Refresh" button).

When the user presses the "F5" key, I want to call my refresh function.

I have found an event LVN_KEYDOWN (Indicates that a key has been pressed). After some research, I have found that the virtual keycode for "F5" is VK_F5. I am having trouble putting the two together, how can I check to see (in my event) that the "F5" key was the one that was pressed? I have tried several things similar to the code below:

void ListOption::OnLvnKeydownList1(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR);

    // TODO: Add your control notification handler code here
    if(pLVKeyDow == (LPNMLVKEYDOWN)VK_F5)  
        callRefreshFunction();

    *pResult = 0;
}

How to add data dynamically in structure which is a Pointer to an array of pointers

I have two structure as below:

typdef struct abc
{
   int id;
   char name;
}s_abc,*lpabc;
typdef struct result
{
    int acc_no;
    lpabc *details;
}s_res;

I need to dynamically add the data within the structure result which points out to an array of pointers ie: struct abc The structure abc could be an array of 5 values for eg. How should i add the values ?

the structure defined are explicit: For better understanding i'm attaching the structure below:-

typedef struct _wfs_cdm_physicalcu
{
    LPSTR                 lpPhysicalPositionName;
    CHAR                  cUnitID[5];
    ULONG                 ulInitialCount;
    ULONG                 ulCount;
    ULONG                 ulRejectCount;
    ULONG                 ulMaximum;
    USHORT                usPStatus;
    BOOL                  bHardwareSensor; 
 } WFSCDMPHCU, *LPWFSCDMPHCU;

typedef struct _wfs_cdm_cashunit
{
    USHORT                usNumber;
    USHORT                usType;
    LPSTR                 lpszCashUnitName;
    CHAR                  cUnitID[5];
    CHAR                  cCurrencyID[3];
    BOOL                  bAppLock;
    USHORT                usStatus;
    USHORT                usNumPhysicalCUs;
    LPWFSCDMPHCU         *lppPhysical;

} WFSCDMCASHUNIT, *LPWFSCDMCASHUNIT;
typedef struct _wfs_cdm_cu_info
{
    USHORT                usTellerID;
    USHORT                usCount;
    LPWFSCDMCASHUNIT *lppList;
} WFSCDMCUINFO, *LPWFSCDMCUINFO;

Here i need to access the data of _wfs_cdm_physicalcu 4 times ie : an array.

Why std::random_device entropy is always 0?

Suppose I have this cross-platform program

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::cout << "rd.entropy = " << rd.entropy() << std::endl;
    std::uniform_int_distribution<int> dist(0, 9);

    for (int i = 0; i < 10; ++i) {
        std::cout << dist(rd) << " ";
    }
    std::cout << std::endl;
}

On Linux Mint 17.1 with g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 it always produces random numbers:

$ g++ -std=c++11 testrd.cpp -o testrd
$ ./testrd
rd.entropy = 0
9 2 6 0 8 1 0 2 3 8 
$ ./testrd
rd.entropy = 0
3 6 2 4 1 1 8 3 7 5 
$ ./testrd
rd.entropy = 0
3 4 4 6 8 5 4 6 6 3 
$ ./testrd
rd.entropy = 0
2 4 7 7 6 3 0 1 1 9 
$ ./testrd
rd.entropy = 0
7 2 5 0 7 8 6 6 0 6 

But how can I be sure, that on any system std::random_device is random? For example, on Windows with mingw-gcc it is not random (see, for example this question), it will produce same sequence on start. But on MSVC++ (according to S. Lavavej) starting from 2013.4 it is random.

I thought that I can do this:

if (rd.entropy() != 0) {
    // initialize some generator like mt19937 with rd()
}
else {
    // use another seed generator (for example, time in milliseconds)
}

i.e. comparing rd.entropy() with 0. But it turns out to be wrong.

How can I test std::random_device for randomness?

How to use qDebug() with two parameters in qt?

I am trying to use qDebug() with two parameters but it fails everytime.

When I use separately there is no problem, such as;

qDebug() << "img:width = " << img.width();
qDebug() << "img:height = " << img.height();

However when I combine them, it gives error.

qDebug() << "img:width = " << img.width() << "/t img:height = " << img.height() << std::endl;

Error is :

error: no match for 'operator<<' in '((QDebug*)((QDebug*)((QDebug*)qDebug()().QDebug::operator<<(((const char*)"img:width = ")))->QDebug::operator<<(img.QImage::width()))->QDebug::operator<<(((const char*)"/t img:height = ")))->QDebug::operator<<(img.QImage::height()) << std::endl'

Can I use two or more parameters in qDebug?

how does one pass an Armadillo vec/mat as a ref argument to another method?

I apologise as it might be a daft question but: I want to use a function to fill my matrix but am struggling to pass it as an argument. Can anyone help?

calculating vertex normals in opengl with c++

could anyone please help me calculating vertex normals in OpenGL? I am loading an obj file and adding Gouraud shading by calculating vertex normals without using glNormal3f or glLight functions.. I have declared functions like operators, crossproduct, innerproduct,and etc.. I have understood that in order to get vertex normals, I first need to calculate surface normal aka normal vector with crossproduct.. and also since I am loading an obj file.. and I am placing the three points of Faces of the obj file in id1,id2,id3 something like that

I would be grateful if anyone can help me writing codes or give me a guideline how to start the codes. please ... thanks..

its to draw

FACE cur_face = cube.face[i];
        glColor3f(cube.vertex_color[cur_face.id1].x,cube.vertex_color[cur_face.id1].y,cube.vertex_color[cur_face.id1].z);
        glVertex3f(cube.vertex[cur_face.id1].x,cube.vertex[cur_face.id1].y,cube.vertex[cur_face.id1].z);
        glColor3f(cube.vertex_color[cur_face.id2].x,cube.vertex_color[cur_face.id2].y,cube.vertex_color[cur_face.id2].z);
        glVertex3f(cube.vertex[cur_face.id2].x,cube.vertex[cur_face.id2].y,cube.vertex[cur_face.id2].z);
        glColor3f(cube.vertex_color[cur_face.id3].x,cube.vertex_color[cur_face.id3].y,cube.vertex_color[cur_face.id3].z);
        glVertex3f(cube.vertex[cur_face.id3].x,cube.vertex[cur_face.id3].y,cube.vertex[cur_face.id3].z);
    }

This is the equation for color calculation

VECTOR kd;
VECTOR ks;
kd=VECTOR(0.8, 0.8, 0.8);
ks=VECTOR(1.0, 0.0, 0.0);
double inner =  kd.InnerProduct(ks);

int i, j;
for(i=0;i<cube.vertex.size();i++)
{
    VECTOR n = cube.vertex_normal[i];
    VECTOR l = VECTOR(100,100,0) - cube.vertex[i];
    VECTOR v = VECTOR(0,0,1) - cube.vertex[i];
    float xl = n.InnerProduct(l)/n.Magnitude();
    VECTOR x = (n * (1.0/ n.Magnitude())) * xl;
    VECTOR r = x - (l-x);

    VECTOR color = kd * (n.InnerProduct(l)) + ks * pow((v.InnerProduct(r)),10);
    cube.vertex_color[i] = color;

C++: Parsing with strtok and creating char* array

I have a problem today with parsing a string, and, although I have used strtok previously, I came across a problem. My code looks like this>

int main()
{
char *arr[8]; //create a pointer to array of 8 elements
string data;

cout<<"please input string "<<endl;
cin>> data;

ifstream in(data.c_str());
    if (in.is_open()) {
        cout<<"opened"<<endl;
    } else{
        cout<<"can't open the file you asked for"<<endl;
    }

std::string line;

while(getline(in,line)) {
        if(line.find("STR") == 0) { //looking only for lines that start with STR

  char *forParsing = new char[line.size()+1];
  std::copy(line.begin(), line.end(), forParsing);
  forParsing[line.size()]='\0';  //everything looks good up to here

  char * pch;

  pch = strtok (forParsing,","); //separate input string on every comma
  while (pch != NULL)
  {
     arr[x] = pch; x++;  //x previously initialized to zero
     cout<<pch<<endl;
     pch = strtok (NULL, ",");
  }

  delete[] forParsing;
} //end if
} //end while

After some debugging, it seems to me that strtok does it's work on a first line it gets. After that, program takes a next line from a file and then entire thing crashes.

My plan with this is to put all the non-empty tokens in arr, then do some light editing, and collect it all into one string that will later be used.

Does anyone have any idea why is this happening?

Thanks in advance.

NOTE> if its of any importance Process return 255(0xFF) when it crashes.

Import a persistent key in to Windows key storage using CNG storage functions

I'm trying to import a persistent RSA public key into the key storage. I read on the CNG help page that it's possible for private keys and I wonder if I can also apply is to public keys (specifically the BCRYPT_RSAPUBLIC_BLOB). I've tried with the following code, but in the import section, when I call NCryptSetProperty to set the public blob as a property, I get "Error 0x80090029" which is NTE Bad Data. Having trouble debugging why this function is failing.

NCRYPT_PROV_HANDLE providerHandle = NULL;
NCRYPT_KEY_HANDLE keyHandle = NULL;
NTSTATUS status = STATUS_UNSUCCESSFUL;
PBYTE blob = NULL;
DWORD blob_len = 0;

///////////////////Export Test (extract key from storage)///////////////////////////

// Open handle to the Key Storage Provider
if(FAILED(status = NCryptOpenStorageProvider(
    &providerHandle,            //OUT: provider handle
    MS_KEY_STORAGE_PROVIDER,    //IN: Microsoft key storage provider
    0)))                        //IN: dwFlags (unused)
{
    //report fail
}

// Open key in the Key Storage Provider
if (FAILED(status = NCryptOpenKey(
    providerHandle,
    &keyHandle,
    keyName.c_str(),
    0,
    0)))
{
    //report fail
}

// (2 step key extraction process) 1. Get size of key
if (FAILED(status = NCryptExportKey(
    keyHandle,              //IN: Handle of the key to export
    NULL,                   //IN(opt): key used to encrypt exported BLOB data   <-- potentially an safer way for key extraction, encrypt it with a key during extraction (decrypt with NCryptDecrypt)
    BCRYPT_RSAPUBLIC_BLOB,  //IN: BLOB type (http://ift.tt/1EURer6)
    NULL,                   //IN(opt): List of paramters for the key
    NULL,                   //OUT(opt): Output byte buffer
    0,                      //IN:  Size of the output buffer
    &blob_len,              //OUT: Amount of bytes copied to the output buffer
    0)))                    //IN: Flag to modify function behaviour (0 means no flag set)
{
    //report fail
}

// Allocate data blob to store key in
blob = (PBYTE)malloc(blob_len); 
if (NULL == blob) {
    //report fail
}

// (2 step key extraction process) 2. Get key and store in byte array (Extracted key is in form of BCRYPT_RSAKEY_BLOB)
if (FAILED(status = NCryptExportKey(
    keyHandle,
    NULL,
    BCRYPT_RSAPUBLIC_BLOB,
    NULL,
    blob,
    blob_len,
    &blob_len,
    0)))
{
    //report fail
}


///////////////Import Test (Store into storage)//////////////////////////////////////////////

// Create a persisted key
if(FAILED(status = NCryptCreatePersistedKey(
    providerHandle,             //IN: provider handle
    &keyHandle,                 //OUT: Handle to key
    NCRYPT_RSA_ALGORITHM,       //IN: CNG Algorithm Identifiers. NCRYPT_RSA_ALGORITHM creates public key
    keyName.c_str(),            //IN: Key name. If NULL, the key does not persist 
    0,                          //IN: Key type
    NCRYPT_OVERWRITE_KEY_FLAG)))//IN: Behaviour: 0 - apply to current user only, NCRYPT_MACHINE_KEY_FLAG - apply to local comp only, NCRYPT_OVERWRITE_KEY_FLAG - overwrite existing key
{
    //report fail
}

// Set the size of the key
if(FAILED(status = NCryptSetProperty(
    keyHandle,                          //IN: Handle to key
    BCRYPT_RSAPUBLIC_BLOB,              //IN: CNG Algorithm Identifiers. BCRYPT_RSAPUBLIC_BLOB allows me to use set this blob as the new key's blob
    blob,                               //IN: Key name. If NULL, the key does not persist 
    blob_len,                           //IN: Key Length
    0)))                                //IN: Bahaviour: 0 - apply to current user only, NCRYPT_MACHINE_KEY_FLAG - apply to local comp only, NCRYPT_OVERWRITE_KEY_FLAG - overwrite existing key
{
    //report fail <<-------------------------- Fail here
}

// Finalize key generation (Key is now usable, but uneditable) 
if(FAILED(status = NCryptFinalizeKey(keyHandle, 0)))            {
    //report fail
}
////////////////////////////////////////////////////////////////////////