text:
Q: PHP Routing Not Working In Second Level of URL Parameter I am using this code for simple PHP routing system
the `.htaccess` file is like this:

RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

The index.php file is like
<?php
        $url_requested = $_SERVER['REQUEST_URI'];
        $url_len = strlen($url_requested);

        $actual_path = substr($url_requested,strpos($url_requested,'/'),$url_len);

        if($actual_path == "/"){
            include_once('./home.php');
        }
        else if(preg_match("!/products/[a-z,A-Z,0-9]!",$actual_path)){
            $actual_route = substr($actual_path,(strrpos($actual_path,'/')+1),$url_len);
            $actual_route = str_replace("%20"," ",$actual_route);
            $data_arr = [
                'content_to_show' => $actual_route
            ];
            include_once('./products.php');
        }
        else if($actual_path == "/products"){
            include_once('./products.php');
        }
        else if($actual_path == "/solutions"){
            include_once('./solutions.php');
        }
        else {
            include_once('./404.php');
        }
    ?>

The products.php page is like

        <?php include_once('./navbar.php'); ?>

        <?php
            if(isset($data_arr) && !empty($data_arr)){
        ?>

            You are viewing

            <?php echo $data_arr['content_to_show']; ?>
            page

        <?php
        }
        else {
        ?>

This is products page.

Product 1

Product 2

Product 3

Product 4

Product 5

        <?php
        }
        ?>

And the solutions.php looks like

   <?php include_once('./navbar.php'); ?>

This is solutions page.

now when navigating to URLS like
http://website/home
http://website/solutions
http://website/products

things work properly but when trying http://website/products/product 1 I am still seeing the product partial view!
I tried to dump the $data_arr out of the if(isset($data_arr) && !empty($data_arr)){} and noticed that it is not even been set!
Can you please let me know how to fix this


text:
Q: Python: Is it possible to set the length of graph edges on pyvis using edge weight as length? As stated in the subject, I was wondering if it is possible to make edges on pyvis.network show up with the weight of the graph as their actual length. The graph in itself is undirected and around 2000 nodes large, most of which are just intermediate node. If not, are there other libraries that could do the same thing ?
Thank you.

A: You can increase the mass of the nodes, as it is based on a inverted gravity model.
Example
nt.add_node(0, mass=5)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cleanest way to execute code outside of try block only if no exception is thrown This question is about the best way to execute code outside of try block only if no exception is thrown.
try {
    //experiment
    //can't put code after experiment because I don't want a possible exception from this code to be caught by the following catch. It needs to bubble.
} catch(Exception $explosion) {
    //contain the blast
} finally {
    //cleanup
    //this is not the answer since it executes even if an exception occured
    //finally will be available in php 5.5
} else {
    //code to be executed only if no exception was thrown
    //but no try ... else block exists in php
}

This is method suggested by @webbiedave in response to the question php try .. else. I find it unsatisfactory because of the use of the extra $caught variable.
$caught = false;

try {
    // something
} catch (Exception $e) {
    $caught = true;
}

if (!$caught) {

}

So what is a better (or the best) way to accomplish this without the need for an extra variable?

A: One possibility is to put the try block in a method, and return false if an exception is cought.
function myFunction() {
    try {
        // Code  that throws an exception
    } catch(Exception $e) {
        return false;
    }
    return true;
}

A: Have your catch block exit the function or (re)throw/throw an exception. You can filter your exceptions as well. So if your other code also throws an exception you can catch that and (re)throw it. Remember that:

*

*Execution continues if no exception is caught.

*If an exception happens and is caught and not (re)throw or a new one throw.

*You don't exit your function from the catch block.

*It's always a good idea to (re)throw any exception that you don't handle.

*We should always be explicit in our exception handling. Meaning if you catch exceptions check the error that we can handle anything else should be (re)throw(n)

The way I would handle your situation would be to (re)throw the exception from the second statement.
try {
    $this->throwExceptionA();
    $this->throwExceptionB();

} catch (Exception $e) {
    if($e->getMessage() == "ExceptionA Message") {
        //Do handle code

    } elseif($e->getMessage() == "ExceptionB Message") {
        //Do other clean-up
        throw $e;

    } else {
        //We should always do this or we will create bugs that elude us because
        //we are catching exception that we are not handling
        throw $e;
    }
}


text:
Q: Editing function in WordPress template - can edit just one variable? I know pretty much no PHP other than what I've tinkered with on WordPress, but I'm trying to customize my theme to allow two authors to be listed on the front-end of posts.
I installed the Co-Authors Plus plugin (Here)
And from the back end it's working well, both authors show up.
For it to show up on the front end, according to several support articles I need to adjust the theme functions to check if there are multiple authors, and if so display them.
I understand the basics and identified the theme file, but have no idea how to incorporate it because it seems that the theme isn't calling a function to display the authors, it's calling a variable in a much larger function (again, I don't know php, so if I'm wrong here, please let me know).
This is the bare bones code provided by Co-Authors Plus:
if ( function_exists( 'coauthors_posts_links' ) ) {
coauthors_posts_links();
} else {
the_author_posts_link();
}

But when I look in the functions file I don't see where that could go. I see this:
// mom_post_meta
function mom_posts_meta ($class = '', $display = null) {
    $num_comments = get_comments_number(); // get_comments_number returns only a numeric value

if ( comments_open() ) {
    if ( $num_comments == 0 ) {
        $comments = __('No Comments', 'theme');
    } elseif ( $num_comments > 1 ) {
        $comments = $num_comments .' '. __(' Comments', 'theme');
    } else {
        $comments = __('1 Comment', 'theme');
    }
    $write_comments = ''. $comments.'';
} else {
    //$write_comments =  __('Comments off', 'theme');
    $write_comments = '';
}
$author_link = esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) );
if (class_exists('userpro_api')) {
    global $userpro;
$author_link = $userpro->permalink(get_the_author_meta( 'ID' ));
}

$categories = get_the_category();
$separator = ', ';
$cats = '';
if($categories){
    foreach($categories as $category) {
        $cats.= 'term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s", 'theme' ), $category->name ) ) . '">'.$category->cat_name.''.$separator;
    }
}
    $output = '
';
    $author = mom_option('post_meta-author') == 1 ? ''.__('Posted by:', 'theme').' '.get_the_author().'': '';
    $date = mom_option('post_meta-date') == 1 ? ''.__('On:', 'theme').' <time datetime="'.get_the_time('c').'" itemprop="datePublished" class="updated">'.get_mom_date_format().'</time>': '';
    //$date = mom_option('post_meta-date') == 1 ? ''.__('The last Update:', 'theme').' <time datetime="'.get_the_time('c').'" itemprop="datePublished" class="updated">'. get_post_modified_time(mom_option('date_format')).'</time>': '';
    $cat = mom_option('post_meta-cat') == 1 ? ''.__('In', 'theme').': '.trim($cats, $separator).'': '';
    $comments = mom_option('post_meta-comments') == 1 ? ''.$write_comments.'': '';
    if ($display == 'date_comments') {
        $output .= $date.$comments;
    } else {
        $output .= $author.$date.$cat.$comments;
    }
    if(function_exists('the_views')) {
        $output .= ''.__('Views:', 'theme').' '.the_views(false).'';
    }
    $output .= get_mom_show_review_score();
    $output .= '
';
    echo $output;
}

I see that the $author line is what defines the output on the front end, but without an understanding of php I'm not sure how to include an if-else statement in there.
I tried a few amateur edits, and just got errors. Any guidance of how to incorporate this while preserving the theme styling would be so very much appreciated.
I'm using Momizat's Goodnews theme.


text:
Q: Function to add static values to a pandas series, up to a certain value, but still react to changes based on a given columns value I was able to create exactly what I wanted as a for loop going through a pandas dataframe. However, it's very slow once applied to even a small dataset (1000s of rows).
The beginning data frame is as follows:
import pandas as pd
import numpy as np

d = np.random.randint(low=0, high=2, size=(50, 2))
df = pd.DataFrame(d, columns=['Column 1', 'Column 2'])

def my_signal(df):

    if ((df['Column 1']) - (df['Column 2'])) < 0:

        return 1

    else:

        return 0

df['signal'] = df.apply(my_signal, axis=1)

print(df.head())

Which produces the following output
   Column 1  Column 2  signal
0         1         0       0
1         0         0       0
2         1         1       0
3         0         1       1
4         0         0       0

Now I'd like to run through the data and if the signal is 0 then we return -0.2 and if its 1 we return 0.2 for our position. We'd also like to having a running total, called 'new col'.
def my_pos(df):

    if df['signal'] == 1:

        return 0.2

    else:

        return -0.2

df['position'] = df.apply(my_pos, axis=1)

df['new col'] = df['position'].cumsum()

print(df.head())

   Column 1  Column 2  signal  position  new col
0         0         0       0      -0.2     -0.2
1         0         0       0      -0.2     -0.4
2         1         0       0      -0.2     -0.6
3         0         1       1       0.2     -0.4
4         0         0       0      -0.2     -0.6

But now we get to the problem. We don't want the total position value to exceed 1 or be less than -1. I've tried using clip but what happens is that just caps the value displayed and while the 'new col' value still exceeds negative one. Here's an example of what we don't want to happen as we progress through the data
       Column 1  Column 2  signal  position   new col
20         0         0       0      -0.2         -0.8
21         0         0       0      -0.2         -1.0
22         1         0       0      -0.2         -1.0
23         0         0       0      -0.2         -1.0
24         0         1       0       0.2         -1.0

So in last row even though position was 0.2 our 'new col' value didn't change. But that's because at the 'new col' 23rd index value the value is actually -1.4, but appears as 1.0. So when we add 0.2 it still returns 1.0 because the value is -1.2, still less than -1.
I've been able to create a for loop to accomplish this, but as a mentioned it's very slow. I have to add a new column beforehand, but here's the loop:
df['new col'] = 0

for i in range(len(df)):

if df['signal'].iloc[i] == 0:   # if the signal is negative

    if ((df['new col'].iloc[i - 1]) - 0.2) < -1:   # if the row above - 0.1 < -1 set the value of current row to -1

        df['new col'].iloc[i] = -1

    else:   # if the new col value above -0.2 is > -1 then subtract 0.1 from that value

        df['new col'].iloc[i] = df['new col'].iloc[i - 1] - 0.2

