text:
Q: Why does this code run slow in firefox? So I wrote this code for a simple game. The code runs at 60 fps in both Chrome and Safari but Firefox barely manages 30-40 fps. The code looks simple enough to me. What could be causing the delay?
I checked in firebug and found out that only one function "follow" is taking up all the time. Here is the code:
function checkCollision (ball0, ball1) {
    var dx = ball1.X - ball0.X,
        dy = ball1.Y - ball0.Y,
        dist = Math.sqrt(dx * dx + dy * dy);

    if (dist < ball0.rad + ball1.rad) {
      var angle = Math.atan2(dy, dx),
          sin = Math.sin(angle),
          cos = Math.cos(angle);

          var pos0 = {x: 0, y: 0},
          pos1 = rotate(dx, dy, sin, cos, true),
          vel0 = rotate(ball0.spdX, ball0.spdY, sin, cos, true),
          vel1 = rotate(ball1.spdX, ball1.spdY, sin, cos, true),
          vxTotal = vel0.x - vel1.x;
      vel0.x = ((ball0.mass - ball1.mass) * vel0.x + 2 * ball1.mass * vel1.x) /
               (ball0.mass + ball1.mass);
      vel1.x = vxTotal + vel0.x;
      var absV = Math.abs(vel0.x) + Math.abs(vel1.x),
          overlap = (ball0.rad + ball1.rad) - Math.abs(pos0.x - pos1.x);
      pos0.x += vel0.x / absV * overlap;
      pos1.x += vel1.x / absV * overlap;
      //rotate positions back
      var pos0F = rotate(pos0.x, pos0.y, sin, cos, false),
          pos1F = rotate(pos1.x, pos1.y, sin, cos, false);
      ball1.X = ball0.X + pos1F.x;
      ball1.Y = ball0.Y + pos1F.y;
      ball0.X = ball0.X + pos0F.x;
      ball0.Y = ball0.Y + pos0F.y;
      var vel0F = rotate(vel0.x, vel0.y, sin, cos, false),
          vel1F = rotate(vel1.x, vel1.y, sin, cos, false);
      ball0.spdX = vel0F.x;
      ball0.spdY = vel0F.y;
      ball1.spdX = vel1F.x;
      ball1.spdY = vel1F.y;
    }
}

function move()
{
    var side,i;
    for (i=0 ; i < balls.length; i++)
    {
        var obj = balls[i];
        if (side=obj.edgeX())
        {
            if (side === 'l')
                obj.X = obj.rad;
            else if (side === 'r')
                obj.X = canvas.width() - obj.rad;
            obj.spdX*=-1;
        }
        if (side=obj.edgeY())
        {
            if (side === 't')
                obj.Y = obj.rad;
            else if (side === 'b')
                obj.Y = canvas.height() - obj.rad;
            obj.spdY*=-1;
        }

        if (leash == true && i === 0)
        {
            if (mouse.X>obj.X && (obj.spdX<10))
                obj.spdX+=obj.accX;
            else if (mouse.X<obj.X && (obj.spdX>-10))
                obj.spdX-=obj.accX;
            if (mouse.Y>obj.Y && (obj.spdY<10))
                obj.spdY+=obj.accY;
            else if (mouse.Y<obj.Y && (obj.spdY>-10))
                obj.spdY-=obj.accY;
        }

        obj.X+=obj.spdX;
        obj.Y+=obj.spdY;
        if (Math.abs(obj.spdX)>0.1)
            obj.spdX*=0.98;
        else obj.spdX=0;
        if (Math.abs(obj.spdY)>0.1)
            obj.spdY*=0.98;
        else obj.spdY = 0;
    };
}

function follow()
{
    var ballA, i, ballB,j;
    requestAnimationFrame(follow);
    //stats.begin();
    context.clearRect(0,0,canvas.width(),canvas.height());

    move();
    for (i = 0, len = balls.length - 1; i < len; i++) {
          ballA = balls[i];
          for (j = i + 1; j < balls.length; j++) {
            ballB = balls[j];
            checkCollision(ballA, ballB);
          }
     }
    balls.forEach(function(obj){
        drawCircle(obj.X,obj.Y,obj.rad, obj.color);
        if (leash == true && obj.control === true)
        {drawLeash(mouse.X,mouse.Y,obj.X,obj.Y,obj.color);}
    });
    //stats.end();
};

Here is the animation: http://ipsumturpis.xtreemhost.com/follower/index.html

A: I vaguely remembered there used to be a problem in FF regarding with canvas drawing performance, so I have commented out drawCircle(obj.X,obj.Y,obj.rad, obj.color); and poof, magic happened - my frame rate went up from 11 FPS to 60.

A: Try caching balls length in a variable.  Unless it's absolutely necessary for reasons I don't see, running balls.length (or any function) in every iteration of a loop is naturally going to be time consuming.
So try something like this;
ballslen = balls.length;
for (j = i + 1; j < ballslen; j++)


text:
Q: Passing value to a php file via jQuery Let's say that I have two links.

Name 1

Name 2

And when I click one of these links jQuery passes the ID of the link I clicked to a PHP file without reloading the page.
Due to the fact that the id's will not be constants I assume this.id will need to be used in the jQuery.
Then in the PHP file the id is put into a variable then sent to the database. Such as,
$var = JQUERY?

insert db...

I am just stumped on how to create the jQuery needed to send the ID to the PHP file. And then to retrieve that non-constant ID using PHP.
How might I got about doing this?

A: $("[href=#]").click(function(){

var id = parseInt($(this).attr("id"));

// ur logic to send id to the db here...

})

A: jQuery provides several ways to send content to the server via Ajax. The one you should look into is the $.post method.
The method below will send the id the anchor tag to the server and then alert the servers response. Just make sure that your-file.php is sending a response. Usually I just put something like echo 'Hi, I like waffles.'; in my php.
jQuery(function(){
   jQuery('.charName').bind("click", function(){
      jQuery.post("your-file.php", { id: this.id }, function(response){

         alert(response);
      })
   })
});

I like to refer to http://visual.jquery.com whenever I need jQuery help. It's a nice little site.

