text:
Q: find free variables in lambda expression Does anyone know how I can figure out the free variables in a lambda expression? Free variables are the variables that aren't part of the lambda parameters.
My current method (which is getting me nowhere) is to simply use car and cdr to go through the expression. My main problem is figuring out if a value is a variable or if it's one of the scheme primitives. Is there a way to test if something evaluates to one of scheme's built-in functions? For example:
(is-scheme-primitive? 'and)
;Value: #t

I'm using MIT scheme.

A: For arbitrary MIT Scheme programs, there isn't any way to do this.  One problem is that the function you describe just can't work.  For example, this doesn't use the 'scheme primitive' and:
(let ((and 7)) (+ and 1))

but it certainly uses the symbol 'and.
Another problem is that lots of things, like and, are special forms that are implemented with macros.  You need to know what all of the macros in your program expand into to figure out even what variables are used in your program.
To make this work, you need to restrict the set of programs that you accept as input.  The best choice is to restrict it to "fully expanded" programs.  In other words, you want to make sure that there aren't any uses of macros left in the input to your free-variables function.
To do this, you can use the expand function provided by many Scheme systems.  Unfortunately, from the online documentation, it doesn't look like MIT Scheme provides this function.  If you're able to use a different system, Racket provides the expand function as well as local-expand which works correctly inside macros.
Racket actually also provides an implementation of the free-variables function that you ask for, which, as I described, requires fully expanded programs as input (such as the output of expand or local-expand).  You can see the source code as well.
For a detailed discussion of the issues involved with full expansion of source code, see this upcoming paper by Flatt, Culpepper, Darais and Findler.

A: [EDIT 4] Disclaimer; or, looking back a year later:
This is actually a really bad way to go about solving this problem.  It works as a very quick and dirty method that accomplishes the basic goal of the OP, but does not stand up to any 'real life' use cases.  Please see the discussion in the comments on this answer as well as the other answer to see why.
[/EDIT]
This solution is probably less than ideal, but it will work for any lambda form you want to give it in the REPL environment of mit-scheme (see edits).  Documentation for the procedures I used is found at the mit.edu doc site. get-vars takes a quoted lambda and returns a list of pairs.  The first element of each pair is the symbol and the second is the value returned by environment-reference-type.
(define (flatten lst)
  (cond ((null? lst) ())
        ((pair? (car lst)) (append (flatten (car lst)) (flatten (cdr lst))))
        (else
          (cons (car lst) (flatten (cdr lst))))))

(define (get-free-vars proc-form)
  (let ((env (ge (eval proc-form user-initial-environment))))
    (let loop ((pf (flatten proc-form))
               (out ()))
      (cond ((null? pf) out)
            ((symbol? (car pf))
             (loop (cdr pf) (cons (cons (car pf) (environment-reference-type env (car pf))) out)))
            (else
              (loop (cdr pf) out))))))

EDIT:  Example usage:
(define a 100)

(get-vars '(lambda (x) (* x a g)))
 => ((g . unbound) (a . normal) (x . unbound) (* . normal) (x . unbound) (lambda . macro))

EDIT 2: Changed code to guard agains calling environment-reference-type being called with something other than a symbol.
EDIT 3: As Sam has pointed out in the comments, this will not see the symbols bound in a let under the lambda as having any value.. not sure there is an easy fix for this.  So, my statement about this taking any lambda is wrong, and should have read more like "Any simple lambda that doesn't contain new binding forms"... oh well.


text:
Q: Returning Google ads within ad groups with specific labels I can't seem to figure out why my code isn't returning ads with a specific labels and need help understanding where I went wrong with my code. I am iterating through the ad groups that have a specific label "AUTOENABLE" and then iterating through each ad with the same label but also checking on another script the URL endpoint.
  adCount: 0,
  adsEnabled: 0,
  adsDisabled: 0,
  adsSetEnabled: [],
  adsSetDisabled: []
};

function adsTest() {

  var ag_iter = AdWordsApp.labels().withCondition("Name = AUTOENABLE").get();

  if(ag_iter.totalNumEntities() < 1){
    Logger.log("ERROR: No AUTOENABLE label found in AdGroup");
    return;

    // Iterating through all Ad groups to work individually
    while (ag_iter.hasNext()) {
    // Getting the ad group and printing it's name
    var ag = ag_iter.next();
    Logger.log(ag.getName())

    // Taking an iterator from all Ads inside Ad Group
    var ad_iter = ag.ads().withCondition("LabelNames = AUTOENABLE").get();
    if(ad_iter.totalNumEntities() < 1){
    Logger.log("ERROR: No AUTOENABLE label found in Ads.");
    return;
  }
    while(ad_iter.hasNext()){
      var ad_iter = ads.next();
      checkAd(ad);
    }
   }
  }

    report();
}

function report(){

    Logger.log(stats.adCount + " ads checked");
    Logger.log(stats.adsEnabled + " ads are enabled");
    Logger.log(stats.adsDisabled + " ads are disabled");
    Logger.log((stats.adsSetDisabled.length + stats.adsSetEnabled.length) + " ads modified");
    if(stats.adsSetEnabled.length > 0){
      Logger.log("Changed to enabled:");
      stats.adsSetEnabled.forEach(adLog);
    }
    if(stats.adsSetDisabled.length > 0){
      Logger.log("\nChanged to disabled:");
      stats.adsSetDisabled.forEach(adLog);
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configurable joint, rotation not acting as expected I've take the Crawler project example and rework it for a personal project. And I have a huge issue making work the joints of the lower legs (not the upper legs thought).

I had to apply local transformation like this, so that the object are all in the same direction. Then I've edit the axis in the configurable joint, only the Z axis is limited, the others are locked. Then I've applied a 90 limit angle rotation.

Thing is, in what ever constraint I use for the axis, when I apply an angle, I still get the same angle limit.
I use a model to predict between -1 and 1 an output for the angle, which is mapped in a function to give 0 or 180 Degrees.
    public void SetJointTargetRotation(float x, float y, float z)
    {
        x = (x + 1f) * 0.5f;
        y = (y + 1f) * 0.5f;
        z = (z + 1f) * 0.5f;

        var xRot = Mathf.Lerp(joint.lowAngularXLimit.limit, joint.highAngularXLimit.limit, x);
        var yRot = Mathf.Lerp(-joint.angularYLimit.limit, joint.angularYLimit.limit, y);
        var zRot = Mathf.Lerp(-joint.angularZLimit.limit, joint.angularZLimit.limit, z);

        currentXNormalizedRot =
            Mathf.InverseLerp(joint.lowAngularXLimit.limit, joint.highAngularXLimit.limit, xRot);
        currentYNormalizedRot = Mathf.InverseLerp(-joint.angularYLimit.limit, joint.angularYLimit.limit, yRot);
        currentZNormalizedRot = Mathf.InverseLerp(-joint.angularZLimit.limit, joint.angularZLimit.limit, zRot);

        joint.targetRotation = Quaternion.Euler(xRot, yRot, zRot);
        currentEularJointRotation = new Vector3(xRot, yRot, zRot);
    }

But for testing I'm not using the neural net yet, I hard code inputs like this:
bpDict[leg3Lower].SetJointTargetRotation(0, 0, 1f);

But this is what I get:

In red, the movement of the leg (down to right).
In bleu, the original position of the leg.
In Black, the "axis" and limit that it was supposed to make.\
And even if I fool around with the axis, it will always go to the same position when I apply 1f(inside the robot, supposed to be down) -1 (flat, supposed to be up the sky).
Am I missing something?

A: I fond out that I had to modify the Secondary axis in the Configurable joint. I don't fond this very instinctive, but yhea I managed to make it work by letting the axis to 0,0,-1 and 0,-1,0 to the secondary axis.
I didn't understand the logic, but if you come by this post, try to add 1 or -1 in both of them.


text:
Q: Adding a Mask as a see-through object in Flex I'm trying to add an overlay over my main scene in Flex, with a see thru.
The idea is that users can only interact with the elements exposed thru the Ellipse.
Here is my code:
<!-- Our black overlay -->
<s:Graphic width="100%" height="100%" cacheAsBitmap="true" mask="{this.focus}"
           maskType="{MaskType.CLIP}">
    <s:Rect width="100" height="100">
        <s:fill>
            <s:SolidColor alpha="0.7" color="0x000000" />
        </s:fill>
    </s:Rect>
</s:Graphic>

<!-- Our mask -->
<s:Group id="focus" cacheAsBitmap="true">
    <s:Ellipse id="ellipse" x="150" y="150" width="100" height="100">
        <s:fill>
            <s:SolidColor color="0xFFFFFF" />
        </s:fill>
    </s:Ellipse>
</s:Group>

In Flash Builder, the overlay seems to work as desired:

But here is the effect as rendered in the game:

Is the opposite of what I'm looking for!  Any help is appreciated.
Thanks.
------------- EDIT-----------------
@HotN:  Thanks for your help, is there anyway to add an alpha to the surrounding area?  The idea is for the rest of the game to be visible.

A: Rather than trying to mask the black rectangle, try putting your street image on top of the black rectangle and using the ellipse as the mask for your active image instead.


text:
Q: can't delete item from collectionView I have simple collectionview which shows 1 column on iphone and 2 columns on iPad
There is a button which removing an item from collectionview but when I press the button I got this error:

The number of sections contained in the collection view after the update (3) must be equal to the number of sections contained in the collection view before the update (4), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

And this is my code
protocol AudioListDataProtocol: class {
    func search(searchText: String)
    func playComposition(composition: Composition, data: [Composition], play: Bool)
    func endEditing()
}

class AudioListDataAdapter: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, AudioItemCellProtocol {
    var delegate: AudioListDataProtocol!
    var isFavoriesList = false

    private var data = [Composition]()
    private var collectionView: UICollectionView!
    private var searchBar: UISearchBar!
    private let cellIdentifier = "AudioCellIdent"
    private var selectedIndexPath: IndexPath!
    private var cellWidth = 0 as CGFloat
    private var sectionCount = 0
    private var itemCount = 0

    //MARK: public methods
    func initSearchBar(searchBar: UISearchBar) -> Void {
        self.searchBar = searchBar
        self.searchBar.delegate = self
        self.searchBar.returnKeyType = .done
        self.searchBar.placeholder = DicionaryManager.shared.getStringValue(dKey: AMKeys.mobile_label_search_here)
    }

    func initCollection(collection: UICollectionView) -> Void {
        self.collectionView = collection
        self.collectionView.dataSource = self
        self.collectionView.delegate = self
        self.collectionView.register(UINib.init(nibName: "AudioItemCell", bundle: nil), forCellWithReuseIdentifier: cellIdentifier)
    }

    func setListData(data: [Composition], itemsPerSection: Int, itemWidth: CGFloat) -> Void {
        cellWidth = itemWidth
        self.data = data
        itemCount = itemsPerSection
        sectionCount = Int(ceil(Double(self.data.count / itemCount)))
    }

    func reload() {
        collectionView.reloadData()
    }

    //MARK: UISearchBarDelegate
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.showsCancelButton = true
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.characters.count >= 3 {
            if let d = delegate {
                d.search(searchText: searchText)
            }
        }
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.text = ""
        if let d = delegate {
            d.search(searchText: "")
            d.endEditing()
        }
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let d = delegate {
            d.endEditing()
        }
    }

    //MARK: UICollectionViewDataSource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionCount
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemCount
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? AudioItemCell {
            return cell
        }
        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        let c = cell as! AudioItemCell
        c.setupComposition(composition: data[curItemIndex(indexPath: indexPath)])
        c.indexPath = indexPath
        c.favoriteState = isFavoriesList
        c.delegate = self
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        PlayerManager.shared.changePlaylist()
        var item: Composition
        item = data[curItemIndex(indexPath: indexPath)] as Composition
        item.isPlaying = true
        item.showPlayer = true
        collectionView.reloadItems(at: [indexPath])
        selectedIndexPath = indexPath
        delegate.playComposition(composition: item, data: data, play: true)
    }

    func playingCompositionForReload(composition: Composition) {
        composition.isPlaying = true
        composition.showPlayer = true
        collectionView.reloadData()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: cellWidth, height: 90)
    }

    //MARK: helpers methods
    func updateState(play: Bool) -> Void {
        if (selectedIndexPath) != nil {
            let item = data[curItemIndex(indexPath: selectedIndexPath)]
            item.isPlaying = !item.isPlaying
        } else {
            selectedIndexPath = IndexPath(row: 0, section: 0)
            let item = data[0]
            item.isPlaying = true
            item.showPlayer = true
        }

        collectionView.reloadItems(at: [selectedIndexPath])
    }

    private func curItemIndex(indexPath: IndexPath) -> Int {
        return indexPath.section * itemCount + indexPath.item
    }

    //MARK: AudioItemCellProtocol
    func removeCellAtIndexpath(indexPath: IndexPath) {
        collectionView.performBatchUpdates({
                        self.data.remove(at: self.curItemIndex(indexPath: indexPath))
            sectionCount = Int(ceil(Double(self.data.count / self.itemCount)))
            self.collectionView.deleteItems(at: [indexPath])
        }, completion: nil)
    }
}