elif df['signal'].iloc[i] == 1:     # if the signal is positive

    if ((df['new col'].iloc[i - 1]) + 0.2) > 1:     # if the value above + 0.1 > 1 set the current row to 1

        df['new col'].iloc[i] = 1

    else:   # if the row above + 0.2 < 1 then add 0.1 to the value of the current row

        df['new col'].iloc[i] = df['new col'].iloc[i - 1] + 0.2

I'm thinking the main source of my problem is being able to reference each previous value within the function. But I'm not sure. At the end of the day my question would be how produce the output from the above for loop in a much more efficient way to my pandas dataframe.
Thanks!


text:
Q: JQuery UI Datepicker not functioning I am running into an issue where I feel as though I have everything set up correctly; but, no matter what, the JQuery UI Datepicker will not show up.
I have the following set up in my header (Angular project, header is always loaded no matter the route):
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet">

As well as this

However when I am in Firefox and click on the following, nothing happens

   <input type="date" id="date" max="{{maxDate}}" class="form-control" ng-model="revenue.date" placeholder="YYYY-MM-DD" required/>

It also does not show up here
<input type="date" class="form-control" ng-model="user.startofbusiness" name="startofbusiness" id="startofbusiness" required>

I've checked many different StackOverflow threads but even when I follow the methodologies put forth by them, I can't get it to cooperate.
Any tips would be greatly appreciated!

A: As it turns out, this was implemented correctly, and is actually working. The issue was with regards to having used ng-repeat to generate the table's information dynamically. I am addressing this by writing a custom directive to handle the datepicker.


text:
Q: Angular remote form not displaying error I have created an angular form that displays input validation errors received from the server. My solution works fine except for one small issue.
If I submit the form with no value, after the page loads, I am receiving the correct response from my server i.e. 422, but the validation error is not displayed. If I then start typing a value in the input the validation error flashes and disappears.
I am almost certain that it has something to do with my directive, but I'm not sure how to fix it. This is my current directive code:
var appServices = angular.module('webFrontendApp.directives', []);

appServices.directive('serverError', function(){
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope,element,attrs,ctrl){
      element.on('change keyup', function(){
        scope.$apply(function(){
          ctrl.$setValidity('server', true);
        });
      });
    }
  };
});