A: you have to implement some ajax to achieve the same , lets have a click handler for a href first.
And then make a ajax call
$('.charName').click(function() {
   var idval = this.id ;

   $.ajax({
   type: "POST",
   url: "some.php",
   data: "id=idval  &location=Boston",
   success: function(msg){
     alert(msg ); // this is the response
   }
 });
 return false// this is diable ahref post back to the same page itself
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: upgrade not allowed with locked packages? I've got 2 packages with the version locked because the new ones are not compatible with other programs I use.  This prevents the Ubuntu distribution upgrade from even trying to do its work. Observe:
$ sudo apt-get update
Hit:1 https://rweb.crmda.ku.edu/cran/bin/linux/ubuntu bionic-cran35/ InRelease
Hit:2 http://archive.canonical.com/ubuntu cosmic InRelease
Hit:3 http://us.archive.ubuntu.com/ubuntu cosmic InRelease
Hit:4 https://packages.microsoft.com/repos/vscode stable InRelease
Hit:5 http://us.archive.ubuntu.com/ubuntu cosmic-backports InRelease
Hit:6 http://us.archive.ubuntu.com/ubuntu cosmic-updates InRelease
Hit:7 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu cosmic InRelease
Hit:8 http://security.ubuntu.com/ubuntu cosmic-security InRelease
Hit:9 http://ppa.launchpad.net/unit193/encryption/ubuntu cosmic InRelease
Reading package lists... Done

$ sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages have been kept back:
  git-lfs thunderbird
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.

$ sudo do-release-upgrade
Checking for a new Ubuntu release
Please install all available updates for your release before upgrading.

The only workaround I can see is to allow the updates to happen with git-lfs and thunderbird, then do the upgrade, and then install the old versions of those programs.  Seems more tedious than it should be.
Other ideas?


text:
Q: graphviz how to draw a vertical tree like file managers do How do I render a vertical tree image like file manager do. By default graphviz is rendering a triangular tree. The problem is if the width of a level (rank) is too many, the produced image is too wide. Typically file manager applications model a directory hierarchy on the vertical axioms.
specific example, given a family tree with 5 brothers, each having 5 kids, would require rendering of 25 nodes ... which becomes too wide.
Here is  an example image

Update: ... thanks everyone, I have managed to make some progress. But I am seeing some weird edges as marked on the picture below. It looks good at the first couple of tiers, then it gets bad.


text:
Q: how to use batch file variable outside inner for loop I am not familiar with batch script variable scoping. But I ran into scoping problem due to my lack of batch script experience.
for /f %%i in ('dir /s /b "%FolderLocation%"') do (
set fullpathandfilename=%%i ::
For %%A in ("%fullpathandfilename%") do (
Set File=%%~nxA
echo %%File :: this would work and print out only filename
)
echo %File% ::this will not have filename I extracted above
)

So how can i use %%File outside my inner for loop

A: Again, EnableDelayedExpansion:
setlocal enabledelayedexpansion

for /f %%i in ('dir /s /b "%FolderLocation%"') do (
For %%A in ("%%~i") do (
Set File=%%~nxA
echo !File!
)
:: This shows how "%" doesn't work but "!" does
Echo ^%File^%: %File%   -   ^!File^!: !File!
)

And that should work for you. Just remember to use !File! inside a for-loop and %File% outside.


text:
Q: PHP Keeps Inserting on Refresh I am currently working on registration for my app until I came upon this problem that whenever I go on to my page, it would create a new row in my users table. It seems that when I reload the page, the form would automatically submit. I had referred to this question:

Use header("location: "); after you are done inserting, that way a fresh form will be displayed and refreshing should not lead to submitting again.

However, all that happened when I did that was a big redirect loop, preventing me from accessing the page all together.
Here is my code for my registration:
<?php

    global $conn;
    global $register;
    global $error;

    $username = $_POST['username'];
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $password = $_POST['password'];
    $confirmPassword = $_POST['confirmPassword'];

    define(HEADER_TITLE, "Register");
    include_once 'template/header.php';

    if (isset($_POST['register'])) {
        $register->register($username, $firstName, $lastName, $email, $phone, $password, $confirmPassword);
    }

?>

Register

            <?php
            if ($error->display() != null ) {
                #echo '
';
                $error->display();
            } else {
                #echo '
';
            }
        ?>

        <form action="register" method="post">
            <input type="text" class="form-control" name="firstName" placeholder="First Name" value="<?php echo $_GET['firstName']; ?>">

            <input type="text" class="form-control" name="lastName" placeholder="Last Name" value="<?php echo $_GET['lastName']; ?>">

            <input type="text" class="form-control" name="username" placeholder="Username" value="<?php echo $_GET['username']; ?>">

            <input type="email" class="form-control" name="email" placeholder="E-Mail Address" value="<?php echo $_GET['email']; ?>">

            <input type="tel" class="form-control" name="phone" placeholder="Phone Number" value="<?php echo $_GET['phone']; ?>">

            <input type="password" class="form-control" name="password" placeholder="Password">

            <input type="password" class="form-control" name="confirmPassword" placeholder="Confirm Password">

            <input type="submit" class="btn btn-info btn-lg" name="register" value="Register!">

            Have an account? Login!
        </form>

<?php include_once 'template/footer.php'; ?>

My register.class.php:
<?php

/**
* User Registration
*/
class register {

public function register($reg_username = '', $reg_firstName = '', $reg_lastName = '', $reg_email = '', $reg_phone = '', $reg_password = '', $reg_confirmPassword = '') {

    global $conn;
    global $error;

    // TO PREVENT AN UNDEFINED INDEX
    // First Name
    if(isset($reg_firstName)) {
        $reg_firstName = stripslashes(htmlspecialchars($conn->real_escape_string($reg_firstName)));
    } else {
        $error->set('312');
    }

    // Last Name
    if(isset($reg_lastName)) {
        $reg_lastName = stripslashes(htmlspecialchars($conn->real_escape_string($reg_lastName)));
    } else {
        $error->set('313');
    }

    // Username
    if(isset($reg_username)) {
        $reg_username = stripslashes(preg_replace('/\s+/', '', htmlspecialchars($conn->real_escape_string($reg_username))));
    } else {
        $error->set('311');
    }

    // Email
    if(isset($reg_email)) {
        $reg_email = stripslashes(preg_replace('/\s+/', '', htmlspecialchars($conn->real_escape_string($reg_email))));
    } else {
        $error->set('314');
    }

    // Phone
    if(isset($reg_phone)) {
        $reg_phone = stripslashes(preg_replace("/[^0-9]/", "", htmlspecialchars($conn->real_escape_string($reg_phone))));
    } else {
        $error->set('315');
    }

    // Password
    if(isset($reg_password)) {
        $reg_password = stripslashes(htmlspecialchars($conn->real_escape_string($reg_password)));
    } else {
        $error->set('316');
    }

    // Password
    if(isset($reg_confirmPassword)) {
        $reg_password = stripslashes(htmlspecialchars($conn->real_escape_string($reg_confirmPassword)));
    } else {
        $error->set('317');
    }

    // Check if username exists in the database
    $stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
    $stmt->bind_param('s', $reg_username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows == 0) {

        $stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
        $stmt->bind_param('s', $reg_email);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows == 0) {

            $stmt = $conn->prepare("SELECT * FROM users WHERE phone=?");
            $stmt->bind_param('s', $reg_phone);
            $stmt->execute();
            $stmt->store_result();

            if ($stmt->num_rows == 0) {

                // Do passwords match?
                if ($reg_password == $reg_confirmPassword) {

                    $reg_passwordEncrypt = hash("sha256", $reg_password);

                    // Insert data
                    $stmt = $conn->prepare("INSERT INTO users (username, firstName, lastName, email, phone, password, company, website, bio) VALUES (?, ?, ?, ?, ?, ?, '', '', '')");
                    $stmt->bind_param("ssssss", $reg_username, $reg_firstName, $reg_lastName, $reg_email, $reg_phone, $reg_passwordEncrypt);
                    $stmt->execute();
                    header("Location: /login");

                } else {
                    // Set Error
                    $error->set('308');
                }

            } else {
                // Set Error
                $error->set('306');
            }

        } else {
            // Set Error
            $error->set('304');
        }
    } else {
        // Set Error
        $error->set('301');

    }

}

}

$register = new register;

Thanks!

A: It is because you have same name for method as class name. It is working as PHP 4 constructor and it is calling the method when initializing the object.
https://wiki.php.net/rfc/remove_php4_constructors


text:
Q: What if I migrate an AWS standalone account to Organizations? At work, we have an AWS standalone account which have been created some time ago by the IT Department and inside we have some users created. Now we want to move to AWS Organizations because the consolidated billing and the possibility of apply ACL across multiple users.
My question is: What happen with the already running services that have been created via the standalone account (e.g, API Gateways, Lambda functions, S3 buckets and EC2 instances) when we switch to Organizations format?
The answer to this question change if we create a new account and then invite our already old account to the new organization?

A: AWS Organizations is just an account management tool- it doesn't affect the resources within an account. So, to answer your question: your resources will stay as they are after you switch to Organizations.

A:
My question is: What happen with the already running services that
have been created via the standalone account (e.g, API Gateways,
Lambda functions, S3 buckets and EC2 instances) when we switch to
Organizations format?

There won't be any impact for the existing services under your account unless you enable Service Control Policies and attach a restrictive policy to the AWS account, where existing users won't be able to perform restricted actions (By default, Service Control Policies are Disabled in Organizations). Only noticeable thing is, the billing will be consolidated to the root account. You can even detach the account from the organization, later if needed.

The answer to this question change if we create a new account and then
invite our already old account to the new organization?

There is a difference when creating a new account under the organization vs inviting an already existing account to become a part of an organization. The main difference is, when you create a new account under the organization, the account cannot be detached from the organization later on.

Tutorial: You can find a complete guide by referring to the AWS Organizations Hands-on! video tutorial.


text:
Q: How to insert a point into PostGIS from PHP? For the following line, I received an error in my PHP page, but the query is OK when I run it from pgmyadmin.
I am trying to insert a point into my PostGIS from PHP which contains name, address and a geometric point. Here, p_id is primary key and it is an integer.
$sql = "INSERT INTO app (p_id, p_fname, p_lname, p_saddr, p_caddr, the_geom) VALUES(intval($p_id), $fname, $lname, $street, $city, ST_GeomFromText(POINT($long $lat), 4326))";
$result = pg_query($dbh, $sql);

Error:
Warning: pg_query() [function.pg-query]: Query failed: ERROR: syntax error at or near "," LINE 1: ...me, p_saddr, p_caddr, the_geom) VALUES(intval(5), , , , , ST... ^ in /Applications/XAMPP/xamppfiles/htdocs/HostMobileApp/requestProcessor.php on line 66
Error in SQL query: ERROR: syntax error at or near "," LINE 1: ...me, p_saddr, p_caddr, the_geom) VALUES(intval(5), , , , , ST... ^

A: This a really a duplicate of your previous question, and my answer is the same. Don't mix SQL and WKT! Use ST_MakePoint if you need to embed parameters into an SQL statement.
$sql = 'INSERT INTO app(p_id, p_fname, p_lname, p_saddr, p_caddr, the_geom) '
 . 'VALUES(intval($p_id), $fname, $lname, $street, $city, ST_SetSRID(ST_MakePoint($long, $lat), 4326))';
$result = pg_query($dbh, $sql);

A: It looks like you are having a problem with quotes when referring to your column names.  Here is the documentation for an Insert Query from the PostgreSQL website:  Documentation: Manuals: Insert
The gist is that when you are stating an Insert Into clause, where you name the column names, you do not put these in quotes.  You only put the values you are inserting in single quotes, or in your case, you use the variables so no quotes are necessary.
I think your structure should look like this:
$sql = "INSERT INTO app (p_id, p_fname, p_lname, p_saddr, p_caddr, the_geom)
     VALUES(intval($p_id), $fname, $lname, $street, $city, ST_GeomFromText(POINT($long $lat), 4326))";

$result = pg_query($dbh, $sql);


text:
Q: How To Calculate Columns Selectively in MS Access I am creating a Travel Expense Report using Microsoft Access 2007. I am new in creating this. I already created tables and forms in MS Access. I have a meal, transportation, and other allowances in my table. The user of the application will enter his/her expenses for the whole week in the table. I already figured out on how to get the total of each expenses in rows. My problem is how could I get the total of each allowances like the total of all meal, total of all transportation, and total of all other expenses for the entire week..

A: In the design view of your report add report header and footer sections if you don't already have them (this is on the arrange toolbar).
In the report footer add text boxes (report design toolbar) for each expenses total you wish to calculate.  Resize and align the text boxes so they line up with your expenses columns in the detail section.
Change the control source of each expenses total by typing directly into the text box
=sum([expensenamehere])

e.g.
=sum([Meal])

you'll need to change the format of each expenses total to Currency (text box properties).


text:
Q: Mediator Pattern in JavaScript Questions I'm creating a sort of library based on the mediator for my work. We create lots of applications so I wanted something that can easily be taken and modified on a per app basis. I also want it to be easy enough to create "widgets" (for lack of a better term) and easy to remove them without worrying about breaking anything. Many of these apps we make are also extendable by outside developers making apps or widgets for the apps.
That's how I came across the mediator pattern. I wrote up something that works something like this:
//Extend
Core.extend('widget',function(params){
  alert(params.message);
});

//Load it
Core.load('widget',{message:'Hello World'});

//Remove it
Core.remove('widget');

I have 3 questions tho:

*

*How do/should you deal with DOM manipulation in this pattern with JavaScript? I don't want developers messing with the DOM outside of their widget.

*How do/should you deal with AJAX requests. Should you do anything at all? Should you just offer a AJAX/JSONP call in the library (Core in this example).

*My biggest question, how do you actually interact with other widgets? I don't want to tight couple (obviously), but I don't get how you'd interact with another widget. For example, let's say you have a text box and on submit it sends it to a DB. How can another widget, lets call it the "timeline" widget, now when it was submitted and then update the timeline with the text from the text box widget?
===UPDATE===
I ended up writing this:
http://oscargodson.github.com/Core.js/

A: Widgets interacting with widgets:  I just finished building this a few days ago.  I looked through the way you've implemented it, and here are some additional ideas for you.
The push system you've built is very similar to jQuery's DOM event system, whereby arbitrary events can be emitted and received.  I've been using that system for a bit do develop de-coupled widgets however I've found it quite wanting because ultimately "pushes" (events, emits, whatever) are out of context -- as in listeners have no idea if this even is within the scope of what they wanted until they interrogate the event.
Consider for example if every UI element on a web page was a widget in your system.  There would easily be 30+ on one page.  If each one was to push a "loaded" message, the other 29 have to receive it.  Furthermore, as you mentioned, 3rd party developers will be developing for this system.  It then puts the burdens on them to filter out messages they don't want to receive.
The approach I've taken in my latest widget-communication system is what I call a "pubstring"/"substring" approach (and to be fair I'm sure someone else has come up with this idea before me and has some cool sounding name for it).  Basically, whenever a widget "pushes", that push is turned into a string which contains:  the realm (context), the widget's type, the widget's specific ID whatever it may be, and the specific message.
So say for example a widget with ID 45, type "tweet-list", in realm "custom" pushes a message "loaded".  The pub string would then render to:  custom.tweet-list.45.loaded.
When subscriptions are placed they are inputted via a hash table that can optionally contain values for the 4 attributes (you could easily add more besides the realm/type/id/msg I have).  Listening would then be like:
listen({ realm: 'custom', type: 'whatever' }, f);  // (where 'f' is a function)
The listener part of your framework could turn that hash table into a "substring" which would be a regular expression expressing the filters for which it represents:
custom\.whatever\.[^\.]+\.[^\.]+
That regex is stored as a compiled regular expression to some hidden array...
__subscriptions.push(new RegExp(subString));
Then whenever something was pushed (ie. published) the framework basically loops through the __subscriptions array, fires off a .test of each stored subString (regex) and executes the callback for that subString if matches.
Using this system unlimited filtered listeners can be applied and listeners know they're receiving notifications for only the contexts they are interested in.
Examples:
// Listen for all messages by widget ID #99
listen({ id: 99 } ,f);

