text:
Q: Laravel Virgin: Disable/mock database connection when testing model mutators that utilize relationships I have the following models:

*

*Grid.php
namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Rover;

class Grid extends Model
{
    /**
     * Table Name
     */
    protected $table='grid';

    public function rovers()
    {
        return $this->hasMany(Rover::class);
    }
}

*

*Rover.php
namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Grid;

class Rover extends Model
{

    /**
     * Table Name
     */
    protected $table='rover';

    public function grid()
    {
        return $this->belongsTo(Grid::class);
    }

    public function setGridPosXValue($value)
    {
        $Grid = $this->grid()->first();
        $width = $Grid->width;
        if($value < 0 || $value > $width){
            throw new \InvalidArgumentException("X is out of grid bounds");
        }

        $this->attributes['x']=$value;
    }

    public function setGridPosYValue($value)
    {
        $Grid = $this->grid()->first();
        $height = $Grid->height;

        if($value < 0 || $value > $height){
            throw new \InvalidArgumentException("Y is out of grid bounds");
        }

        $this->attributes['y']=$value;
    }
}

And I want to test the Rover's mutator with theese tests:
namespace Tests\Unit;

use Tests\TestCase;
use App\Model\Rover;
use App\Model\Grid;
use Mockery;

define("TEST_ROVEL_SUCCESS_VAL",3);
define("TEST_ROVEL_NEGATIVE_VAL",-1);

class RoverModelTest extends TestCase
{
    public function testSetGridPosXValueThrowsExceptionWhenNegative(){
        $this->markTestSkipped('To be implemented');
    }

    public function testSetGridPosXValueThrowsExceptionWhenOverWidth(){
        $rover = new Rover();
        $grid = new Grid();
        $grid->width=5;
        $grid->height=5;
        $rover->grid=$grid;

        $this->expectException(\InvalidArgumentException::class);
        $rover->setGridPosXValue(TEST_ROVEL_NEGATIVE_VAL);

    }

    public function testSetGridPosXValueThorwsExceptionOnNormal(){
        $rover = new Rover();
        $grid = new Grid();

        $grid->width=5;
        $grid->height=5;

        $rover->grid=$grid;
        try {
            $rover->setGridPosXValue(TEST_ROVEL_SUCCESS_VAL);
            $this->assertEquals($rover->x,TEST_ROVEL_SUCCESS_VAL);
        } catch(\Exception $e) {
            $this->fail("No exception should be thrown when setting a correct value.");
        }
    }
}

So when I run the tests I get the following error:
PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

SFF                                                                 3 / 3 (100%)

Time: 125 ms, Memory: 18.00 MB

There were 2 failures:

1) Tests\Unit\RoverModelTest::testSetGridPosXValueThrowsExceptionWhenOverWidth
Failed asserting that exception of type "Illuminate\Database\QueryException" matches expected exception "InvalidArgumentException". Message was: "SQLSTATE[08006] [7] FATAL:  password authentication failed for user "laravel" (SQL: select * from "grid" where "grid"."id" is null limit 1)" at
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:46
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/PostgresConnector.php:33
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php:182
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:918
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:943
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:399
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:325
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:657
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:624
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:333
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2124
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2112
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2598
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2113
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:521
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:505
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php:77
/var/www/html/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php:386
/var/www/html/app/Model/Rover.php:23
/var/www/html/tests/Unit/RoverModelTest.php:28
.

2) Tests\Unit\RoverModelTest::testSetGridPosXValueThorwsExceptionOnNormal
No exception should be thrown when setting a correct value.

/var/www/html/tests/Unit/RoverModelTest.php:44

FAILURES!
Tests: 3, Assertions: 2, Failures: 2, Skipped: 1.

Meaning that the tests hit a misconfigured database connection.
So how I can set a "fake" database connection in order not to use any database at all when testing? The reason why is because I want to do a unit testing instead of an integration testing.
In my case I want the code not to hit the db connection and test the logic that the mutator has without writing into the database at all.

A: You are using $this->grid()->first() instead of $this->grid which forces the use of the database connection to get the grid.
You can probably achieve what you need using a partial mock:
class RoverModelTest extends TestCase
{
    private $rover;

    // Avoid code duplication
    protected function setUp() : void {
        parent::setUp();
        $this->rover = $this->getMockBuilder(Rover::class)
                 ->setMethods('grid')
                 ->getMock();
        $grid = new Grid();
        $grid->width=5;
        $grid->height=5;
        $this->rover->expects($this->any())->method('grid')->willReturn(collect([$grid]));

    }

    public function testSetGridPosXValueThrowsExceptionWhenNegative(){
        $this->markTestSkipped('To be implemented');
    }

    public function testSetGridPosXValueThrowsExceptionWhenOverWidth(){
        $this->expectException(\InvalidArgumentException::class);
        $this->rover->setGridPosXValue(TEST_ROVEL_NEGATIVE_VAL);
    }

    public function testSetGridPosXValueThorwsExceptionOnNormal(){
        try {
            $this->rover->setGridPosXValue(TEST_ROVEL_SUCCESS_VAL);
            $this->assertEquals($this->rover->x,TEST_ROVEL_SUCCESS_VAL);
        } catch(\Exception $e) {
            $this->fail("No exception should be thrown when setting a correct value.");
        }
    }
}


text:
Q: Seeking examples of 3D Maps? Similar to Seeking examples of beautiful maps? is there any similar collection for 3D maps?

A:
This question has been converted to Community Wiki and wiki locked
  because it is an example of a question that seeks a list of answers
  and appears to be popular enough to protect it from closure.  It
  should be treated as a special case and should not be viewed as the
  type of question that is encouraged on this, or any Stack Exchange
  site, but if you wish to contribute more content to it then feel free
  to do so by editing this answer.

Minecraft or at an wider vision: Voxel drawings. Have a great potential for real 3D maps.
Different from raster data that are 2D matrix, a collection of voxels are a 3D matrix and can represent volume.

A: I do a lot of work in 3D, especially landscape visualisation for planning proposals.  The screenshot below shows an example.  I have blurred out the on-screen coordinates and mini-map out of courtesy to the client (although this model has been used in public exhibitions so it is not confidential anymore).  The mini map scrolls with the user and there are hot-keys to toggle elements of the model on and off, jump to pre-programmed locations and a few other tricks like split-screen views showing the model and real-world panoramic photos.  The buildings are very simple in this view as simple extrusions are usually enough, but occasionally something a bit fancier is called for.

At the risk of being accused of advertising (and I respectfully hope that this reference will be seen as relevant in the context of this thread), I also produce hard-copy 3D maps (no computer required). The maps aren't physically 3D but use a special foil and printing technique to give the optical illusion of 3D without squinting.  It's a bit difficult to show an example on the computer sadly as you loose all the 3D effect. You can see an image of an early prototype and get an idea of how it works here.  Please be aware that what you see is a prototype and my main consultancy work has prevented me updating these for ages, until very recently and I was working on new (and visually improved) series just yesterday.

A: recce.at has a stylized 3D map that looks nice:

A: I think that OpenwebGlobe is very nice and promissing project. I do few maps using this library and it looks great and works quite fast IMO.

A: Edushi town maps.
See for example Beijing and Hong Kong:

A: 3D geology also but with GRASS GIS
Severals faults interpolated from boreholes datas (Midi fault in Belgium)

Geological map with fault surfaces interpolated from surface data and drilling data

Surfaces from boreholes data

A: I just want to answer here because I think our project fits somehow here.
We are mainly focused on 3D geology. Thus our maps might look different from what you expect. Behind the map is much more: a database for 3D objects (much like PostGIS, but still different).
This special model shows the geology beyond Dresden, Saxony, Germany:

There is also a model of Switzerland. You can explore it yourself at viewer.geomol.ch:

redpajama_set_name: RedPajamaStackExchange


text:
Q: SDWebImage not setting images in UITableView cells until scroll in Xcode 9.0 beta I have been using SDWebImage in one of my projects for quite long and accidentally happened to open the project up in the recently released Xcode 9.0 beta. The library was working absolutely fine on the previous versions so I can't help but think it's Xcode that's broken it.
The issue I am facing is that the images in UITableView do not get set when the cells are initially loaded. The images are set only when scrolled out of the view and then back in. I have tried setting placeholder images but to no use. Any help would be very much appreciated. I have been banging my head over this for quite a while now and can't find any solutions.

A: Use this is in your code when all the data in tableView is loaded successfully
  dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });

A: So the answer to this, for now, is -
I was giving my UIImageViews a value relative to its height in the following manner -
    cell.userImage.layer.cornerRadius = cell.userImage.frame.size.height / 2;

Changed it to -
    cell.userImage.layer.cornerRadius = 25.0f;

And it's working just fine. Not sure where the issue is but I am assuming that it's got something to with the storyboard/constraints in the Xcode 9.0 beta.


text:
Q: Why page scrolls when showing Jquery-ui dialog Whenever i display a jquery-ui modal dialog scrollbars appear in the page.
this is how i display the dialog
$("#Frmula").dialog({
    autoOpen: false,
    height: 250,
    width: 460,
    modal: true,
    buttons: {
        //'Create an account': function() { },
        Close: function() {
            $(this).dialog('close');
            //$('input:visible:enabled:first').focus();
        }
    },
    close: function() {
    }
});

Any ideas why it happens ?
thanks

A: Sorry for the late posting.
My page was too big containing many divs, tables and iframes. That is why i could not provide a jsfiddle as the code works fine on simpler forms.
Some of the contents in my page are left aligned while others were right aligned. I knew one of those was causing the problem for the jquery-ui to incorrectly determine the dimensions of the dialog.
I tried selectively removing parent divs and table elements one by one and found that one particular div which has float:right was the culprit.
The container div which was inside a iframe was set to float:right. this was causing the scrollbars to appear. I moved float:right from the div to its immediate parent and the problem is solved.
thought it might help others.
Edit : Also watchout for Align property that are set to Right


text:
Q: How do I make the Apache Server point to the /var/www/html directory In a new RHEL 7.5 server, I have created a var directory and within that the /www/html directory in which my website resides. When I try to access the website, I get the Apache Server Test page and mentions that the Apache server is running and I need to point to the /var/www/html directory.
How do I point the Apache Server to the /var/www/html directory?

A: You need to configure the available-sites and enabled-sites and remember to restart apache after changes in the config files.
Have a look at this guide:
https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-14-04-lts#step-four-%E2%80%94-create-new-virtual-host-files


text:
Q: How to store gmail, name and google profile picture using Firebase Auth and Firebase I'm making an Android  application with FireBase and FireBaseAuth for Google Sign in. I have no user-table in my database, so FireBaseAuth doesn't do much other than authenticate the users.
I have a NavigationDrawer in the MainScreen (HomeScreen), where I wish to display the user's profile picture, name and email. Like this example (but with only 1 account / picture):