I think the issue is with the element.on('change keyup'.... section of this code. That's why the error message flashes when I start typing. Also when I change this to 'change' instead of 'change keyup', the error message is displayed permanently when I start typing.
Does anybody have an idea of how I can display the error message even if I did not type any value into the input before submitting it the first time?
UPDATE AS PER COMMENT
Here is my form:
<form ng-submit="create(memberData)" name="form" novalidate>

     <input type="text" ng-model="memberData.email" placeholder="janedoe@mail.com"  name="email" class="col-xs-12 form-control" server-error>

       {{errors.email}}

    <button type="submit" class="btn btn-danger col-xs-12">Join Private Beta</button>

</form>

And my controller:
$scope.memberData = {};
$scope.create = function() {
    var error, success;
    $scope.errors = {};
    success = function() {
      $scope.memberData = {};
    };
    error = function(result) {
        angular.forEach(result.data.errors, function(errors, field) {
            $scope.form[field].$setValidity('server', false);
            $scope.errors[field] = errors.join(', ');
        });
    };

    BetaMember.save({ beta_member: { email: $scope.memberData.email || "" }}).$promise.then(success, error);

};

A: Since the form itself doesn't have a $setValidity method, because doens't have an ng-model, and assuming that the server error is not referred to a single field ( in this case a $setValidity method is preferred ), I think that the simplest solution could be this one:
Create a form with some random validation ( this one simply needs at least the username ) and a div that can display a custom server error.

    <form novalidate name="createForm">

            <input ng-model="name" name="name" type="text" required placeholder="John Doe">

                Some kind of error!

            {{ serverError.message }}

        <input
            value="Join Private Beta"
            ng-disabled="createForm.$invalid || serverError"
            ng-click="create()"
            type="button">

    </form>

Then in your controller you can add the create method that deal with YourService ( should return a promise ) and if the response is failure you can create a simple object with a custom server error message inside which will also be usefull to disable the form button, if you need.
var AppCtrl = function($scope, YourService){

    // Properties

    // Shared Properties

    // Methods
    function initCtrl(){}

    // Shared Methods
    $scope.create = function(){

        YourService.makeCall().then(function(response){

            // Success!

            // Reset the custom error
            $scope.serverError = null;

        }, function(error){

            // Do your http call and then if there's an error
            // create the serverError object with a message
            $scope.serverError = {
                message : 'Some error message'
            };

        })

    };

    // Events

    // Init controller
    initCtrl();

};

AppCtrl.$inject = [
    '$scope',
    'YourService'
];

app.controller('AppCtrl', AppCtrl);

I mean it's very simple snippet here, I just wanted to bring an example. Nothing to complex, but you can scale this to something more.

A: It seems that there was an extremely simple workaround. Since I had the filter form.email.$dirty in my view, the error would not be displayed if the user clicked submit without clicking on the form first.
After removing form.email.$dirty and only having form.email.$invalid, it works perfectly. I think this is sufficient in my case, as this validation is dependant on a server response and will not be triggered before the form is submitted. The error object is also cleared up in my controller ensuring that the page does not load an error when it's first loaded.


text:
Q: Laravel relation between 3 models? I need to define relations between 3 Models in Laravel.
I have Users, Documents and Permissions. A User can have many Documents and a Document can be assigned to many Users. That's the easy part, a many-to-many relation.
Now I have a Permission table with two entries, read and write.
I can't get my head around it, how to assign read or write permission to a document, based on the User.
For example:
User1 can write Document1 and read Document2
User2 can write both
User3 can only read both

A: App\User::find(1)->documents()->save($document,
                ['read' => true, 'write' => false]);

Also, in your models, add to your relationships:
->withPivot('document_id', 'user_id', 'read', 'write');

This would also be the fields of your table.
And than use
foreach ($user->documents as $document) {
    echo 'Can read: ' . $document->pivot->read;
}

For readability you could add a name to the pivot using:
->withPivot(...)->as('permissions')

And than access the pivot using:
foreach ($user->documents as $document) {
    echo 'Can read: ' . $document->permissions->read;
}

Thanks to bogdan in the comments for the pivot name.


text:
Q: PHP autloading failing in __sleep() magic method I'm having issues with autoloading classes in PHP's magic __sleep() method.  Autoloading doesn't take place, so the class cannot be found.  In an attempt to debug this I tried calling spl_autoload_functions() which then causes PHP to segfault...
The example code below demonstrates the problem.  Using an instance method or a static method has the same behaviour.  This seems to work fine for me using __destruct() instead, which suits my use case fine, but I'm curious as to the reason behind this.  Is it a PHP bug, or is there a sensible explanation?
In Foo.php, just as an autoload target
<?php
class Foo {
    public static function bar() {
        echo __FUNCTION__;
    }
}
?>

In testcase.php
<?php
class Autoloader {
    public static function register() {
        // Switch these calls around to use a static or instance autoload function
        spl_autoload_register('Autoloader::staticLoad');
        //spl_autoload_register(array(new self, 'instanceLoad'));
    }

    public function instanceLoad($class) {
        require_once dirname(__FILE__) . '/' . $class . '.php';
    }

    public static function staticLoad($class) {
        require_once dirname(__FILE__) . '/' . $class . '.php';
    }
}
Autoloader::register();

class Bar {
    public function __sleep() {
        // Uncomment the next line to segfault php...
        // print_r(spl_autoload_functions());
        Foo::bar();
    }
}
$bar = new Bar;

This can be run by placing both files in a directory and running php testcase.php.  This occurs for me with PHP 5.3.3 and 5.2.10.

A: The problem you describe sounds very similar to this entry in the PHP bug tracker:
http://bugs.php.net/bug.php?id=53141
That bug was fixed in PHP 5.3.4 (search for "53141" on http://php.net/ChangeLog-5.php).


text:
Q: CORS error on some API endpoints but not others in same controller I have a controller with multiple API endpoints. Most endpoints work as expected but there are 2 which throw a CORS error when deployed on a remote server.

Access to fetch at 'BACKEND URL' from origin 'FRONTEND URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have omitted some code below for brevity.
The API /api/person/uid/14 works as expected in both localhost and on a remote server.
The API /person/email/john@email.com works on localhost, but returns an error when deployed on a remote server.
Both frontend and backend are hosted on the same machine and sit on the same domain. The only difference in the URL are the ports (frontend 3000; backend API 8082).
Having said that, the first API (and many others in this controller) work on both local and the remote server, only the email and mobileNumber validation APIs are throwing a CORS error, which makes this really puzzling.
Any thoughts are appreciated.
PersonController.java
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api")
public class PersonController {

@Autowired
PersonService personService;

@GetMapping("/person/uid/{uid}")
public Boolean uidExists(@PathVariable("uid") String uid) {
    return personService.uidInUse(uid);
}

@GetMapping("/person/mobileNumber/{mobileNumber}")
public Boolean mobileNumberExists(@PathVariable("mobileNumber") String mobileNumber) {
    return personService.mobileNumberInUse(mobileNumber);
}

@GetMapping("/person/email/{email}")
public Boolean emailExists(@PathVariable("email") String email) {
    return personService.emailInUse(email);
}

@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
        MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return errors;
}
}

PersonService.java
@Service
public class PersonService {

@Autowired
PersonRepository personRepository;

// NOTE: ...NotDeleted and ...InUse methods implies deleted == false

// read methods
public List<PersonDto> findAllNotDeleted() {
    return personRepository.findByDeleted(false).stream()
            .filter(p -> !p.getDeleted())
            .map(Person::toDto)
            .collect(Collectors.toList());
}

public Optional<Person> findByIdInUse(Long personId) {
    return personRepository.findByPersonIdAndDeleted(personId, false);
}

// checkers
public Boolean uidInUse(String uid) {
    return personRepository.findByPersonUidAndDeleted(uid, false)
            .isPresent();
}

//edit: check if personid is the same as personname
public Boolean uidInUse(String uid, Long personId) {
    Optional<Person> personOptional = personRepository
            .findByPersonUidAndDeleted(uid, false);
    return personOptional.isPresent() &&
            !Objects.equals(personOptional.get().getPersonId(), personId);
}

public Boolean mobileNumberInUse(String personMobileNumber) {
    return personRepository.findByPersonMobileNumberAndDeleted(personMobileNumber, false)
            .isPresent();
}

public Boolean emailInUse(String email) {
    return personRepository.findByPersonEmail(email).size() > 0;
}

public Boolean idInUse(Long id) {
    return personRepository.findByPersonIdAndDeleted(id, false).isPresent();
}

// create / update methods
public PersonDto createNotDeleted(CreatePersonDto personDto) {
    return personRepository.save(personDto.toPerson(false)).toDto();
}

//for deletion
public PersonDto save(PersonDto personDto, Boolean deleted) {
    return personRepository.save(personDto.toPerson(deleted)).toDto();
}

//normal save
public Person save(Person person) {
    return personRepository.save(person);
}

// helpers (if other controllers need can move to util)
public String generateUid() {
    String randomString;

    do {
        randomString = generateRandomString(8);
    } while (uidInUse(randomString));
    return randomString;
}

private String generateRandomString(int length) {
    int leftLimit = 48; // "0"
    int rightLimit = 122; // "z"
    Random random = new Random();

    return random.ints(leftLimit, rightLimit + 1)
            .filter(i -> i <= 57 || (i >= 65 && i <= 90) || i >= 97)
            // "9" and below OR "A" to "Z" OR "a" and above
            .limit(length)
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();

}
}

A: Could be an issue with consumes/produces, try adding produces = MediaType.APPLICATION_JSON or other media type and adjust your request headers as well.


text:
Q: JS - Adding 2 multiselect checkboxes I'm using 2 jQuery UI widgets that adds the selections and only allows the user to select 5 total checkboxes between both dropdown widgets. I'm able to prevent to user from checking more boxes once 5 is hit but cannot uncheck. The below code does not put any restrictions. Any help would be appreciated.
UI widget i'm using:http://www.erichynds.com/blog/jquery-ui-multiselect-widget
<select id="dropdown1" multiple="multiple" class="multiselect">
<select id="dropdown2" multiple="multiple" class="multiselect">

js
$(document).ready(function() {
    $(".multiselect").multiselect({
        header: "Choose up to 5 areas total",
        click: function (event, ui) {
            if (!this.checked) return true;

            if ($(".multiselect").children(":checked").length >= 5) {
                return false;
            }
        },
        selectedList:5
    });
});

removing the return true IF allows the user to only select 5 which also prevents user from unchecking.

A: Try
$(document).ready(function() {
    $(".multiselect").multiselect({
        header: "Choose up to 5 areas total",
        click: function (event, ui) {

            if (!this.checked && $(".multiselect").children(":checked").length >= 5) {
                return false;
            }
        },
        selectedList:5
    });
});

This way the condition to return false will only be met if the user clicked a non-checked box. If user clicks checked box, it will allow unchecking it.


text:
Q: Show that the following equation has exactly $n$ real roots.
If $0<a_1< \cdots < a_n$, show that the following equation has exactly $n$ real roots.
  $$ \frac{a_1}{a_1-x}+\frac{a_2}{a_2-x}+ \frac{a_3}{a_3-x}+ \cdots + \frac {a_n}{a_n - x} = 2015$$

My working:
The LHS easily becomes $$a_1(a_2-x)...(a_n-x)+a_2(a_1-x)(a_3-x)...(a_nx)+.....+a_n(a_1-x)(a_2-x)...(a_{n-1} -x)$$
This shows it has $n$ roots
But what about exactly and real?

A: Hint:
Let $x=a+ib$ a root
Using Complex conjugate root theorem, $a-ib$ also be another root
$$2015-2015=\sum_{r=1}^n\left(\dfrac{a_r}{a_r-(a-ib)}-\dfrac{a_r}{a_r-(a+ib)}\right)=\sum_{r=1}^n?$$
Equate the imaginary parts to find  $b=0$

A: Sketch the graph of the expression on the left hand side of the equation. Try cases n=1, 2 and 3 to get a feel for the general case.
Note that $f(x) = \dfrac{a_1}{a_1-x} + \dfrac{a_2}{a_2-x} + \dfrac{a_3}{a_3-x} + \dots + \dfrac{a_n}{a_n-x} $ has discontinuities/poles at $x=a_1, a_2, a_3, \dots, a_n$ and it is continuous everywhere else.
Also in each of the intervals $(-\infty, a_1), (a_1, a_2), (a_2, a_3), \dots, (a_n, \infty)$ the function $f(x)$ is a monotonically increasing function of $x$ because as $x$ increases each of the denominators decreases so each of the terms $\dfrac{a_i}{a_i-x}$ increases (because the $a_i$ are positive).
As $x$ approaches $-\infty$, each of the terms is small and positive and so $f(x)$ approaches 0 from above; as $x$ approaches $\infty$, each of the terms is small and negative and so $f(x)$ approaches 0 from below.
It should be clear from your sketch that the graph of $y=f(x)$ crosses the horizontal line $y=2015$ at exactly n points, one in each of the intervals $(-\infty, a_1), (a_1, a_2), (a_2, a_3), \dots, (a_{n-1}, a_n)$. So the equation $f(x) = 2015$ has exactly n real roots.
There is nothing special about the value 2015 - for any real value on the right hand side, the same argument shows that equation has exactly n real roots.


text:
Q: Suddenly all database functions fail on my app Suddenly all database functions don' t work on my app. The error is always NullPointer exception and points to deferent methods from dataObjectsProvider class, depended which funcion used. For e.g when trying to insert values on CreateDataObjectsMethod, when trying to empty/delete the database to deleteObjectsMethod.
All these functions worked the last time I closed eclipse and I'm pretty sure that I didn't change something on anything else except on the onClick method of update button which I was trying to make it work. This doesn' t explain why all other functions don' t work. Can you check if I've accidentally made a crusial mistake chich I don't see?
DataObjectsProvider class:
public class DataObjectsProvider {

  // Database fields
  private SQLiteDatabase database;
  private DbHelper dbHelper;
  private String[] allColumns = { DbHelper.COLUMN_ID,
      DbHelper.COLUMN_SONGNAME, DbHelper.COLUMN_SONGARTIST,
      DbHelper.COLUMN_SONGGENRE };

  public DataObjectsProvider (Context context) {
        dbHelper = new DbHelper(context);
      }

  public void open() throws SQLException {
        dbHelper.getWritableDatabase();
      }

  public void close() {
        dbHelper.close();
      }

  public DataObjects createDataObjects (String songName, String songArtist,
          String songGenre) {
       dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DbHelper.COLUMN_SONGNAME, songName);
        values.put(DbHelper.COLUMN_SONGARTIST, songArtist);
        values.put(DbHelper.COLUMN_SONGGENRE, songGenre);
        long insertId = database.insert(DbHelper.TABLE_SONGS, null,
                values);
            Cursor cursor = database.query(DbHelper.TABLE_SONGS,
                allColumns, DbHelper.COLUMN_ID + " = " + insertId, null,
                null, null, null);
            cursor.moveToFirst();
            DataObjects newDobject = cursorToDataObjects(cursor);
            cursor.close();
            return newDobject;

      }

  public Cursor fechAllDobjects(){

      Cursor mCursor = database.query(DbHelper.TABLE_SONGS,
              new String[] {DbHelper.COLUMN_ID,
              DbHelper.COLUMN_SONGNAME, DbHelper.COLUMN_SONGARTIST,
              DbHelper.COLUMN_SONGGENRE},
                null, null, null, null, null);
      if (mCursor != null) {
           mCursor.moveToFirst();
          }
          return mCursor;
  }

  public Cursor fechDobjectsByName(String inputText) throws SQLException {

      Cursor mCursor = null;
      if (inputText == null  ||  inputText.length () == 0)  {
       mCursor = database.query(DbHelper.TABLE_SONGS,
         new String[] {DbHelper.COLUMN_ID,
         DbHelper.COLUMN_SONGNAME, DbHelper.COLUMN_SONGARTIST,
         DbHelper.COLUMN_SONGGENRE},
         null, null, null, null, null);

      }
      else {
       mCursor = database.query(true, DbHelper.TABLE_SONGS,
         new String[] {DbHelper.COLUMN_ID,
         DbHelper.COLUMN_SONGNAME, DbHelper.COLUMN_SONGARTIST,
         DbHelper.COLUMN_SONGGENRE},
         DbHelper.COLUMN_SONGNAME + " like '%" + inputText + "%'", null,
         null, null, null, null);
      }
      if (mCursor != null) {
       mCursor.moveToFirst();
      }
      return mCursor;
  }

     /* public void deleteDobjects(DataObjects dobjects) {
            long id = dobjects.getId();
            database.delete(DbHelper.TABLE_SONGS, DbHelper.COLUMN_ID
                + " = " + id, null);

      }*/
      public void DeleteItem(long l)
        {
    dbHelper.getWritableDatabase();
    String query = "DELETE FROM songs WHERE _id="+l;
    database.execSQL(query);
        }

      public void UpdateItem(int id, String songName, String songArtist, String songGenre) {
          dbHelper.getWritableDatabase();
          ContentValues values = new ContentValues();
          values.put(DbHelper.COLUMN_SONGNAME, songName);
          values.put(DbHelper.COLUMN_SONGARTIST, songArtist);
          values.put(DbHelper.COLUMN_SONGGENRE, songGenre);
          database.update(DbHelper.TABLE_SONGS, values, DbHelper.COLUMN_ID +"="+id, null);
      }

      public void deleteAllDobjects() {
          dbHelper.getWritableDatabase();
          database.delete(DbHelper.TABLE_SONGS, null, null);
      }

      public List<DataObjects> getAlldobjects() {
            List<DataObjects> dobjects = new ArrayList<DataObjects>();

            Cursor cursor = database.query(DbHelper.TABLE_SONGS,
                allColumns, null, null, null, null, null);

            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
              DataObjects dobject = cursorToDataObjects(cursor);
              dobjects.add(dobject);
              cursor.moveToNext();
            }
            // Make sure to close the cursor
            cursor.close();
            return dobjects;

      }

    private DataObjects cursorToDataObjects(Cursor cursor) {
        DataObjects dobject = new DataObjects();
        dobject.setId(cursor.getLong(0));
        dobject.setSongName(cursor.getString(1));
        dobject.setSongArtist(cursor.getString(2));
        dobject.setSongGenre(cursor.getString(3));
        return dobject;
    }

}
Database helper class:
public class DbHelper extends SQLiteOpenHelper {

