text:
Q: Prevent Double Form Submit using Tokens I am trying to prevent the user from double submitting the forum by adding token hidden field.
So here is what I have done so far (before the forum loads I have this code to create a token with the current time as a value.
$token = time();
setcookie('formToken', $token, time() + 3600);

in my forum I have a hidden input like this
<form method="post" action="'.$PHP_SELF.'?action=update">
<input type="hidden" name="token" value="'.$token.'" />
<input type="submit" value="go" />
</form>

now on the top of my page where $action == "update" I have this code
if(isset($_POST)  &&  ($_POST['token'] != $_COOKIE['formToken'])){
    $error_list .= '
You can not submit this forum twise.
';
}

if i hit F5 to refresh the page it submit the form again without displaying my error.

A: Why not just set a session when the form is successfully submitted?
so $_SESSION['submitted'] = 1;
Then you can check for it.
Or Do
if(isset($_POST['submit'])  &&  ($_POST['token'] != $_COOKIE['formToken'])){
    $error_list .= '
You can not submit this forum twice.
';
}

A: gd1 answer will not prevent double click submission or accidental double submit by various jQuery bindings on a complex javascript form code.
Double click may be even faster then disabling submit button, or hiding it with javascript, so this would not be a full answer either.
The session token will not work either because session is not yet written and thus available or updated for the second process which may be just milliseconds away sharing the same session ID. The session is stored only upon completion of the fist process.
Cookie technique could be an answer as far as both processes are able to communicate over cookie in a blocking way, which may result to the same problems as the session sharing above.
The best solution would be to use server's shared memory access to check if the other process had already processed the data (order, payment, etc..) with the pregenerated data hash, or use database table blocking select and insert to check if the pregenerated hash has been already submitted.

A: I suggest you to use use the PRG pattern (Post/Redirect/Get), which is also implemented by forums like phpbb.

Post/Redirect/Get (PRG) is a web development design pattern that
prevents some duplicate form submissions, creating a more intuitive
interface for user agents (users). PRG implements bookmarks and the
refresh button in a predictable way that does not create duplicate
form submissions.

A: Suggestion 1)
on Successful Submission Delete the cookies  (removeTokens)
    function removeToken()
{
    //set formToken cookie val to "" (or any default xxxx) and the past expiry date for it
    setcookie("formToken", "", time()-3600);
    //try to unset - this is not needed ,we may try it
    unset($_COOKIE['formToken']);
}

ie simply on your page if(isset($_POST)) removeToken();
Suggestion 2)
Perform a redirect as suggested by Tom Wright here Avoiding form resubmit in php when pressing f5
 header('Location: formsubmitSucess.php');

A: I use this way of preventing double form submissions, it has worked on all occasions so far. Let me know if you need additional questions as this tutorial assumes you have intermediate knowledge on database and PHP.
STEP 1 : add a field on your database like this:
replace YOUR-TABLE with the name of your database table.
    ALTER TABLE `YOUR-TABLE` ADD `token` VARCHAR(35) NULL DEFAULT NULL AFTER    `creationtoken`, ADD UNIQUE (`token`) ;

STEP 2 on your form page you add this to the very first line:
it will create a unique toke that will be inserted into your database table along with you query, so that it can be checked for later to make sure no other like it is submitted into your database, meaning no double form submissions.
    <?php
    session_start();
    date_default_timezone_set('America/Chicago');
    $_SESSION['token'] = md5(session_id() . time());
    ?>

then just before your submit button add this:
    // add this before the submit button
    // this will post the unique token to the processing page.

Session Token: <?php echo strtolower($_SESSION['token']) ?>

    <input type="hidden" name="token" id="token" value="<?php echo  $_SESSION['token']?>" />
    // add this before the submit button

    <input type="submit" id="submit" name="submit" class="button" value="Submit" />

STEP 3: now on your process.php page
    //this is where all of your form processing takes place.

    // this is where you call the database
    // if you need the database file let me know...
    include("../common/databaseclass.php");
    $db= new database();

    //here the token is posted then the database table is checked and
    //if the form has already been added it will return a 1 and will
    //cause the query to die and echo the error message.

    $token = $_POST['token'];
    $query = "SELECT token FROM YOURTABLE WHERE token = '$token' LIMIT 1";
    $result = $db->query($query);
    $num = mysql_num_rows($result);

    if ($num>0) {die('your form has already been submitted, thank you');}

    else {

    $host = "localhost";
    $user = "user";
    $pass = "password";
    $db_name = "database";

    mysql_connect($host,$user,$pass);
    @mysql_select_db($db_name) or die( "Unable to select database");

    // table query
    $sql1="INSERT INTO YOURTABLE (
    `token`,
    `user`,
    `email`,
    `password`,
    `newaccount`,
    `zipcode`,
    `city`,
    `state`,
    `country`,
    `telephone`,
    `creationip`,
    `createdaccount`
     )
     VALUES (
     '$token',
     '$username',
     '$email',
     '$password',
     '$newaccount',
     '$zipcode',
     '$city',
     '$state',
     '$country',
     '$phone',
     '$ipadress',
     '$createdaccount'

       )";

    $db->query($sql1);
    header("location:" http://home.php ");

    }

A: For the same issue I made a code to use it for my own stuff. It has the PRG pattern and flexible to use it on same page or with extern PHP file for redirection - Easy to use and safe, maybe this might help you.
class unPOSTer {

        private
            $post = "KEEP_POST";

        public function __construct(string $name = null) {
            if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
                if (session_status() == PHP_SESSION_NONE) {
                    session_start();
                }
            } else {
                if (!$_SESSION) {
                    session_start();
                }
            }
            $this->post = $name;
        }

        public function unPost() {
            if (session_status() !== PHP_SESSION_ACTIVE) {
                session_start();
            } elseif (strcasecmp($_SERVER["REQUEST_METHOD"],"POST") === 0) {
                $_SESSION[$this->post] = $_POST;
                header("Location: " . $_SERVER["PHP_SELF"] . "?" . $_SERVER["QUERY_STRING"]);
                exit;
            } elseif (isset($_SESSION[$this->post])) {
                $_POST = $_SESSION[$this->post];
            }
        }

        public function retrieve($data) {
            if (isset($_SESSION[$this->post])) {
                $posts = @$_SESSION[$this->post][$data];
                if (isset($posts)) {
                    return $posts;
                } else {
                    return null;
                }
            }
        }

        public function reset() {
            if (isset($_SESSION[$this->post])) {
                unset($_SESSION[$this->post]);
            }
        }
    }

Then use it like this:
<?php
    require_once "unPOSTer.class.php";
    $unpost = new unPOSTer();
    $unpost->unPost();
?>
<form action='' method=POST>
    <input type=text name=fname value="<?php echo $unpost->retrieve("fname"); ?>" placeholder="First Name">
    <input type=text name=lname value="<?php echo $unpost->retrieve("lname"); ?>" placeholder="Last Name">
    <input type=submit name=send value=Send>
</form>
<?php echo $unpost->reset(); ?>

Not much to configure, do it on every page you send form data if you like. The retrieve() method spits out the data you have sent, in case if you might go back and fix something. Feel free to fork/pull it at my GitHub page I added 2 demos there.

A: I had the same problem, here is a simple fix:
if(!empty($_SESSION['form_token']) && time() - $_SESSION['form_token'] < 3){
    $data['message'] = 'try again later';
    return;
}
$_SESSION['form_token'] = time();

In my case the PRG pattern didn't have any effect since form submitted multiple times at the same time and the code had not been executed and there is no data saved to compare it against.


text:
Q: How to validate form with php and show the error text in html I want to validate form using php and then make the input save in json file. I used span class to echo the error message from writer.php to html. But it's not echo the error text in html, it's refer to writer.php with blank page.

    <title>Data Buku</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>

Data Buku

* required field.

        <form action="writer.php" method="post">
            <?php echo $error;?>

Informasi Pengarang

            Nama:
<input type="text" name="nama" id="nama" />
            * <?php echo $namaErr;?>

            Nomor Telepon:
<input type="text" name="telepon" id="telepon" />
            * <?php echo $nomorErr;?>

            e-Mail:
<input type="email" name="email" id="email" />
            * <?php echo $emailErr;?>

Tulisan

            Judul:
<input type="text" name="judul" id="judul" />
            * <?php echo $judulErr;?>

            Konten:
<textarea name = "konten" rows="6" cols="50" id="konten"></textarea>
            * <?php echo $kontenErr;?>

            <input type="submit" id="submit" name = submit value="Create" />
            <input type="reset" id="reset" value="Reset" />
        </form>

This is my php file
<?php
    // Append new form data in json string saved in json file

    // path and name of the file
$filetxt = 'dataInJson.json';

    // error message
$namaErr = "";
$nomorErr = "";
$emailErr = "";
$judulErr = "";
$kontenErr = "";

    // check if all form data are submited, else output error message
    if(isset($_POST['submit'])) {
    // if form fields are empty, outputs message, else, gets their data
    if(empty($_POST['nama'])) {
        $namaErr = "Write your name";
    }
    if(empty($_POST['telepon'])){
        $nomorErr = "Write the phone number";
    }
    if(empty($_POST['email'])){
        $emailErr = "Write the email";
    }
    if(empty($_POST['judul'])){
        $judulErr = "Write the title";
    }
    if(empty($_POST['konten'])) {
        $kontenErr = "Write the content";
    }
    else {

    // gets and adds form data into an array
    $data = array(
      'nama'=> $_POST['nama'],
      'telepon'=> $_POST['telepon'],
      'email'=> $_POST['email'],
      'judul'=> $_POST['judul'],
      'konten'=> $_POST['konten'],
    );

    // path and name of the file
    $filetxt = 'dataInJson.json';

    $arr_data = array();        // to store all form data

    // check if the file exists
    if(file_exists($filetxt)) {
      // gets json-data from file
      $jsondata = file_get_contents($filetxt);

      // converts json string into array
      $arr_data = json_decode($jsondata, true);
    }

    // appends the array with new form data
    $arr_data[] = $data;

    // encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
    $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

    // saves the json string in "dataInJson.json"
    // outputs error message if data cannot be saved
    if(file_put_contents('dataInJson.json', $jsondata)){
        echo '';
    }
    else{
        echo 'Tidak dapat menyimpan data di "dataInJson.json"';
    }
  }
}
    else echo 'Form fields not submited';
?>

A: Your if/else statements are wrong. Your else execute only if !empty($_POST['konten']).
I suggest you, pull errors in to one array, stored in session in redirect user (if scripts in different files) and show content of errors array. If you have trouble with logic, view this question here - PHP form validation submitting

