text:
Q: waypoints sticky not initializing OK, I'm  sure this is a simple problem, but I'm pulling my hair out.
I'm trying to make the element .subheads_wrapper sticky on my page.
I've put the latest waypoints files under Inetpub\wwwroot\includes\waypoints-master.
My page is in Inetpub\wwwroot\mypage\index.php
In the header, I've attached the proper files I think:
<script src="../includes/waypoints-master/lib/jquery.waypoints.min.js"></script>
<script src="../includes/waypoints-master/lib/shortcuts/sticky.min.js"></script>

css:
.stuck {
  position:fixed;
  top:0;
}

jquery:
var sticky = new Waypoint.Sticky({
     element: $('.subheads_wrapper')[0]
});

But I keep getting the error:

Waypoint.Sticky is not a constructor

What am I doing wrong?

A: I ended up recoding my page and just using the jquery waypoint function:
$('#screen2').waypoint(function(direction) {
           if (direction == 'down') {
            $('.freeze_column').css({'position':'fixed'});
            }
          if (direction == 'up') {
            $('.freeze_column').css({'position':'absolute'});

          }
      });

A: Are you using the jQuery version of Waypoints? If so, where are you calling jQuery?
There are a few versions of the Waypoints plugin that are included when you download it: jQuery, Zepto, and "noframework".  If you are not using jQuery, then you want to make sure you're calling the "noframework" file:
noframework.waypoints.js

However, if you are using the jQuery version, as you stated in your question, I want to make sure you're calling jQuery and if so, where. This can help narrow down the issue.

A: The class constructor is not being found. It sounds like one or both js files are not loading properly.
When you instantiate a class by using the new operator it looks for a user defined or built-in object with the constructor name following the key word new.
Example:
var animal = new dog()

This would look through all currently loaded scripts for a dog constructor and will return the not a constructor error if none are found. Since we know the constructors for waypoints and stickys are found in the js files then it stands to reason they are not being loaded. Double check the paths to jquery.waypoints.min.js and sticky.min.js are correct. Also, verify through your browser console that they are actually being loaded and/or not disabled by something else.


text:
Q: Convert Json Date to date I have use the below code for converting JSON Date to Original Date. Below is my Code..
    var convertDate = function (jsonDate) {
            var date = new Date(parseInt(jsonDate.substr(6)));
            return date.format("mm-dd-yyyy");
       };

alert(convertDate(aData["Date"]));

Below error is shown in Firebug.
 if (isNaN(date)) throw SyntaxError("invalid date");

Any Help...

A: date parsing works like this:
 var dateObject = new Date("12-15-2012 01:23");

A: Try this function
function convertDate(jsonDate) {
    var offset = new Date().getTimezoneOffset() * 60000;
    var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);

    if (parts[2] == undefined)
      parts[2] = 0;

    if (parts[3] == undefined)
      parts[3] = 0;

    return new Date(+parts[1] + offset + parts[2]*3600000 + parts[3]*60000);
};

A: This isn't a full answer, but I'm writing it as an example of the kind of thinking you should have gone through.
The error it showed is the line of code where it threw an error. Presumably it's inside a library or something. Evidently it threw because the variable date was expected to be a number but wasn't. Judging by its name and expected type (number), date must be the argument to the constructor for Date, and this part was running inside the call to new Date. Conclusion: the script fails because parseInt isn't returning a number. To investigate this: click the error line in Firebug to open the part that fails, set a breakpoint there, run it again, and navigate through the call stack by clicking the tabs along the top of the Firefox window.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Circular Reveal Animation not working sharedActivity.kt.. main file

package com.example.animation_android

    import android.animation.Animator
    import android.animation.AnimatorListenerAdapter
    import android.os.Bundle
    import android.support.v7.app.AppCompatActivity
    import android.view.View
    import android.view.ViewAnimationUtils
    import android.widget.Button
    import android.widget.RelativeLayout
    import android.widget.TextView

    class SharedActivity : AppCompatActivity() {

        private var revealDemo : RelativeLayout? = null

        override fun onCreate(savedInstanceState: Bundle?) {

    //to enable transition
      //      window.requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)

            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_shared_element)

            initPage()
        }
    //after doing back
        override fun onSupportNavigateUp(): Boolean {
            finishAfterTransition()
            return true
        }

        private fun initPage() {

            // Toolbar declaration
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
            supportActionBar?.title = "Shared element Transition"

            revealDemo = findViewById(R.id.click_reveal)
            revealDemo?.setOnClickListener {
                makeCircularRevealAnimation(revealDemo!!)
            }

            val btnexit:Button = findViewById(R.id.exit_button)
            btnexit.setOnClickListener{
                finishAfterTransition()

            }
        }
    **here function block for Reveal animation**
        private fun makeCircularRevealAnimation(revealDemo: RelativeLayout) {

            val textDesc : TextView = findViewById(R.id.textDesc)

            val centerx = (revealDemo?.left + revealDemo?.right ) / 2
            val centery = (revealDemo?.top + revealDemo?.bottom ) / 2

            val radius : Float = Math.max(textDesc.width,textDesc.height) * 2.0F

            if(textDesc.visibility == View.INVISIBLE) {
                textDesc.visibility == View.VISIBLE
                textDesc.setText(R.string.description)

                ViewAnimationUtils.createCircularReveal(textDesc,centerx,centery,0F,radius).start()
            }
            else
            {
                val reveal : Animator = ViewAnimationUtils.createCircularReveal(textDesc,centerx,centery,radius,0F)
                reveal.addListener(object : AnimatorListenerAdapter()
                {
                    override fun onAnimationEnd(animation: Animator?) {
                        textDesc.visibility == View.VISIBLE
                    }
                }
                )
                reveal.start()

            }

        }
    }

Activity_shared_element.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@android:color/white"
    android:gravity="center_horizontal"
    android:padding="10dp"
    android:id="@+id/click_reveal">   <- layout on clicklistner defined

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/textDesc"
        android:padding="20dp"
        android:background="#f0ce11"
        android:gravity="center"
        android:visibility="invisible"
        android:elevation="4dp"/>

    <TextView
        android:id="@+id/activity_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Rahul Katiyar"
        android:textColor="@android:color/darker_gray"
        android:textSize="30sp"
        android:transitionName="smartherd_shared"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/LinearLayout"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/activity_title">

        <!-- same transition Name -->

    <ImageView
        android:id="@+id/logo_reveal"
        android:layout_width="200dp"
        android:layout_height="175dp"
        android:transitionName="logo_shared"
        android:src="@drawable/mylogo"/>

    <ImageView
        android:id="@+id/img_reveal"
        android:layout_width="200dp"
        android:layout_height="175dp"
        android:transitionName="pic_shared"
        android:src="@drawable/myimage"/>

</LinearLayout>

    <Button
        android:id="@+id/exit_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="EXIT [Back Press]"
        android:layout_below="@+id/textView2"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="51dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/description"
        android:id="@+id/textView2"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

All the code and xml files are  correct in Android Studio. but I am not able to launch the circular reveal transition.
all the detail has been added above. also function is define for activity
private fun makeCircularRevealAnimation(revealDemo: RelativeLayout)
but is is not working for me.
guys please and let me know what is missing from codes?

A: I found my mistake, textDesc.visibility == View.VISIBLE should be textDesc.visibility = View.VISIBLE and same for textDesc.visibility = View.VISIBLE. To assign value we use single =.


text:
Q: How to define weights for KNN? I want to identify a set of weights for the distance measure in KNN method. I read through the MATLAB help and I found that there are functions for inverse or squared inverse (w.r.t the distances) weights however a user defined weights must be a function of the form: @ fnc
where

fcn is a function that accepts a matrix of nonnegative distances, and returns a matrix the same size containing nonnegative distance weights. For example, inversesquared is equivalent to @(d)d.^(-2).

I had defined the function to provide a random set of weights:
function WGT=gene
weights=round(rand(a,b))
WGT=T
end

However, when I apply KNN the weights does not changed and are equally distributed.

A: Does your fitting code look like ClassificationKNN.fit(x, y, 'DistanceWeight', gene_weights)? For example, I think what you mean above is
function w = gene_weights(x)
    w = round(rand(size(x)));
end

Or more compactly, you can just specify gene_weights = @(x) round(rand(size(x)));


text:
Q: How could I know which bit-version of C++ program I'm building in VS2008? As the subject says, I'm building my C++ program in Visual Studio 2008.  But how could I know if the program built is targeted to 32-bit or 64-bit?  I looked around the project properties but couldn't find an option to specify this.
I looked at this article: In Visual Studio, how to correctly build an application for 64-bit machines? But it looks like discussing about C# - I couldn't find any "Any CPU"-like configurations.

A: *

*Open Visual Studio 2008

*Load your project

*Once your project is loaded, the VS2008 toolbar should look something like this:

*

*Drop down the list that says "Win32" and choose "Configuration Manager...".  This will open the Configuration Manager dialog:

*

*Under "Active Solution Platform", click the drop down list

*Select ""

*The "New Solution Platform" opens:

*

*Click on the top drop-down (labeled "Type or select the new platform:")

*One of the options, at the bottom of the list, should read "x64".  Select it.

*In the "Copy settings from:" drop-down, choose ""

*Check the "Create new project platforms" checkbox

*Press the "OK" button

*The New Solution Platform dialog closes, and now the x64 platform will be available for you to use in the Configuration Manager dialog.

*In the Configuration Manager dialog, for each project in your solution, choose the appropriate platform:

*

*Keep in mind that once you have the x64 platform added to Configuration Manager, you'll probably have to setup appropriate configurations (Release, etc.)


text:
Q: JNA CreatePseudoConsole declaration What is correct JNA declaration of CreatePseudoConsole function?
Windows API declaration is following:
HRESULT WINAPI CreatePseudoConsole(
    _In_ COORD size,
    _In_ HANDLE hInput,
    _In_ HANDLE hOutput,
    _In_ DWORD dwFlags,
    _Out_ HPCON* phPC
);