// Listen for all messages by widgets in realm clientB
listen({ realm: 'clientB' }, f);

// Listen for the data-received push of widgets whose type is tweet-list
listen({ type: 'tweet-list', message: 'data-received' }, f);

Because the regex is really just a concatenation, regex can be included within the filter too.
// Listen for any data- message
listen({ message: 'data-[^\.]+' }, f);

The beauty of this system is that you could still keep your current interface to "keep thing simple" and just test for a string or a hash table for argument[0].  In other words..
// This
listen('loaded', f);

// Could be equivalent to this on the backend:
listen({ message: 'loaded' }, f);

I know that was long but hope it gave you some ideas.


text:
Q: Native Android browser not showing div at jquery.mobile On the Chrome browser, I get everything working, but, if I want to make it work at the native Android Browser, I can't see the div I want to show. Instead, it shows me the first span with the class leftscroller.
How could this be? I tried Android 4.1.2 and 4.1.3 browsers.
This is the JS code:
    $('.navigation-block').on('click', function(){
        $(this).parents('#navigation.small').toggleClass('open');
    });

    /* Scrollable */
    var showScrollIndicators = function() {
        var subnav = $('#navigation.small .subnav')
        if (subnav.length > 0) {
            var scrollLeft = subnav.scrollLeft();
            var viewportWidth = subnav.innerWidth();
            var scrollWidth = subnav[0].scrollWidth;
            var leftScroller = $('#navigation.small').find('.leftscroller'),
                rightScroller = $('#navigation.small').find('.rightscroller');
            leftScroller.addClass('enabled');
            rightScroller.addClass('enabled');
            if (scrollLeft === 0) {
                // we've reached the far left part of the scroll area
                leftScroller.removeClass('enabled');
            }
            if (scrollWidth - scrollLeft <= viewportWidth) {
                // we've reached the far right part
                rightScroller.removeClass('enabled');
            }
        }
    };

    /* Add scroll indicators */
    $('#navigation.small .ph_subnav').append(
        'You can scroll to the left' +
        'You can scroll to the right'
    );
    showScrollIndicators();

    $('#navigation.small .subnav').scroll(function() {
        showScrollIndicators();
    });

What am I doing wrong? So the whole area which falls beneath /Scrollable/ is not shown.


text:
Q: Github how to give authorization to my repository to other people Hello i'm completely new in the source control systems and i need some help so my friend and i could work on 1 project that we decided to make.
So i make a repository and clone it in my computer using this:
git clone https://github.com/L...ject_Stanev.git. My friend is making the same thing successful. when he makes new files or changes to mine he is able to add and commit but when he tries to push this is what the console says:  http://i.stack.imgur.com/76Wo8.png (sorry i can't add images)
so how can i give him authorization so he can push in my repository ?

A: From your repository within GitHub, navigate to the settings screen from the list menu on the right side of the browser.
From the settings go to the collaborators section using the link on the left side of the screen.
Add your friend to the list of collaborators and they will be able to push to the repo.


text:
Q: List all ancestors of a child in hierarchical data structure Consider the following sample table:
with v1 as (
select 'I' as parent_id, 'M' as child_id from dual union all
select 'M', 'M1' from dual union all
select 'M', 'D' from dual union all
select 'I', 'P' from dual union all
select 'P', 'K' from dual union all
select 'A', 'P1' from dual union all
select 'C', 'A' from dual union all
select 'A', 'I' from dual union all
select 'P1', 'K1' from dual
)
select ListAgg(child_id,'<-')
   within group(order by Level desc)  as Path
from v1
START WITH child_id = 'D'
CONNECT BY PRIOR parent_id = child_id;

It returns:
A<-I<-M<-D

It is not returning A's parent which is C.
What should I change in the query so that it returns C as well like below:
C<-A<-I<-M<-D

NOTE that before executing the query, I have no means to know that C is the root of the hierarchy. So, I can not pass C in the query (and that is how I have designed the my query above).

A: You can use following query:
With v1 as (
select 'C' as parent_id, 'A' as child_id from dual union all
select 'I', 'M' from dual union all
select 'M', 'M1' from dual union all
select 'M', 'D' from dual union all
select 'I', 'P' from dual union all
select 'P', 'K' from dual union all
select 'A', 'P1' from dual union all
select 'A', 'I' from dual union all
select 'P1', 'K1' from dual
)
select ListAgg(case when level =1 then parent_id || '<-' || child_id else parent_id end,'<-')
   within group(order by Level desc) as Path
from v1
START WITH child_id = 'D'
CONNECT BY prior parent_id = child_id;

Sqlfiddle demo
Cheers!!


text:
Q: How can I wrap a mousemove jQuery event in a conditional? I'm exploring some different ways of filtering bot traffic from my site. Unfortunately, since many of these more sophisticated bots can execute JavaScript, many of my old tricks to exclude bot traffic from Google Analytics no longer work.
One idea I had is to use jQuery to only fire a pageview when a mousemove is detected on the document, like this:
var counter = 0;
if(counter === 0){
          $(document).mousemove(function(event){
               alert("Fire an event to GA here");
               counter += 1;
          }
     );
}

This does indeed fire the alert when the mouse is moved, but unfortunately the alert continues to pop up even though it has already fired once. My other concern is that I'd like to disable the event handler once it has fired, since mousemove can be resource intensive to the user.
Is this possible? And is there a better way to do this besides mousemove?

A: Your use of the counter is broken, but there's no need to keep the mousemove event handler attached to the document after it's fired. Try using one to bind the event so that it will execute only once:
$(document).one("mousemove", function(event){
    alert("Fire an event to GA here");
});

A: $(document).on('mousemove', function(){
    alert("GA triggered");
    $(document).off('mousemove');
});

A: You're darn close. You just inverted your if() by placing it outside the binding.
Look at jQuery's unbind() as well.
var counter = 0;
$(document).mousemove(function(event){
      if(counter === 0){
           alert("Fire an event to GA here");
           counter += 1;
           $(document).unbind( "mousemove" );
      }
});

A: Use one (jquery documentation)
So this will look something like this for your code:
$(document).one('mousemove',function(){
alert("Fire an event to GA here");
       counter += 1;
});


text:
Q: Configure Routing for the Angular (ui.router) with a Parameter Setting up routing for the multi-tenant frontend application using AngularJs and UI-Router.
For an example when a user type the following URL the dashboard should be loaded for userxyz and the parameter must be maintained in the user's browser through session, so that the user should be able to browse other hyperlinks within application.
http://servername.com/#/dashboard/userxyz

Am struggling to achieve this, I have watched some tutorials but unable to understand.
Here is the code for my route configuration.
(function () {
    'use strict';

    app.config(["$stateProvider", "$urlRouterProvider",
        function ($stateProvider, $urlRouterProvider) {
            $stateProvider
                .state("dashboard", {
                    url: "/dashboard/{tenantid}",
                    templateUrl: "app/components/dashboard/dashboardView.html",
                    controller: "DashboardController"
                })

                .state("people", {
                    url: "/people/{tenantid}",
                    templateUrl: "app/components/people/peopleView.html",
                    controller: "PeopleController"
                })

                .state("contact", {
                    url: "/contact/{tenantid}",
                    templateUrl: "app/components/contact/contactView.html",
                    controller: "ContactController"
                })

                $urlRouterProvider.otherwise("/dashboard/{tenantid}");
        }]);
})();

In my index.html, I have the following code to display the state in ui-view:

And, I did manage to setup the hyperlinks using ui-sref, here how it is:
Home
People
Contact

A: Better user local o session storage for save the tenant
According with the comments before:
If you don't need support for ie7 (hope so), try to use the native browser localStorage, for insert an item localStorage.setItem('key', 'value') for retrieve localStorage.getItem('key')
see the localStorage browser support here Local Storage Browser Support


text:
Q: Reading data from ~150+ (.csv) files into two categories based on the presence of a particular string in the file name I'm trying to set up a way to automate a lot of data analysis in Python 3. For now, most of the actual analysis is fairly simple (plotting 2 curves based on 4 input files and doing a few calculations). As I will always have a minimum of 4 files, I currently have something like this to read in all of the data from a .csv file from the 4 files I am looking at. Realistically, there are ~150+ files at any given time and I need a way to compare all of them very quickly.
For some background:
1). All files will be located in the same folder with the same path (except for the specific file name).
2). There are two categories (I call them 'Control' and 'NP') and each category has 2 files corresponding to it: Control-A, Control-B, and NP-A and NP-B.
3). There is a currently a ton of information that is located in the file name (lab conditions and so forth that the data acquisition software is reading live during the measurements), but somewhere in the middle of the filename lies the word either "Dark" or "Illuminated".
With this information, I am trying to find a way to import all of the files at once and separate them based on the file name. For example, all files that contain the words "ControlDark" will be grouped together, all files that contain "ControlIlluminated" will be grouped together and so forth for the other two combinations ("NPDark" and "NPIlluminated").
Right now, all I have is a a GUI that allows me to manually select 4 files from a specific path (using askopenfilename()). I'm not aware of any good ways to read in hundreds of .csv files at once.
Right now, I can only accommodate 4 data sets at a time as I'm not aware of a way to save entire folders worth of data (without having a corresponding askopenfilename() or np.genfromtxt('path\filename.csv'))
f1 = askopenfilename()
f1_data = pd.read_csv(f1, names = ['A', 'B', 'C'])