A: You would need the page to submit to itself unless you did an AJAX solution so this would all have to be on one page:
<?php
    error_reporting(E_ALL);
    class   ValidateInfo
        {
            public  $errors;
            public  $message;
            public  $data;
            public  function Check($payload = array(),$type = "error",$mess = "unknown",$validate = array())
                {
                    $trimmed                =   trim($payload[$type]);

                    if(!empty($validate)) {
                            // Strip out everything but numbers and letters and a couple of symbols.
                            if(in_array('digits',$validate) && in_array('letters',$validate)) {
                                    $this->data[$type]  =   preg_replace('/[^0-9a-zA-Z\s\-\_]/','',$trimmed);
                                }
                            // Strip out all but numbers
                            elseif(in_array('digits',$validate)) {
                                    $this->data[$type]  =   preg_replace('/[^0-9]/','',$trimmed);
                                }
                            // Strip out letters
                            elseif(in_array('letters',$validate)) {
                                    $this->data[$type]  =   preg_replace('/[^a-zA-Z\s\-\_]/','',$trimmed);
                                }
                            // Re-assign data type to consolidate
                            $this->data[$type]          =   (!isset($this->data[$type]))? $trimmed:$this->data[$type];

                            // Check if data is an email
                            if(in_array('email',$validate)) {
                                    $this->data[$type]  =   (filter_var($this->data[$type], FILTER_VALIDATE_EMAIL))? $this->data[$type]:'';
                                }

                            // Strip out html tags
                            if(in_array('strip',$validate)) {
                                    $this->data[$type]  =   strip_tags($this->data[$type]);
                                }
                        }

                    if(!isset($this->data[$type]))
                        $this->data[$type]  =   $trimmed;

                    $this->errors[$type]    =   (empty($this->data[$type]))? 1:0;
                    $this->message[$type]   =   $mess;
                }
        }

    // Creat instance of info processor
    $info   =   new ValidateInfo();

    // check if all form data are submited, else output error message
    if(isset($_POST['submit'])) {

            // Checks empty fields
            $info->Check($_POST,'nama','Write your name',array('letters','digits'));
            $info->Check($_POST,'telepon','Write the phone number',array('digits'));
            $info->Check($_POST,'email','Write the email',array('email'));
            $info->Check($_POST,'judul','Write the title',array('letters','digits'));
            $info->Check($_POST,'konten','Write the content', array('letters','digits','strip'));

            if(array_sum($info->errors) == 0) {

                    // path and name of the file
                    $filetxt    =   'dataInJson.json';

                    // Assign stored data
                    $data       =   $info->data;

                    // path and name of the file
                    $filetxt    =   'dataInJson.json';

                    // to store all form data
                    $arr_data   =   array();

                    // check if the file exists
                    if(file_exists($filetxt)) {
                            // gets json-data from file
                            $jsondata   =   file_get_contents($filetxt);

                            // converts json string into array
                            $arr_data   =   json_decode($jsondata, true);

                            // appends the array with new form data
                            $arr_data[] =   $data;

                            // encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
                            $jsondata   =   json_encode($arr_data, JSON_PRETTY_PRINT);

                            // saves the json string in "dataInJson.json"
                            // outputs error message if data cannot be saved
                            if(file_put_contents('dataInJson.json', $jsondata)) {
                                    $info->errors['success']    =   true; ?>

                            <?php }
                            else {
                                    $info->message['general']['put_file']   =   'Tidak dapat menyimpan data di "dataInJson.json"';
                                }
                        }
                    else {
                            $info->message['general']['bad_file']   =   'No file exists';
                        }
                }
        }
    else
        $info->message['general']['submit'] =   'Form fields not submited'; ?>

<title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>

Data Buku

    <?php if(isset($info->errors['success'])) { ?>

Thank you!

    <?php } else { ?>

* required field.

    <?php } ?>

    <form action="" method="post">
        <?php if(isset($info->message['general'])) {
            foreach($info->message['general'] as $_error) { ?>
            * <?php echo $_error; ?>

            <?php
                }
        } ?>

Informasi Pengarang

            Nama:
            <input type="text" name="nama" id="nama"<?php if(isset($info->data['nama'])) { ?> value="<?php echo strip_tags($info->data['nama']); ?>" /><?php } ?>
            <?php if(isset($info->errors['nama']) && $info->errors['nama'] == 1) { ?>* <?php echo $info->message['nama']; ?><?php } ?>

            Nomor Telepon:
            <input type="text" name="telepon" id="telepon"<?php if(isset($info->data['telepon'])) { ?> value="<?php echo strip_tags($info->data['telepon']); ?>"<?php } ?> />
        <?php if(isset($info->errors['telepon']) && $info->errors['telepon'] == 1) { ?>* <?php echo $info->message['telepon']; ?><?php } ?>

            e-Mail:
            <input type="email" name="email" id="email"<?php if(isset($info->data['email'])) { ?> value="<?php echo strip_tags($info->data['email']); ?>"<?php } ?> />
        <?php if(isset($info->errors['email']) && $info->errors['email'] == 1) { ?>* <?php echo $info->message['email']; ?>
<?php } ?>

Tulisan

            Judul:
            <input type="text" name="judul" id="judul"<?php if(isset($info->data['judul'])) { ?> value="<?php echo strip_tags($info->data['judul']); ?>"<?php } ?> />
        <?php if(isset($info->errors['judul']) && $info->errors['judul'] == 1) { ?>* <?php echo $info->message['judul']; ?><?php } ?>

            Konten:
            <textarea name = "konten" rows="6" cols="50" id="konten"><?php if(isset($info->data['konten'])) {  echo strip_tags($info->data['konten']); } ?></textarea>
        <?php if(isset($info->errors['konten']) && $info->errors['konten'] == 1) { ?>* <?php echo $info->message['konten']; ?>
<?php } ?>

        <input type="submit" id="submit" name = submit value="Create" />
        <input type="reset" id="reset" value="Reset" />
    </form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Awesome wm setting size for the tasklist item I'm coding a custom vertical wibox that contains my tasklist, I want it to look like this:

but instead of being fixed height, the tasklist items just take up all the available space. Here's the result:

Here's my code so far:
function render_task_box(s)
    myotherbox[s] = awful.wibox({ position = "left", screen = s, ontop =
    true, width = 200 })

    mytasklist[s] = awful.widget.tasklist(
        s,
        awful.widget.tasklist.filter.currenttags,
        mytasklist.buttons,
        nil,
        nil,
        wibox.layout.flex.vertical())

    local middle_layout = wibox.layout.fixed.vertical()
    middle_layout:add(mytasklist[s])

    local layout = wibox.layout.align.vertical()
    layout:set_middle(middle_layout)

    myotherbox[s]:set_widget(layout)

end

So how do I get wanted result? (or at least set height of tasklist icon)
Update
Looked up some docs and tried this:
local l = wibox.layout.flex.vertical();
l:set_max_widget_size(20)

It did nothing.

A: After reading some of the awesome's source code I've found a solution.
Somewhere in your script require this
local common = require("awful.widget.common")

Then create a function that overrides task update function:
function list_update(w, buttons, label, data, objects)
    -- call default widget drawing function
    common.list_update(w, buttons, label, data, objects)
    -- set widget size
    w:set_max_widget_size(20)
end

Then pass this function to tasklist
    mytasklist[s] = awful.widget.tasklist(s,
    awful.widget.tasklist.filter.currenttags,
    mytasklist.buttons,
    nil,
    list_update,
    wibox.layout.flex.vertical())

Thats it!


text:
Q: Qt application fails to run I've just completed my application programmed with Qt. It runs fine with my Qt Creator, but when I copy the .exe from release directory with all neccessary dll files. It doesn't require any further dll files but it just crashes. What happened?
Problem signature:
Problem Event Name:       APPCRASH
Application Name:         agrisis.exe
Application Version:      0.0.0.0
Application Timestamp:    532025fe
Fault Module Name:        Qt5Cored.dll
Fault Module Version:     5.2.1.0
Fault Module Timestamp:   52ed6764
Exception Code:           c0000005
Exception Offset:         00216730
OS Version:               6.1.7601.2.1.0.256.48
Locale ID:                1033
Additional Information 1: 0a9e
Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
Additional Information 3: 0a9e
Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

I've copied all the dll files from Qt5 bin directory to my application directory but now it doesn't crash at Qt5Cored.dll anymore, it crashes at Qt5WebKitd (the application screen is shown fine but the web component fails to appear):
Problem Event Name:       APPCRASH
Application Name:         agrisis.exe
Application Version:      0.0.0.0
Application Timestamp:    53214fe7
Fault Module Name:        Qt5WebKitd.dll
Fault Module Version:     5.2.1.0
Fault Module Timestamp:   52ed99de
Exception Code:           c0000005
Exception Offset:         01d0a465
OS Version:               6.1.7601.2.1.0.256.48
Locale ID:                1033
Additional Information 1: a7aa
Additional Information 2: a7aa91f17ea749d42a4de3b390fa5b3d
Additional Information 3: a7aa
Additional Information 4: a7aa91f17ea749d42a4de3b390fa5b3d

A: You are probably missing a file that is only loaded at runtime (like a plug-in DLL). This guide will help you find those DLLs quickly. It assumes that:

*

*The release version of your app works correctly when you build + run it from Qt Creator

*Your (dynamically-linked) copy of Qt is installed in C:\Qt\5.2.1\mingw48_32\

Initial deployment (Quick and dirty)

*

*Close Qt Creator.

*Copy the following into C:\Deployment\

*The release version of MyApp.exe

*All the .dll files from C:\Qt\5.2.1\mingw48_32\bin\

*All the folders from C:\Qt\5.2.1\mingw48_32\plugins\

*(If you used QML) All the folders from C:\Qt\5.2.1\mingw48_32\qml\