A: HRESULT is a 32-bit integer, so your function declaration would be int CreatePseudoConsole().
As for the arguments, you can extend Structure to create your own COORD structure, mapping the two Windows SHORTs to Java's 16-bit integer short.
JNA already has a mapping for WinNT.HANDLE, so just use that.  You can optionally use JNA's DWORD mapping, but most of the time I just map those directly to an int.
So the only thing left is the pointer to HPCON, which is not directly mapped.  The docs describe this as a pointer to a HANDLE.  You can use HANDLEByReference here, or extend that to your own more narrowly typed class.  This mapping of HGLRCByReference is a good example to use if you want to create an HPCONByReference.


text:
Q: How to disable p:defaultCommand when blockUI is active? I am using Primefaces 7.0 and want to disable the defaultCommand when the blockUI is active... My Problem is, when i hit the SaveButton the blockUI is active, but i can still press ENTER and the defaultCommand gets triggered. How can i disable this? I dont want to disable the defaultCommand always.
<h:form id="form">

    <p:panel id="pnlContent">
        <p:commandButton value="SaveButton" id="btnSave" action="#{defaultView.longRunningOperation}"/>

        <p:defaultCommand target="btnSave"/>
    </p:panel>

    <p:blockUI block="pnlContent" trigger="btnSave"/>

</h:form>

A: You can drop the focus from all components within the blocked panel by invoking JQuery.blur() on them:
<p:commandButton value="SaveButton" id="btnSave"
    onclick="$(PrimeFaces.escapeClientId('form:pnlContent') + ' *').blur()" />

This will prevent additional command invocations on subsequent pressing of enter.


text:
Q: "CoreBluetooth[API MISUSE] CBCentralManager can only accept commands while in the powered on state " error while trying to range beacons I'm trying to range estimote beacons in my app.
But when app ranges beacons after firing [beaconManager:didRangeBeacons:inRegion:] method,it outputs "CoreBluetooth[API MISUSE] CBCentralManager can only accept commands while in the powered on state " into debug console,and also i'm not able to connect to beacon for changing some values.I can range beacons and read values which don't require connection to beacon,such as minor,major,proximity etc.,but I also need to change them.
What's my problem?
Thanks in advance!

A: I ran into the same problem. I suspect this is a bug with Estimote SDK. I managed to work around this by calling the startEstimoteBeaconsDiscoveryForRegion method (which I believe goes on to turn on CBCentralManager). My initialisation code is as follows:
_estBeaconManager = [[ESTBeaconManager alloc] init];
_estBeaconManager.delegate = self;
_estBeaconRegion = [[ESTBeaconRegion alloc] initWithProximityUUID:ESTIMOTE_PROXIMITY_UUID identifier:@"Estimotes"];
[_estBeaconManager startRangingBeaconsInRegion:_estBeaconRegion];
[_estBeaconManager startEstimoteBeaconsDiscoveryForRegion:_estBeaconRegion];

Hope this helps

A: Just for you out there who are missing the obvious like me, make sure you have BlueTooth turned on on the phone.


text:
Q: Terminal commandline basics
Sometimes, actually, it's lowercase. Other times, it has someone else's login. Like it'll be "jdoe" for some reason. Why does it change like that? This is my work computer, if that explains anything. Thanks!

A: If you're talking about your commandline prompt: http://www.ibm.com/developerworks/linux/library/l-tip-prompt/


text:
Q: tempfile object skips lines in for loop I read data from a csv file, perform some normalization on each row and then write it into a temp file. The temp file object is created in the main() function as code in one file writes to it and code in another file reads from it. This is to avoid importing large files into memory.
However, the following script writes only a subset of rows into the file. When I replace temp_file.write(row) with a print statement all rows are printed to stdout.
Can someone help me understand why print returns all rows but only a subset is written to the temp file.
Update: I added the normalize() method to the main() method and the results are correct. I suspect the issue is something to do with passing the tempfile object name to another python file and writing to it from that file.
Main Method
def main():

    [argparse code here - removed for brevity]

    temp_file = NamedTemporaryFile()

    if os.path.isfile(args.input_file):
        normalize.normalize_file(args.input_file, temp_file)
    else:
        print 'Please supply a valid source file'

    if __name__ == '__main__':
        main()

Method imported from another file
def normalize_file(csv_file, temp_file):

    with open(csv_file) as file:
        reader = csv.reader(file)
        for line in file:
            row = line.lower()
            matchStr = re.search(r'\\users\\\w+\\',row, re.I)
            if matchStr:
                row = row.replace(matchStr.group(), '\\users\\usr\\')
            matchStr = re.search(r'\w:\\',row, re.I)
            if matchStr:
                row = row.replace(matchStr.group(), '\\')
            temp_file.write(row)
            #if I put print here all rows are printed out correctly


