dimanche 31 juillet 2016

Printing name and value of a macro

I have a C program with a lot of optimizations that can be enabled or disabled with #defines. When I run my program, I would like to know what macros have been defined at compile time.

So I am trying to write a macro function to print the actual value of a macro. Something like this:

SHOW_DEFINE(X){
  if( IS_DEFINED(X) )
      printf("%s is defined and as the value %dn", #X, (int)X);
  else
      printf("%s is not definedn", #X);
}

However I don't know how to make it work and I suspect it is not possible, does anyone has an idea of how to do it?

(Note that this must compile even when the macro is not defined!)

Why does my for loop variable stays in scope? [duplicate]

This question already has an answer here:

This took me a while to track it down, and I can fix it by changing:

for(i = 1; i < 2; i++) 

to

for(var i = 1; i < 2; i++)

But why is it in scope at all in the first example, it must be by design.

loop(); 

function whyIsIinScope()
{
  alert('why is i in scope? i is ' + i ); 
}

function loop()
{
  for(i =1; i < 2; i++)
  {
    whyIsIinScope();
  }
}

https://jsfiddle.net/gbsjv4re/

mq_open giving "too many open files"

I created a message queue with following code. First few times it works properly.

int main()
{
    mqd_t mqdes;
    char mq_name[10] = "/mq";
    int oflag = O_CREAT | O_RDWR, ret;
    struct mq_attr attr;

    attr.mq_maxmsg = 1024;
    attr.mq_msgsize = 2048; 

    mqdes = mq_open(mq_name, oflag, 0766, &attr);
    if(mqdes == -1) {
            perror("mq_open");
            if(errno == EMFILE)
                    perror("EMFILE");
            exit(1);
    }

    printf("mqueue created, mq_descriptor: %dn", mqdes);

    ret = mq_close(mqdes);
    if(ret == -1) {
            perror("mq_close");
            exit(2);
    }
    printf(" mq closed successfuln");


    return 0;
}

After that, it's giving following error

mq_open: Too many open files
EMFILE: Too many open files

But why i'm getting this error? How can I see possix message queues like ipcs is for system V?

Can a C compiler change bit representation when casting signed to unsigned?

Is it possible for an explicit cast of, say, int32_t to uint32_t, to alter the bit representation of the value?

For example, given that I have the following union:

typedef union {
    int32_t signed_val;
    uint32_t unsigned_val;
} signed_unsigned_t;

Are these code segments guaranteed by the spec to have the same behaviour?

uint32_t reinterpret_signed_as_unsigned(int32_t input) {
    return (uint32_t) input;
}

and

uint32_t reinterpret_signed_as_unsigned(int32_t input) {
    signed_unsigned_t converter;
    converter.signed_val = input;
    return converter.unsigned_val;
}

I'm considering C99 here. I've seen a few similar questions, but they all seemed to be discussing C++, not C.

How to send user to another page after login (node js)

I have the following code that checks to see if a user exists in a database...

router.post('/', function (req, res) {

    User.findOne({
        username: req.body.log_username,
        password: req.body.log_password
    }, function (err, docs) {
        if (docs.length !== 0) {
            console.log("user exists");

        }
        else {
            console.log("no exist");
        }
    });

});

I have a home page that I want to send the user to if the login was a success. What should I put in the if statement to send the use to another page, in this case, home.js. home.js has the following code in it...

var express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
    res.render('home', { title: 'Express' });
});

module.exports = router;

were does this function gets its values?

This is an example from a book. The function returns TRUE if even and FALSE if not. I cant understand how it works. This is what I understand:

  1. 42 binds to n
  2. Creating "even" function
  3. x binds to n which = 42
  4. x != 0
  5. initiating "else"
  6. creating "odd" function
  7. odd(42 - 1)
  8. Initiating "!even(41)".

What does JS do with "even(41)"? were TRUE comes from? The way I understand it should return TRUE only when x === 0

document.write(
  ((n) => {
    const even = (x) => {
      if (x === 0) return true;
      else {
        const odd = (y) => !even(y);
        return odd(x - 1);
      }
    }
    return even(n)
  })(42)
)

F_GETPIPE_SZ returns -1 in C

Why would F_GETPIPE_SZ return -1? It sounds like an error, but I can't find any mention of what error it is, or, more importantly, what I'm supposed to do to not get the error.

I'm running Raspbian on a Raspberry Pi, for what it's worth. I haven't tried the code on my desktop Debian yet. As far as I can tell, I'm following the textbook F_GETPIPE_SZ example. Am I missing something?

#define _GNU_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char **argv)
{
  int fd, pipesize;
  fd = mkfifo("/tmp/audio-fifo",0666);
  //  fcntl(fd, F_SETPIPE_SZ, 4096);
  pipesize = fcntl(fd, F_GETPIPE_SZ);
  printf("Pipe size: %dn", pipesize);
  return 0;
}

Clang static analyzer can't find stdio.h

I'm trying to use Clang static analyzer on a very simple program:

#include <stdio.h>
main ()
{
    printf("Hello, world !");
}

When i do

clang helloworld.c

It compiles the program successfully.


When i do

clang -cc1 -analyze -analyzer-checker=unix helloworld.c

it raises an error:

helloworld.c:1:10: fatal error: 'stdio.h' file not found
#include <stdio.h>
         ^
1 error generated.

clang --analyze -Xanalyzer -analyzer-checker=unix helloworld.c

doesn't print anything.


What is the problem and how can i fix it? I assume static analyzer doesn't see the header files though the compiler can use them. Please, help me.

Pass a input value with url in php

I want to pass a input value with a url.

<div class="modal-body">
    <div id="myDiv" class="answer_list">
        <form action="" id="usrform" method="get">
            <textarea name="comment" style="width: 450px; height: 80px; form="usrform"></textarea>

   <?php echo '<a href="reject_request.php?leave_id='.$id1.'&emp_id='.$emp_id.'">'?>
   <button style="float: right" type="button"  class="btn btn-primary" name="submit">
        Proceed
    </button></a></form></div>
</div>

Here I want to pass the textarea input value to 'reject_request.php' page with other variables. I couldn't able to find a way, Can any one help me !

To Display Excel Spreadsheet with Charts on Websites

Is there anyway to display Excel Spreadsheet with charts (Live, does not need to be editable) on Websites?

Currently I have some Excel reports with charts. I am building a website to display these spreadsheet data. The spreadsheet doesn't need to be editable. But I want it to be displayed right away, instead of a link downloading it locally every time and open it.

Is there anyway easy way I can do this?

Some methods that I have researched but would not work in my case:

  1. Google Doc

  2. Saving as html output in excel (I want it to be automatically. All the spreadsheet generation/ HTML code creation would be in linux)

  3. Sharepoint

Thanks!

C - generic function: swap two items in array

My problem: I would like to create function that can swap any two items in array of generic type.

I have SwapG function that can swap two items of any type:

void SwapG(void * a, void * b, size_t size)
{
    void * temp = malloc(size);
    memcpy(temp, a, size);
    memcpy(a, b, size);
    memcpy(b, temp, size);
}

Here is my attempt of function that would swap two items in array of any type:

void SwapInArrayG(void ** arr, int a, int b, size_t size)
{
    void * temp = malloc(size);
    memcpy(temp, *(arr + a), size);
    memcpy(*(arr + a), *(arr + b), size);
    memcpy(*(arr + b), temp, size);
}

I'm pretty sure I messed the pointers up, still I can't find solution. I would appreciate any help :).

Copy pointer to struct to new pointer to copy of the struct in in C

i have this case where i want to store pointers to structs in some hash table (linked list ) i have :

struct Base {
 int age;
};

struct Base *l1 = malloc(sizeof(struct Base )); 
l1->age = 20;

now here i stuck somewhere in the code (deep down) i have function which gives me the pointer to Base

callback_(struct Base *l)
{

i don't want to point to l1 which will be gone when the callback ends i want to create new pointer to base which the values of the l1 (age)

struct Base  *l2 = ???;

do i need to copy each value ? (deep copy ) in realty there are many members and allot of data so i need something better then deep copy

How do I build a delay-loaded libxml2 implementation without a xmlFree error?

So building off my last question, I'm receiving the error message:

LINK : fatal error LNK1194: cannot delay-load 'libxml2.dll' due to import of data symbol '__imp__xmlFree'; link without /DELAYLOAD:libxml2.dll

Which is, to my understanding, happening because libxml2 defines and undefines xmlFree:

globals.h
XMLPUBVAR xmlFreeFunc xmlFree;
#undef  xmlFree

...

xmlFreeFunc xmlFree;

#ifdef LIBXML_THREAD_ENABLED
XMLPUBFUN  xmlFreeFunc * XMLCALL __xmlFree(void);
#define xmlFree 
(*(__xmlFree()))
#else
XMLPUBVAR xmlFreeFunc xmlFree;
#endif

How do I fix my code so that I can delay-load libxml2 while still deallocating memory (if I comment out just the xmlFree line, my code works fine)?

test store method in Laravel

I am trying to test the store method in the simplest way possible. I don't necessarily need Mockery, I'm fine with actually adding to the database. I couldn't get Mockery to work anyway.

Now I have this:

public function testStore()
{
    $data = ['name' => 'TestClub', 'code' => 'TCL'];
    Input::replace($data);
    $this->route('POST', 'clubs.store', $Input::all());
    $this->assertResponseOk();
}

This is my controller method:

public function store() {
    $validator = Validator::make($data = Input::all(), Club::$rules);
    if ($validator->fails()) {
        return Redirect::back()->withErrors($validator)->withInput();
    }
    Club::create($data);
    return redirect(Session::get('backUrl'));
}

I get a return code 500, I have no idea why. Can I somehow see the request it's sending?

I am using Laravel 5.0

Firebase Date storage goes wrong

So I am trying to store a date in Firebase like this:

 var fb = new Firebase(FIREBASE_URL);
        var syncData = $firebase(fb);
        var date = new Date(2014, 0, 1);
        console.log(date);
        syncData.$child('date').$set(date);
        var dateInFirebase = syncData.$child('date');
        dateInFirebase.$on('loaded', function(){
            console.log(dateInFirebase.$value);
        });

The first date correctly logs 'Wed Jan 01 2014 00:00:00 GMT+0100 (CET)', however the second log is this: '2013-12-31T23:00:00.000Z' which is 1 day before that, is this some bug in firebase or am I missing something obvious? I haven't found any other questions on this so I'm inclined to think I did something wrong, I just don't know what.

EDIT: Okay now I'm totally confused, if I replace the dateconstructor with the empty constructor (today's date) he stores the date correctly..