And this button pressed code
delegate.removeCellAtIndexpath(indexPath: indexPath)

What I did wrong here and why its crashing?
Please help I stuck on this a day.

A: The problem is with your numberOfItemsInSection method and the use of the itemCount property. You are returning a fixed number. You are assuming every section has the same fixed number of items. Instead, you should be returning the current number of records in your data source for the given section.
It would help a lot if you setup your data source to be an array of arrays where the outer array represents your sections and each inner array is the items in that section. Then you simply return the array count instead of some predetermined variable.


text:
Q: c# Unity - Mutiplayer interacting with objects   using UnityEngine;
using UnityEngine.Networking;

public class Interactable : NetworkBehaviour {

    public float radius = 2f;
    bool isFocus = false;
    Transform player;
    bool hasInteracted = false;
    public Transform interactionPoint;

    public virtual void Interact()
    {
        // This method is meant to be overwritten
        Debug.Log("Interacting with " + transform.name);
    }

    private void Update()
    {
        if (isFocus && !hasInteracted)
        {

            float distance = Vector3.Distance(player.position, interactionPoint.position);

             if(distance <= radius)
            {
                Interact();
                hasInteracted = true;

            }

        }

    }

    public void onFocused(Transform Player)
    {
        isFocus = true;
        player = Player;
    }

    public void onDeFocused()
    {
        isFocus = false;
        player = null;
        hasInteracted = false;

    }
    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, radius);

    }

}

This is for the interaction which is overwritten.
 using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Networking;

public class SphereBehaviour : Interactable {

    public float countdown = 1;
    public float timeLeft = 5f;

    public override void Interact()
    {
        Debug.Log("Interacting with the Sphere object");
        StartCoroutine(StartCountdown());

    }