      public static final String TABLE_SONGS = "songs";
      public static final String COLUMN_ID = "_id";
      public static final String COLUMN_SONGNAME = "songname";
      public static final String COLUMN_SONGARTIST = "artist";
      public static final String COLUMN_SONGGENRE = "genre";

      private static final String DATABASE_NAME = "songsdb.db";
      private static final int DATABASE_VERSION = 1;

      // Database creation sql statement
      private static final String DATABASE_CREATE = "create table "
          + TABLE_SONGS + "("
          + COLUMN_ID + " integer primary key autoincrement, "
          + COLUMN_SONGNAME + ","
          + COLUMN_SONGARTIST + ","
          + COLUMN_SONGGENRE + ");";

      public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }

      @Override
      public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
      }

      @Override
      public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        Log.w(DbHelper.class.getName(),
            "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS " + TABLE_SONGS);
        onCreate(database);
      }
}

delete database log:
02-15 13:33:13.158: W/dalvikvm(1966): threadid=1: thread exiting with uncaught exception (group=0x40c931f8)
02-15 13:33:13.168: E/AndroidRuntime(1966): FATAL EXCEPTION: main
02-15 13:33:13.168: E/AndroidRuntime(1966): java.lang.NullPointerException
02-15 13:33:13.168: E/AndroidRuntime(1966):     at com.d69.dancesongsdb.DataObjectsProvider.deleteAllDobjects(DataObjectsProvider.java:113)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at com.d69.dancesongsdb.MainActivity$3.onClick(MainActivity.java:102)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at android.os.Looper.loop(Looper.java:137)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at android.app.ActivityThread.main(ActivityThread.java:4424)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at java.lang.reflect.Method.invokeNative(Native Method)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at java.lang.reflect.Method.invoke(Method.java:511)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
02-15 13:33:13.168: E/AndroidRuntime(1966):     at dalvik.system.NativeStart.main(Native Method)

insert data log:
02-15 13:35:36.457: W/dalvikvm(2104): threadid=1: thread exiting with uncaught exception (group=0x40c931f8)
02-15 13:35:36.477: E/AndroidRuntime(2104): FATAL EXCEPTION: main
02-15 13:35:36.477: E/AndroidRuntime(2104): java.lang.NullPointerException
02-15 13:35:36.477: E/AndroidRuntime(2104):     at com.d69.dancesongsdb.DataObjectsProvider.createDataObjects(DataObjectsProvider.java:39)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at com.d69.dancesongsdb.MainActivity$2.onClick(MainActivity.java:66)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at android.view.View.performClick(View.java:3511)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at android.view.View$PerformClick.run(View.java:14105)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at android.os.Handler.handleCallback(Handler.java:605)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at android.os.Looper.loop(Looper.java:137)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at android.app.ActivityThread.main(ActivityThread.java:4424)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at java.lang.reflect.Method.invokeNative(Native Method)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at java.lang.reflect.Method.invoke(Method.java:511)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
02-15 13:35:36.477: E/AndroidRuntime(2104):     at dalvik.system.NativeStart.main(Native Method)

A: You have a few lines of code that are just:
dbHelper.getWritableDatabase();

Now, this won't actually do anything. Instead, I think you want to do this:
database = dbHelper.getWritableDatabase();

Without that line, the database is null when you use it in createDataObjects which causes the NullPointerException.
I count at least 5 instances where that happens, so make sure you change them all.


text:
Q: Unity Not Displaying Sprites / Textures I'm getting started with Unity, but having trouble with the most basic of operations - getting an image to appear on the screen.
I've tried researching this, but almost all the tutorials / info on Unity are about more advanced usage and don't cover the basics.  There's very little info out there on basic image loading and drawing.
My project has one object, with this script attached:
public class Boxland_Main : MonoBehaviour
{
     Texture2D test_sprite;

     void Start ()
     {
       print ("STUFF");  // this works
       test_sprite = (Texture2D) Resources.Load ("richard_green.png");
     }

     void Update ()
     {
       GUI.DrawTexture (new Rect(0, 0, 50, 50), test_sprite);  // this doesn't work
     }
}

My image file is in the Resources directory, but all I ever get is a powder blue screen.
EDIT:
For clarity, I'd be interested in any solution that just gets an image up on the screen.  I feel I'm getting close to going back to XNA or GameMaker.
UPDATE:
Here's what I've got now (still with no sprite being drawn):
public class Boxland_Main : MonoBehaviour
  {
  public Texture2D test_sprite;

  void Start ()
    {
    test_sprite = (Texture2D) Resources.Load ("richard_green");
    }

  void OnGui ()
    {
    if (test_sprite) GUI.DrawTexture (new Rect (0, 0, 50, 50), test_sprite);
    }
  }

UPDATE:
I found that if I drag an image directly from the asset window onto the scene window in the Unity UI, it adds the sprite to the view and the sprite shows up on compile.  However, it's rendering blurry and pixelated, and there doesn't seem to be any way to specify a particular frame on the sprite sheet.
UPDATE:
I came across some material while researching that may point to a partial answer:
Unity 4.3 - 2D, how to assign programmatically sprites to an object
http://docs.unity3d.com/ScriptReference/Resources.Load.html
This seems to cover loading an image, but never goes into explaining how to draw the image.

A: You should call GUI functions insde OnGUI, not the Update (http://docs.unity3d.com/Manual/gui-Basics.html)
So try to change your Update() to
void OnGUI() {
    if(test_sprite) {
        GUI.DrawTexture (new Rect(0, 0, 50, 50), test_sprite);
    }
}

A: You dont specify the .png for resources. Just the name.
test_sprite = (Texture2D) Resources.Load("richard_green", Texture2D);

A: I never did get Unity to draw anything (that wasn't blurry and compressed-looking), using any technique, but I just tried out Monogame (http://www.monogame.net/) and got good-looking sprites on the screen within five minutes.  The downside to Monogame is the lack of Xbox One support, but I'm willing to live with that for now.
It looks like my final conclusion is either:
A) Unity is STILL just not a good solution for making 2D games, or
B) It's such a different animal from other engines I've used that I just can't wrap my brain around it.
And yet, obviously, lots of developers have made nice games in it (with graphics).  Someone really needs to write a good, basic intro tutorial in the style of "Step 1: Starting a project, Step 2: Loading an image, Step 3: Drawing an image".
I'll likely come back to this post sometime in the future when I'm ready to give Unity a third try, and see if there are any new ideas / techniques out there.

A: Did you try the example on unity?
https://docs.unity3d.com/530/Documentation/ScriptReference/Texture2D.LoadImage.html
using UnityEngine;

public class ExampleClass : MonoBehaviour {
    // Load a .jpg or .png file by adding .bytes extensions to the file
    // and dragging it on the imageAsset variable.
    public TextAsset imageAsset;
    public void Start() {
        // Create a texture. Texture size does not matter, since
        // LoadImage will replace with with incoming image size.
        Texture2D tex = new Texture2D(2, 2);
        tex.LoadImage(imageAsset.bytes);
        GetComponent<Renderer>().material.mainTexture = tex;
    } }


text:
Q: asp.net c# .net framework 2.0 and 3.5 We have a asp.net application built in .net framework 2.0.
I need to edit a web report and add few columns to the report.
I updated the aspx.cs file and uploaded it to the server but there is no change in the report. If I change aspx file it works but aspx.cs file changes are not reflecting on the server. And I dont have local setup of the application to check.
Is it necessary to compile the file, but same thing I have done with framework 4.5 without compiling and it worked. How can I update the report without compiling the file.

A: In server it executes only compiled code, if you upload .cs files, it will affect nothing, so you need to upload compiled code(.dll) to see the changes.

A: you need to publish the new .dll file found in the bin directory to the remote locations bin folder.
If youre publishing through VS which I suspect your not, this would do this automatically on publish.
If youre doing what I think your doing and copying and pasting you need to copy the bin directory up too.
There are a number of files \ folders that you need but the aspx.cs files are not any of them.

A: In ASP.NET when you place the aspx and aspx.cs file the files get complied automatically before the execution by ASP.NET engine. Please check the updated code does it contain any reference from 4.5 library.Additionally you can try to referesh the IIS cache sometimes ASP.Net engine unable to refresh/replce the existing files in the cache folder.


text:
Q: Pink noise and averaging Disclaimer: I am aware this is somehow at the boundary between physics and statistics, but I have the impression that it is more likely that somebody doing/studying physics, rather than statistics, has stumbled in this problem, which in the end is very practical. Feel free to comment and/or suggest a better community if you disagree!

When measuring any physical parameter, uncertainty can be reduced by repeating the measurement many times and then taking the average value $\mu=(\sum_1^N x_i)/N$, or also by measuring for a longer time. Assuming the single measurement has a noise $\sigma_{x_i}=\sigma_0$, it is common knowledge that the standard deviation of the average of $N$ measurement should scale as $\sigma_\mu = \sigma_0/\sqrt{N}$ (or actually $\sigma_0/\sqrt{N-1}$)... so the more you measure, the more precise your estimate.
However, indeed this is only true if the $N$ measurements are uncorrelated, which is equivalent to stating that the measurement is affected only by white noise. When flicker noise is present (i.e., ultimately, always), the power spectral density of noise deviates from flat in the low-frequency limit, and at some point starts growing as $\propto 1/\omega$ (or even steeper but let us neglect that). As a result, this means that the value you measure "now" has some correlation with those you got "previously", and the rule above fails.
Question: How does the standard deviation scale with the number of measurements or with the integration time in the presence of flicker/pink noise?! Can you point me in the right direction and/or do you have a good textbook/reference discussing this? I am having a hard time finding one... statistics books even rarely discuss power spectral densities, not to mention specific cases like this one; in physics texts, it is uncommon that correlated noise is discussed in detail.
What I have concluded so far. It is quite obvious that in the presence of pink noise the precision of the estimate won't improve forever like $\approx 1/\sqrt{N}$ by simply increasing the number of measurements $N$. I have found vague comments about the existence of a "Flicker floor" but no real clear discussion about it. I see that the problem has a well-defined frequency scale, which is the frequency below which flicker noise takes over and dominates the spectral density, the "Flicker corner" $\omega_c$. So I would intuitively expect that measuring for a time that is longer or shorter than the time scale $1/\omega_c$ makes a qualitative difference.
One obvious approach to see what happens if I integrate my measurement for a time $T$ might be to consider the measurement window - say, $[-T/2,+T/2]$ - and use its Fourier transform (sinc function) to see which are the frequencies that I am sampling and calculate the total noise. With white noise, it works fine but when you turn to pink, the integral of the PSD clearly diverges. I suspect this has to do with the fact that even the average does not converge with flicker... but... not sure where to head to from here.
[Edit] I have found some interesting clues, "flicker floor" was the main search key that led me to the link below. I have not gone through the work in details but it seems to answer to at least some of my doubts
https://arxiv.org/abs/1407.7760v6