Adding play buttons for all audio tags on a page

I want to add a play button for each audio file on a page. Therefore I added a button with an indexed classname under each audio-tag, but now I don't know how to proceed and bind the click event to the buttons. Maybe there's a much more elegant approach in general …

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<audio id="myaudio" src="http://www.soundjay.com//mechanical/gun-cocking-01.mp3">
</audio>

<audio id="myaudio" src="http://www.soundjay.com//mechanical/gun-cocking-02.mp3">
</audio>
$( "audio" ).each(function( index ) {
   $( '<button class=audioButton"' + index + '">Play Clip #' + index + '</button>' ).insertAfter( this );
});

$("button").on("click", playTest);

jQuery returns object with length attribute undefined

I was checking if some elements exist with:

if ($(selector).length > 0){
....
}

However, sometimes the returned object (even if the element exists in the DOM and has returned) does not have the length attribute so this never evaluates to true. This error appears in chrome. Do you have any idea what the problem might be?

Edit: I use this code:

var variable;
for(let elem in selectors){ 
    if($(elem).length > 0){
      variable = true;
      break;
    }
    else
      variable = false;
  }

Given a list of selectors, variable is true if at least one of the selectors exists. This is inside a google chrome extension's content script. After this code runs in the plugin I get the same problem even in the console of google chrome.

How to sort associative array with specified sequence of values?

I want to sort associative array with specified sequence of values

$arr=array(array("company"=>"A", "revenue_range"=>"10-100M"),
      array("company"=>"B", "revenue_range"=>"0-10M"),
      array("company"=>"C", "revenue_range"=>"10-100M"),
      array("company"=>"D", "revenue_range"=>"100M-1B"),
      array("company"=>"E", "revenue_range"=>">1B"),
     array( "company"=>"F", "revenue_range"=>"0-10M")

);

Result:-

$arr=array(array("company"=>"B", "revenue_range"=>"0-10M"),
       array( "company"=>"F", "revenue_range"=>"0-10M"),
      array("company"=>"A", "revenue_range"=>"10-100M"),
      array("company"=>"C", "revenue_range"=>"10-100M"),
      array("company"=>"D", "revenue_range"=>"100M-1B"),
      array("company"=>"E", "revenue_range"=>">1B"));

Woocommerce - Need to send email to specific address based on zip code

Basically, in woocommerce you have the option to input multiple email addresses (separated by commas) of who to send the completed order to, in WooCommerce -> Settings -> Emails -> New order. But I need a way to send to only one of these recipients based on the zip code of the customer who is ordering the product. Or completely overwrite woocommerce's way of handling this.

How can I tie into the function responsible for this, in order to send to the correct recipient? Basically, is there a hook defined for this, or does a plugin exist for something like this, or will I have to edit core WooCommerce files? If edits are needed to core files, can someone point me in the right direction as to which files will need edits?

Best Practice of using Promise with Mongoose

I'm quite new with this promise concept. I'm not sure but looking at this, I belieave I'm just using promise as callbacks and I'm ending in a promise hell!

I've this function which is suppose to get user object from MongoUser database, update it and save it again. here's my code snippet:

var changePassword = function(data){
      return new Promise(function(fulfill, reject){
        MongoUser.findOne({username: data.username}).exec()
          .then(function(mongoUser){
            mongoUser = new MongoUser();
            mongoUser.username = data.username;
            mongoUser.password = data.password;
            mongoUser.save().then(function(){
              fulfill(data);
            }).catch(function(error){
              log.error("MongoDB Failed in updating data", {"error": error});
              reject(error);
            });
          })
          .catch(function(error){
            log.error("MongoDB Failed in updating data", {"error": error});
            reject(error);
          });
      });
};

Any Idea how to use returned promise from Mongoose without creating a new one?

Is unreferenced blob automatically collected by GC in firebird?

By unreferenced I mean it's not inserted to a table as a column in a row. So after calling isc_create_blob2 to create a blob I don't insert the blobId to a table. Instead I simply call isc_close_blob to close the handle.

If the answer is yes then what would happen if I don't even call isc_close_blob? The api guide says you should call isc_cancel_blob in this case or the storage space allocated for the blob will remain in the database but it doesn't explicitly clarify whether it's just temporarily kept in the database until the program that called isc_create_blob2 exits and will be collected by then or it's really stuck in the database forever.

Why am I getting a segmentation fault in my LinkedList insertion method in C

The segmentation fault occurs at the line "else if(head -> next == NULL){". I feel like I'm missing something fundamental about pointers.

Here is the code.

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

typedef struct Node{
    int value;
    struct Node* next;
}Node;

void insert(Node* head, int value){
    if(head == NULL){
        head = (Node*)malloc(sizeof(struct Node));
        head -> value = value;
        head -> next = NULL;
    }else if(head -> next == NULL){
        printf("goodn");
        head -> next = (Node*)malloc(sizeof(struct Node));
        head -> next -> value = value;
        head -> next -> next = NULL;
    }else{
        insert(head -> next, value);
    }
}

int main(){
    struct Node* head;
    head = NULL;
    insert(head, 3);
    insert(head, 4);
    printf("%dn", head -> value);
    return 0;
}

How 'heavy' is it on the server to run mysql commands every few seconds

I have a set of data that is used by GUI for positions and stuff, and that positions are also stored in MySQL. Every time the data changes, it is reflected on the server too.