*Rename C:\Qt\ to C:\QtHidden. (This turns your PC into a clean environment, just like one that doesn't have Qt installed.)

*Launch C:\Deployment\MyApp.exe.

If your app worked correctly, congratulations! You are almost ready for deployment. You don't want to ship a 1.5GB package though, so it's time to clean up unused files.
If it didn't work correctly, ask for more help.
Final deployment (Cleaned up)
Do the deletion steps below in C:\Deployment\ and all of its subdirectories. After each deletion, launch C:\Deployment\MyApp.exe and test it. If it stops working, restore the files you just deleted.

*

*Delete all the debug DLLs and keep the release DLLs only. (Debug DLLs end with 'd'. For example, delete Qt5Cored.dll but keep Qt5Core.dll)

*Delete a few DLLs and test MyApp.exe. Repeat until you try all DLLs.

*(If you used QML) Delete a few .qml files and test MyApp.exe. Repeat until you try all .qml files.

*(If you used QML) Delete qmldir files from the folders that have no more DLLs or .qml files

When you have removed all the files that you don't need,

*

*Rename C:\QtHidden\ back to C:\Qt\ to restore your installation.

*Distribute your app.

Adapted from: http://qt-project.org/wiki/Deploy_an_Application_on_Windows

A: Usually when running the .exe file a message will show up about missing dll. But for some dll files this message is not shown at all.
I copied all the dll file of Qt then tested by removing them 1 by 1.


text:
Q: Render is not called in a BasicGameState I am starting a very simple game in java, but am already stuck at the first step. I've made a StateBasedGame class (Kreations), which succesfully adds and enters and inits my BasicGameState (MenuGameState). However the update() and render() methods of MenuGameState are not called - and I have trouble figuring out why. Can you help?
Here follows the code:
StateBasedGame:
import gamestates.MenuGameState;

import org.newdawn.slick.*;
import org.newdawn.slick.state.StateBasedGame;

public class Kreations extends StateBasedGame
{

  public Kreations() {
        super("Kreations");
    }

  @Override
  public void update(GameContainer gc, int delta) throws SlickException
  {

  }

  @Override
  public void render(GameContainer gc, Graphics g) throws SlickException
  {

  }

  public static void main(String[] args) throws SlickException
  {
      try {
           AppGameContainer container = new AppGameContainer(new Kreations());

           container.setDisplayMode(800,600,false);

         //Make sure the logic updates consistently
           container.setMinimumLogicUpdateInterval(20);
           container.setMaximumLogicUpdateInterval(20);

           container.start();
         } catch (SlickException e) {
           e.printStackTrace();
         }
  }

    @Override
    public void initStatesList(GameContainer gc) throws SlickException {
        this.addState(new MenuGameState());
    }
}

BasicGameState:
package gamestates;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class MenuGameState extends BasicGameState {

    public static final int ID = GameStates.MAIN_MENU.ordinal();

    @Override
    public void init(GameContainer gc, StateBasedGame sbg)
            throws SlickException {

    }

    @Override
    public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
            throws SlickException {
        g.drawString("Hello World", 100, 100);
    }

    @Override
    public void update(GameContainer gc, StateBasedGame sbg, int delta)
            throws SlickException {

    }

    @Override
    final public int getID() {
        // TODO Auto-generated method stub
        return GameStates.MAIN_MENU.ordinal();
    }

    public void enter(GameContainer container, StateBasedGame game) throws SlickException {
          System.out.print("MenuGameState.enter() is called");
       }

}

A: Unless there's code elsewhere that's supposed to call those methods, update() and render() methods of MenuGameState are not called because there are no calls to them.

A: I haven't found the javadoc of the StateBasedGame class, but my guess is that the current state is rendered by the method render() of StateBaseGame. And since you overrode the method to make it do nothing, your state's render() method is never called by any object. Try removing the overridden render() and update() method in your main class.
BTW, in the source file that I found on github, these two methods are final, so it's impossible to override them, which probably indicates that these methods are not supposed to be overridden.


text:
Q: Тип Memo в Firebird Какой тип в Firebird соответсвтует memo и как его объявлять?
A: VarChar
 и указывайте длину
A: Если длина неизвестна или потенциально не ограничена, то blob sub_type text.
Подробно о типе данных BLOB можно почитать в официальной документации Firebird 2.5 Language Reference (Russian), страницы 34-35


text:
Q: CI: Argument Count Error in join 2 tables I'm working on a project & I've encounter with this problem "Argument Count Error". I've checked code by code but did not find anything.
Controller Code :
<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Appointment extends CI_Controller
{
       public function __construct()
       {
              parent::__construct();
              $this->load->model(['appointment_m', 'jadwal_m']);
       }

       public function index($id)
       {
              $dokter = $this->appointment_m->getProfileApp($id);
              $jadwal = $this->appointment_m->getJadwalApp($id);

              $data = [
                     'dokter' => $dokter,
                     'jadwal' => $jadwal
              ];

              // var_dump($data);
              // die;
              $this->load->view('frontend/appointment/appointment', $data);
       }
}

Model Code :
<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Appointment_m extends CI_Model
{
       public function getProfileApp($id = null)
       {
              $this->db->from('tbldokter');
              if ($id != null) {
                     $this->db->where('id_dokter', $id);
              }
              $query = $this->db->get()->row();
              return $query;
       }

       public function getJadwalApp($id)
       {
              $this->db->join('tbldokter', 'tbldokter.id_dokter = tbljadwal.id_dokter');
              $this->db->from('tbljadwal');
              $this->db->where('tbldokter.id_dokter', $id);
              $query = $this->db->get();
              return $query;
       }
}

modal name process :

An uncaught Exception was encountered Type: ArgumentCountError
Message: Too few arguments to function Appointment::index(), 0 passed
  in D:\xampp\htdocs\dental-web\system\core\CodeIgniter.php on line 532
  and exactly 1 expected
Filename:
  D:\xampp\htdocs\dental-web\application\controllers\Appointment.php
Line Number: 12
Backtrace:
File: D:\xampp\htdocs\dental-web\index.php Line: 315 Function:
  require_once

I've search over this site related this type problem but I did not find my problem solution. This problem comes before submit form. Please Help me.
Thank You

A: Your index is need to receiving an ID, did you pass the ID to it? If not, then the error will shown to you.

A: if the $id of the index() function in controller is mandatory, then you have to make sure it always exist. if not, try defined $id = null, so if the $id is absent, you will not get error.

A: Error message clearly says that Argument count is less than arguments required by your index function in your Appointment Controller. To make an argument optional assign some default values to that argument like:

public function index($id = NULL){
  // your code here
}

Now you call this method with or without parameter.
One more thing that you have to know is: index method is the default method of that controller, means if you call your controller in config/routes.php without any method the index method is called by default. Such as:

$route['yourController'] = 'yourController';

http://yourDomain/yourController in this case the index method is called by default.
OR

$route['yourController/(any:)'] =  'yourController/$1';

In this case index method will be called with a parameter.


text:
Q: computed property that changes its value with action in Ember.js I do have a controller that has an action {{loadRight}} that passes  the current model to the controller when I click a button.
When I first load the app, I also use firstElement computed property which pulls the first element from my model array.
Basically what I want to do is create a second computed property which would return the current model that's clicked so that I can use this information in my template.
I created a currentElement computed property however since I suck at javascript I couldn't pass the current model from action method to the computed property. I keep getting model is not defined error.
I would appreciate any help. Below is my controller.
// controller works.js
import Ember from "ember";

export default Ember.Controller.extend({
  firstElement: function () {
    return this.get('model.firstObject');
  }.property('model.[]'),

  currentElement: function () {
    if(!currentModel) {
      currentModel = this.get('model.firstObject');
    }
    return currentModel;
  }.property('model.[]'),

  actions: {
    loadRight: function (currentElement) {
    console.log(currentElement);
    }

  }});

A: You could define property selectedElement (that's clicked). When loadRight fired you could set selectedElement with selection.
Then currentElement is simple computed property, depends on model.firstObject and selectedElement.
export default Ember.Controller.extend({
  firstElement: function () {
    return this.get('model.firstObject');
  }.property('model.[]'),

  selectedElement: null,

  currentElement: function () {
    return (this.get('selectedElement') || this.get(`firstElement`));
  }.property('firstElement', 'selectedElement'),

  actions: {
    loadRight: function (selection) {
      this.set('selectedElement', selection);
      return false; // or something transition logic
    }
  }
});


text:
Q: mysql_real_escape_string strange apostrophe behaviour? I have a form and a user enters eg (note apostrophe at end of string)
My Bday'

Now, I want to strip apostrophes, simple as that... not escape them, not add slashes just get rid of them
Firstly I have the following:
$event_title = mysql_real_escape_string($_POST['event_title']);

echo "

event title is $event_title";

Which results in the following being returned:
event title is My Bday\\\'

Why 3 slashes?
So, then I go ahead and deal with this by using the following:
$event_title = str_replace("'", "", $event_title);

$event_title = stripslashes($event_title);

Then I return it again to check results
echo "

event title is $event_title";

I get the following:
event title is My Bday\

Any ideas what's happening? I simply want to strip apostophes and slashes but somehow it's not happening
magic_quotes_gpc is off by the way
If I don't use stripslashes therefore leaving them in for MySQL to deal with I get the following error:
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'Private',
event_notes = '' where user_event_id = '35'' at line 3

update user_events set event_date = '2012-11-17', event_title = 'My Bday\\\',
event_vis = 'Private', event_notes = '' where user_event_id = '35'

OK, a further EDIT:
I tried this:
$event_title = $_POST['event_title'];

$event_title = str_replace("'", "", $event_title);

$event_title = trim($event_title);

$event_title = mysql_real_escape_string($event_title);

echo "

event title is $event_title";

and I get this:
event title is My Bday\\

I simply want to get rid of apostrophes, clearly something else is going on here but its got me!

A: What's happening is this:
mysql_real_escape_string escapes all the characters that should be escaped by adding a slash in front of a character being escaped. But adding just a slash will lead to storing the character as unescaped within the DB, therefore also the slash must be escaped prior to inserting...
That's why You have My BDay\\\'. If this value is stored into a DB the final result will be My BDay\'.
But when You do str_replace("'", "", 'My BDay\\\''); You will end up with My BDay\\\ and after calling stripslashes on this You will get My BDay\ - that is absolutely correct!
So don't bother with how the string looks like after calling mysql_real_escape_string, just store that value into the DB and after retrieving it You will end up with My BDay' again...
EDIT How You come to just one slash from the three after calling stripslasshes? The function goes from the start of the string to its end and looks for any slash escaped characters to remove the escaping slash. So it finds first two slashes and removes one, but still two remains (the one just processed and the third one), so it processes next two slasshes it finds that will result in just one slash remaining...
If You'd call stripslashes on the string My BDay\\\' - that will lead to My BDay'...
EDIT2 My bad... The next two slashes are added probably because You have magic_quotes_gpc ON - turn that off or call mysql_real_escape_string(stripslashes($string)).

A: One slash to escape the apostrophe, the other to escape the slash that escape the apostrophe.
Internally the mysql interpret the \' how '

A: in your php settings the string_splash setting is ON and that is why when the string is passed from form - it is already excapped...  Now you using mysql_real_escape_string - which excapes "excape character" as well as single quote as well. and that is why three slashes..
Try using this function - which I use a lot
function sanitize( $value )
{
    if( get_magic_quotes_gpc() )
    {
          $value = stripslashes( $value );
    }
    //check if this function exists
    if( function_exists( "mysql_real_escape_string" ) )
    {
          $value = mysql_real_escape_string( $value );
    }
    //for PHP version < 4.3.0 use addslashes
    else
    {
          $value = addslashes( $value );
    }
    return $value;
}

It is not specifically for php 4 or older years... The function works to escape string and make sure it does not double escape it ( which is the question beign asked )
if( function_exists( "mysql_real_escape_string" ) ) - this line escapes if the database connection is available  and
else part of that if condition makes sure it works if database connection is not available and  php 4 support is added benifit only...


text:
Q: What material of core should I use for signal 1Mhz pulse transformer I want to make 1Mhz pulse signal transformer, and I don't know what material should I choose. I found some epcos cores like N49 but it is for power transformers. Also I found some material with low THD but they are all for frequences under 1MHz

A: The lower \$\mu_R\$ cores will support HF signals.  The overall specs of the load, volt-second, inductance, leakage inductance and parasitic capacitance with load capacitance will affect the signal integrity.
You might want to compare your overall specs with these HV gate drive pulse transformers.  They will also have the cores you need if you must DIY.
https://products.pulseelex.com/files/product_files/P883.pdf


text:
Q: Polymer and npm, update to latest version I think this is more an npm than a Polymer question.
I have a quite large Polymer project, which is now up to version 1.3.0 according to bower.json inside the Polymer folder.
I have been "offline" from this project for about 2 months and now I realized that the Polymer framework is 1.6.0
How can I update to Polymer 1.6.0 using npm?
How can I update all existing components already installed in my project?

A: All you need to do is update your package.json to contain the latest Polymer version, like so:
"dependencies": {
    "polymer": "~1.6.0"
}

Then, run npm update --save (see the documentation here) which will find the latest version compatible with ~1.6.0 (e.g. 1.6.1) and save it in your dependencies.
If you're not sure what the latest version is, you can "cheat" and set the dependency to "*" in your package.json, then run npm update --save. This will automatically find the latest version and save it in your package.json.
You might also find npm outdated useful - it will identify outdated dependencies in your package.json for you to upgrade.


text:
Q: Запись составного высказывания в коде Даны высказывания:

*

*Высказывание A: Конь - животное

*Высказывание B: Ночью светит солнце

*Высказывание С: 5 больше 999

*Высказывание D: (100 - 5) равно 95

Записать на языке C# следующие логические выражения(составные высказывания):
logicalExpressionX1 = A И НЕ(B)
logicalExpressionX2 = C ИЛИ D
logicalExpressionX3 = (A И НЕ(B)) ИЛИ B
logicalExpressionX4 = logicalExpressionX1 И С
logicalExpressionX5 = logicalExpressionX1 ИЛИ logicalExpressionX4

Вывести значение каждого логического выражения в консоль.

A: Вы можете сделать вот такую конструкцию, с помощью которой можно решить вашу задачу.
public class StatementTools
    {
        public static string OperatorOR(string text1, string text2)
        {
            return text1 + " или " + text2;
        }
        public static string OperatorAnd (string text1, string text2)
        {
            return text1 + " и " + text2;
        }
        public static string OperatorNot(string text)
        {
            return "не " + text;
        }
    }
    static void Foo()
    {
        string a = "Конь - животное";
        string b = "Ночью светит солнце";
        string logicalExpressionX1 = StatementTools.OperatorAnd(a, StatementTools.OperatorNot(b));
        Console.WriteLine(logicalExpressionX1);
    }


text:
Q: SSRS Textbox Only Displays Partial Data I have a report in SSRS that contains many textboxes that pull data from our Epicor 10 database. One in particular only displays the first 30 characters. In our ERP system, the field format is x(16000) so the user can enter quite a bit of data. The textbox size is definitely large enough to contain more than 30 characters (it's about half a page wide). I enabled the "Can Grow" option, and I've expanded the text box box horizontally and vertically, but still, only the first 30 characters display.
Typically, the text in this field begins with a number (these are shipping comments so it will say, for example, "2 Skids @60 boxes... etc.). That's the only real difference I can find between this particular text box and the other ones on the report that display the entire field value. Am I missing some Option, or do I need to convert the field in some way?
Thanks in advance.

A: Pull up your report in System Management | Reporting | Report Data Definition and check to see if it is a Calculated field limited the number of characters as Hannover Fist has posited. Searching the table Ice.RptCalcField I see a number of out of the box things that limit to x(30), but I don't see anything larger than x(2000). There are couple of DataFields in Ice.ZDataField that are that large, so I am assuming this isn't an out of the box sort of thing.
If the Data Definition field is set to x(16000) try changing it to x(100) and see if that makes a difference. Maybe the value you have is large for the printing framework and it is reverting to some sort of default.
Good luck, I would be interested to see how this turns our for you as we may eventually run into a similar problem.


text:
Q: Wrong dimension received by Tensor Sequential model for 1D CNN model I load my dataset from Pandas dataframe and follow the instructions given by Tensorflow, but i modified it since i have my own train,validation and test dataset. This is my dataframe datatypes and I load it using tensorflow dataset (target is CLASS, RECORD_NAME and MINUTE are not included):
RECORD_NAME        int64
Minute             int64
ShanEn11         float64
DimFractal11     float64
Approx11         float64
                  ...
DimFractal416    float64
Approx416        float64
SampEnt416       float64
D2416            float64
CLASS              int64
Length: 153, dtype: object

So i have 150 * 1 input dimension for my model here and use Binary since the class are 0 and 1:
def GetModel2():
    model = Sequential()
    model.add(layers.Conv1D(filters=64,kernel_size=5,activation='relu'))
    model.add(layers.Conv1D(filters=128,kernel_size=3,activation='relu'))
    model.add(layers.MaxPool1D(pool_size=2,strides=2))
    model.add(layers.Dropout(rate=0.2))
    model.add(layers.Conv1D(filters=128,kernel_size=13,activation='relu'))
    model.add(layers.Conv1D(filters=256,kernel_size=7,activation='relu'))
    model.add(layers.MaxPool1D(pool_size=2,strides=2))
    model.add(layers.Flatten())
    model.add(layers.Dense(150,activation='relu'))
    model.add(layers.Dense(1,activation='softmax'))
    model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), optimizer='adam', metrics=['accuracy'])
    return model

and this is the method how i convert my dataframe for train and validation into model:
def dataset_maker(train,valid):
    trainY = train.pop('CLASS')
    validY = valid.pop('CLASS')
    trainY = trainY.values
    validY = validY.values
    trainX = train.drop(columns=['Minute','RECORD_NAME']).values
    validX = valid.drop(columns=['Minute','RECORD_NAME']).values
    # trainX = np.expand_dims(trainX,axis=-1)
    # validX = np.expand_dims(validX,axis=-1)
    train = tf.data.Dataset.from_tensor_slices((trainX, trainY))
    valid = tf.data.Dataset.from_tensor_slices((validX, validY))
    # return(trainX,validX,trainY,validY)
    return train,valid

for test:
def test_maker(test,nsr_time,sddb_time):
    test_sddb_sel = test[(test['CLASS']== 1) & (test['Minute']== sddb_time)]
    test_nsr_sel = test[(test['CLASS']== 0)].sample(n=len(test_sddb_sel))
    subs = [test_sddb_sel,test_nsr_sel]
    subs =  pd.concat(subs)
    testY  = subs.pop('CLASS').values
    subs=subs.drop(columns=['Minute','RECORD_NAME']).values
    test= tf.data.Dataset.from_tensor_slices((testX, testY))
    return(test)

But when i run this line:
 model = GetModel2()
 model.fit(train, epochs=500, validation_data = (valid))

This error happens:
ValueError: Input 0 of layer sequential_2 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: (150, 1)

I though that my input are correct since i only have 1Dim dataset. Any help are appreciated.
UPDATE
I will explain what i do in dataset maker. Before i build the dataset for train and validation, i need to set which group of data should used for. Since there is two csv contain record of each class (binary 1 and 0), it also contain information about the Record name and Minute. Each record has 30 minute so the structure should be
RECORD_NAME Minute  ShanEn11    DimFractal11    Approx11    SampEnt11   D211    ShanEn12    DimFractal12    Approx12    SampEnt12   D212    ShanEn21    DimFractal21    Approx21    SampEnt21   D221    ShanEn22    DimFractal22    Approx22    SampEnt22   D222    ShanEn23    DimFractal23    Approx23    SampEnt23   D223    ShanEn24    DimFractal24    Approx24    SampEnt24   D224    ShanEn31    DimFractal31    Approx31    SampEnt31   D231    ShanEn32    DimFractal32    Approx32    ... DimFractal49    Approx49    SampEnt49   D249    ShanEn410   DimFractal410   Approx410   SampEnt410  D2410   ShanEn411   DimFractal411   Approx411   SampEnt411  D2411   ShanEn412   DimFractal412   Approx412   SampEnt412  D2412   ShanEn413   DimFractal413   Approx413   SampEnt413  D2413   ShanEn414   DimFractal414   Approx414   SampEnt414  D2414   ShanEn415   DimFractal415   Approx415   SampEnt415  D2415   ShanEn416   DimFractal416   Approx416   SampEnt416  D2416   CLASS
0   16265   1   11.906891   0.381605    0.612757    0.373743    0.383648    11.906891   0.425259    1.577411    1.296275    0.603426    10.906891   0.388828    0.786206    0.539881    0.538828    10.906891   0.163120    0.849461    0.517985    0.490904    10.906891   0.465596    1.603956    1.578086    0.884919    10.906891   0.478893    1.489283    1.335001    0.795363    9.906891    0.443527    1.049104    1.026672    1.053325    9.906891    0.433486    0.845778    ... 0.494621    1.316569    2.000113    1.348125    8.906891    0.559719    1.377016    2.182452    1.356932    8.906891    0.555625    1.319638    2.039932    1.225024    8.906891    0.477939    1.315621    2.035342    1.395533    8.906891    0.441140    1.284476    1.874663    1.249584    8.906891    0.488296    1.320431    2.129360    1.424701    8.906891    0.355288    1.327155    1.933752    1.097245    8.906891    0.418731    1.313926    2.071668    1.383929    0

So i list each record and slice it into proportion 50:20:30 as train-test-validation. For class 0 it has 20 unique record name so the number of dimension for training for class 0 is 10 record30 minutes each 150 row = 300150 and for class  1 is 930150 = 270150.
and the process look like this:
    for w in range(n_exp):
        print('Sequence ',w+1)
        zeros,unos = shufling(zero,uno)
        zero_train,zero_val,zero_test = halfing_ZERO(zeros)
        print('ZERO_TRAIN_VALID_TEST = ',zero_train,zero_val,zero_test)
        uno_train,uno_val,uno_test = halfing_UNO(unos)
        print('UNO_TRAIN_VALID_TEST = ',uno_train,uno_val,uno_test)
        ZERO_tra = zero_data.loc[zero_data['RECORD_NAME'].isin(zero_train)]
        ZERO_val = zero_data.loc[zero_data['RECORD_NAME'].isin(zero_val)]
        ZERO_test = zero_data.loc[zero_data['RECORD_NAME'].isin(zero_test)]
        UNO_tra= norm_data.loc[norm_data['RECORD_NAME'].isin(uno_train)]
        UNO_val = norm_data.loc[norm_data['RECORD_NAME'].isin(uno_val)]
        UNO_test = norm_data.loc[norm_data['RECORD_NAME'].isin(uno_test)]
        train = [ZERO_tra,UNO_tra]
        valid = [ZERO_val,UNO_val]
        tests = [ZERO_test,UNO_test]
        train_dt = pd.concat(train)
        valid_dt = pd.concat(valid)
        test_dt = pd.concat(tests)

where zero and uno represent list of unique record name. The the dataset_maker are called to make train and valid test. Since the testing are quite tricky due i want to test the result for each minutes, the process to create test dataset are recursively done by get all data from record with certain minute label.
so from this process will produce train test and validation data with this same proportion and size:
train = (300*150) for class 1 and (270*150) for class 0 from 10 rec class 1 and 9 rec class 0
valid = (60*150) for class 1 and (60*150) for class 0 from 2 rec both on class 1 and 0
test = (240*150) for class 1 and (210*150) for class 0 from 8 rec class 1 and 7 class 1

A: Tensorflow Conv1D expects input shape as [batchsize, steps, input_dims], and outputs [batchsize, new_steps, filters]. Batchsize can be any integer, often depending on a machine memory. Then your batch will be ``[batchsize, 150, 1]```. That's why you got that error.
Now you use model.fit. model.fit expects params to be x = tensor of [the num of total samples, 150, 1], y=[the num of total samples, 1], and you specify batch_size also
tf.keras.layers.Conv1D
Model.fit
add input_shape at the first layer.
def GetModel2():
    model = Sequential()
    model.add(layers.Conv1D(filters=64,kernel_size=5,activation='relu', input_shape=[150, 1]))
    model.add(layers.Conv1D(filters=128,kernel_size=3,activation='relu'))
    model.add(layers.MaxPool1D(pool_size=2,strides=2))
    model.add(layers.Dropout(rate=0.2))
    model.add(layers.Conv1D(filters=128,kernel_size=13,activation='relu'))
    model.add(layers.Conv1D(filters=256,kernel_size=7,activation='relu'))
    model.add(layers.MaxPool1D(pool_size=2,strides=2))
    model.add(layers.Flatten())
    model.add(layers.Dense(150,activation='relu'))
    model.add(layers.Dense(1,activation='softmax'))
    model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), optimizer='adam', metrics=['accuracy'])
    return model

Be careful about input shape.
def dataset_maker(train,valid):
    trainY = train.pop('CLASS')
    validY = valid.pop('CLASS')
    trainY = trainY.values  # [750,1]
    validY = validY.values  # [?, 1]
    trainX = train.drop(columns=['Minute','RECORD_NAME']).values
    validX = valid.drop(columns=['Minute','RECORD_NAME']).values

    trainX = np.expand_dims(trainX,axis=-1)  # [750, 150] -> [750, 150, 1]
    validX = np.expand_dims(validX,axis=-1)  # [?, 150] -> [?, 150, 1]
    train = tf.data.Dataset.from_tensor_slices((trainX, trainY))
    valid = tf.data.Dataset.from_tensor_slices((validX, validY))
    # return(trainX,validX,trainY,validY)
    return train,valid

 # Make sure you have right shapes. trainX: [750, 150, 1], trainY: [750, 1]
 batch_size=750
 model = GetModel2()
 model.fit(x=trainX, y=trainY, epochs=500, validation_data=(validX, validY), batch_size=batch_size)


text:
Q: How to find out the out-most stacks when `System.StackOverflowException` is raised? In  Visual Studio 2015 for C#, I debug a program. The debugger pauses somewhere and raises System.StackOverflowException:

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll

It means that there is infinite recursion going on.
I want to find out which method is initially called and then leads to the exception, so I turn to the Call Stack window, but there are so many stacks that the out-most stacks  have been truncated off  the Call Stack window:

...
  The maximum number of stack frames supported by Visual Studio
  has been exceeded.

*

*Is there some way to find out the out-most stacks when System.StackOverflowException happens?

*Is there some way to limit the maximum number of stack frames before System.StackOverflowException is raised, so that all the stack frames can  be shown in the Call Stack window?
Thanks.

A:
Is there some way to limit the maximum number of stack frames before
  System.StackOverflowException is raised, so that all the stack frames
  can be shown in the Call Stack window?

Temporary hack: Make the stack frame smaller until you can see the cause.  Then restore the size to default.  There is no project setting for this, but this old trick might still work:
EDITBIN.EXE /STACK:<stacksize> file.exe

Is there some way to find out the out-most stacks when
  System.StackOverflowException happens?

One approach is to use the Trace or Debug class to add logging of all calls to whatever the recursing function function is.  Call this function "Cursed()"  If there are 10 places in your code that call "Cursed()" add a trace to each one before the call:
Trace.WriteLine("Foo calling Cursed()");
...
Trace.WriteLine("Bar calling Cursed()");

You can add any variables you want.
You can see how to use Trace and Debug at support.microsoft.com, "How to trace and debug in Visual C#" - https://support.microsoft.com/en-us/help/815788/how-to-trace-and-debug-in-visual-c
If you look at the debug or trace output you then see what function and values triggered the infinite recursion.
Add more logging, asserts, conditional breakpoints to narrow things more.

A: You can run your program with my Runtime Flow tool (30-day trial) and should be able to see all method calls before the StackOverflowException.


text:
Q: I'm trying to apply the do while loop in my c program login but i dont get it kindly please help me with my problem
#include <stdio.h>
#include <string.h>
int samplepre ()
{
    do {

    char username[3]; // users's input username
    char password[3]; //user's input password
    char choice; // Main menu choice
    char x; // option try again
    char string;
    int i; // for for loop : index

    printf ("\t************\n");
    printf ("\t*Login Menu*\n");
    printf ("\t************\n");

    printf ("Enter your username:"); // The user is ask to input its username
    scanf  ("%s",username);
    printf ("Enter password:"); // The user is ask to input its password
    scanf  ("%s",password);

    if (strcmp(username,"admin") == 0 && strcmp(password,"vdedote") == 0)
    {  // if the condition is true the set of codes will execute
       system ("cls");
       printf ("****************\n");
       printf ("*WELCOME ADMIN!*\n");
       printf ("****************\n");
       system ("PAUSE");
       //printf ("\n");
       printf ("What may I be of service sir?\n");
       printf ("************\n");
       printf ("*MAIN MENU:*\n");
       printf ("************\n");
       //printf ("\n");
       printf ("[A] Remove Vowels\n"); // The user will be asked of his own choice
       printf ("[B] Remove Entered Character\n");
       printf ("[C] Arithmetic\n");
       printf ("Select your choice:");
       scanf  ("%s",choice);

   }
    else
    {     // if the user inputs wrong data
         // x = option try again
     printf ("****************\n");
     printf ("*ACCESS DENIED!*\n");
     printf ("****************\n");
     printf ("Would you like to try again <Y/N>");
     scanf  ("%s",x);
    }
    while (strcmp(username,"admin") == 1 && strcmp(password,"vdedote") == 1);
}

A: *

*You are missing a } before the while.

*You need to move username and password out of your loop.

*You shouldn't use scanf http://c-faq.com/stdio/scanfprobs.html

*You are not allocating enough space for your username and password
Maybe you should read a tutorial about proper reading first?
The answer to this question looks pretty nice:
how to read string entered by user in c

A: You're missing a closing brace } just before the while.
Once you've fixed this syntax error, be sure to understand that strcmp returns zero if the strings are equal.

A: Because you are not closing the do !!
do{.......}
while(...);

A: thanks for your question,

*

*After you corrected the syntactical errors (braces)

*After you have made the indentation look better

*After you have understood the idea of strcmp

*After you have understood that doing it this way is VERY dangerous

then and only then:
should you end the do .. while .. loop with a conditional statement where it is checked IF the user is NOT the admin, then you repeat!
    while (strcmp(username,"admin") != 0 && strcmp(password,"vdedote") != 0);

so the loop knows it needs to repeat because it is not the admin with the right password login in!

A: The thing is strcmp() returns 0 when the strings are equal.

int strcmp(const char *s1, const char *s2);

RETURN VALUE
The strcmp() and strncmp() functions return an integer less than,
       equal to, or greater than zero if s1 (or the first n bytes thereof)
       is found, respectively, to be less than, to match, or be greater than
       s2.


text:
Q: UI for displaying large amounts of hierachical data I have large amounts of data with a hierachical structure of arbitrary depth. I'm looking for a solution to display the data within a responsive single page application, so that the user can select any element within the hierarchy.
Right now I'm using a typical tree-control:

Since I have many data elements the usability of such a tree-control is really bad on devices with a small screen. Do you have any suggestions concerning the Layout of the User Interface that enriches the usability?

A: An off-canvas menu is one option that could work for you.
On mobile it will give you much more screen space to display your links. It's becoming a more popular option on desktop now as well, or you could have off-canvas navigation on mobile and your tree menu on desktop.
There are plenty of good off-canvas solutions available, I've used jQuery.mmenu on a single page page site with good results. It looks good, it's well documented, and it has plenty of configuration options.
Hope this helps!


text:
Q: ExcelDataReader wrong decimal number (non formatted) I've been using ExcelDataReader to get some .xlsx files and convert them to DataSet with the AsDataSet() method.
But, I have a big problem. Inside a column on Excel we have a value '2061,95' (with ',' as decimal separator, because I'm from Brazil).
I renamed the .xlsx to .zip and extracted the files and the value is '2061.94899999'.
But inside my software there is a rule that a number can be with only 2 decimal places and I can't use round.
Does anyone have an idea?


text:
Q: Discord.py: How to pin a post made by a webhook? Message= await webhook.send("Test message to pin")
await Message.pin()

But I get a str in return from webhook.send. How can I get a message type so I'm able to pin it?
Thank you in advance.

A: If you read the documentation. You will see that you need to add the following parameter: wait=True (when sending through a webhook). This will return the message. If you dont do this it will return None as explained in the doc.
Thus what you need to do:
Message = await webhook.send("Test message to pin", wait=True)
await Message.pin()


text:
Q: How to Return Specific Values from a Filter in Javascript I have an object array
animals[
 {id:1, name:"cat"},
 {id:2, name:"dog"},
 {id:3, name:"fish"}
]

and i have another
selected = [1,2]

I want to have a return as a string of selected ones:
"cat, dog"

I currently know how to filter
   const selectedAnimals = selected.filter(function(e) {
      return animals.find(o => o.id == e);
    })

But this returns the list of ids. How would I rerturn the list of names and in string format? Would I need to use reduce or can i do it with the filter option?

A: You have to use filter() on your animals array. Can use includes() to check if array contains given value.
var selectedAnimals = animals.filter(animal => selected.includes(animal.id));

Live Example:

var animals = [
 {id:1, name:"cat"},
 {id:2, name:"dog"},
 {id:3, name:"fish"}
];

var selected = [1,2];

var selectedAnimals = animals.filter(animal => selected.includes(animal.id));

console.log(selectedAnimals);

A: You are using the filter function backwards.  You should use filter on the animals array. Try this:
const selectedAnimals = animals.filter(function(e) {
   return selected.find(id => e.id == id);
})

This will give you a list of animal objects with ids, then you can loop over that and extract the name if you want to create an array of just the names.

A: You can archive that by doing the following
let animals = [
 {id:1, name:"cat"},
 {id:2, name:"dog"},
 {id:3, name:"fish"}
]

let selected = [1,2]

const selectedAnimals = animals.filter(e =>(
      selected.includes(e.id))
    )

and selectedAnimals should have [ {id: 1, name: "cat"}, {id: 2, name: "dog"} ]
Alternatively, you can use a map but then you will end up with the following.
let selectedAnimals = animals.map((e,t) => { if(selected.includes(e.id)) return e.name; else return null} )

["cat", "dog", null]


text:
Q: Overlay over navigation bar in Android 4 I am struggling with this despite going through some samples...
I want to overlay over the android navigation bar - I have tried the following code...
s_translucentParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_FULLSCREEN
                ,
                PixelFormat.TRANSLUCENT);

But of course, that fills a window which does not cover the navigation bar...  after doing some reading, I tried the following (from Draw bitmaps on top of the Navigation bar in Android) ...
w = new android.view.WindowManager.LayoutParams(-1, -1,0,-navigationBarHeight(),    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_FULLSCREEN
|WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
|WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
|WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
|WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, Pixel.Translucent);
f.addView(v, w);

But this does not overlay for me despite me altering the window size ... it just doesn't overlap the navigation bar :(
I want to make something like the following...
https://play.google.com/store/apps/details?id=com.haxor&hl=en_GB
This does not display above the navigation bar, but below it (which is fine for my needs)
Can anyone help me?  thanks.

A: What you see on screenshots at your Play Market link is Android KitKat's (API 19) Translucent Decor.

You can now make the system bars partially translucent with new
  themes, Theme.Holo.NoActionBar.TranslucentDecor and
  Theme.Holo.Light.NoActionBar.TranslucentDecor. By enabling translucent
  system bars, your layout will fill the area behind the system bars, so
  you must also enable fitsSystemWindows for the portion of your layout
  that should not be covered by the system bars.
If you're creating a custom theme, set one of these themes as the
  parent theme or include the windowTranslucentNavigation and
  windowTranslucentStatus style properties in your theme.

Your translucent Activity should be declared in AndroidManifest.xml like:
<activity android:name="com.example.app.TranslucentActivity"
          android:theme="@android:style/Theme.Holo.NoActionBar.TranslucentDecor" />

Other way you might want to go is just hiding Navigation Bar with API 14+:
View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
              | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

Or you might want to use Immersive Full-screen Mode with API 19:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
}

Take a look at Using Immersive Full-Screen Mode and Hiding the Navigation Bar for more detailed information.


text:
Q: How can I limit CD drive speed while on the live CD to avoid drive noise? I sometimes disconect my harddisks for the weeks while only using the internet and I use the Ubuntu Live CD. But every time it needs something while in live desktop it accelerates and makes a lot of noise, also the acceleration takes too long. I want lower drive speed than acceleration lags, because acceleration lags stop me completly exactly when I need something.
How can I lower the CD drive speed, say to maximum 16x, without restarting?
I can't restart because I only use the CD drive, no harddisks, no flash disks, no network disks.
Edit:
No USB drives.
Setcd does not work for the live session.

A: well, if you don't want to buy a pendrive, do the following lines:
sudo apt-get install setcd
setcd -x 1

Change -x 1 to -x [number]. Higher the number, faster the drive.
But you should remember, that CD works on high speed for a reason. Ubuntu may become slow, when you do that.

A: The easiest thing to do is use the supplied USB creator tool or Unetbootin to create a bootable USB drive, which is exactly the same thing as using a Live CD, only without the drive noise.


text:
Q: Why is the first part of equation i.e $v_0(t_f-t_0)$ not considered while plugging real life problem to it?
Why is the speed*time stuff is not present while we look for the distance?

I got it from this (physics for dummies)

A: On page 68 the paragraph headed Calculating displacement given a time and acceleration includes the text:

Assume that you're on your traditional weekend physics data-gathering expedition. Walking around with your clipboard and white lab coat, you happen upon a football game. Very interesting, you think. In a certain situation, you observe that the football, although it starts from rest, has three players subjecting forces on it, as you see in Figure 5-4.

The football starts from rest so $v_0 = 0$.


text:
Q: How to set data to an empty QTableView cell Connection conn;
model = new QSqlQueryModel(this);
QString query;
model->setQuery(query, conn.db);

ui->tableView->setModel(model);

The cells I want to populate with data are in column that I added myself doesn't belong to db
of the model.

A: QSqlQueryModel is read-only. Write your own custom model, or fill QStandardItemModel with items you got from QSqlQueryand add your own items.


text:
Q: Timeout on tests using working POST route with actix-web I've successfully migrated a web application from Rocket to actix-web. By utilizing postman, I've verified that the same requests yield the same responses. Migrating the tests however has been proven to be a little bit more tricky.
My POST requests time out when running cargo test, even though the application just accepts and returns the expected response just fine when running cargo run.
#[cfg(test)]
mod test {
    use actix_web::{client, http, test, App};

    #[test]
    fn main() {
        let mut ts = TestSuite::new();

        assert!(ts.get_request("/health").status().is_success()); // works

        let filter_test_body =
            r#"{"key_1":[{"id":"a string"},{"id":"another string"}],"int_1":100}"#;
        assert!(
            ts.post_request("/post_route", filter_test_body)
                .status()
                .is_success()
        ); // times out while actual app returns success with same payload within a few ms
    }

    fn create_app() -> App<project_name::AppState> {
        // {...} some initialization and defining app_state

        return App::with_state(&app_state)
            .resource("/health", |r| {
                r.method(http::Method::GET).f(project_name::health)
            })
            .resource("/post_route", |r| {
                r.method(http::Method::POST)
                    .with(project_name::post_route_handler)
            });
    }

    struct TestSuite {
        server: test::TestServer,
    }

    impl TestSuite {
        pub fn new() -> TestSuite {
            TestSuite {
                server: test::TestServer::with_factory(create_app),
            }
        }
        pub fn get_request(&mut self, endpoint: &str) -> client::ClientResponse {
            let request = self.server
                .client(http::Method::GET, endpoint)
                .finish()
                .unwrap();

            self.server.execute(request.send()).unwrap()
        }
        pub fn post_request(&mut self, endpoint: &str, body: &str) -> client::ClientResponse {
            let request_payload: other_lib::request::RequestPayload =
                serde_json::from_str(body).unwrap();
            let request = self.server
                .client(http::Method::POST, endpoint)
                .header(http::header::CONTENT_TYPE, "application/json")
                .json(request_payload)
                //.body(body.to_string())
                .unwrap();

            self.server.execute(request.send()).unwrap() // thread 'test::main' panicked at 'called `Result::unwrap()` on an `Err` value: Timeout'
        }
    }
}

In contrast, here's the POST test from the codebase utilizing Rocket.
#[test]
fn test_filters() {
    let client = mount_test_rocket(); // getting access to the test server (rocket::local::Client)
    let mut response = client.post("/post_route").header(ContentType::JSON)
        .body(r#"{"key_1":[{"id":"a string"},{"id":"another string"}],"int_1":100}"#).dispatch();
    assert_eq!(response.status(), Status::Ok);
    // + more assertions looking into the actual response body
}

A: The solution is a simple one. Turns out, the request does really time out on cargo test. A potential solution would be to get in the timeout method into the chain, or much simpler in my case, turn on the same optimization that I use when running the application by passing in the --release flag.


text:
Q: Problems linking to library after Ubuntu upgrade After recently using a new Ubuntu installation (was 11.04, is now 12.04), my project seems to fail linking correctly. I try to link to the API of LuxRender, an open-source rendering library. My code is written in C++ and compiled using g++.
I've already spent a lot of time on this problem and encountered a few solutions to problems with similar symptoms. However, I did not find a solution yet so I came here to ask for help.
The sample code, testmain.cc:
#include <lux_api.h>

int main (int argc, char* argv[]) {
    lux_instance* lux = CreateLuxInstance("Test");
    DestroyLuxInstance(lux);

    return 0;
}

The problem
$ g++ -c -o testmain.o testmain.cc -Wall -g -pedantic -I/home/taz/lux/lux-build/lux/cpp_api -I/home/taz/lux/lux-build/lux/core -I/home/taz/lux/lux-build/lux/core/queryable
$ g++ -o testmain testmain.o -llux
testmain.o: In function `main':
/home/taz/Documents/msc/test/testmain.cc:4: undefined reference to `CreateLuxInstance'
/home/taz/Documents/msc/test/testmain.cc:5: undefined reference to `DestroyLuxInstance'
collect2: ld returned 1 exit status

Firstly, note that while other people have linking problems since Ubuntu 11.10, the link order is correct (-llux after testmain.o) so that's not the problem.
Secondly, the CreateLuxInstance and DestroyLuxInstance functions are exported using C-style naming (with extern "C") in lux_api.h. I include the header file where this happens so the compiler should be aware of it, right? (Checked the pre-processor output using g++ -E.) The functions do correctly appear in the library so they should be available to the linker:
$ nm -s /usr/local/lib/liblux.so | grep LuxInstance
000000000008c440 t CreateLuxInstance
000000000008c4d0 t DestroyLuxInstance

Thirdly, I have compiled (and after upgrading, recompiled) this library from source using the maintainer's cmake files. But even when I grab a compiled version from their site, I get the same problems. In both cases, the library matches the included header(s).
Lastly, I know that the correct library file gets used by passing -Wl,--verbose to see which library files the linker actually uses.
What am I missing here?
Some versions:
$ ld --version
GNU ld (GNU Binutils for Ubuntu) 2.22
Copyright 2011 Free Software Foundation, Inc.
This program is free software; you may redistribute it under the terms of
the GNU General Public License version 3 or (at your option) a later version.
This program has absolutely no warranty.

$ g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ uname -a
Linux linuxtaz 3.2.0-24-generic #37-Ubuntu SMP Wed Apr 25 08:43:22 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

$ lsb_release -irc
Distributor ID: Ubuntu
Release:    12.04
Codename:   precise

Edit:
The problem turned out to be in de LuxRender distribution when building luxShared, the shared library to be used with the Lux api. Why this problem turned up after an Ubuntu upgrade is still a mystery for me, but for others struggling with this problem, here is my "solution":
The distribution I wanted to build is v1.0-RC1. In the file cpp_api/export_defs.h I added the following lines:
#ifdef LUX_DLL
 #define CPP_API __attribute__ ((visibility ("default")))
#endif

The compiler complains about CPP_API being declared doubly but I ignored that. Now the library builds with publicly available API functions:
$ nm ./liblux.so | grep LuxInstance
000000000008c6c0 T CreateLuxInstance
000000000008c750 T DestroyLuxInstance

A:
The functions do correctly appear in the library so they should be available to the linker:

$ nm -s /usr/local/lib/liblux.so | grep LuxInstance
000000000008c440 t CreateLuxInstance
000000000008c4d0 t DestroyLuxInstance

No, they do not. The t symbols are local (can't be used outside the library in which they are defined). You want T (global) symbols.
If these symbols are exported by lux_api.h (which they appear to be), then the library has not been properly built. Open a bug for your distribution.


text:
Q: $\forall r>0$ small enough $f(B(x_0,r))$ doesn't contain a ball around $f(x_0)$ Let $k<m$ and $f:\mathbb{R}^k \to \mathbb{R}^m$  be continuously differentiable around $x_0$. with $\operatorname{rank}Df(x_0) = k$.
Then $\forall r>0$ small enough $f(B(x_0,r))$ doesn't contain a ball around $f(x_0)$.
My attempt is the following:
Since $f$ is onto its image $\operatorname{Img}(f) \subset \mathbb{R}^m$ of degree at most $k$. Since $\operatorname{rank}Df(x_0) = k$, around $x_0$ the image of $f$ is a subset of $\mathbb{R}^m$ which is of dimension $k$. That is, around $x_0$ $f$ is injective (by the inverse function theorem).
The inverse function theorem applies for functions from $\mathbb{R}^k$ to itself, is this a legitimate use of this theorem, thinking of the image as a $k$ dimensional subset of $\mathbb{R}^m$? If so how do we show this?
Letting $U$ be the environment in which $f$ is injective, we take $r>0$ so that $B(x_0,r) \subset U$. If $\exists \delta > 0$ s.t $B(f(x_0),\delta) \subset f(B(x_0,r))$ then since $\dim(B(f(x_0),\delta)) = m$ we get $m \leq k$, in contradiction.
I'm not sure the use of the inverse function theorem is correct (due to the fact the image is in $\mathbb{R}^m$).
And also the second part, couldn't I have concluded that without $f$ being injective in $U$?

A: HINT: Suppose $df(x_0)=\begin{bmatrix} I_k \\ 0 \end{bmatrix}$. Consider $g\colon\Bbb R^k\times \Bbb R^{m-k}\to\Bbb R^m$ given by $g(x,y) = f(x)+(0,y)$.

A: Fix an $x$ where derivative is nonsingular. Notice that $Df(x)(\mathbb{R}^k)$ is a linear $k$-dimensional subspace of $\mathbb{R}^m$. Near the point $x$, $f$ is very close (little $o$ - close) to the derivative map. Thus, projection onto the affine plane $f(x) + Df(x) (\mathbb{R}^k)$, which is a copy of $\mathbb{R}^k$, we end up with a map between same dimensional Euclideans. Derivative agrees with the original derivative, hence is nonsingular. Now, we are in a position to impose IFT. If projection of $f$ is injective then we deduce that image of $f$ is (locally) $k$-dimensional.
For detailed argument refer to https://mathoverflow.net/a/323429/121665 .


text:
Q: VBscript for adodb query I need to add a few lines to our billing system, and I don't know enough about the syntax of this call.  Can someone tell me what the zero's in the first line of this query means?
  strSqlStmt = strSqlStmt & "SELECT Trim(users.PILastName & ' ' & users.PIFirstName), 0, 0, 0, 0, Count(plab.billing), 0, 0, 0 "
  strSqlStmt = strSqlStmt & "FROM plab, pform, users, userinfo "
  strSqlStmt = strSqlStmt & "WHERE userinfo.PI=users.PI "
  strSqlStmt = strSqlStmt & " AND UCase(users.location) ='S' "
  strSqlStmt = strSqlStmt & " AND plab.sampleid=pform.sampleid "
  strSqlStmt = strSqlStmt & " AND plab.email=userinfo.email "
  strSqlStmt = strSqlStmt & " AND plab.finisheddate Between " & dtmRange & " "
  strSqlStmt = strSqlStmt & " AND plab.finished=True "
  strSqlStmt = strSqlStmt & " AND plab.billing = 1 "
  strSqlStmt = strSqlStmt & "GROUP BY Trim(users.PILastName & ' ' & users.PIFirstName) "

A: It's just static (constant) values 0 return in positions (columns) specified from SELECT statement
Here is a SQLFiddle example


text:
Q: Recording with Camera2 API without using MediaRecorder In my Android application, I need to capture camera images continuously and keep sending them over the network for remote viewing.
I have looked at Camera2 recording sample. It seems this code relies on MediaRecorder class. However, in my case, I just need to capture raw images as fast as possible, encode it in a specific way, and send it over the network.
Looks like the central concept of Camera2 API is that it requires a Surface class. Is it possible to create a pseudo-surface class and somehow attach to it such that the images can be captured continuously? Or, is there a better way? Regards.

A: You can use an ImageReader if you just want ByteBuffers of uncompressed YUV data.
If you do want to encode the frames before sending them over the network, you can use a MediaCodec (which can give you a Surface) connected to the camera to efficiently encode the frames before sending them to the destination. That's assuming the kind of encoding you want is available on the device.
The latter is what most video chat apps do, whenever possible.


text:
Q: What's the maximum file transfer speed over WiFi 802.11g? What's the maximum transfer speed you get, (or I can get) for files transfer between two wifi-connected computers ?
Im on computer A  trying to copy a big file from computer B, they are side by side (on adhoc network) and I can't get more than 800 KB transfer rate.
Both adapters have relatively the same configuration:

*

*Wireless mode set to IEE 802.11g

*QoS (Quality of Service) enabled

*Power output set to 100%

*Rate set to 54

*some enhancements like Xpress mode, Optimize brandwith are enabled (and they don't make changes)

*Other settings set to defaults

Is that normal ? if so, what does 54 Mb/s mean ? I should ask : how to get my ~7Mb ?
PS: the computer B Wifi adapter is a USB RTL8187 Wifi adapter.

A: Mb/s means megabits per second.  To convert to megabytes, you simply divide by 8, since there are 8 bits in a byte.
So 54Mb/s = 54Mb/s * 1Mb/8MB = 6.75MB/s
So you can theoretically cap out at just under 7 megabytes per second on 802.11g. :)

A: This source is very handy in comparing the various throughput's of different networking media. As they note, depending on the technology there can be a large difference between the stated raw physical layer speed, and the actual payload throughput.
For 802.11g they list a maximum throughput of 3.1 MB/s
Also, note that 802.11g connections can actually get worse if you place the peers too close to each other. Not all manuals list this, but try keeping both machine at least 20 centimeters apart.

A: You describe the transfer between two computers, but please be aware that the data has to travel from computer A to the router first and then is send from router to computer B. If you want to avoid this, than you have to set up a network on the first computer and then join the network with the second computer or use peer networking. And we did not get into details of disk and computer and router speed here...
Also, 54Mbit is the "Marketing Speed", the speed of protocol frames send out, not the speed of the data bits. Rule of thumb is, that the fastest over-air transfer you can get is half the speed, e.g.
- where the disk is connected to the router itself is 20-25 Mbit/s
- where you have computer - router - computer divide again by two, e.g. 10-12 Mbit.
(File copy on from my USB drive connected to a 300n router yields 5.4 MB/s (43.2Mbit/s))

A: When working with one router (and this router has only one radio), then the two computers will have to share the bandwidth between each other.
For example, you have 6 MB/s bandwidth. Computer A is using half and computer B is using the other half or can drop to 3 or 2 MB/s.
If you have a multi radio (MIMO) router then the transfer rates can increase. The best scenario for transferring would be Ethernet-router-Ethernet between computers, allowing for either 100Mbit transfers or Gigbit networks with 1000Mbit transfers.

A: Unless the computers are connected by an ad-hoc wireless network, it is the distance between the computer and the access point that is important.
54 Mbps is a theoretical throughput, which is roughly equivalent to 6,75MB/s. So you can expect up to 6,75MB/s as network bandwidth.
But when you are transferring files, the bandwidth is not fully used for transfer because of:

*

*Wireless control frames

*Network overhead (IP headers)

*File Transfer Protocol overhead

*Packet loss

*Interference and retransmission

At the end, the best you can expect is around 4MB/s in real transfer rate with a light protocol (like HTTP).

A: Slow network file copying in Windows 7 can be caused by Remote Differential Compression.

Remote Differential Compression (RDC) allows data to be synchronized with a remote source using compression techniques to minimize the amount of data sent across the network.
[…]
There seems to be a problem with this Windows 7 and disabling this feature resolves the problem with slow file copy performance.
To disable Remote Differential Compression:

*

*Click Start – Control Panel – Programs – Trun Windows features on or off

*Uncheck "Remote Differential Compression" and click OK.

*Restart the computer and you should see an improved performance with copying files.

A: I think your router is the limit, I have an old asus 54G (I think it is WL-520) and the max speed is 1MB/s, I tried other router and get 2MB/s. With 54g I doubt you will reach 2+MB/s

A: My Netgear R6250 gives download speeds of over 30mb/s. This does seem pretty close to the 'formula' of LinkSpeed (Mbps) * 0.03 given by a poster on 30 Oct 2014. I see he has been given a negative 2 score. Seems a bit unfair.
File transfer from my laptop (Intel dual band wireless AC 7260 card) to an external drive connected to the routers USB 3 port is around 20 Mbps at a distance of 3m with the router partly hidden by an LG 42in TV (I can just see the top 2 in above the tv).
Curiously moving the router to different position, in front of the TV, didn't improve the speeds so I put it back as the Mrs thinks it is more tidy.
So I would say that as a rough guide 0.03 * linkspeed = real world download speed is reasonable.

A: In my real world experiment with various wifi link speed between 12Mbps to 300Mbps i derived the below formula
Aprox Download speed (MBps)= LinkSpeed (Mbps) * 0.03
Example if your link speed is  54Mbps then your download speed is 54*0.03=1.62(MBps)
Rest of the data are used for wifi over head because of other wifi networks around you.


text:
Q: Finding the Dim of a matrix $A $ such that $AC = 0$
Hi,
So the answer that is given to this problem is $n(n-1)$, which doesn't make a lot of sense to me.
Take for example a $3\times3$ matrix:
$$
A=\begin{bmatrix}
a_{11} & a_{12} & a_{13} \\
a_{21} & a_{22} & a_{33} \\
a_{31} & a_{32} & a_{33} \\
\end{bmatrix}
$$
$$
A C=\begin{bmatrix}
c_1\times a_{11} + c_2\times a_{12} + c_3\times a_{13} \\
c_1\times a_{21} + c_2\times a_{22} + c_3\times a_{33} \\
c_1\times a_{31} + c_2\times a_{32} + c_3\times a_{33} \\
\end{bmatrix}
$$
If $C_1,C_2 $or $C_3 = 0$ then dim($A$) can be  $0,1,2,3 $
If $C_1$ and $C_2 = 0$ them Dim($A$) can be $0,1,2,3,4,5,6$
etc.
If $C_1= C_2 = C_3 = 0$ Dim($A$) can be $9$
Where am I going wrong?

A: We can think at an $ n \times n $ matrix $A$ as an element of a vector space $V$ of dimension $n^2$. We can figure this thinking at $A$ as a set of $n$ rows $\mathbf{a_i}$ each of them have $n$ independent elements $a_{ij}$, so that matix can be expressed as a linar combination that have as coefficients these $n^2$ numbers and as basis the $n\times n$ matrices that have only one entry $=1$ and all other entries null.
Now, your question asks what is the dimension of the subspace of $V$ of all matrices $A$ such that $A\mathbf{c}=0$ for any $c$.
This means that for each row we can chose $n-1$ entries, but the last entry $ a_{in}$ is determined by the condition :
$$
c_na_{in}=-\sum_{j=1}^{n-1}a_{ij}c_j
$$
so for each of the $n$ rows we can chose only $(n-1)$ indpendent values, and the dimension of the subspace is $n (n-1)$.

In your example you have to consider $c_1,c_2,c_3$ all $\ne 0$ and you can see that:
$$
c_1\times a_{11} + c_2\times a_{12} + c_3\times a_{13}=0
$$
gives $a_{13}$ as a function of the other elements...and so one for the other rows.....


text:
Q: Which quantity is greater, $\frac{x^2}{y+\frac1y}$ or $\frac{y^2}{x+\frac1x}$? $x \gt y$, $ xy \neq 0$
A= $ x^2\over {y+{1\over y}}$
B= $ y^2\over {x+{1\over x}}$
Options:
1) Quantity A is greater.
2) Quantity B is greater.
3) The two quantities are equal.
4) The relationship cannot be determined from the given information.
By taking $x=2, y=1 $, I get $A\gt B$ , Thus options 2 and 3 are eliminated.
By taking$ x=2, y=-1$ , I get $B\gt A$ , Thus option 1 is eliminated.
So answer is option 4.
But I am not satisfied with this solution by taking particular values of $x$ and $y$.
Is there any other method to deal with this question?
What should be proper tag for this?
I think it should be comparision but that is not available in tag list.So please edit it.