    public IEnumerator StartCountdown() // Countdown from 5
    {
        countdown = timeLeft;
        while (countdown > 0)
        {
            yield return new WaitForSeconds(1.0f);
            countdown--;
        }

    }

The Problem is that this isn't networked and I can't think of the logic to do it. An Interface won't work or anything. Is there any possible solution which doesn't require changing everything?
I'm just trying to turn Brackeys set of youtube tutorials to something multiplayer.

A: I'm assuming you're using the public "countdown" variable for some UI element.

*

*If you want each player to see their own countdown when they themselves touch this Sphere, this should work fine.

*If anyone touching the sphere should trigger a countdown for everyone, then this will have to be done differently. You'll want the host/server to track interactions between players and spheres, then trigger the countdown coroutine in the clients.
I personally don't recommend #1 in any case, as collisions/interactions should be done server-side.


text:
Q: Can I specif the detail field when I have an elasticsearch index exception? I got an error message when I try to index elasticsearch:
got response {'took': 1, 'errors': True, 'items': [{'index': {'_index': 'mapstore-development-products', '_type': 'product', '_id': '776896', 'status': 400, 'error': {'type': 'mapper_parsing_exception', 'reason': 'failed to parse', 'caused_by': {'type': 'number_format_exception', 'reason': 'empty String'}}}}]}
Is there any way that I can know which specific fields are empty from this return result?

A: This problem is caused by (1) not creating an index mapping before posting the first record (2) You have a field that is empty (string) for your first record, which later you want it to be number.
Elasticsearch will dynamically assign types to your fields if you do not specify your mapping in advance. I don't think you should find the specific empty string field. Instead, you should create your mapping for your index before posting the first record so this problem should be resolved. For your case, you might need to create a new index with correct mapping and then reindex.
See this:

*

*https://discuss.elastic.co/t/how-to-resolve-numberformatexception-issues-caused-by-an-empty-string/5633

*https://medium.com/@eyaldahari/reindex-elasticsearch-documents-is-easier-than-ever-103f63d411c


text:
Q: Asp.net Core Identity unit test controller actions I'm having a problem working out how and what to test.
I have a controller that injects UserManager and calls the CreateAsync method to create a new user.
I don't want to test the Identity user manager as this has clearly been thoroughly tested already. What I would like to do is test that the controller runs through the correct paths (in my case, there are 3 paths, sending responses back with either model state errors, identity response errors or a simple string)
Should I be trying to create a mock of the user manager in order to create my test (I'm not sure how to set up user manager as a mock dependency)
Second, how can I set conditions to verify that the controller has taken a given path.
I am using xUnit and Moq.
[Route("api/[controller]")]
public class MembershipController : BaseApiController
{
    private UserManager<ApplicationUser> _userManager;

    public MembershipController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    [HttpGet("RegisterNewUser")]
    public HttpResponseMessage RegisterNewUser([FromBody] NewUserRegistration user)
    {
        if (ModelState.IsValid)
        {
            ApplicationUser newUser = new ApplicationUser();
            newUser.UserName = user.username;
            newUser.Email = user.password;
            IdentityResult result = _userManager.CreateAsync(newUser, user.password).Result;

            if (result.Errors.Count() > 0)
            {
                var errors = new IdentityResultErrorResponse().returnResponseErrors(result.Errors);
                return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
            }
        }
        else
        {
            var errors = new ViewModelResultErrorResponse().returnResponseErrors(ModelState);
            return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
        }

        return this.WebApiResponse(
                    "We have sent a valifation email to you, please click on the verify email account link.",
                    HttpStatusCode.OK);
    }
}

In My unit test I have the following to test a happy path scenario
    [Fact]
    public void RegisterNewUser_ReturnsHttpStatusOK_WhenValidModelPosted()
    {
        var mockStore = new Mock<IUserStore<ApplicationUser>>();
        var mockUserManager = new Mock<UserManager<ApplicationUser>>(mockStore.Object, null, null, null, null, null, null, null, null);

        ApplicationUser testUser = new ApplicationUser { UserName = "user@test.com" };

        mockStore.Setup(x => x.CreateAsync(testUser, It.IsAny<CancellationToken>()))
           .Returns(Task.FromResult(IdentityResult.Success));

        mockStore.Setup(x => x.FindByNameAsync(testUser.UserName, It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult(testUser));

        mockUserManager.Setup(x => x.CreateAsync(testUser).Result).Returns(new IdentityResult());

        MembershipController sut = new MembershipController(mockUserManager.Object);
        var input = new NewUserInputBuilder().Build();
        sut.RegisterNewUser(input);

    }

Where "input" in sut.RegisterNewUser(input); refers to a helper class which constructs the viewmodel which the controller action requires:
public class NewUserInputBuilder
{
    private string username { get; set; }
    private string password { get; set; }
    private string passwordConfirmation { get; set; }
    private string firstname { get; set; }
    private string lastname { get; set; }

    internal NewUserInputBuilder()
    {
        this.username = "user@test.com";
        this.password = "password";
        this.passwordConfirmation = "password";
        this.firstname = "user";
        this.lastname = "name";
    }

    internal NewUserInputBuilder WithNoUsername()
    {
        this.username = "";
        return this;
    }

    internal NewUserInputBuilder WithMisMatchedPasswordConfirmation()
    {
        this.passwordConfirmation = "MismatchedPassword";
        return this;
    }

    internal NewUserRegistration Build()
    {
        return new NewUserRegistration
        { username = this.username, password = this.password,
            passwordConfirmation = this.passwordConfirmation,
            firstname = this.firstname, lastname = this.lastname
        };
    }
}

My aim here is to force 3 conditions via tests:

*

*Create a valid viewmodel and return a success message

*Create a valid viewmodel but returns a IdentityResponse error (eg. user exists) which gets converted to

*Create an invalid viewmodel and returns Modelstate errors

The errors are handled using a abstract class which returns a json object
The base class for the controller simply constructs a HttpResponseMessage for return.
Basically I want to check that the correct error response class is called by forcing the test down the modelstate error path, the identityresult.errors path and that the happy path can be achieved.
Then my plan is to test the error response classes in isolation.
Hopefully that is enough detail.

A: Mehod under test should be made async and not use blocking calls ie .Result
[HttpGet("RegisterNewUser")]
public async Task<HttpResponseMessage> RegisterNewUser([FromBody] NewUserRegistration user) {
    if (ModelState.IsValid) {
        var newUser = new ApplicationUser() {
            UserName = user.username,
            Email = user.password
        };
        var result = await _userManager.CreateAsync(newUser, user.password);
        if (result.Errors.Count() > 0) {
            var errors = new IdentityResultErrorResponse().returnResponseErrors(result.Errors);
            return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
        }
    } else {
        var errors = new ViewModelResultErrorResponse().returnResponseErrors(ModelState);
        return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
    }

    return this.WebApiResponse(
                "We have sent a valifation email to you, please click on the verify email account link.",
                HttpStatusCode.OK);
}

Review of Happy path scenario and method under test shows that there is no need to setup the UserStore as test will be overriding the user manager virtual members directly.
Note the test has also been made async as well.

*

*Create a valid viewmodel and return a success message

[Fact]
public async Task RegisterNewUser_ReturnsHttpStatusOK_WhenValidModelPosted() {
    //Arrange
    var mockStore = Mock.Of<IUserStore<ApplicationUser>>();
    var mockUserManager = new Mock<UserManager<ApplicationUser>>(mockStore, null, null, null, null, null, null, null, null);

    mockUserManager
        .Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
        .ReturnsAsync(IdentityResult.Success);

    var sut = new MembershipController(mockUserManager.Object);
    var input = new NewUserInputBuilder().Build();

    //Act
    var actual = await sut.RegisterNewUser(input);

    //Assert
    actual
        .Should().NotBeNull()
        .And.Match<HttpResponseMessage>(_ => _.IsSuccessStatusCode == true);
}

*Create a valid viewmodel but returns a IdentityResponse error (eg. user exists) which gets converted

For this you just need to setup the mock to return a result with errors.
[Fact]
public async Task RegisterNewUser_ReturnsHttpStatusBadRequest_WhenViewModelPosted() {
    //Arrange

    //...code removed for brevity

    mockUserManager
        .Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
        .ReturnsAsync(IdentityResult.Failed(new IdentityError { Description = "test"}));

    //...code removed for brevity

    //Assert
    actual
        .Should().NotBeNull()
        .And.Match<HttpResponseMessage>(_ => _.StatusCode == HttpStatusCode.BadRequest);
}

And for

*Create an invalid viewmodel and returns Modelstate errors

You just need to set the model state of the controller so that it is invalid.
[Fact]
public async Task RegisterNewUser_ReturnsHttpStatusBadRequest_WhenInvalidModelState() {
    //Arrange
    var mockStore = Mock.Of<IUserStore<ApplicationUser>>();
    var mockUserManager = new Mock<UserManager<ApplicationUser>>(mockStore, null, null, null, null, null, null, null, null);

    var sut = new MembershipController(mockUserManager.Object);
    sut.ModelState.AddModelError("", "invalid data");
    var input = new NewUserInputBuilder().Build();

    //Act
    var actual = await sut.RegisterNewUser(input);

    //Assert
    actual
        .Should().NotBeNull()
        .And.Match<HttpResponseMessage>(_ => _.StatusCode == HttpStatusCode.BadRequest);
}

FluentAssertions were used to do all the assertions. You could just as easily used Assert.* API.
This should be enough to get you on your way with the above question.

A: Here's a simple way using NUnit (you could do something similar with xUnit), if you don't want to test the user manager. (I've also shown how the DbContext can be passed to the same controller, using an in-memory database that can be used for setting up mock data)
    private DbContextOptions<MyContextName> options;

    [OneTimeSetUp]
    public void SetUp()
    {
        options = new DbContextOptionsBuilder<MyContextName>()
            .UseInMemoryDatabase(databaseName: "MyDatabase")
            .Options;

        // Insert seed data into the in-memory mock database using one instance of the context
        using (var context = new MyContextName(options))
        {
            var testWibble = new Wibble { MyProperty = 1, MyOtherProperty = 2 ... };
            context.wibbles.Add(testWibble);

            context.SaveChanges();
        }
    }

    [Test]
    public void Some_TestMethod()
    {
        // Use a clean instance of the context to run the test
        using (var context = new MyDbContext(options))
        {
            var store = new UserStore<MyUserType>(context);
            var userManager = new UserManager<MyUserType>(store, null, null, null, null, null, null, null, null);

            MyController MyController = new MyController(userManager, context);

            ... test the controller
        }
    }


text:
Q: SSO on Jboss with RedHat SSO I have a Library that is use to authenticate my user and get roles. In my library I must call the LDAP, the Database and merge the result to get my user role. Is it possible to call my library with RH-SSO? Before I use picketlink and I define in my standalone the login-module to call my lib
Thank you

A: Based on the upstream project (Keycloak) documentation, you need to implement the User Storage SPI.


text:
Q: VBA Nested loops in tabular data I've had a pretty thorough search but I'm still struggling with this problem. Essentially, I have a list of various titles, each of which has 10 variables corresponding, which may or may not have data points.

I'd like to loop through the first column, with a nested loop going through each row to count and record the number of populated data points in each. Mostly I'm not sure how to reference cells in the second loop. Any help would be greatly appreciated!

A: I dont really understand your ultimate goal however i hope the code below will help you to go to the right direction.
As far as i understand i wrote a code that COUNT how many cells for each row where there s data.
I am not really sure if it is what you want but let me know and i will edit my code to your requirement.
Option Explicit
Sub test()

Dim wb As Workbook
Dim ws As Worksheet
Dim Lastrow As Long
Dim i As Long, j As Long, c As Long

Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1") '  Change the name of your worksheet

Lastrow = ws.Cells(Rows.Count, 1).End(xlUp).Row ' Find the las row

With ws

        For i = 1 To Lastrow 'Start at row 1 until the last row

            c = 0

                For j = 2 To 11 ' 10 Variables (until the column "L")
                        If Not IsEmpty(.Cells(i, j)) Then c = c + 1  ' Count and record the number of populated data points in each columns
                Next j

            .Cells(i, 12).Value = c 'Past the result in column "L"

        Next i

    End With

End Sub


text:
Q: Microsoft Graph /me not working for Personal Account I am working on implementing OneDrive APIs,though for developer account able to get user detail but while trying login through personal account or other account rather developer account,I am getting following response :
protocol=http/1.1,
code=401,
message=Unauthorized,
url=https://graph.microsoft.com/v1.0/me

I have given all of the Application as well as Delegated permissions in the Azure developer console.
Permissions that were set in Azure developer console:

com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
  .url("graph.microsoft.com/v1.0/me")
  .addHeader("Authorization", "Bearer " + accessToken)
  .build();
try {
   response = okHttpClient.newCall(request).execute();
   Log.e(LOG_TAG, response.toString()); // Do something with the response.
}
catch (IOException e) {
  e.printStackTrace();
}
return response;

A: We have a good quick start and a 30 min walk through tutorial here that would be useful to walk through to understand the permissions side and delegated authentication
https://developer.microsoft.com/en-us/graph/get-started/android
For a user delegated flow, you do not need the application permissions you have consented there. To authenticate /me you only require User.Read as per docs
https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http
You can use https://jwt.ms/ and take the access token to validate that the scope is in the token too.


text:
Q: Incorrect SAS freq table output with ODS Excel trying to export SAS "proc freq" results to an Excel file (xlsx), using Enterprise guide 7.12 with SAS 9.4 on windows.
The following code example :
ODS EXCEL
file='C:\Download\example.xlsx'
STYLE=HtmlBlue
OPTIONS ( sheet_interval="none" sheet_name="Results" );

data example;
input ins_cd$ 1-2 decl_aatrim $ 4-8 prog $ 10-13 compt $ 15-18;
cards;
02 20153 7646 XC12
02 20153 7646 AB02
02 20153 7646 CC13
02 20153 9999
02 20153 7595 PS03
02 20153 7595 PS04
02 20153 6080 XC12
02 20153 6080 XC15
02 20153 6080 CC18
02 20153 6080 DC08
;

proc sort data=example;
by ins_cd decl_aatrim prog compt;
run;

data example2;
set example;
by ins_cd decl_aatrim prog compt;
if first.prog=1 then do;
test=first.prog;
rank=1;
retain rank 1;
end;
else rank=rank+1;
run;

proc freq data=example2;
tables prog*compt;
run;

ods EXCEL close;

outputs the freq table as expected in the results viewer, with four rows per prog like so :(truncated for less copy paste, and freq row labels values roughly translated ):
                           compt
                AB02    CC13    CC18    [...]
prog
6080    Freq       0       0        1      1       0       0        1      1
        Pct     0.00    0.00    11.11   11.11   0.00    0.00    11.11   11.11
        row pct 0.00    0.00    25.00   25.00   0.00    0.00    25.00   25.00
        col.pct 0.00    0.00    100.00  100.00  0.00    0.00    50.00   100.00
7595    Freq       0       0        0       0      0 [...]
[...]

but when the xlsx file produced by ods is opened in Excel, the freq table looks like this:
prog                    compt
Freq
Pct
row pct
col.pct     AB02    CC13    CC18    DC08    PS03    PS04    XC12    XC15    Total
6080           0       0       1       1
            0.00       0   11.11 [...]
            0.00    0.00   25.00
            0.00    0.00  100.00
7595           0
            0.00 [...]

and the four cells with freq calculations are merged into one  cell and row for each prog.
This http://support.sas.com/kb/32/115.html seems to be related to my problem, but the proposed crosslist solution does not give the wanted output in Excel either.
Any ideas? Thanks!

A: If you can use Proc Tabulate instead. You have more control over your table and the appearance anyways.

A: This is caused by how PROC FREQ works, and the ODS HTML solution (what you refer to as the results viewer) is no different.  Notice that it has:

1

11.11

Inside each cell - so one main table cell has a mini-table in it with the freq/rowpct/colpct/totalpct in it (or in the case of the above, the two elements on a bottom header).
You can solve this a number of ways.  One option is, as Reeza notes in another answer, to use PROC TABULATE.
Another option would be to write your own table template via PROC TEMPLATE; that's how PROC FREQ's crosstab is done, after all; you could look at how they did that and change it, perhaps.
A third option would be to postprocess this output; since the resulting table has all of the data you want, just not in rows, you could easily write a VBA routine to change the format to the desired one.


text:
Q: C++ Conditional operator performance I've a conditional statement expensive_foo() which is false in 99.9% cases. And I have a conditional statement bar which is true in ~50% cases.
And I want some action be done if both statements are true. So I almost certainly know that expensive_foo() is false and I want to check it only if bar is true.
Will the code below check the expensive_foo() ONLY if bar is true? Or it will check expensive_foo() every time?
if ( bar && expensive_foo() )
{
    ...
}

Or I need to make a structure like this:
if ( bar )
{
    if ( expensive_foo() )
    {
        ...
    }
}

A: The logical AND operator && is short-circuited, which means that it is guaranteed the second operand is evaluated if and only if the first one is evaluated as true. The conditions if (bar && foo) and if (bar) if (foo) are identical.
Given that foo is expensive to compute, you should almost definitely check bar first. Even though bar won't be predictable by the branch predictor very well, that's a minor effect compared to the computation of foo.
Thus the structure should probably be:
if (bar)
{
    if (bool const foo = compute())   // expensive
    {
        // ...
    }
}

Note that all of those constructions mean that we may or may not call compute(). If you require the function call unconditionally, then you should make it the first check. In that case, the successful branch prediction on the result should be exploited.

A: Both codes will check foo only in case bar is true. In first case this is guaranteed by the language lazy boolean expression evaluation (which actually could be explicitly turned off in some compilers, but is ON by default).

A: The other answers are good, but I'm questioning the premise.
If you are querying a predicate that is false 99.9% of the time, that is analogous to doing linear search in a list of 2000 entries, where the item you are looking for could be anywhere with roughly equal probability.
In that case, typically one would try to organize the list differently so as to do a O(logN) (or better) search instead of O(N).
I don't know if you can do this, but that is where I would focus.
When a question is being asked with highly skewed probability, that can be a big speedup opportunity, if one can un-skew it.
(Assuming a big % of time is spent in this activity. If not, the point is moot.)

A: I'd be surprised if the optimized assembly for both wasn't exactly the same.  expensive_foo() will never be called if bar is false.

A: I saw a comment that the compiler can re-order operations and I'm inclined to that opinion.
The efforts to improve automatic parallelization of the sequential programs has resulted in somewhat better compilers and it helps a programmer to avoid complex routines of parallelization from their programs.
The compiler could re-order the operations provided the re-ordering does not violate/worsen the locality or in a broad sense doesn't violate the actual intention of the of the program.
But I doubt the fact that the compiler would try to re-order a conditional statement
like :
  if ( bar && expensive_foo() )

If the less expensive Boolean function is put at the beginning, it is certain that we can save some time.


text:
Q: while loop terminating after fetching some data I have written a procedure that creates a temporary table and executes a query by fetching the rows from the temporary table.I have around 13486 rows in the temporary table.But when i am calling the procedure i observed that the procedure is getting terminated after fetching 107 rows from the temporary table.Moreover i also observed that this value is not constant..Sometimes it is 107 the other time it is 114 and some other time it is just 100.Why this happens?Please need help?Somebody please..Here is my procedure.And i came to know that while loop will terminate for >1000 iterations.Please suggest me a method to overcome this.
DELIMITER $$

DROP PROCEDURE IF EXISTS `lookup`.`test` $$
CREATE PROCEDURE `lookup`.`test` ()
BEGIN

CREATE  TEMPORARY  TABLE  lookup.airportname(id  int  AUTO_INCREMENT,PRIMARY KEY(id))
AS (select distinct airport_id from lookup.airport);
SET @num=0;
SET @arpt=NULL;
SELECT count(*) INTO @num FROM airportname;
SET @i=0;

while @i<@num do
SELECT airport_id INTO @arpt FROM airportname WHERE id=@i;
select @arpt,@i;
set @i=@i+1;
end while;
END $$

DELIMITER ;

I am using mysql query browser.Thank you.

A: If you want to insert value into id Then it should not be auto_increment. - Remove auto_increment from table definition, it should work

A: delimiter |
create procedure employee_select()
Begin
Declare empno,done int(9);
Declare emp_select Cursor for select emp_no from gross_salary ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
Open emp_select;      // cursor opening
read_loop: loop    // start looping all the datas one by one
fetch emp_select into empno; // fetching the select value into variable empno

//note :variable name should not be same as columne name in select statement"
IF done THEN
   LEAVE read_loop;   // if no more rows, this makes it to leave the loop"
END IF;

//Enter the code you want do for each row

 end loop;

close emp_select;
End |
delimiter ;


text:
Q: How to set the connection of associated table in CakePHP I actually have 2 databases, one named as clientDefaultDb and client1Db.
here's the code of association.
ProductsController
    $connection = ConnectionManager::get('client1Db');
    $productSource = TableRegistry::get('Products', ['connection' =>
             $connection]);

    $products = $productSource->find('all');
    $products->contain(['ProductUnits']);

Here we set the connection of the table to Client1Db
and I call the contain with ProductUnits
ProductTable.php
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('products');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasMany('ProductUnits')
            ->setForeignKey([
                'item_code'
            ])
            ->setBindingKey([
                'item_code'
            ]);

    }

The return is no error.
It fetched the product correctly and have some data, but the problem is there's no data at ProductUnits it's empty.
I tried to manually query directly to the database it return something.
Tried copying the data of ProductUnits at Client1Db then pasted it to the clientDefaultDb then I tried running the code again, and the ProductUnits return the data that i've been copied.
so probably all associated table is difinetely connected to  the default database.
So how can I change the default connection of the associated tables?

A: Use Table::setConnection() on the associated models.
$this->SomeAssoc->setConnection(/* connection here */);

A: I managed to make it work. Thanks @burzum for the idea.
here's the code.
$this->loadModel('ProductUnits');
$connection = ConnectionManager::get('client1Db');
$this->ProductUnits->setConnection($connection);


text:
Q: Writing a python dict into excel I have an extremely long python dict with some keys with more dicts inside like the example below
{
       "dscpTagValue": {"data": 10,
                        "accuracy": Low Drop"}
       "description": "Latency Insensitive"
}
,
{
       "dscpTagValue": {"data": 10,
                        "accuracy": Low Drop"}
       "description": "Latency Insensitive"
}
{
       "dscpTagValue": {"data": 10,
                        "accuracy": Low Drop"}
       "description": "Latency Insensitive"
}

How would I export this into excel?, some dicts could have several dictionaries inside, some dicts could have no other dicts inside just keys and values..

A: Considering the data to be a list of dictionaries, you can use csv.DictWriter() and specify the column names of the csv with the maximum keys. Something like this:
data = [
        {
            "dscpTagValue": {"data": 10, "accuracy": "Low Drop"},
            "description": "Latency Insensitive"
        },
        .
        .
        .
]

import csv

len_keys = [len(d.keys()) for d in data] # no. of keys of each dictionary
csv_columns = list(data[np.argmax(len_keys)]) # csv column headers == longest dict (keys)

try:
    with open('file.csv', 'w') as f:
        writer = csv.DictWriter(f, fieldnames=csv_columns)
        writer.writeheader()
        for d in data:
            writer.writerow(d)
except IOError:
    print('IOError')

A: I highly suggest you to use pandas for these data management operations. Using a list of dictionaries such as:
l = [{'dscpTagValue': {'data': 10, 'accuracy': 'Low Drop'},
  'description': 'Latency Insensitive'},
 {'dscpTagValue': {'data': 9, 'accuracy': 'Low Drop'},
  'description': 'Latency Insensitive'},
 {'dscpTagValue': {'data': 8, 'accuracy': 'Medium Drop'},
  'description': 'Latency Sensitive'}]

You can write it into an excel using to_excel of a pandas Dataframe:
import pandas as pd
df = pd.DataFrame(l)
print(df.to_string())
#                             dscpTagValue          description
#0    {'data': 10, 'accuracy': 'Low Drop'}  Latency Insensitive
#1     {'data': 9, 'accuracy': 'Low Drop'}  Latency Insensitive
#2  {'data': 8, 'accuracy': 'Medium Drop'}    Latency Sensitive

df.to_excel("my_excel_file.xlsx", sheet_name='my sheet name')


text:
Q: How to monitor dead relus I think I might have a problem with dead Relus, but I don't really know how to check it with tensorboard or any other way. Your help would be really appreciated.

A: I initially had this same question myself and couldn't find an answer, so here's how I'm doing it with Tensorboard (This assumes some familiarity with Tensorboard).
activation = tf.nn.relu(layer)
active = tf.count_nonzero(tf.count_nonzero(activation, axis=0))
tf.summary.scalar('pct-active-neurons', active / layer.shape[1])

In this snip, activation is my post-ReLU activation for this particular layer. The first call to tf.count_nonzero(out, axis=0) is counting how many activations each neuron has seen across all training examples for the current step of training. The second call tf.count_nonzero( ... ) that wraps the first call counts how many neurons in the layer had at least one activation for the batch of training examples for this step. Finally, I convert it to a percentage by dividing the number of neurons that had at least one activation in the training step by the total number of neurons for the layer.
More information on setting up Tensorboard can be found here.

A: How about adding the summary

tf.summary.scalar('%s/fraction_of_zero_values' % tag, tf.nn.zero_fraction(value))


text:
Q: how add public key to ssh-agent permanently I added my existed public key to ssh-agent but after restarting I need to run
ssh-add ~/.ssh/id_rsa

to add it again. Is there a way to add it permanently?

A: You can not do that. You would need some secure store for the passphrase and you don't have it in ssh-agent. By storing the passphrase in plaintext, you basically downgrade the security to none (and you would better do by removing the passphrase completely).
There are applications in GNOME that store the passphrase securely encrypted with the account password (gnome-keyring, seahorse), but pure ssh-agent does not know that.


text:
Q: How to see errors from an ionic app from my device Fellows I have made an app by using ionic framework.
When I run
ionic serve

On the terminal it runs as it should be. But when I run it via:
ionic run

I see on the device the app running by displaying the ionic's loading screen, but after that it does not run as it should be.
What I am asking is how can I see - debug any sort of error from the app running on the device in order to figure out what's wrong?
I am using an Adroid device for the tests.

A: Try this :
ionic run android -c -l

// -c for consolelogs and -l for livereload

A: After ionic run android command keep fixed to your cable and laptop.
Go to your chrome and type chrome://inspect you can see your app in that and click inspect so that you can able to look what is going on in your mobile app and you can debug it.

A: You can add additional flags when using  ionic run.

*

*-c will show console logs.

*-s will show server logs.

*-l will perform live reload of the application when code changes.

So you can use something like
ionic run android -cls
Note that for livereload to work if the device is not connected directly make sure its in the same network as the serving device. Make sure to serve to a local IP address in this case (you can use ionic address to change that).

A: I fixed it by running:
adb logcat | grep 'Web Console'

On a linux terminal / git bash


text:
Q: Disabling some controls after the submit button is successful After user fills some values in the form and clicks the submit button I want to disable some controls on the form for example some text boxes and some drop down controls.
Currently my drop down starts like this:
<select name="myquestion_@i" id="questionselect" >

How can I modify it to get disabled after Submit button is clicked? I don't want JS. Just directly with MVC.
I am new to MVC but I think I should do something like this maybe?
<select name="myquestion_@i" id="questionselect" disabled = @Model.DissableIt>

A: <select name="myquestion_@i" id="questionselect"
@{
    if(Model.DissableIt)
    {
        @:disabled="disabled"
    }
}
>


text:
Q: Python using different Tensorflow version than Conda environment I installed tensorflow with pip. When I check my tensorflow version inside the conda environment it shows as 2.7.0 as I want it to be. However when  I check it inside python on the same environment, I get 2.6.0. How can I change this so that in both cases I get 2.7.0? I already tried uninstalling and reinstalling tensorflow inside the environment and upgrading it with pip.
(dataset2vec) C:\Users\sozen>pip show tensorflow
Name: tensorflow
Version: 2.7.0
Summary: TensorFlow is an open source machine learning framework for everyone.
Home-page: https://www.tensorflow.org/
Author: Google Inc.
Author-email: packages@tensorflow.org
License: Apache 2.0
Location: c:\users\sozen\anaconda3\envs\dataset2vec\lib\site-packages
Requires: termcolor, numpy, grpcio, gast, protobuf, absl-py, h5py, typing-extensions, six, tensorflow-io-gcs-filesystem, google-pasta, flatbuffers, tensorboard, keras, wrapt, wheel, keras-preprocessing, libclang, tensorflow-estimator, opt-einsum, astunparse
Required-by: ismlldataset

(dataset2vec) C:\Users\sozen>pip install --upgrade tensorflow
Requirement already satisfied: tensorflow in c:\users\sozen\anaconda3\envs\dataset2vec\lib\site-packages (2.7.0)
Requirement already satisfied: gast<0.5.0,>=0.2.1 in c:\users\sozen\anaconda3\envs\dataset2vec\lib\site-packages (from tensorflow) (0.4.0)

(dataset2vec) C:\Users\sozen>python -c "import tensorflow as tf;print(tf.__version__)"
2.6.0

Cheers

A: I don't know exactly what the problem was but I created a new environment directly installing tensorflow during creation and inside that environment it still used 2.6.0 with python. Then I forced install 2.7.0 and it magically worked!
Here's a list of the commands I used:
conda activate tensorTest
python --version
python -c "import tensorflow as tf;print(tf.__version__)"
pip install tensorflow
python -c "import tensorflow as tf;print(tf.__version__)"
>>Still showed 2.6.0
pip install tensorflow==2.7.0
python -c "import tensorflow as tf;print(tf.__version__)"
>>2.7.0!


text:
Q: AMQ Message Ordering with Exponential Backoff I am curious about the way AMQ handles message ordering when it comes to message redelivery and exponential backoff.
Say you have three messages: [M3,M2,M1]. If I pluck the the M1 message from the head of the queue and my system fails to process it, does M1 go back onto the head of the queue, thus delaying all of the other messages behind it? Or is there some some clever strategy where the message is put on the side until it is ready to be delivered, thus allowing messages M2 and M3 to be processed before M1?

A: I ran an experiment and it looks like strict ordering is maintained. M1 will always be consumed before M2, and so on.


text:
Q: Communicating between two processes on heroku (what port to use) I have a Procfile like so:
web:     bundle exec rails server -p $PORT
em:      script/eventmachine

The em process fires up an eventmachine with start_server (port ENV['PORT']) and my web process occasionally needs to communicate with it.
My question is how does the web process know what port to communicate with it on?  If I understand heroku correctly it assigns you a random port when the process starts up (and it can change if the ps is killed or restarted).  Thanks!

A: According to Heroku documentation,
Two processes running on the same dyno can communicate over TCP/IP using whatever ports they want.
Two processes running on different dynos cannot communicate over TCP/IP at all. They need to use memcached, or the database, or one of the Heroku plugins, to communicate.

A: Processes are isolated and cannot communicate directly with each other.
http://www.12factor.net/processes
There are, however, a few other ways.  One is to use a backing service such as Redis, or Postgres to act as an intermediary - another is to use FIFO to communicate.
http://en.wikipedia.org/wiki/FIFO
It is a good thing that your processes are isolated and share-nothing, but you do need to architecture your application slightly differently to accommodate this.

A: I'm reading this while on my commute to work. So I haven't tried anything with it (sorry) but this looks relevant and potentially awesome.
https://blog.heroku.com/archives/2013/5/2/new_dyno_networking_model


text:
Q: Given a set $A=\{ B \subseteq \mathbb{R}\}$, is this relation $R$ of equivalence? $$A=\{B\subseteq \mathbb{R}\}$$
$$R: (C,D) \in R \iff C\setminus D \text{ or } D\setminus C \text{ is not greater than countable}$$
The question: Is $R$ a relation of equivalence? If it is, what class of equivalence?
It's reflexive: $(C,C) \in R \iff C \setminus C = \emptyset$, which has a cardinality less than countable. As for rest () I'm lost.
Symmetric: $(C,D) \in R \hookrightarrow (D,C) \in R \iff C \setminus D\text{ or } D\setminus C\text{ less than countable } \hookrightarrow C \setminus D \text{ or } D\setminus C \text { less than countable}$
Transitive: $(C\setminus D \text{ or } D\setminus C \text{ less than countable) and (} D\setminus E \text{ or } E\setminus D \text{ less than countable} ) \hookrightarrow (C,E) \in R$
(how can you show if this is last statement is true or not?)
What about the second part of the question?

A: Symmetry is trivial: $(C,D)\in R$ means either $C\setminus D$ is countable or $D\setminus C$ is countable. Therefore either $D\setminus C$ is countable or $C\setminus D$ is countable and so $(D,C)\in R$.
But Transitivity fails: Consider $C=(-1,0]$, $D=(-1,1)$ and $E=[0,1)$. Then $C\setminus \{1\}=E\setminus D$ so that $(C,D)\in R$ and $(D,E)\in R$. But $C\setminus E=(-1,0)$ and $E\setminus C=(0,1)$. Neither of which are countable. So $(C,E)\not\in R$
Note: I am using "countable" to mean "at most countable"


text:
Q: Unix sockets doesn't work with PHP on Apache I wrote a following short script in PHP:
<?
$s = socket_create(AF_UNIX,SOCK_STREAM,0);
socket_connect($s,"/tmp/tmpsock");
socket_write($s,"test");
socket_close($s);
>

I user this code to connect to a simple server that prints everything it receives onto terminal output.
The script works fine when I opened it from terminal using php index.php, however I want it to be a part of a webapp, and I try to run it on apache2 server opening the index.php page in web browser (on server of course). The script doesn't work then - the socket_connect function returns nothing, the error description is "Success()" and the message doesn't appear on server.
I use Ubuntu 16.04, Apache 2.4 and PHP 7.0


text:
Q: Firebase custom application setup customApp= new FirebaseApp(getApplicationContext(),"My News",<to be filled>);
    storage = FirebaseStorage.getInstance(customApp);

I'm new to firebase and what is the exact use of the custom App.
I want to create a custom app to upload large files to google cloud storage using firebase. is that custom app recommended for me?

A: No need to use customApp;
Simply we can use
storage = FirebaseStorage.getInstance("gs://<Google cloud storage bucket name>");

If we want storage references then
mStorageRef = storage.getReferenceFromUrl("gs://<Google cloud storage bucket name>");

A:   @Override
public void onCreate() {
    super.onCreate();
    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApiKey("AI...3LnY")
            .setStorageBucket("gs://f...t")
            .setApplicationId("1:356....:android:f......232")
            .build();
    customApp = FirebaseApp.initializeApp(getApplicationContext(),options,"MyApp");
    //storage
    storage = FirebaseStorage.getInstance(customApp);`enter code here`

}

A: If you're new to Firebase, chances are you don't need a custom FirebaseApp. Instead, just use FirebaseStorage.getInstance().getReference() as shown in the Firebase Storage documentation.

A: Great answer Mr. Frank van Puffelen.
It's working for me (imported bucket from Google Cloud Storage.)
mStorageRef = FirebaseStorage.getInstance("gs://c......s").getReference();

Download the file from google cloud storage to a local device using firebase.
final StorageReference downloadRef;
        downloadRef = mStorageRef.getRoot().child(downloadPath);

        try {
            File output = new File(Environment.getExternalStorageDirectory() + File.separator + Config.MY_VIDEOS_PATH);
            if (!output.exists()) {
                output.mkdir();
            }
            localFile = new File(output, downloadId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Download and get total bytes
        downloadRef.getFile(localFile)
                .addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(FileDownloadTask.TaskSnapshot taskSnapshot) {
                        showProgressNotification(title, "",
                                taskSnapshot.getBytesTransferred(),
                                taskSnapshot.getTotalByteCount());
                    }
                })
                .addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                        Log.d(TAG, "download:SUCCESS");
                        // Send success broadcast with number of bytes downloaded
                        broadcastDownloadFinished(downloadPath, taskSnapshot.getTotalByteCount());
                        showDownloadFinishedNotification(downloadPath, (int) taskSnapshot.getTotalByteCount());

                        // Mark task completed
                        taskCompleted();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        Log.w(TAG, "download:FAILURE", exception);
                        Log.w(TAG, "download:FAILURE", exception.getCause());

                        // Send failure broadcast
                        broadcastDownloadFinished(downloadPath, -1);
                        showDownloadFinishedNotification(downloadPath, -1);

                        // Mark task completed
                        taskCompleted();
                    }
                });


text:
Q: what is the difference between "reservation" and "advance reservation"? Aren't they both have meaning of 'pre'?
I'm Korean and there's same problem in Korean. But there's no clear answer so I came here
please let me know plz

A: Whether advance is redundant in advance reservation depends on the context. Usually the phrase stands for a reservation that is made in advance of whatever it is for; when so used, advance in it is indeed redundant. As Anton's answer explains, that may or may not be undesirable.
There may, however, be special contexts in which advance reservation stands for a reservation that is made in advance of the time when the relevant reservations are normally made. In such a context, advance is not redundant.

A: Your question relates to the use of redundancy in English. You will find your example and many others discussed in:

One way to cut the clutter in our writing is to eliminate repetitious expressions. Because we so often see and hear redundancies (such as "free gifts" and "foreign imports"), they can be easy to overlook. Therefore, when editing our work, we should be on the lookout for needless repetition and be ready to eliminate expressions that add nothing to what's been said.
Now does this mean that repetition must be avoided at all costs, or that good writers never repeat themselves? Certainly not. Careful repetition of key words and sentence structures can help establish clear connections in our writing. In effective rhetorical strategies of repetition, we consider how writers may rely on repetition to emphasize or clarify a central idea.
Our concern here is with eliminating needless repetition — redundant expressions that make writing longer, not better. Following are some of the common redundancies in English. In specific contexts, some of these phrases may serve a purpose. More often, however, the phrases weigh down our writing with unnecessary words. We can eliminate the needless repetition in each case by omitting the word or phrase in parentheses.
(absolutely) essential; (absolutely) necessary; (actual) facts; advance (forward); (advance) planning; (advance) preview; (advance) reservations; ...
ThoughtCo


text:
Q: Quasi-binomial GLM in R I'd like some advice on data I'm analyzing from a factorial-design study in which each sample is a count of 200 urchin eggs that were exposed to various types and concentrations of pollutants, and for each sample we counted how many urchin eggs were fertilized. However, since the 200 eggs for each sample come from the same individual and are exposed to the treatments together as a batch, the 200 counts cannot be considered independent. I've tried fitting multiple models with this data, but each has an obvious flaw to me that I'd like to overcome:

*

*The binomial logistic regression assumes that each of the 200 counts are independent, vastly inflating power so that all p-values are very small.

*Beta models on the proportion of eggs fertilized (at least, the beta model implemented in the R package "betareg") do not accept values that are exactly 0 or 1, of which I have several. This would require rebounding values that are 0 or 1 before fitting the model.

*An OLS regression with a logit transform of the proportion data has the same issue, requiring me to rebound values to an arbitrary interval within (0, 1).

Another researcher who has worked with similar data has recommended using ordinary linear regression with a transformation of logit(p*0.95 + 0.025) for the raw proportions, but this seems arbitrary to me and complicates the interpretation of the results, which are no longer simply on the log-odds scale.
One thing I did try is a GLM with a quasi-binomial distribution, which ran fine and produced similar qualitative results to the logit-linear model, and accepted proportions that were 0 or 1. I think there's a legitimate basis for using a quasi-binomial, as after rebounding the response to (0.01, 0.99) and logit transforming it, the variance is still higher for treatments with intermediate proportions than with those towards the extremes, and since the logit transform is supposed to stabilize the variance, this seems like a fair reason to use a model that accounts for over-dispersion. Additionally, it seems reasonable that eggs from different urchins could have different probabilities of fertilization success, and we might therefore expect over-dispersion in the data a-priori.
What's surprising to me, however, is that the quasi-binomial implementation in R seems not to be affected by sample size - if I run the model with proportions, the results are exactly the same as if I run the model with the raw counts of fertilized and unfertilized eggs, or if I run the model with proportions and include the number of eggs (again, 200 per sample) in the "weights" argument, or even if I arbitrarily alter the sample size. To me, this is a desirable property, but it's inconsistent with the definitions of the quasi-binomial distribution that I've seen online, which has a parameter for the number of trials just as the binomial distribution does.
My questions, therefore, are:

*

*Am I justified in using a quasi-binomial model over a beta model or logit-transformed linear regression, taking into account the possible overdispersion and the need to rebound values that are 0 or 1? I haven't seen this model used in many other studies (not that I've looked much), but it runs and seems to make sense...

*Why is the quasi-binomial implementation in base R insensitive to sample size? Is this a property specific to R's implementation, or a general property of quasi-binomial GLMs?

*If the quasi-binomial GLM runs in base R with proportion data and no information on sample size, why isn't the standard binomial model capable of this? Maybe it is, but it's not something I've been able to make work in R.


text:
Q: $("select#mySelect option[value='option1']").remove() when "select#mySelect" is actually a jQuery selector? I've been looking at this answer https://stackoverflow.com/a/9048545/364088 which presents the following code.
$("select#mySelect option[value='option1']").remove()

That's useful but what can be done if you already have a variable initialized like this .
var mySel = $("select#mySelect");

How would you be able to incorporate that variable into the ".remove" example shown above ?
Something like this (but obviously not this)
mySel.("option[value='option1']").remove()

A: Use .find to find descendants matching a particular selector:
mySel.find("option[value='option1']").remove()


text:
Q: Google Sheets Script Not Outputting to Datasheet I'm currently having an issue with this simple script that basically just copies and pastes input data.
The function inputting the value to the Sales Log tab but not the Pay Log tab for some reason. I'm not well versed in any form of coding so help is greatly appreciated!
function submit() {
  var ss        = SpreadsheetApp.getActiveSpreadsheet();
  var formSS    = ss.getSheetByName("Food Sales");
  var datasheet = ss.getSheetByName("Pay Log");
  var datasheet = ss.getSheetByName("Sales Log");

  var values = [[formSS.getRange("E10").getValue(),
                 formSS.getRange("E11").getValue(),
                 formSS.getRange("E12").getValue()]];

  datasheet.getRange(datasheet.getLastRow()+1, 1, 1, 3).setValues(values);

}

A: This is because you are using the same variable dataSheet for two different sheets.
On the line var datasheet = ss.getSheetByName("Pay Log"); you assigned the Pay Log sheet on the datasheet but then replaced it by the Sales Log sheet on the next line var datasheet = ss.getSheetByName("Sales Log");
What you can do is create and assign different variables for both sheets before pasting. Simple way you can do it is by the code below.
function submit() {
  var ss        = SpreadsheetApp.getActiveSpreadsheet();
  var formSS    = ss.getSheetByName("Food Sales");
  var datasheet1 = ss.getSheetByName("Pay Log");
  var datasheet2 = ss.getSheetByName("Sales Log");

  var values = [[formSS.getRange("E10").getValue(),
             formSS.getRange("E11").getValue(),
             formSS.getRange("E12").getValue()]];

 datasheet1.getRange(datasheet1.getLastRow()+1, 1, 1, 3).setValues(values);
 datasheet2.getRange(datasheet2.getLastRow()+1, 1, 1, 3).setValues(values);

}

Or in case you have more sheets to paste your data into, you can use the getSheets() function which will return an array that contains all your sheets. You can then loop through the sheets starting from your second sheet. Example code below
function submit() {
  var ss        = SpreadsheetApp.getActiveSpreadsheet();
  var formSS    = ss.getSheetByName("Food Sales");
  var dataSheet = ss.getSheets();

  var values = [[formSS.getRange("E10").getValue(),
             formSS.getRange("E11").getValue(),
             formSS.getRange("E12").getValue()]];

  for (i = 1; i < dataSheet.length; i++){
    dataSheet[i].getRange(dataSheet[i].getLastRow()+1, 1, 1, 3).setValues(values);
    };

 };

*

*Refer to this link for more details on the Class Spreadsheet: https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getsheets

A: Using getValues
function submit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var formSS = ss.getSheetByName("Food Sales");
  var datasheet1 = ss.getSheetByName("Pay Log");
  var datasheet2 = ss.getSheetByName("Sales Log");
  var values = formSS.getRange(10, 5, 3).getValues();//getValues()
  datasheet1.getRange(datasheet1.getLastRow() + 1, 1, 1, 3).setValues(values);
  datasheet2.getRange(datasheet2.getLastRow() + 1, 1, 1, 3).setValues(values);
}


text:
Q: Is $H_{m}$ a measurable set? Let $\mathbb{R}^{4}$ be equipped with its usual Euclidean topology and associated Borel $\sigma$-algebra. If $x = (x_{0},x_{1},x_{2},x_{3}) \in \mathbb{R}^{4}$, define $\tilde{x}$ by $(x_{0},-x_{1},-x_{2},-x_{3})$ and:
$$x\cdot \tilde{x} := x_{0}^{2}-x_{1}^{2}-x_{2}^{2}-x_{3}^{2} $$
For each $m\ge 0$, let $H_{m}$ be the hyperboloid:
$$H_{m}:= \{x\in \mathbb{R}^{4}: \hspace{0.1cm} x\cdot \tilde{x} = m^{2}, x_{0} > 0\}$$
Question: I believe $H_{m}$ is a measurable set on $\mathbb{R}^{4}$, but I wasn't able to find a criative way to prove it. Any ideas?


text:
Q: How to properly use -Exclude in Remove-Item for a list of string from a variable in Powershell? I have a variable that stored the list of files to be removed in this format:
$list = """" + "file1.txt" + """"

and a complete $list would be looking something like this:
$list
"file1.txt","file2.txt","file3.txt",...

and trying to use Remove-Item with the variable failed, it removed all the files:
Remove-Item -Recurse -Path "c:\myfiles\*" -Exclude $list

How to properly achieve this? Thanks in advance!

A: You're close but $list needs to be an array not a string (with excess quotes).
Just quote each element, and separate them with a comma to do this:
$list = "file1.txt","file2.txt"

Remove-Item -Path "c:\myfiles\*" -Recurse -Exclude $list -WhatIf

I would also recommend reading about_quoting_rules as it seems you don't know that double and single quotes do different things.
Using single quotes instead:
$list = """" + "file1.txt" + """"

can be expressed as:
$list = '"file1.txt"'

(These extra quotes aren't needed for the code above)


text:
Q: Django: convert .count value returned to int I have a the following models:
class Question(models.Model):
    question = models.CharField(max_length=100)

class Answer(models.Model):
    question = models.ForeignKey(Question)
    value = models.CharField(max_length=200)

I want to calculate the % of answers with the value "yes" for a given question object but I get the error TypeError int() argument must be a string or a number, not 'method'. Does count not return a int data type?
My view:
def questn(request, question_id):
    q = Question.objects.select_related().get(id=question_id)
    qc = q.answer_set.count
    qyc = q.answer_set.filter(value="YES").count
    qycp = ( int(qy) / int(qc) ) * 100
    return render(request, 'base.html', {
        'q':q,
        'qc':qc,
        'qyc':qyc,
        'qycp':qycp,
    })

A: You need to invoke count:
qc = q.answer_set.count()

Adding the () invokes the count method.  Not having it makes qc refer to the count method itself.
Here is an example:
>>> a = [1, 2, 3, 4]
>>> a.clear
<built-in method clear of list object at 0x02172198>
>>> a
[1, 2, 3, 4]
>>> a.clear()
>>> a
[]
>>>

As you can see, the clear method of a list is only invoked once the () is added.


text:
Q: Binding ViewModel to DataGrid In my application there's a screen that behaves much like excel (datagrid).
I already made this application but I wanted to make everything MVVM in
Version 2..
I want to be able to bind my DocumentViewModel to my DataGrid but I haven't been able to do this correctly yet.
Most importantly is the Cell class where i would like to bind every property in there to the View.
ViewModel:
public class DocumentViewModel : IDocumentViewModel
{
    int _assetID;
    string _documentName
    Table _table

    public DocumentViewModel(int assetID, string documentName, Table table)
    {
        _assetID = assetID;
        _documentName = documentName;
        _table = table;
    }

    public int AssetID { get { return _assetID; } }

    public string DocumentName { get { return _documentName; } }

    public Table Table
    {
        get { return _table }
        set
        {
            if (value != null)
            {
                _table = value
            }
        }
    }

}

public class Table
{
    ObservableCollection<Column> _columns;
    ObservableCollection<Row> _rows;

    public Table()
    {
        _columns = new ObservableCollection<Column>();
        _rows = new ObservableCollection<Row>();
    }

    public ObservableCollection<Column> Columns
    {
        get { return _columns; }
        set { _columns = value; }
    }

    public ObservableCollection<Row> Rows
    {
        get { return _rows; }
        set { _rows = value; }
    }
}

public class Column
{
    public string Header { get; set; }
    public int Index { get; set; }
    //public int ColumnWidth { get; set; }

}

public class Row
{
    public List<Cell> Cells;
}

public class Cell
{
    public int ID { get; set; }
    public string Value { get; set; }
    public bool HighLight { get; set; } //ignore highlight for now
    public bool Bold { get; set; }
    public string ForeGroundColor { get; set; }
    public string BackGroundColor { get; set; }
}

View:
I set a filled DocumentViewmodel to the DataContext property of my UserControl in codebehind.
When i run my program it doesn't give any errors but the DataGrid remains empty (No columns or rows added)
<UserControl x:Class="ViewModel.TableViewControl"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ViewModel"
        xmlns:commands="clr-namespace:ViewModel.Commands"
        xmlns:viewmodels="clr-namespace:ViewModel.ViewModels"
        mc:Ignorable="d">
    <DockPanel>
        <DataGrid Name="dg_TableGrid" DataContext="{Binding Table}"><!--  -->
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.HeaderTemplate>
                        <DataTemplate>
                            <ItemsControl ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Column}">
                                <ItemsControl.ItemsPanel>
                                    <ItemsPanelTemplate>
                                        <StackPanel Orientation="Horizontal" />
                                    </ItemsPanelTemplate>
                                </ItemsControl.ItemsPanel>
                                <ItemsControl.ItemTemplate>
                                    <DataTemplate>
                                        <TextBlock Margin="2" Width="{Binding Width}" Foreground="{Binding ForeGroundColor}" Text="{Binding Header}" />
                                    </DataTemplate>
                                </ItemsControl.ItemTemplate>
                            </ItemsControl>
                        </DataTemplate>
                    </DataGridTemplateColumn.HeaderTemplate>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ItemsControl ItemsSource="{Binding Rows}">
                                <ItemsControl.ItemsPanel>
                                    <ItemsPanelTemplate>
                                        <StackPanel Orientation="Horizontal" />
                                    </ItemsPanelTemplate>
                                </ItemsControl.ItemsPanel>
                                <ItemsControl.ItemTemplate>
                                    <DataTemplate>
                                        <TextBox Margin="2" Width="{Binding Width}" Text="{Binding Data}" />
                                    </DataTemplate>
                                </ItemsControl.ItemTemplate>
                            </ItemsControl>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </DockPanel>
</UserControl>


text:
Q: Help to create a notation!! If $A$ is an algebra and $D_1, D_2\in A$ we can define the commutator $$[D_1, D_2]:=D_1\circ D_2-D_2\circ D_1.$$
I'd like to create an analogous notation to sum up things like these:
$$D_1\circ D-D\circ D_2.$$
It must be a notation which makes sense in general.
It seems something silly, but I am going to use this in another context where expressions like this are huge and very frequent so it would be very useful to have such a notation.
Thanks.


text:
Q: Is it possible to get a NSTimeZone instance from CLLocation (or CLLocationCoordinates2D)? I was doing a lot of research around this and it's hard for me to think that it is not possible to get an instance of NSTimeZone for a given CLLocation instance (or coordinates) using built-in iOS libraries.
Around the web I saw solutions using a third party rest service or using APTimezones, anyone knows how to do it with apple's frameworks?

A: CLLocation does not contain a timezone.  There's no reason for that.  It does have an NSDate that specified the date/time the point was recorded, but NSDate's are always UTC time.  You only need a timezone when displaying time in local time.


text:
Q: Absolutely positioning images inside relatively positioned div I've seen several posts related to this issue, but still can't get the following to work:

.container {
  position: relative;
  width: 100%;
}

.left {
  position: absolute;
  left: 0px;
}

.right {
  position: absolute;
  right: 0px;
}

According to http://www.w3schools.com/css/css_positioning.asp, specifically the line that says:

An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is

The issue is that the container div has no height. I'd really like to not have to specify the height of the container div. I know that floating the one image left, and the other image right, and setting overflow: auto on the container div will work, but I guess I was hoping to not have to go that route since I like the technique of absolute positioning inside a relative div.
Is this possible?

A: There is no natural way for the parent container to resize dynamically to your absolutely positioned children because the children are outside of the flow.
The best way of doing what you are describing is to use floats, and a clearing method:

body {
  padding: 20px;
}

.container {
  position: relative;
  width: 100%;
  background: yellow;
}

.left {
  float: left;
  background: red;
  width: 100px;
  height: 200px;
}

.right {
  float: right;
  background: blue;
  width: 100px;
  height: 200px;
}

/* Use the clearfix technique: http://www.yuiblog.com/blog/2010/09/27/clearfix-reloaded-
    overflowhidden-demystified/ */

.clearfix:before,
.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  overflow: hidden;
}