Then if I want to update MySQL as frequent as jquery (or javascript, I don't know) tracking "mousemove" motion, that is, send request to the server that for every "mousemove" change the value in MySQL, how 'heavy' is it, especially when multiple users are using the same server?

What would be a better solution? I'm thinking of waiting for 3 seconds until the motion is finished, then if there is no more motions, sending request to the server then.

Although multiple people aren't using my server, but this always concerns me and hinders me from progressing. Please help.

Count the same numbers in rows and columns php mysql

I have MySql table like this :

+----+----+----+
| g1 | g2 | g3 |
+----+----+----+
| 1  | 2  | 5  |
+----+----+----+
| 5  | 1  | 3  |
+----+----+----+
| 1  | 3  | 4  |
+----+----+----+

And I need get output in PHP like:

number 1 is used 4 times
number 2 is used 1 time
number 3 is used 2 times

I make some code but it only write me how many time I used the number and I don't know how to add whitch number. Thi is my code:

for ( $i=1 ; $i<=20; $i++){

            $query = mysql_query("SELECT g1, g2, g3d FROM users 
            WHERE g1 = $i OR g2 = $i OR g3 = $i ") or die(mysql_error()) ;

            $row1 = mysql_num_rows($query);

        $row = mysql_fetch_array($query)    ;
            if ($row1 >=1){echo $row1; }
        }

Thanks for any help.

samedi 30 juillet 2016

How to enable PHP redis extension on Travis

I'm running Travis CI for running my tests. I'm using the Trusty container with php v5.6.

Here is my entire .travis.yml file:

language: php

dist: trusty

php:
  - '5.4'

before_script:
  - phpenv config-rm xdebug.ini
  - before_script: echo "extension = redis.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini

sudo: required

install:
  - npm install -g gulp
  - composer install

env:
  - APP_ENV=circleci

script:
  - gulp test

The before_script: syntax is copied directly from the travis documentation but my builds fail with a composer error saying:

- The requested PHP extension ext-redis * is missing from your system. Install or enable PHP's redis extension.

Swig: pass byte array in Java to C

I am trying to create Java implementation for passing byte [] to C using Swig.

Swig:

%include "typemaps.i"
%apply(char *STRING, int LENGTH) { (char *buff, int len) }; 
%inline {
   typedef struct {
        char*         buff;        
        int           len;  
  } workit_t;
}

In my generated java class (workit_t.java), the parameter buff is a String, instead of a byte [].

Java:

public void setBuff(String value){
 ... 
}

What am I doing wrong in my swig definition?

When I write a simple swig definition with no struct, I get the desired type of parameter.

Swig:

%include "typemaps.i"
%apply(char *STRING, int LENGTH) { (char *buff1, int *len1) };

Java:

public static void Mathit(byte[] buff1, byte[] buff2) {
...
}

Travis-Ci not following PSR-4

I am trying to learn how to use Travis-CI. My first attempt is not going well.

I have a project at https://github.com/RogerCreasy/simpleJWT

Here is my .travis.yaml

language: php
php:
  - '5.4'
  - '5.5'
  - '5.6'
  - '7.0'

before_script:
  - composer self-update
  - composer install --prefer-source --no-interaction --dev

script: vendor/bin/phpunit --configuration phpunit.xml

I am using PSR-4 autoloading in my composer.json file.

 "autoload": {
 "psr-4": {
   "RogerCreasy\SimpleJWT\": "src"
   }
 },

PHPUnit tests run successfully locally. But, through Travis they fail. Travis looks for the class I am testing at the full namespace (/RogerCreasy/SimpleJWT/)

Where should I look for the problem?

Matching both preg_matches in an if statement

I have 2 preg_match in an if statement, and if either of them are true, I want to print_r both of them. But for some reason, only the first preg_match is being matched each time, even though both of them has the same pattern. Why is this happening?

<?php

$string = "how much is it?";
if (preg_match("~b(how (much|many))b~", $string, $match1) || preg_match("~b(how (much|many))b~", $string, $match2)) {
print_r($match1);
print_r($match2);   
}

?>

Result:

Array ( [0] => how much [1] => how much [2] => much )

Expected Result:

Array ( [0] => how much [1] => how much [2] => much )
Array ( [0] => how much [1] => how much [2] => much )

Socket.io create a separate event handler file

I have crated a socket connection, and at the moment I am looking to just clean up and make everything well organized.

Here is a image of my current file structure FILE STRUCTURE

So what I am wanting to do is take

socket.on("send message", function(data){
    io.sockets.emit("new message", data);
});

and put it in the file called socketEvents.js which is located in main --> js.

However I am not 100% sure on how to include that file on successful connection. I have tried using something like require(); but to no avail. Is there a standard method of including a separate file to run events? Or is it not good practice?

why recvfrom() still block when a SIGALRM has been captured?

I want to use alarm() to set the timeout of recvfrom. But found that when use signal() to register a handler for SIGALRM, and a SIGALRM has been captured and then invoked the signal handler. But after returned from handler, the recvfrom() still blocks while there is no data coming and there is no EINTR error. Why? Does the signal() set the SA_RESTART flag automatically? Here is the code:

signal(SIGALRM, sig_handler);
while(1)
{
    alarm(5);
    n = recvfrom(sock, buf, BUF_MAX, 0, (struct sockaddr*)&addr, &len);
    if(n < 0)
    {
        if(errno == EINTR)
        {
            printf("recvfrom timeoutn");
            continue;
        }
        else
        {
            printf("recvfrom errorn");
        }
    }
    else
    {
         printf("data: %sn", buf);
         alarm(0);
    }
}

void sig_handler(int signo)
{
    return;
}

Fix the white blank page after form is processed

Here is a PHP script i wrote just so i can get information sent to me from my portfolio. For some reason its not showing the end script echo's. displays a white page and no email is being sent? I looked around and didn't see anything.

    <?php
$name = $_POST['c_name'];
$email = $_POST['c_email'];
$ref = $_POST['c_ref'];
$message = $_POST['c_message'];
$submit = $POST['f_submit'];

$from = 'From: Portfolio';
$to = 'user@email.com';
$subject = 'Website Request';

$body = "Name: $namen
         Email: $emailn
         Reference: $refn
         Message: $messagen";

if ($_POST['f_submit']) {
        if ($name != '' && $email != '') {
                if (mail ($to, $subject, $body, $from)) {
                    echo "Thank you for your quote we will be contacting you within 24 hours!";
                }else{
                    echo "Unfortunatley something went wrong try entering your information one more time.";
                }
        }
}


?>

Function that only works if you pass in a NULL pointer? [on hold]

This is all the SDK documentation that I was given, which really isn't much.

DESCRIPTION - Connects to the bus with the given 'name'.

typedef void* BusId
Bus_Connect(BusId *bus, char *name, int port);

The API function call will only work properly if I pass in a NULL pointer.

int result;
BusId busName = 0;    //connection error if just BusId busName;
char *testName = "A";
int port = 1;

result = Bus_Connect(&busName, testName, port);   

I thought maybe the function is doing a NULL check, but that would mean it would error if you passed in a NULL. But this is the reverse case, where it only works when the pointer is NULL.

Any ideas why this is?

laravel get all hours where value exits or not

here is my laravel DB query

DB::table ( 'zee_hours' )
->select (
    [
        'zee_hours.hours',
        DB::raw ( 'COALESCE(count(zee_shipment_events.amazon_order_id),0)' ),
    ] )
->leftJoin ( 'zee_shipment_events', 'zee_hours.hours', '=', DB::raw ( 'HOUR(zee_shipment_events.pdate)' ) )
->join ( 'zee_shipment_items', 'zee_shipment_items.shipment_id', '=', 'zee_shipment_events.id' )
->join ( 'zee_promotions', 'zee_promotions.shipment_item_id', '=', 'zee_shipment_items.id' )

->groupBy ( 'zee_hours.hours' )
->get ();

Problem this way, I am only able to get those hours where some order was placed.

what I want is, I need even those hours where no order was placed (showing 0 with them)

Have tried hard, but still, no way

Checking only the O_RDONLY flag to open(2)

I'm checking the flags sent to the open(2) call against permissions I've set up in some meta files. The perms here are related to the octal values typically sent to calls like chmod. I want the if block to be entered when perms is not matched by the relevant flag.

if((perms == 4 && !(flags & O_RDONLY)) ||
   (perms == 2 && !(flags & O_WRONLY)) ||
   (perms == 6 && !(flags & O_RDWR))) 

I expected this to work, and it does just fine in the the O_WRONLY and O_RDWR. However, the actual value of O_RDONLY is 0, so the & operator will return false for every value. Unfortunately, removing the negation will lead to the undesired behavior of every perms value of 4 skipping the if block. How can I achieve my goal here?

Mysql Two tables mixed data

I have two tables:

table1:

ID| Name
1 | firstname1
2 | firstname2
3 | firstname3

table2:

ID| Name
1 | lastname1
2 | lastname2
3 | lastname3

And i want insert combination table1 and table2 to table3 example: table3:

ID| Fullname
1 | firstname1-lastname1
2 | firstname1-lastname2
3 | firstname1-lastname3
4 | firstname2-lastname1
5 | firstname2-lastname2
6 | firstname2-lastname3
7 | firstname3-lastname1
8 | firstname3-lastname2
9 | firstname3-lastname3

A try in php (pdo) but is very slow... i must create 10 000 000 records (after combination)

my php:

<?php
//get firstnames, get lastnames before and...
foreach ($firstnames as $firstname) {
    foreach ($lastnames as $lastname) {
        $this->pdo->prepare("INSERT INTO `table3` (`fullname`) VALUES(?)")->execute([$firstname['name'] . '-' . $lastname['name']]);
    }
}

Soo, how i can create a query that mix data?

Thans

Laravel 5.1 Session not working outside Route::get

I have some code like this and working:

Route::get('addnew',function(){         
        $user = Users::where('username','=',session('username'))->first();
        $data = $user->toArray();
        return view('layout.addnew')->with($data);
    });
Route::post('addnew', ['uses'=>'UsersController@addnew']);

With code above: session('username') not null

But, when i use this code like below:

$user = Users::where('username','=',session('username'))->first();
$data = $user->toArray();
Route::get('addnew',function() use($data){
        return view('layout.addnew')->with($data);
    });
Route::post('addnew', ['uses'=>'UsersController@addnew']);

With code above: session('username') null => so $data is non-object and code not working.

Somebody help me, please!

Thank you very much!

Warning when using qsort in C

I wrote my comparison function

int cmp(const int * a,const int * b)
 {
   if (*a==*b)
   return 0;
else
  if (*a < *b)
    return -1;
else
    return 1;
}

and i have my declaration

int cmp (const int * value1,const int * value2);

and I'm calling qsort in my program like so

qsort(currentCases,round,sizeof(int),cmp);

when i compile it I get the following warning

warning: passing argument 4 of ‘qsort’ from incompatible pointer type
/usr/include/stdlib.h:710: note: expected ‘__compar_fn_t’ but argument is of type ‘int
(*)(const int *, const int *)’

The program works just fine so my only concern is why it doesn't like the way im using that?

ServiceM8 create new job via API

I'm sending the following JSON to the SM8 API https://api.servicem8.com/api_1.0/job.json

The response I am getting is 200 OK, & the job is being created in my servicem8 dashboard, but the name and description fields are not being populated for some reason.

Also, I was hoping to capture the newly created job ID from the response object, but it is either not being returned or I am unsure how to access it.

Here's the JSON that I'm passing to the API:

{
    "status":"Quote",
    "job_address":"123 Street Lane, , London, SE2",
    "description":"Remove & replace existing carpets",
    "contact_first":"Joe",
    "contact_last":"Bloggs"
}

Anyone see what the problem is?

Cheers

Basic 2D pole-balancing setup in Phaser (Box2D)

Ignoring the task of actually balancing a pole by providing the appropriate forces at the appropriate times (that part's fine), does anyone have some basic guidance on how to setup the task of pole-balancing in Phaser? I have the Phaser-based Box2D plugin as well, if that makes it easier.

Basically I'm looking for the type of objects to create (e.g., bodies, joints), the creation/initialization process, and the process of applying forces in either direction. Doesn't matter to me that those forces are incorrect initially, I'm just not sure how to build the scene I want within Phaser.

I get the impression such things should be quite simple to do in Phaser, but it doesn't feel that way to me at present.

main(int argc, char *argv[]) [duplicate]

Possible Duplicates:
What are the arguments to main() for?
What does int argc, char *argv[] mean?

Every program is starts with main(int argc, char *argv[]) definition . I don't understand what it means. I would be very glad if somebody could explain why we use these arguments if we dont use them in the program? Why not just: int main()?

EDIT:

The name of the program is one of the elements of *argv[] and argc is the count of the number of arguments in *argv[]? What are the other arguments sent to *argv[]? How do we send them?

Can't override _renderItem function in jQuery UI autocomplete

I'm trying to display images with labels in jQuery UI Autocomplete. I got stuck at the error "jquery-ui.js:6853 Uncaught TypeError: Cannot read property 'value' of undefined". However, during my investigation, it turned out that the problem is in overriding _renderItem function - whatever I do in its overriden implementation I see the same error, even if I define it by just copying code from jQuery UI source code. I tried jQuery UI versions 1.10.4 1.11.4 and 1.10.2 and problem still exists. I think that I've already tried almost everything, even making really silly versions of autocomplete, but still every time I do something with _renderItem implementation, the error occurs.

According to source code of jQuery UI, the reason of this error is lack of 'ui-autocomplete-item' data, but I do send it, so I've got no idea what I'm doing wrong.

PHP - Numbers, number digit

i have a question about numbers in php.

Example i have this numbers

1111122333344

I want to show that number one have five digits, number two have two digits and number three have four digits and for have two digits. I want to seperate it. But how can i do that? Thank you for help. Here is example:

Number that i have 1111122333344
number 1 have = 5 (digits)
number 2 have = 2 (digits)
number 3 have = 4 (digits)
number 4 have = 2 (digits)

I have tried this and its not working

$numbers = '1111122333344';
if ($numbers > 3) {
echo '2';
}

(Sry for bad eng) Thank you!

WooCommerce: Assigning an endpoint to a custom template

This function adds a tab named "Special Page" into "My Account" tab list:

add_filter( 'woocommerce_account_menu_items' , 'jc_menu_panel_nav' );

function jc_menu_panel_nav() {
    $items = array(
        'dashboard'       => __( 'Dashboard', 'woocommerce' ),
        'orders'          => __( 'Orders', 'woocommerce' ),
        'downloads'       => __( 'Downloads', 'woocommerce' ),
        'edit-address'    => __( 'Addresses', 'woocommerce' ),
        'payment-methods' => __( 'Payment Methods', 'woocommerce' ),
        'edit-account'    => __( 'Account Details', 'woocommerce' ),
        'special-page' => __( 'Special Page', 'woocommerce' ), // My custom tab here
        'customer-logout' => __( 'Logout', 'woocommerce' ),
    );

    return $items;
}

That results in this:

enter image description here

But the link points to my-account/special-page/, and naturally gives a 404 error.

How I can assign this URL to a file named special-page.php?

Start windows 10 App from my website

This will require some outside the box thinking for sure.

I have a windows 10 photo booth app called "Instant Photo Booth 3" installed on my computer. My goal is to open this app from my Wix website. This is not a public website, but will always be run on the same computer so the app will be installed.

I almost got it working by using the Apps protocol URL Name as a hyperlink on my website as shown below.I got that info from windows 10... DEFAULT PROGRAMS > APPS BY PROTOCOL

here

This opens the app, but the app never completely loads so it somehow doesn't like being opened like this. but if I double click the app on my windows desktop it loads fine.

Please, can I have some ideas. Thanks

C/C++ Inline asm improper operand type

I have the following code, that is supposed to XOR a block of memory:

void XorBlock(DWORD dwStartAddress, DWORD dwSize, DWORD dwsKey)
{
DWORD dwKey;
__asm
{
    push eax
    push ecx
    mov ecx, dwStartAddress          // Move Start Address to ECX
    add ecx, dwSize                  // Add the size of the function to ECX
    mov eax, dwStartAddress          // Copy the Start Address to EAX

    crypt_loop:                         // Start of the loop
        xor byte ptr ds:[eax], dwKey     // XOR The current byte with 0x4D
        inc eax                         // Increment EAX with dwStartAddress++
        cmp eax,ecx                     // Check if every byte is XORed
    jl crypt_loop;                      // Else jump back to the start label

    pop ecx // pop ECX from stack
    pop eax // pop EAX from stack
}
}

However, the argument dwKey gives me an error. The code works perfectly if for example the dwKey is replaced by 0x5D.

Get css value with pixels

How can I get element width or height value which would be translated as a pixel number? All I got by using .css('width') are the expressions, not even a percentage number, like calc(-25px + 50%).

Edit

my code here. (Chrome)

var bars_width = element.css('width');
$('.histgram-content').css('width', bars_width);
bars_width = parseInt(bars_width.replace('px', '')) * 0.85;
$('.histgram-bar').css('width', (bars_width/data.length).toFixed(0).toString() + 'px');
/*** average Y ***/
var graph_height = $('.histgram-graph').css('height');
graph_height = parseInt(graph_height.replace('px', ''));

var average_height = $('.average-line').css('top');
average_height = graph_height - parseInt(average_height.replace('px', ''));

The average_height returns the expression I said. The last line got the result of 'NaN'.

Cannot send data using form from index.php

I've run in to a small problem and I hope someone can help me out.

I made a form and it works fine:

http://www.volunteeringnews.com/formorg.php

If I hit send it returns a message saying User has been created.

So that works but if I go to http://www.volunteeringnews.com/ and under "Organisations" I click Submit it doens't work. And the Submit button is justa link to formorg.php.

I tried adding this to index.php but that was no success.

$action = isset($_POST['action']) ? $_POST['action'] : "";

//include database connection
include 'mysqli.php';

Can someone have a look?

Thanks!

Duplicating epoll file descriptor

Is there a way to duplicate a file descriptor created using epoll_create, in such a way that the copy can be modified (adding/removing watched file descriptors using epoll_ctl) independently.

E.g. I create an epoll file descriptor A which waits for events on the files P and Q. The I copy it to epoll file descriptor B, and make B also waits for events on file R. Calling epoll_wait(A) will still only wait for P and Q.

Is this the behavior when calling dup on A, or is it needed to recreate the epoll file descriptor using epoll_create and epoll_ctl?

vendredi 29 juillet 2016

Xampp - Ubuntu - cant access my project in lampp/htdocs

I have installed xampp to Ubuntu 12.04. I have put my project in the folder /opt/lampp/htdocs/project_is_here

When I type in the browser localhost/soap/php (soap/php is in my htdocs folder) which is where index.php I get the following error:

Access forbidden!

You don't have permission to access the requested directory. There is either no index document or the directory is read-protected.

If you think this is a server error, please contact the webmaster.

Error 403

localhost
Apache/2.4.3 (Unix) OpenSSL/1.0.1c PHP/5.4.7

Any ideas how to fix this? I think this is the right location to put the project, because I tried other places and it said location didnt exist and this error goes away here and I get this.

Any ideas?

How to get rid of use-strict warning when using webpack and jshint-loader?

I have a webpack project wired with the jshint-loader which is defined like so:

postLoaders: [
       {
           test: /.js$/,
           exclude: /node_modules/,
           loader: 'jshint-loader'
       }
],

and when I run webpack-dev-server I get the following warning in all of my files:

WARNING in ./js/main.js jshint results in errors Use the function form of "use strict". @ line 1 char 1 "use strict";

I tried using the "strict": false option in my config file under jshint but it did not help.

Adding 'use strict' in the files also did not help.

The only solution that I found was adding /*jshint globalstrict: true*/ in each js file in my project...

Does someone have a solution for it in the global scope?

Thanks.

Html&Javascript Audio Play&Stop Button

<!DOCTYPE html> 
<html> 
<body> 

<img id="myImage" onclick="aud_play_pause()" src="../../images/off.png" alt=""/>

<audio id="myAudio">
</audio>

<script>
    function aud_play_pause()
    {
        var song = ["../Sesler/3.mp3"];
        var myAudio = document.getElementById("myAudio");
        var image = document.getElementById('myImage');
        myAudio.src = song;
        if (myAudio.paused)
        {
            image.src = "../../images/on.png";
            myAudio.play();
        }
        else if(image.src.match("on"))
        {
            image.src = "../../images/off.png";
            myAudio.pause();
        }
    }
</script>

</body> 
</html>

Hi,

I couldn't understand why it doesn't work. It is suppose to start when I click (it starts) and it is suppose to pouse when I click again (it doesn't). I think the "else if" statement doesn't work but why?

Thanks,

H. Caglar

fatal error - cannot connect to database

I'm trying to create a simple php blog and downloaded demo files from here - https://daveismyname.com/creating-a-blog-from-scratch-with-php-bp.

Creating database (named blog01) and tables was sucessful.

On index.php I have an error:
Fatal error: Uncaught exception 'PDOException' with message ' in D:localhostblog-01includesconfig.php on line 11

config.php:

define('DBHOST','localhost');
define('DBUSER','username');
define('DBPASS','password');
define('DBNAME','blog01');

$db = new PDO("mysql:host=".DBHOST.";port=8889;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

I tried all combinations of username and password (demo, admin...) without success.

Also tried without port=8889.

php version - 5.6.14

Any help.

Embed a Blob using PDFObject

I´m using: https://pdfobject.com/

To display an embedded pdf file on my web app. However I cannot render a pdf created from a blob. This is what I´ve tried:

      var arrayBufferView = new Uint8Array(response.Body.data);
      var file = new Blob( [arrayBufferView], {type: response.ContentType});
      var url = window.URL.createObjectURL(file)
      PDFObject.embed(url, "#my-container");

Gets me this result on html:

<div id="my-container" class="ng-scope pdfobject-container">

    <embed class="pdfobject" src="blob:http%3A//localhost%3A4000/869a8d9a-7eaa-48dd-99aa-49bf299114aa" type="application/pdf" style="overflow: auto; width: 100%; height: 100%;" internalinstanceid="88">

</div>

However the embed container displays nothing in my browser. I´m using Chrome 51.0.2704.103 m

Tag posts in Wordpress (if you only know the post slugs)

I have a list of post-slugs retrieved from Google Analytics (1000+) and I want to tag those posts with specific tag in bulk in Wordpress. They're too many posts to do this manually from the dash.

I was trying to get a post by its slug and then for each post to add the specific tag using the wp_set_post_tags function, but it seems the argument 'name' doesn't allow adding slugs in an array.

'name' => array('slug_1', 'slug_2', 'slug_etc');

I can't get it working, and I'm pretty sure this should be a fairly simple task.

button click, adds some text and number to a div. Doesn't work

I really need some help to create this order list. It's the mening that, when you click on the button it adds the text inside the addToList, to the div, so it shows up on the page. It should add the data (name, price), in javascript. But can't get it to work properly.

<html>
 <body>
    <div id="myList">

    </div>

    <button onclick="addToList('donut', '25,-')">add</button>
 </body>
</html>




    <style>
    #myList {
        border: 1px solid black;
        margin-bottom: 10px;
    }
    </style>





    <script>
    function displayListCart() {
        var myList = document.getElementById("myList");
    };



    function addToList(name,price) {
      var itemOrder = {};
      //itemOrder with data
      itemOrder.Name=name;
      itemOrder.Price=price;
      //Add newly created product to our shopping cart 
      listCart.push(itemOrder);
      displayListCart();
    }
    </script>

Deeply assign JavaScript object literal

I am trying to deeply assign a value in an object. For example:

const errors = {}
if(errorOnSpecificField) {
  // TypeError: Cannot read property 'subSubCategory' of undefined(…)
  errors.subCategory.subSubCategory.fieldWithError = 'Error Message'
}

Right now, without lodash, I can do:

const errors = {}
if(errorOnSpecificField) {
    errors.subCategory = errors.SubCategory || {}
    errors.subCategory.subSubCategory = errors.SubCategory.subSubCategory || {}
    errors.subCategory.subSubCategory.fieldWithError = 'Error Message'
}

With lodash, I can do this:

const errors = {}
if(errorOnSpecificField) {
    _.set(errors, 'subCategory.subSubCategory.fieldWithError', 'Error Message');
}

I am trying to avoid using a third party library. Is there a more elegant solution, especially now that es2015 has object destructuring. The inverse operation is easy:

  let {subCategory : {subSubCategory: {fieldWithError}}} = errors

What is an elegant solution to deep object assignment? Thanks!

Performance fact of using multiple loops(not nested) / single loop for the same dataset

For exporting data as pdf, i need to query a dataset from the database and then loop through it to manage indexes and then export as pdf. When querying, the dataset can be manipulated in different ways with the use of joins and other mechanism. The confusion is, depending on the structure of the dataset, it can be done within a single loop and it may be done with multiple loops(not nested). What is the performance effect of these two ways.

For example: dataset contains "organizations" and its "inquries"."inquiries" has different types. In this condition, I can query to retrieve dataset as whole and use one loop to go through it or retrieve dataset as sections and then use multiple loops to go through.

What is the performance fact of these two scenarios. Thanks in advance

Is it possible to use PassportJS without a local database?

I have an app that uses all of the oAuth authentications that are bundled with passport, but I'm using an external service for my database / user creation.

If I do something like this:

passport.use('local-signup', new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true        },
    function(req, username, password, done) {

        request.post('http://myapiservice.com/createuser').then(function(err,  response, body){
          return done(err, body.user); 
       })

    }))

How would I use a remotely-stored user with this? I'm not connecting to the database in any way other than a POST API call to create the user and a GET call to retrieve the user, so I'm not sure how Express' req.user would behave / get updated.

Can't find a single guide or question about this elsewhere so would love a bit of guidance!

If I set signal(SIGCHLD, SIG_IGN); to avoid zombies - system() returns -1 and "No child processes"

I have a simple server which does fork for a new socket connection. If I set signal(SIGCHLD, SIG_IGN); to avoid zombies when I call system() in child process to execute needed script - everything is executed fine but seems like child gets removed from table of processes before it exited, so it's strange. Here is the example of output:

server started. version 0.20
opening socket 
binding 
listening 
parent process does nothing
client message: print.php
executing php script: "print.php" 
full command line of execution: "php print.php" <-- we call system() which executes php script on server
Hello, World!                      <-- this is output of php script
return value from script execution: -1      <-- should be ok but -1 instead
system returns -1 error: No child processes
child is closing socket 

Extjs: Mask component for modal window

I need to create a modal window in the other normal window. When I create a modal window is blocked mask.

Ext.application({
name : 'Fiddle',

launch : function() {
    var win2 = null;

    var win1 = Ext.create('Ext.window.Window', {
        closeAction: 'hide',
        width: 500,
        height: 500,
        resizable: false,
        titleAlign: 'center',
        items: {
            xtype: 'button',
            text: 'show modal',
            handler: function() {win2.show()}
        },
        title: 'Simple window'
    });

    Ext.create('Ext.panel.Panel', {
        items: {
            xtype: 'button',
            text: 'show window',
            handler: function() {
                var isRendered = win1.rendered;
                win1.show(null, function() {
                    if (!isRendered) {
                        win2 = Ext.create('Ext.window.Window', {
                            closeAction: 'hide',
                            resizable: false,
                            titleAlign: 'center',
                            width: 200,
                            height: 200,
                            renderTo: win1.getEl(),
                            modal: true,
                            title: 'Modal window'
                        })
                    }
                });
            }
        },
        renderTo: Ext.getBody()
    });
}});

z-index is right:

  • Mask component is 19006
  • Modal window component is 19010
  • Simple window component is 19000

I don't understand where I was wrong.

call previous signal handler with raise(3) is not synchronous

My program uses a library that installs a SIGHUP handler. I need to add another handler.

I found here: http://stackoverflow.com/a/13290134/447503 a suggestion to restore the original handler and call raise() , then restore my handler.

It's considered better, because you don't need to check for three-args or one-arg version of the handler and for SIG_DFL and SIG_IGN in your code.

However, raise() returns before the original hadler is called. I restore my handler and only then my program receives the signal I just sent. So the program enters infinite loop.

PrevSigHupSignalHandler = sigset(SIGHUP,SgpCacheRefreshSignalHandler);

static void SgpCacheRefreshSignalHandler(int signo)
{
  signal(SIGHUP, PrevSigHupSignalHandler);
  raise(SIGHUP);
  /* when it returns here .. set our signal handler again */
  signal(SIGHUP, SgpCacheRefreshSignalHandler);
}

C++: Pointer Arithmetic

I was reading a bit in Pointer Arithmetic, and I came upon 2 things I couldn't understand neither know it's use

address_expression - address_expression

and also

address_expression > address_expression

Can someone please explain them to me, how do they work and when they are used.

Edit:

What I meant to say is what do they produce if I just take two addresses and subtract them

And If I take two addresses and compare them what is the result or comparing based upon

Edit: I now understand the result of subtracting addresses, but comparing addresses I still don't get it.

I understand that 1<2, but how is an address greater than another one and what are they compared upon

JSON-RPC PHP class not found error

I am using this php wrapper for multichain's json rpc api: https://github.com/Kunstmaan/libphp-multichain in a php file.

I'm not sure how I should adjust my code and I'm reluctant to adjust the libraries so I wanted to check this understanding:

<?php
   require_once 'libphp-multichain/src/be/kunstmaan/multichain/MultichainClient.php';
   require_once 'libphp-multichain/src/be/kunstmaan/multichain/MultichainHelper.php';
   $client = new MultichainClient("http://107.170.46.124:port",{usr},{pwd});
   print_r($client);

The error I see in apache error log is:

PHP Fatal error: Class 'MultichainClient' not found in /var/www/html/new.php on line 5

Previously I had the wrong question on here which was referring to a php error treating MultichainClient as a function

Testing and Production environment mixed in VPS CakePHP

I have a VPS on Godaddy with CentOs6 and I want to setup a testing environment for my project. I got myself a free domain and set it up on my VPS with no problems. I uploaded my CakePHP Project to my testing environment with my new domain, so far so good, the problems comes when I realize that my testing environment which is running on the same server with a different domain and a different account is using my Production files. If a check my APP Global Variable it returns /home/production/public_html/app/ and it should return /home/testing/public_html/app/. If I delete bootstrap.php I get an error that the file couldn't be found but if it is found the files that are used are the ones from my production environment. I hope I'd explained myself well.

Merge default with user defined settings

I'm trying to create a plugin with settings. There will be default settings, and user defined settings. I will have to somehow merge the two in an object. I tried the following:

JSFiddle

function MyPlugin(options) {
  if (typeof optoins === null || typeof options !== 'object') options = {};

  var defaults = {
      prop1: true,
      prop2: false,
      prop3: 0,
      prop4: 100,
    }
    // Set default options
  for (var name in defaults) {
    !(name in options) && (this.options[name] = defaults[name]);
  }
}
var test = new MyPlugin();

But I get an error saying:

Uncaught TypeError: Cannot set property 'prop1' of undefined

What's the correct, most efficient way to merge the default and user defined settings?

How to install LARAVEL 5

how to install laravel on hostinger server/ any other free hosting server. I had learned and done working codes in localhost. But i would like to run it on a real server.

Laravel Version : 5

PHP Version Server :5.5.35

1) I had copied the full laravel code to "/home/< username >/"

2) copied the files in /home//laravel/public to /home/< username >/public_html