text:
Q: What are some tips for optimizing the assembly code generated by a compiler? I am currently in the process of writing a compiler and I seem to have run into some problems getting it to output code that executes in a decent timeframe.
A brief overview of the compiler:

7Basic is a compiler that aims to compile 7Basic code directly into machine code for the target architecture / platform. Currently 7Basic generates x86 assembly given a source file.

The problem is that the assembly code generated by the compiler is slow and inefficient.
For example, this code (which compiles down to this assembly code) takes nearly 80.47 times longer to execute than the equivalent C code.
Part of the problem is that the compiler is generating code like the following:
push eax
push 5000000
pop ebx
pop eax

Instead of the more logical:
mov ebx,5000000

...which accomplishes the same thing.
My question is: what are some techniques to avoid this sort of problem? The parser basically uses recursion to parse the expressions, so the code generated reflects this.

A: You might want to consider generating C code rather than assembly and then let a C compiler (e.g. gcc) handle the code generation for you. There's no point trying to re-invent the wheel.

A: I'm taking a compiler course at the moment. I've made some great progress in outputting efficient code, but you should look into the dragon book. It is a rite of passage. You should take a look at the code from Jeremy Bennett's book, Introduction to Compiling Techniques: A First Course Using ANSI C, LEX, and YACC. The book itself is very hard to find, but you can download the source code for the compiler free from
http://www.jeremybennett.com/publications/download.html
The code generator file (cg.c) has some functions for generating fairly optimized code. The target language isn't i386, but you should consider looking at how he describes registers and keeps track of where symbol table entries are stored. His output assembly could be further optimized, but it provides a great base for producing code that could rival the output from gcc -S in some regards.
One general optimization would be to subtract the stack pointer to reserve space for all local and temporary variables upon entering a function. Then just reference the offsets instead of constantly pushing/popping.
For example, if your intermediate code is a list of quadruples, you should simply iterator through it for each function and keep track of the maximum offset. Then output the line to subtract the amount of space on the stack. This removes the need to push so many variables on and off. To remove the need to pop them, you can simply mov their value from their offset on the stack into a register. This will significantly improve performance.

A: There are any number of reasons a particular code generator may emit the instruction sequence you list.  The most likely is that the code generator you're using just isn't trying very hard to emit optimum code.
This pattern of emitted code suggests to me that your code generator doesn't know that the x86 has "mov immediate" instructions that embed the constant value into the instruction stream directly.  The x86 encoding for opcodes with immediate values can get a little complicated (variable length R/M bytes) but this is already required if you want to use many of the x86 instructions.
This emitted code also suggests that the code generator doesn't know that EAX is not modified by the EBX instructions.  This feels like the codegen is template driven rather than discrete logic.
This kind of codegen happens when the compiler's internal intermediate representation of operations is not detailed enough to represent all the facets of the target architecture.  This is particularly true if the code generator architecture was originally designed for a RISC instruction set but has been repurposed to emit x86 instructions.  RISC architecture tend to have very few and very simple load, store, and operate reg/reg instructions, whereas the x86 instruction set has evolved organically over decades to include a wide variety of opcodes that operate directly on memory, inline constants into the instructions, and a whole mess of other stuff.  If the compiler's intermediate representation (expression graph) is wired for RISC, it will be difficult to make it grok the wide variety and subtleties of x86.

A: Peephole optimizations will help, but one obvious issue is that your compiler doesn't do register allocation!
http://en.wikipedia.org/wiki/Register_allocation
If you want to get serious performance levels, you're doing to have to look into that. It can be done in a single pass if you do it greedily "on the fly".

A: One technique is called peephole optimisation. This takes an iterative approach to cleaning up assembly code. Essentially you scan through the assembly code, looking at only two or three instructions at a time, and see whether you can reduce them into something simpler. For example,
push eax        ; 1
push 5000000    ; 2
pop ebx         ; 3
pop eax         ; 4

The first step would look at lines 2 and 3, and replace that with:
push eax        ; 1
mov ebx,5000000 ; 2a
pop eax         ; 4

Second, you might consider 1 and 4, and if eax is not touched in the middle instruction, remove them both, leaving what you want:
mov ebx,5000000 ; 2a


text:
Q: tbb parallel_reduce for a snippet of OpenMP reduction I have the following code snippet of OpenMP that I know works correctly for sure.
char cipherChar=plainText[charLoop];
#pragma omp parallel for reduction(^:cipherChar)
for(keyLoop=0;keyLoop<numKeys;keyLoop++) {
    cipherChar = cipherChar ^ getBit( &(keyList[keyLoop]), charLoop);
}
cypherText[charLoop]=cipherChar;

But when I try to write this code in tbb, I don't get the correct output
char cipherChar=plainText[charLoop];
cipherChar ^= tbb::parallel_reduce(tbb::blocked_range<int>(0, numKeys), cipherChar,
[&](const tbb::blocked_range<int>& r, char c) -> char {
            char result = c;
            for(int i = r.begin(); i <= r.end(); i++) {
                    result ^= getBit( &(keyList[i]), charLoop);
            }
            return result;
    },

    [](char a, char b) {
            return a ^ b;
    }
);
cypherText[charLoop]=cipherChar;

Can anyone tell me what I might be doing wrong in the above tbb code that I am getting a wrong result?

A: The second parameter to parallel_reduce - the one following blocked_range - should be the identity value for the used reduction operation. This value is used by the implementation to initialize accumulators. For exclusive or, the identity value is 0. Also it is important that the type of the identity value matches the type of the result.
So, your call should be
cipherChar ^= tbb::parallel_reduce(
    tbb::blocked_range<int>(0, numKeys),
    char(0), // <- identity for XOR
    body_lambda,
    reduction_lambda
);


text:
Q: Xilinx FPGA "X" state in simulation and didn't find the bug I wrote an ASRAM in VHDL and simulate it. I get many "X" if I try to read.
I know that this problem is caused by too many drivers on one net but I didn't find the problem nor solved it.
Appreciate some help.
[
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.std_logic_unsigned.all;
use IEEE.std_logic_arith.all;
use work.mem_type.all;

entity async_sram_tristate_new_nBit_test is
    generic (   DAT_WIDTH:  natural := 16;  -- number of data bits
                ADDR_WIDTH: natural := 6); -- number of address bits

    port (      ram_dat : inout std_logic_vector ((DAT_WIDTH - 1) downto 0); -- bidirectional data bus to/from the SRAM device
                ram_addr: in    std_logic_vector ((ADDR_WIDTH - 1) downto 0);  -- address bus of the SRAM device
                nCS     : in    std_logic;   -- low-active Chip-Enable of the SRAM device; defaults to '1' (inactive)
                nOE     : in    std_logic;   -- low-active Output-Enable of the SRAM device; defaults to '1' (inactive)
                nWE     : in    std_logic;   -- low-active Write-Enable of the SRAM device; defaults to '1' (inactive)
                clk     : in    std_logic;

                data_fpga_read   : out  ram_array_16(0 to (2**(ADDR_WIDTH-1) - 1));
                data_fpga_write  : in ram_array_16(0 to (2**(ADDR_WIDTH-1) - 1))

            );
               -- ram_wait : out std_logic := '0'); -- wait pin to stretch the strobe period; defaults to '0' (inactive)
end async_sram_tristate_new_nBit_test;

architecture Behavioral of async_sram_tristate_new_nBit_test is

constant ADRR_HALF  : natural := 2**(ADDR_WIDTH-1);
constant MEM_SIZE   : natural := 2**(ADDR_WIDTH);
constant DEPTH      : natural := 1;

signal ram : ram_array_16(0 to 2**(ADDR_WIDTH) - 1);              -- declerates a variable ram of type ram_array // this is the REAL memory
signal ram_output_buffer : std_logic_vector ((DAT_WIDTH - 1) downto 0); -- declerates a variable ram of type ram_array to buffer the output
signal addr_buffer : std_logic_vector((ADDR_WIDTH - 1) downto 0);
signal nWE_buffer, nOE_buffer : std_logic_vector(DEPTH downto 0);
begin
    -------------------------------------------------------------------------
    -- TRISTATE BUFFER
    -------------------------------------------------------------------------

    ram_dat <= ram_output_buffer when nOE_buffer(DEPTH) = '0' else (others => 'Z'); -- tristate buffer

    -------------------------------------------------------------------------
    -- ADRESS READ AND BUFFER
    -------------------------------------------------------------------------
    read_addr: process(clk)
    begin
        if(rising_edge(clk)) then
            addr_buffer <= ram_addr;
        end if;
    end process;

    -------------------------------------------------------------------------
    -- READ PROCESS
    -------------------------------------------------------------------------
    read_ram : process (clk)
    begin
        if(rising_edge(clk)) then
        nOE_buffer <= nOE_buffer(DEPTH - 1 downto 0) & nOE;
            if (nOE_buffer(DEPTH) = '0') then
                if (addr_buffer(ADDR_WIDTH - 1) = '0') then -- checks if the adress is in the "read-only" space
                    ram_output_buffer <= ram(conv_integer(unsigned(addr_buffer))); -- makes the data aviable via the output buffer
                end if;
            end if;
        end if;
    end process;

    -------------------------------------------------------------------------
    -- WRITE PROCESS
    -------------------------------------------------------------------------
    write_ram : process(clk)
    begin
        if(rising_edge(clk)) then
        nWE_buffer <= nWE_buffer(DEPTH - 1 downto 0) & nWE;
            -- nWE = 0 indicates that the microcontroller wants to write data
            if (nWE_buffer(DEPTH) = '0') then
                if (addr_buffer(ADDR_WIDTH -1) = '0') then
                    ram(conv_integer(unsigned(addr_buffer))) <= ram_dat;
                end if;
            end if;
        end if;
    end process;

    --ram(2**(ADDR_WIDTH-1) to (2**ADDR_WIDTH)-1) <= data_fpga_write;
    --data_fpga_read <= ram(0 to (2**(ADDR_WIDTH-1)- 1));