f2 = askopenfilename()
f2_data = pd.read_csv(f2, names = ['A', 'B', 'C'])

f3 = askopenfilename()
f3_data = pd.read_csv(f3, names = ['A', 'B', 'C'])

f4 = askopenfilename()
f4_data = pd.read_csv(f4, names = ['A', 'B', 'C'])

Basically I bring up a gui with the askopenfilename() command and manually find the 4 files in question. However, I want to automate this so that I can dump all ~150+ files into this right from the start.
I have found a way to begin, but I'm getting a bit stuck with reading each file into it's own data structure. So far I have:
import glob
import pandas as pd
import os

path = r'full\path\here'
all_files = glob.glob(os.path.join(path, "*.csv"))

#Setting up a list for each of the 4 files I need to generate each plot
DarkControl = []
IllControl = []
DarkNP = []
IllNP = []

for f in all_files:
     if "Control" in f and "Dark" in f:
          DarkControl.append(f)
     elif "Control" in f and "Illuminated" in f:
          IllControl.append(f)
     elif "GoldNP" in f and "Dark" in f:
          DarkNP.append(f)
     elif "GoldNP" in f and "Illuminated" in f:
          IllNP.append(f)

So I have a list for each of the categories, but right now it is a list of strings. Is there a good way to (possibly using pandas data frames?) to create a data frame for each file f in all_files? I want to definitely avoid creating one massive structure with all files. In each file, the first column is my x variable, the second is my y variable. I want to make sure that I can plot the y values of any given f and the y values of some other f against the x values (all x values are the same for all files)

A: Usually we would ask for a MVC example we can test our code against. However, I think I do have some understanding of your problem.
If I understand your problem correctly, you have sensor-type data where x is some type of time-like axis and this is repeated across multiple experimental trials.
You are on the right track for sorting the files out but a python list comprehension would probably be a cleaner/more pythonic way of writing this
Dark_control=[f for f in all_files if "Control" in all_files if "Dark" in all_files]
You could also implement your pattern matching in your glob.glob.
A data frame would be perfect for this type of structure where depending on your data structure (and how you want it set up) you could use that same list comprehension to read the data as well.
Dark_control=[pd.read_csv(f) for f in all_files if "Control" in all_files if "Dark" in all_files]
The code above would create an array of data frames with all of the values together which you could pd.concat or pd.join depending on how you have your final data.
Not sure why you couldn't have all of your data together in a single large dataframe for analysis (look into using multi-indexing to keep different experimental trials separate).


text:
Q: Split JSON arrays across multiple select boxes I'm using AngularJS in parts of my website, not for the whole thing. I have a couple of select boxes with one that is dependent on the other. One contains a list of countries, and the other contains cities for the selected country.
In the past, I would split my json into 2 queries to the server, so on country changed, it'll send the selected value, and the server would return a json list accordingly which will be inserted into the select box using jquery. This time, and using http://builtwith.angularjs.org/ as sort of a guideline, I decided to return everything as one json, and handle this functionality purely in javascript.
So lets say, my json looks like this:
[
  { "code": 1, "country": "Germany", "cities": [ "Berlin", "Munich" ] },
  { "code": 2, "country": "Italy", "cities": [ "Rome", "Venice" ] },
  { "code": 3, "country": "United Kingdom", "cities": [ "London", "Manchester" ]}
]

I would need all the values of country as one list for country select box, and the list of each cities for the other select box.
Here's the controller so far:
angular.module('myApp', [])
    .controller('MyController', ['$scope', '$http', function ($scope, $http) {

        $http.get('/api/locations')
            .success(function (data, status, header, config) {

                $scope.locations = data[0];
                $scope.countryList = [];
                $scope.cityList = [];

                for (var i = 0; i < data.length; i++) {
                    $scope.countryList.push([data[i].code, data[i].country]);
                    for (var j = 0; j < data[i].cities.length; j++) {
                        $scope.cityList.push([data[i].code + '-' + data[i].cities[j], data[i].cities[j]]);
                    }
                }
            });
    }]);

My select boxes:
Country:
<select ng-model="country" data-ng-options="c for c in countryList"></select>

City:
<select data-ng-model="city" data-ng-options="c for c in cityList"></select>

Currently, both select boxes get filled, but their text contains both values of the array. The cities box contains ALL cities, not just the ones for the first country.
I'm not sure if i'm on the right path here, or if there's an easier way to achieve this.
So sum up, I'd like to know:

*

*Should i keep the whole json as one request/response and handle
it in JS?

*How do you load each select box the 'official' angularjs way?

*I'm aware of the ng-change attribute on the select box, but I'm
not sure how I'd create a query and change the city list values
according to the selected country.

Here is a plunk: http://plnkr.co/edit/zAcRjSDm9OndxugtsAOs?p=preview

A:
I'm not sure if i'm on the right path here, or if there's an easier way to achieve this.

Yes you are on the path of The Angular Way. And yes, there is an easier way.

I'm aware of the ng-change attribute on the select box, but I'm not sure how I'd create a query and change the city list values according to the selected country.

Here is a forked Plunk that demonstrates how to set the 2nd select box based on the output of the first.
The country select box has 2way binding via ng-model, so the result is bound to a value called country
The country select box uses country.cities for it's inputs, and binds the selected value to city

Should i keep the whole json as one request/response and handle it in JS?

That depends on how you build your service. If you forsee no use of separating cities from countries, then keep them bounded.
Otherwise you may wish to have the following REST api:
get /country //returns array of all countries
get /<countryname>/cities //returns array of all cities in country

The downside is that you need to make multiple get requests for the data. The upside is your api is a bit more modular. However it depends on your use case.

How do you load each select box the 'official' angularjs way?

Your plunk syntax 'c for c in cityList' appears correct.


text:
Q: Jmeter throws CannotResolveClassException: com.zeroclue.jmeter.protocol.amqp.AMQPConsumer I am trying to import a JMX file and it throws the following exception. I have downloaded jmeter-plugins-manager-1.3.jar and have put in 'lib/ext' folder as suggested in here.

A: You are missing the JMeterAMQP.jar in your lib/ext directory.
To resolve this issue you can check this JMeter-Rabbit-AMQP git project and build an executable JMeterAMQP.jar and then just copy the .jar file into your JMeter's lib/ext directory. Additionally, you also need RabbitMQ Java Client into your lib/ directory.
So, here is a quick solution for you:

*

*Download JMeterAMQP.jar from this link and paste it into your JMeter's lib/ext directory.

*Download amqp-client from this link and paste it in your JMeter's lib/ directory.

*Restart your JMeter.
That's it, you should be able to open your JMX file now.


text:
Q: Get next midnight date and time using Python time library only I have a timestamp generated from time.time().
Example: 1597316030
Converting to date and time this gives "Thursday, August 13, 2020 10:53:50 AM GMT+00:00".
Is it possible to get the timestamp that would correspond to "Thursday, August 14, 2020 12:00:00 AM GMT+00:00" (next midnight, or any other date and time), using only time library (without date or datetime, for example)?
Thanks!

