text:
Q: trsp route between two points ( not edge to edge ) I'm trying to solve common problem, how to generate route/navigate between two GPS coordinates and not between two edges using trsp algorithm. I did read many articles here but i'm not sure how should i create temporary edge on huge psql database where even now routing taking several seconds and insert/update can take forewer.
Solution where i will navigate to nearest edge and then calculate distance between edge coordinates and destination coordinates is in my case not good b/c i'm trying to avoid one way streets and this solution is ignoring it.
Another solution i have is to find edge where both start(x1,x2) and end(x2,y2) coordinates are nearest to the destination GPS coordinates ( which does not need to be nearest edge ) and navigate there but found this edge is also very slow.

A: Matus
It seems I am having the same problem. I will give you a partial answer and then present my problem.
Did you try the second version of pgr_trsp? Given start(x1,y1) and end(x2,y2) you can locate the nearest edges with an appropriate query. Then, with Linear Referencing functions, you can have the appropriate floating point (0 to 1) values that represent the points along that edge. Here is what I did:
WITH ways AS    (
    --The following selects the closest segment to the signal
    SELECT DISTINCT ON (tl.oid)     tl.oid AS oid,
                    map.id AS id,
                    map.geom_way AS map_geom,
                    tl.the_geom AS point_geom,
                    tl.veh_id AS veh_id
                FROM gps_signal_table tl
                JOIN ways_table map ON ST_DWithin (tl.the_geom, map.geom_way, 0.001)
            ORDER BY tl.oid,  ST_Distance(tl.the_geom,map.geom_way),tl.veh_id
        )
UPDATE gps_signal_table AS tl SET
    edge_id = id,
    point_on_edge = ST_ClosestPoint (map_geom,point_geom),
    position_on_edge = ST_LineLocatePoint (map_geom,point_geom)
    FROM ways WHERE tl.oid = ways.oid;

My problem lies in the fact that I cannot (yet) take advantage of the results that this function pgr_trsp(sql,edgeid1,position1,edgeid2,position2) produces, i.e. create a LINESTRING geometry from it.
I hope this helps and I hope you can help back!

A: If you don't have an edge from where you want to start from, you won't be able to apply routing logic to it. I suggest reworking your implementation to ensure you have adequate nodes based on your routing needs. If you don't have attributes such as streets, one way properties and so on encoded into your network graph, clearly you aren't going to be able to route it.


text:
Q: Updating multiple records from database at once I just added the names of those undefined index in my edit_mision_vision.php. I have updated my code and it's working now. Thanks for the help :)
update_mission_vision.php // where the update happens and where the notice showed (but it is fixed now) that says vision, mission, and values are undefined
<?php
    $conn=mysql_connect("localhost", "root");
    mysql_select_db("alumni", $conn);
    if (! $conn)
    {
        DIE('Could not connect: ' . mysql_error());
    }

    if(isset($_POST['update']))
    {
    $vision = $_POST['vision'];
    $mission = $_POST['mission'];
    $values = $_POST['values'];

    $query="UPDATE about SET description='$vision' WHERE title='Vision'";
    $retval = mysql_query( $query, $conn );
    $query1="UPDATE about SET description='$mission' WHERE title='Mission'";
    $retval = mysql_query( $query1, $conn );
    $query2="UPDATE about SET description='$values' WHERE title='Values'";
    $retval = mysql_query( $query2, $conn );

    if(! $retval )  {
        DIE('Could not enter data: ' . mysql_error());
    }else{
        echo "";
    }
    }
    if (isset($_POST['cancel']))
    {
        header("Location: /alumni/admin_profile.php");
    }
    mysql_close($conn);
?>

edit_mission_vision.php where i edit the mission, vision, and values description // this is where i added the name="vision", name="mission", name="values" and that solved my problem.
<form action="/alumni/admin/update_mission_vision.php" method="post">
<?php
    include_once 'db.php';
    $sql="SELECT * FROM about";
    $result_set=mysql_query($sql);
    while($row=mysql_fetch_array($result_set))
    {
?>

<?php if($row['title']=='Vision') { ?>
 Vision</labrl>

<textarea id="vision" name="vision" maxlength="1000" height="1000000px" rows="10" cols="100"><?php echo $row['description']; ?></textarea>

<?php  } ?>

<?php if($row['title']=='Mission') { ?>
Mision

<textarea id="mission" name="mission" maxlength="1000" height="1000000px" rows="10" cols="100"><?php echo $row['description']; ?></textarea>

<?php  } ?>

<?php if($row['title']=='Values') { ?>
Values

<textarea id="values" name="values" maxlength="1000" height="1000000px" rows="10" cols="100"><?php echo $row['description']; ?></textarea>

<?php  } ?>

  <?php
    }
    ?>

    <input type="submit" name="update" value="Save Changes"/>
    <input type="submit" name="cancel" value="Cancel"/>
</form>

A: replace this code with your "edit_mission_vision.php" file
<form action="/alumni/admin/update_mission_vision.php" method="post">
<?php
    include_once 'db.php';
    $sql="SELECT * FROM about";
    $result_set=mysql_query($sql);
    while($row=mysql_fetch_array($result_set))
    {
?>

<?php if($row['title']=='Vision') { ?>
 Vision</labrl>

<textarea name="vision" id="vision" maxlength="1000" height="1000000px" rows="10" cols="100"><?php echo $row['description']; ?></textarea>

<?php  } ?>

<?php if($row['title']=='Mission') { ?>
Mision

<textarea name="mission" id="mission" maxlength="1000" height="1000000px" rows="10" cols="100"><?php echo $row['description']; ?></textarea>

<?php  } ?>

<?php if($row['title']=='Values') { ?>
Values

<textarea name="values" id="values" maxlength="1000" height="1000000px" rows="10" cols="100"><?php echo $row['description']; ?></textarea>

<?php  } ?>

  <?php
    }
    ?>

    <input type="submit" name="update" value="Save Changes"/>
    <input type="submit" name="cancel" value="Cancel"/>
</form>

if you get same value in all the three records then you need to create array and then update array in your query via while loop..
and add "[]" after name attribute of textarea.
hope it will help.

A: 1) you need to define name in your all textareas.
2) Why you need three queries in order to update single field?
Try this query :
update `about` set `description` =
                  case
                       when title='Vision' then '$vision'
                       when title='Mission' then '$mission'
                       when title='Values' then '$values'
                  end

Side Note : Stop using mysql_*. It's no more available. use
  mysqli_* or PDO.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MS Excel - Locate like terms in cells I am trying to locate and identify neighboring lines with a matching word.
For example:
| --Col A--     | -Col B- |
| That Car!!    | [blank] |
| Blue Car$     | [blank] |
| Ponies^!_     | [blank] |
| Car Sales     | [blank] |
| Detroit__     | [blank] |
| Banana^       | [blank] |

"That Car!!" and "Blue Car$" are neighboring cells both containing the word "car."
I cannot figure out how to write a =formula() in Col B to identify matching words.  All the formula needs to do is identify the duplicate word (not case sensitive) and output the word "BLANK" for the second line.
Remove Duplicates will do the rest.
The line containing "Car Sales" will not be identified.
How can I do this?

A: This stackoverflow answer contains a custom VBA function to calculate similarity between texts: https://stackoverflow.com/a/42657518/4721734
Using that, you can write something like this formula:
=IF(Similarity(A2,A3)>=0.5,A3,"BLANK")

A: Here is a Power Query solution (that will also remove that unwanted row)
Power query is available in Windows Excel 2010+ and Office 365

*

*Select some cell in your Data Table

*Data => Get&Transform => from Table/Range

*When the PQ Editor opens: Home => Advanced Editor

*Make note of the Table Name in Line 2

*Paste the M Code below in place of what you see

*Change the Table name in line 2 back to what was generated originally.

*Read the comments and explore the Applied Steps to understand the algorithm

M Code
let
    Source = Excel.CurrentWorkbook(){[Name="Table8"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}}),

//remove the non-alphabet characters and split into List of Words
    #"Added Custom" = Table.AddColumn(#"Changed Type", "Remove non-alpha characters",
        each Text.Split(Text.Combine(
            List.Accumulate(Text.ToList([Column1]),{},
                (state,current)=> if List.Contains({"A".."Z"," ","a".."z"},current) then
                List.Combine({state,{current}}) else state))," ")),