A: Suppose I compute the difference $A-B$ and see if it is always of one sign.
$$\begin{align}A - B &=\frac{x^2}{y+1/y} - \frac{y^2}{x+1/x}\\
&=\frac{yx^2}{y^2+1} - \frac{xy^2}{x^2+1}\\
&=\frac{xy\left(x(x^2+1)-y(y^2+1)\right)}{(x^2+1)(y^2+1)}\\
&=\frac{xy(x-y)(x^2+xy+y^2+1)}{(x^2+1)(y^2+1)}\\
&=\frac{xy(x-y)\left((x+y/2)^2+3y^2/4+1\right)}{(x^2+1)(y^2+1)}\end{align}$$
Every term in the last expression is positive but the term $xy.$ Therefore $$A > B \text{ if and only if } xy > 0.$$

A: If D really is the true answer, then supplying counterexamples to every other claim is the only way to prove it. And there is no shame in doing it that way.

A: A nice approach is as follows: note first of all that $x + 1/x$ is positive if $x$ is positive and negative if $x$ is negative. Now, if $x$ and $y$ have the same sign, then
$$
A > B \iff\\
\frac{x^2}{y+1/y} > \frac{y^2}{x+1/x} \iff \\
x^2(x + 1/x) > y^2(y + 1/y) \iff \\
x^3 + x > y^3 + y
$$
Note, however, that $f(x) = x^3 + x$ is an increasing function.  So, $x^3 + x > y^3 + y \iff x > y$.  So, $A > B \iff x > y$
On the other hand, if $x$ and $y$ have opposite signs, then
$$
A > B \iff\\
\frac{x^2}{y+1/y} > \frac{y^2}{x+1/x} \iff \\
x^2(x + 1/x) < y^2(y + 1/y) \iff \\
x^3 + x < y^3 + y \iff\\
x < y
$$
So, it suffices to take any positive values $x<y$, then the values $-x,y$.