The user is not Required to sign in to use the app, but some Activities (like Write a Review) requires a user to be signed in. If the user is not signed in, nothing has to be displayed about the user in the NavigationDrawer. However, if there is a signed in user, it's info should be displayed as in the example.
Here is my FireBaseAuth code in ReviewActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reviews);

    //  Setting up the toolbar:
    Toolbar toolbar = findViewById(R.id.Activity_Review_Toolbar);
    toolbar.setTitle("Write a review");

    //  Setting up the database:
    firebaseDatabase = FirebaseDatabase.getInstance();
    firebaseAuth = FirebaseAuth.getInstance();
    reviewDatabaseReference = firebaseDatabase.getReference().child("Reviews");

    firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
            if (firebaseUser != null) {
                // Already logged in
            }
            else {
                onSignedOutCleanup();
                // Not signed in
                startActivityForResult(
                    AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setIsSmartLockEnabled(false)
                        .setAvailableProviders(
                            Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                            new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
                        .build(),
                    RC_SIGN_IN);
            }
        }
    };
}

User sign-in works great, but my question is, how can I store a user's information, based on the Google information from FireBaseAuth? (I'm confident that I will have to create a User-model and a table for users).
Any help is appreciated, thanks!

A: Assuming you are saving data on firebase realtime database.
Step 1.Get user information from signup.
I'm using a simple email and password. Check the firebase auth docs for federated logins
SignUpService
public void signUpWithEmail(String email, String password) {
    this.firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
        if(task.isSuccessful()) {
            //Has the means to create a user (code step 3)
            UserService userService = new UserService();
            //A simple firebase user
            FirebaseUser firebaseUser =  task.getResult().getUser();
            //Your version of a user that is optionally converted from a firebase user
            UserEntity userEntity =  userService.convertFirebaseUserToUser(firebaseUser);
            //create the user (code below)
            userService.create(userEntity).subscribe(reference -> Log.i(SignUpService.TAG, reference.toString()));

        }else{
            Log.e(TAG, "Couldnt sign user up");
        }

    });
    return;
}

Step 2. (Optional) Convert FirebaseUser to a user that fits your business rules
//Takes a firebase user and converts them into a user based on your business rules

public UserEntity convertFirebaseUserToUser(FirebaseUser firebaseUser)
{
UserEntity userEntity = new UserEntity();
    userEntity.setDisplayName(firebaseUser.getDisplayName());
    userEntity.setEmail(firebaseUser.getEmail());
    userEntity.setDisplayPhoto(firebaseUser.getDisplayName());
    userEntity.setKey(firebaseUser.getUid());
    return userEntity;
}

3. Create the user
/**
 * Takes a user entity and creates one
 * @param userEntity
 * @return
 */
public void create(UserEntity userEntity) {
    //initialise your backend
    FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    DatabaseReference databaseReference;

    //retrieve the firebase key for the user you are about to add
    databaseReference = firebaseDatabase.getReference(BASE_PATH).push();
    String key = databaseReference.getKey();
    //create a user hashmap, with the user key as the hashmaps key, and the user entity as the value <K,V>
    Map<String, Object> userEntityHashMap = new HashMap<>();
    userEntityHashMap.put(key, userEntity);

    //create a listenner for your result
    DatabaseReference.CompletionListener completionListener = new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
            //returns the reference to your newly created user
            if(databaseError != null) {
                //handle the incoming user creation error
            }
        }
    };
    databaseReference.setValue(userEntity, completionListener);
    return;
}

In my opinion a better way of doing this would be to have firebase cloud functions do this work for you on user sign up. If you're curious about moving the actual user profile fetching to your database without having to do it on your client, checkout the authentication triggers for firebase cloud functions. It will push all that functionality to the firebase servers to do for you

A: How usually its done, you will store it on the SharedPreference to store the user details such as firebaseToken, userId, firstname..etc


text:
Q: Unwanted line break before  Based on help here (
Use of Javascript with Dojo/Dijit on a WordPress page) I got Dijit half way working using a custom template.
But, I still can't figure out why WP inserts breaks where it does. I'd like to keep as much of the page in the WP Page, and as little in the template as possible.  Worst case, I guess I do it all in a template.  Right now, I have the header in the template, and the form-stuff in the page.
Specifically, why doesn't Width and the textbox for Width show up on the same line (all browsers)?
What I typed in (I put it all one big long line to try to avoid the breaks):
Width:<input type="text" name="controlWidth" value="99" dojoType="dijit.form.TextBox" trim="true" id="controlWidth" propercase="false" style="width: 50px">

What WP puts out:

        Width:

<input type="text" name="controlWidth" value="99" dojoType="dijit.form.TextBox" trim="true" id="controlWidth" propercase="false" style="width: 50px">

Secondly, the ColorPalatte looke good in IE, but not FireFox 5 nor Chrome 12.

A: It was a bug in wpautop() which treated <input> as a block element. It is fixed now. See ticket #16456.


text:
Q: How to test Slate JS behavior in Cypress How can I insert text in a Slate editor with Cypress? The Slate onChange handler doesn't seem to be called while typing with cy.type() or cy.clear().

A: The Cypress input commands (e.g. cy.type() and cy.clear()) work by dispatching input and change events - in the case of cy.type(), one per character. This mimics the behavior of a real browser as a user types on their keyboard and is enough to trigger the behavior of most application JavaScript.
However, Slate relies almost exclusively on the beforeinput event (see here https://docs.slatejs.org/concepts/xx-migrating#beforeinput) which is a new browser technology and an event which the Cypress input commands don't simulate. Hopefully the Cypress team will update their input commands to dispatch the beforeinput event, but until they do I've created a couple of simple custom commands which will trigger Slate's input event listeners and make it respond.
// commands.js
Cypress.Commands.add('getEditor', (selector) => {
  return cy.get(selector)
    .click();
});

Cypress.Commands.add('typeInSlate', { prevSubject: true }, (subject, text) => {
  return cy.wrap(subject)
    .then(subject => {
      subject[0].dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: text }));
      return subject;
    })
});

Cypress.Commands.add('clearInSlate', { prevSubject: true }, (subject) => {
  return cy.wrap(subject)
    .then(subject => {
      subject[0].dispatchEvent(new InputEvent('beforeinput', { inputType: 'deleteHardLineBackward' }))
      return subject;
    })
});

// slateEditor.spec.js
cy.getEditor('[data-testid=slateEditor1] [contenteditable]')
    .typeInSlate('Some input text ');

cy.getEditor('[data-testid=slateEditor2] [contenteditable]')
    .clearInSlate()
    .typeInSlate('http://httpbin.org/status/409');

If you need to support other inputTypes, all of the inputTypes supported by Slate are listed in the source code for editable.tsx

A: As of Cypress v5.5, this now works as expected! No hacks should be required to make it work with Slate.
See https://github.com/cypress-io/cypress/issues/7088.


text:
Q: Get parent Div and then the elements inside I've got some html (note this block of HTML is repeated with the data inside changing):

Jo Bloggs

Widget Maker

England

                <button class="memberMore">MORE INFORMATION</button>

And what I'm trying to do in java is get the actual values from inside the div (ie, Jo Bloggs, Widget Maker, England)
This is what I thought would work:
$(".memberMore ").click(function (e) {
    e.preventDefault();
    //Get the 'parent' div (memberDiv)
    var myDiv = $(this).closest("div");
    alert($(myDiv).next(".myUserName").text());
    return false;
});

But the alert box is showing the 'undefined' error.
Could anyone spare me 5 minutes to show me the error of my ways please?
thanks,
Craig

A: Use find() instead

$(".memberMore ").click(function(e) {
  e.preventDefault();
  //Get the 'parent' div (memberDiv)
  var myDiv = $(this).closest("div");
  console.log($(myDiv).find(".myUserName").text());
  return false;
});

Jo Bloggs

Widget Maker

England

  <button class="memberMore">MORE INFORMATION</button>

A: Try this
$(".memberMore ").click(function (e) {
    e.preventDefault();
    alert($(this).find(".myUserName").text());
    return false;
});

A: You should you the "siblings" function, not the "find", like this:
$(".memberMore ").click(function (e) {
    e.preventDefault();
    alert($(this).siblings(".myUserName").text());
    return false;
});

Fiddle here

A: To return all paragraphs in that div, loop through them:

$(".memberMore ").click(function(e) {
  e.preventDefault();
  //Get the 'parent' div (memberDiv)
  var myDiv = $(this).closest("div");
  var txtReturn = '';
  myDiv.find('p').each(function(index) {
    if (index>0) {
      txtReturn += ', '
    }
    txtReturn += $(this).text()
  });
  alert(txtReturn);
  return false;
});

Jo Bloggs

Widget Maker

England

  <button class="memberMore">MORE INFORMATION</button>

Or you can make it slightly easier by moving the button out of the div, and/or changing it to input type="button" (so it has no inner text).

$(".memberMore").click(function(e) {
  e.preventDefault();
  //Get the 'parent' div (memberDiv)
  var myDiv = $(this).prev("div");
  alert(myDiv.text());
  return false;
});
$(".memberMore2").click(function(e) {
  e.preventDefault();
  //Get the 'parent' div (memberDiv)
  var myDiv = $(this).closest("div");
  alert(myDiv.text());
  return false;
});

Jo Bloggs

Widget Maker

England

  <input type="button" class="memberMore2" value="MORE INFORMATION" />

<button class="memberMore">MORE INFORMATION</button>

A: You can also use the siblings() function to get the text of all elements. If you need to get the string
Jo Bloggs, Widget Maker, England
You could do:

$('.memberMore').on('click', function() {

  var text = $(this).siblings().map(function() {
    return $(this).text();
  }).get().join(', ');

  alert(text);

});

Jo Bloggs

Widget Maker

England

  <button class="memberMore">MORE INFORMATION</button>

A: If you want to show the text of all p, you can try something like:
$(".memberMore ").click(function(e) {
  e.preventDefault();

  $(this).parent().find('p').each(function(index, elemt){
     console.log($(elemt).text());
  });

  return false;
});

The key here is the parent() method.


text:
Q: Приложение react не деплоится на heroku Пытаюсь задеплоить react приложение на heroku. В процессе деплоя выдает ошибку
https://github.com/IlyaChurakov/GigaChat.git

Не могу понять как это исправить.
Также, если я пытаюсь задеплоить build, то ошибка становится такой:

Вот мой билд: https://github.com/IlyaChurakov/GigaChat-for-heroku.git


text:
Q: jcraft, eclipse sftp plugin documentation I installed jcraft, but don't know how to use. is there any documentation available?. I googled, checked their site with no help.

A: THat should be related to this Guide to FTP & WebDAV support, which includes:

*

*Introducing Target Management

*Importing a remote directory into the workspace as a project

*Exporting a folder to a remote directory

*Synchronizing with the remote directory

*FAQ


text:
Q: Mistake in Spivak's *Calculus on Manifolds*? Didn't see this in any of the errata:

Problem 1-8(b): Suppose $T$ is a linear transformation. If there is a basis $x_1, \dotsc, x_n$ of $\mathbb{R}^n$ and numbers $\lambda_1, \dotsc, \lambda_n$ such that $Tx_i = \lambda_i x_i$, prove that $T$ is angle preserving if and only if all $|\lambda_i|$ are equal.