//Add a column representing the previous row
    ShiftedList = {null} &  List.RemoveLastN(Table.Column(#"Added Custom", "Remove non-alpha characters"),1),
    Custom1 = Table.ToColumns(#"Added Custom") & {ShiftedList},
    prevRow = Table.FromColumns(Custom1, Table.ColumnNames(#"Added Custom") & {"Previous Row"}),

//Mark "BLANK" if previous row has the same word in the list of words
    #"Added Custom1" = Table.AddColumn(prevRow, "Blank", each
        try if List.ContainsAny([#"Remove non-alpha characters"],[Previous Row],Comparer.OrdinalIgnoreCase)
             then "BLANK" else null otherwise null),

//filter out the non-null rows
    #"Filtered Rows" = Table.SelectRows(#"Added Custom1", each ([Blank] = null)),

//Remove unneeded columns
    #"Removed Columns" = Table.RemoveColumns(#"Filtered Rows",{"Remove non-alpha characters", "Previous Row", "Blank"})
in
    #"Removed Columns"


text:
Q: Confusion about $q and promises I have read up on Kris Kowal's Q and angularjs $q variable for a few hours now. But for the life of me I can't figure out how this works.
At the moment I have this code in my service:
resetpassword: function (email, oldPassword, newPassword) {

                var deferred = $q.defer(); //Why am I doing this?
                var promise = auth.$changePassword(email, oldPassword, newPassword); //$changepassword in angularfire returns a promise
                console.log(deferred); //Object with resolve, reject, notify and promise attrs
                var rValue = promise.then(function(){
                        //successcallback
                        return 1; //if changepassword succeeds it goes here as expected
                    }, function(error){
                        //errorcallback
                        return error.code; //if changepassword fails (wrong oldpass for example) it goes here, also works
                    }
                );
                deferred.resolve(promise); //Should I do this? I thought my promise was resolved in the callbacks?
                console.log(rValue); //This outputs another promise? Why not 1 or error.code, how the am I ever going to get these values??
                return rValue; //I want 1 or error.code to go back to my controller
            },

A: var deferred = $q.defer(); //Why am I doing this?

It's the deferred anti-pattern that you are doing because you don't understand promises. There is literally never a good reason to use $q.defer() in application logic.
You need to return a promise from your function:
resetpassword: function(email, oldPassword, newPassword) {
    return auth.$changePassword(email, oldPassword, newPassword)
           .then(function() { return 1; })
           .catch(function(e) { return e.code });
}

Usage is:
resetpassword(...)
.then(function(num) {
    if (num === 1) {

    }
    else {

    }
});

It helps to think how the function would be written in synchronous code:
 resetpassword: function(email, oldPassword, newPassword) {
     try {
         auth.$changePassword(email, oldPassword, newPassword)
         return 1;
     }
     catch (e) {
         return e.code;
     }
 }

A: A promise is a function that does not execute immediately.  Instead, you are 'promising' to respond to the status of a deferred object whenever it has completed it's processing.  Essentially, you are creating an execution chain that simulates multiple threads.  As soon as a deferred object is complete, it returns a status code, the calling function is able to respond to the status code, and return it's own status code if necessary, etc.
var deferred = $q.defer();

Here you are creating a deferred object, to hold the callbacks which will be executed later.
var promise = auth.$changePassword(email, oldPassword, newPassword);

This is the actual function, but you are not calling it here. You are making a variable to reference it, so that you can monitor it.
var rValue = promise.then(function(){

The .then() is the function that will be executed if the promise is successful. Here you are inlining a function that will execute upon the success of the promise's work.
}, function(error){

And then chaining the error function, which is to be executed if the promise fails. You are not actually doing anything here other than returning the error code, but you could do something to respond to the failure yourself.
deferred.resolve(promise);

This is the point where you are actually telling your deferred object to execute the code, wait for a result, then execute either the success or the failure code as appropriate.  The promise is added to the execution chain, but your code is now free to continue without waiting and hanging up.  As soon as the promise is finished and a success or failure is processed, one of your callback functions will process.
 console.log(rValue);

Your function is not returning the actual values here because you don't want your function to stop and wait for a response before continuing, since this would block the program until the function completes.
return rValue;

You are returning your promise to the caller.  Your function is a promise which is calling a promise which might be calling another promise, etc.  if your function was not a promise, then even though the code you are calling is not blocking, your code would become a block as you wait for the execution to complete.  By chaining promises together, you are able to define how you should respond without responding at exactly that moment.  You are not returning the result directly, but instead 'promising' to return a success or fail, in this case passing through the success or fail from the function you are calling.

A: What you have done is mixed promises. As you put in the code comments,

$changepassword in angularfire returns a promise

Basically, var deferred = $q.defer() creates a new promise using deferred.promise, but you are already creating a promise with $changePassword. If I understand what you are trying to do correctly, you would simply need to do this.
resetpassword: function (email, oldPassword, newPassword) {
    auth.$changePassword(email, oldPassword, newPassword).then(function(result)       {
        console.log(result); // success here
    }, function(err){
        console.log(err); // error here
    });
}

EDIT:
Upon Robins comment, if you want to deal with the result in a controller, rather than call the then() function inside the service, return the promise itself to the controller. Here is an example:
Service function:
resetpassword: function (email, oldPassword, newPassword) {
    // return the promise to the caller
    return auth.$changePassword(email, oldPassword, newPassword);
}

Controller function:
.controller('MyCtrl', ['$scope', 'myService', function($scope, myService){
    // get the promise from the service
    myService.resetPassword($scope.email, $scope.oldPassword, $scope.newPassword).then(function(result){
        // use 1 here
    }, function(err){
        // use err here
    });
}]);

A: You use deferred promises when you are going to perform a task that will take an unknown amount of time, or you don't care when it gets done - an Asynchronous task. All you care about is getting a result back whenever the code you called tells you that the task is completed.
What you should be doing in your function is returning a promise on the deferred that you are creating. Your code that calls resetpassword should then wait for this promise to be resolved.
function (email, oldPassword, newPassword) {

                var deferred = $q.defer(); //You are doing this to tell your calling code when the $changepassword is done. You could also return the promise directly from angularfire if you like but of course the return values would be different.
                var promise = auth.$changePassword(email, oldPassword, newPassword); //$changepassword in angularfire returns a promise
                console.log(deferred); //Object with resolve, reject, notify and promise attrs
                promise.then(function(){
                        //successcallback
                        deferred.resolve(1); //if changepassword succeeds it goes here as expected
                    }, function(error){
                        //errorcallback
                        deferred.reject(0); //if changepassword fails (wrong oldpass for example) it goes here, also works
                    }
                );
                // Quite right, you should not do this.
                console.log(rValue); //This outputs another promise? Why not 1 or error.code, how the am I ever going to get these values??
                return deferred.promise; // Return the promise to your controller
            }


text:
Q: How to implement Dirichlet distribution formula in php Refer to this image
From the above, I want to find the dirichlet distribution, variables are listed in the picture.
I got probability calculation formula From this, I want to find the next step that is Dirichlet distribution.
function weighted_random($values, $weights) {
    $count = count($values);
    $i = 0;
    $n = 0;
    $num = mt_rand(0, array_sum($weights));

    while($i < $count) {
        $n += $weights[$i];

        if($n >= $num) {
            break;
        }

        $i++;
    }

    return $values[$i];
}


text:
Q: Friendly ID not updating slug Using Rails 5 with Friendly ID 5.1.0
Trying to understand how to update the slug when a Post title is changed.
In the Friendly ID documentation it says you have to update the slug to nil before you can save your updated slug.
Example
post = Post.first
post.title # "My first post"
post.slug = "my-first=post"
post.title = "My newer first post"
post.save!
post.slug # "my-first=post"

# Setting to nil first
post.slug = nil
post.title = "My newer first post"
post.save!
post.slug # "my-newer-first-post"

In my Post model I have set should_generate_new_friendly_id? in hopes it will update the slug without manually setting the slug to nil from the console or a web form.
# == Schema Information
#
# Table name: post
#
#  id         :integer          not null, primary key
#  title      :string           default(""), not null
#  body       :text             default(""), not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  slug       :string
#
# Indexes
#
#  index_posts_on_slug  (slug) UNIQUE
#

class Post < ApplicationRecord
  extend FriendlyId
  friendly_id :title, use: :history

  private

    def should_generate_new_friendly_id?
      title_changed? || super
    end
end

Is it the job of the should_generate_new_friendly_id? method to update the slug if it's defined in your model?
Thanks again.

A: Just add this method in your model:
def should_generate_new_friendly_id?
 title_changed?
end

A: Looking at the source code, you should change the private method to:
def should_generate_new_friendly_id?
  slug.blank? || title_changed?
end

For reference https://github.com/norman/friendly_id/blob/b6b6c004890ae3558a8ee19cc004a1456d9d0fff/lib/friendly_id/initializer.rb#L78


text:
Q: Macros in the Cider repl (e.g. ->) why is the use of the threading macro ->> producing an error in the cider-repl:
(-> "x..")

//  Unable to resolve symbol: -> in this context

A: this happens when you create a new namespace in the repl and have not yet defined anything in it. so the aliases for the clojure.core functions have not yet been established:
start by creating a new blank namespace:
user> (in-ns 'i-dont-exist-yet)
#namespace[i-dont-exist-yet]

Then try to use the threading macro (or anything from clojure.core):
i-dont-exist-yet> (-> 1)
CompilerException java.lang.RuntimeException: Unable to resolve symbol: -> in this context, compiling:(*cider-repl api*:47:18)

which fails to lookup the symbol -> in the current namespace, though it works if you tell it which namespace to use explicitly:
i-dont-exist-yet> (clojure.core/-> 1)
1

There is a convenience function in clojure.core that will add all the expected refers for your new namespce. You won't need to do this when you create your namespace from a file with the ns macro at the top because ns does this for you (amongst other useful things):
i-dont-exist-yet> (clojure.core/refer-clojure)
nil
i-dont-exist-yet> (-> 1)
1


text:
Q: Using Date( strtotime()) and AM/PM I am trying to receive a PM from my date()but I am always getting a AM back.
I looked in our MYSQL database and the datatype is set to TIME.
I was wondering how I can fix this within PHP. IF it is a database issue, what is the best datatype so I can receive AM/PM?
Here is my code(The sun rise row is working perfectly. The Sun set row is returning a AM...)
            <?= $time= date("g:i A", strtotime("$srise_dec")) ?>

            Average Sunset

            <?= $time= date("G:i A" , strtotime("$sset_jan")) ?>


text:
Q: Java Rest API secured by Azure AD I've an angular app which calls a java rest api to get the data. We need to secure these apps by azure AD.
I'm using ADAL.js library for angular app and trying to find any library which can be used for rest api but haven't found any on the internet. All the samples are provided for webAPi which is using Microsoft's OWIN framework.
Currently my understanding is that,  our angular app will call to Azure AD to get the access token and will send that to java rest api.
Its a JWT token signed by RSA private key.
I can get the public key from JWKs uri and validate whether the JWT token and its signature is valid or not. If it's valid, the rest api will send the response back to angular app
 -  Is it enough on rest api side? Don't we need any communication between Rest api and Azure AD ? What if someone steals the access token and use that (within its expiration period ?)
I was under impression that resource server ( java rest api) also needs to talk to Authorization server (Azure AD) but not sure if it's really required for JWT tokens.

A: @Deb,I found your reqirement matched this scenarios----Web application to Web API.I recommend you refer to this document(
https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/#web-application-to-web-api). If your front-end used the Angular App, you could use passportjs to pass Azure AD authorization. Please refer to documnet(
https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-webapi-nodejs/#6-install-passportjs-in-to-your-web-api).

Its a JWT token signed by RSA private key. I can get the public key
  from JWKs uri and validate whether the JWT token and its signature is
  valid or not. If it's valid, the rest api will send the response back
  to angular app - Is it enough on rest api side? Don't we need any
  communication between Rest api and Azure AD ?

If you got the access_token,you could call your REST API with this token in your request.  You need not any communication between REST API and AAD. But please note, you need make your API application trust another application

What if someone steals the access token and use that (within its
  expiration period ?) I was under impression that resource server (
  java rest api) also needs to talk to Authorization server (Azure AD)
  but not sure if it's really required for JWT tokens.

You also can set the expiration time in your application for the tokens. See the part 'Token Expiration' in this document(https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/#application-types-and-scenarios)


text:
Q: How to combine multiple vars files per host? I have a playbook running against multiple servers. All servers require a sudo password to be specified, which is specific to each user running the playbook. When running the playbook, I can't use --ask-become-pass, because the sudo passwords on the servers differ. This is the same situation as in another question about multiple sudo passwords.
A working solution is to specify ansible_become_pass in host_vars:
# host_vars/prod01.yml
ansible_become_pass: secret_prod01_password
domain: prod01.example.com

# host_vars/prod02.yml
ansible_become_pass: secret_prod02_password
domain: prod02.example.com

Besides ansible_become_pass, there are other variables defined per host. These variables should be committed to the git repository. However, as ansible_become_pass is specific to each user running the playbook, I'd like to have a separate file (ideally, vaulted) which specifies the password per host.
I imagine the following:
# host_vars/prod01.yml: shared in git
domain: prod01.example.com

# host_vars/prod01_secret.yml: in .gitignore
ansible_become_pass: secret_prod01_password

I imagine both files to be combined by Ansible when running the playbook. Is this possible in Ansible? If so, how?

A: You should be able to use the include_vars task with the inventory_hostname or ansible_hostname variable.  For example:
- name: Include host specific variables
  include_vars: "{{ ansible_hostname }}.yml"

- name: Include host specific secret variables
  include_vars: "{{ ansible_hostname }}_secret.yml"

An even better solution would be to address the problem of users having unique passwords on different hosts.

A: You could create a new group in the inventory file, maybe sudo-hosts. Put all your sudo host in this group. Then create a file under the directory group_vars with the name of this goup. In this file put the secret yaml-structured text.
sudo_hosts:
  host1:
    password: xyz
    othersecret_stuff: abc
  host2:
    ...

then use ansbile-vault to encrypt this file with ONE password. Call the playbook with option --ask-vault-pass
and you can use your secrets with
"{{ sudo_host['ansible_host'].password }}"


text:
Q: Non-Zero exit of Perl script In my Perl script, if I use exit(-1), the script exits. But if I use exit(-433) or exit(-233), it doesn't exit. Why? An example follows.
if ($result1[0] eq "Error") {
    print "Error occurred while updating https route\n";
    print "Error returned from the script:\n";
    print $result1[1];
    exit(-377);
}

A: Run perlbug to submit a bug report. Despite your incorrect argument, that shouldn't prevent exit from functioning.
As you can see (by the face that y is never printed), I can't replicate this on a Linux system:
$ perl -E'say "x"; exit($ARGV[0]); say "y";' -- -377 ; echo $?
x
135

$ perl -E'say "x"; exit($ARGV[0]); say "y";' -- -1 ; echo $?
x
255

$ perl -E'say "x"; exit($ARGV[0]); say "y";' -- -433 ; echo $?
x
79

$ perl -E'say "x"; exit($ARGV[0]); say "y";' -- -233 ; echo $?
x
23

0..255 are acceptable on unix systems. 0..65535 on Windows.

A: I would even restrict the exit value to 0..127, for the following reason: If your program (on Unix) is killed by signal N, the exit value is set to N+128. Hence, if you use higher exit values, you can't distinguish a "normal" exit from one forced by a signal.


text:
Q: I'm trying to install psycopg2 onto Mac OS 10.6.3; it claims it can't find "stdarg.h" but I can see it's there; what should I do? I'm desperately trying to successfully install psycopg2 but keep running into errors. The latest one seems to involve it not being to find "stdarg.h" (see code below). However I can see with my own eyes that a file called stdarg.h exists at /Developer/SDKs/MacOSX10.4u.sdk/usr/include/stdarg.h (where it claims it can't find anything) so I've no idea what to do about it.
I'm running Mac OS 10.6.3 and within the last few days I've made sure I have all the latest OS developer tools.
I have Python 2.6.2 and PostgreSQL 8.4 if that makes any difference.
python setup.py install
running install
running build
running build_py
running build_ext
building 'psycopg2._psycopg' extension
creating build/temp.macosx-10.3-fat-2.6
creating build/temp.macosx-10.3-fat-2.6/psycopg
gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.2.1 (dt dec ext pq3)" -DPG_VERSION_HEX=0x080404 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -DHAVE_PQPROTOCOL3=1 -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -I. -I/opt/local/include/postgresql84 -I/opt/local/include/postgresql84/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.3-fat-2.6/psycopg/psycopgmodule.o
In file included from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/unicodeobject.h:4,
             from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:85,
             from psycopg/psycopgmodule.c:27:
/Developer/SDKs/MacOSX10.4u.sdk/usr/include/stdarg.h:4:25: error: stdarg.h: No such file or directory
In file included from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/unicodeobject.h:4,
             from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:85,
             from psycopg/psycopgmodule.c:27:
/Developer/SDKs/MacOSX10.4u.sdk/usr/include/stdarg.h:4:25: error: stdarg.h: No such file or directory
lipo: can't figure out the architecture type of: /var/folders/MQ/MQ-tWOWWG+izzuZCrAJpzk+++TI/-Tmp-//ccakFhRS.out
error: command 'gcc' failed with exit status

A: I don't know your specific problem but i recommend you to install it using macports.
Installing psycopg2 is as simply as:
sudo port install py26-psycopg2

A: The following works for me:

*

*$ mkvirtualenv --no-site-packages --distribute psycopg2_test

*$ cd $VIRTUAL_ENV

*$ pip install psycopg2
Notes

*

*I installed my base Python via MacPorts.

*The above commands make use of:

*

*pip

*virtualenvwrapper

*virtualenv

*I bootstrapped pip via the following:

*

*wget http://python-distribute.org/distribute_setup.py

*python distribute_setup.py

*easy_install pip
UPDATE: I realize it seems like a lot of yak shaving, but learning how to use virtualenv and friends is an up-front investment that pays off pretty quickly, especially when dealing with projects that have a lot of dependencies.

A: I actually had a very similar problem as this (except with OSX Lion, Python 2.7) Can't install psycopg2 in virtualenv "error: stdarg.h: No such file or directory".
I ended up using this solution: https://stackoverflow.com/a/8834568/396327
Basically, uninstalling/reinstalling XCode from scratch (and a few more hacks to get it to recognize gcc-4.2).


text:
Q: Sphinx api-doc not putting packages together Background
My code has the following structure:
.
└── my_package
    ├── __init__.py
    ├── classif
    │   ├── __init__.py
    │   ├── inference.py
    │   └── models.py
    ├── datasets
    │   ├── __init__.py
    │   └── datasets.py
    └── matching
        ├── __init__.py
        ├── elastic.py
        └── search.py

After a sphinx-quickstart (with autodoc) I ran sphinx-apidoc as follows:
sphinx-apidoc -f -o source my_package -e -M

I now have the following files:
.
├── Makefile
├── build
├── my_package
│   ├── __init__.py
│   ├── __pycache__
│   ├── classif
│   ├── datasets
│   └── matching
└── source
    ├── _static
    ├── _templates
    ├── conf.py
    ├── index.rst
    ├── modules.rst
    ├── my_package.classif.inference.rst
    ├── my_package.classif.models.rst
    ├── my_package.classif.rst
    ├── my_package.datasets.datasets.rst
    ├── my_package.datasets.rst
    ├── my_package.matching.elastic.rst
    ├── my_package.matching.rst
    ├── my_package.matching.search.rst
    └── my_package.rst

I also modified conf.py to add:
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))

and added modules to the index.rst:
.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules

# [more lines]

Now here is the issue
After running make clean ; make html I get the warnings:
/path/to/my_package.classif.rst: WARNING: document isn't included in any toctree
/path/to/my_package.datasets.rst: WARNING: document isn't included in any toctree
/path/to/my_package.matching.rst: WARNING: document isn't included in any toctree

Which makes sense as sphinx-apidoc did not reference them in my_package.rst. How can I solve this?

A: The issue was actually known -> https://github.com/sphinx-doc/sphinx/issues/4446
Upgrading to sphinx 1.7.6 solved it.


text:
Q: ganglia generated too much rrd files & cannot automatic deleted I'm using ganglia 3.7.2 for monitoring hadoop(2.6.0-cdh5.4.0) cluster(7 servers), And I enabled metrics2 on hadoop & hbase;
I installed gmetad on one server, and gmond on the other servers with yum ;
At the beginning , the monitor runs very well, I can see the normal monitor data on the ganglia web page, but the problem is :
After several hours, the rrd files are too many, so I have to make symbol link for path /var/lib/ganglia/rrds, and after a couple of days, the rrd files occupied almost 1TB disk space, and web page cannot show up the monitor data, anybody know how to fix this ?
gmond config (using single channel):
globals {
daemonize = yes
setuid = yes
user = ganglia
debug_level = 0
max_udp_msg_len = 1472
mute = no
deaf = no
allow_extra_data = yes
host_dmax = 86400 /*secs. Expires (removes from web interface) hosts in 1 day */
host_tmax = 20 /*secs */
cleanup_threshold = 300 /*secs */
gexec = no
send_metadata_interval = 60 /*secs */
}

A: Resolved this problem, and I did the things below:

*

*Changed default rrd rule to :
RRAs "RRA:AVERAGE:0.5:1:256" "RRA:AVERAGE:0.5:24:512" "RRA:AVERAGE:0.5:168:512" "RRA:AVERAGE:0.5:672:512" "RRA:AVERAGE:0.5:5760:1024"

*Closed the datanode.sink and nodemanager.sink of hadoop metric2;
Reference: http://www.perzl.org/ganglia/bestpractices.html##Best_Practices_Ganglia_Sampling


text:
Q: Codeigniter curl cron job and sessions I'm using CodeIgniter and I have cron jobs run with curl, for example:
0,30 * * * * curl --silent http://example.com/cron/1

I also store sessions in the database
But session also storing curl in the database.
How to avoid this?
The server is running on Centos 6
Or I can make call to cron without curl to not use session?

A: I think this is the simplest way to get codeigniter working under cron job,
You can use curl in cron jobs to execute or run the codeigniter in cron jobs Example:

*

*
*

*
*

*
*

*
*

*/usr/bin/curl https://www.domain.com/controller/function
I used this way, but I did not get curl in DB.


text:
Q: MSSQL Database Slow after upgrading to SQL 2012 We are in the process of moving our large database from a local server (MSSQL 2000) to a SQL 2012 Server hosted on Amazon Web Services.
I created a new database from scratch on the new server, ran a script to create the tables, imported all the data and then ran SQL compare to build all the stored procedure and views etc.
A stored procedure when run on the local server took 2 mins but now running on SQL 2012 it's going over 30 mins and timing out.
I've rebuilt all the indexes and updated the statistics as well as running the stored procedure on the server rather than remotely but no difference.
Any suggestions?
Update - More Info
Thanks for your replies
[Old Server] AMD Quad Codde 2376 2.29Ghz with 4GB Ram running Windows 2003  + SQL 2000
[New AWS Instance] Intel Xeon E5-2670 2.50Ghz with 30.5 GB Ram running Windows 2012 + SQL 2012

wait_type                           wait_time_s pct running_pct

DIRTY_PAGE_POLL                     23132.77    28.47   28.47

HADR_FILESTREAM_IOMGR_IOCOMPLETION  23131.66    28.47   56.95

SP_SERVER_DIAGNOSTICS_SLEEP         23100.10    28.43   85.38

LATCH_EX                            4784.63     5.89    91.27

SOS_SCHEDULER_YIELD                 1548.42     1.91    93.18

LCK_M_U                             1438.27     1.77    94.95

WRITELOG                            753.34      0.93    95.87

A: You have to start from somewhere, analysing the server. As you claim that you've updated the stats/indexes, next is to see where it hurts. Use this widely used script for finding the wait stats so you can inhale the situation better.
WITH [Waits] AS
    (SELECT
        [wait_type],
        [wait_time_ms] / 1000.0 AS [WaitS],
        ([wait_time_ms] - [signal_wait_time_ms]) / 1000.0 AS [ResourceS],
        [signal_wait_time_ms] / 1000.0 AS [SignalS],
        [waiting_tasks_count] AS [WaitCount],
        100.0 * [wait_time_ms] / SUM ([wait_time_ms]) OVER() AS [Percentage],
        ROW_NUMBER() OVER(ORDER BY [wait_time_ms] DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats
    WHERE [wait_type] NOT IN (
        N'CLR_SEMAPHORE',    N'LAZYWRITER_SLEEP',
        N'RESOURCE_QUEUE',   N'SQLTRACE_BUFFER_FLUSH',
        N'SLEEP_TASK',       N'SLEEP_SYSTEMTASK',
        N'WAITFOR',          N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',
        N'CHECKPOINT_QUEUE', N'REQUEST_FOR_DEADLOCK_SEARCH',
        N'XE_TIMER_EVENT',   N'XE_DISPATCHER_JOIN',
        N'LOGMGR_QUEUE',     N'FT_IFTS_SCHEDULER_IDLE_WAIT',
        N'BROKER_TASK_STOP', N'CLR_MANUAL_EVENT',
        N'CLR_AUTO_EVENT',   N'DISPATCHER_QUEUE_SEMAPHORE',
        N'TRACEWRITE',       N'XE_DISPATCHER_WAIT',
        N'BROKER_TO_FLUSH',  N'BROKER_EVENTHANDLER',
        N'FT_IFTSHC_MUTEX',  N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
        N'DIRTY_PAGE_POLL', N'SP_SERVER_DIAGNOSTICS_SLEEP')
    )
SELECT
    [W1].[wait_type] AS [WaitType],
    CAST ([W1].[WaitS] AS DECIMAL(14, 2)) AS [Wait_S],
    CAST ([W1].[ResourceS] AS DECIMAL(14, 2)) AS [Resource_S],
    CAST ([W1].[SignalS] AS DECIMAL(14, 2)) AS [Signal_S],
    [W1].[WaitCount] AS [WaitCount],
    CAST ([W1].[Percentage] AS DECIMAL(4, 2)) AS [Percentage],
    CAST (([W1].[WaitS] / [W1].[WaitCount]) AS DECIMAL (14, 4)) AS [AvgWait_S],
    CAST (([W1].[ResourceS] / [W1].[WaitCount]) AS DECIMAL (14, 4)) AS [AvgRes_S],
    CAST (([W1].[SignalS] / [W1].[WaitCount]) AS DECIMAL (14, 4)) AS [AvgSig_S]
FROM [Waits] AS [W1]
INNER JOIN [Waits] AS [W2]
    ON [W2].[RowNum] <= [W1].[RowNum]
GROUP BY [W1].[RowNum], [W1].[wait_type], [W1].[WaitS],
    [W1].[ResourceS], [W1].[SignalS], [W1].[WaitCount], [W1].[Percentage]
HAVING SUM ([W2].[Percentage]) - [W1].[Percentage] < 95; -- percentage threshold
GO

I assume it is this option called "TARGET_RECOVERY_TIME" and is set using ALTER DATABASE command. For more details refer BOL at http://msdn.microsoft.com/en-us/library/hh403416(v=sql.110).aspx.
By just setting TARGET_RECOVERY_TIME to something different than 0 you're actually enabling the indirect checkpoint which is more efficient and brings optimization. Set it for example to 60 seconds and watch how your system behaves.


text:
Q: Active Partitions In Windows 10 I have a question about active partitions (Windows 10).  When I installed Windows on SSD#1, Windows decided to place the active partition on SSD#2 (which I use for nothing at the moment; I know this because I can see it in disk manager and also through diskpart).
What I want to do is take SSD#2 and put it in an HTPC I'm building.  I took out SSD#2 yesterday but my the computer said:

Reboot and select proper boot device or insert boot media in selected boot device and press a key.

I plugged it back in and the computer booted up normally.
My question is, how do I move the active partition to my actual boot drive (SSD#1)? If I go to disk management I can make a small partition on SSD#1 and set it as active as opposed to SSD#2, but
a. will that also add the necessary boot files to the new partition? and
b. would that mess something up with Windows booting?

A: What you need is partition management and cloning software. Personally I use Paragon Hard Disk Manager (which would make much of what I'm about to say much easier... but it's not cheap). You can find free solutions such as GPartEd and clonezilla.
In your case you appear to already have enough free space available on Disk 0, so you only need clonezilla. Using that you can make a copy of the first partition from Disk 1 to the unallocated space on Disk 0. Understand that the names and even the order the drives are listed under clonezilla will be different. But you should be able to identify which is which by their dramatically different total capacities.
However, that still will not let you boot when you remove Disk 1. This is because there is a special bit of code found outside the partition in a place called the "boot sector". This bit of code is necessary for your BIOS to find the windows 10 boot loader and begin booting windows.
But before you solve that problem there is yet another: The active partition only indicates the boot partition for that drive. Each drive can have it's own Active partition. The point is that the "Active" partition does not, tell the BIOS which drive to boot.
To tell your BIOS which drive to boot you will need to go into your BIOS and check your boot settings, making sure your system drive is the first in the boot order. In fact, the reason windows may have installed it's boot files to the second drive is that it may have detected that this is your currently configured boot drive.
Once the BIOS is booting the correct drive you can solve the missing boot sector code by booting from your Windows 10 DVD and entering the recovery environment. Then run the "Startup Repair" option. This should find the missing boot sector code and create it again on your currently configured boot drive.
One last detail. Understand that your system appears to be using the older BIOS boot method. However, EFI is the default with fresh installations of Windows 10. As such most of the information out there about solving this problem will be focused on EFI and will not be relevant to you. Keep this in mind.


text:
Q: "have no pig in the race": is it an idiom? Below is an excerpt from an essay on Literary Hub:

It was sweet that readers who have absolutely no pig in the race would care so much about a story that they wanted to shout it from the rooftops.

I have never come across this alleged idiom, so I turned to OED but to no avail. Results from COCA for "no pig" are rather immaterial, too. Then I searched Google for "no pig in the race", to find out that there seems to be something like pig-racing in North Carolina State Fair, but nothing relevant to the usage in the above sentence.
I was a little confused. The author of the essay above used this expression like it was an idiom, but I reckon there should be some steps away from "unfamiliar phrases you can guess upon" to an easily recognizable idiom.

A: Your instinct is correct, and the author is apparently being facetious. The actual idiom is "have no horse in this race". From The Free Dictionary:

A phrase said when one is not invested in or affected by the outcome of something.

I haven't looked at your link, so I don't know the context of that sentence, but presumably there is some reason why the author changed "horse" to "pig".


text:
Q: TextWrapped Label breaks Layout Option FillAndExpand in StackLayout I'm having a cell view with nested StackLayouts, there's one label that will be wrapped if the text is long, which is the desired behaviour. However, the wrap breaks the LayoutOptions set to (basically) all parent views resulting in a gray gap on the right hand side.
    <StackLayout Orientation="Horizontal" BackgroundColor="Gray" Margin="0,30,0,0">
        <BoxView
            HorizontalOptions="Start"
            BackgroundColor="#EEBB00"
            WidthRequest="100"
        />
        <StackLayout
            BackgroundColor="#CC4400"
            HorizontalOptions="FillAndExpand"
        >
            <BoxView
                BackgroundColor="Green"
                HeightRequest="10"
                HorizontalOptions="FillAndExpand"
            />
            <Label
                FontSize="16"
                HorizontalOptions="FillAndExpand"
                Text="Name that is toolongandwillbewrapped"
            />
            <StackLayout
                Orientation="Horizontal"
                HorizontalOptions="FillAndExpand"
                BackgroundColor="Blue"
            >
                <Label
                    FontSize="13"
                    Text="Left"
                    TextColor="White"
                    HorizontalOptions="StartAndExpand"
                    VerticalTextAlignment="End"
                />
                <Label
                    FontSize="13"
                    Text="Right"
                    TextColor="White"
                    HorizontalOptions="EndAndExpand"
                    VerticalTextAlignment="End"
                />
            </StackLayout>
        </StackLayout>
    </StackLayout>

The resulting views are:

So I can tell why this is happening, but well, of course I don't like it. The expected behaviour is for the right-hand-side stacklayout to expand all the way to the right. I've tried various ways to circumvent this and would not be here if I had succeeded. Does anybody have an idea?

A: Unfortunately, it's a bug in Xamarin.Forms (probably, iOS-only).

*

*Bugzilla #28650

*Bugzilla #31128

*Bugzilla #33841
The workaround in that case is using Grid instead of StackLayout : http://forums.xamarin.com/discussion/comment/152969/#Comment_152969


text:
Q: Use deep-first-search. Find out all the articulation points and biconnected components. Show the change process of Low[v] for each node Given the following undirected graph G = (V, E). Using vertex s as the source vertex.
If multiple neighbors are available, visit them using alphabetical order.


text:
Q: C++ and preprocessor macros: variadic type Take for example the following macro:
#define _CREATE_VAR(X1) double X1{smc::define_variable (data, X1, #X1)};
#define _CREATE_VAR2(X1,X2) double X1{smc::define_variable (data, X1, #X1)}; /
                        double X2{smc::define_variable (data, X2, #X2)}; /
#define _CREATE_VAR3(X1,X2,X3) double X1{smc::define_variable (data, X1, #X1)}; /
                        double X2{smc::define_variable (data, X2, #X2)}; /
                        double X3{smc::define_variable (data, X3, #X3)}; /
#define _CREATE_VAR4(X1,X2,X3,X4) double X1{smc::define_variable (data, X1, #X1)}; /
                        double X2{smc::define_variable (data, X2, #X2)}; /
                        double X3{smc::define_variable (data, X3, #X3)}; /
                        double X4{smc::define_variable (data, X4, #X4)}; /
#define _CREATE_VAR5(X1,X2,X3,X4,X5) double X1{smc::define_variable (data, X1, #X1)}; /
                        double X2{smc::define_variable (data, X2, #X2)}; /
                        double X3{smc::define_variable (data, X3, #X3)}; /
                        double X4{smc::define_variable (data, X4, #X4)}; /
                        double X5{smc::define_variable (data, X5, #X5)}; /

Is there a way to simplify this by using one macro _CREATE_VAR instead of having multiple instances with different variable argumentsand corresponding names? Ideally, I would like to automatically call the same macro _CREATE_VAR regardless of how many arguments.

A: If you don't mind a slightly different call syntax, you can use boost.preprocessor for that:
#include "boost/preprocessor.hpp"

// or to not include entire preprocessor header, the following header files will do
// #include <boost/preprocessor/stringize.hpp>
// #include <boost/preprocessor/seq/for_each.hpp>

#define CREATE_ONE_VAR(maR_, maData_, maVarName) \
  double maVarName {smc::define_variable (data, maVarName, BOOST_PP_STRINGIZE(maVarName))};

#define CREATE_VAR(maSeq) \
  BOOST_PP_SEQ_FOR_EACH(CREATE_ONE_VAR, %%, maSeq)

Example of use:
CREATE_VAR((x1)(x2)(x3))  //does the same as your original _CREATE_VAR3(x1, x2, x3)

Now you can call it with any number of variables from 1 to BOOST_PP_LIMIT_SEQ, which is normally 256.
A few notes:
I use %% to indicate that the argument is unused. You can put anything in there (it gets passed to the internal macro's maData parameter, which we don't use).
You should not name your macros to start with an underscore followed by a capital letter. It's illegal according to the standard, as such symbols (as well as any symbol including two consecutive underscores) are reserved for your compiler.

A: One way to do it is to use a FOR_EACH macro on __VA_ARGS__, its not pretty and it probably takes a while to fully follow along with whats happening but at least it doesn't depend on boost.
Helper macros:
// Concatenates tokens, even when the tokens are macros themselves.
#define PP_JOIN_HELPER_HELPER(_0, _1)       _0##_1
#define PP_JOIN_HELPER(_0, _1)              PP_JOIN_HELPER_HELPER(_0, _1)
#define PP_JOIN_IMPL(_0, _1)                PP_JOIN_HELPER(_0, _1)

#define PP_JOIN_2(_0, _1)                                                                   PP_JOIN_IMPL(_0, _1)
#define PP_JOIN_3(_0, _1, _2)                                                               PP_JOIN_2(PP_JOIN_2(_0, _1), _2)
#define PP_JOIN_4(_0, _1, _2, _3)                                                           PP_JOIN_2(PP_JOIN_3(_0, _1, _2), _3)
#define PP_JOIN_5(_0, _1, _2, _3, _4)                                                       PP_JOIN_2(PP_JOIN_4(_0, _1, _2, _3), _4)
#define PP_JOIN_6(_0, _1, _2, _3, _4, _5)                                                   PP_JOIN_2(PP_JOIN_5(_0, _1, _2, _3, _4), _5)
#define PP_JOIN_7(_0, _1, _2, _3, _4, _5, _6)                                               PP_JOIN_2(PP_JOIN_6(_0, _1, _2, _3, _4, _5), _6)
#define PP_JOIN_8(_0, _1, _2, _3, _4, _5, _6, _7)                                           PP_JOIN_2(PP_JOIN_7(_0, _1, _2, _3, _4, _5, _6), _7)
#define PP_JOIN_9(_0, _1, _2, _3, _4, _5, _6, _7, _8)                                       PP_JOIN_2(PP_JOIN_8(_0, _1, _2, _3, _4, _5, _6, _7), _8)
#define PP_JOIN_10(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9)                                  PP_JOIN_2(PP_JOIN_9(_0, _1, _2, _3, _4, _5, _6, _7, _8), _9)
#define PP_JOIN_11(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10)                             PP_JOIN_2(PP_JOIN_10(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9), _10)
#define PP_JOIN_12(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11)                        PP_JOIN_2(PP_JOIN_11(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10), _11)
#define PP_JOIN_13(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12)                   PP_JOIN_2(PP_JOIN_12(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11), _12)
#define PP_JOIN_14(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13)              PP_JOIN_2(PP_JOIN_13(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12), _13)
#define PP_JOIN_15(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14)         PP_JOIN_2(PP_JOIN_14(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13), _14)
#define PP_JOIN_16(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15)    PP_JOIN_2(PP_JOIN_15(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14), _15)

// Chooses a value based on a condition.
#define PP_IF_0(t, f)           f
#define PP_IF_1(t, f)           t
#define PP_IF(cond, t, f)       PP_JOIN_2(PP_IF_, PP_TO_BOOL(cond))(t, f)

// Converts a condition into a boolean 0 (=false) or 1 (=true).
#define PP_TO_BOOL_0 0
#define PP_TO_BOOL_1 1
#define PP_TO_BOOL_2 1
#define PP_TO_BOOL_3 1
#define PP_TO_BOOL_4 1
#define PP_TO_BOOL_5 1
#define PP_TO_BOOL_6 1
#define PP_TO_BOOL_7 1
#define PP_TO_BOOL_8 1
#define PP_TO_BOOL_9 1
#define PP_TO_BOOL_10 1
#define PP_TO_BOOL_11 1
#define PP_TO_BOOL_12 1
#define PP_TO_BOOL_13 1
#define PP_TO_BOOL_14 1
#define PP_TO_BOOL_15 1
#define PP_TO_BOOL_16 1

#define PP_TO_BOOL(x)       PP_JOIN_2(PP_TO_BOOL_, x)

// Returns 1 if the arguments to the variadic macro are separated by a comma, 0 otherwise.
#define PP_HAS_COMMA(...)                           PP_HAS_COMMA_EVAL(PP_HAS_COMMA_ARGS(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0))
#define PP_HAS_COMMA_EVAL(...)                      __VA_ARGS__
#define PP_HAS_COMMA_ARGS(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, ...) _16

// Returns 1 if the argument list to the variadic macro is empty, 0 otherwise.
#define PP_IS_EMPTY(...)                                                        \
    PP_HAS_COMMA                                                                \
    (                                                                           \
        PP_JOIN_5                                                           \
        (                                                                       \
            PP_IS_EMPTY_CASE_,                                              \
            PP_HAS_COMMA(__VA_ARGS__),                                      \
            PP_HAS_COMMA(PP_IS_EMPTY_BRACKET_TEST __VA_ARGS__),         \
            PP_HAS_COMMA(__VA_ARGS__ (~)),                                  \
            PP_HAS_COMMA(PP_IS_EMPTY_BRACKET_TEST __VA_ARGS__ (~))      \
        )                                                                       \
    )

#define PP_IS_EMPTY_CASE_0001           ,
#define PP_IS_EMPTY_BRACKET_TEST(...)   ,

// Retrieve the number of arguments handed to a variable-argument macro.
#define PP_VA_NUM_ARGS_HELPER(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, N, ...)    N
#define PP_VA_NUM_ARGS(...) PP_VA_NUM_ARGS_HELPER(__VA_ARGS__, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

// Correctly handles the case of 0 arguments.
#define PP_NUM_ARGS(...)        PP_IF(PP_IS_EMPTY(__VA_ARGS__), 0, PP_VA_NUM_ARGS(__VA_ARGS__))

// Pass each variable in a VA_ARGS list to a macro.
#define PP_FE_0(action, X)
#define PP_FE_1(action, X) action(X)
#define PP_FE_2(action, X, ...) action(X)PP_FE_1(action, __VA_ARGS__)
#define PP_FE_3(action, X, ...) action(X)PP_FE_2(action, __VA_ARGS__)
#define PP_FE_4(action, X, ...) action(X)PP_FE_3(action, __VA_ARGS__)
#define PP_FE_5(action, X, ...) action(X)PP_FE_4(action, __VA_ARGS__)
#define PP_FE_6(action, X, ...) action(X)PP_FE_5(action, __VA_ARGS__)
#define PP_FE_7(action, X, ...) action(X)PP_FE_6(action, __VA_ARGS__)
#define PP_FE_8(action, X, ...) action(X)PP_FE_7(action, __VA_ARGS__)
#define PP_FE_9(action, X, ...) action(X)PP_FE_8(action, __VA_ARGS__)
#define PP_FE_10(action, X, ...) action(X)PP_FE_9(action, __VA_ARGS__)
#define PP_FE_11(action, X, ...) action(X)PP_FE_10(action, __VA_ARGS__)
#define PP_FE_12(action, X, ...) action(X)PP_FE_11(action, __VA_ARGS__)
#define PP_FE_13(action, X, ...) action(X)PP_FE_12(action, __VA_ARGS__)
#define PP_FE_14(action, X, ...) action(X)PP_FE_13(action, __VA_ARGS__)
#define PP_FE_15(action, X, ...) action(X)PP_FE_14(action, __VA_ARGS__)
#define PP_FE_16(action, X, ...) action(X)PP_FE_15(action, __VA_ARGS__)

#define PP_FOR_EACH(action, ...) PP_JOIN_2(PP_FE_, PP_NUM_ARGS(__VA_ARGS__))(action, __VA_ARGS__)

Definition for your macro:
#define CREATE_VAR(var)     double var{smc::define_variable(data, var, #var)};
#define CREATE_VARS(...)    PP_FOR_EACH(CREATE_VAR, __VA_ARGS__)

Also, you may or may not need to use #pragma GCC system_header depending on what warning lvl you're compiling with in order to get rid of ISO C99 requires rest arguments to be used. You could've used #pragma GCC diagnostic ignored "-pedantic-errors" but apparently that is bugged. If you're using msvc you'll have to figure out the warning to disable by yourself.

A: These are called Variadic Macros, A macro can be declared to accept a variable number of arguments much as a function can.
The declaration syntax is similar to that of variadic functions: an ellipsis "..." is used to indicate that one or more arguments must be passed. Common compilers also permit passing zero arguments to such a macro, however. During macro expansion each occurrence of the special identifier VA_ARGS in the macro replacement list is replaced by the passed arguments.
For example C99 way, also supported by VC++ compiler.
#define FOO(fmt, ...) print(fmt, ##__VA_ARGS__)

void print(const char *fmt, ...) {

    va_list args;
    va_start(args, fmt);
    vsprintf(str, fmt, args);
        va_end(args);

        printf("%s\n", str);

}

This is a simple use case to show how to use vardiac maco and then how we can use the variable argument list correctly...with out looking for additional library!
Also have a look at
http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html

A: According to my understanding of your question. you should use ellipsis(...).  I suggest you to go through with following link. This is help full to understand.
http://msdn.microsoft.com/en-us/library/ms177415(v=vs.80).aspx


text:
Q: Scikit SGDClassifier using letters as features instead of words I'm trying to classify phrases using the SGDClassifier following this tutorial
My pipeline looks like this:
p_clf = Pipeline([('vect', CountVectorizer(analyzer='word', ngram_range=(1, 2),
                                  token_pattern=r'\b\w+\b', min_df=1)),
                  ('tfidf', TfidfTransformer()),
                  ('clf', SGDClassifier(loss='log', penalty='l2',
                                        alpha=1e-3, n_iter=5, random_state=42)), ])

Even though I'm getting the right classification, I don't understand why it treats letters as features instead of the entire word. In this example when I call predict_proba('Hello') I get:
[[ 0.15889614  0.23752053  0.4353584   0.16822494]
 [ 0.15889614  0.23752053  0.4353584   0.16822494]
 [ 0.15889614  0.23752053  0.4353584   0.16822494]
 [ 0.15889614  0.23752053  0.4353584   0.16822494]
 [ 0.11579265  0.19786962  0.36811551  0.31822223]]

Where each row is a letter and the columns are my classes.
Shouldn't it be just one row?

A: In your case 'Hello' is interpreted as an array of characters like ['H','e','l','l','o']. (Remember that predict_proba expects an array or a sparse matrix as input.) This can be solved by putting the string in a list:
predict_proba(['Hello'])


text:
Q: Spring Java, file not found when loading xml So I followed a tutorial for Spring that I found online, namely a Hello World, and they have this structure at the end. I tried it and it worked fine, now I created a new Dynamic Web project, Eclipse doesn't seem to like this structure. I get:
Caused by: java.io.FileNotFoundException: class path resource [Spring-Module.xml] cannot be opened because it does not exist

How do I fix this? Or rather, what's causing Eclipse to not know where the file is?
Error here:

Works here:

A: Make sure resources folder is on classpath.
Project -> Properties -> Build Path -> Add folder


text:
Q: opencv RNG alternative for Java I use opencv-3.2.0, I found RNG can use with C++, but not exist in Java:
C++
RNG rng( 0xFFFFFFFF );
rng.uniform( -3, 10 );
rng.uniform(0, 200);

Java
There is no RNG

Please tell me how to use RNG uniform in Java.

A: Just a small search on google, I found this link, in the explanation of uniform, it says:

returns uniformly distributed integer random number from [a,b) range. The methods transform the state using the MWC algorithm and return the next uniformly-distributed random number of the specified type, deduced from the input parameter type, from the range [a, b) .

And the examples:
RNG rng;

// always produces 0
double a = rng.uniform(0, 1);

// produces double from [0, 1)
double a1 = rng.uniform((double)0, (double)1);

// produces float from [0, 1)
double b = rng.uniform(0.f, 1.f);

// produces double from [0, 1)
double c = rng.uniform(0., 1.);

// may cause compiler error because of ambiguity:
//  RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)?
double d = rng.uniform(0, 0.999999);

So, it seems java also have RNG.


text:
Q: Python unit testing sys.exit call with assertRaises or mock.patch I've read a lot of answers suggesting that the way to unit test sys.exit is to do the following:
with self.assertRaises(SystemExit) as system_exit:
    function()
self.assertEqual(system_exit.exception_code, 1)

Does the above not actually raise a SystemExit in my test? Is it better or worse to do the following?
@mock.patch("<path to class file>.sys.exit")
def testFunction(self, mock_sys_exit):
    function()
    mock_sys_exit.assert_called_once_with(1)

Are both the approaches equivalent, or is one better than the other? And why?


text:
Q: Do macros run faster than global variables in C? How to change macros between runs? I'm writing a program in C in which there are several constants I would like all of my functions to use. So far, I have used macros. A simplified version of the program looks as follows.
#define CONSTANT 10 //int
int multiplication_by_constant(int a){ return a*CONSTANT;}
int main(){
   for(int i = 1; i< 10; i++)
       printf("%d\n",multiplication_by_constant(i));
}

Now I want to run experiments on the program by running it several times with different values of the constant. I want to automate this, and not re-compile each time I change CONSTANT. I used a simple solution by changing the macros to global variables, putting the original main function into a new 'program()' function, then to run the experiments in the main file, i.e.
int CONSTANT =  10; //int
int multiplication_by_constant(int a){ return a*CONSTANT;}
void program(){
   for(int i = 1; i< 10; i++)
       printf("%d\n",multiplication_by_constant(i));
}
int main(){
   while(CONSTANT < 100){
       program();
   }
   return 0;
}

I discovered that this implementation lead to quite a substantial loss of performance of the loop
for(int i = 1; i< 10; i++)
       printf("%d\n",multiplication_by_constant(i));

which now requires around 50% more run time than when I was using the macro. Is this normal?
Can anyone suggest a more efficient way for me to run my experiment?
PS In C++, I would do this by defining a 'class program', setting CONSTANT to be a class member and 'multiplication_by_constant' a member function. I could then easily run the experiments through 'main' using the class definition, and I think I wouldn't have the efficiency loss... I have to use C in this implementation which is why I've resorted to the global variables and functions.

A: Macros don't "run", exactly. A macro is an instruction to the C preprocessor, which effectively replaces uses of the macro with the definition of the macro before passing it on to the compiler. Whether a given macro or function call is more efficient is dependent on the macro and the function call. In your example, as John Bode shows in his answer, having the macro represent a literal is advantageous over using a variable. In general there is no inherent difference between expressing the same code inline vs as a macro. A more efficiently coded inline statement will be more efficient then a less efficiently coded macro.

A: Well, here's a potential source of the performance difference.  With a macro, the value of CONSTANT is known at compile time, so the compiler can take advantage of that knowledge and structure the machine code a little differently.  I took a variation of your code and used gcc -Wa,-aldh to get an assembly listing1 for both the macro and global variable versions, with an interesting difference.
First is the macro version:

 3                    .globl mul_by_const
 5                    mul_by_const:
 6                    .LFB2:
 7 0000 55                    pushq   %rbp
 8                    .LCFI0:
 9 0001 4889E5                movq    %rsp, %rbp
10                    .LCFI1:
11 0004 897DFC                movl    %edi, -4(%rbp)
12 0007 8B55FC                movl    -4(%rbp), %edx
13 000a 89D0                  movl    %edx, %eax
14 000c C1E002                sall    $2, %eax
15 000f 01D0                  addl    %edx, %eax
16 0011 01C0                  addl    %eax, %eax
17 0013 C9                    leave
18 0014 C3                    ret

The highlighted lines are the meat of the function; instead of multiplying the value in %eax by 10, the function does an arithmetic shift left by 2 places followed by an addition (effectively multiplying by 5), and then adds the result to itself.  For example, given an i value of 3:
 3 << 2 == 12
 3 + 12 == 15
15 + 15 == 30

If you change the value of CONSTANT, the compiler will generate different machine code (a CONSTANT value of 7 results in an arithmetic shift left by 3 followed by a subtraction, while a value of 19 gives a left shift of 3 followed by 3 additions, etc).
Compare that with the global variable version:

 2                    .globl CONSTANT
 3                            .data
 4                            .align 4
 7                    CONSTANT:
 8 0000 0A000000              .long   10
 9                            .text
10                    .globl mul_by_const
12                    mul_by_const:
13                    .LFB2:
14 0000 55                    pushq   %rbp
15                    .LCFI0:
16 0001 4889E5                movq    %rsp, %rbp
17                    .LCFI1:
18 0004 897DFC                movl    %edi, -4(%rbp)
19 0007 8B050000              movl    CONSTANT(%rip), %eax
19      0000
20 000d 0FAF45FC              imull   -4(%rbp), %eax
21 0011 C9                    leave
22 0012 C3                    ret

This version uses the imull opcode to do the multiplication.  Since the value of CONSTANT isn't known at compile time, the compiler can't do any special optimizations based on that value.
Now, this is how things shake out on my particular platform; I don't know what compiler you're using or what OS you're running on, so it's likely that the machine code you're getting is different from what I have above.  I'm just pointing out that knowing CONSTANT at compile time allows the compiler to do some extra optimization.
Edit
If you change the value of a macro, you have to recompile.  You could put the macro in a header file, and then write a script to regenerate the header and recompile, something like
#!/bin/bash

let CONSTANT=1
while [ $CONSTANT -lt 20 ]
do
  cat > const.h << EOF
#ifndef CONST_H
#define CONST_H
#define CONSTANT $CONSTANT
#endif
EOF
  # build and run your test code, assuming profiling is captured
  # automatically
  gcc -o test test.c
  ./test
  let CONSTANT=CONSTANT+1
done

and your C code would #include the const.h file:
#include "const.h"
int multiplication_by_constant(int a){ return a*CONSTANT;}
...

1. Platform is SUSE Linux Enterprise Server 10 (x86_64), compiler is gcc 4.1.2

A: It looks like you are not quite understanding what the preprocessor does. Think of macros as search-and-replace templates, i.e. your small program
#define CONSTANT 10 //int
int multiplication_by_constant(int a){ return a*CONSTANT; }
int main(){
   for(int i = 1; i< 10; i++)
       printf("%d\n",multiplication_by_constant(i));
}

Is equivalent to writing
int multiplication_by_constant(int a){ return a*10; }
int main(){
   for(int i = 1; i< 10; i++)
       printf("%d\n",multiplication_by_constant(i));
}

In this, there is no field to read before multiplying the input value, which would account for the speedup.
Try running just the preprocessor and compare the output of your two variants, and if you really are running just these small programs (and the above is not a distilled version of your actual problem), you could try comparing the assembler output as well. If nothing else, you will get a better understanding of whatever toolchain you are using :-)

A: C programs are built in steps.  Those steps are as follows:

*

*Preprocessing: (macros, includes, defines, etc...) Basically anything that starts with a # symbol is taken care of here.

*Compilation: The preprocessed C source is translated (compiled) into assembler.

*Assembly: The assembler translates the assembly source file (generated through compilation) into a machine object code file.

*Linking: The final step resolves external references to libraries and generates a runnable program.

Armed with this knowledge, the macro is processed in the preprocessing stage.  In your case, everywhere CONSTANT shows up in the source is replaced by 10.  So to change the constant, you have to change the #define statement and recompile.  Since CONSTANT is replaced with the actual number 10, it is considered an immediate value.  But if you want to change it during run time, you have to use a variable as there is no other way of getting around it.
One thing you could do, however, is change this line:
 printf("%d\n",multiplication_by_constant(i));

To this:
 printf("%d\n",i * CONSTANT);

This way you avoid the function call entirely and remove the overhead associated with making that function call.


text:
Q: What's the difference between return true and return false in OnInit() function of MFC In the source code generated by the template for a Dialog based MFC application the InitInstance() of the main application, derived from CWinApp, initializes the application environment and then creates the dialog that is the main application interface and displays it with DoModal(). When the displayed dialog returns, the application finishes and terminates.
In the main application interface dialog that is derived from CDialogEx there is a method OnInitDialog() which is called as part of initializing the dialog.
What is the difference between returning TRUE or returning FALSE from this method?
BOOL CMyTabDlgs::OnInitDialog()
{
    CDialog::OnInitDialog() ;
    // Some code
    return true;
}

and
BOOL CMyTabDlgs::OnInitDialog()
{
    CDialog::OnInitDialog() ;
    // Some code
    return false;
}

A: The OnInitDialog() member function is called by the MFC framework when it is processing a WM_INITDIALOG message.
The purpose of this member function is to provide a place to perform any special initialization of the dialog's controls and interface.
One of the events that can be done in the OnInitDialog() method is to set the focus to one of the controls in the dialog. This action allows the programmer to decide which control (button, edit window, combo box, etc.) displayed in the dialog should have the focus first.
Or the programmer can just allow the MFC framework to make that decision for them.
If the programmer sets the focus to a particular control, the OnInitDialog() method should return FALSE so that the MFC Runtime knows that the focus has already been set.
If the programmer does not set the focus to a particular control, the OnInitDialog() method should return TRUE so that the MFC Runtime knows that it needs to set the focus.
That is what the comments in the OnInitDialog() method skeleton created by the MFC template indicate as in the code sample from https://technet.microsoft.com/en-us/windows/fwz35s59(v=vs.60)
BOOL CSimpleDlg::OnInitDialog()
{
   CDialog::OnInitDialog();

   // TODO: Add extra initialization here
   m_cMyEdit.SetWindowText(_T("My Name")); // Initialize control values
   m_cMyList.ShowWindow(SW_HIDE);      // Show or hide a control, etc.

   return TRUE;  // return TRUE unless you set the focus to a control
   // EXCEPTION: OCX Property Pages should return FALSE
}

The MSDN article CPropertySheet::OnInitDialog has a fuller explanation for the return value:

Specifies whether the application has set the input focus to one of
  the controls in the property sheet. If OnInitDialog returns nonzero,
  Windows sets the input focus to the first control in the property
  sheet. The application can return 0 only if it has explicitly set the
  input focus to one of the controls in the property sheet.


text:
Q: Image attachment as first item (left aligned) in NSAttributed string I am trying to add an image to a UILabel using a NSAttributedString with a NSTextAttachment
func attributedString(string:String)->NSAttributedString {
    let label:NSMutableAttributedString = NSMutableAttributedString()

    let string = NSAttributedString(string: string)
    let attachment = NSTextAttachment()
    attachment.image = #imageLiteral(resourceName: "WaterIcon")
    let imageString = NSAttributedString(attachment: attachment)

    label.append(string)
    label.append(imageString)

    return label
}

when I switch
    label.append(imageString)
    label.append(string)

… which is what I want regarding the order, the image doesn't show up at all :-(
How can I add the image as first item in the string?

A: You code works just fine for me with the two append statements swapped:

Perhaps there is a problem with how your label is sized/positioned, or how you are assigning the attributed string to the label. But you have not shown any of that part of your code, so who knows what you're doing wrong?


text:
Q: dual (p,q)-property If the set system $(X,S)$ has the $(p,q)$-property does its dual system also have the property? (Possibly, for different $p$ and $q$.)
Explicitly, I am asking about the equivalence of the following two properties:

*

*Out of any $p$ sets in $S$ we can find $q$ with nonempty intersection.

*Out of any $p$ points in $X$ we can find $q$ contained in the same set in $S$.
I guess the answer is no, but do not have a counter-example.

A: The properties are not equivalent. Let $S$ consist of (at least two) subsets of $X$, which have one point entirely in common, but which are otherwise disjoint (and which have other points than that common point). This has the $(p,q)$ property, since all sets in $S$ have nonempty intersection. But if $p,q>1$, then you can pick two points other than the common point, from different elements of $S$, and they are not contained in a single set from $S$.
For example, let $S=\{\ \{0,1\}, \{0,2\}\ \{0,3\}\}$. This has the $(p,q)$ property for any positive $p$ and $q$, since $0$ is in the intersection of $S$; but the dual $(3,2)$-property fails, since no two elements of $1, 2, 3$ are contained in a single set of $S$.


text:
Q: CSS vertical line for complex tbody I've a dynamic HTML page which has a table with multiple 'tbody' elements.
Each tbody element is a little complex as it has a nested structure.
I need to have a vertical line inside each of the tbody.
For that matter, I tried to use pseudo-element 'after' to create the vertical line. But it doesn't seem to work.
Could you please help me fix it?
Here's the sample design:

My code:

.container tr:last-child::after {
  content: '';
  display: inline-block;
  height: 100%;
  border-left: 1px solid red;
  position: relative;
  border-left: 2px solid red;
  right: 10px;
}

Heading 1

Content

      Row 1 Column 2
      Row 1 Column 3

      Row 2 Column 1
      Row 2 Column 2

      Row 3

Heading 2

Content

      Row 1 Column 2
      Row 1 Column 3

      Row 2 Column 1
      Row 2 Column 2

      Row 3

Heading 1

Content

      Row 1 Column 2
      Row 1 Column 3

      Row 2 Column 1
      Row 2 Column 2

      Row 3


text:
Q: How do I use a mixin param in a each loop? I'm trying to create a BEM spacing helper mixin that contains the name of the screen in the class name. An example output: .marSm0 .marSm0__t .marSm0__b .marSm0__x
$emMd0: 1em !default;
$emMd1: 1.5em !default;
$emMd2: 2em !default;
$emMd3: 4em !default;

$emMdSpacing: ($emNone, $emMd0, $emMd1, $emMd2, $emMd2 );

@mixin spacingHelper($screenSize, $spacingValues){
    @each $space in $spaceValues {
      .mar#{screenSize}#{$space} {
            margin: #{$space}rem;
        }

        .mar#{screenSize}#{$space}__x {
            margin-left: #{$space}rem;
            margin-right: #{$space}rem;
        }

        .mar#{screenSize}#{$space}__y {
            margin-top: #{$space}rem;
            margin-bottom: #{$space}rem;

        }

        .mar#{screenSize}#{$space}__l {
            margin-left: #{$space}rem;
        }

        .mar#{screenSize}#{$space}__r {
            margin-right: #{$space}rem;
        }

        .mar#{screenSize}#{$space}__b {
            margin-bottom: #{$space}rem;
        }

        .mar-#{screenSize}#{$space}__t {
            margin-top: #{$space}rem;
        }

        .pad#{screenSize}#{$space} {
            padding: #{$space}rem;
        }

        .pad#{screenSize}#{$space}__x {
            padding-left: #{$space}rem;
            padding-right: #{$space}rem;
        }

        .pad#{screenSize}#{$space}__y {
            padding-top: #{$space}rem;
            padding-bottom: #{$space}rem;

        }

        .pad#{screenSize}#{$space}__l {
            padding-left: #{$space}rem;
        }

        .pad#{screenSize}#{$space}__r {
            padding-right: #{$space}rem;
        }

        .pad#{screenSize}#{$space}__b {
            padding-bottom: #{$space}rem;
        }

        .pad#{screenSize}#{$space}__t {
            padding-top: #{$space}rem;
        }
    }
}

The problem I'm having is that the $screenSize mixin argument isn't working in the each loop. How do I fix this? I'm sure if the each loop is having a scope issue. Code
Ignore for question validation

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin quis vehicula tellus, id ultrices massa. Suspendisse dignissim in odio non rutrum. Vestibulum dapibus eget eros at aliquet. Quisque vitae vulputate massa, ac laoreet orci. Vestibulum vestibulum ante quis eros sollicitudin euismod. Cras eget orci turpis.


text:
Q: Displaying the same title search results from "Ask Question" When I search for a question I'd like to be shown the same results as when I type in a title in "Ask Question"
I often use the "Ask Question" as a search tool, like this:
Some results!

Better results?

Update: I have updated the screen shot to a version without quote marks, the two search results are still inconsistent. But are they better?

A: Your screenshot is a little blurry, but it looks to me like you have an open quote at the beginning of your search bar example. Assuming you have a close quote at the end, the search is only going to look for the exact phrase "Importing a MySQL schema to Xcode as a CoreData Data Model," so it's not surprising that you only get one result. You're not using the quotes in your title search, and you have lots of juicy programming-related words, so it's not surprising that you get many results there.
The main issue here is that the search bar searches everything, not just the title — though it was changed to weight the title more heavily at one point for exactly this reason — while the Ask Question bar searches only in the title.
I am against any proposal which would remove users' ability to search question bodies and answers, which is effectively what this proposal is (though I do realize that wasn't the intent of the request).

A: I've just read this blog https://blog.stackoverflow.com/2009/07/stack-overflow-search-now-61-less-crappy/.
The best solution is:
title:only search these keywords in the title


text:
Q: Mounting NFS stopped working after server upgrade to newest Debian? I have NFS server that is working as a general filer in a LAN.
Recently due to disk malfunction, I lost everything there, so I got new disks, reinstalled newest Debian (jessie), copied back config files - and NFS no longer works?!
my /etc/exports contains:
/media/media *(rw,sync,no_subtree_check,all_squash,anonuid=31244,anongid=31451)
/media/private *(rw,sync,no_subtree_check,all_squash,anonuid=16830,anongid=10818)

I did couple of reboots, /etc/init.d/nfs-common restart, /etc/init.d/nfs-kernel-server restarts.
On client side, I have, in /etc/fstab:
172.28.173.1:/media/media                  /media/MEDIA      nfs     rsize=8192,wsize=8192,timeo=14,soft,intr,rw,user,noatime,nodiratime  0       0
172.28.173.1:/media/private                /mnt/nfs/private  nfs     rsize=8192,wsize=8192,timeo=14,soft,intr,rw,user,noatime,nodiratime  0       0

When mounting the filesystem, mount command takes long time, and ends without printing anything. Running "df" later on shows:
df: '/media/MEDIA': Stale NFS file handle

In syslog on client I see:
2013-12-18T15:27:08.319605+01:00 h3po4 kernel: [  363.398977] RPC: AUTH_GSS upcall timed out.
2013-12-18T15:27:08.319619+01:00 h3po4 kernel: [  363.398977] Please check user daemon is running.

But I have no idea what daemon it talks about, why it even needs some "user daemon", and why is there AUTH_GSS call - I want access to be 100% open to the nfs share within LAN.
I verified that it's not a firewall issue (by disabling firewall for a test).
I don't think I ever reconfigured anything else on the server, before disk crash, but I'm not sure - the machine has been working for > 4 years, without a problem, so I could have changed something and forgot about it.
So, I checked some more things.
Before mounting on client, mount directory is:
drwxr-xr-x  2 root root 4096 maj  1  2013 MEDIA/

But after "mount /media/MEDIA", waiting for it to finish, I get:
ls: cannot access /media/MEDIA: Stale NFS file handle
d?????????? ? ?    ?       ?            ? MEDIA/

The directory on server side is always "normal":
drwxrwxrwx 2 media media 6 Dec 18 14:05 /media/media/

also, exportfs works fine:
=# exportfs -v
/media/media        <world>(rw,wdelay,root_squash,all_squash,no_subtree_check,anonuid=31244,anongid=31451,sec=sys,rw,root_squash,all_squash)
/media/private      <world>(rw,wdelay,root_squash,all_squash,no_subtree_check,anonuid=16830,anongid=10818,sec=sys,rw,root_squash,all_squash)

and I can see the exported filesystems from client:
$ showmount -e blob
Export list for blob:
/media/private *
/media/media   *


text:
Q: Laravel 5.3 - Unable to pass data through mailable Using backpack for laravel.
This is what my controller looks like:
public function store(StoreRequest $request)
{
    $finance = $request->all();
    if ($request->input('shouldPay') == 'Yes') {
        Mail::to($request->user())->send(new NewBill($finance));
        return parent::storeCrud();
    }
    else {
        return parent::storeCrud();
    }
}

And this is what my mailable NewBill looks like:
class NewBill extends Mailable
{
 use Queueable, SerializesModels;

/**
 * The finance instance.
 *
 * @var finance
 */
public $finance;

/**
 * Create a new message instance.
 *
 * @return void
 */
public function __construct()
{
    //
    $this->finance = $finance; //THIS IS LINE 31
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.newbill');
}
}

This is the error:
ErrorException in NewBill.php line 31:
Undefined variable: finance

I tried doing like the doc tells you to (in the controller):
public function store(StoreRequest $request, $financeId)
{

    $finance = Finance::findOrFail($financeId);
    if ($request->input('shouldPay') == 'Yes') {
        Mail::to($request->user())->send(new NewBill($finance));
        return parent::storeCrud();
    }
    else {
        return parent::storeCrud();
    }
}

Result:
Missing argument 2 for App\Http\Controllers\Admin\FinanceCrudController::store()

I was thinking it would be easier to send the email right from the store function instead of going through the mailable, is that possible?
If not, how can I fix the issue going on?

A: public function __construct($finance)
{
    $this->finance = $finance;
}

try this


text:
Q: Подгрузка из Firebase Firestore в recycle view Загружаю данные из Firebase Firestore в recycle view и пытаюсь сделать постепенную подгрузку данных при достижении конца списка.
Вроде бы получилось, но работает не совсем корректно:
1) при переходе на другой фрагмент и возвращении обратно на этот, отображаются не все записи и подгрузка не работает
2) при попытке обновить список с помощью swipeRefreshLayout он обновляется, но показываются только последние 4 записи, подгрузка также перестает работать
3) переодически при прокрутке (например, когда записей меньше чем сам лимит) может вылетать с ошибкой в 194 строке lastVisible = task.getResult().getDocuments().get(task.getResult().size() - 1); пишет length=0; index=-1
Как решить эти проблемы? Помогите, пожалуйста
HomeFragment.java
public class HomeFragment extends Fragment {

    private final int LIMIT_ITEM_LOAD = 4;

    private View item_1, item_2, item_3, item_4, item_5;
    private SwipeRefreshLayout swipeRefresh;

    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private DocumentSnapshot lastVisible;
    private boolean isScrolling;
    private boolean isLastItemReached;
    private List<Meeting> list;
    private MeetingAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        item_1 = getActivity().findViewById(R.id.item_1);
        item_2 = getActivity().findViewById(R.id.item_2);
        item_3 = getActivity().findViewById(R.id.item_3);
        item_4 = getActivity().findViewById(R.id.item_4);
        item_5 = getActivity().findViewById(R.id.item_5);

        BottomNavigationView navigation = getActivity().findViewById(R.id.navigation);
        navigation.getMenu().getItem(0).setChecked(true);
        setBorderItemSelected(item_1);

        Toolbar toolbar = view.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setTitle("Лента событий");
        setHasOptionsMenu(true);

        recyclerView = view.findViewById(R.id.recyclerView);
        linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);

        swipeRefresh = view.findViewById(R.id.swipeRefresh);
        swipeRefresh.setColorSchemeResources(
                R.color.orange_300,
                R.color.pink_300,
                R.color.green_300,
                R.color.blue_300);
        swipeRefresh.setOnRefreshListener(refreshListener);

        getLastKeyFromFirebase();

        return view;
    }

    private SwipeRefreshLayout.OnRefreshListener refreshListener = new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                @Override public void run() {
                    swipeRefresh.setRefreshing(true);
                    getLastKeyFromFirebase();
                    swipeRefresh.setRefreshing(false);
                }
            },1000);
        }
    };

    private void getLastKeyFromFirebase() {

        Query query = FirebaseFirestore.getInstance()
                .collection("meetings")
                .orderBy("id", Query.Direction.DESCENDING)
                .limit(LIMIT_ITEM_LOAD);

        query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    list = new ArrayList<>();

                    for (DocumentSnapshot document : task.getResult()) {
                        Meeting meeting = document.toObject(Meeting.class);
                        list.add(meeting);
                    }

                    adapter = new MeetingAdapter(list, getContext());
                    recyclerView.setAdapter(adapter);
                    lastVisible = task.getResult().getDocuments().get(task.getResult().size() - 1);
                    Toast.makeText(getContext(), "Основа загружена", Toast.LENGTH_SHORT).show();

                    recyclerView.addOnScrollListener(onScrollListener);

                }
            }
        });
    }

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);

            if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                isScrolling = true;
            }
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            int firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
            int visibleItemCount = linearLayoutManager.getChildCount();
            int totalItemCount = linearLayoutManager.getItemCount();
            Log.d("Ok","firstVisibleItem = " + firstVisibleItem);
            Log.d("Ok","visibleItemCount = " + visibleItemCount);
            Log.d("Ok","totalItemCount = " + totalItemCount);

            if (isScrolling && (firstVisibleItem + visibleItemCount == totalItemCount) && !isLastItemReached) {
                isScrolling = false;

                Query nextQuery = FirebaseFirestore.getInstance()
                        .collection("meetings")
                        .orderBy("id", Query.Direction.DESCENDING)
                        .startAfter(lastVisible)
                        .limit(LIMIT_ITEM_LOAD);
                nextQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        for (DocumentSnapshot document : task.getResult()) {
                            Meeting meeting = document.toObject(Meeting.class);
                            list.add(meeting);
                        }
                        adapter.notifyDataSetChanged();

                        lastVisible = task.getResult().getDocuments().get(task.getResult().size() - 1);
                        Toast.makeText(getContext(), "Подгрузка завершена", Toast.LENGTH_SHORT).show();

                        if (task.getResult().size() < LIMIT_ITEM_LOAD) {
                            isLastItemReached = true;
                        }
                    }
                });
            }
        }

    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_filtration:
                //
                break;
            default:
                break;
        }
        return true;
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.toolbar_home, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

}