.clearfix:after {
  clear: both;
}

.clearfix {
  zoom: 1;
}

/* IE < 8 */

      Left

      Right

If you insist on doing absolute positioning and need the parent container to match the height of the children, you will have to resort to javascript.


text:
Q: converts svg array of points to curve I am trying to convert a array of points into a curve/path in SVG.
I have something like [[0,0], [100,50], [50,100], [350,50]] and would like to convert that to a curve. I supose it has to be a path, with with the control points for the curves.
I tested appending new path to the svg with
var svg = document.querySelector('svg');
var points = [
    [100, 100],
    [200, 150],
    [100, 200],
    [100, 300],
    [300, 300]
];
points.forEach(function (point, i, points) {
    if (!i) return;
    var start = points[i-1];
    var end = point;

    var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    var x = Math.round((start[0] + end[0]) / 1.5);
    var controlA = x + ',' + start[1];
    var controlB = x + ',' + end[1];

    path.setAttribute('d', 'M' + start.join(',') + ' C' + controlA + ' ' + controlB + ' ' + end.join(','));
    path.setAttribute('stroke', 'black');
    path.setAttribute('stroke-width', 1);
    path.setAttribute('fill', 'none');
    svg.appendChild(path);
});

But that didn't work as expected...
Any suggetion are apreciated. What i would like to achieve is a more "hand drawed" curve, with no har corners...
http://jsfiddle.net/3vgyf1qm/1/