text:
Q: How to check if both username and email are already registered? I have tried various ways but can't seem to solve this. The latest approach I have tried was creating two "findOne" functions, but it still fails.
         const checkUser = registerLogin.findOne({ username }, (err, user) => {
          return user;
         });

         registerLogin.findOne({ email }, (err, user) => {
            if (err)
                res.send(err);

            else if (checkUser)
                res.status(403).json({ registerErrRequired: "Username is taken." });

            else if (user)
                    res.status(403).json({ registerErrRequired: "Email is already in use." });

            else if (!REGEX.test(email))
                res.status(403).json({ registerErrRequired: "Invalid email." });

A: You can use $or operator to do it. Something like:
registerLogin.findOne({$or: [{email: email}, {username: username}]}, (err, user) => {...})

A: Please find the code snippet below:
router.post('/register', async (req, res) => {

// Validate the user data
const { value, error } = validations.registerValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);

// Checking if the user is already in database
const emailExist = await User.findOne({ email: req.body.email });
if (emailExist) return res.status(400).send({ Message: 'Email already exists!' });

// Hash password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);

// Create a new user
const user = new User({
    name: req.body.name,
    email: req.body.email,
    password: hashedPassword
});
try {
    const savedUser = await user.save();
    res.send({ user: savedUser._id });
} catch (error) {
    res.status(400).send(err);
}

});


text:
Q: how to set a status here i've a problem where i want to set the status whether it is approved or reject.. the condition are if admin select the registration number and driver name, that means the status is approve otherwise, if admin fill up the reason, that means the request is reject..
here is the code to set status
if ($reason =='null'){

                $query2 = "UPDATE usage SET status ='APPROVED' WHERE '$bookingno'=bookingno";
                $result2 = @mysql_query($query2);
    }
    elseif (($regno =='null')&&($d_name =='null')) {

                $query3 = "UPDATE usage SET status ='REJECT' WHERE '$bookingno'=bookingno";
                $result3 = @mysql_query($query3);
    }

when i save the data, the status field are not updates..

A: Two things:
(1) 'null' (with quotation marks) is a string. You probably just want null (and an identity rather than an equality check) - or, better yet, use is_null(), isset() or empty() (whichever is more appropriate in your case).
(2) If your status field is an ENUM() (which it ought to be), make sure you've got capitalisation right. Normally it shouldn't matter, but if your table is set to any sort of binary character encoding (*_bin Collation), it will.

A: You have your where clause formatted incorrectly, it seems. Change this:
$query2 = "UPDATE usage SET status ='APPROVED' WHERE '$bookingno'=bookingno";

to this:
$query2 = "UPDATE usage SET status ='APPROVED' WHERE bookingno='$bookingno'";

(for both $query2 and $query3).
See if that doesn't fix it.

A: a very easy way to solve this would be to log the query string as it's been created
if ($reason =='null'){

    $query2 = "UPDATE usage SET status ='APPROVED' WHERE '$bookingno'=bookingno";
    $result2 = @mysql_query($query2);
    error_log($query2);

}
elseif (($regno =='null')&&($d_name =='null')) {

            $query3 = "UPDATE usage SET status ='REJECT' WHERE '$bookingno'=bookingno";
            $result3 = @mysql_query($query3);
            error_log($query3);
}

Then go check the query string that was created in the php error log file, if the query does not work then run the query against your database natively or phpmyadmin if you are using mysql....see if you get an errors. sometimes you will find that your varibales do not populate as intented and this will be revealed by the log file.


text:
Q: Impact of grizzly.writeTimeout in file download I am working on a JSF based web application that provides open/save dialog for the user to download an XML file. If user clicks open/save immediately once open/save dialog appears, the file is downloaded completely. But if there is a delay of more than 90sec, the file is either not downloaded or the downloaded contents are incomplete. (Incomplete file download when waiting minutes before clicking open/save in dialog)
I am using Glassfish V3 server. After going through the Glassfish survival guide in java.dzone, I modified com.sun.grizzly.writeTimeout to 300000. As per my understanding from various blogs, this jvm option corresponds to the time before Grizzly stop waiting for the browser to read the response bytes. By default, if the browser haven't read all the response bytes after 30 seconds, Grizzly drops the connection. As I have changed to 300000ms, I thought Grizzly will drop the connection after 300seconds. However, now the contents are properly downloaded if the waiting time to click open/save is < 15 minutes. If waiting time is more than 15 minutes, the contents are incomplete.
I would like to know the behavior and impact of com.sun.grizzly.writeTimeout on file download.
Any inputs are appreciated.

A: Grizzly makes 3 attempts to send at least 1 byte of data. Each attempt may take {com.sun.grizzly.writeTimeout} milliseconds.


text:
Q: How to insert multiple record in laravel I have 2 variables, here we go:
@name = array('a','b','c');
@age = array('1','2','3');

And then I want to insert into column name value a and column age value 1 and loop until the end of the array.
I tried using this but non sense:
    $t = count($name);
    DB::table('users')->insert(array(
        for ($i=0; $i < $t ; $i++) {
        }
    array('name' => $name.$i, 'dob' => $dob.$i)
    ));

How do i fix it??

A: This way:
$name = 'whatever name - ';
$age = 'whatever age - ';

foreach(range(1,3) as $i)
{
    DB::table('users')->insert(
        array('name' => $name.$i, 'dob' => $dob.$i)
    );
}

Or, having your arrays:
$names = array('a','b','c');
$ages = array('1','2','3');

foreach($names as $name)
{
    foreach($ages as $age)
    {
        DB::table('users')->insert(
            array('name' => $name, 'age' => $age)
        );
    }
}

A:     if u want to insert
    name age
    a     1
    b     2
    c     3
like this then use following code

  $names = array('a','b','c');
  $ages = array('1','2','3');

     foreach($names as $index => $name)
     {
        $data=array('name' => $name, 'age' => $ages[$index]);
        DB::table('users')->insert($data);

     }

  if u want to insert
    name age
    a     1
    a     2
    a     3
    b     1
    b     2
    b     3
    c     1
    c     2
    c     3
like this then use following code
 $names = array('a','b','c');
  $ages = array('1','2','3');

     foreach($names as $name)
     {
        foreach($ages $age){
         $data=array('name' => $name,'age' => $age);
        DB::table('users')->insert($data);
       }

     }

A: Create array of array of data :
$data = array();
foreach($names as $index => $name)
{
    $item = array('name' => $name, 'age' => $ages[$index]);
    array_push($data,$item);

 }

Users::insert($data); // Eloquent
OR
DB::table('users')->insert($data); //Insert all rows


text:
Q: How to install Raspbian to SD card on Mac How can i install Raspbian OS to my SD card without installing any additional software or application on my Mac. Most of tutorials found on google will require to install SD Formatter or didn't provide detail steps.

A: *

*Download raspbian image from Raspbian website

*Extract the zip file

*Run df -h on any terminal
$ df -h
Filesystem      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
/dev/disk1     465Gi  278Gi  186Gi    60% 3262771 4291704508    0%   /
devfs          191Ki  191Ki    0Bi   100%     660          0  100%   /dev
map -hosts       0Bi    0Bi    0Bi   100%       0          0  100%   /net
map auto_home    0Bi    0Bi    0Bi   100%       0          0  100%   /home
/dev/disk2s1    60Mi   20Mi   40Mi    34%     512          0  100%   /Volumes/boot

Get disk number from df -h output. In example above X will be 2

*Unmount SD card

$ sudo diskutil unmount /dev/diskXs1

*Go to download directory and use dd command to format and copy Raspbian image to SD card

$ sudo dd bs=1m if=./2017-04-10-raspbian-jessie.img of=/dev/rdiskX

*Eject SD card

$ sudo diskutil eject /dev/rdiskX

*Insert SD card to Raspberry PI and start playing with it!


text:
Q: windowSoftInputMode adjustResize Thanks for your help!
I am trying to have my bottom LinearLayout (which holds a button) show on screen at all times 10dp above bottom. There is an EditText above this Linearlayout which I would like to resize according to how much text has been entered.
In my manifest I have android:windowSoftInputMode="stateVisible|adjustResize" which resizes my EditText, but always pushes the LinearLayout I want to show off screen. (When enough text is entered)
PLEASE HELP ME PLACE A LINEARLAYOUT 10DP ABOVE KEYBOARD WHEN ENOUGH TEXT HAS BEEN ENTERED WHILE ONLY RESIZING MY EDITTEXT. THANK YOU.
(I am going for something similar to this version of twitter below)
I am using ActionBarSherlock to get a specific theme. (Not sure if that matters)
Similar to this version of Twitter for android (image)
activity_main.xml
<!-- MAIN LAYOUT -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mainactivity_main_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">

<!-- TOP BAR -->
<LinearLayout
    android:id="@+id/mainactivity_top_layout"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:layout_gravity="center_horizontal"
    android:background="@drawable/top"
    android:orientation="horizontal" >

    <!-- TITLE -->
    <EditText
        android:id="@+id/mainactivity_edittext_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0.02"
        android:background="@android:color/transparent"
        android:inputType="textCapSentences"
        android:paddingLeft="10dp"
        android:paddingRight="0dp"
        android:textColor="#262626"
        android:hint="@string/title_hint"
        android:maxLength="20" />

    <!-- COLOR CHANGER BUTTON -->
    <ImageButton
        android:id="@+id/mainactivity_button_color_changer"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/color_changer_custom"
        android:layout_gravity="center"
        android:onClick="onClickAction" />

    <!-- OVERFLOW MENU BUTTON -->
    <ImageButton
        android:id="@+id/mainactivity_button_overflow"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/overflow_custom"
        android:layout_gravity="center"
        android:onClick="onClickAction" />

</LinearLayout>

    <!-- BODY -->
    <EditText
        android:id="@+id/mainactivity_edittext_body"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/backer1"
        android:gravity="top|left"
        android:orientation="vertical"
        android:inputType="textCapSentences|textMultiLine"
        android:maxLines="20"
        android:paddingTop="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:textColor="#262626"
        android:hint="@string/body_hint" />

     <!-- BOTTOM BAR -->
     <LinearLayout
         android:id="@+id/mainactivity_bottom_layout"
         android:layout_width="wrap_content"
         android:layout_height="50dp"
         android:background="@drawable/bottomless"
         android:orientation="vertical" >

         <!-- BUTTON -->
         <Button
            android:id="@+id/mainactivity_button"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/close_custom"
            android:text="@string/close_text"
            android:textColor="@color/button_text_color" />

    </LinearLayout>

</LinearLayout>

AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mikemilla.www"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
 <uses-permission android:name="android.permission.WAKE_LOCK"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.mikemilla.pinitnotes.MainActivity"
        android:theme="@style/mytransparent.windowNoTitle"
        android:label="@string/app_name"
        android:windowSoftInputMode="stateVisible|adjustResize"
        android:configChanges="orientation"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>


text:
Q: Best practice - should Expenses be tracked in Opportunity Object? should we use opportunity to track expense related to an account, or create a custom object for tracking expense. I want to know logically which is more appropriate.

A: I'll go out on a limb and say NO
SFDC has designed the Opportunity object to represent a sales process wherein there is an 'opportunity' to sell something(s) on a particular date (CloseDate) that can be placed into forecast buckets (Commit, Upside, Pipeline, etc.); that Opportunity goes through a lifecycle (StageName).
The 'somethings' that can be sold are represented by Opportunity Products which in turn are linked to entries in Pricebooks
You are swimming upstream by subverting the intent of the Opportunity to use for expense tracking.
Furthermore, if you decide at a later point to use Opportunity as intended, you will find that your logic will get tortured as you have two very different use cases inhabiting the same SObject


text:
Q: Excel VBA: Selecting Multiple worksheets based on the results of a userform - for updating and printing I am creating an excel workbook to be used for clients where the sheet tabs will be hidden. I would like to have a userform pop up where clients select which sheets they would like in checkboxes and for these to then be selected together (so that the page numbering is updated) as well as printed continuously.
From other options I've seen, I have Populated a specific sheet with the names of the Sheet Names as so:
Dim iRow As Long
Set PP = Worksheets("Printing Page")
Dim CB1 As Worksheet
Set CB1 = Worksheets("Retail, Mall, Shopping Centres")
Dim CB2 As Worksheet
Set CB2 = Worksheets("Sports & Social Clubs")

    'Clear & Populate the sheet
    PP.Cells.Clear

    PP.Cells(1, 1).Value = Chr(34) & CB1.Name & Chr(34)
    PP.Cells(2, 1).Value = Chr(34) & CB2.Name & Chr(34)

    'Check each checkbox and enter the sheet number in PP

    If Me.CBRetailMallSC = False Then
        PP.Rows(1).Delete
    End If

     If Me.CBSportsSocial = False Then
        PP.Rows(2).Delete
    End If

From there i've tried turning these values into an array and transposing or running a function like in this link.
However I always get an error message saying "Run time error 9 - subscript out of range" and pointing to the Sheets(x).Select line of code.
Please please help, i am completely and utterly lost!!!
PS: if only one checkbox is selected then everything runs fine, but as soon as 2  then it breaks.

A: Is the idea that the client uses the checkboxes to choose which hidden sheets they would like to print out?  And you want to print them out as a single document instead of several different documents?
If so this is the logic you'll need.  You are correct in having a special page to copy the other pages to.  (I don't understand why you are deleting rows form the "PP" page though.)  You can add headers and footers with page numbers on your print page.  You only need to keep track of the last used row on the print sheet.
For each sheet the client selects, copy the used range.  (It helps to keep the width within a normal sheet size, or you can programmatically force it to print
full page size.)  Paste the first copied sheet to row "A" of the print sheet.  Find the last used row of the print sheet and add 1 row.  Put a page break there.  Add another row and paste the second selected sheet to that row, and so forth.


text:
Q: Visual C++ find out max possible value of variable's data type I am using VS2010 to port an existing Mac application written in C++ to Windows. The following line of code:
T var_max;
var_max = std::numeric_limits<typeof(var_max)>::max();

given a variable, determines the maximum value for the data type of that variable.
How do I write equivalent code in VC++? I tried using typeid to determine the data type, but it only gives out a string and cannot be used in a template.

A: You don't need to determine the data type. It's T. Try this code:
#include <limits>
template <typename T>
T MaxValue()
{
    T var_max = (std::numeric_limits<T>::max)();
    return var_max;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int value = MaxValue<int>();
    return 0;
}


text:
Q: AEM - How to cache model for page scope? I have a sling-model that needs to do some costly operations at initialization. These are related to the page scope, meaning based on currentPage properties. Hence it would make sense that the model gets initialized only once per page call.
I found a nice article regarding this at how to call sling model only once where they are setting the cache property of the Model-annotation to true.
But this unfortunately only works per resource.
So setting the cache=true property the model gets initialized for every component that calls it via data-sly-use. It only helps wenn calling data-sly-use in the same component (resource), but that's not helpful.
Can I somehow have the model cached for the entire lifecycle of the page-request?

A: SlingHttpServletRequest is a wrapper around HttpServletRequest and supports setAttribute and getAttribute methods provided by servlet api.
Setting attributes:
slingRequest.setAttribute(ATTRIBUTE_NAME, myobject);

Retrieve:
//check for null
MyClass myobject = (MyClass) slingRequest.getAttribute(ATTRIBUTE_NAME);


text:
Q: Font weight in windows store app I'm tryign to set my font weight propert to bold. But can't do that. So How can i set my font weight property to bold in c# code?
tbgc1.FontWeight.Weight = ?;

A: using Windows.UI.Text;

....

tbgc1.FontWeight = FontWeights.Bold;

See FontWeight class on MSDN


text:
Q: NerdDinner exceptions and custom errors In this tutorial in Details action Scott uses
if (dinner == null)
return View("NotFound");
else
return View("Details", dinner);

to return 404 Not Found message view.
But in my downloaded source code for NerdDinner there are these lines:
        if (dinner == null) {
            return new FileNotFoundResult { Message = "No Dinner found for that id" };
        }