MeetingAdapter.java
public class MeetingAdapter extends RecyclerView.Adapter<MeetingAdapter.MyViewHolder> {

    private List<Meeting> meetingsList;
    private Context context;

    public MeetingAdapter(List<Meeting> meetingsList, Context context) {
        this.meetingsList = meetingsList;
        this.context = context;
    }

    @NonNull
    @Override
    public MeetingAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.item_meeting, parent, false);
        return new MeetingAdapter.MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MeetingAdapter.MyViewHolder holder, int position) {
        holder.date.setText(meetingsList.get(position).getDate());
        holder.title.setText(meetingsList.get(position).getTitle());
    }

    @Override
    public int getItemCount() {
        return meetingsList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView date, title;

        MyViewHolder(View itemView) {
            super(itemView);

            date = itemView.findViewById(R.id.date);
            title = itemView.findViewById(R.id.title);
        }
    }

}


text:
Q: PHP executing in browser timeout and echo output in the same line I have a script which send emails to my clients
<?
    set_time_limit(0);
    error_reporting(E_ALL);

    $_SESSION['start_time'] = time();
            $strSubject = strip_tags($_POST["txtSubject"]);
            $strSubject = utf8_encode($strSubject);
            $strMessage = $_POST["txtDescription"];
            $txtFormName = $_POST["txtFormName"];
            $txtFormName = utf8_encode($txtFormName);
            $txtFormEmail = $_POST["txtFormEmail"];
            $mailSended = 0;
                $count = 0;
                $Ccount = 0;
                foreach($_FILES['fileAttach']['error'] as $status){
                    if($status === UPLOAD_ERR_OK) {
                    $fname[] = $_FILES['fileAttach']['name'][$Ccount];
                    $tmp_path[] = $_FILES['fileAttach']['tmp_name'][$Ccount];
                    $ftype[] =  $_FILES['fileAttach']['type'][$Ccount];
                        $count++;
                    }
                    $Ccount++;
                }
            //if not empty post txtTo
        if(!empty($_POST['txtTo'])){
            $recipients = str_replace(';',',', $_POST['txtTo']);
            $recipients = explode(',', $recipients);

            foreach ($recipients as $ReCEmail)  {
            ob_start();
                SendEmails($ReCEmail,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftype,$tmp_path);
            ob_end_flush();
            }
        }    //if empty post txtTo  takes emails from file
        else
        {
            $handle = fopen(getcwd() . "/emails.txt", "r");
            if ($handle) {
                while (($line = fgets($handle)) !== false) {
                ob_start();
                    SendEmails($line,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftype,$tmp_path);
                ob_end_flush();
                }
                fclose($handle);
            } else {
                echo "error opening the file.";
            }
        }

        function SendEmails($vasia,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftypes,$tmp_path) {

            $strTo = $vasia;
            $txtFormName = utf8_decode($txtFormName);
            $strSid = md5(uniqid(time(),true)).base_convert(time() * 2, 10, 36);
            $strHeader = "X-Priority: 0 (Highest)" .PHP_EOL;
            $strHeader .= "Importance: High" .PHP_EOL;
            $strHeader .= "From: ".$txtFormName." <".strip_tags($txtFormEmail).">" .PHP_EOL ."Reply-To: ".strip_tags($txtFormEmail);
            $strHeader .= "MIME-Version: 1.00" .PHP_EOL;
            if(count($fname) == 0)
            {
                $strHeader .= "Content-type:text; charset=\"UTF-8\"" .PHP_EOL;
                $strHeader .= "Content-Transfer-Encoding: 7bit"  .PHP_EOL;
                $strHeader .= $strMessage .PHP_EOL;
            } else {
                $strHeader .= "Content-Type: multipart/mixed; boundary=\"".$strSid."\"".PHP_EOL;
                $strMSG = "This is a multi-part message in MIME format.".PHP_EOL .PHP_EOL;
                $strMSG .= "---".$strSid.PHP_EOL;
                $strMSG .= "Content-type:text/html; charset=\"UTF-8\"".PHP_EOL;
                $strMSG .= "Content-Transfer-Encoding: 8bit" .PHP_EOL .PHP_EOL;
                $strMSG .= $strMessage .PHP_EOL;
                    //*** Attachment ***//
                    for($x=0;$x<count($fname);$x++)
                    {
                        if($fname[$x] != "")
                        {
                            $strContent = chunk_split(base64_encode(file_get_contents($tmp_path[$x])));
                            $strMSG .= "--".$strSid.PHP_EOL;
                            $strMSG .= "Content-Type: ".$ftypes[$x]."; name=\"".$fname[$x]."\"".PHP_EOL;
                            $strMSG .= "Content-Transfer-Encoding: base64".PHP_EOL;
                            $strMSG .= "Content-Disposition: attachment; filename=\"".$fname[$x]."\"".PHP_EOL.PHP_EOL;
                            $strMSG .= $strContent.PHP_EOL;
                        }
                    }
                $strMSG .= "--".$strSid."--";

            }

            // sleep(3) 1 email in 3 sec, 20 emails in 1 min, 1200 email in 1 hour
            // sleep(4) 1 email in 4 sec, 15 emails in 1 min, 900 email in 1 hour
            sleep(4);
            $flgSend = mail($strTo,utf8_decode($strSubject),$strMSG,$strHeader);
            global $mailSended,$diff;
            $mailSended++;
                if($flgSend)
                {
                    echo "
 $vasia Mail send completed." ."     ";
                }
                else
                {
                    echo "
 $vasia Cannot send mail.      ";
                }
                $end_time = time();
                $diff = $end_time - $_SESSION['start_time'];
                echo "Sent " . $mailSended . " emails in " .secondsToTime($diff);
                ob_flush();
        }

    function secondsToTime($s)
    {
        $h = floor($s / 3600);
        $s -= $h * 3600;
        $m = floor($s / 60);
        $s -= $m * 60;
        return $h.':'.sprintf('%02d', $m).':'.sprintf('%02d', $s);
    }

    ?>

Questions

*

*How to show in browser echo output in the same line clearing last echo output?

*How prevent browser timeouts until script is working? I want to see in real time echo output!!!

A: PHP does not execute in the browser, it executes on the server and then it's output is sent to the browser. Once the server sends the script's output it no longer has any control over it. Therefore, you cannot "replace" one echo with another. You need Javascript to do something like that.
Your PHP is not timing out. You've got set_time_limit(0); at the top which removes the time limit. If something is timing out it's not PHP.

A: I would fall back to Javascript if you want to hide the previous line etc. php renders on the server. Check you php.ini and see your timeout sometimes you are not able to override these settings. The setting you are looking for is
max_execution_time

Good luck.


text:
Q: Haml/Ruby/Rails adding an element conditionally? I have this code:
- userlist.each do |member|
  = render :partial => 'projects/member_small', :locals => { :user => member }

And I want to add a div element every two times do |member| occurs. So basically every two times. I want this:
- userlist.each do |member|
  .row
    = render :partial => 'projects/member_small', :locals => { :user => member }

A: You could slice the list into groups of two:
- userlist.each_slice(2) do |group|
  .row
    - group.each do |member|
      = render :partial => 'projects/member_small', :locals => { :user => member }