end Behavioral;

A: As multiple commenters suggested, because ram_dat is inout, it can (but must not) be driven at the same time by your module and the system instantiating your module.
Make sure you understand how your protocol guarantees absence of multiple drivers (by switching to Z when not in the "driving seat"), and verify that both "outside" and "inside" of the module adhere to this protocol (it may be both are in the wrong!).
I am just summarizing comments into an answer so it's easier to find later.


text:
Q: How to Convert days of week into numbers for correlation calculation using R Is there an accepted way to handle converting the days of the week from text to numeric values for calculating the correlation coefficient in R ?
Should I use dummyVars maybe using the caret package in R and treat them as categorical or is there a better way to avoid any possible dummy variable trap or data loss?
Maybe the following sample table will help the discussion (just show the code snippet and run to see a very basic table)

    PurchaseDay
    Product
    Count
    ReturnDay

    Wednesday
    Tractor
    3
    Tues

    Monday
    Bus
    2
    Mon

    Saturday
    Tractor
    5
    Tues

Is it important that Mon and Monday get the same numeric coding even though they are in different columns?
What is the standard way of representing days of the week as numbers in R so I can create a numeric representation of the data and pass it to the corr()


text:
Q: Trying to execute PHP from JavaScript, not working? I am using the following code: <a href="#" onclick="<?php var_dump($_SERVER)?>">$_SERVER Variable. is this even possible? if not then how would I do this? I amn using $_SERVER for very specific - experimental purposes.
Thanks in advance!

A: No, but you can always send AJAX requests to a php file on the server and parse the response back into your HTML/JS. Check out jQuery's AJAX if you want the easy route ;)  http://api.jquery.com/jQuery.ajax/  A much easier example found at: Sorry, for the self promotion, but on jQuery's Ajax Tutorial I cover this :)

A: Here's a simple PHP/AJAX example:
http://www.w3schools.com/ajax/ajax_aspphp.asp

A: No because PHP is server side scripting while JS is client side

A: You just try the echo to get the specific server value you want instead of using the var_dump


text:
Q: Changing a parameter by specific time in NDSolve in a COVID-19 spread simulation I'm trying to create a mathematical model for COVID-19, to help my city, using the follow system of equations:
odesSEIQRD = {
Derivative[1][S][t] == (-β)*S[t]*(I[t]/(η - Q[t] - D[t])),
Derivative[1][E][t] == (-ζ)*E[t] + β*S[t]*(I[t]/(η - Q[t] - D[t])),
Derivative[1][I][t] == ζ*E[t] - γ*I[t] - μ*I[t] - δ*I[t],
Derivative[1][Q][t] == δ*I[t] - γ*Q[t] - ϵ*Q[t],
Derivative[1][R][t] == γ*I[t] + γ*Q[t],
Derivative[1][D][t] == μ*I[t] + ϵ*Q[t]
};
sol1=NDSolve[{odesSEIQRD,S[0]==η-I0,E[0]==0,I[0]==I0,Q[0]==0,R[0]==0,D[0]==0},{S,E,I,Q,R,D},{t,0,6000},Method->{"StiffnessSwitching",Method->{"ExplicitRungeKutta",Automatic}}];

where
η = 212000000;
β = 3.3*λ[t];
ζ = 1/Log[7];
γ = 0.00005;
μ = 0.0063;
ϵ = 0;
δ = 1;
I0 = 76;

I need to change Lambda, between 1 and 0, in some specific time (day). Example: lambda = 1 between t=0 and t=5. Lambda = 0.8 between t=5 and t=10, and lambda = 0.4 between t=10 and t=20, Lambda = 0.1 between t=20 and t=30. Finally, I need to plot the curve using this values. It must flatten the I[t] curve. The Lambda parameter is related to social isolation, Lambda = 1 -> no social isolation, Lambda = 0 total social isolation.

A: You can define any of your "constants" as arbitrary functions of time. In the example you mention, you could use the Piecewise function to define a discontinuous function of time; or use a Module to define a more complex function if need be.


text:
Q: NullPointerException on TreeView called from controller This is what I have:

*

*FXML: FTPView.fxml

*Controller: FTPController.java
The FTPView.fxml contains a TreeView. I want to add TreeItem'sto that TreeView programmatically but I am not able to do it.
This is the way I am doing it:

*

*Implementing the Initializable interface in the controller.

*Adding the following code to the initialize() method, setting the root TreeItem to the TreeView.
@Override
    public void initialize(URL location, ResourceBundle resources) {

        rootItem = new TreeItem<>();
        tv_serverfiles.setRoot(rootItem);
    }

*Other stuff filling the TreeView.
At one point i was doing it completely wrong, setting the rootelement on the constructor. Then, reading some post in SO, i noticed that i should implement Initializable interface, so i would get the method initialize that would set the root element to my TreeView until all FXML stuff had loaded.
But i am still getting the same error, the NullPointerException.
CODE
FTPView.fxml
I think should skip this one because the unique interesting line is <TreeView fx:id="tv_serverfiles"/>
FTPController.java
public class FTPController implements Initializable{

private FTPClient ftpClient;
private TreeItem<String> rootItem;

private final String
            CONNECTED="Conectado",
            DISCONNECTED="Desconectado",
            ERROR="Error de conexión";

@FXML
private Pane pnMain;

@FXML
private TextField tf_ipaddress;

@FXML
private TextField tf_port;

@FXML
private TextField tf_user;

@FXML
private PasswordField pf_password;

@FXML
private Button btn_connect;

@FXML
private Button btn_sendfile;

@FXML
private TextField tf_filepath;

@FXML
private Button btn_filechooser;

@FXML
private AnchorPane sp_record;

@FXML
private Button btn_requestfile;

@FXML
private ProgressBar pb_progresstransfer;

@FXML
private Label tf_status;

@FXML
private TitledPane tp_transfer_status;

@FXML
private Pane pnRemoteExplorer;

@FXML
private TreeView<String> tv_serverfiles;

@FXML
private Button btn_refresh;

@FXML
private Button btn_goback;

@Override
public void initialize(URL location, ResourceBundle resources) {
    rootItem = new TreeItem<>();

    tv_serverfiles.setRoot(rootItem);
}

/**
 * Carga los ficheros remotos en el TreeTableView para poder listarlos correctamente
 * @param files
 */
private void loadRemoteDirectory(FTPFile[] ftpFiles) {

    //Evento que actualiza los archivos en la tabla
    tv_serverfiles.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<String>>() {

        @Override
        public void changed(ObservableValue<? extends TreeItem<String>> observable, TreeItem<String> oldValue,
                TreeItem<String> newValue) {

            rootItem.getChildren().clear();

            try {
                ftpClient.changeWorkingDirectory(newValue.getValue());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            for(FTPFile f: ftpFiles) {
                TreeItem<String> element = new TreeItem<String>(f.getName());
                rootItem.getChildren().add(element);
            }

        }
    });
}

}

