jeudi 30 juin 2016

Active link turn different color

I'm trying to link those three scripts so that a active link turns to a different color purple. jquery.js contains the downloaded jquery library. I don't know why it is not working as expected. Anyone?

<link href="site.css" rel="stylesheet">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="color.js"></script>

</head>

<body>


<div class="nav-container" >
<ul class="navigation-menu" >
  <li><a href='start.php'>Home</a></li>
  <li><a href='pay.php'>C2B Payments</a> </li>
  <li><a href='sms.php'>C2B SMS</a></li>
  <li><a href='#'>B2C Payments</a>
    <ul>
      <li><a href="getbtc.php"> B2C Payments</a></li>
      <li><a href="payment.php"> Make Payments</a></li>
    </ul>
  </li>

  <li><a href='bsms.php'>B2C SMS</a></li>
  <li><a href='index.php'>Log Out</a></li>
</ul>

//JS color.js
$(document).ready(function(){
  $('ul li a').click(function(){
    $('li a').removeClass("active");
    $(this).addClass("active");
});
});

 //css site.css
.navigation-menu li a.active {
  background-color: purple;
  color:#fff;
  }

Laravel 5 Cron doesn't work

I am not sure why cron doesn't for Laravel artisan commands. But when I launch it manually like php artisan my:command it works.

I have put command in Kernel:

protected function schedule(Schedule $schedule)
{
    $schedule->command('my:command')->everyMinute();
}

Also when I run php artisan schedule:run it says: No scheduled commands are ready to run.

Crontab looks like this:

* * * * * php /project/artisan schedule:run

At first I thought maybe cron itself doesn't work, but it executes php files not related to artisan.

I am using PHP7 if it changes anything.


UPDATED (cron artisan commands work, but schedule dont)

Cron command works (log has been saved in storage/app folder)

* * * * * php /project/artisan command:test

Cron schedule doesn't work

* * * * * php /project/artisan schedule:run

test.php

namespace AppConsoleCommands;

use IlluminateConsoleCommand;
use Storage;
use CarbonCarbon;

class test extends Command
{
    protected $signature = 'command:test';

    protected $description = 'Command description';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        Storage::prepend('test.log', Carbon::now());
    }
}

Kernel.php

namespace AppConsole;

use IlluminateConsoleSchedulingSchedule;
use IlluminateFoundationConsoleKernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    protected $commands = [
        Commandstest::class,
    ];


    protected function schedule(Schedule $schedule)
    {
        $schedule->command('command:test')->everyMinute();
    }
}

PHP Dom Document - Using Glob and get and specific element and class in every file of a directory

I'm using Glob function in order to get every .htm file and then I trying to get text from a specific table where class = 'DataGrid_Item', by using PHP's DOM element with following HTML (same structure) and following code:

1. HTML

<div>
<table rules="all" id="GridViewAfiliacion" style="border-collapse:collapse;" border="1" cellspacing="0">
    <tbody>
        <tr class="DataGrid_Header" style="background-color:#98B676;">
            <th scope="col">ESTADO</th>
            <th scope="col">ENTIDAD</th>
            <th scope="col">REGIMEN</th>
            <th scope="col">FECHA DE AFILIACION ENTIDAD</th>
            <th scope="col">TIPO DE AFILIADO</th>
        </tr>
        <tr class="DataGrid_Item" align="center">
            <td>ACTIVO</td>
            <td>NUEVA EPS S.A.</td>
            <td>CONTRIBUTIVO</td>
            <td>01/06/2016</td>
            <td>COTIZANTE</td>
        </tr>
    </tbody>
</table>

2. PHP

    // Directory of Files

$directory = "../fosyga/archivoshtml/";
$array_filename = glob($directory . "*.htm");

foreach($array_filename as $filename)
    {
    $dom = new DOMDocument('1.0', 'utf-8');
    $dom->loadHTML($filename);
    $content_node = $dom->getElementById("GridViewAfiliacion");

    // Get the HTML as a string

    $string = $content_node > C14N();
    }

It's possyble to extract class="DataGrid_Item" info into a string?

Pd: I think the glob function does not work properly in this case, I'm not using that in a correct way.

Get total quantity and price from given dates

Hello guys I would like to ask how could I get the total quantity and total price of sales with this format of date. I was have this data in my database.

ID    Quantity    Price    Date
1       10          100          June 27,2016
2       12          120          June 28,2016
3      15          150          June 29,2016

I only getting one data with the first one row of 1 only. I have this query.

$query= $this->db->select('SUM(total_price) as overall_price, SUM(quantity) as total_quantity')->from('sales')
        ->where('branch',$_SESSION['branch'])->where('date_sold >=',date('F d,Y',strtotime($from)))->where('date_sold <=',date('F d,Y',strtotime($to)))->get();

How could I also get all the records from specific range of date for example from June 27 to June 29 ? I only got 1 record

$query= $this->db->select('*')->from('sales')->where('branch',$_SESSION['branch'])->where('date_sold    >=',$from)->where('date_sold <=',$to)->get();

Got tape os posts. Cann't count number of likes for each post

Trying to learn django and a bit more. Got a problem with counting number of likes for every post in tape. Problem is that I can not get id of post. If i refresh page, count of likes changes. But to make it changing with ajax is real problem. Please explain me how make changing likes count for every post in tape, if click like button.

Ajax code.

{% block jquery %}
    function updatePostLikesCount(){
        var postlikescount = $(".post-likes-count");
        var count = $(this)
        $.ajax({
            type: "GET",
            """Here is the biggest problem for me"""
            url: "/like_post/{{ post.id }}/post_likes_count/",
            success: function(data){
                postlikescount.html(data.count);
            },
            error: function(response, error){
            }
        })
    }
    updatePostLikesCount();

    $(".post-like").click(function(event){
        var img = $(this);
        event.preventDefault();
        $.ajax({
            url: img.parent().attr('href'),
            success: function(){
                updatePostLikesCount();
            },
            error: function(response, error){
            }
        })
    });
{% endblock %}

Here is tape of posts.

{% for post in tape %}
    ...
    {{ post.text }}
    ...
    <a class="post-like-href" href="/like_post/{{ post.id }}/">
        <img class="post-like"  src="{% static "" %}"/>
    </a>
    {% if post.like.liked_users.count > 0 %}
            <span class="post-likes-count" >
                {{ post.like.liked_users.count }}
            </span>
    {% endif %}
{% endfor %}

Here is a view that count post's likes

def post_likes_count(request, post_id, *args, **kwargs):
    if request.is_ajax():
        like = Like.objects.get(post_id=post_id)
        if like.liked_users.count == None:
            count = 0
        else:
            # like = Like.objects.get(post_id=post_id)
            count = like.liked_users.count()
        return JsonResponse({
            'count': count,
        })
    else:
        raise Http404

Else I tried to reload an element of page with likes , but was defeated :-)

Animate.css shake effect not working every time

I'm making a Twitch Streamer application, that pulls some data using Twitch API, for a predetermined set of streamers.

I have three buttons to select all/online/offline channels, and I am looking to add the animated shake effect to all these buttons.

On my first attempt, I had a simple if/else check in place to make the shake work correctly - detect if the animated shake class already exists, if so, remove it, and then add it again. Else, just add it.

That didn't work. I found an answer here on SO that said it won't work that way because the addClass and removeClass occur so fast that the DOM doesn't have time to catch up.

I then used a queue with an anonymous function to add the class back after inducing a slight delay after the removeClass -

if ($(this).hasClass("animated shake")) {
            $(this).removeClass("animated shake").delay(50).queue(
                function() {
                    $(this).addClass("animated shake");
                });
            //$(this).addClass("animated shake");
        } else {
            $(this).addClass("animated shake");
        }

Now, the shake effect works like 90% of the time, but if you keep switching back and forth between online/offline channels, there will be cases in between where the shake doesn't work.

Here's the app on Codepen.

I'd appreciate any help as to why it doesn't work every single time.

Note - The shake effect is on the online/offline buttons only, for now.

Shopify Dynamic Page Titles & Descriptions

would love some pointers if any SHOPIFY tech heads know how to solve this

BACKGROUND:

We're setting up a shoe store using the shopify platform with a structure that divides collections primarily into gender, style, brand and this is done via tags. So for example you may have a shoe that has tags with Womens, Birkenstock, Sandals.

A typical URL maybe = /collections/womens/birkenstock/sandals.

THE CHALLENGE:

Now my CHALLENGE is in this example the page title and page description is based on the leading collection in the URL, that being 'women'. Women in this instance does not best description to the user or search engines what this URL is about.

THE OUTCOMES NEEDED:

Is there a way you can create like dynamic page title & description in shopify from using a combination of {{ Collection }} {{ current_tags }}

/collections/womens/ = This would have a page name of womens-shoes

/collections/womens/birkenstock = This would have a page name of Womens Birkenstocks

/collections/womens/birkenstock/sandals = This would have a page name of Womens Birkenstocks Sandals

Each would aslo have thier own unique page description and not base it on the leading collection of just 'women'. Hope that makes sense.

I know I can create a collection of say womens-birkenstock or womens-birkenstock-sandals which would give me the result but for a number of reasons I really can't go down that path

Look forward to seeing if anyone knows how this works or even better an example of a SHOPIFY shop who has done this

Find and replace content within a string

I literally cannot find the solution for this anywhere. Is it possible to find everything from start and end, and the content inside.

var start = "/* Start: User One */";
var end = "/* End: User One */";

var userCSS = "
/* Start: User One */ 
div.user_one {height: 700px;}
/* End: User One */

/* Start: Storm */ 
div.storm {height: 500px;}
/* End: Storm */";

I've added the start and end as I've already extracted them, but how do I do a search for the start and end, and then once I've the start and end found how do I replace everything from start to end. So ideally once I've found the following:

This is what I am looking for, and ideally be able to replace it with a variable

/* Start: User One */ 
div.user_one {height: 700px;}
/* End: User One */

I can replace it with a variable. I feel like since I'm searching for the start and end, this has to be some sort of regex solution, but my regex is heavily limited.

New content variable

/* Start: User One */ 
div.user_one {height: 500px;}
div.user_one h1 {height: 500px;}
/* End: User One */

Input

/* Start: User One */ 
div.user_one {height: 500px;}
/* End: User One */

/* Start: Storm */ 
div.storm {height: 500px;}
/* End: Storm */";

Expected output