Counterexample: the linear transformation taking $(0,1)$ to itself and $(1,1)$ to $-(1,1)$ does not preserve the angles between those two vectors, although it is diagonalizable with all eigenvalues of norm $1$.
Did Spivak perhaps mean to require that the $x_i$ be an orthogonal basis?


text:
Q: How does one describe people who do not pick up irony, or vibes? I realise that at a severe level this can present as a symptom of Asperger's Syndrome, or High Functioning Autism. But I am not talking about that.
I am referring to people who just don't seem to understand irony. For example, let's say we have a doormat outside our house with the words 'BEWARE OF THE OLD WOMAN' written on it.
I think most people, at least in Britain, would see it as a joke. But some, at the extreme, might expect to meet a fierce old lady. Other's, less afflicted, might think it was a severe instance of political incorrectness. What do we call someone who just doesn't see the joke?
Or let's say that someone comes to dinner and is thoroughly miserable all evening, and the host or hostess just does not pick up on the fact that it is because of a difficulty that the guest has in their lives.
Do we say 'Penelope is 'insensitive'? No that isn't quite the word is it? Because had Penelope understood the reason she would have been as sympathetic as the next person. It was just that it simply never occurred to Penelope that her guest might be feeling sad about something, that she, the guest was not able to talk about. There are people who just don't pick up signs around them. Metaphorically they have no peripheral vision. They only see the obvious, and what is straight in front of them.
How do we describe such people?

A: This is really two questions together.
The person who fails to understand irony I would call humour-challenged, humourless or simply [excessively] serious.
The one who fails to pick up on other people's moods or mental states is unobservant, oblivious, unaware or incognizant, or possibly even self-absorbed, literal-minded or tunnel-visioned.

A:
thick

*informal
  of low intelligence; stupid.
  "he's a bit thick"

  [ODO]

A: For me the obvious choice would be oblivious [TheFreeDictionary], but there are others: unself-aware, immune to irony, obtuse, etc.

A: Collins gives overliteral :

overliteral ...
adjective
literal to a fault

where of course the sense of 'literal' used is that defined by Google Dictionary:

literal  adjective

*

*taking words in their usual or most basic sense without metaphor or exaggeration.

A: By coincidence, my colleague coined this pun today: A person who doesn't "get" irony suffers from an irony deficiency.

A:
serious

or

earnest

or

sincere

These don't imply a lack of sense of humor, but rather the default state of taking things at face value.


text:
Q: How to reset or clear the bootstrap datetimepicker? How to reset or clear the datetimepicker? I can't find solution for this bootstrap datetimepicker version. I don't want to use the default clear. As you can see there's a highlighted day, using a reset it should clear the highlighted day and display the plain datetimepicker.

$('.select2').select2({

});

$('#apptDay').datetimepicker({
  format: 'L'
});

$("#apptDay").on("show.datetimepicker update.datetimepicker", function(e) {
  highlight()
});

function highlight() {
  var dateToHilight = ["11/21/2022", "11/25/2022", "12/30/2022"];
  var array = $("#apptDay").find(".day").toArray();

  for (var i = 0; i < array.length; i++) {
    var date = array[i].getAttribute("data-day");

    if (dateToHilight.indexOf(date) > -1) {
      array[i].style.color = "orange";
      array[i].style.fontWeight = "bold";
    }
  }
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<link rel='stylesheet' href='https://rawgit.com/tempusdominus/bootstrap-4/master/build/css/tempusdominus-bootstrap-4.min.css'>

    Select Doctor
    *
    <select class="form-control select2 select2-hidden-accessible" style="width: 100%;" tabindex="-1" aria-hidden="true">
      <option selected="selected">Alabama</option>
      <option>Alaska</option>
      <option>California</option>
      <option>Delaware</option>
      <option>Tennessee</option>
      <option>Texas</option>
      <option>Washington</option>
    </select>

      <input name="day" type="text" class="form-control datetimepicker-input" data-target="#apptDay" placeholder="mm/dd/yyyy" value="" />

A: It's easy to remove the styles if you set a class (instead of modifying the style property):
if (dateToHilight.indexOf(date) > -1) {
  array[i].classList.add('highlighted');
}

and define the styles with CS:
.highlighted {
  color: orange;
  font-weight: bold;
}

Then you could simply remove that class in any case, you want:
$('.highlighted').removeClass('highlighted');

To highlight different dates depending on the value of a select element, you could define a global var (maybe country) and save the value of the select in this var:
var country = 'Alabama';

$(".select2").on("change", function() {
  country = $(this).val();
});

Then you only need to define your dates, that you want to highlight in a multi dimension array or object with the values of the select element as keys:
var dateToHilight = {
    'Alabama': ["11/21/2022", "11/25/2022"],
    'Alaska': ["11/23/2022", "11/29/2022"],
    'California': ["11/17/2022", "11/18/2022"],
    'Delaware': ["11/19/2022", "11/26/2022"],
    'Tennessee': ["11/20/2022", "11/30/2022"],
    'Texas': ["11/15/2022", "11/24/2022"],
    'Washington': ["11/14/2022", "11/27/2022"],
};

and modify the highlighting if to select the second dimension with that key:
if (dateToHilight[country].indexOf(date) > -1) {
  array[i].classList.add('highlighted');
}

Working example: (for demonstration with a keyup event)

var country = 'Alabama';

$('.select2').select2({});

$('#apptDay').datetimepicker({
  format: 'L'
});

$("#apptDay").on("show.datetimepicker update.datetimepicker", function() {
  highlight();
});

$(".select2").on("change", function() {
  country = $(this).val();
});

function highlight() {
  var dateToHilight = {
    'Alabama': ["11/21/2022", "11/25/2022"],
    'Alaska': ["11/23/2022", "11/29/2022"],
    'California': ["11/17/2022", "11/18/2022"],
    'Delaware': ["11/19/2022", "11/26/2022"],
    'Tennessee': ["11/20/2022", "11/30/2022"],
    'Texas': ["11/15/2022", "11/24/2022"],
    'Washington': ["11/14/2022", "11/27/2022"],
  };
  var array = $("#apptDay").find(".day").toArray();

  for (var i = 0; i < array.length; i++) {
    var date = array[i].getAttribute("data-day");

    if (dateToHilight[country].indexOf(date) > -1) {
      array[i].classList.add('highlighted');
    }
  }
}
.highlighted {
  color: orange;
  font-weight: bold;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<link rel='stylesheet' href='https://rawgit.com/tempusdominus/bootstrap-4/master/build/css/tempusdominus-bootstrap-4.min.css'>

    Select Doctor
    *

    <select class="form-control select2 select2-hidden-accessible" style="width: 100%;" tabindex="-1" aria-hidden="true">
      <option selected="selected">Alabama</option>
      <option>Alaska</option>
      <option>California</option>
      <option>Delaware</option>
      <option>Tennessee</option>
      <option>Texas</option>
      <option>Washington</option>
    </select>

      <input name="day" type="text" class="form-control datetimepicker-input" data-target="#apptDay" placeholder="mm/dd/yyyy" value="" />


text:
Q: JMH - Benchmarking Neo4j I am currently trying to benchmark 2 different implementations of a database model using JMH and one of them is Neo4j.
The problem I am facing is that the measured time is vastly different to the time shown in the Neo4j Browser.
Using JMH:
Benchmark             Mode  Cnt     Score   Error  Units
Neo4j_JDBC.run        avgt       2434.298          ms/op
NEO4j_EMBEDDED.run    avgt          0.316          ms/op

In the Neo4j Browser:
Started streaming 1 records after 2 ms and completed after 2 ms.

The query is the same, no matter if I take the embedded server or the remote one connected using JDBC.
JMH Code:
@Setup
    public void setup() throws SQLException {
        con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost", "neo4j", "password");
    }

    @TearDown
    public  void  tearDown() throws SQLException {
        con.close();
    }

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.MILLISECONDS)
    @Measurement(iterations = 1, time = 1)
    @Fork(1)
    public void run() throws SQLException {
            String query = "query...";
            Statement st = con.createStatement();
            st.executeQuery(query);
    }

The implementation is taken straight from the documentation
The opposite is the case for the second data model though, that is using a MySQL server.
There the 'real' execution speed in DataGrip (that is also using JDBC) is shown to be ~ 100ms and my benchmark shows around 1.6ms/ops.
Am I missing something in my configuration?
Is this even the correct way to benchmark different database systems with different models?
Any help is appreciated!
edit: I updated the JMH code to not measure the connection instantiation and now I get the following results when comparing Neo4j with MySQL:
Benchmark                 Mode  Cnt   Score   Error  Units
MYSQL_JDBC.run            avgt        1.224          ms/op
Neo4j_JDBC.run            avgt       18.580          ms/op

The MySQL code is pretty much the same as above just with a different JDBC URL.
Execution-time in Datagrip for the MySQL query:
1 row retrieved starting from 1 in 301ms (execution: 202ms, fetching: 99ms)

Obviously the more often I execute it, the faster it is but the lowest it has been in Datagrip was 45ms. Not even close to the 1.2 ms/op I measured using JMH.
Is it maybe a caching issue? Or is it not measuring properly?

A: You are also measuring the time that it takes to set up a connection to the database in JMH, while directly interacting with the database does not. Try refactoring the Connection into a field and set it before executing performance tests.


text:
Q: How do you configure prometheus.yml file to collect Prometheus metrics in a Spring-Boot application? I have a simple Maven Spring-Boot Application (Java) and am using Prometheus to collect metric information from it. I have all of the necessary Prometheus dependencies in my pom file, and I have included the @EnablePrometheusEndpoint annotation to my @SpringBootApplication class, and have included "metrics_path: '/prometheus' " in my prometheus.yml file (as shown below), but am receiving a 406 error when I try to access the metrics (on localhost:8080/prometheus). How should i modify my prometheus.yml file to see my exported metrics?
Below is all of the (simple) spring boot code I am looking to instrument:
@SpringBootApplication
@RestController
@EnablePrometheusEndpoint
public class Example {

    //Just a logger that keeps track of relevant information:
    private static final Logger LOGGER = Logger.getLogger(Example.class.getName());

    //counter for counting how many times an endpoint has been hit
    static final Counter myCounter = Counter.build()
                                              .name("CounterName") //note: by convention, counters should have "_total" suffix
                                              .help("Total requests recorded by a specific endpoint")
                                              .labelNames("status")
                                              .register();
    @RequestMapping("/hello")
    String hello() {

        myCounter.labels("customLabel1").inc(); //increment the number of requests by one
        LOGGER.log(Level.INFO, "Number of times /hello has been hit: " + myCounter.labels("customLabel1").get());

        return "Hello world! This is an example response!";
    }

    @RequestMapping("/homepage")
    String homePage() {

        myCounter.labels("customLabel2").inc(); //increment the number of requests by one
        LOGGER.log(Level.INFO, "Number of times /homepage has been hit: " + myCounter.labels("customLabel2").get());

        return "this is the home page!!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}

pom.xml file with all required prometheus dependencies:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Prometheus dependencies -->
        <!-- The client -->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_spring_boot</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_servlet</artifactId>
            <version>0.1.0</version>
        </dependency>
        <!-- Hotspot JVM metrics -->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_hotspot</artifactId>
            <version>0.1.0</version>
        </dependency>
        <!-- Exposition HTTPServer -->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_httpserver</artifactId>
            <version>0.1.0</version>
        </dependency>
        <!-- Pushgateway exposition -->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_pushgateway</artifactId>
            <version>0.1.0</version>
        </dependency>

        <!-- Spring Boot Actuator for exposing metrics -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>1.5.8.RELEASE</version>
        </dependency>

    </dependencies>

</project>

And below is my prometheus.yml file. note, the last few lines are where I specified to prometheus what to scrape, and i suspect this is where my problem is:
# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

  # Attach these labels to any time series or alerts when communicating with
  # external systems (federation, remote storage, Alertmanager).
  external_labels:
      monitor: 'codelab-monitor'

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first.rules"
  # - "second.rules"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.
    scrape_interval: 5s

    static_configs:
      - targets: ['localhost:9090']

#The following lines are meant to monitor my  spring boot app
  - job_name: 'hello_world_spring_boot'
    scrape_interval: 5s

    metrics_path: '/prometheus'

    static_configs:
      - targets: ['localhost:8080']

A: As you are using Spring boot, you can use the following Prometheus maven dependencies
<dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_spring_boot</artifactId>
            <version>0.0.17</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_hotspot</artifactId>
            <version>0.0.17</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_servlet</artifactId>
            <version>0.0.17</version>
        </dependency>

Remove the @EnablePrometheusEndpoint and create the following class to enable propagating metrics
@Configuration
public class MonitoringConfig {

    @Bean
    SpringBootMetricsCollector springBootMetricsCollector(Collection<PublicMetrics> publicMetrics) {

        SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics);
        springBootMetricsCollector.register();

        return springBootMetricsCollector;
    }

    @Bean
    ServletRegistrationBean servletRegistrationBean() {
        DefaultExports.initialize();
        return new ServletRegistrationBean(new MetricsServlet(), "/prometheus");
    }
}

Now, if you hit the endpoint /prometheus, you should get the metrics


text:
Q: How to map a domain name to node.js http server on Windows 2008/IIS 7? I can't find any article which explains this. Someone does know ? thanks.
Problem is my domain is already mapped to IIS 7 through port 80. I want to map to same domain but to another port how would you do so ?

A: see http://blogs.iis.net/wonyoo/archive/2008/07/09/application-request-routing-arr-as-a-reverse-proxy.aspx
which requires you to download: http://www.iis.net/download/ApplicationRequestRouting

Basically you create a "re-write rule" using a IIS Extension called "Application Request Routing"


text:
Q: nrow returns null value for only one row in R When I subset just one row of a matrix and pass that to nrow as nrow(x[1,]) or nrow(x[2,]) it returns a NULL value instead of 1.
However if I subset more than one row then nrow(x[1:2,]) returns 2 which is a correct value.
Need help on how to handle cases like nrow(x[i,]).
Thanks in advance.

A: You can use NCOL() and NROW(), they treat vectors as 1-column matrix, i.e
x <- structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1), .Dim = c(3L, 3L))
x
#>      [,1] [,2] [,3]
#> [1,]    1    1    1
#> [2,]    1    1    1
#> [3,]    1    1    1