This goes to FileNotFoundResult where there is this:
public class FileNotFoundResult : ActionResult
{
    public string Message {
        get;
        set;
    }

    public override void ExecuteResult(ControllerContext context) {
        throw new HttpException(404, Message);
    }
}

And that's it. How is the reference to NotFound.aspx view made from here on? I was unable to found out how this gets mapped to NotFound.aspx, though NotFound.aspx does exist in Dinners view folder.
There's also nothing in web.config..
The above code is from Change Set 41262 not the 1.0 version.
Question (to be more clear about it): How come "throw new HttpException(404, message)" returns NotFound view??
Someone please explain.

A: There was a NotFound.aspx view in the Views\Dinners folder when I downloaded it.
Update: Like womp says it's very disingenuous to ask an unclear question and then downvote answers. I suspect the answer to your clarified question is that the downloaded tutorial uses the FileNotFoundResult exception as a placeholder and it's meant to be replaced by the NotFound view. I did a quick search on my NerdDinner solution, which is what I was left with after going through the complete tutorial, and the FileNotFoundResult is not used anywhere.

A: When an HttpException is thrown, it ends up being caught by the asp.net runtime, which will handle it by serving an error page.  This error page can be customized in the customErrors webConfig option
<customErrors mode="RemoteOnly" defaultRedirect="/Dinners/Trouble">
            <error statusCode="404" redirect="/Dinners/Confused"/>

Are you sure it's still loading the NotFound.aspx page, and not the Confused.aspx?
"Sorry - but the dinner you requested doesn't exist or was deleted."

and not
"Are you lost? Try taking a look at the complete list of ..."

A: This is one of the conventions of the ASP.Net MVC framework.  I highly suggest reading some of the ASP.Net MVC tutorials and documentation regarding the conventions of the framework. Here's the one on Views.
Basically, when you call the View() method of a controller, it's a shortcut for explicitly having to code in the path to a view template file.  The convention is that the framework will look for the view template first in the controller's View directory, and then in the Shared directory.  It's also smart enough to look for both .aspx and .ascx extensions when it goes searching for the template.
This is why if you want to load a View that's not in either of those folders, you have to be much more explicit.  For example, to load a partial view that's not in the current controller's View folder, you have to specify the whole path to it:
<% Html.RenderPartial("~/Views/SomeOtherController/SomeView.ascx") %>

rather than the usual
<% Html.RenderPartial("SomeView") %>


text:
Q: Zabbix discovered nodes count change trigger I made a zabbix template and scripts for my OpenVPN server. This template generates VPN users (as discovered nodes) from certificate list. Every node is monitored for traffic, up/down, uptime. All users are placed in VPNUsers group.
I'm trying to make trigger to raise alert when new users added or removed. I studied documentation and found groupsum function, but can't figure out how use it to compare current sum and previous.
Is it possible ?

A: The discovery part was not clear to me, but grpsum is an aggregate item function. The values would be stored in an item, and then on top of that you'd create a trigger with, for example, abschange()<>0 trigger function.


text:
Q: jQuery isotope invalid rendering Why are these two fiddles different? I mean shouldn't they stick to each other in the first fiddle too as in the second fiddle?
Fiddle1: http://jsfiddle.net/gopi1410/EABJw/
Fiddle2: http://jsfiddle.net/gopi1410/EABJw/1/
The only difference in the fiddles is that the first one has the css: #id2 {width: 240px;} while the second fiddle has #id2 {width: 140px;}
Is it a bug in the isotope plugin or am I missing some basic point?

A: Just change your javascript like this:
$(function() {
    var $container = $('#container');
    $container.isotope({
        masonry: {columnWidth: 1},
        itemSelector: '.item'
    });
});


text:
Q: Error when Querying DynamoDB GSI Using C# .NET Core 2.1 I am getting the following error for the code below:
Error    CS1061  'AsyncSearch' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'AsyncSearch' could be found (are you missing a using directive or an assembly reference?
DynamoDBContext context = new DynamoDBContext(client);

                DynamoDBOperationConfig indexHashRangeOpConfig = new DynamoDBOperationConfig()
                {
                    IndexName = "ProjectFGDIndex",
                    ConsistentRead = false,
                };

                IEnumerable<Dashboardreq> list = await
                context.QueryAsync<Dashboardreq>(req.ProjectName, QueryOperator.Between, new string[] {
                                                 req.FileGeneratedFromDate+" " + Constants.DayBeginTime,
                                                 req.FileGeneratedToDate+" " + Constants.DayEndTime
                                                 });

The error occurs in the await context.QueryAsync call.
Looking for guidance...

A: I resolved the issue ny making the following changes to the code:
List<Dashboardreq> list =
                await context.QueryAsync<Dashboardreq>(req.ProjectName, QueryOperator.Between, new string[] {
                                                 req.FileGeneratedFromDate+" " + Constants.DayBeginTime,
                                                 req.FileGeneratedToDate+" " + Constants.DayEndTime
                                                 }, indexHashRangeOpConfig).GetRemainingAsync();


text:
Q: List dates in months from database Hey, I need som help to list my added dates from database, and split it into their added month.
I have no clue on how to do it... Soe can someone please show me examples, or maybe some tutorials how to do?
Thx

A: Something along the lines of this, perhaps?
SELECT * FROM table GROUP BY MONTH(dateColumn)

SELECT * FROM table WHERE MONTH(dateColumn) = 9

A: A must-read reference for date & time handling functions in MySQL is:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

A: Are you looking for the MySQL MONTH() Function?
  Query: SELECT MONTH(NOW());
 Output: 11

A: Not entirely sure what you mean but here goes...
The sample below creates a test collection (assumably your collection retrieved from the database) and groups them by Month and Year and then displays the result. It uses Linq and anonymous objects which you could easily replace with some POCO classes...
    Sub Main()

    Dim ls As New List(Of Object)
    Dim lsGroup As New List(Of Object)
    Dim ran As New Random(Now.Millisecond)

    '' build a sample collection
    For x As Integer = 1 To 100
        ls.Add(New With {.ID = x, .DateAdded = Now.AddMinutes(-(ran.Next(1, 100000)))})
    Next

    '' now group them into years and months
    For Each item In ls
        Dim currentItem As Object = lsGroup.Where(Function(o) o.Year = item.DateAdded.Year And o.Month = item.DateAdded.Month).SingleOrDefault()
        If currentItem Is Nothing Then
            '' create
            Dim var = New With {.Year = item.DateAdded.Year, .Month = item.DateAdded.Month, .ItemCollection = New List(Of Object)}
            var.ItemCollection.Add(item)
            lsGroup.Add(var)
        Else
            '' add
            currentItem.ItemCollection.Add(item)
        End If
    Next

    '' display the results
    For Each group In lsGroup
        Console.WriteLine(group.Year & " - " & MonthName(group.Month))
        For Each item In group.ItemCollection
            Console.WriteLine(" > " & item.ID & " - " & item.DateAdded.ToString())
        Next
        Console.WriteLine()
    Next

    Console.ReadLine()

End Sub

A: Here's what I do when I need the month that's in a timestamp or date item called "t".
TIMESTAMP(DATE_FORMAT(t,'%y-%m-01'))
This returns another timestamp that represents midnight on the first day of that month.
Works for weeks too.
TIMESTAMP(FROM_DAYS(TO_DAYS(t) -MOD(TO_DAYS(t) -1, 7)))
This obscure incantation returns a timestamp that represents midnight on the Sunday preceding the given timestamp.


text:
Q: How to append custom HTML to the end of view with attributes in ASP.NET MVC? Assume we have some action in controller:
public ActionResult SomeAction()
{
    return View();
}

I want to have a possibility to append some HTML code to the end of view's HTML result with help of attributes, e.g.:
[SomeHTML]
public ActionResult SomeAction()
{
    return View();
}

where
public class SomeHTMLAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var response = filterContext.HttpContext.Response;

        if (response.ContentType == "text/html")
        {
            response.Write("someHTML");
        }
    }
}

Filters (ActionFilterAttribute) allow to append some HTML code to the top or bottom of web-page but not to the end of view's HTML.
How to archive this?

A: You could use a Response filter:
public class SomeHTMLAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Filter = new SomeHTMLFilter(filterContext.HttpContext.Response.Filter);
        base.OnActionExecuting(filterContext);
    }
}

public class SomeHTMLFilter : MemoryStream
{
    private readonly Stream _outputStream;
    public SomeHTMLFilter(Stream outputStream)
    {
        _outputStream = outputStream;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        _outputStream.Write(buffer, 0, buffer.Length);
    }

    public override void Close()
    {
        var buffer = Encoding.UTF8.GetBytes("Hello World");
        _outputStream.Write(buffer, 0, buffer.Length);
        base.Close();
    }
}


text:
Q: Get count of text of cell in several sheets in excel using VLOOKUP I have a workbook with several sheets.
In the range from B20:B25 I have some values from a dropdown list. In the left column when that values are wrote, the workbook automatically has to set the many times of that value has selected in all sheets simultaneously.
For example if in the sheet 2 I write the text "TEXT" in cell B22, the workbook has to look up in the last sheets if the text "TEXT" exists ONLY at range B20:B25. If this text was found, so the workbook has to add 1 to the left cell of value "TEXT".
The workbook can have to 60 sheets. And for example the "TEXT" could be wrote at first time in the sheet 55, and its left number must be 1. If the "TEXT" is write again in the sheet 56, the value at its left must be 2.
So the column A must be a counter of times that value in column B is wrote.

I tried with CELL, ADDRESS and MATCH but I had not lucky.
Does exists in VBA a formula that I can create something to count such this?

A: This might not be the most elegant way to do this but it seems to work:
Option Explicit

Function CountThroughSheet(R1 As Range, R2 As Range)
    Application.Volatile
    CountThroughSheet = 0
    Dim TrgAdd As String, i As Integer, R3 As Range
    TrgAdd = R1.Address
    For i = 1 To Application.Caller.Worksheet.Index
        For Each R3 In Sheets(i).Range(TrgAdd)
            If R3 = R2 Then CountThroughSheet = CountThroughSheet + 1
        Next R3
    Next i
End Function

To be placed in a module.
Function is used as follow:

Note that where ever you place the formula, the first argument should be as large as the largest range in previous sheet index. Meaning that if your list decrease in size, you'll need to take blank rows to match previous lists positions.