A: Informally, I think you should be able see that as $x$ and $y$ both increase towards positive infinity, A is larger. As $x$ and $y$ both approach negative infinity, A is smaller.
You can show this by letting $(x, y)>0$, and $x = ay$ for $a > 1$. Then the opposite for the negative side


text:
Q: Filter list of dictionaries by upper/lower limit on values I have a list of dictionaries that I am trying to write a filter function for. The parameters to filter by will be given as a dictionary where the keys will be strings (matching the keys in the list of dictionaries to be filtered) and the values will be a list with an upper and lower limit.
Example list of dictionaries to be filtered:
test_list = [{'hello':1, 'goodbye':4}, {'hello':7, 'goodbye':6}, {'hello': 4, 'goodbye': 2}]

Example filtering parameters:
params = {'hello':[1, 6], 'goodbye':[5, 8]}

The function I've written is as follows:
def filter_list(target_list, **kwargs):
    filtered_list = target_list
    for k,v in kwargs.items():
        for target in filtered_list:
            if target[k]<v[0] or target[k]>v[1]:
                filtered_list.remove(target)
    return filtered_list

For some reason the second parameter is not being checked, and the output I get is:
filter_it = filter_list(test_list, **params)
print(filter_it)

>>[{'hello': 4, 'goodbye': 2}]