/* Start: User One */ 
div.user_one {height: 500px;}
div.user_one h1 {height: 500px;}
/* End: User One */

/* Start: Storm */ 
div.storm {height: 500px;}
/* End: Storm */";

PHP Threads do not seem to be working

I am making a Promise like in JavaScript, and I decided to do it using threads. So, I have the following class:

class Promise extends Thread {

    protected $action = null;
    protected $then = null;
    protected $catch = null;

    public function __construct(callable $callback){
        $this->action = $callback;
        $this->start();
    }

    public function run(){
        call_user_func_array($this->action, [
            function($result){
                if($this->then !== null){
                    call_user_func($this->then, $result);
                }
            },
            function($result){
                if($this->catch !== null){
                    call_user_func($this->catch, $result);
                }
            }
        ]);
    }

    public function then(callable $callback){
        $this->then = $callback;
        return $this;
    }

    public function catch(callable $callback){
        $this->catch = $callback;
        return $this;
    }

}

I then run the following code to test it:

// Run the first thread
(new Promise(function($resolve, $reject){
    sleep(5);
    $resolve(true);
}))->then(function(){
    echo 'Resolved 5 second promise' . PHP_EOL;
});

// Run the second thread
(new Promise(function($resolve, $reject){
    sleep(2);
    $resolve(true);
}))->then(function($result){
    echo 'Resolved 2 second promise' . PHP_EOL;
});

// Show a status
echo 'Waiting for Promises' to complete' . PHP_EOL;

When running this, I was expecting the following output:

Waiting for Promises' to complete
Resolved 2 second promise
Resolved 5 second promise

I instead get the following output:

Resolved 5 second promise
Resolved 2 second promise
Waiting for Promises' to complete

So, why is it not running in a thread like fashion?

Edit

I noticed that if I assign the Promise to a variable it outputs correctly, but feel I shouldn't have to do that...

Issues changing IP Address from int to string

I am trying to convert an IP address (currently IPv4, but recognizes IPv6) from an int array format to a formatted string. I am working on Ubuntu Linux.

I distinguish between IPv4 and IPv6 addresses, and then try to convert the int array to a string.

This is the code that I'm using:

#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>

int main(void)
{
    int i;
    unsigned int val32;
    int ma_ip[4];
    char m_ip[4];
    char ipaddr[INET_ADDRSTRLEN], ipv6[INET6_ADDRSTRLEN];
    int no = 0;
    char *token;
    char s3[] = "10.1.35.1";
    /* just example. test only one ip address.. */
    for(i = 0; i < 1; i++)
    {
        char *mm = strstr(s3, ":");
        if( *mm != NULL)
        {
             token = strtok(s3, ":");
             while(token != NULL)
             {
                 token = strtok(NULL, ":");
                 no++;
             }
             if(no >= 2 && no <= 7)
                 printf("nthis is ipv6n");
             else
                 printf("nwrong ipv6n");
         }
         else
         {
             token = strtok(s3, ".");
             while(token != NULL)
             {
                 token = strtok(NULL, ".");
                 no++;
             }
             if(no == 4)
             {
                 printf("nthis is ipv4.n");
                 val32 = inet_addr(s3)
                 ma_ip[i] = val32;
             }
             else
                 printf("nwrong ipv4.n")
         }
         inet_ntop(AF_INET,&ma_ip[0],ipaddr,INET_ADDRSTRLEN);
         printf("nipaddr = %sn", ipaddr);
         strcpy(&m_ip[0], ipaddr);
         printf("nafter strcpy = %sn", m_ip[0]);
    }
}

This output is wrong:

ipaddr = 0.0.0.10

It should actually be:

ipaddr = 10.1.35.1

I also get this error in the last printf after the strcpy:

format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ error !**

Why is this happening, and how can I fix it?

jqueryUI autocomplete menu show effect

I spend half of a day trying to apply fade effect for autocomplete drop down menu... The final result is very uncomfortable for me - look like 'lucky shoot', not real solution.

I used jqueryui default demo for example, and add lines:

var acMenu = $("#tags").data().autocomplete.menu.activeMenu;
acMenu._basehide = acMenu.hide;
acMenu.hide = function(){
      this._basehide("fade","slow");
      };
acMenu._baseshow = acMenu.show;
acMenu.show = function(){
      this._baseshow("fade","slow");
      }; 

The whole file looks like (© for www.jqueryui.com):

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
  <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });

    var acMenu = $("#tags").data().autocomplete.menu.activeMenu;
    acMenu._basehide = acMenu.hide;
    acMenu.hide = function(){
          this._basehide("fade","slow");
          };
    acMenu._baseshow = acMenu.show;
    acMenu.show = function(){
          this._baseshow("fade","slow");
          }; 

  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags" />
</div>


</body>
</html>

Can you suggest me better solution ?

Thanks!

INSERT does not work with mysqli

Have tried the following but still in database record is not getting inserted , please help

Page Name : multipleselect

    <body>
      <form action="multipleselectlogic.php" method="post">

      <select name="course[]" multiple="multiple">

        <option value="math01">Math 001</option>
        <option value="math02">Math 002</option>
        <option value="math03">Math 003</option>
        <option value="math04">Math 004</option>
        <option value="math05">Math 005</option>
        <option value="math06">Math 006</option>
        <option value="math07">Math 007</option>

      </select>

      <input type="submit" value="Add" name="send" />

      </form>


      </body>
      </html>