ERROR
javafx.fxml.LoadException:
/D:/DAM2/Projects/EclipseOxygen/ClientFTPSMTP/bin/FXML/FTPView.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at interfaz.controller.MainController.openFTPUI(MainController.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.Trampoline.invoke(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
    at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at interfaz.controller.FTPController.initialize(FTPController.java:103)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
    ... 49 more


text:
Q: Convergence of $n^{-\gamma}T$ where $T$ a hitting time for uniform rvs, can I use CLT? Let $X_1,X_2,\dots$ be iid uniform on $\{1,\dots,n\}$ and define $T=\inf\{k:X_k=X_r \text{ for some }r<k\}$.
The objective is to figure out when $n^{-\gamma} T$ converges weakly to some non-degenerate distribution. So $\gamma$ is a parameter that can be chosen?
My work: $P(T=k)=\frac{n-1}{n}\times \cdots \times \frac{n-(k-2)}{n} \times \frac{k-1}{n}$ so then I constructed the characteristic function. The question then reduces to the following.
As $n\rightarrow \infty$, what happens to
$$\sum_{k=2}^{n+1} \left( \prod_{j=1}^{k-2}\frac{n-j}{n} \right)\frac{k-1}{n} e^{it\frac{k}{n^\gamma}}.$$
Just plugging this into wolfram, it looks complicated. Should I recognize this, or did I do something incorrectly?
Edit: Is this actually a simple application of CLT? For any $n$, the mean and variance are finite, so this converges to some kind of normal?

A: It is not hard to make the following argument rigorous.
$$\mathbb{P}(T>k)=\prod_{j=1}^{k-2} \left(1-{j\over n}\right)
\approx \prod_{j=1}^{k-2} e^{-j/n}
\approx e^{-k^2/2n}.\tag1$$
For any $t>0$ set $k=\lfloor \sqrt{n} t\rfloor$ and plug this into
(1)  to show that
$$\mathbb{P}(T/\sqrt{n}>t)\to e^{-t^2/2}.$$
Thus $T/\sqrt{n}$ converges in distribution to the probability
measure with density  $t\,e^{-t^2/2}$ on $(0,\infty)$.


text:
Q: PHP causing server error 500 Does anyone have a clue what it is about this bit of php code that would cause an apache2 webserver with nginx to throw a server error 500?
function cycleColsDbl() {
    static $cols = ['transparent;', '#efefef;'], $i = 0;
    $selectCol = ($i++/2 % 2 == 0) ? 0 : 1;
    return $cols['$selectCol'];
}

The server suexec.log spat out a rather nonsensical claim:
[2016-04-17 08:34:34]: uid: (10003/usr) gid: (1003/1003) cmd: cgi_wrapper

And error.log says nothing at all about this.
The 500 is thrown on page load so the function never actually gets called.
Ideas anyone?

A: This $cols['$selectCol']; will look for a key $selectCol, not 0 or 1. It would look for 0 or 1 if you didn't make it literal, i.e. remove the single quotes.
Also, static $cols = ['transparent;', '#efefef;'] is not correct syntax to create an array in PHP.
function cycleColsDbl() {
    static $cols = array('transparent;', '#efefef;'), $i = 0;
    $selectCol = ($i++/2 % 2 == 0) ? 0 : 1;
    return $cols[$selectCol];
}


text:
Q: How to delete Databricks feature tables through the Python API The documentation explains how to delete feature tables through the UI.
Is it possible to do the same using the Python FeatureStoreClient? I cannot find anything in the docs: https://docs.databricks.com/_static/documents/feature-store-python-api-reference-0-3-7.pdf
Use case: we use ephemeral dev environments for development and we have automated deletion of resources when the environment is torn down. Now we are considering using the feature store, but we don't know how to automate deletion.

A: You can delete a feature table using the Feature Store Python API.
It is described here:
http://docs.databricks.com.s3-website-us-west-1.amazonaws.com/applications/machine-learning/feature-store/feature-tables.html#delete-a-feature-table
Use drop_table to delete a feature table. When you delete a table with drop_table, the underlying Delta table is also dropped.
fs.drop_table(
  name='recommender_system.customer_features'
)

A: The answer above is correct, but note that the drop_table() function is experimental according to databricks documentation for the Feature Store Client API so it could be removed at any time. Besides that fs is also in reference to:
from databricks.feature_store import FeatureStoreClient
fs = FeatureStoreClient()

fs.drop_table(name='recommender_system.customer_features')


text:
Q: calculation precision during projection transformation I am using wgs 84 base tiles, and the tile is not rendered as image but with geojson format.
I try to draw them in the tile according to the data. And the geometry of the returned feature is lng and lat format.
This is the formula I used:
double tileNumWidth = 1 << (zoom+1);
double tileNumHeight = 1 << zoom ;
float px = (float) ((tileNumWidth * fromLngToX(x) - tileX) * 256);
float py = (float) ((tileNumHeight * fromLatToY(y) - tileY) * 256);

public static double fromLngToX(double lng) {
    return (lng + 180) / 360d;
}

public static double fromLatToY(double lat) {
    return (90 - lat) / 180d;
}

It worked as expected in a lower zoom level:
http://pbrd.co/1qBajKH
However once the map is zoomed to a higher level like 18+, then I will found that the lines cross two tile may be not conjugated:
http://pbrd.co/1qBaN3k
You may notice the obvious drift(not much, seems only 1 px).
So I wonder if this is caused by the precision of calculation?


text:
Q: Google place api calling issues Have facing some issues autocomplete Ap module.I have enable place api in play console.But after enabling also will getting error.Kindly check and help on this query
......
Issues :
Error while autocompleting: REQUEST_DENIED


text:
Q: xml-validator doesn't work I tried to check this document at xml validator into Firefox.
But this cheking was successful.
And I want to know why? Here is some mistake accordings DTD:
from CDATA   #FIXED "Kathy Shepherd"
and after this at note - from="someone else">
Maybe exist, some another way for validation xml document at browser.
Code:
<?xml version="1.0" ?>
<!DOCTYPE note      [
<!ELEMENT note      (message)>
<!ELEMENT message   (#PCDATA)>
<!ATTLIST message
         number CDATA #REQUIRED
         date CDATA   #REQUIRED
         from CDATA   #FIXED "Kathy Shepherd">
                    ]>
<note>
    <message number="10" date="041513" from="someone else">
        Remember to buy milk on the way home from work
    </message>
</note>

Question:

*

*How to make this XML-checking at correct way (maybe at some others
browsers)?

A: Web browsers don't implement validating XML parsers. They only care if a document is well-formed or not.
If you want to perform validation, use a validator such as the W3C Markup Validation Service.


text:
Q: Select row by regex match in Idiorm and Paris I'm looking for following SQL equivalent in Idiorm and Paris:
SELECT * FROM table WHERE (regex=0 AND col=_match_) OR (regex=1 AND _match_ REGEXP col)
LIMIT 1

Following Idiorm & Paris statements only matches col=_match_:
Idiorm:
$row = ORM::for_table('table')
->where_equal('col', '_match_')
->find_one()

Paris:
MyModel::where('col', '_match_')->find_one()

A: The sentence where_any is the solution for that
Example:
$myModel = ORM::for_table('table')
        ->where_any_is(array(
            array('regex'=> 0,'col' => 'match'),
            array('regex'=> 1,'col' => '_match_')))
        ->limit(1)->find_many();

See the docs oficial for filtering query: https://idiorm.readthedocs.org/en/latest/querying.html#filtering-results

A: After reading docs and codes, it seems that Idiorm/Paris doesn't support that functionality. So, we have two options:

*

*Using where_raw() method, which by this way we will pass where clause as a string directly to Idiorm.

*Adding a new method like where_condition() to Idiorm ORM class which matches $value against $column_name by setting $reverse = true, otherwise, it's a normal where condition (that matches $column_name against $value).
public function where_condition($column_name, $operator, $value, $reverse = false)
{
$multiple = is_array($column_name) ? $column_name : array($column_name => $value);
$result = $this;

foreach($multiple as $key => $val) {
    // Add the table name in case of ambiguous columns
    if (count($result->_join_sources) > 0 && strpos($key, '.') === false) {
        $table = $result->_table_name;
        if (!is_null($result->_table_alias)) {
            $table = $result->_table_alias;
        }

        $key = "{$table}.{$key}";
    }
    $key = $result->_quote_identifier($key);

    if($reverse)
        $result = $result->_add_condition('where', "? {$operator} {$key}", $val);
    else
       $result = $result->_add_condition('where', "{$key} {$operator} ?", $val);
}
return $result;

}


text:
Q: What does this mean: "document.write('I've seen this on every Yahoo! news page, at the bottom of the source code,
and failed to understand why they break the script word like that.
Does anybody know if there's any reason for this?
document.write("<scr"+"ipt language=javascript src=http://l.yimg.com/d/lib/bc/bc_2.0.4.js></scr"+"ipt>");

A: Consider this simplified example:
<script>
document.write("something </script> something");
</script>

The browser's HTML parser would see the </script> within the JavaScript string and interpret that as the end of the script element.
The HTML parser doesn't know about JavaScript syntax - all it knows is that the <script> element ends at the next </script>.
(It also knows that you can't have nested <script> elements, hence the breaking of the opening <script> as well as the closing </script> in your example.)

A: Suppose you are writing a tool that detects the beginning and end of script blocks in a chunk of text. Suppose you see
<blah><blahdeblah><script>

blah blah blah

blah

print("</script>")

print("<script>")

blah

</script>

</blahdeblah></blah>

Without knowing the syntax of the script language, how does your tool know that this is ONE script block and not TWO script blocks with ")blah between them?
A web browser is such a tool. It's a reasonable practice to make sure you never confuse the web browser by never having <script> or </script> in your file unless it actually is a script tag.

A: so that it doesn't get evaluated but gets inserted as a string.

A: It's a bad way to prevent XML/XHTML and HTML validators from yelling at the source code.

A: Some browsers tend to "act" to fast when parsing a document and immediately try to execute the javascript when they find a script tag (even though it is itself in a piece of js). To avoid this they break the decalration of the tag.

A: For a full discussion of this, see:
   http://www.wwco.com/~wls/blog/2007/04/25/using-script-in-a-javascript-literal/
The short answer is that your code is parsed in two discrete steps.
The first one is XML. And that means that the element <SCRIPT> is looking for a </SCRIPT>. It's important to remember that XML elements are content agnostic. That means that the parser doesn't know yet that there's JavaScript in there.
Once it has the contents of the <SCRIPT> element, then it processes that chunk of text, which presumably is JavaScript.
By splitting up the tag with a string concatenate operator you prevent a constant from tripping up the XML phase.
One simple solution is to put < and > in the Javascript text.


text:
Q: Zebra Stripping with phpspreadsheet I was looking around for examples and/or guides on how to use phpspreadsheet's conditional formatting. Specifically looking so that I could zebra stripe my spreadsheet in a way that allows for resorting of the sheet. I came up very empty with only a few spotty SO questions using the old PHPExcel library and just one example from the documentation. Given that zebra stripes are pretty common style to apply I was mildly outraged that I couldn't find a copy/paste job. So I figured it out myself and now will leave it here for posterity and hopefully myself in a few years.
I am actually going to spell out a lot more as I have used phpspreadsheet for a few years now and out of the box the defaults don't really give you a nice looking spreadsheet. I will also note I do not care how it looks; its just data to me but, my bosses must have quality formatting.

A: Zebra Stripping
$range = 'A3:'.$spreadsheet->getActiveSheet()->getHighestDataColumn.
               $spreadsheet->getActiveSheet()->getHighestDataRow();
$conditional1 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
$conditional1->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_EXPRESSION)
              ->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_EQUAL)
              ->addCondition('MOD(ROW(),2)=0');
$conditional1->getStyle()->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
             ->getStartColor()->setARGB('DFDFDF');
$conditional1->getStyle()->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
             ->getEndColor()->setARGB('DFDFDF');
$spreadsheet->getActiveSheet()->getStyle($range)->setConditionalStyles([$conditional1]);

The range starts at A3 because I have a logo in row 1 and headers in row 2. Also you can apply as many conditions as you need which is why the final setConditionalStyles is wrapped in an array.
Freeze 1 columns and  2 rows
$sheet->freezePane('B2');

This will freeze that cell B2 and everything to the left and above. Super helpful for long and wide sheets letting you keep your primary_key and headers in view at all times.
Insert Logo in 1st cell
$spreadsheet->getActiveSheet()->insertNewRowBefore(1, 1);
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setCoordinates('A1');
$drawing->getShadow()->setVisible(true);
$drawing->setName({{alt text}});
$drawing->setPath(resource_path().{{filepath}});
$drawing->setWorksheet($spreadsheet->getActiveSheet());
$spreadsheet->getActiveSheet()->getRowDimension('1')->setRowHeight(55);

Hiding a sheet
$spreadsheet->getActiveSheet()->setSheetState('veryHidden');

This is one thing I really like to do as I have written some automation that relies on a user making
edits to a spreadsheet and returning the sheet to a specific email address that I can access via api and download and reprocess based on the edits to the sheet. I use this mainly for storing information our erp needs to access records such as a customer_id or contract_number so that when the sheet comes back I don't have to re-query ident info I can just grab it from the hidden sheet. Bonus of using very hidden is a normal user can't unhide it unless they know enough to open the dev window and get in VB script.
Put Filters on all headers
$dimensions = 'A2' . ':' . $spreadsheet->getActiveSheet()->getHighestDataColumn() .
                           $spreadsheet->getActiveSheet()->getHighestDataRow();
$spreadsheet->getActiveSheet()->setAutoFilter($dimensions);
$autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter();
$autoFilter->showHideRows();

The trick on this one is the last line it won't actually apply the filters until there is some kind of action so I just grabbed a random function that wouldn't have any effect on my sheet.
Auto Width Columns
$colNumber = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString(
             $spreadsheet->getActiveSheet()->getHighestDataColumn);
for ($col = 1; $col <= $colNumber; $col++) {
    $colAlpha = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col);
    $spreadsheet->getActiveSheet()->getColumnDimension($colAlpha)->setAutoSize(true);
}
$sheet->calculateColumnWidths();

Making Spreadsheets with multiple tabs
First let me note I have come up with a somewhat standard structure I use whenever I make a spreadsheet and then I feed it through one function that does all of the above things. So here is my standard.
$report = json_encode([
        'filepath' => 'Program Size/',
        'filename' => $customer_name->company_name.' Program Size '.Carbon::parse('now')->format('Ymd').'.xlsx',
        'Type' => 'buildMultiSheet',
        '1' => [
            'request' => [
                'TabName' => 'Program Size',
                'header' => array_keys($source[0]),
                'body' => $source,
                'formatArray'=> [
                    'aboveHeader'=>['Total Value:',$sum],
                    'zebra' => 'stripe',
                    'F:G' => '"$"#,##0.00_-'
                ]
            ]
        ],
        '2' => [
            'request' => [
                'TabName' => 'config_sheet',
                'header' => [],
                'body' => $queryLog,
                'formatArray'=> [
                    'hidden'=> 1
                ]
            ]
        ]
    ]);

This structure has every thing you need to make a spreadsheet with multiple tabs. Source for me is generally the result of a DB call. This isn't complete detail for example a tabname longer than 31 characters will freak out so you have to check for it. One of these days I might tidy things up and publish a package to go along side phpspreadsheet but, we  will see if/when that ever happens.
$spreadsheet = new Spreadsheet();
$filename = $requestD["filename"];
unset($requestD["filename"]);
$filepath = $requestD["filepath"];
unset($requestD["filepath"]);
$tabCounter = 0;
$spreadsheet->setActiveSheetIndex($tabCounter);

foreach ($requestD as $tab) {
    $sheet = $spreadsheet->getActiveSheet();
    $body = $tab["request"]["body"];
    $spreadsheet->getActiveSheet()->setTitle($tab["request"]["TabName"]);
    $headers = $tab["request"]["header"];
    $sheet->fromArray($headers, NULL, 'A1');
    $sheet->fromArray($body, NULL, 'A2', false);

    //processing here, sheet formatting , etc.

    $tabCounter++;
    $spreadsheet->createSheet();
    $spreadsheet->setActiveSheetIndex($tabCounter);
}

//remove last empty sheet before resetting index
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->removeSheetByIndex($tabCounter);

Well that's all the tips I have. If I have done anything really dumb please do let me know how I can improve.


text:
Q: Laravel InertiaJS SSR: Cannot find module laravel-vite-plugin/inertia-helpers.js I have installed the newest version of Laravel as of this writing with Sail. I use Inertia for the front end. I followed the guide and installed the necessary dependencies. Running npm run dev and npm run build works fine. However, when I run npm run ssr I encountered the follwing error:
Cannot find module '/var/www/html/node_modules/laravel-vite-plugin/inertia-helpers.js' imported from /var/www/html/bootstrap/ssr/ssr.mjs

package.json
{
    "private": true,
    "scripts": {
        "dev": "vite",
        "build": "vite build && vite build --ssr",
        "ssr": "node bootstrap/ssr/ssr.mjs"
    },
    "devDependencies": {
        "@inertiajs/inertia": "^0.11.0",
        "@inertiajs/inertia-vue3": "^0.6.0",
        "@inertiajs/progress": "^0.2.7",
        "@inertiajs/server": "^0.1.0",
        "@vitejs/plugin-vue": "^3.0.1",
        "@vue/server-renderer": "^3.2.37",
        "autoprefixer": "^10.4.7",
        "axios": "^0.27",
        "laravel-vite-plugin": "^0.5.0",
        "lodash": "^4.17.19",
        "postcss": "^8.4.14",
        "tailwindcss": "^3.1.6",
        "vite": "^3.0.0",
        "vue": "^3.2.37"
    }
}

resources/js/ssr.js
import { createInertiaApp } from '@inertiajs/inertia-vue3';
import createServer from '@inertiajs/server';
import { renderToString } from '@vue/server-renderer';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { createSSRApp, h } from 'vue';

createServer(page =>
  createInertiaApp({
    page,
    render: renderToString,
    resolve: name => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
    setup({ app, props, plugin }) {
      return createSSRApp({ render: () => h(app, props) }).use(plugin);
    },
  })
);

vite.config.js
import vue from '@vitejs/plugin-vue';
import laravel from 'laravel-vite-plugin';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    laravel({
      input: 'resources/js/app.js',
      refresh: true,
      ssr: 'resources/js/ssr.js',
    }),
    vue({
      template: {
        transformAssetUrls: {
          base: null,
          includeAbsolute: false,
        },
      },
    }),
  ],
  resolve: {
    alias: {
      '@': '/resources/js',
    },
  },
  ssr: {
    noExternal: ['@inertiajs/server'],
  },
});