Why is this? By my reckoning none of the items in the list of dictionaries should pass the criteria. But if I change the parameters to:
params = {'hello':[1, 8], 'goodbye':[5, 8]}

The output is now:
>>[{'hello': 7, 'goodbye': 6}]

The real data this is going to be used on is a list of about 2500 dictionaries, each having about 45-50 key:value pairs. I need to be able to filter by an arbitrary number of parameters, as I won't always want to specify upper and lower limits on each, hence why I'm not hard-coding a comparison with each parameter.
Thanks in advance for all/any help!

A: Is this what you are looking for?
result = list(filter(lambda x: all(lower < x[key] < upper
                                   for key, (lower, upper) in params.items()),
                     test_list))

A: You have a issue in this peice of code:
for target in filtered_list:
      if target[k]>=v[0] and  target[k]<=v[1]:
            filtered_list.remove(target)

You are removing items from iterable Type which prevent you from certain loops... this is a way to filter a list you better do something like this:
filtered_list = [target for target in filtered_list if target[k]<v[0] or target[k]>v[1]]

A: You already got the answer, so I just give some additional explanation for you.
First, your code is deleting an item from a list while iterating over the list. So it will ignore some items. For example, when you delete the second item of a list. Then it will get the fourth item next loop.
I have modified your original code, so you can understand what it should be.
First, you can use copy instead move.
def filter_list_with_copy(target_list, **kwargs):
    filtered_list = []
    for target in target_list:
        all_satisfied = True
        for k, v in kwargs.items():
            if target[k] < v[0] or target[k] > v[1]:
                all_satisfied = False
                break
        if all_satisfied:
            filtered_list.append(target)
    return filtered_list