Now, as you point out nrow(x[1,]) and nrow(x[2,]) return NULL
nrow(x[1,])
#> NULL
nrow(x[2,])
#> NULL

but,
NCOL(x[1,])
#> [1] 1
NROW(x[1,])
#> [1] 3

You could also make the object a tibble, but I guess you don't want to go there with a matrix. Regardless,
# install.packages(c("tidyverse"), dependencies = TRUE)
library(tidyverse)

z <- x %>% as_tibble()

nrow(z[1,])
#> [1] 1
ncol(z[1,])
#> [1] 3

A: You can also use drop = FALSE in subsetting the matrix, which provides R from dropping the matrix class:
(m <- matrix(1, 3, 3))
#>      [,1] [,2] [,3]
#> [1,]    1    1    1
#> [2,]    1    1    1
#> [3,]    1    1    1
class(m[1, ])
#> [1] "numeric"
class(m[1, , drop = FALSE])
#> [1] "matrix" "array"

Then nrow() returns the desired result:
nrow(m[1, , drop = FALSE])
#> [1] 1
nrow(m[2, , drop = FALSE])
#> [1] 1


text:
Q: Query to search for 2 years and exclude 1 My apologies for the oddly worded question as I wasn't quite sure how I would name the title without explaining the situation.
I am currently working with a vendor table which gives a unique ID to each vendor, but the table is not normalized.
For example the ID 100000003744450  appears multiple times in the table with a different data in each row.
There are many columns but the only ones that matter to me at the moment are the ID and the year column.  I am attempting to find the vendors who have rows for 2013, 2014 but not 2015.
So far I have:
select *
from table
where ls_d_yr = '2013'
   or ls_d_yr = '2014'

I need to filter this results by removing any of the vendors that have the year 2013/2014 and should not have any rows with 2015 listed.
Here are the column

A: If one of 2013 and 2014, use NOT EXISTS to exclude ID's having ls_d_yr in 2015.
select *
from table t1
where ls_d_yr IN ('2013', '2014')
  and not exists (select 1 from table t2
                  where t2.ID = t1.ID
                    and t2.ls_d_yr = '2015')

If both 2013 and 2014 are required, add a GROUP BY and use HAVING to make sure two different years are provided:
select ID
from table t1
where ls_d_yr IN ('2013', '2014')
  and not exists (select 1 from table t2
                  where t2.ID = t1.ID
                    and t2.ls_d_yr = '2015')
group by ID
having count(distinct ls_d_yr) = 2

A: You can use NOT EXISTS for this:
select *
from table AS t1
where ls_d_yr IN ('2013', '2014') AND
      NOT EXISTS (SELECT 1
                  FROM table AS t2
                  WHERE t1.ID = t2.ID AND ls_d_yr = '2015')

A: Another variation, should work in both Teradata and Aster (and probably every other DBMS):
select vendor
from table
where ls_d_yr in ('2013','2014','2015') -- probably numbers instead of strings?
group by vendor
having min(ls_d_yr) = '2013' -- at least one row from 2013
   and max(ls_d_yr) = '2014' -- at least one row from 2014, but none from 2015

A: One method for doing this uses aggregation and having:
select t.vendor
from table t
group by t.vendor
having sum(case when ls_d_yr = '2013' then 1 else 0 end) > 0 and
       sum(case when ls_d_yr = '2014' then 1 else 0 end) > 0 and
       sum(case when ls_d_yr = '2015' then 1 else 0 end) = 0;

Each condition in the having clause tests for one year.  The > 0 means that one or more records exist for the year.  The = 0 means that no record exists.
This logic is based on the statement:  "I am attempting to find the vendors who have rows for 2013, 2014 but not 2015."  I don't follow the logic in the last paragraph.

A: select to_char(id), ls_d_yr
  from table
 where ls_d_yr like '%2014%'
    or ls_d_yr like '%2013%';

something like that.


text:
Q: COUNTIFS with value to be tested being an array
I am trying to perform a COUNTIFS function based on whether the cell value to be tested (the col sample data) appears in a array of values (Excel sample col).
Obviously to do a COUNTIFS is easy enough:
=COUNTIFS(  $E$3:$E$13,A6   ,$F$3:$F$13,"<"&EOMONTH($B$3,1), $F$3:$F$13, ">="&DATE(YEAR(B$3),MONTH(B$3),1), $G$3:$G$13, "<12")

Where the column E in the function is equal to one value, in this case a6. But where I am having issues is to test to check if in an array of values i.e. in this example the cells a5 & a6.
Has anyone any ideas? (aside from the obvious counting individually, there are a lot more than two values in the array!)
https://docs.google.com/spreadsheets/d/1QYbXwIdFEdjXqlLjF0b0jSusZNuqOMaUKVKZrjR4wko/edit?usp=sharing

A: I couldn't find a solution to this using a few different combinations, the majority of functions I know need a single reference cell.
so VBA version:
Function ARRAYMATCHS(RefRng As Range, DataRng As Range, DateRng As Range, RefMonth As String, MonthsRng As Range, Months As Integer)

    Dim x As Integer
    Dim c As Integer
    x = 0
    c = 0

    For Each cell In DataRng
    c = c + 1
        If Not IsError(Application.Match(cell.Value, RefRng, 0)) Then
           If (MonthsRng(c, 1) > Months) Then
                If (Month(DateRng(c, 1)) = RefMonth) Then
                    x = x + 1
                End If
           End If
        End If
    Next cell

    ARRAYMATCHS = x

End Function

Which works fine but I would be interested in any native combinations of functions that could have done this!


text:
Q: How can i replace a specific word in a string in swift? I am looking for a way to replace a word inside a string in swift. Can anyone help?
this is what I have so far, I can find the specific word, but i do not know how to replace it...
     var str = "helo, playgound"

     var findWords = ["helo","playgound"]
     var replaceWords = ["hello","playground"]

extension String {
    var wordList:[String] {
        return "".join(componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet())).componentsSeparatedByString(" ")
    }
}

func stringToArray() -> Array<String> {
    var arr = str.wordList
    return arr
}

func correction(var _arr:Array<String>) -> String{

    for var i = 0; i < _arr.count; i++ {
            if str.lowercaseString.rangeOfString(findWords[i]) != nil {
                println("exists")
        }
      }
  return str
}

A: It depends what your definition of a "word" is. If you're looking for an intelligent built-in notion of a "word", the easiest solution is probably to use NSRegularExpression, which knows where "word" boundaries are:
var s = NSMutableString(string:"hello world, go to hell")
let r = NSRegularExpression(
    pattern: "\\bhell\\b",
    options: .CaseInsensitive, error: nil)!
r.replaceMatchesInString(
    s, options: nil, range: NSMakeRange(0,s.length),
    withTemplate: "heaven")

After that, s is "hello world, go to heaven", which is the right answer; we replaced the "hell" that is a word, but not the "hell" in "hello". Notice that we are also matching case-insensitively, which seems to be one of your desiderata.
That example shows how do just one pair ("hell" and "heaven") but it is easy to abstract it into a method so that you can do it again and again for further pairs:
var str = "helo, playgound"

var findWords = ["helo", "playgound"]
var replaceWords = ["hello", "playground"]

func correct(str:String, orig:String, repl:String) -> String {
    var s = NSMutableString(string:str)
    let r = NSRegularExpression(
        pattern: "\\b\(orig)\\b",
        options: .CaseInsensitive, error: nil)!
    r.replaceMatchesInString(
        s, options: nil, range: NSMakeRange(0,s.length),
        withTemplate: repl)
    return s
}