I will really appreciate someone can point me to the right direction. I did try to resolve it on my own but no luck. I can't find any solution either in the documentation.

A: You should modify "ssr": "node bootstrap/ssr/ssr.mjs" to the correct path to ssr.js bundle like  "ssr": "node storage/ssr/ssr.js"


text:
Q: How to sort an UltraGrid by multiple columns programmatically? Say we have an UltraGrid.
How can I sort it programmatically first by column A, then B, then C.
Thanks!

A: Documentation here:
http://help.infragistics.com/Help/Doc/WinForms/2011.2/CLR2.0/html/Infragistics2.Win.UltraWinGrid.v11.2~Infragistics.Win.UltraWinGrid.UltraGridBand~SortedColumns.html
You can just set the sort indicator (order is important), code taken from above link:
UltraGridBand band = this.ultraGrid1.DisplayLayout.Bands[0];

// Sort the rows by Country and City fields. Notice the order in which these columns
// are set. We want to sort by Country and then sort by City and in order to do that
// we have to set the SortIndicator property in the right order.
band.Columns["Country"].SortIndicator = SortIndicator.Ascending;
band.Columns["City"].SortIndicator    = SortIndicator.Ascending;

// You can also sort (as well as group rows by) columns by using SortedColumns
// property off the band.
band.SortedColumns.Add( "ContactName", false, false );

More information on the second method can be found here:
http://help.infragistics.com/Help/NetAdvantage/NET/2008.2/CLR2.0/html/Infragistics2.Win.UltraWinGrid.v8.2~Infragistics.Win.UltraWinGrid.SortedColumnsCollection~Add.html

A: If you also wanted to automatically group by ContactName this may do it for you:
band.SortedColumns.Add( "ContactName", false, true);

Notice usage of    true        as the last parameter


text:
Q: Foreach loop with additional behavior for one specific iteration I'm iterating over a list with a foreach loop and I want to do some additional stuff to exactly one of the x that I iterate over (specifically cryoTemp in the code below). I could add this  functionality with a simple if statement in the body of the loop, but it sets off a subconscious "bad code" alarm in my head, as the if statement will be evaluated on every iteration, even though it will only evaluate to true once. Is there a smarter, perhaps more "Pythonic" way to do this?
for p in self.params:
    < get parameter p from server >
    < parse response >
    log_in_redis_and_mysql(p, value)

    # log cooling rate based on cryoTemp value
    if p == 'cryoTemp':
        self.pastCryoTemps.append(value)
        # calculate average of queue when it fills up then remove the oldest (first) element
        if (len(self.pastCryoTemps) == 4):
            differences = []
            for i in range(len(self.pastCryoTemps) - 1):
                differences.append(-(self.pastCryoTemps[i] - self.pastCryoTemps[i + 1]))
            average = sum(differences) / len(differences)
            log_in_redis_and_mysql('cooling_rate', average)
            self.pastCryoTemps.pop(0)

A: If you know which index has the special-cased behavior, you can do:
for i, x in enumerate(y):
    if i == known_index:
        g(x)
    else:
        f(x)

If you don't, then there's nothing wrong with simply checking each x against a predicate.


text:
Q: How To Count Shuffle permutations Let $n\in \mathbb{N}$ and $S(n)$ the permutation group on $\{1,\ldots,n\}$.
For any $p,q\in \mathbb{N}$ with $p+q=n$, the set $Sh(p,q)\subset S(n)$ is
the set of all permutations $\tau$ such that $\tau(1)< \cdots \tau(p)$ and
$\tau(p+1)<\cdots <\tau(n)$, usually called the set of $(p,q)$-shuffles.
More generally for any $k;p_1,\ldots,p_k\in\mathbb{N}$ with $p_1+\cdots +p_k=n$,
the set of $(p_1,\ldots,p_k)$-shuffles $Sh(p_1,\ldots,p_k)\subset S(n)$ is
the set of all permutations $\tau$, such that $\tau(1)< \cdots \tau(p_1)$,
$\tau(p_1+1)<\cdots <\tau(p_2)$ (up to) $\tau(n-p_k+1)<\cdots <\tau(n)$.
====
Now the question is: HowTo calculate the cardinality $|Sh(p_1,\ldots,p_k)|$?
I know that $|Sh(p,q)|=\binom{p+q}{q}$ but just as a fact. From empirical
tests I would 'guess' $|Sh(p_1,\ldots,p_k)|=\binom{n}{p1,\ldots,p_k}$, where
the expression on the left means the multinomial coefficient, but I'm more interested in deriving such an appropriate expression.

A: Choose $p$ numbers from the set $1..n$ and there is a unique shuffle such that $\tau(1)..\tau(p)$ to have those $p$ values and the other $q$ fill in the remaining places. The multinomial coefficinet $n\choose p_1...p_k$ is the number of ways to partition $1..n$ into subsets of cardinality $p_i$, and each subset can again be ordered each such partition is a unique shuffle.


text:
Q: what is worth vimxfer So I readed someones vimrc file (or at least I think it is) with maps like this:
nmap <leader>r :r $HOME/.vimxfer<cr>
nmap <leader>w :'a<leader>.w! $HOME/.vimxfer<cr>

what is this vimxfer file? for what is worth? I haven't found any info about it

A: .vimxfer is just the name of a file in that person's home directory. It looks like they're using it as some sort of staging area for transferring text from one place to another.