Second, you can use while instead for. Then you can control your loop index.
def filter_list_with_while(target_list, **kwargs):
    filtered_list = target_list
    for k, v in kwargs.items():
        filtered_index = 0
        filtered_list_length = len(filtered_list)
        while filtered_index < filtered_list_length:
            target = filtered_list[filtered_index]
            if target[k] < v[0] or target[k] > v[1]:
                filtered_list.remove(target)
                filtered_list_length = len(filtered_list)
            else:
                filtered_index += 1
    return filtered_list


text:
Q: KML. Google Map V3. Performance. Labels i can not find answers on my questions in google, i hope for sharing your experience with me.
I am going to use KML in Google Maps. My elements are polygons, icons. Also i have to write and rotate text inside polygons, i know KML does not support this element type i am going to use something like ELabel extension with some modifications.
My questions are:
1) What is faster either use nature Google KML Processor + ELabel or the third-party KML Processor + Elabel ?
2) Are there alternative ways to get my task ?
Thanks.

A: ELabel is for Maps API V2. Since that's been deprecated, you should use Maps API V3 instead. If you do use Maps API V3, you can capture the mouse click on the KML layer and create your own infowindow, showing it the way you want. Here's more information:
http://code.google.com/apis/maps/documentation/javascript/layers.html#KMLLayers