for pair in Zip2(findWords,replaceWords) {
    str = correct(str, pair.0, pair.1)
}

str // hello, playground

A: The easiest is probably this:
let statement = "Swift is hard."
let swiftRange = statement.startIndex..<advance(statement.startIndex, 5)
let newStatement = statement.stringByReplacingCharactersInRange(swiftRange, withString: "Objective-C")
// now newStatement = "Objective-C is hard."

Following a longer commenting tour: The above is under the assumption of the OP "I can find the specific word, but i do not know how to replace it...", so it's not about finding a "word" which to define is another discussion. It's just about replacing an already found word.
Another word on stringByReplacingCharactersInRange: @matt states that this is Cocoa cross-over. In that case Apple is telling a plain lie:

I fostered the web but there's no Apple source telling anything. Only the Foundation method for NSString. Their Swift book is silent too (in many respects). Well, I don't trust Apple anyway any longer since Yosemite-fail.


text:
Q: How can I draw Op-Amp diagrams using circuitikz? I'm writing a thesis for the school where I go at and I need to draw the following Op-Amps configurations:

*

*inverting configuration

*non-inverting configuration

*differential configuration

*inverting adder amplifier

*non-inverting adder amplifier

So far I only have been able to draw the first configuration with the following code:
\begin{circuitikz}
\draw (0, 0) node[op amp] (opamp) {}
      (opamp.-) to[short,-*] ++(-1, 0) coordinate(A)
      (opamp.+) -| ++(-1,-1) node[ground](B){}
      (opamp.out) to[short,*-o] ++(1, 0) coordinate(C)
      (A) to[R,l_=$R_1$,-o] ++(-2, 0) -- ++(-1, 0) coordinate(D) to [V<=$v_1$] (D |- B) node[ground]{}
      (A) |- ++(1,1) coordinate[yshift=1ex] (L1) to[R=$R_2$] ++(2,0) -| (opamp.out) to[short,-o] ++(1,0)
;
\end{circuitikz}

And this is the result I got:

Can someone help me with the code of the other configurations maintaining the same style as the one I got?
Thanks in advance!
Samuel.