But it shows an error.

Fatal error: require(): Failed opening required '/home//public_html/../bootstrap/autoload.php' (include_path='.:/opt/php-5.5/pear') in /home//public_html/index.php on line 22

Answer : Use Heroku Server as @lciamp Suggested in the comment

Clarification :

Please suggest me a list of Payed Servers which support Laravel Framework

I am getting php fetal error [duplicate]

This question already has an answer here:

Whats wrong I am doing with this code. I am getting fetal error. Please help to solve this out. I think everything is fine but its not working at all

if (!empty($_POST['pic_tobe_add'])){

  $pic_tobe_add = $_POST['pic_tobe_add'];

  if (count($pic_tobe_add)<=6); {

  $pic1 = $pic_tobe_add[0]; 
  empty($pic_tobe_add[1]) ? $pic2 = "NA" : $pic2 = $pic_tobe_add[1];
  empty($pic_tobe_add[2]) ? $pic3 = "NA" : $pic3 = $pic_tobe_add[2];
  empty($pic_tobe_add[3]) ? $pic4 = "NA" : $pic4 = $pic_tobe_add[3];
  empty($pic_tobe_add[4]) ? $pic5 = "NA" : $pic5 = $pic_tobe_add[4];
  empty($pic_tobe_add[5]) ? $pic6 = "NA" : $pic6 = $pic_tobe_add[5];

Javascript increasing a value and the velocity on increasing it

I need to increase a number and I used setInterval(Function, time) so I put a variable for time: time = 1000 now I need to change it so I put a function that changes it when I click a button:

function changetime() {time = time - 100;}

but it seems that you can't change the time of setInterval while is working... how can I do that? I tried with a setTimeout but the number now changes "jumping". is not regular... I'm not sure but it seems that the "jump" changes when I change the setTimeout time... like if the timeout is now in the setInterval time.

Original code---_>

var time = 1000;
function interval() { setInterval(Function, time);}
function changetime() {setTimeout(interval, 10);tempo = tempo - 200;}

PHP accepting json from $http.post vs $.post

I have an angular app where I setup the following json object:

var newUser = {
    username: $scope.form.username,
    password: $scope.form.password,
    userTypeId: 1,
    email: $scope.form.email
};

I then attempted to post to my php backend:

$http.post(
    ENVIRONMENT.backendUrl + '/users/add/.json?XDEBUG_SESSION_START=PHPSTORM',
    newUser
).success(function() {
    alert("success");
}).error(function() {
    alert("failure");
});

Oddly enough, none of the variables were there in the $_POST array, nor in the php://input. But when I changed the post to use jquery instead, it work:

$.post(
    ENVIRONMENT.backendUrl + '/users/add/.json?XDEBUG_SESSION_START=PHPSTORM',
    newUser
).success(function() {
    alert( "success");
}).error(function() {
    alert( "failure");
});

Any idea on why these two ways of posting cause a difference in the $_POST value?

Linux C: error of redefinition of in include headers

I have a project, which has below header include map:

main.c <- main.h <- tcphelper.h <- tcptest.h <- util.h
                 <- udptest.h    <------------- util.h

In util.h, I defined a function prototype of struct cpu_usage:

void get_cpu_usage(struct cpu_usage *cu);

Now when I compile this project by GCC, I have this redefinition error. How do solve this problem?

thanks!

In file included from udptest.h:15:0,
                 from main.h:10,
                 from main.c:7:
util.h:27:8: error: redefinition of struct cpu_usage
 struct cpu_usage{
        ^
In file included from tcptest.h:14:0,
                 from tcphelper.h:10,
                 from main.h:9,
                 from main.c:7:
util.h:27:8: note: originally defined here
 struct cpu_usage{
        ^

java script traffic light sequence timer

<!DOCTYPE html>
<html>
<body>


<img id="Change Lights" src="red.jpg" width="1500" height="800"> 

 <br><button onclick="nxt()" id="button">Change colour</button></br>

 <script>

var img = new Array("red.jpg", "amber.jpg","green.jpg");



var imgElement = document.getElementById("Change Lights");
var lights = 0;
var imgLen = img.length;

             function nxt()
        {
            if(lights < imgLen-1)
                {
                    lights++;
                }
            else{
                    lights=0;                
                }

                imgElement.src = img[lights];                    
        }



</script>
</body>
</html>

hi this is my code I'm really stuck on how to add a timer I have researched how to do a timer but I still cant figure it out,so that the traffic lights change by itself, please could you help me by giving a timer to add or complete it with a timer.

Why in the given piece of code `fgetc()` function gave proper output whereas `fscanf()` failed to do so?

The following piece of code worked :

 #include<stdio.h>
    void main()
    {
        FILE *ip, *op ;
        char ch ;
        ip = fopen ( "read.txt", "r" ) ;
        op = fopen ( "out.txt", "a" );
        while ( 1 )
        {
            ch = fgetc ( ip ) ;   //used for getting character from file read.txt
            if ( ch == EOF )
                break ;
            fprintf ( op, "%c", ch ) ;
        }
            fclose ( ip ) ;
            fclose ( op );
    }

But the following code was not giving required output as fscanf() was used :

#include<stdio.h>
void main()
{
    FILE *fp, *op ;
    char ch ;
    fp = fopen ( "read.txt", "r" ) ;
    op = fopen ( "out.txt", "a" );
    while ( 1 )
    {
        ch = fscanf ( fp, "%c", &ch ) ;  //to read the characters from read.txt
        if ( ch == EOF )
            break ;
        fprintf ( op, "%c", ch ) ;
    }
        fclose ( fp ) ;
        fclose ( op );
}

I also don't understand how the variable ch was automatically taking up the next character.

jeudi 28 juillet 2016

C# How to refresh a GridView without data binding or JavaScript?

I've asked this question before here, but it doesn't seem to gain any attention. Maybe I've not written it well.

Simply put: Is there a way to refresh/redisplay a Gridview without having to use a DataBind()?

The databind() reloads the gridview but it also wipes any data that was typed into its textboxes, dropdownlist selections, etc. Of course the way to avoid that is to save the data using the submit call and reload the new data. But that's a databind() solution.

There must be a way to refresh a GridView by simply reloading what values it has "held" in it. Maybe in ViewState[] ?? (assuming ViewState keeps all the data automatically)

My gridview sample etc are in the link above.

Thanks

Why is _LARGEFILE_SOURCE defined in stdio.h when compiling with g++ but not gcc?

If the following code is compiled with gcc lfs.c -o lfs, it prints nothing. However, if it is compiled with g++ lfs.c -o lfs, it prints "_LARGEFILE_SOURCE defined by stdio.h!".

#ifdef _LARGEFILE_SOURCE
int largefile_defined_at_start = 1;
#else
int largefile_defined_at_start = 0;
#endif

// This defines _LARGEFILE_SOURCE, but only in C++!
#include <stdio.h>

int main(void) {
#ifdef _LARGEFILE_SOURCE
  if (!largefile_defined_at_start)
    printf("_LARGEFILE_SOURCE defined by stdio.h!");
#endif
  return 0;
}

In either case, _LARGEFILE_SOURCE is not defined by the compiler:

gcc -dM -E - < /dev/null |grep _LARGEFILE_SOURCE |wc -l
0
g++ -dM -E - < /dev/null |grep _LARGEFILE_SOURCE |wc -l
0

Why is stdio.h defining _LARGEFILE_SOURCE when GCC is invoked via the g++ frontend?

Java with RWeka packege

I have mac EL Capitan, 10.11.5, I used RWeka package, it downloaded correctly and initialized with any error, but when I apply

J48(Species ~ ., data = iris)

I have this error

Error in .jnew("weka/core/Attribute", attname[i], .jcast(levels, "java/util/List")) : 
  java.lang.UnsupportedClassVersionError: weka/core/Attribute : Unsupported major.minor version 51.0

I used java version with these details,

52F85:~ kameljabreen$ java -version
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)

Please help me to solve this problems, it is my problm since one month, I read a lot about this problem in web sites. I did all thing, installing java JDK version 1.8 .... ect. now I used java 1.7. Please give me solutions. Thanks in advance

How to play multiple sounds like SDL_Mixer does, but natively in SDL2?

In my last question I figured out how to play sounds natively in SDL2: How to lower the quality and specs of a wav file on linux

The issue I have now is wanting to mimic the 1 music and many sounds thing that SDL_Mixer does. A theory is I can use different channels, mono, stereo etc to play multiple sounds. Another theory is to look deep into the SDL Audio functions and try and find someway to play many sounds. I thought even using threads may work, but the problem with that is I find overwriting the default audio device seems to remove my old sound.

Has anyone done this or have any idea of playing multiple sounds with background music natively in SDL2 using the SDL_OpenAudioDevice with WAV files?

javascript to > jquery

i have a script like:

<script>
function vatCalculation() {
    var netto = document.getElementById('netto').value;
    var lordo = parseFloat(parseFloat(netto) / parseFloat(0.8)).toFixed(2);
    var ritenuta = parseFloat(parseFloat(lordo) * parseFloat(0.2)).toFixed(2);

    document.getElementById('lordo').value = lordo;
    document.getElementById('ritenuta').value = ritenuta;
}
</script>

and the html is:

<input name="netto" id="netto" type="number" maxlength="20" min="0" placeholder="00.00" onchange="vatCalculation();" />

<input name="lordo" id="lordo" type="text" maxlength="20" min="0" placeholder="00.00" readonly="true" />

<input name="ritenuta" id="ritenuta" type="text" maxlength="20" min="0" placeholder="00.00" readonly="true" />

Now the value of var are showed inside the field, but if i want tho show it inside <h1></h1> tag, what i need to to? Need to use jQquery? (fore live results). What can i do?

Why passing 2D matrix gives error in C?

I have written this below simple code to demonstrate passing 2D matrix in C. I have gone through most of the online articles. And this code is inaccordance with those suggested approaches. But still I am getting a compile error. Please explain.

#include <stdio.h>

int max = 0;

void maxId(int i,int j, int p[8][12]){


}

int main(){
    int m = 8;
    int n = 12;
    int p[m][n] = {{0,1,1,0,1,0,0,0,1,1,1,0},
                 {0,1,1,0,1,0,0,0,1,1,1,0},
                 {0,0,1,0,1,0,0,0,1,1,1,0},
                 {0,1,0,0,1,1,1,0,1,1,1,0},
                 {0,0,1,0,1,0,1,0,1,1,1,0},
                 {0,0,1,0,1,0,1,0,1,1,1,0},
                 {0,1,0,0,1,1,0,0,1,1,1,0},
                 {0,0,1,0,1,0,0,0,1,0,1,1}};

    int v[m][n];

    for(int i= 0;i<m;i++)
        for(int j = 0;j<n;j++){
            v[i][j] = v[i][j];
        }

    maxId(0,0,p);
    return 0;
}

Updated

The compile error shown is

29 13 C:UsersRainDropDocumentsdevc++ projectsUntitled2.cpp [Error] cannot convert 'int ()[n]' to 'int ()[12]' for argument '3' to 'void maxId(int, int, int (*)[12])'

How to generate Fibonacci faster

I am a CSE student and preparing myself for programming contest.Now I am working on Fibonacci series. I have a input file of size about some Kilo bytes containing positive integers. Input formate looks like

3 5 6 7 8 0

A zero means the end of file. Output should like

2 
5 
8 
13 
21 

my code is

#include<stdio.h>

int fibonacci(int n) {
  if (n==1 || n==2)
    return 1;
  else
    return fibonacci(n-1) +fibonacci(n-2);
}
int main() {
  int z;
  FILE * fp;    
  fp = fopen ("input.txt","r");    
  while(fscanf(fp,"%d", &z) && z) 
   printf("%d n",fibonacci(z));
  return 0;
}

The code works fine for sample input and provide accurate result but problem is for my real input set it is taking more time than my time limit. Can anyone help me out.

Parse error: syntax error, unexpected '/' in line 728

I am getting error for the line " /core/session/manager->start();"

Please advise for any solution for this error.

// Start session and prepare global $SESSION, $USER.
if (empty($CFG->sessiontimeout)) {
    $CFG->sessiontimeout = 7200;
}
 /core/session/manager->start();

// Set default content type and encoding, developers are still required to use
// echo $OUTPUT->header() everywhere, anything that gets set later should override these headers.
// This is intended to mitigate some security problems.
if (AJAX_SCRIPT) {
    if (!core_useragent->supports_json_contenttype()) {
        // Some bloody old IE.
        @header('Content-type: text/plain; charset=utf-8');
        @header('X-Content-Type-Options: nosniff');
    } else if (!empty($_FILES)) {
        // Some ajax code may have problems with json and file uploads.
        @header('Content-type: text/plain; charset=utf-8');
    } else {
        @header('Content-type: application/json; charset=utf-8');
    }
} else if (!CLI_SCRIPT) {
    @header('Content-type: text/html; charset=utf-8');
}

C How to use leftmost digit from a integer

I was wondering how to reverse my output to match entered number. Example if user entered 543210, I want the output to be: Five Four Three Two One Zero. But instead it's reversed and I can't figure out how to reverse it. I can't use loops or anything else.

Code:

int main(void){
        int value;
        int digit;

        printf("enter:");
        scanf("%i", &value);

        while(value)
        {


                digit = value % 10;
                value = value / 10;

                if(digit != 0)
                {

                        switch(digit)
                        {
                                case 0:
                                        printf("zero ");
                                        break;
                                case 1:
                                        printf("one ");
                                        break;
                                case 2:
                                        printf("two ");
                                        break;
                                case 3:
                                        printf("three ");
                                        break;
                                case 4:
                                        printf("four ");
                                        break;
                                case 5:
                                        printf("five ");
                                        break;
                                case 6:
                                        printf("six ");
                                        break;
                                case 7:
                                        printf("seven ");
                                        break;
                                case 8:
                                        printf("eight ");
                                        break;

                                case 9:
                                        printf("nine ");
                                        break;
                        }
                }

        }

        return 0;

}

Exmaple: If user entered 1234 Output would be: four three two one.

How would I fix it to be: One Two Three Four.

Break long lines that end with comment

Given the file alfa.c:

#include <stdio.h>
int main() {
  int bravo = 1;
  printf("charlie delta echo foxtrot golf hotel india juliet kilo lima %dn", bravo);
}

I can format it using GNU Indent and the long line is correctly broken:

$ indent -st alfa.c
#include <stdio.h>
int
main ()
{
  int bravo = 1;
  printf ("charlie delta echo foxtrot golf hotel india juliet kilo lima %dn",
          bravo);
}

However if I add a comment, the line is no longer broken:

$ indent -st alfa.c
#include <stdio.h>
int
main ()
{
  int bravo = 1;
  printf ("charlie delta echo foxtrot golf hotel india juliet kilo lima %dn", bravo);  // this is a comment
}

How can I break long lines, even if they end with a comment?

I can not get in the h1 heading

The content-script or in the background I get the title, but his pass or get-opens popup window with your script - it does not get the title of the page is obtained (necessary h1 of the page on which this expansion popup opens)?

UPD: In the popup-window, I want to convey title to the server, but in the same script, I can not get the standard script, also comes undefined localStorage, although on the whole page, I kept the title in localStorage another script (which content.js) .

Manifest is following:

{
    "manifest_version": 2,
    "version": "0.1",
    "name": "Title",
    "description": "Description",
    "content_scripts": [
        {
            "matches": [ "*://*/*" ],
            "css": ["ctyle.css"],
            "js": ["content.js"],
            "run_at": "document_end"
        }
    ],
    "background": {
    "scripts": ["background.js"]
  },
    "icons" : {
        "16" : "icon-16.png",
        "48" : "icon-48.png",
        "128" : "icon-128.png"
    },
    "permissions": [
        "tabs",
        "Need site/*",
        "storage"
  ],
    "browser_action": {
        "default_title": "Title",
        "default_icon" : "icon-32.png",
        "default_popup": "popup.html"
    }
}

Aggregate sum multidimensional arrays grouped by name

I have an array as follows

Array
(
    [0] => Array
        (
            [operation_name] => test 1
            [capacity] => 180
        )

    [1] => Array
        (
            [operation_name] => Operation 2
            [capacity] => 251
        )

    [2] => Array
        (
            [operation_name] => Operation 2
            [capacity] => 241
        )

    [3] => Array
        (
            [operation_name] => Operation 3
            [capacity] => 554
        )

)

I want to sum the "capacity" key value of same "operation_name" key arrays and made it as a one array.

In the above array I need to sum the following 2 arrays,

    [1] => Array
        (
            [operation_name] => Operation 2
            [capacity] => 251
        )

    [2] => Array
        (
            [operation_name] => Operation 2
            [capacity] => 241
        )

And output the resulting array as below.

Array
(
    [0] => Array
        (
            [operation_name] => test 1
            [capacity] => 180
        )

    [1] => Array
        (
            [operation_name] => Operation 2
            [capacity] => 492
        )

    [2] => Array
        (
            [operation_name] => Operation 3
            [capacity] => 554
        )

)

How to do this with php?

Find a triplet with sum=0 in a BST - Time complexity with below code

I wrote the below code for finding a Triplet in a BST that adds upto 0. But having difficulty determining the time complexity.

The find() method's time complexity is O(logn). Is the time time complexity of isTriplet() O(n^2) ?

bool find(Node* root, int target) {
  if (root == NULL)
      return false;

  if (root->data == target)
      return true;

  return (target < root->data) ?  find(root->left, target) :  find(root->right, target);
}

bool isTriplet(Node* root, Node* actualRoot) {
  if (root == NULL)
     return false;

  if (root->left == NULL && root->right == NULL)
      return false;

  int sum = root->data;
  if (root->left)
      sum += root->left->data;
  else if (root->right)
      sum += root->right->data;

  sum = -1 * sum;

  return (find(actualRoot, sum) || isTriplet(root->left, actualRoot) || isTriplet(root->right, actualRoot));
}

Yii2: Config params vs. constants

When should I use what?

I have the option to define constants in the index.php entry script file like it is recommended in Yii2 guide: constants. Or I could use the params in the configuration - explained in YII2 guide: params. Both are per application and not really global.

Currently it seems to me that params are a bit less comfortable if I want to combine values like this:

define('SOME_URL',            'http://some.url');
define('SOME_SPECIALIZED_URL', SOME_URL . '/specialized');

Besides, accessing is bit more code (Yii::$app->params['something']) compared to constants.

So when should or could I use what?

Inserting data into database using pdo

keep failing inserting data into database... im totally newbie in this... just need someone to explain the correct way inserting data

<?php   
    //TO ADD DATA
    if (isset($_POST['add'])) {
        $conn = new PDO("mysql:host=localhost;dbname=fzdb", 'root', '');
        $stmt = $conn->prepare("INSERT INTO 'order' (phone, name, address, city, state, postcode, product, size, quantity) VALUES 
            (:Phone, :Name, :Address, :City, :State, :Postcode, :Product, :Size, :Quantity)");

        $stmt->bindParam(':Phone', $phone);
        $stmt->bindParam(':Name', $name);
        $stmt->bindParam(':Address', $address);
        $stmt->bindParam(':City', $city);
        $stmt->bindParam(':State', $state);
        $stmt->bindParam(':Postcode', $postcode);
        $stmt->bindParam(':Product', $product);
        $stmt->bindParam(':Size', $size);
        $stmt->bindParam(':Quantity', $quantity);

        $phone = 'Phone';
        $name = 'Name';
        $address = 'Address';
        $city = 'City';
        $state = 'State';
        $postcode = 'Postcode';
        $product = 'Product';
        $size = 'Size';
        $quantity = 'Quantity';


        $stmt->execute();
    }
    ?>

Kind of adware injected into google chrome

I have been fighting with strange kind of virus for a long time. Agressive ads suddenly appeared on many websites. I tried many tools to detect adware/malware, I am using Kaspersky antivirus, nothing helped. When I unistall google chrome everything is ok for a few days and than it happens again. Nothing strange in google chrome extensions, nothing strange in regedit scans, no suspected proces in background, no trace.

I have some experince in web development so I tried to understand origin of that. In google dev tool, there is extra script p.js which is excecuting document.write... - it writes extra ads to website. There are http request from my computer to strange websties: p.ato.mx pipelinemg etc...

What is going on? What is inhibitor of that strange connections, which are origns of agressive ads? Please help me!

_f_data_rom linker script symbols

I am working on startup code of micro controller 32 bit and codewarrior compiler , As we have to deal with linker script. Certain variables that used in startup code for initilization of RAM and stack come from linker script.

Linker Script initialize these variables with different address. Problem is one variable have wrong address. In linker script it initialized by following command _f_data_rom.

  • Could any one tell me how linker initiazed variables that provides address for stack , RAM initialization?
  • What this command means _f_data_rom ?

it looks like

RC_SDATA_SRC       = _f_sdata_rom;
RC_SDATA_DEST      = _f_sdata;
RC_SDATA_SIZE      = (SIZEOF(.sdata)+3) / 4;
RC_DATA_SRC        = _f_data_rom;
RC_DATA_DEST       = _f_data;
RC_DATA_SIZE       = (SIZEOF(.data)+3) / 4;

Symfony2: linkedin error - invalid redirect_uri

In linkedin developers page under settings of application I added http://example.org/login as "Authorized Redirect URL".

In application I am using HWIOauthBundle and in security.yml I added following:

firewalls:
    secured_area:
        oauth:
            resource_owners:
                linkedin:   "/login/check-linkedin"
            login_path:        /login
            use_forward:       false
            failure_path:      /login
            oauth_user_provider:
                service: hwi_oauth.user.provider

Once I enter http://example.org/login and press linkedin button. I am getting an error:

invalid redirect_uri. This value must match a URL registered with the API Key.

I see multiple topics on this problem, but no solving.

P.S. I tried adding http://example.org/login/check-linkedin as "Authorized Redirect URL" in developers page, but I still get same error.

Why are LSP violations in PHP sometimes fatal, and sometimes warnings?

This LSP violation raises a Fatal Error:

abstract class AbstractService { }
abstract class AbstractFactory { abstract function make(AbstractService $s); }
class ConcreteService extends AbstractService { }
class ConcreteFactory extends AbstractFactory { function make(ConcreteService $s) {} }

This LSP violation also raises a Fatal Error:

interface AbstractService { }
interface AbstractFactory { function make(AbstractService $s); }
class ConcreteService implements AbstractService { }
class ConcreteFactory implements AbstractFactory { function make(ConcreteService $s) {} }

While this LSP violation only raises a Warning:

class Service { }
class Factory { function make(Service $s) {} }
class MyService extends Service { }
class MyFactory extends Factory { function make(MyService $s) {} }

Why? Shouldn't they all be fatal since they're all contravariant?

Insert HTML after String / String position

I've come up short on an answer for this so hopefully there's someone who can help me.

I'm trying to non-destructively insert HTML before and after a substring or position in text to create new inline elements or wrap existing text. I would just use innerHTML and be done with this already but I would really like to preserve possible event listeners that might be bound to that particular DOMNode. Is there a method or a prototype of a Element that treats textNodes as individual items that would allow me to append HTML after or before it?

The code might operate like this:

var testParagraph = document.getElementById("TestParagraph");

/** 
    text nodes would represent each item 
    that has been seperated by a space, for example 
**/

testParagraph.insertBefore(document.createElement("span"), testParagraph.textNodes[3])

Thanks for your time!

How do I combine these Array values?

Hi I have the following Array structure, how can I merge the sub-array values by ['number'] ?

 array(4) { 
          ["success"]=> bool(true) 
          ["messages"]=> array(2)
           {  

            ["0"]=> array(5){

                ["number"]=>string(1)                           
                ["incoming_id"]=> string(6)                        
                ["usernumber"]=> string(13)                         
                ["content"]=> string(4)                           
                ["date"]=> string(10)  

                }

            ["1"]=> array(5){

                ["number"]=>string(1)                           
                ["incoming_id"]=> string(6)                        
                ["usernumber"]=> string(13)                         
                ["content"]=> string(4)                           
                ["date"]=> string(10)  

                }  
        }             
       ["start"]=> string(1) 
       ["next"]=> string(2) 
       }

I want the following thing: If the value of ['number'] in [0] is the same as in [1] they should be saved in one new Array. For Example [0]['number']-> 1234 and [1]['number'] -> 1234 their values should be merged into one array named [1234]-> content from [0]['content'] , content from [1]['content'].

Thanks for your help.

Get users ip on page click

I'm trying to get my users ip address when they open a certain page. I want this ip mailed to me or stored in the database.

At the moment I have this, but its not working.

<?php
$to = "flash1996mph@hotmail.com";
$subject = "test";
$ip = $_SERVER['REMOTE_ADDR'];
$txt = "Hello world!";

header ('mail($to,$subject,$txt,$ip);')
?>

I have no idea if this is right or wrong, I'm just a newby trying.. This was the first that came up in my mind.

All help is appreciated.

Thanks in advance,

-Kev

edit:

<?php
$to = "flash1996mph@hotmail.com";
$subject = "test";
$ip = $_SERVER['REMOTE_ADDR'];
$txt = "Hello world!";

 mail($to,$subject,$txt,$ip); 
?>

Got this now, and its still not working.

Scanning a 2d character array

This code doesn't scan the whole array. It breaks in the middle

# include<stdio.h>
# include<stdlib.h>
int** create(int m)
{
  char **a;
  int i;
  a=(char**)malloc(sizeof(char*)*m);
  for(i=0; i<m; i++)
    *(a+i)=(char*)malloc(sizeof(char)*m);
  return a;
}
int main()
{
  int i,j,n;
  char **a;
  scanf("%d",&n);
  a = create(n);
  for(i=0;i<n;i++)
    for(j=0;j<n;j++)
      scanf("%c",*(a+i)+j);

  printf("Output is n");
  for(i=0;i<4;i++)
    for(j=0;j<4;j++)
      printf("%c",*(*(a+i)+j));
  return 0;
}

input given is n = 4 it scans two line and then prints back that two line... Here is a screenshot of the output Output ScreenShot

Bootstrap grid with different number of elements per column depending on screen size

I am using a bootstrap grid to display picture thumbnails, where the number of thumbnails displayed depends on the number of matches to a user's search criteria. I am displaying a different number of thumbnails per row depending on the screen's size, defined as:

 <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">

I then use the following PHP construct to create new row div elements:

<?php

                    for ($i = 0; $i < sizeof($products); $i++):

                        if ($i % 3 == 0) {

                            if ($i > 0)
                                echo "</div>";

                            echo "<div class="row">";

                        }

                        $product = $products[$i];

                        ?>

This works well for -md and -lg but obviously not for -sm and -xs for which I'd need i%2 and i%1. Anybody knows some way I can retrieve from PHP the column size that boostrap is using?

mercredi 27 juillet 2016

How to use angularjs template inside php project based on Zend

I have php framework based on Zend library and I'd like to use angularjs script in phtml file but I have problem how to include template edytuj_row.phtml located in:

ProjectName->SourceFiles->application->admin->views->settings->edytuj.phtml

<div row-settings></div>

<script type="text/javascript">
    var app = angular.module('mainApp', []);

    app.directive('rowSettings', function(){
        return {
            templateUrl: 'edytuj_row.phtml'            
        };
    });
</script>

to show I use:

Both files edytuj_row.phtml and edytuj.phtml are localizated in the same directory but edytuj_row.phtml is not seen. What is right path in templateUrl ? In this situation in place of <div row-settings></div> is loaded recurently main web page instead of template.

Webpack resolve svg

Installed in node:

npm install svg-url-loader --save

I have added to the webpack.config.js:

module: {
    loaders: [
        { test: /.css$/, loader: "style-loader!css-loader" },
        {test: /.svg/, loader: 'svg-url-loader'},
    ]
}

To the Page.jsx:

require("svg-url!C:/../WebApp/main_page_assets/02_general_alerts_icons.svg");
require("C:/../WebApp/css/dashboard/dashboard.css");

And in my css:

.test {
    background: url('../../main_page_assets/02_general_alerts_icons.svg');
    background-repeat: no-repeat;
}

And I receive:

ERROR in ./~/css-loader!../css/dashboard/dashboard.css
Module not found: Error: Cannot resolve module 'svg-url-loader' in C:..W
bAppcssdashboard
 @ ./~/css-loader!../css/dashboard/dashboard.css 6:74-135

What can be the reason? Paths issues? i have been playing with the paths back and forth and cant make it work

More optimal way to find a specific word in a string buffers C

I've made an app that parses HTTP headers. I'm trying to find if there is a better way to filter HTTP packets by POST method than the one I've come up with. What I am trying to accomplish is to take advantage of the fact that I know that all the POST methods packet strings start with "POST". Is there a way to search for the first word of a string, store it and then use a condition with it? My code works but I would prefer not to search for the whole packet for a "POST" - you never know when you get the word "POST" inside a GET packet, for example.

   char re[size_data];
   strncpy(re,data,size_data);   //data is the buffer and size_data the buffer size
   char * check;
   check = strstr(re,"POST"); 
   if(check!= NULL)
  { *something happens* }

Hide DIVs by ID on page load

I have the following JS in the page layout (running RoR):

<script>
  $(document).ready(function() {
    document.getElementById('1').style.display = 'none';
    document.getElementById('2').style.display = 'none';
    document.getElementById('3').style.display = 'none';
    document.getElementById('4').style.display = 'none';
    document.getElementById('5').style.display = 'none';
    });
</script>

I am trying to have the 5 divs to be hidden on page load but can not seem to get it to work. I can use JS or JQuery. I have tried this as well:

$(window).load(function() {
  ...js code...
});

and still could not get it to hide the divs on page load.

What do I need to write in JS to have div with id 1..5 to be hidden?

N-ary Tree in C: How to add nodes and store data?

I want to create an n-ary tree composed in this way:

FileFolderTree

Each node has a key, name, type (File/Folder) and URL:

struct node {
    int key;
    char[10] name;
    char[100] url;
    char type;
} node;

Every node can have a different number of child nodes.

I already read about a solution that uses linked lists: N-ary trees in C
But it doesn't say anything about algorithms for adding or accessing nodes.

How can I store my data in a tree like this?
How can I add nodes to the linked list?
How can I access the data once the tree is built?

Passing semaphores as an argument to functions

I'm working on a static analysis tool which detects if a there's a mismatch for between lock/release calls for a semaphore. The detection is specific to VxWorks RTOS.

I came across this testcase and my tool detects this as mismatch between lock and release of semaphores because my implementation is solely based upon comparing the semaphore strings passed to the lock/release call.

void fun(char semid);
char id,i;
int main()
{
    id = semCreate();         //initializing a semaphore
    fun(id);
    semGive(id);              //semaphore release call
    return 0;
}
void fun(char semid)
{
    semTake(semid);          //semaphore lock call
    i++;        
}

Logically the code makes sense, but is this a correct way of using semaphores? Is this a regular programming practice or is it plainly invalid?

Some detailed code supporting or rejecting the usage of semaphores as given above would be highly appreciated.

ReactJS determine if component is on screen

I'm designing an application and am wondering whether React can handle the use case. I'm going to have a canvas that has boxes. Inside those boxes will be input fields, buttons, spinners, etc. There will be hundreds of boxes. The user will be able to zoom in/out, as well as pan in any direction, such that the user can zoom in and a single box will fill the entire page, and zoom out so that the user can see all boxes. I'd like to be able to detect whether any portion of an arbitrary box is visible, so that I don't spend time updating the fields with constantly changing server information if the box isn't visible to the user. Is this something that can be accomplished with React?

Thanks in advance for any help. I apologize if my terminology is incorrect, and it probably is.

Symfony Event Listener

Hi I'm tring to do a Symfony event listener following this documentation: http://symfony.com/doc/2.8/cookbook/doctrine/event_listeners_subscribers.html

<?php

namespace FMAppBundleEventListener;

use DoctrineORMEventLifecycleEventArgs;
use FMAdminBundleEntityAddressBillingAddress;

class BillingAdressListener
{
    /**
     * @param LifecycleEventArgs $args
     */
    public function listenBillingAdress(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        if(!$entity instanceof BillingAddress){
            return;
        }

        $this->postPersist($args);
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postPersist(LifecycleEventArgs $args)
    {
        $em = $args->getEntityManager();
        $billingAdress = $args->getEntity();

        dump($billingAdress); die();
    }
}

service.yml

billing_adress.listener:
        class: FMAppBundleEventListenerBillingAdressListener
        tags:
            - { name: doctrine.event_listener, event: listenBillingAdress }

But nothing is happening when I'm submitting a form with the BillingAddress object.

Did I do something wrong?

Laravel error handling when route does not exist

I have a route to show my users' profile in my laravel project. But when you go to an url and fill in a username that does not exist it gives a nasty error, obviously because that username doesn't exist in the database.

Has anyone any idea how I can error handle this?

Here's my route:

Route::get('user/{name}', 'userController@showUser');

Here's my function:

public function showUser($name)
    {
        $user = User::where('name' , '=', $name)->firstOrFail();
        return view('user.show', compact('user'));
    }

This is what I've tried but doesn't seem to work since I get this error: View not found

$user = User::where('name' , '=', $name)->first();
        if(!empty($user)){
            return view('user.show', compact('user','projects'));
        }else{
            return view('user');
        }

Prevent user from pressing backspace

I'm developing a program that uses malloc and realloc functions to increment the pointer buffer in real-time while the user is typing a string.

The problem is, that I'd like to prevent the user from hitting Backspace to correct the input. Is it possible to block Blackspace key somehow in C while using getche()?

My final program will have two inputs: one without Backspace (you can't go back), and another with Backspace. (you can correct the input and then press Enter).

char *szString;
char *tmp;
int i = 0;
char c;

szString = '�';
szString = malloc(1);

printf("Enter a string: ");

while ((c = getche()) != 'r')
{
    if(c = 0x08) // BackSpace
    {
        //
    }
    szString[i] = c;
    i++;
    tmp = realloc(szString, i+1);
    szString = tmp;
}

szString[i] = '�';

printf("nYou typed: %s", szString);