Page Name : multipleselectlogic

      <body>
      <?php

      $con = mysqli_connect("156.62.38.214","abc","abc22#","checkarray");

      if (mysqli_connect_errno())
      {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

      $std_id = 20;

      $course = $_POST['course'];



      if($course)
      {


      foreach ($course as $c)
      {


         print_r($course);

         echo $std_id;

         $sql = mysqli_query($con, "INSERT INTO check(course,std_ID)   
         VALUES('mysqli_real_escape_string($con , $c)','$std_ID')"); 

         if($con->query($sql)== TRUE)
         {
           echo " Insert Successfull";
         }
         else
         {  
             echo "Error:" . $sql . "<br>" . $con->error;
         }

        }

        }


        ?>


        </body>

Database : checkarray

Table Name : check

ID - Primary Key , Auto_increment - Null ( No )

course - varchar(100) - Null ( Yes )

std_ID - int(11) - Null ( Yes )

collation : utf8_general_ci

Details

I am not getting any error ( echo "Error:" . $sql . "
" . $con->error; ) , but no record are inserted into database

How to call ajax for a given list anchor tags with same class id but different url to call

I'm new to AJAX, and start to make an ajax able script, in which, I have a number of anchor tags with same class id. But with different url to call for each anchor tag. My function runs but, it call all the anchor tag, even i use to click on one anchor tag. But the task is done for only that clicked anchor tag And My 2nd problem is when the task completed for one anchor tag and I start to run other ones, it does not complete the task until I refresh the web page again, and click on it. But it shows that success on every anchor tag. Even the work is not done. Hope you understand my problem, Here is my ajax code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('.submitdelete').click(function() {
$.ajax({
    type:'POST', 
    url: 'http://localhost/w/wp-admin/admin.php?page=rssap-feeds&action=removePosts&post=28', 
    success: function(response) {
     alert("You have made it!");
    }
});
});
</script> 
<a href="#" title="Remove Posts" class="submitdelete">Remove Posts</a>
//this is for below one
<script type="text/javascript">
 $('.submitdelete').click(function() {
$.ajax({
    type:'POST', 
    url: 'http://localhost/w/wp-admin/admin.php?page=rssap-feeds&action=removePosts&post=29', 
    success: function(response) {
     alert("You have made it!");
    }
});
});
</script>
<a href="#" title="Remove Posts" class="submitdelete">Remove Posts</a>

And if some one does not understand this problem, please comment below for more information.

Question is How do I do that correctly?

Opening a file from userspace from a Linux kernel module

I've been following a tutorial for opening files from userspace from a Linux kernel module at http://www.howtoforge.com/reading-files-from-the-linux-kernel-space-module-driver-fedora-14

The code is the following:

#include <linux/module.h>  // Needed by all modules
#include <linux/kernel.h>  // Needed for KERN_INFO
#include <linux/fs.h>      // Needed by filp
#include <asm/uaccess.h>   // Needed by segment descriptors

int init_module(void)
{
    // Create variables
    struct file *f;
    char buf[128];
    mm_segment_t fs;
    int i;
    // Init the buffer with 0
    for(i=0;i<128;i++)
        buf[i] = 0;
    // To see in /var/log/messages that the module is operating
    printk(KERN_INFO "My module is loadedn");
    // I am using Fedora and for the test I have chosen following file
    // Obviously it is much smaller than the 128 bytes, but hell with it =)
    f = filp_open("/etc/fedora-release", O_RDONLY, 0);
    if(f == NULL)
        printk(KERN_ALERT "filp_open error!!.n");
    else{
        // Get current segment descriptor
        fs = get_fs();
        // Set segment descriptor associated to kernel space
        set_fs(get_ds());
        // Read the file
        f->f_op->read(f, buf, 128, &f->f_pos);
        // Restore segment descriptor
        set_fs(fs);
        // See what we read from file
        printk(KERN_INFO "buf:%sn",buf);
    }
    filp_close(f,NULL);
    return 0;
}

void cleanup_module(void)
{
    printk(KERN_INFO "My module is unloadedn");
}

The code is copy-pasted from the link above. On my machine, running Fedora 19 with 3.11.10-200 kernel, it seems that filp_open isn't run, providing the buf variable with null values.

What could be wrong? I am still learning the ropes of Linux kernel module development.

Nginx redirect URL into a PHP GET url

I have an nginx/PHP site.

Right now I have working URLs like:

http://example.com/search?param1=var1&param2=var2&param3=var3

Where var1, var2, and var3 are the first name, last name, and location respectively.

Question

I would like http://example.com/var1/var2/var3 to forward to http://example.com/search?param1=var1&param2=var2&param3=var3 without the url in the browser changing. So, the PHP functionality can remain but the URL looks clean and typing in a clean URL transforms it to a proper GET request.

So Far

I have my nginx file: /nginx/sites-available/default

And I have found code that people have used for forwarding from one URL to another while masking it:

location / {
    proxy_pass http://192.168.1.24;
    proxy_redirect http://www.example.com/some/path http://192.168.1.24;
    proxy_set_header Host $host;
}

But it does not seem to be able to handle the regex change that I want. Is it possible to use nginx to make these changes?

EDIT 1

This does not work, but I think it is closer:

location ~ /(?<var1>[^/])/(?<var2>[^/])/(?<var3>[^/]) {
    proxy_pass http://example.com/search.php?params1=$var1&params2=$var2&params3=$var3
    proxy_set_header Host $host;
}

Imagick CompositeImage feezes when destination is a bit out of the source

I'm trying to overlay a background image with many little icons. Sometimes, one of them goes over the edges of the background image, and this seems to make Imagick freeze. (The image generation takes a loooong time and at the end no image is rendered.)

Is that normal ?

I have ImageMagick 6.9.3-7 Q16 x68 and PHP 5.5.12.

Thanks for your help !

Here is the function that displays icons :

It's a PHP script with Imagick. Here it is.

public function render($imagick, &$draw, &$cursor, &$ready2Print){
    //var_dump($this);
    $metrics = $ready2Print->getCharMetrics();
    //var_dump($metrics);
    $tmpcur = [
        'x' => 0,
        'y' => 0
    ];
    foreach($this->_manas as $mana){
        //if(!self::isExistingMana($mana)) continue;
        // On charge le fichier
        $manaImage = new Imagick(self::getManaFile($mana));
        $size = 0; $yoffset = 0; $xoffset = 0; $advance = 0;
        if($manaImage->getNumberImages() == 0) continue;

        if(self::isLargeMana($mana)){
            // Rendu mana large
            $size = (int)($metrics['characterHeight'] * self::LARGE_MANA_RATIO);
            //var_dump($size);
            $manaImage->resizeImage(0, $size, Imagick::FILTER_LANCZOS, 1);
            $yoffset = (int)($metrics['characterHeight'] * self::LARGE_MANA_TOPLINE);
            $xoffset = (int)($metrics['characterHeight'] * ( self::LARGE_MANA_EFFECTIVE_WIDTH - self::LARGE_MANA_RATIO) / 2);
            $advance = (int)($metrics['characterHeight'] * self::LARGE_MANA_EFFECTIVE_WIDTH);
        } else {
            // Rendu mana small
            $size = (int)($metrics['characterHeight'] * self::SMALL_MANA_RATIO);
            //var_dump($size);
            $manaImage->resizeImage(0, $size, Imagick::FILTER_LANCZOS, 1);
            $yoffset = (int)($metrics['characterHeight'] * self::SMALL_MANA_TOPLINE);
            $xoffset = (int)($metrics['characterHeight'] * ( self::SMALL_MANA_EFFECTIVE_WIDTH - self::SMALL_MANA_RATIO) / 2);
            $advance = (int)($metrics['characterHeight'] * self::SMALL_MANA_EFFECTIVE_WIDTH);
        }

        $imagick->compositeImage(
            $manaImage, Imagick::COMPOSITE_OVER,
            $cursor->x + $tmpcur['x'] + $xoffset,
            $cursor->y + $tmpcur['y'] - $yoffset
        );
        $tmpcur['x'] += $advance;
    }
}

It's a simple loop with coordinates calculations and a CompositeImage call.

Pass variable from another page

I can't pass the variable to another page using session and i don't know what is the error here. Can someone help me? and clues on how to use the session? i want to pass the variable username to another page.

here is the html code. this is my login page where the variable is coming from.

  <div class="wrapper">
  <form class="logform" action="" method="post">
    <p class="title">Admin Login</p>
    <input type="user" name="uname" placeholder="Username" autofocus/>
    <i class="fa fa-user"></i>
    <input type="password" name ="pword" placeholder="Password" />
    <i class="fa fa-key"></i>
    <a href="#">Forgot your password?</a>
    <button type="submit" value="login" name="login">
      <i class="spinner"></i>
      <span class="state">Log in</span>
    </button>
  </form>
</div>

<?php
session_start();

include_once("connection.php");
if(isset($_POST['login'])){
    $user = $_POST["uname"];
  $password = $_POST["pword"];
    $name = mysqli_real_escape_string($con, $user);
    $password = mysqli_real_escape_string($con, $password);
    $select_user="SELECT * FROM accounts WHERE username ='$user' AND password ='$password'";
    $run_user = mysqli_query($con, $select_user);
    $check_user = mysqli_num_rows($run_user);
    if($check_user > 0){
    $_SESSION['uname'] = $username;
        header('location:admin.php');
    }
    else{
        echo "wrong";
    }
}
?>

here is the admin page.

<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

    <h1>Welcome, <?php echo $username; ?>!</h1>
</body>
</html>

Toggle Parse Server public read ACL using cloud code

I am using Parse Server (on Node.js) and have to expand my application to give my users a new function.

I have a class class called 'Programme'. Previously I locked this programme down to user only ACL using a before save function:

Parse.Cloud.beforeSave("Programme", function(req, res) {
    user = req.object.get("user");
    var acl = new Parse.ACL();
    acl.setReadAccess(req.user, true);
    acl.setWriteAccess(req.user, true);
    req.object.setACL(acl);
    res.success();
});

However I now wish to give the users a button to toggle the public view of a Program.

I have coded the button to request the cloud code and have got the beginning of a working function.

However, I have issues with checking if the queried programme has already got public view ACL set, or if it needs setting.

Questions:

  1. How can I toggle the setPublicReadAccess of an item in the Programme class.

  2. How can I deconflict this with my beforeSave function, because I expect my function is going to change it and then the beforeSave function will change it straight back.

My function so far:

Parse.Cloud.define('toggleSharedProgramme', function(req, res) {
    var user = req.object;
    var programmeId = req.params.programmeId;

    var query = new Parse.Query("Programme");
    query.equalTo("objectId", programmeId);
    query.first({ sessionToken: req.user.getSessionToken()}).then(function(results) {

        var acl = new Parse.ACL();
        // acl.setReadAccess(req.user, true);
        // acl.setWriteAccess(req.user, true);
        acl.setPublicReadAccess(true);
        results.setACL(acl);
        results.save();

        res.success('Working - code needs to be added to set the programme's ACL');
    })

});

php move_uploaded_file()

So I'm testing out the move_uploaded_file() php script from the w3schools website http://www.w3schools.com/php/php_file_upload.asp. Here is my code.

if ($_FILES["file"]["size"] < 2000000)
{
    if ($_FILES["file"]["error"] > 0)
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    else
    {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

        if (file_exists("/var/www/upload/" . $_FILES["file"]["name"]))
        {
          echo $_FILES["file"]["name"] . " already exists. ";
        }
        elseif(move_uploaded_file($_FILES["file"]["tmp_name"], "/var/www/upload/".$fileName))
            echo "Stored in: " . "/var/www/upload/".$fileName;
    }
}
else
    echo "Invalid file";

The problem is if(move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/upload/".$fileName)) returns false all the time but it seems the file is stored in the tmp folder on the server (for example: /tmp/php8rrKoW). When I check the tmp folder the file is not there. (It's supposed to get deleted after the script finish executing.) I also don't see the /php8rrkoW folder. I'm not sure if it's supposed to be there. I set the permission for both the tmp folder and /var/www/upload/ to 777 using chmod, but I'm not sure if I should set the owner to apache. So I want to know why the file isn't copied over to /var/www/upload and if there is a way to test this.

Simple PHP search [duplicate]

Alright, I have created a simple PHP search and all of it is working with the database, however I have realised my code is SQL injectable due to an error.

Index (Start page):

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Helpy Search Engine</title>
</head>
<body>
    <h1>Go ahead, search.</h1>
    <form action="results.php" method="get">
        <input type="text" name="query" placeholder="Search..">
        <button type="submit">Search</button>
    </form>
</body>
</html>

Results page (Displays search results.)

<?php

    $search = $_GET['query'];

    mysql_connect("localhost", "My username for DB", "My password for DB") or die(mysql_error());
    mysql_select_db("filthysl_search");

    $query = mysql_query("SELECT * FROM results WHERE title LIKE '%".$search."%'");
    if(mysql_num_rows($query) >= 1) {
        while($a = mysql_fetch_array($query)) {
            echo "<a href='".$a['url']."'>".$a['title']."</a><p>".$a['description']."</p><hr/>";
        }

    } else {
        echo "Oh no! Nothing was found.";
    }


?>

The Error I am getting (On Results page):

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home2/filthysloth/public_html/results.php on line 9

Thanks for any help !

Multidimensional PHP array to jQuery - Only seeing one result

I'm trying to use PHP and jQuery to create a dynamic search results page.

On the PHP side, a SELECT statement is called, where I check if all variables are set, add my HTML that I want to be used clientside, then put the variables in an array named $result.

Of the results of the database call, I also add the longitude and latitude in their own array, named $pins.

I then create a multidimensional array called $results, and put the array together like so:

$result = array('listing'=>$listing);
$pins = array('lat'=>$lat1,'lng'=>$lon2); 
$results = array('listing'=>$result,'pins'=>$pins);

echo json_encode($results);

Now, clientside I use jquery. The issue I'm facing, is there should be 2 results in total. However I see the same result repeated twice (I can confirm they should be unique). Here is my jQuery:

$.ajax({
    url: '/updatedsearch.php',
    type: 'POST',
    data: { 
        q: search, 
        lng: coordinates[0], 
        lat: coordinates[1], 
        },
                    dataType: "json",
                    success: function(data) {
                    if(data == "undefined" || data == null) {
                    console.log("There was no search results or something similar");
                                } else {
                                var pins = [data.pins.lat, data.pins.lng];
                                $.each(data, function(key, val) {
                                    $('#listings').append(data.listing.listing);
                                    console.log(pins);
                                    console.log(data);
                                });
                               }
                            },

Everything here works as it should, apart from when $.each() runs, it appears to be appending the same data twice.

I assume it's because of .append(data.listing.listing);, if I understand correctly I'm not looping through the array here, I'm effectively referencing data.listing.listing[0] - have I understood this correctly?

Strange array assignment behavior in C

I have in my C code an array of elements inside an heap structure defined as

typedef struct Elem {
    void    *key;
    void    *value;
} Elem;

typedef struct Heap {
    unsigned int    size;
    unsigned int    capacity;
    Elem            **array;
    compareFunction compare;
} Heap;

For the element insertion function, I use this pseudo-code for add a custom element inside the heap array

Insert (H, x)
HeapSize(H) := HeapSize(H)+ 1
i := HeapSize(H)
H[i] = x
while i > 1 and H[Parent(i)] < H[i] do
    exchange(H[i], H[Parent(i)])
    i := Parent(i) 

But during the assignment, especially after adding 4 elements, on the 5th call of this function a strange behavior happens in this line H[i] = x

for (k = 0; k < hpSize(hp) - 1; k++)
    printf("%dn", *((int *)hpGetEl(hp, k)->key));
if (hpSize(hp) > 1)
    printf("%dn", *((int *)(hp->array[0])->key));
printf("i: %dn", i);

hp->array[i] = hpCreateElem(key, value);

printf("%dn", *((int *)(hp->array[0])->key));
for (k = 0; k < hpSize(hp); k++)
    printf("%dn", *((int *)hpGetEl(hp, k)->key));

The output of the debugging printf is

1
4
2
3
---
1
i: 4
4198800
---
4198800
4
2
3
7

The assignment change the value of the key inside the first element of the array and insert the new element on the 5th position. How is this possibile?

The hpCreateElem function is defined as

Elem *hpCreateElem(void *key, void *value)
{
    Elem *el;

    el = (struct Elem *) malloc(sizeof(struct Elem));
    if (el == NULL) return NULL;

    el->key = key;
    el->value = value;

    return el;
}

C: Passing 2-dimensional array to function and using it

In a C program (to be compiled by Visual Studio 2013) I need to pass a pointer to a 1-dimensional array as a parameter of a function. The function writes values into the array. In another function I need to pass a two-dimensional array. This time the function does not need to write into the array - it just uses the values in it. I would like the functions to be useable with arrays of different sizes (i.e. I don't want to have to specify the number of elements (or in the case of the 2D array to number of sub-arrays of two elements each) in the array. I suppose I need to pass pointers to the arrays as parameters, but I'm not sure of the syntax for this, or the circumstances in which the array identifier can be used as a pointer to the array, or how this works for a 2D array.

How do I a) Define the functions? b) Define the arrays that I am going to pass to the functions? c) Call the functions? d) Refer to elements of the arrays within the functions?

Everything I have tried so far has given errors of the form "'uchar **' differs in levels of indirection from 'uchar [1]'" or "different types for formal and actual parameter 3" or "'uchar ()[2]' differs in levels of indirection from 'uchar [16][2]'".

Here is some code:

int i2c_write(int device_addr, uchar *data[][], int bytes)
{
}

int i2c_read(int device_addr, int register_addr, uchar *data[], int bytes)
{
}

    uchar readbyte[1];
    uchar writedata[16][2];

    if (i2c_read(0x76, 0xD0, readbyte, 1))  
    { etc.

    writedata[0][0] = 0xE0;
    writedata[0][1] = 0xB6;
    if (i2c_write(0x76, writedata, 1))
    { etc.

Thanks - Rowan

undefined symbol: ib_util_malloc when trying to call a UDF

I created a very simple UDF, compiles fine but when I try to use it, it gives the following error:

root@chii:/data/database/bot# /opt/firebird/bin/isql chii.fdb
Database: chii.fdb, User: SYSDBA
SQL> select YKUDF_PERLWRAPPER('/bin/ls' , '-al') from rdb$database;
/opt/firebird/bin/isql: symbol lookup error: /opt/firebird /UDF/YKUDFPerlWrapper: undefined symbol: ib_util_malloc

This is my sql declaration:

declare external function YKUDF_PERLWRAPPER
cstring(1024), cstring(1024)
returns cstring(16384) free_it
entry_point 'perlwrapper' module_name '/opt/firebird/UDF/YKUDFPerlWrapper';

my function.c:

#include <stdio.h>
#include <ctype.h>
#include "functions.h"
#include "ibase.h"
#include "ib_util.h"


extern void * ib_util_malloc(long);


char * perlwrapper (file, input)
     char * file;
     int * input;
{

  FILE *fp;
  char merged[1024];

  strcpy(merged, file);
  strcat(merged, " "");
  strcat(merged, input);
  strcat(merged, """);

  fp = popen(merged, "r");    /* Issue the command.   */


  /* Read a line      */
  char line[1024];      /* line of data from unix command*/
  char output[16382];
  strcpy(output," ");

  while ( fgets( line, sizeof line, fp))
  {
    strcat(output,line);
  }
  pclose(fp);

  int i;
  int len = strlen(output);
  char * result = (char *) ib_util_malloc (len + 1);

  for (i = 0 ; i < len ; i++)
    result[i] = output[i];
  result[i] = (char) 0;

  return result;
}

my function.h:

#define PROTO_LIST(list) ()

char * perlwrapper PROTO_LIST ((char *, char *));

And my compiler:

gcc functions.c -DIB60 -fpic -O -c -w -shared -I/opt/firebird/include -L/opt/firebird/lib -lib_util -lstdc++ -lm -lc -o functions.o
ld functions.o -o YKUDFPerlWrapper -G -Bsymbolic -lgds -lm -lc 

Tried to search the net about ib_util_malloc but most questions were left unanswered.

Javascript for Adobe Captivate

I got some help with some code to use in Captivate, and it works well. The idea is that when users click on any combination of 4 buttons and then submit, this will join the arrays, remove duplicates and then alphabetize the list in the variable called "things". What I've done is put word pairs (ex. "bet-bat") into the arrays, and it works well.

var someThings = [ ];
var selected = [ ];

var b_or_v =["bet-vet","bat-vat","reb-rev","bick-vic","ban-van"];
var b_or_p =["back-pack","bet-pet","bit-pit","ban-pan","bin-pin"];
var I_or_e =["bit-bet","pit-pet","sit-set","rib-reb","pick-peck","pin-pen","rip-rep"];
var e_or_a =["bet-bat","set-sat","vet-vat","peck-pack","pet-pat","pen-pan","rep-rap"];
function getUnique( arr ) 
{
    var dupes = [ ];

    return arr.filter( function( item ) 
{
        return dupes.hasOwnProperty( item ) ? false : ( dupes[ item ] = true );
    });
}
function newArray( arr )
{   
var temp = [ ]; 

if ( selected.indexOf( arr ) != -1 )
{  
  selected.splice( selected.indexOf( arr ), 1 );

  for ( var i = 0; i < selected.length; i++ )
  {
   temp = temp.concat( selected[ i ] ).sort();
  }

  someThings = temp;
}
else
{
  selected[ selected.length ] = arr+20;
  someThings = someThings.concat( arr ).sort();
} 
}
function newThings( )
{
var str = getUnique( someThings ).toString();
var res = str.replace( /,/g, ", ");
window.cpAPIInterface.setVariableValue( "things", res );
}

As you can see, I've used word pairs (ex. "bet-bat"). So now I want to erase the hyphens and break the word pairs into individual words in the list (alphabetized and no duplicates).

FOR EXAMPLE:

Right now if the user clicks "b_or_v" then b_or_p", the answer appears as: bet-vet,bat-van,reb-rev,bick-vic,ban-van,back-pack,bet-pet,bit-pit,ban-pan,bin-pin

But I want to split these word pairs, and de-duplicate them to get something like:

back, ban, bat, bet, bick, bin, pack, pan, pet, pin, reb, rev, van, vic

Any suggestions? Thanks. Bill

Ensuring that php data is sent to mysql

Hi I have this code shown below. This works great but every so often the data does not get added to the database. What is the best way to ensure that the data gets added to the database. What I think should happen is that on an error it tries again maybe every 15 seconds for say 3 times. Let me know if you don't agree.

Can anybody show me the php code I need to add and where I should add it. I'm a little out of my depth but I'm thinking that the php knows when it's failed as there is "if ($conn->connect_error)" in the code.

I'm also concerned that the data does not get added multiple times.

Please let me know if this is more complicated than I'm thinking. Any help, comments are welcome.

    <?php
///////////////////////////////////////////////
//////////////////// Login ////////////////////
///////////////////////////////////////////////
    $servername = "*******";
    $username = "*******";
    $password = "*******";
    $dbname = "*******";


///////////////////////////////////////////////
/////////////// Get vars //////////////////////
///////////////////////////////////////////////
    $identifier = $_REQUEST['identifier'];
    $paid = "Not Paid";
    $cartAmount = $_REQUEST['cartAmount'];
    $cartMore = $_REQUEST['cartMore'];
    $cartLink = $_REQUEST['cartLink'];
    $cartImage = $_REQUEST['cartImage'];
    $cartSelected = $_REQUEST['cartSelected'];
    $cartName = $_REQUEST['cartName'];
    $cartQuantity = $_REQUEST['cartQuantity'];
    $shippedDate = $_REQUEST['shippedDate'];
    $myNote = $_REQUEST['myNote'];


///////////////////////////////////////////////
///////////// Create connection ///////////////
///////////////////////////////////////////////
    $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }


///////////////////////////////////////////////
///////////// add vars to data base /////////////
///////////////////////////////////////////////
    $sql = "INSERT INTO customers (cartAmount, cartMore, cartLink, cartImage, cartSelected, cartName, cartQuantity, identifier, paid, shipped_date, myNote)
    VALUES ('$cartAmount', '$cartMore', '$cartLink', '$cartImage', '$cartSelected', '$cartName', '$cartQuantity', '$identifier', '$paid', '$shippedDate', '$myNote')";
    
    if ($conn->query($sql) === TRUE) {
        echo $cartAmount . "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    $conn->close();
    echo "Connected successfully";
    ?>

mercredi 29 juin 2016

How to search for specific strings and integers in a .txt file C and use them?

This code is a small learning experience about File I/O which i can't quite finish yet:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    FILE *fP;

    char so_name[64];
    char user_name[64];
    int number;
    char continue_button;

    time_t t;

    system("TITLE Love-0-meter");
    system("COLOR 4D");

    srand((unsigned) time(&t));
    number = (rand() %100);

    printf("Hi and welcome to the love-o-meter, please fill in the details and see how much you and your SO"
       " love each other!nnHave you used this program before?(Y/N)");
    do
    {
        scanf(" %c", &continue_button);

    }while(continue_button != 'n' && continue_button != 'N' && continue_button != 'Y' && continue_button != 'y');

    system("CLS");
    printf("Enter your SO's name: ");
    scanf(" %s", so_name);
    printf("Enter your name: ");
    scanf(" %s", user_name);
    printf("n%s and %s, you love each other %d%%", so_name, user_name, number);

    if(continue_button == 'N' || continue_button == 'n')
    {
        fP = fopen("Love-o-meter.txt", "w");
    }
    else
    {
        fP = fopen("Love-o-meter.txt", "a");
    }
    fprintf(fP, "%s %s %in", so_name, user_name, number);
    fclose(fP);

    return 0;
}

Basically the user must enter 2 names in and be saved in a .txt file along with a random number. But before the names get saved the program must check if they've been used before in the same order. If they have indeed been used before, the program must not generate a new number but use the one saved together with the 2 names and print it out on the screen.

I've been reading all day but i just can't figure out how and what to implement to be able the program to read previously saved names and numbers and use them if it finds a match.

How to share a $scope object between multiple controllers

I am facing problem while sharing a $scope object between 2 controllers.

In controller 'IssueBookCtrl',I am updating the books object element value like this.

$scope.books[i].issued = true;

Then I am using $emit service to share the $scope object with controller 'BookListCtrl_Librarian'.

$scope.$emit('update_parent_controller', $scope.books);

But when I run the view which is using the controller 'BookListCtrl_Librarian',i don't see the updated object.

controller.js

Controllers.controller('BookListCtrl_Librarian', ['$scope','$http','$location','$rootScope','BookData',
function ($scope, $http ,$location, $rootScope , BookData) {
    $http.get('data/books.json').success(function(data) {
    if($rootScope.books==='undefined'){
        $rootScope.books = BookData.getData();
    }
        $scope.books = data;
    });
    $scope.options = ['bookId', 'cost'];

    $scope.$on("update_parent_controller", function(event, books){
        $scope.books = books;
    });
    $scope.issue = function(bookId) {
        for (var i = 0, len = $scope.books.length; i < len; i++) {
            if ($scope.books[i].bookId == bookId) {
                $rootScope.book = $scope.books[i];
                break;
            }
        }
        $location.path('/issue/'+bookId);
    }
        $scope.return = function (bookId) {
            for (var i = 0, len = $scope.books.length; i < len; i++) {
                if ($scope.books[i].bookId == bookId) {
                    $rootScope.book = $scope.books[i];
                    break;
                }
            }
            $location.path('/return/'+bookId);
        }
    $scope.backToLogin = function() {
        $location.path("/main");
    }
    }]);
Controllers.controller('IssueBookCtrl', ['$scope','$rootScope','$http','$routeParams','$location',
function ($scope,$rootScope, $http, $routeParams, $location) {
    var Id=$routeParams.bookId;
    $http.get('data/books.json').success(function(data) {
        $scope.books = data;
    });
    $scope.issue = function(Id) {
        alert("issued");
       for (var i = 0, len = $scope.books.length; i < len; i++) {             
            if ($scope.books[i].bookId === Id) {
                $scope.books[i].issued = true;              
                $scope.$emit('update_parent_controller', $scope.books);
                $location.path('/home/librarian');
                break;
            }
        }
    }
}]);

Please guide me,any help is much appreciated.

Thanks

MEAN stack using AngularJS or any alternative?

I am going to develop a new web based application and I was wondering which template engine should I use.

The initial setup will contain :

  • NodeJS
  • MongoDB
  • Express
  • Bootstrap
  • And some extras such as i18n for multilanguages, less for CSS and probably something else in the future.

And I was thinking in using AngularJS to control the user interface and manage all the requests to the REST api server.

I used Angular v1 around a year ago and I really enjoy it the way it looks so dynamic. However, I have seen that at the moment, Angular 2 is getting stable and it could be a good option to use the latest version of this framework.

However, after looking the initial setup and all the difficulty of this, I was considering moving to another framework/templating engine as my idea is to have a project as a "one page app" and deal everything in it.

I found that using a template engine such as EJS would resolve what I want to develop, but obviously, it would not bring the interaction and logics I want and I had with Angular v1.

My questions are :

  • Is still worth it using Angular 1 for my 1 page app ?
  • Should I move to Angular 2 regardless of the difficulties I am having to set it up ?
  • Is there any alternative to what I am looking for which could be suitable ?

My idea is not to use jQuery when possible and do all the ui animations and logics with the template (like ng-show.. hide.. etc). Apologies for my English as it is not my main language.

Failing to run tests using Karma

I am setting up Karma to simplify unit tests in a legacy project. The problem is, I am getting an error You need to include some adapter that implements __karma__.start method!. As I have found, this is a very non-specific error, so I am at a loss of how to debug it further. I have reduced my setup to the bare minimum, but the error still persists.

Here is the karma config file:

module.exports = function (config) {
  config.set({
    browsers: [ 'PhantomJS' ], //run in Phantom
    autoWatch: false,
    singleRun: true, //just run once by default
    frameworks: [ 'mocha', 'chai', 'sinon', 'chai-sinon' ], // test frameworks
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    files: [
      './js/test/tests.webpack.js' //just load this file
    ],
    preprocessors: {
      './js/test/tests.webpack.js': [ 'webpack', 'sourcemap' ] //preprocess with webpack and our sourcemap loader
    },
    reporters: [ 'mocha' ], //report results in this format
    webpack: { // webpack settings
      devtool: 'inline-source-map',
      module: {
        loaders: [
          { test: /.js$/, loader: 'babel-loader' }
        ]
      }
    },
    webpackServer: {
      noInfo: true
    },
    plugins: [
        'karma-mocha',
        'karma-webpack',
        'karma-sourcemap-loader',
        'karma-mocha-reporter',
        'karma-phantomjs-launcher',
        'karma-chai',
        'karma-sinon',
        'karma-chai-sinon'
    ]
  });
};

Here are the packages I have installed (from package.json):

"babel-core": "^6.9.1",
"babel-loader": "^6.2.4",
"babel-plugin-module-alias": "^1.5.0",
"babel-preset-es2015": "^6.9.0",
"chai": "^3.5.0",
"karma": "^1.0.0",
"karma-chai": "^0.1.0",
"karma-chai-sinon": "^0.1.5",
"karma-chrome-launcher": "^1.0.1",
"karma-mocha": "^1.0.1",
"karma-mocha-reporter": "^2.0.4",
"karma-phantomjs-launcher": "^1.0.1",
"karma-sinon": "^1.0.5",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^1.7.0",
"mocha": "^2.5.3",
"phantomjs": "^2.1.7",
"phantomjs-polyfill": "0.0.2",
"sinon": "^1.17.4",
"sinon-chai": "^2.8.0",
"webpack": "^1.13.1"

Here is .babelrc:

{
  "presets": ["es2015"]
}

And here is the test file that I am referencing in karma.conf.js (tests.webpack.js). My initial idea was to require all spec files in it, but now I have changed it to run at least a single test. Still no luck:

import chai from 'chai';
var expect = chai.expect;

console.log('I was found');
it('works', function () {
    expect(true).to.equal(true);
})

Could you please advise how to debug this problem further?

In a social network environment, what would be the easiest way to check for friendships globally?

For reference, here is a question on SO that I asked recently that is relevant to this question: How to model Friendship relationships

On that question, we figured out a way to display news feed items only if posted by friends. However, what I need is advice on how to check for friendship in a more dynamic way so it can be used throughout several site functions.

For example, I've just installed a comment system, allowing users to post comments on news posts. However, this isn't restricted to friends, and it should be (and later should be made optional by the author of the post).

Posting news items only by friends was slightly different because I was getting data directly from the database, and using SELECT subqueries to only get posts by friends of the current user. However, in the example of the commenting, I only want to display the comment post form if the person is a friend. I'm not actually pulling anything from the database to pick, sort, and display.

Knowing issues like this will arise many times throughout the site, what would be the simplest way to check for friendship? Could I somehow pull all the friends' user IDs from the database into a session array of some kind and then do an if(in_array($friends)) whenever I needed to determine if the person in question is a friend of the currently logged in user? Off the top of my head, this sounds like it would work fine, but I'd like your input first.

The question I linked to above explains how my friendship table works, in case that help you help me with this.

Object created via AngularJs is not appearing on web page

Here is my code. Please tell me where am I wrong. The object dish is not shown when i load the webpage. The webpage remains blank only. I am using AngularJs.

<!DOCTYPE html>
<html lang="en" ng-app>

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="hk.css">
<link rel="stylesheet" href="font-awesome-4.6.3/css/font-awesome.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="bootstrap-social.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="container">
    <div class="row info" ng-init="dish={name:'Uthapizza',
                                         image:'uthapizza.png',
                                         category:'mains',
                                         label:'hot',
                                         price:'4.99'
                                         description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                                         comment:''}">
        <div class="col-md-12">
            <div class="media">
                <div class="media-left media-middle">
                    <a href="#"><img class="img-thumbnail media-object" ng-src={{dish.image}}></a>
                </div>
                <div class="media-body">
                    <h2 class="media-heading">{{dish.name}}<span class="label label-dangerous label-xs">{{dish.label}}</span><span class="badge">{{dish.price}}</span></h2>
                    <p>{{dish.description}}</p>
                </div>
            </div>
         </div>
    </div>
 </div>

Checkbox preselection is not working on EntityType Field (ManyToMany)

My Symfony version is 2.7.3. I have Vehicle entity, which has WorldCountry field (unidirectional ManyToMany):

/**
 * Vehicle
 * @ORMTable(name="vehicle")
 */
class Vehicle
{
    // ...

    /**
     * @ORMManyToMany(targetEntity="AppBundleEntityWorldCountry", fetch="EAGER")
     * @ORMJoinTable(name="vehicle_country_join",
     *   joinColumns={@ORMJoinColumn(name="vehicle_id", referencedColumnName="vehicle_id", onDelete="CASCADE")},
     *   inverseJoinColumns={@ORMJoinColumn(name="country_id", referencedColumnName="country_id")}
     * )
     */
    protected $countries;

    // ...

    public function __construct()
    {
        // ...
        $this->countries = new ArrayCollection();
    }
}

I have form for vehicle creation/editing:

/**
 * Class VehicleType
 * @package AppBundleFormVehicle
 */
class VehicleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...
            ->add('countries', 'entity', [
                'class' => 'AppBundle:WorldCountry',
                'choices' => $this->worldManager->getCountriesByRegionIds([1]),
                'choice_label' => 'name',
                'expanded' => false,
                'multiple' => true,
                'label' => false
            ])
            ->add('submit', 'submit');

        // ...
    }
}

Vehicle creation works fine, for example as result I have: enter image description here

The problem is that on vehicle editing page countries are not preselected (“Kyrgyzstan” in that example), when “choices” option is used:

enter image description here

But without it countries are preselected:

enter image description here

$this->worldManager->getCountriesByRegionIds([1]) - returns array of WorldCountry from repository.

P.S. Please let me know if more information is required.

Change destination ip

I'm trying to create a kernel module that forward packets in certain conditions. Now I'm trying to do just a hard code test to forward a packet received in an interface and forward it to another interface. In this test I'm receiving a packet from 192.168.56.101 on eth0 and I want to forward this packet on eht1 for 192.168.57.103. In eth0 my ip is 192.168.56.102 and in eth1 my ip is 192.168.57.102. The transport protocol I'm using is a experimental protocol (253). The following code is just a simplified part of my code:

#define XOR_PROTOCOL 253

static unsigned int xor_pre_routing_hook(const struct nf_hook_ops *ops, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *))
{
    struct iphdr *iph;
    struct xorhdr *ptr;
    char sip[15];
    char sip2[15];

    iph = ip_hdr(skb);

    sprintf(sip, "%pI4", &iph->saddr);
    sprintf(sip2, "%pI4", &iph->daddr);

    // Check if is XOR protocol
    if (iph->protocol == XOR_PROTOCOL) {
        DEBUG("(Ogirinal) From %pI4 to %pI4.n", &iph->saddr, &iph->daddr);

        if (strcmp(sip, "192.168.56.101") == 0 && strcmp(sip2, "192.168.56.255") == 0) {
           //iph->saddr = inet_addr("192.168.57.102");
           iph->daddr = inet_addr("192.168.57.103"); 
           DEBUG("(Modified) From %pI4 to %pI4.n", &iph->saddr, &iph->daddr);
           iph = ip_hdr(skb);
           iph->check = 0;
           ip_send_check (iph);
           return NF_ACCEPT;
        }
    }
accept:
    return NF_ACCEPT;
}

This hook in NF_INET_PRE_ROUTING. I also have a hook to just print source and destination ip in NF_INET_FORWARD, but there is no packet passing through this hook.

I'm testing with 3 linux virtual machine on virtual box, and I enabled the forward option in each vm. Is possible to forward packets in this scenario? What I'm doing wrong and what can I do to solve this problem?

Tinymce Error - Failed to load plugin js files when dynamically loaded

I'm trying to load TinyMCE dynamically like so (on clicking a button):

$.getScript('path/to/mce4/tinymce.min.js', function(){
    var def = {
        selector: 'textarea',
        body_class: 'sp-mce-editor',
        content_css : "path/to/styles/mce.css",
        plugins: ['advlist autolink lists link image charmap print preview hr anchor pagebreak searchreplace wordcount visualblocks visualchars code insertdatetime media nonbreaking table contextmenu directionality emoticons template paste textcolor fullscreen autoresize'],
        toolbar: "bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | fontsizeselect forecolor backcolor | preview fullscreen | template",
        toolbar_items_size: 'small',
        relative_urls : false,
        convert_urls : true,
        external_plugins: { "nanospell": "path/to/mce4/nanospell/plugin.js" },
        nanospell_server:"php",
        file_browser_callback: RoxyFileBrowser,
        init_instance_callback: (typeof processEditor != 'undefined' ? processEditor : null)
   };


    tinymce.init(def);
});

With this configuration, tinyMCE fails to initialize. In the console I see several 404 errors, each with a message like this:

Failed to load: /path/to/mce4/plugins/textcolor/plugin.js

Sure on checking in the console the JS file tinymce.min.js loads correctly. Also, the /path/to/mce4/plugins/textcolor/plugin.js does not exist. But /path/to/mce4/plugins/textcolor/plugin.min.js exists, and this is true for all the js files involved (i.e. the .min.js files are there, but tinyMCE for whatever reason is looking for the .js files).

Now, when I load tinyMCE in a script tab in the <head>, there's no problem at all, and everything works well.

What could be causing this error, and how am I supposed to fix it? If this is the expected behaviour of tinyMCE, what is the correct way to dynamically load the its js file for the scenario such as I am working on?

Age cannot be calculated properly using datepicker

I just cannot calculate the age when I select a date from the datepicker. It is always showing some wrong age.The age calculation code is written in age.php while the rest of the code is in index.php. And also when I write an age like 1980-10-01 in the age strtotime()it shows the correct answer but I want the user to select the age hence I have written the post variable in it. I am using php 5.2 and cannot upgrade it so please give me a working php 5.2 age calculation method.Thanks in advance.

$(document).ready(function() {
  $('#datetimepicker8').datepicker({
    format: 'dd-mm-yyyy',
    icons: {
      time: "fa fa-clock-o",
      date: "fa fa-calendar",
      up: "fa fa-arrow-up",
      down: "fa fa-arrow-down"
    }
  });
  $(document).on('change', '#birthdate', function() {
    $.ajax({
      url: 'age.php',
      data: {
        action: 'birthage'
      },
      type: 'post',
      success: function(data) {
        $("#age").val(data);
      }
    });
  });
});
age.php 

<?php function birthage() {
  $age="";
  $age=floor((time() - strtotime($_POST['birtdate'])) / 31556926);
  echo $age;
}
//here you can do some "routing"
$action=$_POST['action']; //remember to escape it
 switch ($action) {
  case'birthage': birthage();
  break;
  default: //function not found, error or something
  break;
}
?>
index.php
<div class="form-group row">
  <label class="col-sm-2 form-control-label">Birthdate</label>
  <div class="col-sm-5">
    <div class='input-group date' id='datetimepicker8'>
      <input type='text' id="birthdate" class="form-control" placeholder="D.O.B" name="birthdate" />
      <span class="input-group-addon">
          <i class="fa fa-calendar" aria-hidden="true"></i>
        </span>
    </div>
  </div>
  <label class="col-sm-1 form-control-label">Age:</label>
  <div class="col-sm-4">
    <input type="text" id="age" class="form-control" name="age" placeholder="Age">
  </div>
</div>

Dropdown menu with default value from txt file

I'm working on a project for my school for modifying basic wireless parameters in a linux router with commands just using HTML GUI. I worked mostly with php. So far i've been going fine but now i'm stuck and i cannot find any clear solution for my little problem.

I have the following drop down:

<form method="post" action="changefrequency.php">
<select name="freq">
<option value="auto">Auto</option>
<option value="2412">Channel 1</option>
<option value="2417">Channel 2</option>
<option value="2422">Channel 3</option>
<option value="2427">Channel 4</option>
<option value="2432">Channel 5 </option>
<option value="2437">Channel 6</option>
<option value="2442">Channel 7</option>
<option value="2447">Channel 8</option>
<option value="2452">Channel 9</option>
<option value="2457">Channel 10</option>
<option value="2462">Channel 11</option>
<option value="2467">Channel 12</option>
</select>
  <input type="submit" value="Set Frequency"/>
</form>
</div>

I post the value let's say option 2432 (channel5) to a router via php scripting with the command inside it using FTP upload and it works fine. I have made a script which automatically download in a txt file the frequency. So let's say user selected from the HTML and submited in the drop down channel 5 with value 2432 i will get locally saved a txt that has 2432 or frequency=2432 inside it.

Now my question is how can we check what value will it be inside the txt file and put it as default value for my dropdown? So any time the user changes the frequency the default value will be change in the dropdown menu.

thanks!

Trying to automate a post to wall wth PHP, I am able to post a standalone picture but when it is part of a post it is not showing up

Trying to automate a post to wall wth PHP, I am able to post a standalone picture but when it is part of a post it is not showing up.

Below is my code; this is my first post and tried my best to search through but got no luck. Is the issue due to the localhost option I am using?

<html>
<head>
</head>
<body>
<?php

include_once ('.facebook-php-sdk-mastersrcfacebook.php');
$PAGE_ID = ""; // The page you want to post to (you must be a manager)  
$FACEBOOK_APP_ID = "xxx"; // Your facebook app ID
$FACEBOOK_SECRET = "xxx"; // Your facebook secret
$ACCESS_TOKEN="xxx"; // The access token you receieved above
$PAGE_TOKEN = ""; // Leave this blank. It will be set later
$facebook = new Facebook(array(  
'appId'  => $FACEBOOK_APP_ID, 
'secret' => $FACEBOOK_SECRET,  
'cookie' => true,  
));  

$post = array('access_token' => $ACCESS_TOKEN);
try {
$res = $facebook->api('/me/accounts','GET',$post);
print_r($res);
if (isset($res['data'])) {
  foreach ($res['data'] as $account) {
     if ($PAGE_ID == $account['id']) {
        $PAGE_TOKEN = $account['access_token'];
        break;
     }
  }
}
} catch (Exception $e){
echo $e->getMessage();
}
$facebook->setFileUploadSupport(true);

 $loginUrl   = $facebook->getLoginUrl(
        array(

            'scope'         => 'manage_pages,publish_actions,publish_stream,user_photos',
            'redirect_uri'  => 'http://localhost/'

        ));

$photo = $facebook->api('/me/photos', 'POST', 
    array(
        'source' => '@' . realpath('samsonite.jpg'),
        'message' => 'This photo was uploaded via localhost'
    )
);
echo "came here1";
$photoid=$photo['id'];
echo "came here2".$photoid;
print_r($photo);
echo  'http://www.facebook.com/photo.php?fbid='.$photoid;
$args = array(
'message'   => 'message - My First Fbapplication With PHP script1!',
'name' => 'name - Message Posted from kishore!',
'caption'   => 'Test caption!',
    'picture' =>  'http://localhost/samsonite.jpg'   );
$post_id = $facebook->api("/me/feed?access_token=xxx", "post", $args);

?>
</body>
</html>

DOMPODF failed in Laravel

I have this method in my controller which export a PDF

    public function export($semester)
    {
        // some code

        $pdf = PDF::loadView('entities.match.pdf', ['profiles' => $profiles, 'semester' => $semester]);

        return $pdf->download('Matches_' . $semester->name . '.pdf');
    }

and my "match.pdf" view

<h3>Matches for {{ $semester->name }}</h3>

@if (count($profiles) == 0)
    No Matches for this semester yet...
@else
    <table border="1" border-spacing: "5px" style="width:100%">
    <thead>
    <tr>
        <td align="center" colspan="2">Local Student</td>
        <td align="center" colspan="2">Incoming Student</td>
    </tr>
    <tr>
        <th> Last, first name</th>
        <th> Course</th>
        <th> Last, first name</th>
        <th> Course</th>
    </tr>
    </thead>
    <tbody>
    @foreach($profiles as $item)
        <tr>
            <td width="20%">
                {{ $item['local']->user->last_name }}, {{ $item['local']->user->first_name }}<br>
                {{ $item['local']->user->email }}
            </td>
            <td width="30%">{{ $item['local']->course->name }}</td>
            <td width="20%">
                {{ $item['incoming']->user->last_name }}, {{ $item['incoming']->user->first_name }}<br>
                {{ $item['incoming']->user->email }}
            </td>
            <td width="30%">{{ $item['incoming']->course->name }}</td>
        </tr>
    @endforeach
    </tbody>
    </table>
@endif

The code is correct and works but if only if the amount of "profiles" is less than about 110. If the "profile" amount is above that number, I get "failed" as the download status in Firefox and Chrome.

Is this a DOMPDF bug? Is my code not right? Any workaround?

Hardfault handling - Arm Cortex-M0

I'm having some difficulty creating a hard fault handler for the NRF51 which has an ARM CortexM0.

(note: the following code has been combined from different sources on the internet) Here's what I have so far:

    static void hard_fault_handler_c(unsigned int * hardfault_args)
{
    unsigned int stacked_r0;
    unsigned int stacked_r1;
    unsigned int stacked_r2;
    unsigned int stacked_r3;
    unsigned int stacked_r12;
    unsigned int stacked_lr;
    unsigned int stacked_pc;
    unsigned int stacked_psr;

    stacked_r0 = ((unsigned long) hardfault_args[0]);
    stacked_r1 = ((unsigned long) hardfault_args[1]);
    stacked_r2 = ((unsigned long) hardfault_args[2]);
    stacked_r3 = ((unsigned long) hardfault_args[3]);

    stacked_r12 = ((unsigned long) hardfault_args[4]);
    stacked_lr = ((unsigned long) hardfault_args[5]);
    stacked_pc = ((unsigned long) hardfault_args[6]);
    stacked_psr = ((unsigned long) hardfault_args[7]);

    for(;;);
}

void HardFault_Handler(void)
{
    asm volatile(  
        "movs r0, #4tn"  
        "mov  r1, lrtn"  
        "tst  r0, r1tn" /* Check EXC_RETURN[2] */  
        "beq 1ftn"  
        "mrs r0, psptn"  
        "ldr r1,=hard_fault_handler_ctn"  
        "bx r1tn"  
        "1:mrs r0,msptn"  
        "ldr r1,=hard_fault_handler_ctn"  
        : /* no output */  
        : /* no input */  
        : "r0" /* clobber */  
    );  
}

The error during compilation is the following: Building target: project.elf Invoking: Cross ARM C++ Linker C:UsersStevenAppDataLocalTempccuAgDyP.ltrans9.ltrans.o: In function HardFault_Handler': <artificial>:(.text.HardFault_Handler+0x18): undefined reference tohard_fault_handler_c' collect2.exe: error: ld returned 1 exit status make: *** [FruityMesh.elf] Error 1 makefile:65: recipe for target 'project.elf' failed

In summary, it looks like the linker is having trouble finding the address for hard_fault_handler_c function. I would think that i would need to write assembly to import or include the path to this function but, this is just my suggestion. I haven't been able to write assembly for the M0 that compiles to do so.

Thank you

Webpack - Require Images Using File-Loader

I am using Webpack for my React app.

I installed 'File-loader' & 'Url-loader' in my webpack config.

However, Im not sure how to link images to my components. I am holding the 'src' for the image in a 'Data.js' file from where I pass the data for the image to the react component.

My webpack.config.js:

...
const PATHS = {
    app : path.join( __dirname, "app" ),
    build : path.join( __dirname, "build" )
};

const common = {
    entry : {
        app : PATHS.app
    },
    output : {
        path : PATHS.build,
        filename : "bundle.js"
    },
    module : {
        preLoaders : [
...
        loaders : [
            {
                test : /.css$/,
                loaders : [ "style", "css" ],
                include : PATHS.app
            },
            {
                test : /.jsx?$/,
                loader : "babel",
                query : {
                    cacheDirectory : true,
                    presets : [ "react", "es2015" ]
                },
                include : PATHS.app
            },
            {
                test : /.(jpg|png)$/,
                loader : "file-loader?name=[name].[ext]",
                include : PATHS.app
            }
...

Im my react presentation component, Im simply using require to retrieve the image:

const PreviewTemImgParent = ({ data }) => {
    let img = require( data.get( "src" ));
    return(
        <div className = "card previewImgParent">
            <img
             src = { img }
    ...

The Data.js file has absolute paths (main app folder) for each image (I may be going wrong here):

export const previewTemImgData = Map({
    body : List.of(
        Map({   // using immutable.js
            src : "app/css/asset/template/png/body/GatheredAtEmpireLine.png",
            alt : "image",
            className : "flipParent",
...

Global directory image for what its worth:

enter image description here

I wonder where I am making the mistakes and how to resolve this?

EDIT : After reading around, I figure that webpack needs reference for the relative position of the image, so I have amended webpack.config.js to following:

...
output : {
  path : PATHS.build,
  publicPath : "/",
  filename : "bundle.js"
}
...

However, that doesnt solve the problem. Guidance would be much appreciated.

How to avoid trap representations when doing XOR bit-cancellation on signed ints?

As as suggested solution for Given three numbers, find the second greatest of them, I wrote:

int second_largest(int a, int b, int c) {
    int smallest = min(min(a, b), c);
    int largest = max(max(a, b), c);

    /* Toss all three numbers into a bag, then exclude the
       minimum and the maximum */
    return a ^ b ^ c ^ smallest ^ largest;
}

The idea is that ^ smallest ^ largest cancels out the bits such that the middle number remains.

However, @chux pointed out a problem:

A singular problem with int and a ^ b ^ c ^ smallest ^ largest is that an intermediate result may be a trap representation on rare non-2's complement platforms. – chux

@chux Please explain? XOR just operates bit by bit, and doesn't care what the bits represent, right? – 200_success

XOR does not care, but the result maybe a problem: e.g. with say sign-magnitude integers, -1 ^ 1 goes to -0 which maybe a trap value - stopping the code. see C11 §6.2.6.2 2. Bit-wise ops are better used on unsigned types. – chux

Further C11 §6.2.6.2 3 specifies implementation defined behavior for ^ with int on rare non-2's complement platforms . In particular "It is unspecified whether these cases actually generate a negative zero or a normal zero, " rendering a ^ b ^ c ^ smallest ^ largest unspecified that it will work as desired even if a trap value is not used. The next section explains how this can be UB. Best to leave this novel code to unsigned types. – chux

It seems unfortunate that a technique that should be logically and mathematically sound could be derailed by a technicality.

Is there a way to salvage this XOR technique and make it legally safe, ideally with zero runtime overhead? (Something involving unions, maybe?)

Bootstrap JavaScript Carousel Doesn't Stop Cycling

Twitter Bootstrap Version: 2.0.3

Example HTML code:

<!DOCTYPE html>
<html dir="ltr" lang="en-US" xmlns:og="http://opengraphprotocol.org/schema/">
<head>
<link rel="stylesheet" type="text/css" media="all" href="reddlec/style.css" />
<script type="text/javascript">
$(document).ready(function() {
    $('.carousel').each(function(){
        $(this).carousel({
            pause: true,
            interval: false
        });
    });
});​
</script>
<script src="http://twitter.github.com/bootstrap/assets/js/jquery.js"></script>
<script src="http://twitter.github.com/bootstrap/assets/js/bootstrap-transition.js"></script>
<script src="http://twitter.github.com/bootstrap/assets/js/bootstrap-carousel.js"></script>
</head>
<body>
<div id="myCarousel" class="carousel slide">
  <!-- Carousel items -->
  <div class="carousel-inner">
    <div class="active item">…</div>
    <div class="item">…</div>
    <div class="item">…</div>
  </div>
  <!-- Carousel nav -->
  <a class="carousel-control left" href="#myCarousel" data-slide="prev">&lsaquo;</a>
  <a class="carousel-control right" href="#myCarousel" data-slide="next">&rsaquo;</a>
</div>
</body>
</html>

CSS: Provided with bootstrap.css

Problem: As you can see, I've enabled paused mode, and disabled cycling. But when I click the carousel's left or right controls, the carousel starts cycling at the default interval (5 seconds per cycle) on mouseleave.

How do I forcefully disable cycling? I want the images to be cycled manually by the user.

You can test the problem live on my test site here.

CakePHP 3 Password Reset fix

I have the following code to reset my password via a link through email (that works fine).

In my User Controller:

 public function resetpw($token = null) {
        $resetpw = $this->Users->findByToken('id');
        if ($this->request->is('post')) {
            $pw = $this->request->data['password'];
            $pwtable = TableRegistry::get('Users');
            $newpw = $pwtable->find($resetpw);
            $newpw->password = $pw;
            if ($pwtable->save($newpw)) {
                 $this->Flash->success(__('Your password has been successfully updated.'));
                return $this->redirect(['action' => 'login']);
        }
            else {
                $this->Flash->error(__('Your password could not be saved. Please, try again.'));
             }
        }
    }

The Reset Password CTP file:

Resetting your password?

<?= $this->Flash->render(); ?>
<?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your new password.') ?></legend>
        <?= $this->Form->input('password', ['label' => 'New Password']) ?>
        <?= $this->Form->input('confirmpassword', ['type' => 'password', 'label' => 'Confirm New Password']) ?>
    </fieldset>
    <?= $this->Form->button(__('Update password')); ?>
<?= $this->Form->end() ?>

I also have the following rules regarding comparing the two passwords:

public function validatePasswords($validator)
{
    $validator->add('confirmpassword', 'no-misspelling', [
        'rule' => ['compareWith', 'password'],
        'message' => 'The passwords are not the same.',
    ]);
    return $validator;
}

After typing in two identical passwords for both the password & comfirmpassword fields, I get the following error:

Unknown finder method "SELECT Users.id AS Users__id, Users.username AS Users__username, Users.password AS Users__password, Users.email AS Users__email, Users.role AS Users__role, Users.token AS Users__token FROM users Users WHERE Users.token = :c0"

I'm not really sure what this means and how I go about resolving it.

Angular (ionic) render true values from checkbox

I am using ionic + parse js sdk and would like to render only the true values from a checkbox.

Below is the scope:

$scope.Diagnosed = [
    { text: "Allergies", checked: true},
    { text: "ADHD", checked: false},
    { text: "Alcohol/Drug Dependence", checked: false},
    { text: "Asthma", checked: false},
    { text: "Autism", checked: false},
    { text: "Cancer", checked: false},
    { text: "Diabetes", checked: false},
    { text: "Eating Disorder", checked: false},
    { text: "Fertility Problems", checked: false},
    { text: "Heart Disease", checked: false},
    { text: "High Cholesterol", checked: false},
    { text: "Menopause", checked: false},
    { text: "Mood Disorders (e.g., anxiety, depression)", checked: false},
    { text: "Obesity", checked: false},
    { text: "Stroke", checked: false},
    { text: "Prefer not to answer", checked: false}

    ];

And I am rendering the values on a different page using the below code:

query.get(id,{
success: function(response){

  var currentStart = 1
  for (var i = currentStart; i < response.length; i++) {
    var object = response[i];
          }

 $scope.Details = {
     diagnosed: response.get('diagnosed'),

  };
},
error: function(error){
   alert("Error: " + error.code + " " + error.message);
}
  });
};

And my htm look like the following:

</ion-item class="more-list">
  <ion-item class="item more-item">
    <i class="icon-left ion-cash more-icon"></i>
    <p class="moredetails location"> {{Details.diagnosed}}</p>
  </ion-item>
  </ion-item>
</ion-list>

On that page, the data is rendered like this:

 [{"checked":true,"text":"Allergies"},{"checked":false,"text":"ADHD"},{"checked":false,"text":"Alcohol/Drug Dependence"},{"checked":false,"text":"Asthma"},{"checked":false,"text":"Autism"},{"checked":false,"text":"Cancer"},{"checked":false,"text":"Diabetes"},{"checked":false,"text":"Eating Disorder"},{"checked":false,"text":"Fertility Problems"},{"checked":false,"text":"Heart Disease"},{"checked":false,"text":"High Cholesterol"},{"checked":false,"text":"Menopause"},{"checked":false,"text":"Mood Disorders (e.g., anxiety, depression)"},{"checked":false,"text":"Obesity"},{"checked":false,"text":"Stroke"},{"checked":false,"text":"Prefer not to answer"}]

But how do I only display the values that have been checked as true?

Thank you in advance..

C array pointer arithmetic

I am trying to rewrite my code that takes the user input array, goes to the function and adds zeros between each number and saves it to array 2. My source code works just fine but I am having trouble trying to make it so that it uses pointer arithmetic just for the function to visit each array element, it cannot be sub scripting. What can you tell me about my code or suggestions on how to do this?

Source code:

#include <stdio.h>

void insert0(int n, int a1[], int a2[]);

int main(void) {

  int i;     
  int n;

  printf("Please enter the length of the input array: ");   
    scanf("%d", &n);

  int a[n];   
  int b[2*n];  

  printf("Enter %d numbers for the array: ", n);   
    for (i = 0; i < n; i++){     
      scanf("%d", &a[i]);
    }

  insert0(n, a,  b);

  printf("Output array:");   
    for (i = 0; i < 2*n; i++){
      printf(" %d", b[i]);   
        printf("n");
    }
    return 0; 
}

void insert0(int n, int a[], int b[]) {

  int i, j = 0; 

  for(i = 0; i < n; i++, j+=2){    
    b[j]= a[i];    
      b[j+1] = 0; 
  }
}

My arithmetic:

   #include <stdio.h>

    void insert0(int n, int *a1, int *a2);

    int main(void) {

      int i;     
      int n;

      printf("Please enter the length of the input array: ");   
        scanf("%d", &n);

      int a1[n];   
      int a2[2*n];  

      printf("Enter %d numbers for the array: ", n);   
        for (i = 0; i < n; i++){     
          scanf("%d", &a2[i]);
        }

//not sure if this is how you call it, I've seen it called with arr
      insert0(n, a1, a2); 

      printf("Output array:");   
        for (i = 0; i < 2*n; i++){
          printf(" %d", a2[i]);   
            printf("n");
        }
        return 0; 
    }

    void insert0(int n, int *a1, int *a2) {

      int *p;
      int j = 0;

        // I think I translated this properly     
        for(p = a1; p < a1+n; p++, j+=2){
          a2+j = a1+p;  
          //unsure how to get a2[j+1] to still work here with pointer  
            a2(j+1) = 0; 
      }
    }

C: Passing 2-dimensional array to function and using it [duplicate]

This question already has an answer here:

In a C program (to be compiled by Visual Studio 2013) I need to pass a pointer to a 1-dimensional array as a parameter of a function. The function writes values into the array. In another function I need to pass a two-dimensional array. This time the function does not need to write into the array - it just uses the values in it. I would like the functions to be usable with arrays of different sizes (i.e. I don't want to have to specify the number of elements (or in the case of the 2D array to number of sub-arrays of two elements each) in the array. I suppose I need to pass pointers to the arrays as parameters, but I'm not sure of the syntax for this, or the circumstances in which the array identifier can be used as a pointer to the array, or how this works for a 2D array.

How do I:

  1. Define the functions?
  2. Define the arrays that I am going to pass to the functions?
  3. Call the functions?
  4. Refer to elements of the arrays within the functions?

Everything I have tried so far has given errors of the form "'uchar **' differs in levels of indirection from 'uchar [1]'" or "different types for formal and actual parameter 3" or "'uchar ()[2]' differs in levels of indirection from 'uchar [16][2]'".

Here is some code:

int i2c_write(int device_addr, uchar *data[][], int bytes)
{
}

int i2c_read(int device_addr, int register_addr, uchar *data[], int bytes)
{
}

int main(void)
{
    uchar readbyte[1];
    uchar writedata[16][2];

    if (i2c_read(0x76, 0xD0, readbyte, 1))  
    { etc.
    }
    writedata[0][0] = 0xE0;
    writedata[0][1] = 0xB6;
    if (i2c_write(0x76, writedata, 1))
    { etc.
    }
}

save jquery value with php

i have form like this

<div id="signUp" class="form-inline">
   <div class="form-group">
      <label for="">I Sign up as</label>
      <input id="placehold" type="text" class="form-control text-center" readonly/>
      <div class="smallspace"></div>
      <div class="displayTable">
         <div class="radio-inline">
            <input type="radio" class="radio_item" value="Company"  name="item" id="radioCompany">
            <label class="label_item" for="radioCompany"></label>
            <p class="text-center colorGrey">Company</p>
         </div>
         <div class="radio-inline">
            <input type="radio" class="radio_item" value="Chef"  name="item" id="radioChef">
            <label class="label_item" for="radioChef"></label>
            <p class="text-center colorGrey">Chef</p>
         </div>
         <div class="radio-inline">
            <input type="radio" class="radio_item" value="Food lover" name="item" id="radioFoodLover">
            <label class="label_item" for="radioFoodLover"></label>
            <p class="text-center colorGrey">Food lover</p>
         </div>
      </div>
   </div>
</div>
<script src="js/upload.js"></script>

inside upload js i code like this

(function($) {
    "use strict";

    // register
    $(document).ready(function() {

        $('#signUp input').on('change', function() {
            var signUp = $(this).val();
            $("#placehold").val(signUp);//show value of chosen radio button to input text
        });
    });

})(jQuery);

summary this code is, i have input text(readonly) and 2 radio button, when we choose the radio button then system will get the value of the choosen than show it to the input type text.

the reason i put the validation to other file because honestly it got so much validation, for another input too. i just didnt like it if i have to place the validation inside html file.

my question is: is it posible to get that value and store it to database via PHP?

Grouping multidimensional php array by a key and add the values another key [duplicate]

Suppose I have following array:

Array
(
[2016] => Array
    (
        [C1] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [project_id] => 1
                        [company_type] => C1
                        [capacity_share] => 12
                        [project_year] => 2016
                    )

                [1] => Array
                    (
                        [id] => 4
                        [project_id] => 2
                        [company_type] => C1
                        [capacity_share] => 16
                        [project_year] => 2016
                    )

            )

        [C2] => Array
            (
                [0] => Array
                    (
                        [id] => 2
                        [project_id] => 1
                        [company_type] => C2
                        [capacity_share] => 14
                        [project_year] => 2016
                    )

                [1] => Array
                    (
                        [id] => 3
                        [project_id] => 2
                        [company_type] => C2
                        [capacity_share] => 15
                        [project_year] => 2016
                    )

            )

    )

[2014] => Array
    (
        [C1] => Array
            (
                [0] => Array
                    (
                        [id] => 5
                        [project_id] => 3
                        [company_type] => C1
                        [capacity_share] => 20
                        [project_year] => 2014
                    )

                [1] => Array
                    (
                        [id] => 8
                        [project_id] => 4
                        [company_type] => C1
                        [capacity_share] => 10
                        [project_year] => 2014
                    )

            )

        [C2] => Array
            (
                [0] => Array
                    (
                        [id] => 6
                        [project_id] => 3
                        [company_type] => C2
                        [capacity_share] => 22
                        [project_year] => 2014
                    )

                [1] => Array
                    (
                        [id] => 7
                        [project_id] => 4
                        [company_type] => C2
                        [capacity_share] => 11
                        [project_year] => 2014
                    )

            )

    )

)

Is there any way so that I can create a new array like this:

Array
(
[0] => Array(
    //project_year
    'project_year' => 2016,          

     //sum of 'capacity_share' where company_type = C1 and project_year = 2016
    'C1_capacity_sum' => 28, //[12+16]

     //sum of 'capacity_share' where company_type = C2 and project_year = 2016
    'C2_capacity_sum' => 29 //[14+15]
    )
[1] => Array(
     //project_year
    'project_year' => 2014,

     //sum of 'capacity_share' where company_type = C1 and project_year = 2014
    'C1_capacity_sum' => 30, //[20+10]

     sum of 'capacity_share' where company_type = C2 and project_year = 2014
    'C2_capacity_sum' => 33 //[22+11]
    )
);

I am very new to PHP any can't find any built-in method for this. However I have tried my hands on array_walk and array_map.

I will welcome any hint or help regarding this.

Thanks.