A: OK. Let me copy here what will be a new tutorial I added to the manual. You can find it on the circuitikz page (in the PDF you'll also find a suggestion on how to re-use the shape).
Tutorial: A non-inverting op-amp amplifier
Let's now try to draw a non-inverting amplifier based on op-amps; the canonical implementation can be, for example, this one from ''electronics tutorials''.
Obviously, the style and form of drawing a circuit is often a matter of personal tastes and, maybe even more important, of the details you are focusing on; drawing a non-inverting amplifier will be different if you are drawing it to explain how it works or if you are simply using it in a more complex circuit, assuming its operation well known by the reader. Anyway, the final objective is to have a circuit like the one below, drawn so that it is easy to reuse.

We have to start the drawing from a generic point. Given that the idea is to have a reusable block, instead of positioning the op-amp and build around it, we will start from the input ''pole'':
\begin{circuitikz}[]
    \draw (0,0) node[above]{$v_i$} to[short, o-] ++(1,0)
    node[op amp, noinv input up, anchor=+](OA){\texttt{OA1}}
    ;
\end{circuitikz}

In this snippet, notice that the only absolute coordinate is the first one; that will enable us to ''copy and paste'' the circuit in several places, or create a macro for it. We position a text node above it, and then draw a wire with a pole to a relative (1,0) coordinate: in other words, we move 1 unit to the right drawing a short-circuit, which is the same as a wire. The usage of to[short...] simplifies the position of the pole, but notice that we could have also written:
\draw (0,0) node[above]{$v_i$} node[ocirc]{} -- ++(1,0) ...

with the same result.
The second step is to position the op-amp. We can check the manual and see the component's description:

where we notice the type of the component (it is a node-type component, so we have to use
node to position it) and the available ''anchors'': points we can use to position the shape or to connect to. Not all the anchors are explicitly printed in the description box; you should read further in the manual and you'll see a ''component anchors'' section with the relevant information.
Anyway, the op-amp must be connected with the +  anchor to our input wire, so we say anchor=+ in the option lists; this shifts the whole element so that the named anchor will lie at the current position of the path. Moreover, normally the shape has the inverting input on the bottom side, and we want it the other way around, so we use also noinv input up in the keys defining the node. We could also have flipped the shape with yscale=-1, but in this case, we should have considered the effects on anchors and on the text; see section mirroring and flipping in the manual.
Now we can draw the resistors; let's start with R1. We will draw it going down vertically from the - anchor — we have named the node OA so that will be OA.-. We will need to connect the R2 also, so we do the following:

*

*draw a wire going down, and mark a point where we want the feedback resistor to connect;

*then draw R1 and finally

*draw the ground node.

\begin{circuitikz}[scale=0.8, transform shape]
    \draw (0,0) node[above]{$v_i$} to[short, o-] ++(1,0)
    node[op amp, noinv input up, anchor=+](OA){\texttt{OA1}}
    (OA.-) -- ++(0,-1) coordinate(FB)
    to[R=$R_1$] ++(0,-2) node[ground]{}
    ;
\end{circuitikz}

We only miss the feedback resistor now. We will use orthogonal coordinates, writing:
\draw (FB) to[R=$R_2$] (FB -| OA.out) -- (OA.out);

The meaning is the following:

*

*move the current point to the coordinate named FB;

*put a resistor, with label R2, from here to...

*the coordinates which is on the horizontal of FB and on the vertical of OA.out: the -| coordinate operation is quite mnemonic;

*the continue drawing to OA.out.

You can use a separate \draw command or just continue the path you were writing; the choice is just personal preference, but be warned that it can affect the drawing of poles (see section ''poles (also called nodes)'' in the manual about this if you notice strange things).
Finally, we add the output and a couple of poles:
\begin{circuitikz}[scale=0.8, transform shape]
    \draw (0,0) node[above]{$v_i$} to[short, o-] ++(1,0)
    node[op amp, noinv input up, anchor=+](OA){\texttt{OA1}}
    (OA.-) -- ++(0,-1) coordinate(FB)
    to[R=$R_1$] ++(0,-2) node[ground]{}
    (FB) to[R=$R_2$, *-] (FB -| OA.out) -- (OA.out)
    to [short, *-o] ++(1,0) node[above]{$v_o$}
    ;
\end{circuitikz}

The last step to obtain the final look is to add a bit of styling. We want the op-amp filled with a light cyan color, and we prefer to have the label aligned with the left side of the device:
\ctikzset{amplifiers/fill=cyan!20, component text=left}
\begin{circuitikz}[scale=0.8, transform shape]
    \draw (0,0) node[above]{$v_i$} to[short, o-] ++(1,0)
    node[op amp, noinv input up, anchor=+](OA){\texttt{OA1}}
    (OA.-) -- ++(0,-1) coordinate(FB)
    to[R=$R_1$] ++(0,-2) node[ground]{}
    (FB) to[R=$R_2$, *-] (FB -| OA.out) -- (OA.out)
    to [short, *-o] ++(1,0) node[above]{$v_o$}
    ;
\end{circuitikz}

The \ctikzset command choosing the style is better placed in the preamble, though. Style should be coherent for all the document body, so avoiding stating it for every circuit is normally the best strategy.


text:
Q: How to setup the "Loading Data from a Server" example on the EmberJS homepage within an Ember CLI structure? I'm attempting to teach myself EmberJS basics using EmberCLI and such. Ran into one folder structure hitch which Henry Vonfire helped me understand and clear up.
Now that I have my "sea legs" a bit more stable, I am attempting to implement the "Loading Data from a Server" example from the official EmberJS homepage. I can get the app to run, but apparently no data is returned or rendered to the frontend despite the inspector clearly showing data is being properly fetched in my browser. Why is my "handlebars" template not parsing the data?
My environment is as follows:

*

*Ember CLI version: 1.13.12

*Node JS version: 4.2.2

*NPM (Node Package Manager) version: 2.14.10

*Watchman: 4.1.0

And my simple/humble controller structure is as follows:

*

*app/routes/pull-requests.js

*app/templates/pull-requests.hbs
And the content of each is as follows:
Contents of app/routes/pull-requests.js:
import Ember from 'ember';

export default Ember.Route.extend({
  setupController: function(controller) {
    controller.set('title', "Pull Requests");
  },
  activate: function() {
    document.title = "Pull Requests";
  },
  model: function() {
    return Ember.$.getJSON('https://api.github.com/repos/emberjs/ember.js/pulls').then(function(data) {
      return data.splice(0, 3);
    });
  }
});

Contents of app/templates/pull-requests.hbs:

{{title}}

This is where we would be parsing raw pull request data.

Last 3 Pull Requests to Ember.js

{{#each model as |pr|}}

#{{pr.number}}

      {{pr.title}}

      Opened by @{{pr.head.user.login}}

{{/each}}

{{outlet}}

Initially I had some CORS issues that were cleared up by setting the following contentSecurityPolicy block in config/environment.js:
contentSecurityPolicy: {
  'default-src': "'none'",
  'script-src': "'self'",
  'font-src': "'self'",
  'connect-src': "'self' https://api.github.com/",
  'img-src': "'self'",
  'style-src': "'self'",
  'media-src': "'self'"
},

Now the page simply loads without an error, but without iterating through the data. What's up? Is this something that should be rejiggered into a code block in models/pull-requests.js? Or is there some syntax error with app/templates/pull-requests.hbs that is causing it to fail in some way? Or is it something else?
UPDATE: So Kitler's answer unlocked the core reason this setup was failing. I accidentally overwrote setupController with my code logic without returning it's data. And while I can indeed override it, I should have set return this._super(); by not doing that I was effectively wiping model from the rest of the router chain. But I am posting this update to show what I specifically adjusted in app/routes/pull-requests.js so anyone else may benefit from this solution.
The original setupController code I had was this:
setupController: function(controller) {
  controller.set('title', "Pull Requests");
},

Note how it only has the controller being passed to the interface? To make it work in my setup I had to add model and then return this._super(controller, model) like this:
setupController: function(controller, model) {
  controller.set('title', "Pull Requests");
  return this._super(controller, model);
},

With that set, it all works as expected!

A: Your problem here (most probably) is that you overwrite the setupController method and do not return super, what setupController does is set the model property on your controller.
What you would want to do is return this._super(...arguments) after controller.set('title', "Pull Requests");


text:
Q: The probabilities of uniform distribution variables $P(X_1>X_2)$ and $P(X_2>X_1)$ Let $X_1$ and $X_2$ be two independent random variables with the discrete uniform distribution:
$$X_1,X_2\sim\text{Ud}(1,N)$$
I need to find the probabilities that $P(X_1=X_2)$, $P(X_1>X_2)$, $P(X_2>X_1)$.
I can easily find the first one, by saying that:
$$\sum_{K=1}^N P(X_1=K)\times P(X_2=K)$$
* So, $P(X_1=K)$ and $P(X_2=K)$ both equal to $\cfrac1N$ (because of the distribution type), then we get $\cfrac1{N^2}$ after multiplying them.

*

*For the sigma: $\sum_{k=1}^N$ equals to $N$ because there are no any $k$'s inside the sigma, hence we get:
$$N\times\cfrac1{N^2}=\cfrac1N$$
I couldn't figure out how to solve it (in the same way as I did) in the other cases.

A: The calculations imply a discrete uniform distribution. If you make a table between the outcomes of $X_1$ and $X_2$, you will see that all outcomes where $X_1>X_2$ lie on one side of the line where $X_1=X_2$, and all outcomes for $X_1<X_2$ lie on the other side. Indeed, $X_1>X_2$ and $X_1<X_2$ are equally likely; together with $X_1=X_2$ they partition the sample space. Thus
$$P(X_1>X_2)=P(X_1<X_2)=\frac12\left(1-\frac1N\right)=\frac{N-1}{2N}$$

A: You should break the probability into simpler chunks by using conditional probabilities.
Write:
$$P(X_1>X_2)=\sum_{k=1}^N P(X_1>X_2\mid X_2=k)P(X_2=k)$$
Now, the two probabilities in that sum are easy to work out, and the sum can then be calculated, although you're going to need this formula.

A: In general, you can apply the law of total probability.
The general statement is $ P(A) = \mathbb{E}(P(A \mid B)) $ for random variables $ A $ and $ B $.
For instance,
\begin{equation}
\begin{aligned}
P(X_2 < X_1)
& = \mathbb{E}(P(X_2 < X_1 \mid X_1)) \\
& = \sum_{i=1}^N P(X_2 < X_1 \mid X_1 = i)P(X_1 = i) \\
& = \sum_{i=1}^N P(X_2 < X_1 \mid X_1 = i)\frac{1}{N} \\
& = \sum_{i=1}^N \frac{\sum_{j=1}^i j}{N} \frac{1}{N} \\
& = \frac{1}{N} \sum_{i=1}^N \frac{\sum_{j=1}^i j}{N} \\
& \vdots
\end{aligned}
\end{equation}
I won't finish the entire problem for you, but the general approach is there!


text:
Q: How To implement LuceneNet using Amazon S3 I'm trying to implement Lucene in my app using Amazon S3 to storage the indexes that I generate, but I can find any code examples or a clear article. So anyone that have some kind of experience with this please give a guide or something that can help me start

A: There's a similar question here.
Here's an interesting article of how the biggest Solr service provider Lucid Imagination proposes to deploy their Solr implementation on EC2.
And here's their Search-as-a-Service solution.
If you're not bound to S3, you can use dedicated Solr cloud service called WebSolr.
Also, if you need complete ALM/CI solution for your development project, there's a WebSolr module included in CloudBees.


text:
Q: DIV with "position:absolute;bottom:0" doesn't stick to the bottom of the container in Firefox I have this HTML source:
<!DOCTYPE html>

        <title>Stylish Web Page</title>

The footer is supposed to appear at the bottom of the page, and it does so in Opera and Chrome; However, in Firefox, there's a lot of empty room following the footer. What am I doing wrong? How to fix it?
Here's a screenshot: The blue highlight is the footer.
(Please note: "position: fixed" is not what I want; I want the footer to show up at the bottom of the page, not the browser window.)

A: The issue in Firefox is caused by display:table. Essentially you are telling Firefox to treat this element as a table.
In Firefox position:relative is not supported on table elements. It isn't a bug though, as in the spec the treatment of position:relative table elements is undefined.
This means that in your example the footer is being positioned relative to the window and not the container.
One solution is to use display:block instead or just remove the display rule entirely. You will see the footer will drop down to its rightful place.
A second solution would be to wrap another non-table div around the container and set position:relative to that instead.
A third option is to add position:relative to the body. Live example: http://jsfiddle.net/tw16/NbVTH/
body {
    padding: 0;
    margin: 0;
    position: relative; /* add this */
}

A: What version of FF do you have? In FF 6 it displays correctly: http://screencast.com/t/zAjuG8FP99nX
Have you cleared the cache? Maybe there's something left from previous versions of the page.
Did you close the Firebug window? That pushes the content up when open.
Later edit: the last line means: "after you close firebug, scrollbars disappear and div is at the bottom"


text:
Q: tkinter askopenfilename doubleclick passes event to parent I have this simple example of the behavior:
import tkinter as tk
from tkinter import filedialog, ttk

INITIALDIR = 'C:\\'

class MainWindow(ttk.Frame):
    def __init__(self, root, *args, **kwargs):
        super().__init__(root, *args, **kwargs)
        self.pack()
        btnoptions = {'expand':True, 'fill': 'both'}
        btn = ttk.Button(self, text='Select', command=self.ask_openfile)
        btn.pack(**btnoptions)

    def ask_openfile(self):
        self.file_opt = options = {}
        options['initialdir'] = INITIALDIR
        filename = filedialog.askopenfilename(**self.file_opt)
        return filename

if __name__=='__main__':
    root = tk.Tk()
    root.geometry('600x300')
    MainWindow(root).pack(expand=True, fill='both', side='top')
    root.mainloop()

Basically there is one big button, which opens a open file dialog. If I select a file and press open, it works fine. However, if I double click to select a file, it selects the file, closes the dialog, and immediately opens a new open file dialog. My guess, that the second click somehow is passed to the underlying window and it clicks on the button again (button has to be under the file which is about to be selected). Is there a way to avoid this behavior? Looks like it is Windows problem, tried on windows 7 and 10 with python 3.5. On debian linux everything is fine, however, I need this to work on Windows.

A: Seems like this is a known issue with tk:
https://core.tcl.tk/tk/tktview?name=faf37bd379
That ticket says that the issue is fixed in tk 8.6.8.
I was having this issue with tk 8.6 and updating isn't a great option so I tried to find some other workarounds. I tried disabling the buttons and then enabling them but the rouge click just occurred after the button was enabled. I also tried adding a delay before enabling the buttons again but that didn't work either.
The two workarounds that I found that actually worked are:
1) Change the buttons to require a double-click. This can be done with bind . I don't personally like having to double-click the button but maybe other people are less picky.
2) Change the file selection to a combobox with a list of the files in a selected directory. The directory can be selected using askdirectory in place of askopenfilename. askdirectory requires the user to click the "Select Folder" button so it does not have the same issue with double-clicks.


text:
Q: zend framework create empty display group and then add element Is possible to create an empty display group and then add the elements?
I tried:
addDisplayGroup(null, 'exampleGroup')

But you have to pass at least an element...
I need to create just an empty display group.
I need to do that because after create the display group, I will add the elements one by one in a foreach....
Thanks again...

A: You could try with
$form->addDisplayGroup(array(), 'exampleGroup');

and then get the display group like that:
$displayGroup = $form->getDisplayGroup('exampleGroup');

and add the elements one by one later with $displayGroup->addElement() or $displayGroup->createElement().
You can see more details in the Display Groups documentation.
EDIT:
ZF doesn't allow to add a display group with no elements. The simplest solution could be to create the elements first, put them into an array, and then pass that array to addDisplayGroup.
It's also possible to instantiate a new Zend_Form_DisplayGroup object and then add it to the form using $form->addDisplayGroups(array($group)), but I doubt if it's more convenient than calling addDisplayGroup() with the elements already created.
Hope that helps,

A: How about overriding the form's addDisplayGroup($elements, $name) method, adding a dummy element if necessary:
class My_Form extends Zend_Form
{

    protected $dummyName = '_myDummy';

    public function addDisplayGroup(array $elements, $name)
    {
        if (count($elements) == 0){
            $elt = new Zend_Form_Element_Hidden($this->dummyName);
            $elt->setIgnore(true);
            $elements[] = $this->dummyName;
        }
        return parent::addDisplayGroup($elements, $name);
    }

    public function render(Zend_View_Interface $view = null)
    {
        $this->removeElement($this->dummyName);
        return parent::render($view);
    }
}

Then in your form you can now invoke as:
$displayGroup = $this->addDisplayGroup(array(), 'myDisplayGroup');

$elt1 = new Zend_Form_Element_Text('myElement1');
$displayGroup->addElement($elt1);

$elt2 = new Zend_Form_Element_Text('myElement2');
$displayGroup->addElement($elt2);

// etc

A: My solution:
$zgody = $db->fetchAll($db->select()->from('rodo_regulki')->where( 'id_inwest =?', $inwest ));

$getFirstElement = $zgody[0]->id;
$this->addDisplayGroup(array('zgoda_'.$getFirstElement),'zgody', array('legend' => 'Zgody'));

foreach($zgody as $zgoda) {
    $element = 'zgoda_'.$zgoda->id;
    $addElement = $this->getElement($element);
    $displayGroup = $this->getDisplayGroup('zgody');
    $displayGroup->addElement($addElement);
}


text:
Q: Hundred-Digit Challenge - problem 2 - math's idea of solution For you who don't know what 100 digits challenge is...
The hundred-dollar, hundred-digits challenge problems are a set of ten problems in numerical analysis published in the January/February 2002 issue of SIAM News (http://www.siam.org/siamnews/01-02/challenge.pdf). Nick Trefethen, the proposer of the problems, offered a 100 dollars prize to the person or group obtaining the largest number of correct digits (up to a maximum of 10) for these problems by May 20, 2002. Trefethen underestimated the ingenuity of problem solvers, and 20 independent teams obtained 10 correct digits for all 10 problems. After an anonymous donor stepped in to help defray the larger than anticipated payoffs, prize checks went out to all winners by December 2002.

Second problem :  A photon moving at speed 1 in the $xy$ plane starts at $t=0$ at $(x,y)=(0.5,0.1)$ heading due east. Around every integer lattice point $(i,j)$ in the plane, a circular mirror of radius $\frac{1}{3}$ has been erected. How far from the origin is the photon at $t=10$?
My question is how to solve this without using computer simulation(just pure math).

A: A complete, purely mathematical approach  would imply a high number of tedious passages and calculations (the solution to this problem is known to require $14$ reflections before reaching $t=10$). However, if I interpret correctly the question, it asks for a simple general idea of solution.
If this is the case, we could choose different  methods (e.g. using vectors, analytic geometry, trigonometry). The analytic geometry approach might be rather intuitive. We have to consider a sequence of successive segments on a Cartesian plane, each characterized by a starting point, a running line (the line actually followed by the photon in its path), a collision point (identified by determining the first crossing point  between the running line and a circle), and a reflection line (whose angle is determined by the slope of the tangent to the circle in the collision point). Once completed a step, the collision point and the reflection line become the starting point and the running line of the successive step. Since for each segment of the path we can calculate the distance covered by the photon (or equivalently the time needed to run this distance), we can continue our step-by-step calculations until we reach $t=10$ and look at the point where we have arrived. In this way, the problem reduces to find the way of determining, from a starting point and a running line of a generic step, the corresponding collision point and the reflection line, so that iterating our calculations we can arrive to the solution.
The general approach to each step may be as follows. If $(x_n,y_n) $ is the starting point at the $n^{th} $ step and  $a_n x+b_n $ is the equation of the corresponding running line, we have to begin by finding the collision point, i.e. the first crossing point  with a circle. The circle can be firstly identified by visual examination of the graph (although we have then to  confirm that the line actually crosses the circle and that the identified circle provides the minimal distance between the starting and collision point). Because all circles correspond to a translation of the circle $x^2 + y^2=\frac {1}{9} \,\,\,$ over an integer lattice, we can consider the  equation $(x-j_n)^2 + (y-k_n)^2=\frac {1}{9} \,\,\, $, where $(j_n,k_n) \,\,$ are the integers expressing the coordinates of the centre of the circle on which the $n^{th} $  reflection occurs. Solving the system
$$\begin {cases}
y=a_n x+b_n \\
(x-j_n)^2 + (y-k_n)^2=\frac {1}{9} \end {cases} $$
to find the crossing point between the circle and the running line  gives the coordinates of the collision point:
$$  x_{n+1}=\frac{m^2 \pm \sqrt {m^2-(b_n-k_n)^2-j_n^2  +1/9  }}{  a_n^2+1 }$$
and
$$y_{n+1}= a_n x_{n+1} +b_n$$
where $$m=a_n k_n +j_n-a_n b_n $$ and where we have to choose, among the two solutions, the case that corresponds to the lower distance between the starting and the collision point. This distance $d_n$ can be obtained using the standard formula, knowing that it is calculated between the points $(x_n,y_n) \,\,\,   $ and $(x_{n+1},y_{n+1}) \,\,\,   $.
Now we have to find the slope of the tangent to the circle in $x_{n+1},y_{n+1} \,\,\,$ to calculate the reflection line. Using the derivative of the circle equation, we obtain that the slope $t_n $ of the tangent at the $n^{th} $ reflection is
$$t_n=\pm \frac {(j _n - x_{n+1})}{\sqrt{1/9 - (j_n - x_{n+1})^2}}$$
where again we have to choose, among the two solutions, the appropriate one, looking at our graph to check the sign of the searched tangent. To calculate the slope of the reflection line, we can remind that if a line with angle $\alpha$ with respect to the $x $-axis is reflected on a line with angle $\beta $, the angle of the resulting reflected line is given by $2\beta-\alpha$. In this case we have $$\alpha=\arctan {a_n}  \\  \beta=\arctan {t_n}  $$ so the slope of our reflection line is $$\tan ( 2 \arctan {t_n}  -   \arctan {a_n} ) \,\,\, $$ Because it passes through $x_{n+1},y_{n+1} \, $, its equation is
$$\small {y= \tan ( 2 \arctan {t_n}  -   \arctan {a_n} ) x \\ + y_{n+1} - \tan ( 2 \arctan {t_n}  -   \arctan {a_n} ) x_{n+1} }$$
In this way, based on a starting point with coordinates $(x_n,y_n ) $ and a running line $a_n x+b_n $ that characterize the $n^{th} $ step, we have determined the collision point $(x_{n+1},y_{n+1}) \,\,$, the distance covered between these two points, and the reflection line. Setting the collision point and the reflection line as the starting point and the running line of the successive step, we can repeat several times the whole procedure, until the sum of the distances covered in each step achieves $10$.
To make a practical example, we can apply these calculations to the first step of the problem. We start from the point $(x_1,y_1)=(0.5,0.1) \,\,\,\,$ and the running line is $y=0.1$. The first circle to be crossed is that with centre in $(1,0)$, which has equation $(x-1)^2 +y^2=\frac {1}{9} \,\,\, $. Applying the equations above with $a_1=0 \,$, $b_1=0.1\,$, $j_1=1 \,$, and $k_1=0 \,$, we get $m=1\,$, so that the coordinates of the collision point $(x_2,y_2) \,$ (knowing that we must choose, among the two solutions, that nearer to the starting point) reduce to
$$ x_{2}=1 - \sqrt {1-0.1^2-1    +1/9     } = 1 - \frac {\sqrt {0.91}}{3} \approx 0.682 \\ y_{2}=0 \cdot x_2+0.1=0.1
$$
Using the derivative of the circle equation, we obtain that the slope $t_1 $ of the tangent at the first reflection is
$$t_1= \frac{1 - ( 1 - \sqrt {0.91}/3) }{\sqrt{1/9 - [(1-   (1 - 0.91/3)]^2   }}   \\ =     \frac {\sqrt{0.91}/3 }{\sqrt{1/9 - 0.91/9  }} = \sqrt {91}/3 \approx 3.1798   $$
Lastly, the equation of the reflected line is
$${y=\tan \left ( 2 \arctan {   \sqrt {91}/3    }   \right) x \\ + 0.1 - \tan \left ( 2 \arctan { \sqrt {91}/3    }   \right) \cdot (1 -  \sqrt {0.91}/3 )}$$
$$y=- \frac {3 \sqrt {91}}{41} x + 0.1 + \frac {3 \sqrt {91}}{41} -  \frac {91}{410} $$
which in numbers is approximately
$$y=-0.6980 x +0.5761$$
So we have determined the collision point and the reflection line of the first step. As explained above, these become the starting point and the running line of the second step, allowing to repeat the procedure.


text:
Q: Необработанное исключение System.Net.WebException во время запроса WebClient var uploadServer = api.Photo.GetWallUploadServer(id);
var awda = new WebClient();
MessageBox.Show(uploadServer.UploadUrl);
var responseImg = Encoding.UTF8.GetString(awda.UploadFile(uploadServer.UploadUrl,
    "POST", "https://vk.me/images/safari_152.png"));

var photos = api.Photo.SaveWallPhoto(responseImg, null, id);
var result = api.Wall.Post(id, false, true, text, photos, null);


text:
Q: Error "System UI isn't responding" while running AOSP build on emulator I am trying to run AOSP(oreo 8.1) build on emulator.
I used following commands to build AOSP.
source build/envsetup.sh
lunch aosp_arm-eng
make -j4

my build was successful. Now i'm trying to run on emulator using following command.
emulator

emulator is started with following warning message.
Could not automatically detect an ADB binary. Some emulator functionality will not work until a custom path to ADB  is added in the extended settings page.
After successful boot "System UI isn't responding" message is displaying on the emulator, also emulator is running real slow.
Any help in resolving this issue is greatly appreciated.
emulator screenshot: system ui isn't responding
emulator: WARNING: system partition size adjusted to match image file (2050 MB > 200 MB)
emulator: WARNING: encryption is off
main-loop: WARNING: I/O thread spun for 1000 iterations

A: It often occurs - especially on slow machines running CPU-consuming emulations, that an emulator would initially load into a state where a System UI isn't responding alert shows. It does not necessarily mean the device isn't working; Often enough, the alert can be dismissed and the device will be completely functional from that point on.
I'm not sure what the exact issue to solve here is. Nevertheless, assuming you're running on CI and - besides the emulator's sluggishness, wish to overcome the System UI isn't responding alert appearing upon boot completion (as suggested by the title) -- may I suggest this bash script (gist):
#!/bin/bash

echo ""
echo "[Waiting for launcher to start]"
LAUNCHER_READY=
while [[ -z ${LAUNCHER_READY} ]]; do
    UI_FOCUS=`adb shell dumpsys window windows 2>/dev/null | grep -i mCurrentFocus`
    echo "(DEBUG) Current focus: ${UI_FOCUS}"

    case $UI_FOCUS in
    *"Launcher"*)
        LAUNCHER_READY=true
    ;;
    "")
        echo "Waiting for window service..."
        sleep 3
    ;;
    *"Not Responding"*)
        echo "Detected an ANR! Dismissing..."
        adb shell input keyevent KEYCODE_DPAD_DOWN
        adb shell input keyevent KEYCODE_DPAD_DOWN
        adb shell input keyevent KEYCODE_ENTER
    ;;
    *)
        echo "Waiting for launcher..."
        sleep 3
    ;;
    esac