text:
Q: Google Project Hosting: SVN statistics Is there any way to count downloads thru SVN checkout with Google's hosting?

A: I don't think there is any way to do it. In general, SVN does support commit hooks. Unfortunately, there's no hook for checkouts.


text:
Q: Change a lookup column's width without influencing other text boxes I wanted my lookup column to be larger therefore I added a web part with code to my NewForm:
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('select[title="Relation possible values"]').width(500);
        $('select[title="Relation selected values"]').width(300);
     });
</script>

My problem is now that all of the text boxes are that large. I tried to set their width as well but that doesn't seem to change anything.
What should I do?


text:
Q: Python retrieve variable from text I'm trying to retrieve variables from a text file and pass those variables into python. Also in one text file i will have an content such as :
Total Numbers: 22, Total Boxes: 33, Total Tickets: 62, Total Files: 107
Total Numbers: 2, Total Boxes: 53, Total Tickets: 92, Total Files: 105
Total Numbers: 3, Total Boxes: 13, Total Tickets: 22, Total Files: 137
Total Numbers: 42, Total Boxes: 38, Total Tickets: 62, Total Files: 143

How can I only retrieve variables from the last line, for example i want to be able to pass Total Numbers: 42, then separately pass Total Boxes: 38, etc etc.
For example lets say i have a function in python
def get_content():
f = open('test.txt')
#not sure how to only retrieve last line
my_number = # this is where i want to pass Total_numbers to get a value of 42
f.close()

A: If the file isn't too big, just use readlines to read the lines into a list, making the last line easy to find. Once you have that line, split it on the comma and then again on spaces to isolate the values. I'm not sure what you mean by "passing" them... so here is an example that just extracts the 4 values, converts them to integers and returns them as a tuple.
def get_content():
    """"Returns (numbers, boxes, tickets, files) for the last entry
    in test.txt"""
    with open('test.txt') as fp:
        lines = fp.readlines()
    # just in case there is an empty line at the end...
    while lines and not lines[-1].startswith('Total Numbers'):
        del lines[-1]
    if lines:
        # split on comma then take the number at the end and return
        return tuple(int(part.split()[-1]) for part in lines[-1].strip().split(','))

print(get_content())

A:
How can I only retrieve variables from the last line

In order to retrieve the last line in your data file, you might try
import subprocess
last_line = str(subprocess.check_output(['tail', '-1', 'data.txt']))

From there, splitting, e.g. as outlined by tdelaney, will give the needed values.

A: If you just want to read the last line, and then get the number 42 out:
>>> f = open('somefile.txt')
>>> f.seek(-2, 2)
>>> while f.read(1) != b"\n":
...    f.seek(-2, 1)
...
>>> last_line = f.readline()
>>> last_line.split(',', 1)[0].split(':')[1].strip()
'42'

Now, if you want to get all the data out in a way that you can manipulate it later, you need to do some more work:
>>> import re
>>> e = r'Total (\w+): (\d+)'
>>> data = dict(re.findall(e, last_line))
>>> data['Tickets']
'62'


text:
Q: How to stop iOS Mail from automatically downloading attachments? I would like to know how to stop Mail app on iOS 9.3.5 from automatically downloading the mail attachments. It is taking a lot of space on my iPhone.

A: Most attachments in emails are actually remote images. You can stop iOS Mail from downloading remote images as follows:

*

*Go to Settings

*Tap on Mail

*Under the Messages heading, toggle Load Remote Images off

In terms of stopping other attachments (e.g. MS Word documents etc), there is no such option to prevent downloading these. However, the way it should work is as follows:

*

*When your iPhone is connected to the internet via a cellular network, any email attachments over a certain size will not download automatically.

*Instead, for these attachments you would have to manually select them in the body of the email to download them.

*When your iPhone is connected to the internet via Wi-Fi, all email attachments will download automatically.

As far as I'm aware there is no way to stop this, although there may be 3rd party email apps that give you this option.
If you're sure that emails are taking up a lot of space on your iPhone, you may need to rethink how regularly you delete older emails. You can also filter emails by attachment and then delete the oldest ones to free up space. Another option is to set up a Mailbox for emails with attachments so it's easier for you to manually manage them.

A: goto mail > preference > Accounts
select particular accounts and in AccountInformation tab set DOWNLOAD ATTACHMENT value to NONE.


text:
Q: Javascript : Inject inline code to a html tag I would like to add my Google Analytics tracking event code inline to my input html tag :
<input class="addtobag">

to have something
<input class="addtobag" onClick="_gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);">

I'm asking this as I don't have access to the file that contains the  tag so I'm unable to make the change manually so I'm looking for a javascript code that I will put in the head so when that page load, the tracking event code would be injected automatically.
I want the call to be by my input class and not by id.

A: Why do you want to do it inline?
document.getElementById('ctl00_mainContentPlaceHolder_lvLookProducts_ctrl0_buyArea3493_btnAddToCart').onclick = function () {
    _gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);
};

To do it by class name, you'll need to do a little more logic:
var inputs = document.getElementsByClassName('AddToBag'),
    i = inputs.length;

while(i--) {
    inputs[i].onclick = function () {
        _gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);
    };
}

Fetching by class name returns a list, so you'll have to loop through to apply the handler.

A: jQuery is your friend.
How to replace innerHTML of a div using jQuery?
$("#regTitle").html("Hello World");