text:
Q: Why is a static lifetime needed when using move? A thread should read content from stdout or stderr in pass the read content to via a channel.
Now want to create one Thread for stdout and one for stderr, because I they have the same behaviour I dont want to pass the ChildStdout and ChildStderr structs rather than the a generic that implements the Read trait.
This is my method:
fn start_read_thread<T : Read + Send>(stdout: Option<T>, process: &mut Child) -> Result<Receiver<Result<Vec<u8>, ()>>, ()> {
    let (tx_stdout, rx_stdout): (Sender<Result<Vec<u8>, ()>>, Receiver<Result<Vec<u8>, ()>>) = mpsc::channel();
    std::thread::spawn(move || {
        for b in stdout.unwrap().bytes() {
            let b = b.unwrap();
        }
    });
    return Ok(rx_stdout);
}

Now the compiler says:
    the parameter type `T` may not live long enough
   --> shell_execution\src\powershell.rs:146:17
    |
142 |     fn start_read_thread<'a, T : Read + Send>(stdout: Option<T>, process: &mut Child) -> Result<Receiver<Result<Vec<u8>, ()>>...
    |                              -- help: consider adding an explicit lifetime bound...: `T: 'static +`
...
146 |                 std::thread::spawn(move || {
    |                 ^^^^^^^^^^^^^^^^^^ ...so that the type `[closure@shell.rs:146:36: 148:18]` will meet its required lifetime bounds

Should T not always live long enough, because it gets moved to the thread scope it can't be dropped somewhere else?
Replacing T with ChildStdout works, without the need of adding the static lifetime.
Does someone know why this is happening, and do I build a memory leak with this static lifetime?
Thanks
playground


text:
Q: Android problem with nine-patch png elevation profile I am working with an ui showing chat records where needs message bubbles(for containing message text),I konw i shoud using 9-patch png and so i did,but i got an confusing problem.[Click here to view image][1] https://i.stack.imgur.com/qK2FY.jpg
As you see,the right bubble has a normal elevation as expected but the left not but with a rectangle profile.The problem is that the left one is just mirrored from the right one(I have adjust the 9-patch reference lines).So what wrong with that?
There is another clue that when i replace the left bubble png with the right bubble png,the problem is still there.The following is my layout xml.
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="end"
    android:orientation="horizontal">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/iv_avatar"
        android:layout_width="@dimen/d_fab_mini"
        android:layout_height="@dimen/d_fab_mini"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="@dimen/spacing_normal"
        tools:src="@drawable/avatar_default" />

    <TextView
        android:id="@+id/tv_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/iv_avatar"
        android:layout_marginTop="@dimen/spacing_small"
        android:layout_marginEnd="@dimen/spacing_normal"
        android:layout_marginBottom="@dimen/spacing_normal"
        android:layout_toStartOf="@+id/iv_avatar"
        android:autoLink="web"
        android:background="@drawable/bubble_sent"
        android:elevation="@dimen/z_card"
        android:gravity="center_vertical"
        android:letterSpacing="@fraction/letter_spacing_message"
        android:paddingStart="@dimen/spacing_large"
        android:paddingTop="@dimen/spacing_small"
        android:paddingEnd="@dimen/spacing_large"
        android:paddingBottom="@dimen/spacing_small"
        android:textColor="@android:color/white"
        tools:text="你好,我是XJUNZ" />

</RelativeLayout>


text:
Q: How to display a number/integer in a TableView? I'm trying to build a simple app in which the user would input a date from a date picker(a birthday or any event), then the code would subtract today's date from the date the user gave the app, to get the difference in days and then display a countdown of the number of days left in a table view, along with the name of the event. I have 2 View Controllers, the main TableViewController and then the AddViewController. I've figured out how to get the difference in days, my table view is set up and all the code is running quite well. I just have a problem in displaying the number of days left in the table view as they are integers. I would love to get some help from more experienced developers as I'm relatively new to iOS programming. So without further due, here's my code:
@IBAction func addButtonTapped(sender: AnyObject) {

    var chosen: NSDate = self.datePicker.date
    var today: NSDate = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.DayCalendarUnit, fromDate: today, toDate: chosen, options: nil)
    let secondsInADay = ((60 * 60) * 24)
    let daysLeft = (components.hashValue / secondsInADay)

    var userDefaults: NSUserDefaults = NSUserDefaults()
    var itemList: NSMutableArray? = userDefaults.objectForKey("itemList") as? NSMutableArray

    var dataSet: NSMutableDictionary = NSMutableDictionary()
    dataset.setObject(eventTextField.text, forKey: "itemEventName")
    dataSet.setObject(datePicker.date, forKey: "itemEventDate")
    dataSet.setObject(daysLeft, forKey: "itemDaysLeft")

    if ((itemList) != nil) {

        var newMutableList: NSMutableArray = NSMutableArray()

        for dict: AnyObject in itemList! {

            newMutableList.addObject(dict as NSDictionary)

        }

        userDefaults.removeObjectForKey("itemList")
        newMutableList.addObject(dataSet)
        userDefaults.setObject(newMutableList, forKey: "itemList")

    } else {
        userDefaults.removeObjectForKey("itemList")
        itemList = NSMutableArray()
        itemList!.addObject(dataSet)
        userDefaults.setObject(itemList, forKey: "itemList")

    }

    userDefaults.synchronize()
    self.navigationController?.popToRootViewControllerAnimated(true)

}

So above is the code in my addViewController, users input a name from a text field, and a date from a date picker. Below is a part of the code in my tableViewController. Basically I want the Int daysLeft to be displayed in the cell.
    var toDoItems: NSMutableArray = NSMutableArray()

override func viewDidAppear(animated: Bool) {
    var userDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var itemListFromUserDefaults: NSMutableArray? = userDefaults.objectForKey("itemList") as? NSMutableArray

    if ((itemListFromUserDefaults) != nil) {
        toDoItems = itemListFromUserDefaults!
    }
    self.tableView.reloadData()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:       NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    var toDoItem: NSDictionary = toDoItems.objectAtIndex(indexPath.row) as NSDictionary
    cell.textLabel?.text = toDoItem.objectForKey("itemDaysLeft") as? String

    return cell
}

A: Put a break point on this line:     var toDoItem: NSDictionary = toDoItems.objectAtIndex(indexPath.row) as NSDictionary to see what toDoItemContains, just to verify that it is actually what you expect it to be.  But I think the below code may help.
Instead of:
cell.textLabel?.text = toDoItem.objectForKey("itemDaysLeft") as? String
try:
cell.textLabel?.text = NSString(format:"%@", toDoItem.objectForKey("itemDaysLeft")) as String


text:
Q: Probability and Statistics question on sequences and vowels How many 4-letter "words" (sequences of letters with repetitions allowed) in which vowels appear only
(if at all) as the first and last letter?
please answer as soon as you can, really appreciate it!!

A: This is equivalent to calculating the number of 4 letter words with no vowels in positions 2,3. This gives $26^2\cdot 21^2$ because all letters are valid is the 1st and 4th positions.


text:
Q: Android BLE Scan unstable 6.0.1 I am using Android 6.0.1 and I am facing BLE Scan issue. The problem is sometimes the scan results return no device and sometimes it returns device. It means I have a remote device by name 'A'. 'A' is discovered and shown in my app once and again after few seconds, 'A' disappears in my discovered window and again re-appears after few seconds. This is the problem which I am facing in Samsung S5. But the same app running in Samsung S6 and S7 works fine with scanning.
I have given necessary permission for Location Services too and my GPS is ON. What could be the problem stil?


text:
Q: Repeat action for different worksheets Newbie here! I have an action which I'd like to repeat, for specific workbooks or specific worksheets.
Is there a way to do it without copy and pasting the whole code for the 2nd, 3rd etc worksheets?
Only the workbook and the worksheet names change. other actions (e.g. copy paste) remains the same.
Although there's a "For Each loop", but I don't know how to do it in a way that allows me to specify which worksheets exactly.
For example, I'm

*

*Step 1: copying data from workbook "Red" sheet "Apple". paste into output
workbook.

*Repeat action. Step 2: copying data from workbook "Yellow" sheet "Banana". paste into
same output workbook.

Here's my code if anyone could kindly advise. VBA newbie here thank you!
Sub CopyPastefromOtherWB()

Range("B13").Select

    'Activate WB1
            Workbooks.Open Filename:= "C:\Users\Desktop\My macro projects\Red"

            Worksheets("Apple").Activate

            Range("A1").Select

            Do While Selection.Value <> "Mar"
            ActiveCell.Offset(0, 1).Select

            Loop

            ActiveCell.Offset(1, 0).Select
            Range(ActiveCell, ActiveCell.End(xlDown)).Select
            Selection.Copy

    'Activate output notebook
            Workbooks.Open Filename:= "C:\Users\Desktop\My macro projects\OutputWB"
            Worksheets("Sheet1").Activate
            Range("B13").PasteSpecial paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

    'HERE IS WHERE THE REPEAT HAPPENS. Activate WB2
            Workbooks.Open Filename:= "C:\Users\Desktop\My macro projects\Yellow"

            Worksheets("Banana").Activate

            Range("A1").Select

            Do While Selection.Value <> "Mar"
            ActiveCell.Offset(0, 1).Select

            Loop

            ActiveCell.Offset(1, 0).Select
            Range(ActiveCell, ActiveCell.End(xlDown)).Select
            Selection.Copy

    'Activate output notebook
            Workbooks.Open Filename:= "C:\Users\Desktop\My macro projects\OutputWB"
            Worksheets("Sheet1").Activate
            Range("C13").PasteSpecial paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

    ActiveCell.Offset(0, 1).Select

End Sub

A: Please see How to avoid using Select in Excel VBA.
Sub CopyPastefromOtherWB(ByVal FromPath As String, ByVal FromSheetName As String, ByVal TargetCell As Range)
    With Workbooks.Open(FromPath)
        With .Worksheets(FromSheetName)
            Dim c As Range
            Set c = .Rows(1).Find("Mar", LookAt:=xlWhole).Offset(1, 0)

            TargetCell.Resize(c.Rows.Count, 1).Value = .Range(c, c.End(xlDown)).Value
        End With

        .Close False
    End With
End Sub

With Workbooks.Open("C:\Users\Desktop\My macro projects\OutputWB").Worksheets("Sheet1")
    CopyPastefromOtherWB "C:\Users\Desktop\My macro projects\Red", "Apple", .Range("B13")
    CopyPastefromOtherWB "C:\Users\Desktop\My macro projects\Yellow", "Banana", .Range("C13")
End With

A: After months of learning, I developed a solution, feel free to use the code below and tweak it to your needs. This solution is for a set area of cells.
Sub copypaste_adhoc()

    Dim inputfile As Workbook

    Set inputfile = Workbooks.Open("c:\path\workbook")

    Dim arrSht, i
    arrSht = Array("worksheet1", "worksheet2")

        For i = LBound(arrSht) To UBound(arrSht)

            With Worksheets(arrSht(i))

            .Range("A31:Z31").Copy

            ThisWorkbook.Sheets("Sheet1").Cells(Sheet5.Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues

            End With
            Next i

            Application.CutCopyMode = False

    Sheet5.Range("a1").CurrentRegion.EntireColumn.AutoFit

End Sub


text:
Q: Upload multiple laravel web files in hostinger I have created a sub-directory and  i uploaded new files public_html files and then its' showing 500 and some times access denied
Need to upload multiple laravel file in one shared hosting


text:
Q: Decrypting GPG encrypted file in gihub actions fails, seemingly due to corrupt file So this is a strange one. I've been following the guide for keeping large secrets (use GPG to symmetrically/password-encrypt the file, set the passphrase as a secret, decrypt at action runtime). The problem is that every time I try to decrypt the file, the decryption fails with either gpg: Fatal: zlib inflate problem: invalid distance too far back or  gpg: block_filter 0x00000008000488d0: read error (size=7858,a->size=262834) gpg: block_filter: pending bytes!
Both of those error messages, combined with the fact that if I check the MD5 of the files locally and in the runner they don't match, lead me to believe the files are getting corrupted somehow, but I'm not sure how. I've tried committing them both via local git, and by uploading them through the web ui (to hopefully eliminate LF/CRLF issues) but no dice.
The command I'm using to encrypt:
gpg --symmetric --cipher-algo AES256 .\secret_file.json
And the step in my build process that decrypts:
      - shell: pwsh
        env:
          DECRYPTION_PASSPHRASE: ${{ secrets.DECRYPTION_PASSPHRASE }}
        run: |
          gpg --quiet --batch --yes --decrypt --passphrase=$env:DECRYPTION_PASSPHRASE --output secret_file.json secret_file.json.gpg

Locally, I'm using gnupg 2.2.27 installed via chocolatey, and my build is running on github's windows-2019 runner. Any advice would be very appreciated!

A: I was able to get this working. This may not be an answer if you absolutely need the standard encryption, but ascii-armoring the encrypted file by adding the --armor flag to the encryption command serves as a usable workaround in my case. Guessing this is an artifact of how checkouts work on windows runners.

A: If you're using this command to encrypt:
gpg --symmetric --cipher-algo AES256 ./secret_file.json

Then try this yaml to decrypt:
- shell: pwsh
  env:
    DECRYPTION_PASSPHRASE: ${{ secrets.DECRYPTION_PASSPHRASE }}
  run: |
    echo $DECRYPTION_PASSPHRASE | gpg -d --cipher-algo AES256 --batch --yes --passphrase-fd 0 ./secret_file.json.gpg > ./secret_file.json


text:
Q: How to run ASP.NET MVC 1 and 2 on the same machine? I have developed a site using MVC 1, then updated to MVC 2 Preview 1 and now when I open the site I found the error:

The project type is not supported by this installation.

Since I want to stick this project with the version 1, but also I want to create my new projects with version 2, how can I resolve this already made project to run with ASP.NET MVC 1 while having installed version 2?
I guess the solution goes in the path of resolving some references in web.config, but I don't know exactly what.

A: You need to correct the project type Guid in the csproj file. Older versions of MVC (previews) used a different Guid. Your project can still link to MVC 1, though.
To fix this:

*

*Make sure the project is checked into source control, in case anything goes wrong.

*Right click on Web project in Solution Explorer. Click "Unload project"

*Right click again, choose "Edit .csproj"

*Find ProjectTypeGuids, replace with the value below.

*Save, then right click and reload project.

*Test like crazy to ensure it's still working as you expect with MVC 1. Make sure you've specified strong names for the MVC 1 assemblies instead of bin deployment. With both versions in the GAC, you'll need strong names.
<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

Also, MVC 2 projects need a bindingRedirect in Web.config. The MVC 2 release notes say this is needed only "if the project references any third-party libraries that are compiled against ASP.NET MVC 1.0," but they're wrong.