done

echo "Launcher is ready :-)"

The script awaits for the launcher to become ready and in-focus, and automatically dismisses system responsiveness alerts, coming its way.
It in no way addresses the emulator's sluggishness, however.

A: See this answer from another question to fix the ADB error. However, this will likely not fix the responsiveness of your emulator.
The emulator tends to function extremely slowly if you are compiling aosp for a different architecture than your host machine. If you are building on an x86 machine an x86 build will result in a significantly faster emulator that won't eat up all of your machine's resources.

A: May be this answer could be helpful for someone who have made a mistake like me and could save his time.
I faced this issue on my physical device as i used an app icon of very large size (2100x2100). I resolved it by using an app icon of low size(512x512).


text:
Q: WordNet - What does n and the number represent? My question is related to WordNet Interface.
   >>> wn.synsets('cat')
       [Synset('cat.n.01'), Synset('guy.n.01'), Synset('cat.n.03'),
        Synset('kat.n.01'), Synset('cat-o'-nine-tails.n.01'),
        Synset('caterpillar.n.02'), Synset('big_cat.n.01'),
        Synset('computerized_tomography.n.01'), Synset('cat.v.01'),
        Synset('vomit.v.01')]
    >>>

I could not find the answer to what is the purpose of n and the following number in cat.n.01 or caterpillar.n.02.

A: Per the NLTK docs, a <lemma>.<pos>.<number> Synset string is composed of the following parts:

*

*<lemma> is the word's morphological stem

*<pos> is one of the module attributes ADJ, ADJ_SAT, ADV, NOUN or VERB

*<number> is the sense number, counting from 0

Thus, the <pos> is the part of speech.
According to the wordnet man page, the part of speech character has the following meaning:
n    NOUN
v    VERB
a    ADJECTIVE
s    ADJECTIVE SATELLITE
r    ADVERB

The <number> is used to disambiguate word meanings.


text:
Q: Testing equality of relative frequency ratio in binomial sample I am sorry if this question is too basic or was somewhere else here on Cr-Validated, but i didn't find anything suitable.
I study patients with cancer who were made a byopsy taking to test presence of cancer cellcs 12 prostate core samples. When core samples are explored, they are divided into two groups whether there was found  1-2 prostatic intraepithelial neoplasia samples or 3-4 prostatic intraepithelial neoplasia samples (or PIN samples). I want to test the hypothesis that cancer detectability ( 0 states for no cancer cells found and 1 states for presence of cancer cells) is higher among patients with 3-4 PIN samples rather than 1-2.
To visualise - this is how sample could look like
PIN Group Cancer
1   I     0
2   I     0
1   I     1
...
4   II    1
3   II    1
4   II    0
....

Mathematically speaking I have to test hypothesis of  relative frequency ratio equality. How do I do that?
Simultaneously I opened two sources - one asserting that I have to calculate two CI for ratios and if they intersect then it means that ratios can be equal, and other source claiming it is wrong method.
What do you think? I will be eternally grateful for any clarifications!


text:
Q: Recovery root password PostgreSQL on Windows 7 I forgot password on database, and want to reset it, but I have fatal error on TRUST in file pg_hba.conf:
# host all all all md5
# host all all 127.0.0.1/32 trust
# local all postgres md5
# host all all all ident
host all all 0.0.0.0/0 trust

# IPv4 local connections:
# host all all 10.32.32.26/32 ident map=map1
# host all all 127.0.0.1/32 ident map=map1
# host all all 127.0.0.1/32 sspi map=map1

invalid authentication method "trust"
I try to make IDENT and SSPI with mapping of real user, but I have error:
password authentication failed for user ...
Last try of pg_ident.conf file:
map1  /.+  postgres

Virsion: (PostgreSQL) 9.1.15 on Windows 7
What I am doing wrong?
Full Error on start:

C:\Program Files (x86)...\server\bin>pg_ctl -D "C:\Program Files (x86)...\database" start
server starting
C:\Program Files (x86)...\server\bin>LOG:  invalid authentication method "trust"
CONTEXT:  line 5 of configuration file "C:/Program Files (x86)/.../database/pg_hba.conf"
FATAL:  could not load pg_hba.conf


text:
Q: restarting a script upon boot in screen/tmux I have a script that runs in dot net, that works fine when starting it through putty- either in screen or in tmux.
However i have been trying for in total over 8 hours to get it to work with systemd or crontab, but it doesn't seem to work.
When i run it in cron or systemd, the script wont start or work.
This is the script:
#!/bin/sh
echo ""
echo "Running NadekoBot with auto restart and updating to latest build!"
root="/root"
youtube-dl -U

sleep 5s
while :; do cd "$root/NadekoBot" && dotnet restore && dotnet build --configuration Release && cd "$root/NadekoBot/src/NadekoBot" && dotnet run -c Release && cd "$root" && wget -N https://github.com/Kwoth/NadekoBot-BashScript/raw/1.4/nadeko_installer_latest.sh && bash "$root/nadeko_installer_latest.sh"; sleep 5s; done
echo ""
echo "That didn't work? Please report in #NadekoLog Discord Server."
sleep 3s

cd "$root"
bash "$root/linuxAIO.sh"
echo "Done"

rm "$root/NadekoARU_Latest.sh"
exit

A: Here is the answer, after many hours of trying to figure it out. This works for nadekobot at least.
Copy this text into the systemd system folder as a nedekobot.service file, then don't forget to enable the service file.
[Unit]
Description=Nadekobot

[Service]
WorkingDirectory=/root/
User=root
Type=forking

ExecStart=/usr/bin/tmux new-session -s mc-%i -d '/bin/sh nadeko_start.sh'

ExecStop=/bin/sleep 2

[Install]
WantedBy=multi-user.target


text:
Q: in JMeter, how to send a 4 byte message to a JMS publisher Don't think this has been asked this specifically.
I have to run a performance test on a application that consumes from a ActiveMQ topic. The sampler needs to publish 4 Bytes of data in to the topic which usually be the format of (if you look at the hex value) 0x006403D6.
If you translate them in to decimals, they will be
0x03D6 = 00000011 11010110 ==> 982 ==> 03,D6 ==> 03, 214 ==> 3,214
0x0064 = 00000000 01100100 ==> 100 ==> 00,64 ==> 00, 100 ==> 0,100
So the above example the 4 bytes will be [0,100,3,214].
To get this done I have used a JMSPublisher.
The below is the configuration:

Since I have to send a byte stream I thought to use a ByteMessage from a file.

I tried above with different content in the file in the configuration. But non would give me [0,100,3,214].
It looks like JMeter does convert the text, characters in to byte values. So If I have a empty file the topic will reeve 0 and application will consider it as [0,0,0,0] (Application considers only the first 4 bytes)
If I have ???? in the text file I get [63,63,63,63] (As ? ==> 00111111 ==> 63 in Decimal).
But If I have to get the first byte a 0, I am unable to get that through? As there is no character I could found to represent 0.
May be There is a better way of doing this. Please advise ?

A: Looking into JMS Sampler JavaDoc, the setContent() function accepts String only so there is no way to pass bytes to this as JMeter will treat them as a simple string.
However as per JMS Publisher documentation you should be able to send whatever you want given the object is serialised by XStream

The Object message is implemented and works as follow:

*

*Put the JAR that contains your object and its dependencies in jmeter_home/lib/ folder

*Serialize your object as XML using XStream

*Either put result in a file suffixed with .txt or .obj or put XML content directly in Text Area
Note that if message is in a file, replacement of properties will not occur while it will if you use Text Area.

Also be aware that you can always switch to JSR223 Sampler and use ByteMessage class from Groovy code.


text:
Q: For one employee, In time and Out time should be returned on one line select
    compcode, emplcode, attndate, costcode,
    decode(shiftflg, 'I', readtime) INTIME,
    decode(shiftflg, 'O', readtime) OUTTIME
from
    ecatnrec
where
    emplcode = 'RF025'
order by
    emplcode;

A: You can use aggregation:
select compcode, emplcode, attndate, costcode,
       max(case when shiftflg = 'I' then readtime end) as INTIME,
       max(case when shiftflg = 'O' then readtime end) as OUTTIME
from ecatnrec
where  emplcode = 'RF025'
group by compcode, emplcode, attndate, costcode
order by emplcode;

This assumes that there is at most on "I" and one "O" row for unique values of the group by keys.


text:
Q: Stepwise regression and variable selection with categorical variables in R I am new with statistics and especially stepwise regression with categorical variables. I have 4 categorical variables, each with a different levels (5 levels, 12 levels, 7 levels, and 78 levels).
I used the following to do stepwise in R
null.lm <- lm(log(bid)~1, data=data)
full.lm <- lm(log(y)~log(x) + program + month+ region + code , data=data)
step(null.lm, scope=list(lowr=null.lm, upper=full.lm), directiom="both")

The resulting stepwise model containing the following output:
codeStructure             month02                  month03                  month04                  month05
 0.150322                 0.103917                -0.065815                 0.007522                -0.004914

then I used
predict(step(null.lm, scope=list(lowr=null.lm, upper=full.lm), directiom="both"))

to find the predicted values.
My question is: Was I supposed to create a dummy variable for each level?I mean
for the month categorical variable: create 12 columns (1,0) and then use this in the stepwise?
I use stepwise because when fitting the linear model, not all p-values were significant, so I though of doing variable selection, but I am not sure if what i did is correct.
If I had to use the step outcome: if the observation belongs to month02, then I multiply its coefficient by 1, otherwise by 0?

A: To answer your 1st question: No, you were not supposed to create dummy variables for each level; R does that automatically for certain regression functions including lm(). If you see the output, it will have appended the variable name with the value, for example, 'month' and '02' giving you a dummy variable month02 and so on.
If you were to use the model and generate forecasts by hand, then yes, you multiply the coeff by 1 when the obs belongs to the particular category. Loosely put, (Month==02) is same as (month02==1). However, looks like you've used the predict() function which does the application of the model on (some) data automatically.
PS: there's a typo in direction= in the code you posted.


text:
Q: Mongoose populate Here is my test code which I can not figure out why it isn't working, as it is very similar to test 'populating multiple children of a sub-array at a time'.
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

mongoose.connect('mongodb://localhost/testy');

var UserSchema = new Schema({
    name: String
});

var MovieSchema = new Schema({
    title: String,
    tags: [OwnedTagSchema]
});

var TagSchema = new Schema({
    name: String
});

var OwnedTagSchema = new Schema({
    _name: {type: Schema.ObjectId, ref: 'Tag'},
    _owner: {type: Schema.ObjectId, ref: 'User'}
});

var Tag = mongoose.model('Tag', TagSchema),
    User = mongoose.model('User', UserSchema),
    Movie = mongoose.model('Movie', MovieSchema);
    OwnedTag = mongoose.model('OwnedTag', OwnedTagSchema);

User.create({name: 'Johnny'}, function(err, johnny) {
    Tag.create({name: 'drama'}, function(err, drama) {
        Movie.create({'title': 'Dracula', tags:[{_name: drama._id, _owner: johnny._id}]}, function(movie) {

            // runs fine without 'populate'
            Movie.find({}).populate('tags._owner').run(function(err, movies) {
                console.log(movies);
            });
        });
    })
});

Produced error is
node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: Cannot call method 'path' of undefined
    at /Users/tema/nok/node_modules/mongoose/lib/model.js:234:44

Update
Got rid from OwnedTag and rewrote MovieSchema like this
var MovieSchema = new Schema({
    title: String,
    tags: [new Schema({
        _name: {type: Schema.ObjectId, ref: 'Tag'},
        _owner: {type: Schema.ObjectId, ref: 'User'}
    })]
});

Working code https://gist.github.com/1541219

A: Your variable OwnedTagSchema must be defined before you use it or you'll end up doing basically this:
var MovieSchema = new Schema({
  title: String,
  tags: [undefined]
});

Move it above MovieSchema definition.

A: I would expect your code to work, too. Does it work if you put the OwnedTag right in MovieSchema, like so?
var MovieSchema = new Schema({
  title: String,
  tags: [{
           _name: {type: Schema.ObjectId, ref: 'Tag'},
           _owner: {type: Schema.ObjectId, ref: 'User'}
        }]
});

edit:
var MovieSchema = new Schema({
  title: String,
  tags: [{ type: Schema.ObjectId, ref: 'OwnedTag' }]
});


text:
Q: Multiple Input Files In one Mapper Class Hadoop? So,I am trying to code FP-Tree algorithm in MapReduce Paradigm,
for creating an frequent item set list , i have the following problem :
Input:
File1.txt (Contains all the transactions)
123 452 221 12
45 76 987
77 76 123 354

[Each Line contains items Bought in one Transaction]

File2.txt (Contains Items which are bought in descending order)
12    123

6     221

5     77

4     354

[Count] [Item Id]

Output :
output.txt

123 221
123 77 354

[2nd transaction is eliminated]

Items according to their count are taken in ( descending ), others are deleted
Is it possible to take both File1.txt and File2.txt into one mapper class ? because this will solve my problem
Or is there any way to perform this operation in another way ?
Any help is appreciated.

A: look into mapreduce distributed cache example.may be help full
http://myhadoopexamples.com/2014/04/16/hadoop-map-side-join-with-distributed-cache-example/
read the file in setup method.the above link will give good guidance.
Hadoop Map Reduce read a text file

A: You can read multiple files in one MR program. But each file should have a mapper class separately. Since both of your input files are different, the read logic varies for both of these. You can have two mappers one for each, and the output of this should have the same KEY and passed to reducer.
You can refer to distributed cache.


text:
Q: Touch event not working on IOS with tel links I'm trying to intercept a click on a  tel link on IOS like :
Example
I've created a Fiddle here :
https://jsfiddle.net/Portekoi/yzg1eb96/4/
When I use my iPhone 6S, first link do not firing the alert. But the second link, yes.
I've try to add the CSS hack for IOS cursor : pointer but without success.
How can intercept the click on a tel href on IOS?

A: Your code is working for me
Check attached image