A: using only time library (without date or datetime, for example)?
It is possible without any library and quite simple after you realize that: 0 is start of epoch is midnight 1 Jan 1970 and every 24 hour is 86400 second, therefore any midnight will be multiply of 86400, thus you just need to find smallest multiply of 86400 greater than your timestamp, which can be done following way:
t = 1597316030
t2 = ((t//86400)+1)*86400
print(t2)

Output:
1597363200

Keep in mind that this solution totally ignore existence of timezones.


text:
Q: git: forget to save local changes but reset to past commit I made some changes in my local working directory, I forget to save/commit them, but I command git reset HEAD~1 to go back to my previous commit. How do I recover my local work?

A: If you only ran git reset HEAD~1 (without using --hard), git hasn't changed to content of your files on disk. You can check that, in your IDE, your files still contain the modifications you had before your reset command.
The only things that changed are :

*

*the active commit : you can come back to your previous state by inspecting git reflog to see what was the <sha> of the commit before your git reset HEAD~1 action, and run git reset <sha>

*your staged files : git reset has unstaged your staged files if you had any, and there is no easy way to get back their state.

If you rang git reset --hard, then unfortunately @Code-Apprentice's comment applies : git has reverted the content on disk without saving it first. Check if you have a history of your files in your IDE, or use a file restoration tool for your OS.


text:
Q: WcfAjaxEnabled - Postback I've a wcf ajax enabled hosted in a web site (it's a web chat).
For some reason, when I need to execute a postback, my wcf service works in unexpectedly way (such as big delay in a call, work off, and so on..).
The oddity occurs when I try to call some wcf function through javascript from protected page too (Many page are protected by web config with authentication mode=form).
Are the above issue caused from the same reason? But which can it be the reason?
EDIT:
I notice that the above problems occurs only when my web site contains global asax file with sessionStart and SessionEnd event handlers (it's true even when those event handlers are empty, namely without any instrunction).
@EDIT:
Ok, issue about postback is due to devExpress control (captcha). If I use a simple button for doing some postabck all works fine. Maybe that component injects some bad script in my page, I've not idea.
So, remain questione about access to protected page by login only. It's important to know that login issue occurs only on production site where login page is placed on internal (nested) application, while on test site where login mechanism is on the same application all works fine.
However, in this moment I solved by changing login logic for chat access. I've removed the protection in web config for that chat admin page and I check user credential on its init event. If it's not logged, then I execute a simple redirect to login page and all works correctly.
@@EDIT
Well, I found the exact cause and solved it. Please, take a look here: http://blogs.msdn.com/b/silverlightws/archive/2009/09/30/having-a-pollingduplex-service-and-any-other-wcf-service-in-the-same-website-causes-silverlight-calls-to-be-slow.aspx


text:
Q: jquery close a div with fading and slide I want to make a web page.I am using jquery for animation and for an easier javascript.I want to close a div when clicking in a button with a fading out and slide up effect.
Is this possible?
Thanks

A: JSFiddle
You can't do both at the same time (using slideUp() and fadeOut()). You have to have a work around using animate():
$(".button").animate({ height: 'toggle', opacity: 'toggle' }, 'slow');

You toggle the opacity (making it 0) and also the height (also making it 0) and give it an animate time of slow, but you can make it faster (1000 is 1 second).

A: using jquery .animate() you can do lots of things, here is an example:
html:

<button id="test_bt">CLICK ME</button>

css:
#test_DIV{
    height:200px;
    width:200px;
    background:red;
}

javascript:
$(function(){
    $("#test_bt").click(function(){
        $("#test_DIV").stop().animate({
            height:0,
            opacity:0
        });

    });
});

and here is a FIDDLE


text:
Q: Android: Integrating Foursquare into App
Possible Duplicate:
how to use foursquare API in android application?

This is a question mainly for people who have used Foursquare in their applications, I understand it would seem like gibberish to others.
I'm relatively new to applications that interact with the internet, so please bear with me. I'm writing an application that lists various venues in a certain part of town. I was wondering, how can I list these venues so that if a user clicks on it, they can check into that particular venue on their Foursquare accounts. While some code would be best, I would also appreciate any tips on how to start as well. Right now, I am writing the application in java, using the Eclipse IDE for Android.
Also, if anyone has any simple open source projects integrating Foursquare, I would love to take a look at it!
Best,
Aneem

A: It appears that you have asked the same question twice ( https://stackoverflow.com/questions/8813225/android-using-foursquare)
You have two main ways to integrate foursquare:

*

*Using the 'intents' to launch the foursquare application - while this is not really a full integration, it might be enough for your requirements

*Using the foursquare API you can get full integration, you should take a look at the Libraries page. If you want more examples, one, two and google for the rest.

The examples will not really be enough, you should also look at the different API endpoints to better understand what data is returned to you in each action you take


text:
Q: Create controller, model and view CAKEPHP 3 I've just started to use cakephp but I have a lot of doubts.
First of all:
When I create a Controller, model and view with a DB conection with:
cake bake all "name"

it works fine but when I need no DB for one part of my webpage I can't do anything because it don't work.
So I delete this files:
/src/Controller/MyController.php
/src/Model/Entity/Model.php
/src/Model/Table/MyTable.php
/src/Template/MyTemplate/*
/tests/TestCase/*

And add the following line in routes.php
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'inicio']);

This works, but when I do this I can't see my layout in my page
I have the conection to Bootstrap and my header and footer in the layout but now I don't work, and now I don't have a controller to do my code in.
How can I do a controller model and view without a DB?
Thanks

A:
And add the following line in routes.php
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display',
  'inicio']);
This works, but when I do this I can't see my layout in my
  page

Create empty inicio.ctp and don't use $this->layout = false;

How can I do a controller model and view without a DB?

Bake new controller with command cake bake controller Home  or your controller name.
Inside generated controller use empty methods, without calling Models / ORM methods, or set some variables, like
public function index()
{
 // this is empty method
}

public function aboutUs()
{
 $about_us = [
   'title' => 'My title here',
   'description' => 'some text..'
 ];
 $this->set(compact('about_us'));
}

public function contact()
{
 // Add Modelless form here
}

Modelless Forms: http://book.cakephp.org/3.0/en/core-libraries/form.html
Note: you can add these methods at PagesController and just route, for example:
$routes->connect('/contact', ['controller' => 'Pages', 'action' => 'contact']);


text:
Q: Android Emulator black screen on Phenom II X4 965 I can not start the android emulator on my machine. I can see the phone "frame" but the content is black.
I also tried to start the emulator from command line and I get the following error messages:
./emulator -avd Pixel_3_Edited_API_28
emulator: Android emulator version 30.5.5.0 (build_id 7285888) (CL:N/A)
handleCpuAcceleration: feature check for hvf
emulator: WARNING: Host CPU is missing the following feature(s) required for x86 emulation: SSSE3
Hardware-accelerated emulation may not work properly!
emulator: WARNING: Not all modern X86 virtualization features supported, which introduces problems with slowdown when running Android on multicore vCPUs. Setting AVD to run with 1 vCPU core only.
cannot add library /home/ps/Android/Sdk/emulator/qemu/linux-x86_64/lib64/vulkan/libvulkan.so: failed
added library /home/ps/Android/Sdk/emulator/lib64/vulkan/libvulkan.so
cannot add library /home/ps/Android/Sdk/emulator/lib64/vulkan/libvulkan.so.1: full
host doesn't support requested feature: CPUID.01H:ECX.ssse3 [bit 9]
host doesn't support requested feature: CPUID.01H:ECX.sse4.1 [bit 19]
host doesn't support requested feature: CPUID.01H:ECX.sse4.2 [bit 20]
qemu-system-x86_64: can't open backing store /home/ps/.android/avd/Pixel_3_Edited_API_28.avd/snapshots/default_boot/ram.img for guest RAM: Permission denied
qemu-system-x86_64: falling back to regular RAM allocation.
emulator: INFO: GrpcServices.cpp:301: Started GRPC server at 127.0.0.1:8554, security: Local

Is my computer to old? Do I need a newer CPU?
System
CPU: AMD Phenom II X4 965
Linux Mint 19.3

A: Yes your computer is too old, see
emulator: WARNING: Host CPU is missing the following feature(s) required for x86 emulation: SSSE3
even you are lucky enough to be able to start it, it would not be in usable performance. You should either buy a new computer or use a cloud service to do it. Any recent i5 desktop with like 8gb ram should have given you usable performance.


text:
Q: Is pROC area under the curve incorrect? My current problem : I used caret package to generate classification prediction models and I meant to validate my models with specific metric (AUC ROC). AUC metric is available to train model with training set (internal validation) but NOT to predict (external validation).
1. Internal validation :
Fit <- train(X, Y$levels, method= "svmRadial", trControl = fitControl, tuneLength = 20, metric = "ROC")
Results :
sigma      C       ROC      Sens   Spec     ROCSD    SensSD    SpecSD
0.0068   2.00      0.83     0.82   0.57     0.149    0.166     0.270
2. External Validation :
In order to access to external validation AUC, I tried to predict my training set and calculate directly this metric with pROC.
predictions <- as.vector(predict(Fit$finalModel, newdata = X))
 data <- data.frame(pred=as.numeric(predictions),obs=as.numeric(Y$levels))
 pROC::roc(data$pred, data$obs)
Results :
Area under the curve: 0.9057
3. Conclusion :
Results : AUC(internal validation) != AUC(external validation) whereas I used same data (training set) to check my ROC external validation criterion. In the best case, I should be able to obtain a maximum value of 0.83. However, it would seem very odd to me that AUC(internal validation) < AUC(external validation).
I have no idea to solve this enigma (8-/ skeptical) . All assistance is welcome.

A: So your results are to be expected. In general the "internally validated" AUCs are created by using test cases that were separate from the training cases whereas in your "external validation" you are testing with the same cases you trained on (which is cheating of course). So the internally validated AUC will be expected to be smaller than the externally validated AUC. I think the following diagram should make that clear:


text:
Q: Google like "Did you mean ?" search suggestion using Levenshtein Distance I'm building a simple google like "did you mean ?" search suggestion using Levenshtein Distance algorithm. I've managed to get it working but I have problem with returning the result.
For example, if the keywords are "How to use fasebuk and twitster ?" I want to replace only the incorrect words so the suggestion result would be "How to use facebook and twitter ?"
How to achieve that kind of suggestion ?
Below are what I've done so far :
public function searchsuggestion(Request $request)
    {
        $allwords  = array('facebook','orkut','twitter','yahoo', 'microsoft','paypal','google','bing','msn');
        $shortest = -1;
        $keywords = trim($request->input('q'));
        if (! empty($keywords)) {
            foreach ($allwords as $word) {
                $lev = $this->LevenshteinDistance($keywords, $word);
                if ($lev == 0) {
                    $closest = $word;
                    $shortest = 0;
                    break;
                }
                if ($lev <= $shortest || $shortest < 0) {
                    $closest  = $word;
                    $shortest = $lev;
                }
            }
            if ($shortest == 0) {
                $result = '';
            } else {
                $result = $closest;
            }
            return view('posts/search', compact('result'));
        }
        return redirect()->route('latestposts');
    }

I'm a newbie developer, any help appreciated. Thanks!

A: This is a good question. To do this you will need to process each word in the input string individually. That way you can replace individual words in the input string with the words from your dictionary.
Depending on your dictionary, you may need to do further processing on each hit to prevent false positives. When I started experimenting with your code, most of the words in the input were replaced with "msn" when using the Levenshtein distance alone.
I put together a test case that you can run from the command line to test the routine. In addition to processing each word individually so we can do the replacements, I am getting metaphone keys for both the original word and the dictionary word, then using similar_text to get a percentage of similarity between the two. There are threshold variables that allow you to set a ceiling threshold for Levenshtein distance, set a length limit on the metaphone keys, and set a minimum percentage for similarity of metphone keys.
<?php
class Request
{
    private $_data = [];

    public function __construct(array $data = [])
    {
        $this->_data = $data;
    }

    public function input($key, $default = null)
    {
        return (array_key_exists($key, $this->_data)) ? $this->_data[$key] : $default;
    }
}

function searchsuggestion(Request $request)
{
    $allwords = array('facebook', 'orkut', 'twitter', 'yahoo', 'microsoft', 'paypal', 'google', 'bing', 'msn');
    $keywords = trim($request->input('q'));

    $levThreshold       = 3;
    $metaphoneLength    = 5;
    $metaphoneThreshold = 60;

    if (!empty($keywords))
    {
        $keywordArr = explode(' ', $keywords);
        $matchArr   = [];

        foreach ($keywordArr as $currKeyword)
        {
            $shortest = -1;
            $closest  = null;
            foreach ($allwords as $word)
            {
                $lev = levenshtein($currKeyword, $word);

                if ($lev == 0)
                {
                    break;
                }

                if ($lev <= $shortest || $shortest < 0)
                {
                    $closest  = $word;
                    $shortest = $lev;
                }
            }

            if (!empty($closest) && $shortest <= $levThreshold)
            {
                $origSoundex  = metaphone($currKeyword, $metaphoneLength);
                $foundSoundex = metaphone($closest, $metaphoneLength);

                similar_text($origSoundex, $foundSoundex, $percentage);

                if ($percentage > $metaphoneThreshold)
                {
                    $matchArr[$currKeyword] = $closest;
                }
            }
        }

        if (!empty($matchArr))
        {
            $origWords    = array_keys($matchArr);
            $replaceWords = array_values($matchArr);

            return str_replace($origWords, $replaceWords, $keywords);
        }

        return null;
        //return view('posts/search', compact('result'));
    }
    //return redirect()->route('latestposts');
}

$request = new Request(['q' => 'How to use fasebuk and twitster?']);

$response = searchsuggestion($request);

print $response . "\n";


text:
Q: How uTorrent can read the body of a http response message without a specified size or "chunked" option? I've used the SmartSniff tool to catch the http messages between the uTorrent application and a server. I found one server that sends "HTTP/1.0 200 OK" response messages with a body and no headers that can tell the length of the body or the "chunked" option, but uTorrent seems not having trouble with that, it works fine. And I wander how did it do it ?
I think that, maybe, uTorrent knows about this "server error" and when it is expecting a body, after it reads the response line and headers (in this case none), it reads until the server close the connection. Is this posible ?
Catched communication:

*

*GET /announce.php?(a list of parameters here) HTTP/1.1

*Host: some.server.here:1234

*User-Agent: uTorrent/3320(30416)

*Accept-Encoding: gzip

*Connection: Close

*

*HTTP/1.0 200 OK

*(empty line)

*d8:completei176e10:incompletei0e8:intervali3600e5:peers0:e

A: I researched the link provided and I find the answer. It is as follow:

In a response message without a declared message body length, the message body length is determined by the number of octets received prior to the server closing the connection.


text:
Q: In CQRS, should my read side return DTOs or ViewModels? I'm having a debate with my coworkers in the design of the read side of a CQRS application.
Option 1: The application read side of my CQRS application returns DTOs, e.g:
public interface IOrderReadService
{
    public OrderDto Load(int id);
}

public class SomeController
{
    public ActionResult SomeAction(int id)
    {
        var dto = ObjectFactory.GetInstance<IOrderReadService>().Load(id);
        var viewModel = Mapper.Map<OrderDto, SomeViewModel>();
        return View(viewModel);
    }
}

public class SomeOtherController
{
    public ActionResult SomeOtherAction(int id)
    {
        var dto = ObjectFactory.GetInstance<IOrderReadService>().Load(id);
        var viewModel = Mapper.Map<OrderDto, SomeOtherViewModel>();
        return View(viewModel);
    }
}

Option 2: The application read side returns ViewModels, e.g.:
public interface IOrderReadService
{
    public SomeViewModel LoadSomething(int id);
    public SomeOtherViewModel LoadSomethingElse(int id);
}

public class SomeController
{
    public ActionResult SomeAction(int id)
    {
        return View(ObjectFactory.GetInstance<IOrderReadService>().LoadSomething(id));
    }
}

public class SomeOtherController
{
    public ActionResult SomeOtherAction(int id)
    {
        return View(ObjectFactory.GetInstance<IOrderReadService>().LoadSomethingElse(id));
    }
}

From the research my coworkers and I have done on the matter, responses appear mixed - it looks like it really depends on context.  So I ask you, my dear StackOverflowians:
Does one approach seem to have clear advantages over the other?  If so, what are they?

A: I would prefer to return DTO to separate the application layer from presentation technology (because each presentation technology may have some  requirements on the structure of presentation model) for example a web MVC application binding is different than WPF MVVM binding, also you may require some properties/fields in view models that has nothing to do with application data like for example (SliderWidth, or IsEmailFieldEnabled, ...).
Also for example if using WPF MVVM i would need to implement INotifyPropertyChanged interface to allow binding it is not convenient nor related to implement this interface in the application read service.
so i would prefer separating the concern of read data representation from the actual presentation technology and view model.
So option 1 is better for me

A: The general advice is one projection per screen (Greg Young) or even one projection per widget (if I understand Udi Dahan correctly).
To consolidate read models into DTOs that once again have to be mapped into separate views contradicts the whole purpose of an optimized read model. It adds complexity and mapping steps that we tried to get rid of in the first place.
My advice: Try to get as close as possible to SELECT * FROM ViewSpecificTable [WHERE ...] or something similar if using NoSQL in your thin read layer.
The concept of Aggregate Roots and their "children" doesn't have too much of an implication on the read side, since these are domain model concepts. You don't want to have a domain model on the read side, it only exists on the write side.
UI platform-specific transformation as mentioned by Mohamed Abed should be done in the UI layer, not in the read model itself.
Long story short: I'd opt for option 2. To not confuse it with a platform-specific ViewModel, I'd rather call it ReadModel but have one per view anyway.

A: A read model is a projection of the write model. It's there to fulfill a specific purpose. In your case that seems providing view models to your MVC controllers. As such, why go thru the trouble of mapping DTO's to Viewmodels? The only reason I could think of was that the benefit of having two separate read models might not outweigh their maintenance cost. But do consider that "merging" read models for the purpose of "reuse" and "lowering maintenance costs" increases complexity for the developer (Can I change this table? Hmmm, I now have two (or more) consumers I have to take into account - smells a bit like database integration all over again).
Just my thoughts.

A: One of the primary principles of DDD/CQRS is that you shouldn't be editing the view model. Instead, task-based screens should guide the user towards issuing explicit commands. If you can't come up with task-based screens, you should be using a different form of CQRS like the one I describe here:
http://udidahan.com/2011/10/02/why-you-should-be-using-cqrs-almost-everywhere/


text:
Q: Refresh Excel connections using Powershell I have the below code that opens a spreadsheet, deletes all connections and "Saves" a new file.
$a = New-Object -COM "Excel.Application"
$a.Visible = $false
$b = $a.Workbooks.Open("F:\Scripts\All Users.xlsx")

do
{
    $b.Connections.Item(1).Delete()
    $Count = $b.Connections.Count()
} until($Count -eq 0)

$b.SaveAs("F:\Scripts\Users Home Drive Search.xlsx")
$b.Close()

I would like to know two things:

*

*How do I get the sheet to RefreshAll connections? I've tried "$b.Connections.refreshall()" but the refreshall() doesn't exist.

*How do I quit Excel application? I ran "New-Object -COM "Excel.Application" | Get-Member -MemberType Methods" and I don't see a quit or exit method.

A: RefreshAll() is a method of the WorkBook object, so use that to refresh the external connections:
$b.RefreshAll()

To exit Excel and remove the used COM objects from memory, use
$a.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($b)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($a)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

BTW, I would use more descriptive variable names, so $excel instead of $a and $workbook instead of $b to avoid confusion later on.


text:
Q: change td properties and keep value from extracted data from site I have this structure to get data from another webstie
$searchURL = "http://www.anotherwebsite.com";
$html = file_get_contents($searchURL);

$patternform = '/(<tbody.*<\/tbody>)/sm';
preg_match_all($patternform ,$html,$matches);
preg
echo $matches[0][0];

        OB I
        vízilabda, ffi

        063
        jégkorong3
        Magyarország - Lengyelország

                                    1.59

                                    4.20

                                    3.55

                            P 18:15

                            nov. 08

^^
I had this "input"
Question is:
How can I change three td value to javascript onclick event (extra: that I want to store the name of the event and I want to store the selected odds and add to new div or table line by line.)
I think preg_replace need but regexp. not my desk.

A: Why must javascript be used?  Would simply using the HTML onclick work?


text:
Q: Using perf4J Profiled annotation without other libraries (like log4j for example) When using perf4J, this code works well:
StopWatch stopWatch = new LoggingStopWatch();
stopWatch.stop("example1", "custom message text");

But when using @Profiled, what to do to output or get measures, with minimum of code:
@Profiled(tag = "dynamicTag_{$0}")
public void boucle(int k)
{
    // My code to profile
}

A: When using the @Profiled annotation to add stopwatches to your code, you will typically use AspectJ Load Time Weaving (LTW) to instrument your code at load/runtime, which adds the stopwatch starts/stops and recordings around annotated methods.
Which logging library/API (log4j, slf4j, commons-logging, JUL) is used depends on the specific instance of org.perf4j.aop.ProfiledTimingAspect you configure in your aop.xml configuring your LTW.  For example this config:

<aspectj>
  <!--
    We only want to weave in the log4j TimingAspect into the @Profiled classes.
    Note that Perf4J provides TimingAspects for the most popular Java logging
    frameworks and facades: log4j, java.util.logging, Apache Commons Logging
    and SLF4J. The TimingAspect you specify here will depend on which logging
    framework you wish to use in your code.
  -->
  <aspects>
    <aspect name="org.perf4j.log4j.aop.TimingAspect"/>
    <!-- if SLF4J/logback use org.perf4j.slf4j.aop.TimingAspect instead -->
  </aspects>

  <weaver options="-verbose -showWeaveInfo">
    <!--
      Here is where we specify the classes to be woven. You can specify package
      names like com.company.project.*
    -->
    <include within="ProfiledExample"/>
  </weaver>
</aspectj>

... uses org.perf4j.log4j.aop.TimingAspect, so the stopwatches will be logged to your configured Log4J stopwatch logger.  If you want to avoid third-party libraries, you can change this for the JUL JDK logger.


text:
Q: Is it possible to remove a file from an input type file without reloading the page? Hello person I want to remove a file select an input inside a form, but when I remove it, reload the page and lose everything I had written in the rest of the form,it would be a HelpDesck system for the user and it would be annoying to have to rewrite every time you remove the file.
Is there any way I can do this operation without reloading the page and being able to attach another file to it?
form
<form id="frm" enctype="multipart/form-data">

Novo Comentário

            <input type="text" id="id_chamado_comentario" value="@Model.id" hidden />

            Título
            <input id="titulo_anotacao" type="text" class="form-control" />

            Anotação
            <textarea id="anotacao" class="form-control"></textarea>

            Anexo
            <input type="file" id="anexopost" name="anexopost" class="form-control">
            <button id="BtnLimpar" style="display:none">Limpar</button>

            <button type="button" class="btn btn-outline-primary" id="btn_salvar_anotacao" onclick="createAnotacao()">Salvar</button>
        </form>

javascript
$('#anexopost').on('change', function () {
    var extension = this.files[i].name.split('.')[1]

    if (validExt.indexOf(extension) == -1) {

        Swal.fire({
            title: 'Arquivo Invalido',
            text: "O Anexo só permite os seguintes tipos jpg, jpeg,png, docx, xlsx, word, xls, csv, pdf",
            icon: 'error',
        })
        $("#BtnLimpar").show();
        $('#btn_salvar_anotacao').prop("disabled", true);

    }
    else {
        $('#btn_salvar_anotacao').prop("disabled", false);
    }
})

$("#BtnLimpar").click(function () {
    $('#btn_salvar_anotacao').prop("disabled", false);
    $('#anexopost').val('');
    $(this).hide();
});

function createAnotacao() {

    $('#btn_salvar_anotacao').prop("disabled", true);
    // Adicionar loading no botão
    $('#btn_salvar_anotacao').html(
        ''
    );

    var formData = new FormData();

    var files = $('#anexopost').get(0).files;

    formData.append("titulo_anotacao", $('#titulo_anotacao').val());
    formData.append("anotacao_texto", $('#anotacao').val());
    formData.append("chamados", $('#id_chamado').val());
    formData.append("anotacao_anexo", files[0]);

    $.ajax({
        url: '/Chamados/CreateAnotacao',
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {

            location.reload();
        },
        error: function (data) {
            $('#btn_salvar_anotacao').prop("disabled", false).text("Salvar");
            $('#loading_anotacao').remove();
            swal({ title: 'Ops!', text: 'Houve um erro ao tentar salvar o contéudo. Por favor, contate minha equipe de suporte.', icon: 'error', timer: 10000, button: 'OK!' });
        }
    });

}

I thank you for your help

A: I am not sure but you can try something like this:
    $("#BtnLimpar").click(function (e) {
    e.preventDefault();
// rest of the function


text:
Q: Choosing a SAN technology for 100s of VM Web Servers The Problem
We have an issue with performance on an existing platform, so I'm turning to the hive mind for a second opinion on this. The performance issue so far relates to IOPS rather than throughput.
The Scenario
A blade centre of 16 hosts, each with 64GB of RAM. (It's a Dell M1000e w/ M610s, but that's probably not relevant)
500 VMs, all web servers (or associated web technologies such as MySQL, load balancers, etc), around 90% are Linux and the rest Windows.
Hypervisor is VMWare vSphere.
We need to provide host HA, so local storage is out. As such the hosts just have an SD card to boot.
A bit of background thinking
At the moment we are up to 6 hosts (the blade centre will be at full capacity in a years time at current growth) and we are running iSCSI to a Dell MD3220i w/ MD1220 for expansion.
Possible options we have considered, and immediate thoughts along with them:

*

*Spreading the VMs across NFS datastores, and running NFS storage that meets performance requirement for up to a given number of VMs. NFS seems cheaper to scale, as well as been abstracted a bit more than block level storage so we can move it around as needed.

*Adding more MD3220i controllers/targets. We are concerned though that doing this could have a negative effect somehow in how VMWare handles having lots of targets.

*Swapping all disks from Nearline SAS to SSD. This ought to entirely solve the IOPS issue, but has the obvious side effect of slashing our storage capacity. Also it's still very expensive.

*vSphere 5 has a storage appliance. We haven't researched this much, but it must work well?

The Question
What sort of storage would you run underneath all of that? It wouldn't need to scale to another blade centre, it would just need to provide relatively good performance for all of those VMs.
I'm not looking for "Buy SAN x because it's the best" answers. I'm looking for thoughts on the various SAN technologies (iSCSI, FC, FCoE, InfiniBand, NFS, etc), different types of storage (SATA, SAS, SSD), and methodologies for handling storage for 100s of VMs (Consolidation, Separation, Sharding, etc).
Absolutely any thoughts, links, guides, pointers etc are welcome on this. I'd also love to hear thoughts on the above options we'd already considered.
Many thanks in advance for any input!
Update 5th March '12
Some fantastic responses so far, thank you very much everyone!
Going by the responses to this question so far, I'm beginning to think the following route is the way:

*

*Tier the available storage to the VMWare cluster and place VM disks on suitable storage for their workloads.

*Potentially make use of a SAN that is able to manage the placement of data on to suitable storage automagically.

*Infiniband looks to be the most cost effective to get the required bandwidth with the hosts at full capacity.

It definitely sounds like it would be worth making use of the pre-sales services of a major SAN vendor to get their take on the scenario.
I'm going to continue to consider this problem for a while. In the mean time any more advise gratefully received!

A: The key question is: "where's the bottleneck?"  You mention IOPS, but does that mean that you're positively identified the disks themselves as being the bottleneck, or merely that the SAN ports aren't running at capacity, or that the VMs are in far more iowait than you'd like?
If you've definitely identified that the disks are the limiting factor, then switching to NFS or infiniband or whatever isn't going to do squat for your performance -- you need SSDs (or at least tiered storage with SSDs in the mix) or a whole bundle more spindles (a solution which has itself gotten a whole lot more expensive recently since the world's stepper motor production got washed into the ocean).
If you're not 100% sure where the bottleneck actually is, though, you need to find that first -- swapping out parts of your storage infrastructure more-or-less at random based on other people's guesses here isn't going to be very effective (especially given how expensive any changes are going to be to implement).

A: If you want iscsi or nfs then minimally you'll want a few 10/40gb ports or infiniband which is the cheapest option by far but native storage solutions for infiniband seem to be limited. The issue will be the module for the bladecenter what are its options, usually 8gb fc or 10\1gbe and maybe infiniband.  Note that infiniband can be used with nfs and nothing comes closed to it in terms of performance\price.  if the blade center supports qdr infiniband i'd do that with a linux host of some kind with an qdr infiniband tca via nfs.  Here's a good link describing this http://www.zfsbuild.com/2010/04/15/why-we-chose-infiniband-instead-of-10gige
but if the bladecenter can support qdr infiniband and you can afford native infiniband then thats the solution you should pick.
Currently you can get 40gbe switchs far cheaper (thats a strange thought) then 10gbe switches but I doubt you're blade center will support that.

A: The key to a good VMWare storage platform is understanding what kind of load VMWare generates.

*

*First, since you host a lot of servers, the workload is typically random. There are many IO streams going at the same time, and not many of them can be successfully pre-cached.

*Second, it's variable. During normal operations, you may see 70% random reads, however the instant you decide to move a VM to a new datastore or something, you'll see a massive 60GB sequential write. If you're not careful about architecture, this can cripple your storage's ability to handle normal IO.

*Third, a small portion of your environment will usually generate a large portion of the storage workload.

The best way to approach building storage for a VMWare platform is to start with the fundamentals.

*

*You need the ability to service a large random read workload, which means smaller faster drives, as well as possibly SSD. Most modern storage systems allow you to move data around automatically depending on how it's accessed. If you are going to use SSD, you want to ensure this is how you use it. It should be there as a way of gradually reducing hot-spots. Whether you use SSD or not, it's beneficial to be able to put all the work across all the drives, so something with a type of storage pooling would be beneficial.

*You need the ability to service intermittent large writes, which doesn't care as much about the spindle speed of the underlying drives, but does care about the controller stack's efficiency and the size of the cache. If you have mirrored caching (which is not optional unless you're willing to go back to backups whenever you have a controller failure), the bandwidth between the two caches used for mirroring will be your bottleneck for large sequential writes, usually. Ensure that whatever you get has a high speed controller (or cluster) interconnect for write caching. Do your best to get a high speed front end network with as many ports as you can get while remaining realistic on price. The key to good front end performance is to put your storage load across as many front end resources as possible.

*You can seriously reduce costs by having a tier for low priority storage, as well as thin provisioning. If your system isn't automatically migrating individual blocks to cheap large/slow drives (like nearline SAS or SATA with 7200 RPM and 2TB+ sizes), try to do it manually. Large slow drives are excellent targets for archives, backups, some file systems, and even servers with low usage.

*Insist that the storage is VAAI integrated so that VMWare can de-allocate unused parts of the VMs as well as the datastores.

A: My big VMWare deployments are NFS and iSCSI over 10GbE. That means dual-port 10GbE HBA's in the servers, as well as the storage head. I'm a fan of ZFS-based storage for this. In my case it's wrapped around commercial NexentaStor, but some choose to roll their own.
The key features of ZFS-based storage in this context would be the ARC/L2ARC caching functionality, allowing you to tier storage. The most active data would find its way in RAM and SSD storage as a second tier. Running your main storage pool off of 10k or 15k SAS drives would also be beneficial.
This is another case of profiling and understanding your workload. Work with someone who can analyze your storage patterns and help you plan. On the ZFS/NexentaStor side, I like PogoStorage. Without that type of insight, the transport method (FC, FCoE, iSCSI, NFS) may not matter. Do you have any monitoring of your existing infrastructure? What does I/O activity look like now?

A: Local storage is out? I am quite happy with the write throughput on my local RAID 5s - mirrored with DRBD8 to the cluster-partner of my XEN-machine... (but this is "not supported", of course).
Aside from that I am quite sure that mySQL is your performance problem (I never saw a worse DB). Try to tune it away and/or try to put the whole DB into the filesystem cache (for read access)...


text:
Q: What exactly is the difference between these two statements I am a beginner in java and i was going through this code
    ListNode current = new ListNode();
    current = front;

and
    ListNode current = front;

Arent both set of statements creating a new object or is it that the memory is being reserved only for the first staement andfor the second only a vatriable is getting declared which holds the memory of the fron node?

A: ListNode current = new ListNode();
current = front;

This creates a new ListNode and assigns it to current. It then immediately overwrites that reference, losing the reference to the new object. This is almost certainly a mistake. The code is equivalent to
new ListNode();
ListNode current = front;

If the ListNode() constructor has no side effects, that first statement is useless, and could just be
ListNode current = front;

A: The first statement actually creates a new object (which will be garbage collected soon after because current points to another object in the next instruction), whereas the second one only creates a reference to an existing object.
The recommended code is the second one because the ListNode created in the first one is never used so it is useless to instantiate it.


text:
Q: Crash on trying to set Today's Date on PickerView It's concerned to PickerView, The app get crashed on this line of code -
[datePicker setDate:date animated:YES];

I am getting this error sometime-
Assertion failure in -[_UIDatePickerView _setDate:animated:forced:], /SourceCache/UIKit_Sim/UIKit-2380.17/_UIDatePickerView.m:302
I tried to clean and run but sometimes code works perfectly but sometimes it gave same error.
Can anyone suggest any better solution for this?

A: I think there is not valid date . So please try to use this one..
[datePicker setDate:[NSDate date] animated:YES];

A: Mostly this types of error generated when you applies nil date: check values of date it is nil or/not ?? and give proper condition if you get nil value of UIDatePicker.
This is caused by the diffent locale (NSLocale) set on your device and in the simulator or your date format is wrong ,,,,, You should check if you date formatter is working as expected.


text:
Q: Union being overridden in OBIEE I have used a 'Union' to combine two reports showing different dates. When I open the report on it's own it works fine with the two dates shown. However when I drill to the (union) report from another on the dashboard it only shows one date. Is there a dashboard filter that I may need to un apply or is there some other explanation!? I cannot seem to get the report to function as required from the drill.

A: Tough to answer - need more info.  Some possibilities:

*

*You're not really drilling to the report you think you are. You can learn a lot by looking at the log to see what's happening in the target report.

*You may be passing values from the first report that exclude the date in the second report. Check your filters in the target report.  Look at the generated WHERE clause in the log. Run the SQL directly against the database. Is the date still excluded?

A: You want to start by checking the physical SQL which is written to the nqquery.log. It can also be obtained by viewing the log in Answers directly. Another way is to go to Administration > Issue SQL, enable presentation server cache, set the debug level to 7, execute the SQL and click on the view log link. The Physical SQl can also be tested against the actual database, if that is where your data is coming from. Examining both - your Logical SQL and your Physical SQL can resolve a lot of minor issues, including this one.


text:
Q: find() takes no keyword arguements in the following code text = []
for url in li:
  text.append(requests.get(url,headers={"User-Agent": "XY"}))

for i in range(len(text)):
  text[i] = bfs.BeautifulSoup(text[i].content,'html.parser')

articles = []
for t in text:
  articles.append(t.find(attrs= {"class":"td-post-content"}).text)

Error:
TypeError                                 Traceback (most recent call last)
<ipython-input-29-875997e138e5> in <module>
      1 articles = []
      2 for text in text:
----> 3   articles.append(text.find(attrs= {"class":"td-post-content"}).text)

TypeError: find() takes no keyword arguments

In the above code it shows that find takes no arguements any idea how to fix this?

A:
responses = [requests.get(url, headers={"User-Agent": "XY"})) for url in li]

bfs_list = [bfs.BeautifulSoup(response.content,'html.parser') for response in responses]

articles = [bfs_.find(...) for bfs_ in bfs_list]


text:
Q: defocus button after clicking it At vb project i have 3 buttons (checkbox with buttons appeareance)... if i click 1 of them it remains selected (focused),
i will control that program with a small RF keyboard, i suffer of pressing the space key very easy!!
how can i deselect (loose the focus) of that control to avoid the accidental activation-deactivation by space pressing??
i've tried adding a hidden button, and focussing it on the click event of the check-buttons"... like:
newbutton.focus()

but dont works!, later i've tried to focus the mainform but also it dont work!
form1.focus()

also i've tried:
Form1.select()

but still no working after clicking(cheking) the button it can be easily unchecked clicking the space key again!! wich is the correct way to avoid the accidental unchecking??
thanks.

A: It appears that you working with a WinForm.  The Form as a property named ActiveControl that can be set to Nothing (null).  Doing so in the CheckBox.CheckedChanged handler, will unfocus the CheckBox and prevent the issue you are experiencing.
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
    Me.ActiveControl = Nothing
    ' any other necessary code
End Sub

A: Why not just disable the SPACE and ENTER keys completely for your check box(es)?
'This contains the list of keys that should be disabled from interacting with your check boxes.
'You can add or remove keys from this as you like.
Dim DisabledKeys As New HashSet(Of Keys) From {
    Keys.Enter, Keys.Space
}

Private Sub CheckBoxes_KeyDown(sender As Object, e As KeyEventArgs) Handles CheckBox1.KeyDown, CheckBox2.KeyDown, CheckBox3.KeyDown
    e.SuppressKeyPress = DisabledKeys.Contains(e.KeyCode)
End Sub


text:
Q: Cross origin issue for post request from post man am writing an API with cross origin configuration
my websecurity config have
@Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(Boolean.TRUE);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(someFilter());
        registration.addUrlPatterns("/abc/*");
        registration.setOrder(1);
        return registration;
    }

Controller Class
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/gdpr/1.0")
public class AbcController {

    @PostMapping("/request")
    ReturnStatus saveRequest(HttpServletRequest request,
                             @RequestParam(value = "requestType", required = true) RequestType requestType,
                             @RequestParam(value = "Type", required = true) Type Type,
                             @RequestParam(value = "file", required = true)
                                     MultipartFile uploadedFile) throws InvalidInputException {

    }

Am trying to hit a request from my post man like below

authentication filter check
private static final Pattern HEALTH_CHECK = Pattern.compile("^.+/abc/[\\d]+\\.[\\d]+/?$");
        @Override
            protected void doFilterInternal(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {

                StringBuffer requestURL = request.getRequestURL();

                if (isHealthCheck(requestURL)) {
                    filterChain.doFilter(request, response);
                    return;
                }

                String source = UNKNOWN;

    boolean isHealthCheck(StringBuffer requestURL) {
            if (requestURL != null) {
                Matcher matcher = HEALTH_CHECK.matcher(requestURL.toString());
                return matcher.matches();
            }
            return false;
        }

Matcher.match always getting false
did i missed anything there?
did i add any extra parameter?
Expecting a quick responce.

A: 403 response is not related to CORS.
It may be caused by CSRF protection auto-configuration.
You can try disabling it:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}


text:
Q: Fighting with the Rust borrow checker This code looks like it would work fine to me, but the rust borrow checker doesn't like it:
extern crate rustbox;

use std::error::Error;
use std::default::Default;

use rustbox::{Color, RustBox};
use rustbox::Key;

use std::fs::File;
use std::env;
use std::io::BufReader;
use std::io::BufRead;

fn display_screenful(rb: &RustBox, fr: BufReader<&'static File>, offset: usize) {
    for (rline, idx) in fr.lines().zip(0..).skip(offset).take(rb.height()) {
        match rline {
            Ok(line) => (*rb).print(0, idx, rustbox::RB_NORMAL, Color::White, Color::Black, &line),
            Err(_)   => (*rb).print(0, idx, rustbox::RB_NORMAL, Color::White, Color::Black, "")
        }
    }
}

fn main() {
    let rustbox = match RustBox::init(Default::default()) {
        Ok(v) => v,
        Err(e) => panic!(e),
    };

    let path = env::args().nth(1).unwrap();
    let file = match File::open(&path) {
        Ok(file) => file,
        Err(e)   => panic!(e)
    };
    let file_reader = BufReader::new(&file);

    display_screenful(&rustbox, file_reader, 0);
    rustbox.present();

    loop {
        match rustbox.poll_event(false) {
            Ok(rustbox::Event::KeyEvent(key)) => {
                match key {
                    Some(Key::Char('q')) => { break; }
                    Some(Key::Char(' ')) => {
                        display_screenful(&rustbox, file_reader, rustbox.height());
                        rustbox.present();
                    }
                    _ => { }
                }
            },
            Err(e) => panic!("{}", e.description()),
            _ => { }
        }
    }
}

I guess I could not use a separate function, and use two for loop parts, instead, but that isn't idiomatic Rust, nor is it good coding practice. In fact, I've tried that, but it just tells me that I'm using a moved value. Here are some errors that I'm getting:
   Compiling rusted v0.1.0 (file:///Users/christopherdumas/rusted)
src/main.rs:34:39: 34:43 error: `file` does not live long enough
src/main.rs:34     let file_reader = BufReader::new(&file);
                                                     ^~~~
note: reference must be valid for the static lifetime...
src/main.rs:33:7: 55:2 note: ...but borrowed value is only valid for the block suffix following statement 2 at 33:6
src/main.rs:33     };
src/main.rs:34     let file_reader = BufReader::new(&file);
src/main.rs:35
src/main.rs:36     display_screenful(&rustbox, file_reader, 0);
src/main.rs:37     rustbox.present();
src/main.rs:38
               ...
src/main.rs:45:53: 45:64 error: use of moved value: `file_reader` [E0382]
src/main.rs:45                         display_screenful(&rustbox, file_reader, rustbox.height());
                                                                   ^~~~~~~~~~~
src/main.rs:45:53: 45:64 help: run `rustc --explain E0382` to see a detailed explanation
src/main.rs:36:33: 36:44 note: `file_reader` moved here because it has type `std::io::buffered::BufReader<&'static std::fs::File>`, which is non-copyable
src/main.rs:36     display_screenful(&rustbox, file_reader, 0);
                                               ^~~~~~~~~~~
error: aborting due to 2 previous errors
Could not compile `rusted`.

To learn more, run the command again with --verbose.

A: Firstly, you shouldn't ask for a BufReader<&'static File>. You can't provide one. Ask instead for a BufReader<&'a File> for some lifetime 'a.
fn display_screenful<'a>(rb: &RustBox, fr: BufReader<&'a File>, offset: usize)

or, for short,
fn display_screenful(rb: &RustBox, fr: BufReader<&File>, offset: usize)

That's not enough either - you then end up moving file_reader into the function. You should borrow instead:
fn display_screenful(rb: &RustBox, fr: &mut BufReader<&File>, offset: usize)

and then it compiles.


text:
Q: Matplotlib streamplot varying color I intend to make a streamlines plot with varying color indicating the intensity at different points with a 2D array. u,v representing the wind components at different points.
Code:
x = np.linspace(71.679886,100.43091,299) ##longitude
y = np.linspace(10.64794,31.228256,231)  ##latitude
level = [0,5]
for t in level:  ##t is level in output
    U = u[t,:,:]
    V = v[t,:,:]
    f = X[t,:,:]
    SPD = sqrt(u**2+v**2)
    print(SPD)
    pyplot.streamplot(x,y,u,v,density=5,arrowsize=1,integration_direction='forward',color=SPD,cmap="autumn",linewidth=2)
    pyplot.show()

The output should look similar to this:

Link shows that such plots can be made with specifying a 2D array with color, but I get the error: ValueError: RGBA sequence should have length 3 or 4, if I use a 2D array, color=SPD.
Kindly help.


text:
Q: Request Failed Unexpected response from server. The status code of response is '500'. The status text of response is 'internal server error'. null I have created the "Business Intelligence Center Site" and I have to create dashboards.I have activated the required features at site level and site collection level also.Yet when I click on the 'dashboard design' in performancepoint tab of PerformancePoint Content list ribbon, it is showing me error as "Request Failed Unexpected response from server. The status code of response is '500'. The status text of response is 'internal server error'. null ". It was working fine at starting. And I already downloaded the "Dashboard Designer" too. But later on that dashboard designer too is not connecting with the server. Why is it happening so. I did lot of finding and tried many solutions yet it is not working.

A: Check your Event log on the server.  You may have run out of RAM on the SharePoint server.