EDIT
Guess I didn't read this one, but still same principle.
$(".addtobag").click(_gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']));

http://api.jquery.com/click/


text:
Q: TkFiledialog.askopenfilename() launches a window for "save as" in windows 10 Using Tkinter to launch an open file dialog for use with other python functions results in a "save as" dialog opening.
Using this script:
import tkFileDialog
file_path_string = tkFileDialog.askopenfilename()

I should get the open file dialog, and instead i get a "save file" dialog.
I'm using spyder IDE within the as-downloaded anaconda 3.7 windows installer
import tkFileDialog
file_path_string = tkFileDialog.askopenfilename()

A: the IDE is attempting to save the script file before executing (as should be expected).  This is the problem, not an issue with the script.


text:
Q: how long does it take to switch a UIImageview image How long does it take to switch a UIImageview image for each version of the iPhone on average?
I'm trying to get metering enabled on an AVAudioPlayer and I want to know how often I chould check metering levels so that the image displaying the metering doesn't lag behind actual playback.

A: How long it takes to set the image is unpredictable. It also depends on where you are loading the image from, and wether it has been loaded before. [UIImage imageNamed:...] already does some optimisation when you are reusing the same image, but that doesn't mean you get predictable speed.
If you want to do something like displaying a level meter, you might be better off doing the drawing yourself in a custom view. Override drawRect: and draw the status of the levels in your 'level' view. Us a level property and override it's setter to call setNeedsDisplay if the property value has changed.


text:
Q: Keeping Source Format when copy data using apache poi Using Apache POI,
I successfully copied all my data, but ive lost all my formatting, eg font, foreground color etc.
heres what ive tried
destCell.getCellStyle().setAlignment(srcCell.getCellStyle().getAlignment());
destCell.getCellStyle().setFont(srcCell.getCellStyle().getFont());
destCell.getCellStyle().setFillForegroundColor(srcCell.getCellStyle().getFillForegroundColorColor());

tried this for font still not working
XSSFFont font = new XSSFFont();
                    font.setFontName(srcSheet.getRow(currentRowIndex).getCell(currCellIndex).getCellStyle().getFont().getFontName());
                    font.setFontHeightInPoints(srcSheet.getRow(currentRowIndex).getCell(currCellIndex).getCellStyle().getFont().getFontHeightInPoints());
                    font.setColor(srcSheet.getRow(currentRowIndex).getCell(currCellIndex).getCellStyle().getFont().getColor());
                    font.setFamily(srcSheet.getRow(currentRowIndex).getCell(currCellIndex).getCellStyle().getFont().getFamily());
                    destSheet.getRow(currentRowIndex).getCell(currCellIndex).getCellStyle().setFont(font);

and this gives me an error
destSheet.getRow(currentRowIndex).getCell(currCellIndex).setCellStyle(srcSheet.getRow(currentRowIndex).getCell(currentRowIndex).getCellStyle());

This Style does not belong to the supplied Workbook Styles Source. Are you trying to assign a style from one workbook to the cell of a different workbook?

This is the source format

This is how it looked after i copied over using apache poi

A: I would recommend you to first create a CellStyle with your destination-workbook and add to that one the required parameters from your source-cells. Then apply that CellStyle to your destination-cells.
In my experience the CellStyle object can be a little bit tricky, and the safest way is to create a CellStyle at first.


text:
Q: Python Twisted - How to send the data over the connected socket connections? I've a server as follow:-
class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

The above code receives the message and replies back with the same message. However, my use case is different.
I'm processing some data, storing it into the DB and then finally want to send the data to the connected clients, or one type of data to specific set of connected clients and the other type to another.
How can I do it? How can I call sendMessage function outside the class?

A: You need to subclass WebSocketServerFactory to keep track of your connections.
Take a look at this example, which stores all the open connections in a list and broadcasts to all of them. You could easily adapt it to send specific messages to certain clients.

A: Are you sure you don't want to just use WAMP instead of raw WebSockets?
This might be a lot easier for your use-case, as "broadcast information to interested clients" is exactly what the Publish/Subscribe pattern is for.


text:
Q: Valgrind Alternative for Mountain Lion Unfortunately, Valgrind does not support OS X 10.8 yet. After some Googling, I came across some forum posts where people were able to get it to compile and "almost" link. Does anyone know of any good alternatives to Valgrind for memory leak detection?

A: The Instruments app (part of Xcode) is a very good way to look for leaks and run stress tests on the memory allocation of a running program.

A: While valgrind can be installed, the current state isn't very usable. In a simple program I got the following result;
==16016==
==16016== HEAP SUMMARY:
==16016==     in use at exit: 63,264 bytes in 364 blocks
==16016==   total heap usage: 516 allocs, 152 frees, 67,154 bytes allocated
==16016==
==16016== LEAK SUMMARY:
==16016==    definitely lost: 8,624 bytes in 14 blocks
==16016==    indirectly lost: 1,168 bytes in 5 blocks
==16016==      possibly lost: 4,933 bytes in 68 blocks
==16016==    still reachable: 48,539 bytes in 277 blocks
==16016==         suppressed: 0 bytes in 0 blocks
==16016== Rerun with --leak-check=full to see details of leaked memory
==16016==
==16016== For counts of detected and suppressed errors, rerun with: -v
==16016== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

The same code will be fine with using valgrind on a linux.(compiled on their respective systems)

A: Assuming you can be bothered, if you install MacPorts you will be able to install a functioning Valgrind (3.8.1 as for today) on your system.  Unfortunately MacPorts will require you to install the whole XCode, not just the CL tools, so YMMV.


text:
Q: Can you explain how the formulas implemented in the two functions work? The two functions are based on a product classification system, based on votes from 0.5 to 5 points, that is: (0.5, 1, 1.5, 2, 2.5 3, 3.5, 4, 4.5, 5).
But how mathematical or arithmetic calculations work?
function calculate_stars($rating){
    // step starting from 0
    return (($rating/0.5)-1);
}

And this what tells us this, how it works:
function display_star($rating){
    $output="";
    $step = calculate_stars($rating);
    $output ='
';
    for ($i=0;$i<10;$i++)
    {
        $class = '';
        if($i<=$step)  $class = ' is-active';
        if($i%2 == 0) $class .= ' left';
        $output .= '

';
    }

    $output .='
';
    return $output;

}

echo display_star(0.5);

Can you explain, each arithmetic or mathematical process to understand and learn how these functions work correctly?

A: Use interactive mode to see what it does:
php -a
Interactive mode enabled

php > function calculate_stars($rating){
php {     // step starting from 0
php {     return (($rating/0.5)-1);
php { }
php >
php > function display_star($rating){
php {     //$output="";
php {     $out = array();
php {     $step = calculate_stars($rating);
php {     //$output ='
';
php {     for ($i=0;$i<10;$i++)
php {     {
php {         $class = '';
php {         if($i<=$step)  $class = ' is-active';
php {         if($i%2 == 0) $class .= ' left';
php {         //$output .= '

';
php {         $out[] = str_pad($class, 14, " ", STR_PAD_LEFT);
php {     }
php {
php {     //$output .='
';
php {     //return $output;
php {     return implode($out,' | ');
php {
php { }
php >
php > for($i=0.5; $i <= 5; $i+=0.5) {
php {   printf("% 3s: %d %s\n",
php (     $i,
php (     calculate_stars($i),
php (     display_star($i)
php (   );
php { }
0.5: 0  is-active left |                |           left |                |           left |                |           left |                |           left |
  1: 1  is-active left |      is-active |           left |                |           left |                |           left |                |           left |
1.5: 2  is-active left |      is-active |  is-active left |                |           left |                |           left |                |           left |
  2: 3  is-active left |      is-active |  is-active left |      is-active |           left |                |           left |                |           left |
2.5: 4  is-active left |      is-active |  is-active left |      is-active |  is-active left |                |           left |                |           left |
  3: 5  is-active left |      is-active |  is-active left |      is-active |  is-active left |      is-active |           left |                |           left |
3.5: 6  is-active left |      is-active |  is-active left |      is-active |  is-active left |      is-active |  is-active left |                |           left |
  4: 7  is-active left |      is-active |  is-active left |      is-active |  is-active left |      is-active |  is-active left |      is-active |           left |
4.5: 8  is-active left |      is-active |  is-active left |      is-active |  is-active left |      is-active |  is-active left |      is-active |  is-active left |
  5: 9  is-active left |      is-active |  is-active left |      is-active |  is-active left |      is-active |  is-active left |      is-active |  is-active left |      is-active
php >

You have 10 possible ratings, in .5 increments.  So display_star($rating) steps through all 10, giving the appropriate class.  The star that is displayed depends on the class given.  So for each set of stars, there are 10
 with varying classes.  Check your CSS to see what each one of them does.

A: I devised the following in an attempt to better grasp the code:
<?php
const OFFSET = 0.5;
function calculate_stars($rating){
    return ( ($rating/OFFSET) - 1 );
}
function display_star($rating){
    $output="";
    $str = "";
    $step = calculate_stars($rating);

    for ($i=0, $max = 10; $i < $max; $i++)
    {
        echo str_pad($output,$i,"*"),"\n";
    }
}

display_star(0.5);

See live code
Then, I discovered a related link here and found the code that seems to form the basis of OP's questions. Therefore, the following remarks pertain to the OP's example code.
The function display_star() gets the ball rolling so-to-speak by taking a rating parameter.  That function calls calculate_stars() with an initial $rating of 0.5. The callback returns a value that sets $step. The for-loop  generates a row of 5 stars, each star composed of two-halves which makes it convenient to represent a rating of 0.5 with a half filled in star.
The function calculate_stars() takes a parameter $rating and returns a value that sets $step.  To determine how many half and/or full stars to output, the function uses an algorithm such that it divides the rating by 0.5 or a half, fitting for the one-half incremented values in a 0.5 to 5.0 star rating system.  Next, one is subtracted from that result, so that the final result determines how many stars are fully or partially active, i.e. a rating of 0.5 translates into step 0, so there will be exactly only one half star while the remaining four stars are blank.
In display_star(), the first if-conditional tests that $i is less than or equivalent to the step value. If that statement evaluates as true then the variable $class is assigned a class of "is_active".  The next if-statement uses a modulo operation so that in every other iteration of the for-loop the value of $class expands to include another class, namely "left".  The PHP code generates HTML consisting of ten li elements which the accompanying CSS transforms into a half star followed by four blank stars; see the calculated result here.


text:
Q: install svn server on windows I want to install a SVN server on a Windows 7 64 bit machine (just for me).
I used Slik SVN and set up a service with:
sc create svnserver binpath= "C:\Program Files\SlikSvn\bin\svnserve.exe --service -r H:\svn\repository" displayname= "Subversion" depend= Tcpip start= auto

This is listed in the list of services, but can not be started:
C:\Windows\system32>sc create svnserver binpath= "C:\Program Files\SlikSvn\bin\s
vnserve.exe --service -r H:\svn\repository" displayname= "Subversion" depend= Tc
pip start= auto
[SC] CreateService ERFOLG

C:\Windows\system32>net start svnserver
Der Dienst reagiert auf die Kontrollfunktion nicht.

Any idea why this does not work?

A: From Svnserve Based Server page of TortoseSVN docs, "Run svnserve as a Service" chapter. Your path have space in name

If any of the paths include spaces, you have to use (escaped) quotes
  around the path, like this:

sc create svnserve binpath= "
    \"C:\Program Files\Subversion\bin\svnserve.exe\"
    --service --root c:\repos" displayname= "Subversion"
    depend= tcpip start= auto

A: You state that you want to install a SVN server just for yourself, i.e. you are going to be the only user of the system. So what's the purpose of installing a SVN server in this case?
Did you decide to setup svnserve because you consider this as the easiest way to make your repositories accessible for clients? If you did, then you've missed the easier way to access your repositories:

*

*You can use direct repository access (on local disk).
I.e. you can access a repository with the URL: file:///C:\Repositories\MyProject1 or file:///C:\Repositories\MyProject1\trunk\repo-folder.

*If you need to create a clean repository you may use a command-line:
svnadmin create C:\Repositories\MyProject1
You don't need a svnserve or Apache HTTP Server for that.
I can agree that Subversion bundles like VisualSVN Server make it much easier to maintain your repositories and understand why one installs it on a laptop for personal use and even uses HTTPS access locally. However I completely don't understand why would anyone want to setup a personal svnserve-based SVN server on Windows! There is no real use case for that, IMHO. Better consider a dedicated SVN package or use direct file:// access.


text:
Q: Protocol delegate doesn't call function I implemented side menu from github in my project. I'm trying to add a protocol in it. This way when a cell gets selected, a function in another class (the main viewController) will get called. Here's my code:
tableView.swift
protocol menuTableViewProtocol {
    func didSelectCell(SelectedCellNumber : Int)
}

var delegate : menuTableViewProtocol?

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.delegate?.didSelectCell(indexPath.row)
}

mainVC.swift

class MainViewController: UIViewController, menuTableViewProtocol {

    ...

    // Conforming to Protocal
    func didSelectCell(SelectedCellNumber: Int)
    {
        switch SelectedCellNumber {
        case 0:
            println("0")

        case 1:
            println("1")

        case 2:
            println("2")

        default:
            println("0101010")
        }
    }
}

When I run the app and select a cell, nothing happens. didSelectRowAtIndexpath does get called. (I inserted a println and it prints out), but didSelectCell (the protocol function) doesn't get called. What am I doing wrong and what can I do to fix it?

A: As you mentioned in your comments that you can not set delegate to self and there is no direct relationship between your classes, so you should use NSNotificationCenter instead of protocol and delegate.
//Class A (mainVC.swift)
 //Add Observer in init method
 NSNotificationCenter.defaultCenter().addObserver(self, selector: "handler:", name: "MyNotification", object: nil)

//Handler
func handler(notif: NSNotification) {
    println("MyNotification was handled");
    println("userInfo: \(notif.userInfo)");
    println("SelectedCellNumber \(notif.userInfo!["selectedCellNumber"])"); //Validate userInfo here. it could be nil

}

//Class B (tableView.swift)
// Call from any method
NSNotificationCenter.defaultCenter().postNotificationName("MyNotification", object: nil, userInfo: ["selectedCellNumber" : indexPath.row]);

for more detail, you can follow some tutorials;
http://derpturkey.com/nsnotificationcenter-with-swift/


text:
Q: Function returning a class with a generic type, to returning a class with a specific type If I have the following function:
        public IGenericInterface<T> GetSomething<T>(T GenericType)
        {
            switch (GenericType)
            {
                case SpecificType spec:
                    return new DerivedClass();

                default:
                    return null;
            }
        }

DerivedClass is derived from IGenericInterface<SpecificType>. However I'm getting Cannot implicitly convert type DerivedClass to IGenericInterface<T>.
Why is this happening and is it something that is possible to do? How can I implement a function like this to return any specific implementation of IGenericInterface<T>


text:
Q: Workflow to copy field between lists I have 2 lists:

*

*"General information"(contains field "Current kilometers"(number), "Registration number")

*"Maintenance" (contains field "Kilometres"(number), "Registration Number"(lookup) )
I wanted to create a Workflow so that when the user updates an item in "General information", the value of the "Current kilometres" is to be copied to the "Kilometres" field in the "Maintenance" list.
What I did:

*

*I created a new Workflow for the "General information" list

*I made it to activate on Item Updating

*Then I clicked "this list" and selected as list "Maintenance". I clicked "Add" and in the "Set this field" I chose "Kilometres"; I set "To this value" to: Data source: Current Item, Field from sorce: Current kilometers.

*Then in the section "Find the List Item" I chose Field:Registration Number(the lookup) and Value: Data source: Current Item, Field: Registration Number.
I clicked ok, save, publish. Then tried to update an item in the General information list. Nothing happened to the field in the Maintenance list.
Other Info:

*

*I created the workflow in the SharePoint Designer 2010;

*A lookup field to view the data to the other list is not an option. It has to be done in a workflow.
What am I doing wrong?

A: You can follow the following steps:

*

*Read the current list and save the values of Current kilometers and Registration Number in two varibales.

*Now use the Update Listiem activity and in List option choose "Maintainance" and update the field Kilometres and in the find listitm section use Registration Number

Correct me if i am wrong anywhere.


text:
Q: Laravel access session data inside web.php I can't use localization prefix because of my client's needs. I'm trying to store locale data into session and group my routes based on that 'locale'. But i cant access session data inside web.php.
$locale = Session::get('locale');

    if($locale == 'tr') {
       Route::get('/kurumsal/{slug}', 'App\Http\Controllers\CorporateController@index')->name('corporate');
    } elseif ($locale == 'eng){
       Route::get('/corporate/{slug}', 'App\Http\Controllers\CorporateController@index')->name('corporate');
    }

LanguageController middleware
class LanguageController extends Controller
{
    public function index($locale = ''){
        if ($locale == '') {
            Session::put('locale', 'eng');
        } else {
            Session::put('locale', $locale);
        }
         return redirect()->back();
    }

}

A: For Get Data from session you can use
$value = $request->session()->get('your-key-name');

But I'm not sure It works in Web.php or not..!! But you can use this one in Controller, Middelware etc many more places.
For More Details See Laravel Official Documentation

A: You don't need to conditionally set routes if there's no conflicts.
The following works just fine:
Route::get('/kurumsal/{slug}', 'App\Http\Controllers\CorporateController@index')->name('corporate');
Route::get('/corporate/{slug}', 'App\Http\Controllers\CorporateController@index')->name('corporate');

If you want to restrict non-localised routes from being accessed then you do need session access but you can have that via middleware e.g.:
class LocaleRestricted {

     public function handle($request, $next, ...$localesAllowed) {
          if (!in_array(Session::get('locale'), $localesAllowed)) {
              abort(404, 'This route is not available for this locale');
          }
          return $next($request);
     }
}

You then need to register this locale in your app/Http/Kernel.php:
// ...
protected $routeMiddleware = [
   // ...
   'locale_restricted' => LocaleRestricted::class
];

Then you can use it as:
$locale = Session::get('locale');

Route::middleware('locale_restricted:tr')->group(function () {
       Route::get('/kurumsal/{slug}', 'App\Http\Controllers\CorporateController@index')->name('corporate');
});
Route::middleware('locale_restricted:eng')->group(function () {

       Route::get('/corporate/{slug}', 'App\Http\Controllers\CorporateController@index')->name('corporate');
});


text:
Q: how to post a dummy json response to the server without adding it to database using Django rest framework im trying to figure out is there any way to create post json response  to the server without adding it to database
tried using APIView but that didnt work with my code
async def index(request):
    async with aiohttp.ClientSession() as client:
        data=await(email_sending(client))
        print(data)
        await client.post('http://127.0.0.1:8000/acc/signup/',data=data)
        return web.Response(text="OK")

async def email_sending(client):
    async with client.get('http://www.mocky.io/v2/5c23aef12f00003300049691') as resp:
        resp=await(resp.json())
        totp = pyotp.TOTP('base32secret3232')
        otp=totp.now()
        smtp.sendmail("you@gmail.com",resp['email'], otp)

        # await asyncio.sleep(30)

        sucess=asyncio.create_task(email_verification(otp,client))
        # await sucess
        return resp

async def email_verification(otp,client):
    async with client.get('http://127.0.0.1:8000/connect/hello/') as v_otp:

        v_otp=await(v_otp.json())
        print(v_otp)

here you can see from the following code it gets email adress and username from   another server as json and then sends an otp to that email and now i want to use django rest framework to create a temporary json response for that email_verification step so that i can verify that email (but as of now the code just prints the response)
here is what i have tried earier
@api_view(['GET', 'POST'])
def hello_world(request):
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})
    return Response({"message": "Hello, world!"})

# class hello_world(APIView):
#     def post(self, request):
#         # if request.method==POST:
#             otp=request.data
#             return Response({'otp':otp})

but couldnt figure out how to make it happen


text:
Q: Commit differences between local and remote How can I ask what commits are different between my current local branch and the remote repository that I push to?
Not exactly a git diff origin/master master -- I don't want to see code differences.  Just a list of changes like git log.
I want to quickly see how long it's been since I pushed and how out of sync I am.

A: Git can not send this information remotely.
You would have to do a Git fetch (fetching the changes, without altering your working copy). You will then have a branch called "origin/master" which will enable you to use git log master..origin/master to get the variance between the two.
git fetch
git log master..origin/master

A: You can see which commits are on origin/master but not yet on master using
git log master..origin/master

To see which commits are on your master which you haven't yet pushed, use
git log origin/master..master

A: git log HEAD..origin/yourproject --graph

A: With Visual Studio 2015 and Git version 2.7.1.windows.2, if you just type
git diff origin/master master --name-only

you will receive this:

fatal: ambiguous argument 'origin/master': unknown revision or path not in the working tree.

To work around that, run
git branch -a

which will return something like
* master

  remotes/yourproject

Then use the entire remote path as Git gives it to you, and it will work:
git diff remotes/yourproject master


text:
Q: Why change state to maximized hiding some pixels C# WPF I have made WPF project with window style of none (can resize) then I created custom taskbar on top with exit, maximize and minimize buttons. So exactly this.WindowState = WindowState.Normal; looks like this:

when I press maximize button windows state changes to this.WindowState = WindowState.Maximized; and it does change but hiding some pixels on top and sides (probably on bottom too), see image bellow:

I'cant find anything about it on google and stackoverflow. So here is code am using to change window state:
        private void maximize_Click(object sender, RoutedEventArgs e)
        {
            if(this.WindowState == WindowState.Normal)
            {
                this.WindowState = WindowState.Maximized;
            } else
            {
                this.WindowState = WindowState.Normal;
            }
        }

and to make it maximized without hiding windows bottom taskbar am using this:
        public MainWindow()
        {
            InitializeComponent();
            MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
            MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
        }

I have found reason of this (but not fix yet):
    <WindowChrome.WindowChrome>
        <WindowChrome GlassFrameThickness="0" CornerRadius="0" CaptionHeight="0"
            UseAeroCaptionButtons="False" ResizeBorderThickness="7" />
    </WindowChrome.WindowChrome>

if there is already question about but I couldn't find it please let me know


text:
Q: how to detect toggle with form change I have a section called UPO with upoCost for the section on a form. I use this code to detect if UPO is visible or not, and hence add/subtract base cost of the section.
$("#showUPO").click(function(){
    $("#sectionUPO").toggle();
    if ($("#sectionUPO").is(":hidden")){
        upoCost-=5;
        $("#upoEmailCost").val(upoCost);
    }
    else {
        upoCost+=5;
        $("#upoEmailCost").val(upoCost);
    }
})

So the cost for the section is updated every time I click the button, however the total cost for the form is not.
$("form").on("change", function(){
    var sum = upoCost; // + other costs;
    $("#reqTotalCost").val(sum);
})

I wonder if there's a way to capture it using similar .on("change") methods?

A: $("#upoEmailCost").val(upoCost).trigger('change');

Try manually triggering a change event to bubble up to the form.  Logical changes to an element do not inherently generate events.
$("#showUPO").click(function(){
    var $upo = $("#sectionUPO").toggle();

    if ($upo.is(":hidden")){
        upoCost-=5;
    } else {
        upoCost+=5;
    }

    $("#upoEmailCost").val(upoCost).trigger('change');
});


text:
Q: Reading data value from mysql database through queries I have a login and registration php system on my website. It works perfectly fine. However I would like to add another column to the database. This is balance. I want to display the users 'balance' when they log in on the website.
I have tried to select the balance data value through using this:
<?php
$balance = mysqli_query("SELECT balance FROM users WHERE username='$username'
AND password='$password'");
echo $balance
?>

I am new to php programming therefore I am unsure what is wrong with this piece of code.
The sql database looks as follows:
id    username    email    password    balance
test  test        test     test        test

I would assume from my code that the variable $balance would be set from the value received, that if the username and password entered on the login page is the found on the database. The balance in relation to this will be printed.
This is included in my html part of the web page to display the value of balance:
Balance: <?php echo $balance ?>(current)

When testing the website I get the following error

Warning: mysqli_query() expects at least 2 parameters, 1 given in D:\Windows\xampp\htdocs\TESTSITE\FrontPage.php on line 3

I have tried to figure this out through research but I can't find a solution. Any solutions are welcome as I have reached a stop in development.
In addition I know this is extremely insecure and I shall be ensuring the code is much more secure when the website goes live. I am merely testing at this point.

A: You have 4 issues.

*

*You need to hash your users passwords, storing plaintext passwords is bad practice.

*You need to parameterize your query because without that you are open to SQL injections, and depending on the user's username/password could break your query inadvertently.

*The query function expects parameter 1 to be the connection object.

*The query function returns a result object which needs to be fetched.

Here's an updated version that should function. This assumes $conn is your connection.
<?php
$stmt = mysqli_prepare($conn, "SELECT balance FROM users WHERE username=? AND password=?");
mysqli_stmt_bind_param($stmt, 'ss', $user, $password);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $balance);
mysqli_stmt_fetch($stmt);
echo $balance;
?>

This doesn't account for the hashing. See http://php.net/manual/en/function.password-hash.php and http://php.net/manual/en/function.password-verify.php. You will need to hash all values in your DB currently.

A: *

*If you are using mysqli you must set like this :
$balance = mysqli_query($connection,"SELECT balance FROM users WHERE username='$username'

AND password='$password'"); // $connection is your configuration for connection.

*You must get value from input, like this :
$email = $_POST['email'];
$pass = $_POST['pass'];

Then get boolean from query ,like this :
if($balance) echo 'success' else echo 'wrong';


text:
Q: Why does the program return infeasible when provided with a feasible guess? In order to solve my nonlinear program, I first solve the zero cost version of the problem (i.e. feasibility problem), and use the result as a guess for the full optimization problem.
The feasibility problem, many constraints, among which are constraints of the form x * y = slack in which x, y, slack are all variables (I am using that to represent a relaxed complementarity constraint).  I use the solution to the feasibility problem as the guess to the optimization problem.  The optimization problem is just the feasibility problem with a quadratic cost on the slack added in.
The curious thing is that even with a feasible guess as a starting point, the optimization problem still returns infeasible.  Why is that the case?  Shouldn't the program at least return the initial feasible guess as a solution?
The full program is too long and complicated to be included in this question and I have yet to distill it into a minimally reproducable example.  Perhaps the answer to this question would point me in the right direction to investigate.  Thanks in advance!

A: Since you used SNOPT solver for this problem, and SNOPT uses sequential quadratic programming approach, which doesn't guarantee to generate a feasible solution in every iteration, even if the initial one is feasible.
You could refer to the SNOPT manual https://web.stanford.edu/group/SOL/papers/SNOPT-SIGEST.pdf for more details. What SNOPT does is that it defines a "merit function", which is the combination of the cost and the constraint violation (written as the Lagrangian of the constrained optimization problem), and in each iteration SNOPT attempts to reduce this merit function. So it could increase the violation of the constraint, as long as the cost decrease compensates for the increase of constraint violation.


text:
Q: Bypassing NoneType in a list comprehension To work around when there is no value x.competition.name, I tried to use is not None:
'competition': [x.competition.name if x.competition.name is not None else '-' for x in a]

But the error still keeps showing up:
AttributeError: 'NoneType' object has no attribute 'name'

How can I go about getting around this problem?

A: It sounds like you need to test x.competition:
'competition': [x.competition.name if x.competition is not None else '-' for x in a]

A: Apparently competition is None, so please replace
[x.competition.name if x.competition.name is not None else '-' for x in a]

using
[x.competition.name if x.competition is not None else '-' for x in a]

A: The error message is saying that you tried to get None.name. That means x.competition must be None, which is why you can't get a name attribute from it. Instead, try making your condition x.competition is not None.


text:
Q: Reverting to a specific commit based on commit id with Git? With git log, I get a list of commits that I have made so far.
commit f5c5cac0033439c17ebf905d4391dc0705dbd5f1
Author: prosseek
Date:   Fri Sep 3 14:36:59 2010 -0500

    Added and modified the files.

commit c14809fafb08b9e96ff2879999ba8c807d10fb07
Author: prosseek
Date:   Tue Aug 31 08:59:32 2010 -0500

    Just simple test for core.editor.

... etc ...

*

*How can I revert it back to a specific commit? For example, what should I do if I want to go back to commit c14809fafb08b9e96ff2879999ba8c807d10fb07?

*Is there any other/better way to go back to a specific commit with Git? For example, can I put some label of each commit to get it back with the label?

A: Do you want to roll back your repo to that state, or you just want your local repo to look like that?
If you reset --hard, it will make your local code and local history be just like it was at that commit. But if you wanted to push this to someone else who has the new history, it would fail:
git reset --hard c14809fa

And if you reset --soft, it will move your HEAD to where they were , but leave your local files etc. the same:
git reset --soft c14809fa

So what exactly do you want to do with this reset?
Edit -
You can add "tags" to your repo.. and then go back to a tag. But a tag is really just a shortcut to the sha1.
You can tag this as TAG1.. then a git reset --soft c14809fa, git reset --soft TAG1, or git reset --soft c14809fafb08b9e96ff2879999ba8c807d10fb07 would all do the same thing.

A: git reset c14809fafb08b9e96ff2879999ba8c807d10fb07 is what you're after...

A: I think, bwawok's answer is wrong at some point:

if you do
git reset --soft c14809fa

It will make your local files changed to be like they were then, but leave your history etc. the same.

According to manual: git-reset, "git reset --soft"...

does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

So it will "remove" newer commits from the branch. This means, after looking at your old code, you cannot go to the newest commit in this branch again, easily. So it does the opposide as described by bwawok: Local files are not changed (they look exactly as before "git reset --soft"), but the history is modified (branch is truncated after the specified commit).
The command for bwawok's answer might be:
git checkout <commit>

You can use this to peek at old revision: How did my code look yesterday?
(I know, I should put this in comments to this answer, but stackoverflow does not allow me to do so! My reputation is too low.)

A: If you want to force the issue, you can do:
git reset --hard c14809fafb08b9e96ff2879999ba8c807d10fb07

send you back to how your git clone looked like at the time of the checkin


text:
Q: High availability & scalability for C# I've got a C# service that currently runs single-instance on a PC. I'd like to split this component so that it runs on multiple PCs. Each PC should be assigned a certain part of the work. If one PC fails, its work should be moved to a backup machine.
Data synchronization can be done by the DB, so that should not be much of an issue. My current idea is to use some kind of load balancer that splits and sends the incoming requests to the array of PCs and makes sure the work is actually processed.
How would I implement such a functionality? I'm not sure if I'm asking the right question. If my understanding of how this goal should be achieved is wrong, please give me a hint.
Edit:

*

*I wonder if the idea given above (load balancer splitswork packages to PCs and checks for result) is feasible at all. If there is some kind of already implemented solution so this seemingly common problem, I'd love to use that solution.

*Availability is a critical requirement.

A: I'd recommend looking at a Pull model of load-sharing, rather than a Push model. When pushing work, the coordinating server(s)/load-balancer must be aware of all the servers that are currently running in your system so that it knows where to forward requests; this must either be set in config or dynamically set (such as in the Publisher-Subscriber model), then constantly checked to detect if any servers have gone offline. Whilst it's entirely feasible, it can complicate the scaling-out of your application.
With a Pull architecture, you have a central work queue (hosted in MSMQ, Sql Server Service Broker or similar) and each processing service pulls work off that queue. Expose a WCF service to accept external requests and place work onto the queue, safe in the knowledge that some server will do the work, even though you don't know exactly which one. This has the added benefits that each server monitors it's own workload and picks up work as-and-when it is ready, and you can easily add or remove servers to/from this model without any change in config.
This architecture is supported by NServiceBus and the communication between Windows Azure Web & Worker roles.

A: From what you said each PC will require a full copy of your service -

Each PC should be assigned a certain
  part of the work. If one PC fails, its
  work should be moved to a backup
  machine

Otherwise you won't be able to move its work to another PC.
I would be tempted to have a central server which farms out work to individual PCs. This means that you would need some form of communication between each machine and and keep a record back on the central server of what work has been assigned where.
You'll also need each machine to measure it's cpu loading and reject work if it is too busy.
A multi-threaded approach to the service would make good use of those multiple processor cores that are ubiquitoius nowadays.

A: How about using a server and multi-threading your processing?  Or even multi-threading on a PC as you can get many cores on a standard desktop now.
This obviously doesn't deal with the machine going down, but could give you much more performance for less investment.

A: you can check windows clustering, and you have to handle set of issues that depends on the behaviour of the service (you can put more details about the service itself so I can answer)

A: This depends on how you wanted to split your workload, this usually done by

*

*Splitting the same workload by multiple services

Means same service being installed on
  different servers and will do the
  same job. Assume your service is reading huge data from the db servers and processing them to produce huge client specific datafiles and finally this datafile is been sent to the clients. In this approach all your services installed in diff servers will do the same work but they split the work to increaese the performance.

*Splitting the part of the workload by multiple services

In this approach each service will be assigned to the indivitual jobs and works on different goals. in above example one serivce is responsible for reading data from db and generating huge data files and another service is configured only to read the data file and send it to clients.

I have implemented the 2nd approach in one of my work. Because this let me isolate and debug the errors in case of any failures.

A: The usual approach for load balancer is to split service requests evenly between all service instances.
For each work item (request) you can store relative information in database. Then each service should also have at least one background thread checking database for abandoned work items.

A: I would suggest that you publish your service through WCF (Windows Communication Foundation).
Then implement a "central" client application which can keep track of available providers of your service and dish out work. The central app will act as scheduler and load balancer of the tasks to be performed.
Check out Juwal Lövy's book on WCF ("Programming WCF Services") for a good introduction on this topic.

A: You can have a look at NGrid : http://ngrid.sourceforge.net/
or Alchemi : http://www.gridbus.org/~alchemi/index.html
both are grid computing framework with load balancers that will get you started in no time.
Cheers,
Florian


text:
Q: integrating over the solutions of an implicit equation I have an implicit equation in Mathematica, which I solve by using NSolve. Now, I need to weigh the various solutions according to a Gaussian, but I can't quite make it work. Here is my suggestion so far:
a = (4.2*10^(-5));
b = 4067;
c = 112;
sol[d_] := Select[NSolve[s == (1 + a^2*(2*Pi*1000*d)^2)/((1 + c/(1 + (s*b)/(1 + a^2*(2*Pi*1000*d)^2)))^2 + a^2*(2*Pi*1000*d)^2), {s}], Chop[(Im[s] /. #)] == 0 &][[1]][[1]][[2]];

NIntegrate[Exp[-v^2]*sol[v], {v, -2, 2}]

However, this does not work. Does anyone know what I am doing wrong? What I want is pretty straightforward, but I've had some problems implementing it.
Best,
Niles.

A: Try this; the main points are to use the third argument to NSolve to specify the domain and to make sure the function sol2 is called only on a numerical argument.
sol2[d_?NumericQ] := NSolve[s == (1 +
     a^2*(2*Pi*1000*d)^2)/((1 +
        c/(1 + (s*b)/(1 + a^2*(2*Pi*1000*d)^2)))^2 +
     a^2*(2*Pi*1000*d)^2), {s}, Reals][[1]][[1]][[2]]

NIntegrate[Exp[-v^2]*sol2[v], {v, -2, 2}]
(* 1.66556 *)

Plot[Exp[-v^2]*sol2[v], {v, -2, 2}]