text:
Q: Loading Facebook profile picture securely I'm trying to include users profile picture from facebook, which works fine, but the thing is when you want to include it on a SSL-secured page. I can't find a way to get the picture to load from a secure location. Using the following link to the users profile pic:
https://graph.facebook.com/<FB_ID HERE>/picture?type=square

Even though I use https it doesn't get loaded securely (browser says the page is just partially encrypted). And this isn't strange since the link just redirects to the images, for example for my profile picture:
https://graph.facebook.com/Bazze/picture?type=square

This will get the picture from:
http://profile.ak.fbcdn.net/hprofile-ak-snc4/161513_633115680_6792455_q.jpg

Note that that is not a secure location.
Anyone know how to load the profile picture securely through the https protocol?
Thanks!

A: Add return_ssl_resources=1 to your Graph call:
https://graph.facebook.com/<FB_ID>/picture?type=square&return_ssl_resources=1

This is the proper way to get a SSL-served image; the redirect will be to a https server with a proper SSL certificate.

Update: It appears Facebook will now automatically give you a redirect to https-hosted images when you use https://graph.facebook.com, so the return_ssl_resources parameter is no longer necessary.
Using http://graph.facebook.com still gets you a http-hosted image.

A: Well, https://graph.facebook.com/Bazze/picture?type=square is a 302 redirect to http://....  But note that https://... still works (example).
So it looks like one solution is to parse the 302 yourself, insert the 's' in the appropriate place, then fetch the image.  But on the downside, the linked page above has certificate errors, and there isn't a good way to fix that.
(I'm not saying this is a good answer...)

A: *

*It IS a secure location, it's just not a secure redirect

*All you can do is making sure you are using secure request when calling the graph api, after that Facebook will take over the communication and nothing can be done.

A: The 302 redirect will have your picture URL as stated in the Open Graph API documentation.
The you need to change from:
/ http profile.ak.fbcdn.net /
to:
/ https fbcdn-profile-a.akamaihd.net /
And from: / http static.ak.fbcdn.net / to: / https s-static.ak.fbcdn.net /
I really think that FB should do that in their API's !!!!

A: You could proxy it through your own server. Set up a script that fetches the image from Facebook then servers it back to you over SSL.
For Example
<?php
    $path=$_GET['path'];
    if (stristr($path, "fbcdn.")==FALSE && stristr($path, "facebook.")==FALSE)
    {
        echo "ERROR";
        exit;
    }
    header("Content-Description: Facebook Proxied File");
    header("Content-Type: image");
    header("Content-Disposition: attachment; filename=".$path);
    @readfile($path);
?>

Taken from
http://www.permadi.com/blog/2010/12/loading-facebook-profile-picture-into-flash-swf-using-open-graph-api/
Accessed via https://yourdomainhere.com/proxy.php?path=URLENCODED-IMG-URI should return the userpic via SSL.

A: Use ***http***://graph.facebook.com/Bazze/picture?type=square instead of **https**://graph.facebook.com/Bazze/picture?type=square

A: You can also get secure profile pics in bulk in which case you have to add the return_ssl_resources=1 param as @josh3736 mentioned.
https://graph.facebook.com/?ids=id1,id2,id3,...&fields=picture&return_ssl_resources=1


text:
Q: Attribute validation for entity properties that are nonrequired such as Email and Url, Is this possible? I am attempting to add validation attributes to my entity properties like so. :
[StringLength(100, ErrorMessage = "Must be between 1 to 100 characters")]
[EmailAddress]
public string Email { get; set; }

What I am running into is the fact that these properties are not required, but it still applies the attribute validation, and returns email address is invalid, specifically when this non required field is empty.
Is there any way to use these [Email] and [Url] when the property is not required and empty?
I am assuming there is, but have been unable to find anything on this.

A: What you have should work. Do you have the [Required] attribute on the model's property (assuming this is a view model)?

A: You can set Value for Email,if Email field was empty return value to model:`
@Html.TextBoxFor(m=>m.Email,new{Value=""})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a buoyant boat in Unity I need to find a way to make a 3D boat, appear to be buoyant in the water. Currently I am using a boat with a flat bottom and making it slide along the terrain, which is just below the water. This is giving the illusion of buoyancy, but not really what I'm looking for.
The boat moves using
this.transform.Translate(Vector3.left * Time.smoothDeltaTime * ((speed) + 1));

The boat turns using
this.transform.Rotate(Vector3.forward*Time.smoothDeltaTime*(int)(30*horizontal));

The boat has a RigidBody that uses gravity, does not interpolate, and has a Continuous Dynamic collision Detection. It also uses a convex Mesh Collider, with Smooth Sphere Collisions.
The Water has a Box Collider that is used as a trigger.

Now I need a way to make the boat seem to float in the water programmatically.
That means it

*

*Wobbles when it hits something

*Doesn't touch the bottom of the "river"

*Corrects its rotation to stay flat on the river (doesn't stay crooked after hitting an island or other obstacle)
I would like to do this so that I can give the base of my boat the correct shape so that it can have more realistic collisions with underwater obstacles.

A: Additional to my comment, if really you want it to be buoyant, you have to make it non-kinematic and react to gravity and the water has to bee a volumetric mesh (or a box as you use, but that's less accurate, do not work with waves if you use water with wave effect).
Basically you'd want to add (at least) 4 objects to your boat and place rigidbody inside it and a script which will apply an upward force which is greater than your gravity.
Then in your OnCollisionStay method set a bool. Maybe something like this (on top of my head)
using UnityEngine;
using System.Collections;

public class Buoyancy : MonoBehaviour {
    public float UpwardForce = 12.72f; // 9.81 is the opposite of the default gravity, which is 9.81. If we want the boat not to behave like a submarine the upward force has to be higher than the gravity in order to push the boat to the surface
    private bool isInWater = false;

    void OnTriggerEnter(Collider collidier) {
        isInWater = true;
        rigidbody.drag = 5f;
    }

    void OnTriggerExit(Collider collidier) {
        isInWater = false;
        rigidbody.drag = 0.05f;
    }

    void FixedUpdate() {
        if(isInWater) {
            // apply upward force
            Vector3 force = transform.up * UpwardForce;
            this.rigidbody.AddRelativeForce(force, ForceMode.Acceleration);
            Debug.Log("Upward force: " + force+" @"+Time.time);
        }
    }
}

And place this on all 4 buoyancy objects (together with a collider or trigger of course). When the object is in water, it will push the boat upwards, if it's over the water, it will be pulled down by the gravity until it reaches water again where it will be pulled up again until it finds a balance.
P.S. If you want to move the boat, you will use the this.rigidbody.AddForce(Vector.forward * 5, ForceMode.Force) (or ForceMode.Accelerate) to move the boat

A: Use the Buoyancy script. Just add this to the boat, and add the water level (its y value) in the code. Also it is best to use addForce instead of translate to move the boat.
If you want to make the boat react more realistically, you should also put its center of gravity lower, this way it will "wobble" and it stays right side up.


text:
Q: Replace text appearing on webpage via ajax I've got a website with products catalog using ajax pagination. I want to replace  text on all product cards. First product cards (2 rows) are already rendered on page, but next product cards are loading via ajax while scrolling page down.
I can't change websites source code, so the question is it possible to make a replacement for example via Nginx (smth. like 'sub_filter')? Maybe other variants?

A: sub_filter_types *;
sub_filter_once off;
sub_filter "foo" "bar";

In case if you are using gzip on backend, you have to remove it or add
proxy_set_header Accept-Encoding "";


text:
Q: CreatedAtRoute with Api Versioning I have searched all the posts on the problem in question, but I have not found any acceptable answer to this problem.
I have a controller with Get and Post like this:
[ApiController]
[ApiVersion(StringResources.ApiV10)] //"1.0"
[Route(StringResources.RouteWithVersioning)] //"api/v{version:apiVersion}/[controller]"
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public class ProductsController : ControllerBase
{
    private readonly IMediator _mediator;

    public ProductsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    [ProducesResponseType(typeof(CreateProductResponse), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    public ActionResult<CreateProductResponse> Create([FromBody]CreateProductRequest request)
    {
        try
        {
            var oid = _mediator.Send(new CreateProdRequest
            {
                Name = request.Name
            });

            return CreatedAtRoute(StringResources.GetProduct,
                new
                {
                    Oid = oid
                },
                new CreateProductResponse {Oid= oid});
        }
        catch (ProductException e) when(e.Errors.Select(err => err.Code).ToList().Contains("DuplicateProductName"))
        {
            return Conflict(ApiErrors.ProductAlreadyExist4091);
        }
    }

    [HttpGet(Name = StringResources.GetProduct)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult<GetProductResponse> Get([FromQuery]GetProductRequest request)
    {
        var result = _mediator.Send(new GetRequest
        {
            Oid = request.Oid
        });

        if (result == null)
            return NotFound();

        return Ok(result);
    }
}

But when I create a product and return CreateAtRoute I always get the exception:

exception.System.InvalidOperationException: No route matches the
supplied values.

The class GetProductRequest contains only Oid properties.
I tried to use CreateAtAction too but the URI returned in the header is wrong (it doesn't contain the path /api/v1/Products).
The startup configuration for middleware is this:
app.UseEndpoints(endpoints =>
{
     endpoints.MapControllers();
});

And for services is:
services.AddApiVersioning(options =>
{
     options.ReportApiVersions = true;
     options.AssumeDefaultVersionWhenUnspecified = true;
     options.DefaultApiVersion = new ApiVersion(1, 0);
});

services.AddVersionedApiExplorer(options =>
{
     options.GroupNameFormat = "'v'VVV";
     options.SubstituteApiVersionInUrl = true;
});

I believe that the problem is due to the fact that the API versioning is present in the path, but I don't know how to fix it.

A: The route ("api/v{version:apiVersion}/[controller]") needs a parameter named version, so pass the ApiVersion in to your action and send it along with the route values:
public ActionResult<CreateProductResponse> Create(
    [FromBody] CreateProductRequest request,
    ApiVersion version) // <-- Add this
{
    ⋮
    return CreatedAtRoute(
        StringResources.GetProduct,
        new
        {
            Oid = oid,
            version = version.ToString() // <-- And this
        },
        new CreateProductResponse {Oid = oid});
}


text:
Q: How to write Singleton class JUnit test cases I am new for Junit's and i wrote Singleton class Junit Test case in my below code but i am getting exception and second method for loop not getting to cover can some one help me please to get it solve
Singleton
 public class MSA {
    private static final _msa = new MSA(); // TA is a singleton
    private ArrayList<MSThread> MSThreads = new ArrayList<MSThread>();

    private String msaInfo = null;

        public String getMsaInfo() {
            return msaInfo;
        }

        public void setMsaInfo(String msaInfo) {
            this.msaInfo = msaInfo;
        }

        private MSA() {}

        public static MSA getInstance() {
            return _msa;
        }

       public void shutdown() {
        for (MSThread t: MSThreads) {
            t.shutdown();
        }
    }

TestClass
  @Test
        public void setMsaInfoTest() throws Exception{
            MSA fixture = MSA.getInstance();
            fixture.setMsaInfo("sample");
            assertTrue(fixture.getMsaInfo() == "sample");
        }

  @Test
    public void testShutdown_1()
        throws Exception {
        MSA fixture = MSA.getInstance();
        fixture.shutdown();
    }

Error
java.lang.AssertionError
    at org.junit.Assert.fail(Assert.java:86)
    at org.junit.Assert.assertTrue(Assert.java:41)
    at org.junit.Assert.assertTrue(Assert.java:52)
    at com.verizon.dtix.microsvcagent.MSATest.setMsaInfoTest(MSATest.java:131)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

A: If you're using Maven, in pom.xml you can specify test classes that only run on a single thread. This is one of the easier and safer ways to run unit/integration tests with Singletons in Java. You can do this in the plugins section of the pom:
    <configuration>
        <forkCount>1</forkCount>
        <reuseForks>false</reuseForks>
        <parallel>classes</parallel>
        <reuseForks>false</reuseForks>
        <parallel>none</parallel>
    </configuration>

     <executions>
        <execution>
            <id>single-thread-test</id>
            <phase>test</phase>
            <goals>
                <goal>test</goal>
            </goals>
            <configuration>
                <includes>
                    <include>*/YourTestClassName.java</include>
                </includes>
                <threadCount>1</threadCount>
            </configuration>
        </execution>
    </executions>


text:
Q: How to apply a function to a pandas dataframe when using external arguments and multiple columns? I have an array my_arr:
[10,20,30,40,50,60,70]

I have a pandas df, my_df:

id
start_index
end_index
array_sums

1
1
4

2
3
1

I want the Array sums field to equal the sum of the array from the start_index to the end_index, however if the end_index is smaller than the start_index then I want to sum of the values in the start_index to the end of the array and the values from the start of the array to the start_index. Essentially a sum from start index to end index where the array is like a loop.
def my_func(my_arr, start, end):
    if end >= start:
        consumption = sum(my_arr[start:end+1])
    if end < start:
        consumption = sum(my_arr[start:6])+sum(my_arr[0,end+1])
    return consumption

and I'm computing the following to get array_sums
my_df['array_sums'] = my_df.apply(lambda x: my_func(my_arr,x['first_week'],x['last_week']),axis=1)

But I get the following error: "too many indices for array: array is 1-dimensional, but 2 were indexed".
Can someone provide some help on how I can achieve the desired result? The result should be

id
start_index
end_index
array_sums

1
1
4
140

2
3
1
210


text:
Q: r heatmap.2: preventing some matrix rows from manipulation in dendrogram I analyze certain data on multiple observations with several variables and visualize them via heatmaps, performing rows and columns rearrangement with clustering and dendrogram building. I use heatmap.2() function from R's  gplots library. However certain rows (typically, several last ones) of observations are to be excluded from the analysis, since they are some partial sums or so, but they need be included in the dendrogram on their place. That is I need to perform clustering on data without taking into account these rows for scaling etc, but next to include them on the last positions with conserved coloring scheme. Here is the minimal example of data and manipulations
# load library and create some data
library(gplots)
my_palette <- colorRampPalette(c("red", "yellow", "green"))(n = 299)
df<-read.csv(text="experiment,var1,var2
1,5,4
2,3,2
3,2.3,1
4,3,4
sum1,3,5
sum2,4,5")

# arrange data so that it has the structure of datamatrix with original names
rname<-df[,1]
df<-df[,-1]
rownames(df)<-rname
df.matr<-data.matrix(df)

Next I build the dendrogram with clustering only by observations (rows) and custom color palette. The scaling is performed over columns.
heatmap.2(df.matr,cellnote=df.matr,scale="column",col=my_palette,trace="none",density.info="none",notecol="black",dendrogram="row",Colv="NA")

Here is the result:

As it can be seen, the last rows, sum1 and sum2, took part in clustering rearrangement; supposedly they were also used for computing averages and deviations for data scaling. For some reasons this may be undesirable (these rows may be already partial sums, or come from other population); however they need be included and visualized on the same footing in the final dendrogram. I could drop these rows before analysis, but how to insert them back on place? Or maybe there is some in-built solution in the package itself?

A: one possible solution is to use package pheatmap. I would remove rows sum1 and sum2, build a dendrogram, then add sum1 and sum2 as an annotation on top of heatmap: heatmap You also can change color of annotation bar to match colors used in the heatmap.


text:
Q: Copy Cut Paste functions in javascript textarea handling I am trying to write these functions here at :
https://jsfiddle.net/7rqgkozp/50/
HTML :
<textarea id="text_element" style="width:100%;height:200px" >Copy this ss!</textarea>
<br>
<button onclick="copyToClipboard('text_element')">
    Copy to clipboard
</button>
<button onclick="cutToClipboard('text_element')">
    cut to clipboard
</button>
<button onclick="pastefromclipboard('text_element')">
    paste
</button>

Javascript:
function copyToClipboard(elementId) {

  // Create an auxiliary hidden input
     var Tselected = getSel();  // Execute the copy command

  var aux = document.createElement("input");
  aux.setAttribute("type","text");
  aux.setAttribute("value",Tselected);
  aux.setAttribute("id","Tselected");
  document.body.appendChild(aux);

  // Highlight the content
  aux.select();

   document.execCommand("copy");

}

function cutToClipboard(elementId) {

     var Tselected = getSel(); //get selected text
  // Create an auxiliary hidden input

  var aux = document.createElement("input");
  aux.setAttribute("type","text");
  aux.setAttribute("value",Tselected);
  aux.setAttribute("id","Tselected");
  document.body.appendChild(aux);

  // Highlight the content
  aux.select();

     var myInput = document.getElementById("text_element");
var myInputVal = myInput.value;
    var newvalue =      myInputVal.replace(Tselected, "");
    myInput.value = newvalue;

   //
   document.execCommand("copy");

}

function pastefromclipboard(){
    var Tselected = document.getElementById("Tselected");
    var TselectedVal = Tselected.value;

      var myInput = document.getElementById("text_element");
   document.execCommand("paste");

   myInput.value += TselectedVal;
     document.body.removeChild(Tselected);
document.getElementById("my-element").remove();

}

function getSel() // javascript
{
    // obtain the object reference for the <textarea>
    var txtarea = document.getElementById("text_element");
    // obtain the index of the first selected character
    var start = txtarea.selectionStart;
    // obtain the index of the last selected character
    var finish = txtarea.selectionEnd;
    // obtain the selected text
    var sel = txtarea.value.substring(start, finish);
    // do something with the selected content

    return sel;

}

But I was only able to copy and paste the text at the end of textarea , but I need to paste it where the user clicked on textarea
The code is updated

A: Fixed That by changing the paste function into :
function pastefromclipboard() {
  var Tselected = document.getElementById("Tselected");
  var TselectedVal = Tselected.value;

  var myInput = document.getElementById("text_element");
  document.execCommand("paste");

  if (myInput.setRangeText) {
    //if setRangeText function is supported by current browser
    myInput.setRangeText(TselectedVal)
  } else {
    myInput.focus()
    myInput.execCommand('insertText', false /*no UI*/ , TselectedVal);
  }

  document.body.removeChild(Tselected);
  document.getElementById("my-element").remove();

}


text:
Q: Page design broken on Stack Overflow Here is a screenshot of what I am seeing.

As you can see the tag description is broken. Instead of spreading across the width of the page, it just looks like a column. It only started happening to me couple of days ago. This problem occurs on both Firefox (10.0.2) and Chromium (17.0.963) on Linux.
Screen resolution: 1920x1080.
** New Information **
The issue only happens on the landing pages of half the tags that I visit.
The list of problematic tags:

*

*MATLAB

*Python

*Linux

*Image-processing

*Algorithm

*Multithreading

*C

*C++

List of tags that are fine:

*

*Octave

*OpenCL

*MPI

*SSE

*CUDA

*Bash

*shell

I only verified the tags that I follow.
EDIT
I noticed the difference between the pages that look fine and those that do not.
The tags with featured tab seem to have problems. While those that do not have the tab are OK.
EDIT
It seems to have been fixed as of March 14, 2011.

I am not sure where to report bugs, so if this is not the right place to report bugs, please let me know where I can do so.

A: For some reason, your computer (apparently, since it's a cross-browser issue) is adding extra spacing between your characters. Note the difference between your text and my text in the below image:

Since all your tabs are being extended with extra space between your characters, it's pushing that bar down below where it's supposed to be (because there's not enough space on that line with the header title) and then pushing the tag description to the left.
Note: The resolution of your monitor has nothing to do with this. Stack Overflow is always displayed in the same width no matter what your screen resolution is (unless you go to the mobile version).
I don't know what causes this, I don't see anything in the CSS for the site that might be changing it for you, nor do I know of anything SO could really do to fix it. I only posted this as an answer because it was too big for comments.

A: I'd try pressing Ctrl+0 or your equivalent, or find the browser setting to reset your zoom levels - it looks like you've zoomed in one or more stops with "Zoom Text Only" enabled - that seems to be the only way I can reproduce this in FF10 at any rate which some commenters are reporting.


text:
Q: Pass variable from within PHP function I'd like to report how many files get deleted from a function that I'm running within php via a cron task.
Current codes is as follows:-
<?php

function deleteAll($dir) {
    $counter = 0;
    foreach(glob($dir . '/*') as $file) {
        if(is_dir($file)) {
            deleteAll($file); }
        else {
            if(is_file($file)){
// check if file older than 14 days
                if((time() - filemtime($file)) > (60 * 60 * 24 * 14)) {
                    $counter = $counter + 1;
                    unlink($file);
                }
            }
        }
    }
}

deleteAll("directory_name");

// Write to log file to confirm completed
$fp = fopen("logthis.txt", "a");
fwrite($fp, $counter." files deleted."."\n");
fclose($fp);

?>

That makes sense to me with a VBA background, but the counter returns null I think when written to my custom log file at the end.  I presume there is some restriction on a shared hosting site of being able to declare the variable globally or similar?
Appreciate any help!  It's not the end of world if I can't count the deleted files, but it would be nice to log the output in the format I've chosen.

A: This doesnt work due to scopes. In your example $counter only exists inside your function.
function deleteAll($dir):int {
    $counter = 0; // start with zero
    /* Some code here */
    if(is_dir($file)) {
        $counter += deleteAll($file); // also increase with the recursive amount
    }
    /* Some more code here */
    return $counter; // return the counter (at the end of the function
}

$filesRemoved = deleteAll("directory_name");

Alternatively, if you want to send back more info, eg 'totalCheck'  etc, you can send back an array of info:
function deleteAll($dir):array {
    // All code here
    return [
        'counter' => $counter,
        'totalFiles' => $allFilesCount
    ];
}
$removalStats = deleteAll("directory_name");
echo $removalStats['counter'].'files removed, total: '.$removalStats['totalFiles'];

There are other solutions like 'pass-by-reference', but you dont want those.


text:
Q: Keyboard shortcut to comment/uncomment selected code? In Visual Studio 2008, is there a keyboard shortcut to comment/uncomment selected lines of code?

A: *

*CTRL + K, followed by CTRL + C for commenting

*CTRL + K, followed by CTRL + U for uncommenting

For more good stuff, check Favorite Visual Studio keyboard shortcuts.

A: Look under the Edit->Advanced menu. I actually changed mine to CTRL-/, CTRL-/ so I can't remember what the original was.


text:
Q: Generating a large table of values and selecting some of them following some condition I am working on a problem where I have to generate a table of components while each component of the table has 18 entries. Six of the indices among 18 run from 0 to 1 while the other 12 can take values between 0 to 3. After doing that I have to select some of the entries which follow a certain criterion (sum of all values in each component should be three). I have done this for smaller sized entry tables but for this one Mathematica gives up very fast saying General::nomem: The current computation was aborted because there was insufficient memory available to complete the computation. I don't have a larger memory computer available. Can somebody help me with this please? The commands I am using are:
list =
  Table[{i, j, k, l, m, n, o, p, q, r, s, u, v, x, y, z, a, b},
    {i, 0, 1}, {j, 0, 3}, {k, 0, 3}, {l, 0, 1}, {m, 0, 3}, {n, 0, 3}, {o, 0, 1},
    {p, 0, 3}, {q, 0, 3}, {r, 0, 1}, {s, 0, 3}, {u, 0, 3}, {v, 0, 1}, {x, 0, 3},
    {y, 0, 3}, {z, 0, 1}, {a, 0, 3}, {b, 0, 3}] // Flatten

list1 = Partition[%, 18];

f1 = Total[#] < 4 &;

f2 = Total[#] > 2 &;

list2 = Select[list1, f1];

list3 = Select[list1, f2];

list4 = Intersection[list2, list3];

A: I think the comment solution will serve you well:
p1 = Join @@ Permutations /@ IntegerPartitions[3, {18}, Range[0, 3]];
result = Cases[p1, Alternatives @@@ Range[0, {1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3}]];

Testing this (on my loungebook, so I limited both yours and this to indices to u), yours took ~30 seconds and the initial table took over 50MB on ByteCount, the above finished under timer resolution with under 19KB used... I'd expect 10-20X faster speed on a workstation, same memory needs.
Same result, modulo sort order.
The advantage will of course grow extending the indices to the full set.

A: I don't know if this will save you sufficient memory, but it will certainly cut down your memory use.
$HistoryLength = 0;
list1 =
   Flatten[
     Table[{i, j, k, l, m, n, o, p, q, r, s, u, v, x, y, z, a, b},
       {i, 0, 1}, {j, 0, 3}, {k, 0, 3}, {l, 0, 1}, {m, 0, 3}, {n, 0, 3}, {o, 0, 1},
       {p, 0, 3}, {q, 0, 3}, {r, 0, 1}, {s, 0, 3}, {u, 0, 3}, {v, 0, 1}, {x, 0, 3},
       {y, 0, 3}, {z, 0, 1}, {a, 0, 3}, {b, 0,3}], 17];
list2 = Select[list1, 2 < Total[#] < 4 &]

A: I think this can done as follows:
pol = {1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3};
ip = Join @@ (Permutations /@ PadRight[IntegerPartitions[3, 3]]);
subs = Subsets[Range[18], {3}];
rl = Flatten[Map[Function[u, Thread[u -> #] & /@ ip], subs], 1];
cand = ReplacePart[ConstantArray[0, 18], #] & /@ rl;
ex = Position[pol, 1]
pck = Pick[cand, Max[Extract[#, ex]] <= 1 & /@ cand];

As I understand this aims to find vectors of length 18 with restrictions described whose sum of components is 3.
cand just finds vectors with elements {0,1,2,3}. pck picks out those that comply with condition {0,1} for positions in ex.
There are 5712 cases.
Apologies if I have misunderstood.
A sample (20) is presented below:


text:
Q: Java random values and duplicates I have an array (cards) of 52 cards (13x4), and another array (cardsOut) of 25 cards (5x5). I want to copy elements from the 52 cards into the 25 card array by random.
Also, I dont want any duplicates in the 5x5 array. So here's what I have:
        double row=Math.random() *13;
        double column=Math.random() *4;

        boolean[][] duplicates=new boolean[13][4];

        pokerGame[][] cardsOut = new pokerGame[5][5];
        for (int i=0;i<5;i++)
            for (int j=0;j<5;j++){
                if(duplicates[(int)row][(int)column]==false){
                    cardsOut[i][j]=cards[(int)row][(int)column];
                    duplicates[(int)row][(int)column]=true;
                }
            }

2 problems in this code. First, the random values for row and column are only generated once, so the same value is copied into the 5x5 array every time. Since the same values are being copied every time, I'm not sure if my duplicate checker is very effective, or if it works at all.
How do I fix this?

A: I'd recommend shuffling the deck in place first, then selecting the first 25 cards to place in your 5x5 array. Trying to mix these two steps is unnecessary complication.
If you need to optimize for performance (you probably don't) then it is worth noting that you can use the Fisher-Yates shuffle and stop the algorithm after the first 25 random cards have been selected without shuffling the remaining cards.

A: I think your approach makes it more difficult than it should be.  Try using a class named card, and two collections - one named CardsRemaining and another named CardsUsed.
Initially, CardsRemaining contains all 52 card objects, and CardsUsed is empty.  As cards are added to CardsUsed, they are removed from CardsRemaining, naturally preventing duplicates from occuring.
Your program might end up looking something like this (sorry it's in c#):
  class Program
    {
        static void Main(string[] args)
        {
            List<Card> CardsRemaining=new List<Card>();
            for (int i = 0; i < 12; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    Card c = new Card(i, j);
                    CardsRemaining.Add(c);
                }
            }
            List<Card> CardsUsed = new List<Card>();
            for(int i=0;i<25;i++)
            {
                int cardIndex = getRandomNumber(CardsRemaining.Count);
                Card c = CardsRemaining[cardIndex];
                CardsRemaining.Remove(c);
                CardsUsed.Add(c);
            }
        }
    }

    class Card
    {
        public int Number;
        public int Color;
        public Card(int number, int color)
        {
            this.Number = number;
            this.Color = color;
        }
    }


text:
Q: An equals method when the parameter is of type object I'm learning Java and am having some trouble with casting/polymorphism concepts.
If I have the following method:
public boolean equals(Object x);

Where x could reference an Object of Class Y;
What's the best way to see if x equals y (a variable referencing an obj of Class Y) ? I understand downcasting e.g. (Y) x is bad?

A: Downcasting is the norm in Object.equals. Before downcasting, check that x is indeed a compliant object with x instanceof Y; to ensure the symmetry of equals, a check x.getClass() == this.getClass() will be necessary at times.
If x is not an instance of your class, you immediately return false.

A: Downcasting is not bad if you firstly perform the following checks:

*

*Check for null --> x != null

*Compare classes at runtime --> getClass().equals(x.getClass())
Then you can downcast x as the class of this, and perform specific comparisons.
Prior to your null check, you may also want to compare references of this and x.
If the references are equal, you don't need to perform any other comparison.

A: It highly depends on your interpretation of equality. That's why the equals operator can be overridden.
Just do x.equals(y) and do the interpretation of equality by overriding the equals method.
One template method for this is to do:
public boolean equals(Object x) {
  if (this == x)
    return true;
  if (x == null || this.getClass() != x.getClass())
    return false;
  // Compare attributes as needed here
}

Of course you should check if x != null before, if there are chances it is null.


text:
Q: The difference between Baire 2 and 'effectively Baire 2' In short: Baire 2 functions are often assumed to be given by a double sequence of continuous functions, thought this is not the exact definition.  Does one need the Axiom of Choice (or related) to connect these two definitions?
Longer version:  we are working over the real numbers. As is well-known, Baire 0 functions are the continuous ones, while Baire $n+1$ functions are the pointwise limits of Baire $n$ functions.
I call a function $f$ from reals to reals effectively Baire 2 in case it is the double limit of a double sequence $(f_{n,m})_{n, m \in \mathbb{N}}$, i.e. for all reals $x$, we have
$$
(\forall \epsilon>0)(\exists n'\in \mathbb{N})(\forall n> n')(\exists m'\in \mathbb{N})(\forall m>m')( |f_{m,n}(x)-f(x)|<\epsilon). \qquad (*)
$$
As pointed out by Baire himself already, Baire 2 functions can be represented by effectively Baire 2 functions, though Baire did not use the latter terminology.
The notion (*) is essentially the definition of Baire 2 used in reverse mathematics/second-order arithmetic.
My question is then whether one needs the Axiom of Choice (or related) to show that for a general Baire 2 function, there is a double sequence satisfying (*).

A: It's provable in ZF that every Baire-2 function is effectively Baire-2. It suffices to prove the following:
(ZF) There is an explicit function which maps each Baire-1 function $f: \mathbb{R} \rightarrow \mathbb{R}$ to a sequence of rational polynomials that pointwise converge to it.
The first step is to construct a sequence of reals $\langle r_n \rangle$ such that each $r_n$ codes a rational-valued function $f_n$ such that $|f_n(x)-f(x)| \le \frac{1}{n}$ for all $x \in \mathbb{R}.$ We'll construct $r_1,$ which immediately generalizes to other $n.$
Let $U_k$ enumerate the basic open sets. We use transfinite recursion to define a descending sequence of closed sets $\langle C_{\alpha}: \alpha<\omega_1 \rangle$:

*

*$C_0=\mathbb{R},$

*$C_{\alpha+1}=C_{\alpha} \setminus \bigcup \{U_k: \forall x, y \in C_{\alpha} \cap U_k (|f(x)-f(y)|\le 1)\},$

*For limit $\alpha,$ $C_{\alpha}=\cap_{\xi<\alpha} C_{\xi}.$
If $C_{\alpha} \neq \emptyset,$ then $f \restriction_{C_{\alpha}}$ is continuous at some $x \in C_{\alpha}$ by Baire's Characterization Theorem. Then $x \not \in C_{\alpha+1},$ so $C_{\alpha+1} \subsetneq C_{\alpha}.$ Define a surjective partial map $g: \omega \rightharpoonup\beta = \{\alpha: C_{\alpha} \neq \emptyset\}$ by sending $k$ to the greatest $\alpha$ such that $U_k \cap C_{\alpha} \neq \emptyset,$ and a well-founded partial ordering $(\omega, \prec)$ by $i \prec j$ if $g(i) < g(j).$ Define $h: \text{dom}(g) \rightarrow \mathbb{Z}$ by $h(k)=\lfloor \sup_{U_k \cap C_{g(k)}} f \rfloor.$
Define $f_1: \mathbb{R} \rightarrow \mathbb{Z}$ as follows: for given $x,$ let $j=\min\{k<\omega: x \in U_k \wedge \forall \alpha (x \in C_{\alpha} \leftrightarrow U_k \cap C_{\alpha} \neq \emptyset)\}.$ Set $f_1(x) = h(j).$
Let $r_1$ be a real which encodes $(\omega, \prec)$ and $h.$ From $(\omega, \prec),$ one can determine the sequence $\langle C_{\alpha}\rangle$ and hence $g.$ Thus, $f_1$ can be determined from $r_1.$ This completes the construction of $r_1$ (and hence all $r_n$).
Let $r$ encode $\langle r_n \rangle$ (and thus $f$). By Shoenfield absoluteness relativized to $r,$ we have in $L[r]$ that $r$ encodes a Baire-1 function $\hat{f}.$ Enumerate the rational polynomials by $\langle q_n \rangle.$ A Stone-Weierstrass argument shows that there is $\langle n_k \rangle$ such that $\langle q_{n_k} \rangle$ converges pointwise to $\hat{f}$ in $L[r].$ Let $\langle n_k \rangle$ be the $L[r]$-least such sequence. Applying Shoenfield absoluteness upwards relative to a real encoding $(r, \langle n_k \rangle),$ we see in $V$ that $\langle q_{n_k} \rangle$ converges pointwise to the Baire-1 function coded by $r,$ namely $f.$ This completes the construction.
Some additional remarks: The above construction can be carried out in $Z_2.$ I don't know enough about subsystems of analysis to say more with confidence. By analyzing how much of $L[r]$ is really needed in the above, you can probably get this down to $\Pi^1_1-CA_0.$
As I showed in the comments, it is not provable in ZF that every Baire-3 function is effectively Baire-3, since if $\mathbb{R}$ is a countable union of countable sets, then every indicator function is Baire-3.


text:
Q: Function of two variables is differentiable
A function $f: \mathbb{R}^2 \to \mathbb{R}$ is said to be differentiable at $(x_0,y_0) \in \mathbb{R}$ if there exists a linear transformation $\lambda$ so that $$\displaystyle\lim_{\xi \to 0} \frac{\|f(x_0+h_1,y_0+h_2) - f(x_0,y_0) - \lambda(h,k)\|}{\|\xi\|} = 0 \hspace{1cm} \xi=(h,k) \to 0$$

Solution Verification Requested
Let $f(x,y) = (x+y)^2 = x^2+2xy+y^2$ and we want to check differentiability at $(2,3)$
First, we examine just the numerator and forget the other details for a moment. We examine
$$f(2+h,3+k) - f(2,3)-\lambda(h,k)$$
$$= (2+h)^2+2(2+h)(3+k)+(3+k)^2 - 25 - \lambda(h,k)$$
$$= h^2+4h+4+k^2+6k+9+12+4k+6h+2hk -25 - \lambda(h,k)$$
$$= h^2+2hk+k^2+(10h+10k)+(25 -25) - \lambda(h,k)$$
$$h^2+2hk+k^2+(10h+10k) - \lambda(h,k)$$
Choose $\lambda(h,k) = 10h+10k$. So then we have
$$h^2+2hk+k^2 +10h_10k - \lambda(h,k) = h^2+2hk+k^2=(h+k)^2$$
Now, we can observe that
$$\displaystyle\lim_{\xi \to 0} \frac{\|f(2+h,3+k)-f(2,3)-\lambda(h,k)\|}{\|\xi\|} = \displaystyle\lim_{\xi \to 0} \frac{(h+k)^2}{\sqrt{h^2+k^2}}$$
$$\leq \displaystyle\lim_{\xi \to 0} \Big( \frac{|h|^2}{\sqrt{h^2+k^2}} + \frac{|k|^2}{\sqrt{h^2+k^2}} \Big) = \displaystyle\lim_{\xi \to 0} \frac{|h|}{\sqrt{h^2+k^2}}|h| + \displaystyle\lim_{\xi \to 0} \frac{|k|}{\sqrt{h^2+k^2}}|k| = 0+0 = 0$$
Thus, $f$ is differentiable at $(2,3)$
Does this look good? Did I wave hands anywhere?


text:
Q: Is Sharepoint local bin deployment possible? I've inherited a SharePoint solution where all the projects have strong names and are deployed to the GAC.
I find that its difficult working with projects that are signed, it slows down development, testing and makes debugging difficult.
So, is it possible that SharePoint projects, WebParts, Codebehinds etc be deployed to the local bin instead of the GAC?  Is it considered bad practice to deploy to the local bin?

A: It is always recommanded to use the Bin directory over to GAC, for all the WebParts & Code Behinds. As that will restrict the Trust given to the code, GAC provides full trust to the code.
After deploying to the bin you can gain the required permission using CAS.
I recommend you to read the chapter Application Security of Inside Windows SharePoint Services 3.0 Book
Note: You will have to deploy your code Feature Handler, Timer Job etc to the GAC

A: By default, SharePoint Web applications are only allowed to run with a very restrictive trust level of WSS_Minimal. If we want to have our Web Part deployed to the bin folder, then in order for it to run we must do one of two things: either set the trust level to WSS_Medium or WSS_Full in the web.config, or create a custom CAS policy that will allow this assembly's managed code to run. In a production environment, you will need to make an informed decision on this yourself.
I would use the GAC for local development and testing and use the bin in production.
To debug locally, check the following in your config file:

*

*customErrors=off

*Enable Stack Traces by adding CallStack="true" to the SafeMode tag

*Set the compilation debug attribute to "true"


text:
Q: Karma + Jasmine testing async methods I have the following controller:
export default function($scope, $state, $http) {
    $scope.login = () => {
        $scope.loginFailed = false;

        const postReq: object = {
            method: 'POST',
            url: `/login`,
            data: {},
        }

        try {
            console.log('$scope.login');

            const response = await $http(postReq);

            console.log('login done');

            console.log('$state.go');

            $state.go('dashboard');

            return true;
        } catch(err) {
            console.error(err);
            $scope.loginFailed = true;

            return false;
        }
    };
}

I'm trying to test this method with Jasmine
it('change state to dashboard', async (done) => {
    $httpBackend.expectPOST('/login', undefined).respond(201, { rmId: 123123 });

    await $scope.login();
    expect($state.current.name).toBe('dashboard');
});

The results of my tests are as follows:

LOG: '$scope.login'
  PhantomJS 2.1.1 (Mac OS X 0.0.0) $scope.login change state to dashboard FAILED

Now it seems that Jasmine isn't waiting for the $http call to be completed. (This works fine when I manually test it in a browser)
Is there a better way to correctly test async methods?

A: you don't need to do the await. you just need to flush the backend mock before expect test
your login function must be change like this:
$scope.login = () => {
       return new Promise((resolve, reject) => {
          $scope.loginFailed = false;

        const postReq = {
            method: 'POST',
            url: `/login`,
            data: {},
        }

        const response = $http(postReq).then(
          (success) => {
              $state.go('dashboard');
              resolve(true);
            },
            (error) => {
               $scope.loginFailed = true;

            reject(false);
            });
       });
    };

And your test like :
it('change state to dashboard', async (done) => {
    const  backendMock = $httpBackend;
    backendMock.expectPOST('/login').respond(201, { rmId: 123123 });
    $scope.login().then((response) => {
      expect($state.current.name).toBe('dashboard');
      done();
    });
    backendMock.flush();

});

A: You need to use  $httpBackend.flush(); before writing your assertions. Add this line before your expect statement. It should work..


text:
Q: Change storage class of (existing) objects in Google Cloud Storage I recently learnt of the new storage tiers and reduced prices announced on the Google Cloud Storage platform/service.
So I wanted to change the default storage class for one of my buckets from Durable Reduced Availability to Coldline, as that is what is appropriate for the files that I'm archiving in that bucket.
I got this note though:

Changing the default storage class only affects objects you add to this bucket going forward. It does not change the storage class of objects that are already in your bucket.

Any advice/tips on how I can change class of all existing objects in the bucket (using Google Cloud Console or gsutil)?

A: To change the storage class from NEARLINE to COLDLINE, create a JSON file with the following content:
{
  "lifecycle": {
    "rule": [
      {
        "action": {
          "type": "SetStorageClass",
          "storageClass": "COLDLINE"
        },
        "condition": {
          "matchesStorageClass": [
            "NEARLINE"
          ]
        }
      }
    ]
  }
}

Name it lifecycle.json or something, then run this in your shell:
$ gsutil lifecycle set lifecycle.json gs://my-cool-bucket

The changes may take up to 24 hours to go through. As far as I know, this change will not cost anything extra.

A: I did this:
gsutil -m rewrite -r -s <storage-class> gs://my-bucket-name/
(-r for recursive, because I want all objects in my bucket to be affected).

A: The easiest way to synchronously move the objects to a different storage class in the same bucket is to use rewrite. For example, to do this with gsutil, you can run:
gsutil -m rewrite -s coldline gs://your-bucket/**

Note: make sure gsutil is up to date (version 4.22 and above support the -s flag with rewrite).
Alternatively, you can use the new SetStorageClass action of the Lifecycle Management feature to asynchronously (usually takes about 1 day) modify storage classes of objects in place (e.g. by using a CreatedBefore condition set to some time after you change the bucket's default storage class).

A: You could now use "Data Transfer" to change a storage class by moving your bucket objects to a new bucket.
Access this from the left panel of Storage.

A: If you couldn't access to the gsutil console, as in Google Cloud Function environment because Cloud Functions server instances don't have gsutil installed. Gsutil works on your local machine because you do have it installed and configured there. For all these cases I suggest you to evaluate the update_storage_class() blob method in python. This method is callable when you retrieve the single blob (in other words it refers to your specific object inside your bucket). Here an example:
from google.cloud import storage

storage_client = storage.Client()

blobs = storage_client.list_blobs(bucket_name)

for blob in blobs:
    print(blob.name)
    print(blob.storage_class)

all_classes = ['NEARLINE_STORAGE_CLASS', 'COLDLINE_STORAGE_CLASS', 'ARCHIVE_STORAGE_CLASS', 'STANDARD_STORAGE_CLASS', 'MULTI_REGIONAL_LEGACY_STORAGE_CLASS', 'REGIONAL_LEGACY_STORAGE_CLASS']

new_class = all_classes[my_index]
update_storage_class(new_class)

References:

*

*Blobs / Objects documentation: https://googleapis.dev/python/storage/latest/blobs.html#google.cloud.storage.blob.Blob.update_storage_class

*Storage classes: https://cloud.google.com/storage/docs/storage-classes


text:
Q: Importing shapefiles in folders into geodatabase? Using ArcGIS Desktop 10.3, I need to import thousands of folders containing shapefiles into a geodatabase. How can I do this?
Here is a part of the files that need to be exported into a geodatabase:

A: Right click your geodatabase, select import feature class (multiple), navigate to folders containing shape files, shift+click all your shapefiles.
If you want to consolidate all the thousands of folders into one, that could make that easier


text:
Q: vb.net delegate and invoke - Multithread I am trying to understand how delegates and invoke work.
So I build a form, with a label and a button.
When someone clicks on the Button, the Text changes to "Stop" and a counter starts counting up. This counter should be displayed on a Label. This is my code:
Public Class Form1

  Private t1 As Thread
  Private sek_ As Integer = 0

  Private Sub btn_read_Click(sender As Object, e As EventArgs) Handles btn_read.Click

    If btn_read.Text = "Read" Then

        btn_read.Text = "Stop"
        t1 = New Thread(AddressOf stopw_)
        t1.Start()

    Else
        lbl_stopw_.Text = ""
        btn_read.Text = "Read"

    End If

  End Sub

  Private Delegate Sub stopw_D()

  Private Sub stopw_()

    Do While btn_read.Text = "Stop"
        sek_ = sek_ + 1

        If lbl_stopw_.InvokeRequired Then
            lbl_stopw_.Invoke(New stopw_D(AddressOf stopw_))
        Else
            lbl_stopw_.Text = sek_
        End If

        Thread.Sleep(1000)

    Loop

    sek_ = 0

    If t1.IsAlive Then t1.Abort()

  End Sub

End Class

If I start debugging, the form still freezes and the label does not get updated. If I delete all the delegate and invoke stuff and use Me.CheckForIllegalCrossThreadCalls = False Its working.
What am I doing wrong?

A: Control.Invoke() is used to execute a method on the same thread that the control was created on. Since code can only be executed one line at a time in each thread, executing a method on the control's thread will result in the method being "queued" until the other code in that thread, prior to the method, has completed. This makes it thread-safe as there will be no concurrency issues.
A Delegate is simply a class holding the pointer to a method. It exists so that you can use methods as if they were ordinary objects (in this case you pass it to a function). The AddressOf operator is a quick way of creating a delegate.
Now, you have a few issues in your code. First of all, you should not try to access or modify ANY UI element from a background thread. Whenever you want modify or check a control you must always invoke.
More specifically, I'm talking about your While-loop:
'You can't check the button here without invoking.
Do While btn_read.Text = "Stop"

It is better if you create a Boolean variable that indicates when the thread should run.
Private t1 As Thread
Private sek_ As Integer = 0
Private ThreadActive As Boolean = False

Set ThreadActive to True before you start the thead, then in your thread's While-loop check:
Do While ThreadActive

Now, there is another issue. Your UI freezes because of this:
If lbl_stopw_.InvokeRequired Then
    lbl_stopw_.Invoke(New stopw_D(AddressOf stopw_))

NEVER invoke the the same method which the thread runs on! Doing so starts the processing all over again, but on the UI thread. Your loop makes the UI thread completely busy, which is why it doesn't redraw itself.
So when you are to update something, always invoke a seperate method. If you target .NET 4.0 or higher you can use lambda expressions for a quick, inline delegate:
If lbl_stopw_.InvokeRequired Then
    lbl_stopw_.Invoke( _
        Sub()
            lbl_stopw_.Text = sek_
        End Sub)
Else
    lbl_stopw_.Text = sek_
End If

However if you are targeting .NET 3.5 or lower you have to stick to the normal way of using delegates:
'Outside your thread.
Private Delegate Sub UpdateLabelDelegate(ByVal Text As String)

Private Sub UpdateLabel(ByVal Text As String)
    lbl_stopw_.Text = Text
End Sub

'In your thread.
If lbl_stopw_.InvokeRequired Then
    lbl_stopw_.Invoke(New UpdateLabelDelegate(AddressOf UpdateLabel), sek_)
Else
    UpdateLabel(sek_)
End If

Alternatively, in order to minimize the amount of code you have to write you can create an extension method to do the invoking for you:
Imports System.Runtime.CompilerServices

Public Module Extensions
    <Extension()> _
    Public Sub InvokeIfRequired(ByVal Control As Control, ByVal Method As [Delegate], ByVal ParamArray Parameters As Object())
        If Parameters Is Nothing OrElse _
            Parameters.Length = 0 Then Parameters = Nothing 'If Parameters is null or has a length of zero then no parameters should be passed.
        If Control.InvokeRequired = True Then
            Control.Invoke(Method, Parameters)
        Else
            Method.DynamicInvoke(Parameters)
        End If
    End Sub
End Module

Usage, .NET 4.0 or higher:
lbl_stopw_.InvokeIfRequired( _
    Sub()
        lbl_stopw_.Text = sek_
    End Sub)

Usage, .NET 3.5 or lower:
lbl_stopw_.InvokeIfRequired(New UpdateLabelDelegate(AddressOf UpdateLabel), sek_)

When using this extension method you don't need to write InvokeRequired checks everywhere:
Do While btn_read.Text = "Stop"
    sek_ = sek_ + 1

    lbl_stopw_.InvokeIfRequired(New UpdateLabelDelegate(AddressOf UpdateLabel), sek_)

    Thread.Sleep(1000)
Loop

And finally, this is just unnecessary:
If t1.IsAlive Then t1.Abort()

The thread will always be alive when it reaches that If-statement since it hasn't exited the stopw_ method yet. But once the thread has exited the method it will end normally, so there's no reason to call Abort().
The answer got a bit long, but I hope it to be helpful!


text:
Q: python-binance i can create a reduceonly order i have 1 binance account with humen activity (with hedge mood)
and 1 more biance account listening to the humen account and try copy all order is make.
when a humen create a order, the bot account make it to.
but, when humen create a reduceOnly order and bot try to copy it, the bot get an error like this
APIError(code=-1106) Parameter 'reduceOnly' sent when not required.
the code is like this:
result = self.client.futures_create_order(
symbol=symbol,
side  =side,
positionSide=positionSide,
type  =Ttype,
timeInForce=timeInForce,
reduceOnly=True,
quantity=float(quantity), # with max 3 number after the point
price=price

)
something is worng, how is possible the humen can create a "reduceOnly order" and the bot c'anot?

A: you are using so many unnecessary parameters. this should work:
client.futures_create_order(
symbol = 'BNBUSDT'
,side='SELL'
, closePosition=True
, stopPrice=415
,type='TAKE_PROFIT_MARKET')


text:
Q: Why push notification server send message to client exactly Example with Facebook application in iOS, use Apple Push Notification Service (APNS). I think when Facebook server see an new feed or new friend request, it will send a message to APNS. After that, APNS will push notification to client, who is logging in that facebook account. My question is :

*

*Why APNS know which device logging in that facebook account ?

*How APNS can send message to that client exactly (why APNS know client's IP address) ?

As I know, Push Notification also a technology use in Windows Phone ( Microsoft Push Notification Service), and Android (Cloud to Device Message).
Thanks.

A: Well APNS (Apple Push notification Service) works on a per device per app unique ID.
You push you message to this unique ID and it get deliver on the users device.
Your app must request this ID and pass it to the server wich will send out the notifications.
The ID is that create by the APNS API, thus Apple knows that the ID belongs to that device and app.
I guess that the windows and android will work in the same way.


text:
Q: Unable to setup Node in mac for hub in windows While setting up Selenium Grid:
Windows as Hub
Mac as Node
While registering node in mac, the below error is displayed:
Couldn't register this node: The hub is down or not responding: The hub responded with 305: Use Proxy
Note:
(1) Able to setup Selenium Grid successfully, By
-> Windows as Hub and Node
-> Mac as Hub and Node.
-> Mac as Hub and Windows as Node
(2) Able to connect RDP from Windows to Mac


text:
Q: How do I make my vertical side menu take up the entire screen The navigation bar in my webpage (below) only takes up a small part of the vertical, but I want it to take up the entire vertical. In the CSS file (below) in the .sidenav class I set the height property to 100%, which I thought would solve the problem, but it didn't.
This is my html body (ignore what's between the {% %} that is Django syntax)
{% extends "myapp/layout.html" %}

{% block body %}

Home

News

Contact

About

{% endblock %}

Here is my CSS
body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.sidenav {
  overflow: hidden;
  background-color: #b3b3b3;
  width: 10%;
  height: 100%;
}

.sidenav a {
  color: #f2f2f2;
  text-align: center;
  padding: 20px 30px;
  text-decoration: none;
  font-size: 17px;
  display: block;
}

.sidenav a:hover {
  background-color: #e6e6e6;
  color: black;
}

.sidenav a#active {
  background-color: #4d4d4d;
  color: white;
}

And here is my webpage so far

A: Try using vh(viewport height) as height unit:
.sidenav{
min-height: 100vh
}

A: The solution is to say

height: 100vh;

If you set height to 100%, it will orientate on the parent(root) therefore you would have to set

html{height: 100%}

A: You can also do the following:
html {
  height: 100%;
  width: 100%;
}
body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
  height: 100%;
  width: 100%;
}

I share a codesandbox with your complete code


text:
Q: How to draw a boundary line on a scatter plot for classifier in Julia? If I want to draw a boundary line to separate two classes which is the result of my classifier. How to draw it?
The picture is the sample, the black line is the boundary I want to draw.
the green points is the boundary points. I want to draw a curve perfectly fit those points. But when I plot those curve, the result is the purple line which is not a curve.

A: Here is a reproducible example how to do it:
using Plots

x = rand(1000)
y = rand(1000)
color = [3 * (b-0.5)^2 < a - 0.1 ? "red" : "blue" for (a, b) in zip(x, y)]

y_bound = 0:0.01:1
x_bound = @. 3 * (y_bound - 0.5)^2 + 0.1

scatter(x, y, color=color, legend=false)
plot!(x_bound, y_bound, color="green")

and you should get a plot like:

The crucial thing here is to make your boundary points ordered (i.e. they must be ordered in the vectors properly so that when you plot a line you connect proper points). In my example I achieved it by varying the y-dimension and calculating the x dimension.
In more complex cases it will be better to use contour plot, e.g.:
x = 1:0.1:8
y = 1:0.1:7
f(x, y) = begin
    (3x + y ^ 2) * abs(sin(x) + cos(y)) - 40
end
X = repeat(reshape(x, 1, :), length(y), 1)
Y = repeat(y, 1, length(x))
Z = map(f, X, Y)
contour(x, y, Z, levels=[0], color="green", width=3)

x_s = 7 .* rand(1000) .+ 1
y_s = 6 .* rand(1000) .+ 1
color = [f(a, b) > 0 ? "red" : "blue" for (a, b) in zip(x_s, y_s)]
scatter!(x_s, y_s, color=color, legend=false)

and you should get something like:

However, as you can see this time for the best results it is best to pass scores to contour and specify the classification threshold as level.

A: I guess your TA asked you to conduct a grid search for this question.
The meaning of grid search is not searching over the data point you have, but searching over whole coordinate. (I.e. From (0,0), (0,1), (0,2) to (0,100), then to (1,0), (1,1) and so on.) You may change the distance between each point when you conduct a grid search.
In your case, you need to solve the equation d_1(X) = d_2(X). So what you need to do is to simulate some points (like the above example), then put those points into |d_1(X) - d_2(X)|, and pick the points that bring you to a value that is smaller than epsilon (a self-given small number like 0.05 or 0.1). Then use Plot() to connect them.
This is not the most efficient way to create the boundary but this is what you learnt in your tutorial. You may also try contour().


text:
Q: reading and processing files in parallel in R I am using the parallel library in R to process a large data set on which I am applying complex operations.
For the sake of providing a reproducible code, you can find below a simpler example:
#data generation
dir <- "C:/Users/things_to_process/"

setwd(dir)
for(i in 1:800)
{
    my.matrix <- matrix(runif(100),ncol=10,nrow=10)

    saveRDS(my.matrix,file=paste0(dir,"/matrix",i))
}

#worker function
worker.function <- function(files)
{
    files.length <- length(files)
    partial.results <- vector('list',files.length)

    for(i in 1:files.length)
    {
        matrix <- readRDS(files[i])
        partial.results[[i]] <- sum(diag(matrix))
    }

    Reduce('+',partial.results)
}

#master part
cl <- makeCluster(detectCores(), type = "PSOCK")

file_list <- list.files(path=dir,recursive=FALSE,full.names=TRUE)

part <- clusterSplit(cl,seq_along(file_list))
files.partitioned <- lapply(part,function(p) file_list[p])

results <- clusterApply(cl,files.partitioned,worker.function)

result <- Reduce('+',results)

Essentially, I am wondering if trying to read files in parallel would be done in an interleaved fashion instead. And if, as a result, this bottleneck would cut down on the expected performance of running tasks in parallel?
Would it be better if I first read all matrices at once in a list then sent chunks of this list to each core for it to be processed? what if these matrices were much larger, would I be able to load all of them in a list at once ?

A: Instead of saving each matrix in a separate RDS file, have you tried saving a list of N matrices in each file, where N is the number that is going to be processed by a single worker?
Then the worker.function looks like:
worker.function <- function(file) {
    matrix_list <- readRDS(file)
    partial_results <- lapply(matrix_list, function(mat) sum(diag(mat)))
    Reduce('+',partial.results)
}

You should save some time on I/O and maybe even on computation by replacing a for with a lapply.


text:
Q: $\bigcup_{n}V_n$ is dense in $V$ (Hilbert spaces) I read:

$\bigcup_{n}V_n$ is dense in $V$ (Hilbert spaces)

Does this mean: for every $v \in V$, there is a sequence $\{v_n\}$ with $v_n \in V_n$ for each $n$ such that $|v_n - v|_V \to 0$?
I guess so. But then I also read

$V_n$ is dense in $V$

Does the author mean by this that given $v$, we can pick an $N$ such that there is an element $v_N \in V_N$ that is arbitrary close to $v$?
Are these two statements equivalent then?

A:
Definition. A subset $U \subseteq V$ is called dense in $V$ iff for each $v \in V$ there is a sequence $(u_k) \in {}^{\mathbb N}U$ with $u_k \to u$.

Lets apply this to your two cases: In the first case we are given that for any $v \in V$ there is a sequence $(u_k)$ with $u_k \in \bigcup_n V_n$ and $u_k \to v$. If moreover the $V_n$ are increasing, that is $V_1 \subseteq V_2 \subseteq \cdots$ we can arrange that $u_n \in V_n$ as you say. In general this is not possible (think of $V_{2n} = \{0\}$ for all $n$ or something like that).
The second one is easier: $V_n$ being dense means that for each $v \in V$ there is a sequence $(u_k)$ of elements from $V_n$ converging to $v$, or in $V_n$ there are elements arbitrarily close to $v$.


text:
Q: How to apply conditional column offsets in IONIC 3 I am using the ionic 3 and i have created grids.
<ion-row>
<ion-col col-4 offset-4>

</ion-col>
</ion-row>

And Now i want to apply conditions on columns offset for this i have applied this code given below, but i got the error.
<ion-row>
<ion-col col-4 offset-{{(variable == 1)?'4':'0'}}>

</ion-col>
</ion-row>

If anyone has suggestions so plz help me
Thanks

A: You can't bind value to offset, i think you should try this,
first make a variable in your ts file for example offsetVariable = true
then in your HTML file
<ion-row>
  <ion-col col-4 offset-4 *ngIf="offsetVariable">

  </ion-col>
</ion-row>

and
<ion-row>
    <ion-col col-4 offset-0 *ngIf="!offsetVariable">

    </ion-col>
</ion-row>

A: Below works in Ionic 5

<ion-row>
  <ion-col col-4 [offset]="offsetVariable ? 4 : 0">

  </ion-col>
</ion-row>


text:
Q: yarnrc AuthToken for a specific action my .yarnrc file includes the following code:
npmScopes:
  myOrg:
    npmAuthToken: '${NPM_TOKEN}'
    npmAlwaysAuth: true
    npmRegistryServer: 'https://registry.npmjs.org'

and I want the auth to ask for NPM_TOKEN only for yarn add, and for other yarn <command> to not ask for the NPM_TOKEN
for example
npmScopes:
      myOrg yarn add:
        npmAuthToken: '${NPM_TOKEN}'
        npmAlwaysAuth: true
        npmRegistryServer: 'https://registry.npmjs.org'

is it possible?


text:
Q: Spring annotation @Validated not working in kotlin class, same java code works I'm have kotlin get request.
Validation are not working, Possible to specify day of week more or less validate limits
@RestController
@Validated
open class GetCrab {
    @GetMapping("/v1/get")
open fun getNameOfDayByNumber(@RequestParam dayOfWeek: @Min(1) @Max(7) Int?): String {
        return "ok"
    }
}

In the same java code validation works
@RestController
@Validated
public class GetCrab {

    @GetMapping("/v1/get")
    public String getNameOfDayByNumber(@RequestParam @Min(1) @Max(7) Integer dayOfWeek) {

        return "ok";
    }
}

Java code when validation works: request:
http://localhost:12722/v1/get?dayOfWeek=100
Response ->
{
"errors": [
    {
        "code": "INTERNAL_SERVER_ERROR",
        "details": "getNameOfDayByNumber.dayOfWeek: must be less than or equal to 7"
    }
]

}
Kotlin code, request http://localhost:12722/v1/get?dayOfWeek=100
Response:
ok

A: Please use open modifier for methods too.
E.g. please try code:
@RestController
@Validated
open class GetCrab {
    @GetMapping("/v1/get")
    open fun getNameOfDayByNumber(@RequestParam dayOfWeek: @Min(1) @Max(7) Int?): String {
        return "ok"
    }
}

Both class and method should be open (in Java terms - both of them shouldn't be final), because of Spring proxy logic. From linked article: Spring tries to inherit your class, because sometimes you can request exact your class from @Autowired parameter.
By default all classes and methods are not final in Java. However Kotlin classes/methods are final by default, so you need to put open keyword before them to have ability to override.


text:
Q: Riak erlang error on startup I run riak as such
[idf@node1 ~]$ sudo riak start
!!!!
!!!! WARNING: ulimit -n is 65535; 65536 is the recommended minimum.
!!!!
riak failed to start within 15 seconds,
see the output of 'riak console' for more information.
If you want to wait longer, set the environment variable
WAIT_FOR_ERLANG to the number of seconds to wait.
[idf@node1 ~]$

It tells me to look at the output of riak console
[idf@node1 ~]$ sudo riak console
config is OK
-config /var/lib/riak/generated.configs/app.2016.04.04.21.34.43.config -args_file /var/lib/riak/generated.configs/vm.2016.04.04.21.34.43.args -vm_args /var/lib/riak/generated.configs/vm.2016.04.04.21.34.43.args
!!!!
!!!! WARNING: ulimit -n is 65535; 65536 is the recommended minimum.
!!!!
Exec:  /usr/lib64/riak/erts-5.10.3/bin/erlexec -boot /usr/lib64/riak/releases/2.0.0/riak               -config /var/lib/riak/generated.configs/app.2016.04.04.21.34.43.config -args_file /var/lib/riak/generated.configs/vm.2016.04.04.21.34.43.args -vm_args /var/lib/riak/generated.configs/vm.2016.04.04.21.34.43.args              -pa /usr/lib64/riak/lib/basho-patches -- console
Root: /usr/lib64/riak
Erlang R16B02-basho5 (erts-5.10.3) [source] [64-bit] [smp:16:16] [async-threads:64] [kernel-poll:true]

[os_mon] memory supervisor port (memsup): Erlang has closed
[os_mon] cpu supervisor port (cpu_sup): Erlang has closed
{"Kernel pid terminated",application_controller,"{application_start_failure,riak_core,{{shutdown,{failed_to_start_child,riak_core_handoff_sup,{shutdown,{failed_to_start_child,riak_core_handoff_listener_sup,{shutdown,{failed_to_start_child,riak_core_handoff_listener,{bad_return_value,{error,eaddrinuse}}}}}}}},{riak_core_app,start,[normal,[]]}}}"}

Crash dump was written to: /var/log/riak/erl_crash.dump
Kernel pid terminated (application_controller) ({application_start_failure,riak_core,{{shutdown,{failed_to_start_child,riak_core_handoff_sup,{shutdown,{failed_to_start_child,riak_core_handoff_listen
[idf@node1 ~]$

EDIT:
I changed the default values in the .conf file to the following:
listener.http.internal = 127.0.0.1:10011
listener.protobuf.internal = 127.0.0.1:10012

I still get:
[idf@node1 ~]$ sudo riak console
config is OK
-config /var/lib/riak/generated.configs/app.2016.04.05.11.55.10.config -args_file /var/lib/riak/generated.configs/vm.2016.04.05.11.55.10.args -vm_args /var/lib/riak/generated.configs/vm.2016.04.05.11.55.10.args
!!!!
!!!! WARNING: ulimit -n is 65535; 65536 is the recommended minimum.
!!!!
Exec:  /usr/lib64/riak/erts-5.10.3/bin/erlexec -boot /usr/lib64/riak/releases/2.0.0/riak               -config /var/lib/riak/generated.configs/app.2016.04.05.11.55.10.config -args_file /var/lib/riak/generated.configs/vm.2016.04.05.11.55.10.args -vm_args /var/lib/riak/generated.configs/vm.2016.04.05.11.55.10.args              -pa /usr/lib64/riak/lib/basho-patches -- console
Root: /usr/lib64/riak
Erlang R16B02-basho5 (erts-5.10.3) [source] [64-bit] [smp:16:16] [async-threads:64] [kernel-poll:true]

[os_mon] memory supervisor port (memsup): Erlang has closed
[os_mon] cpu supervisor port (cpu_sup): Erlang has closed
{"Kernel pid terminated",application_controller,"{application_start_failure,riak_core,{{shutdown,{failed_to_start_child,riak_core_handoff_sup,{shutdown,{failed_to_start_child,riak_core_handoff_listener_sup,{shutdown,{failed_to_start_child,riak_core_handoff_listener,{bad_return_value,{error,eaddrinuse}}}}}}}},{riak_core_app,start,[normal,[]]}}}"}

Crash dump was written to: /var/log/riak/erl_crash.dump
Kernel pid terminated (application_controller) ({application_start_failure,riak_core,{{shutdown,{failed_to_start_child,riak_core_handoff_sup,{shutdown,{failed_to_start_child,riak_core_handoff_listen

EDIT 2
I see that even though it fails, there is a riak daemon running?
[idf@node1 ~]$ ps ax | grep riak
26817 ?        S      0:00 /usr/lib64/riak/erts-5.10.3/bin/epmd -daemon
27177 pts/3    S+     0:00 grep --color=auto riak

In the documentation, it says to look for beam.smp, but I don't see those.
"exit with reason bad return value: {error,eaddrinuse} in context start_error   An error like this example can occur when another process is already bound to the same address as the process being started is attempting to bind to. Use operating system tools like netstat, ps, and lsof to determine the root cause for resolving this kind of errors; check for existence of stale beam.smp processes."
[idf@node1 ~]$ ps ax | grep -i beam
27217 pts/3    S+     0:00 grep --color=auto -i beam
[idf@node1 ~]$

This is the .conf file
## Where to emit the default log messages (typically at 'info'
## severity):
## off: disabled
## file: the file specified by log.console.file
## console: to standard output (seen when using `riak attach-direct`)
## both: log.console.file and standard out.
##
## Default: file
##
## Acceptable values:
##   - one of: off, file, console, both
log.console = file

## The severity level of the console log, default is 'info'.
##
## Default: info
##
## Acceptable values:
##   - one of: debug, info, notice, warning, error, critical, alert, emergency, none
log.console.level = info

## When 'log.console' is set to 'file' or 'both', the file where
## console messages will be logged.
##
## Default: $(platform_log_dir)/console.log
##
## Acceptable values:
##   - the path to a file
log.console.file = $(platform_log_dir)/console.log

## The file where error messages will be logged.
##
## Default: $(platform_log_dir)/error.log
##
## Acceptable values:
##   - the path to a file
log.error.file = $(platform_log_dir)/error.log

## When set to 'on', enables log output to syslog.
##
## Default: off
##
## Acceptable values:
##   - on or off
log.syslog = off

## Whether to enable the crash log.
##
## Default: on
##
## Acceptable values:
##   - on or off
log.crash = on

## If the crash log is enabled, the file where its messages will
## be written.
##
## Default: $(platform_log_dir)/crash.log
##
## Acceptable values:
##   - the path to a file
log.crash.file = $(platform_log_dir)/crash.log

## Maximum size in bytes of individual messages in the crash log
##
## Default: 64KB
##
## Acceptable values:
##   - a byte size with units, e.g. 10GB
log.crash.maximum_message_size = 64KB

## Maximum size of the crash log in bytes, before it is rotated
##
## Default: 10MB
##
## Acceptable values:
##   - a byte size with units, e.g. 10GB
log.crash.size = 10MB

## The schedule on which to rotate the crash log.  For more
## information see:
## https://github.com/basho/lager/blob/master/README.md#internal-log-rotation
##
## Default: $D0
##
## Acceptable values:
##   - text
log.crash.rotation = $D0

## The number of rotated crash logs to keep. When set to
## 'current', only the current open log file is kept.
##
## Default: 5
##
## Acceptable values:
##   - an integer
##   - the text "current"
log.crash.rotation.keep = 5

## Name of the Erlang node
##
## Default: riak@127.0.0.1
##
## Acceptable values:
##   - text
nodename = riak@127.0.0.1

## Cookie for distributed node communication.  All nodes in the
## same cluster should use the same cookie or they will not be able to
## communicate.
##
## Default: riak
##
## Acceptable values:
##   - text
distributed_cookie = riak

## Sets the number of threads in async thread pool, valid range
## is 0-1024. If thread support is available, the default is 64.
## More information at: http://erlang.org/doc/man/erl.html
##
## Default: 64
##
## Acceptable values:
##   - an integer
erlang.async_threads = 64

## The number of concurrent ports/sockets
## Valid range is 1024-134217727
##
## Default: 65536
##
## Acceptable values:
##   - an integer
erlang.max_ports = 65535

## Set scheduler forced wakeup interval. All run queues will be
## scanned each Interval milliseconds. While there are sleeping
## schedulers in the system, one scheduler will be woken for each
## non-empty run queue found. An Interval of zero disables this
## feature, which also is the default.
## This feature is a workaround for lengthy executing native code, and
## native code that do not bump reductions properly.
## More information: http://www.erlang.org/doc/man/erl.html#+sfwi
##
## Acceptable values:
##   - an integer
## erlang.schedulers.force_wakeup_interval = 500

## Enable or disable scheduler compaction of load. By default
## scheduler compaction of load is enabled. When enabled, load
## balancing will strive for a load distribution which causes as many
## scheduler threads as possible to be fully loaded (i.e., not run out
## of work). This is accomplished by migrating load (e.g. runnable
## processes) into a smaller set of schedulers when schedulers
## frequently run out of work. When disabled, the frequency with which
## schedulers run out of work will not be taken into account by the
## load balancing logic.
## More information: http://www.erlang.org/doc/man/erl.html#+scl
##
## Acceptable values:
##   - one of: true, false
## erlang.schedulers.compaction_of_load = false

## Enable or disable scheduler utilization balancing of load. By
## default scheduler utilization balancing is disabled and instead
## scheduler compaction of load is enabled which will strive for a
## load distribution which causes as many scheduler threads as
## possible to be fully loaded (i.e., not run out of work). When
## scheduler utilization balancing is enabled the system will instead
## try to balance scheduler utilization between schedulers. That is,
## strive for equal scheduler utilization on all schedulers.
## More information: http://www.erlang.org/doc/man/erl.html#+sub
##
## Acceptable values:
##   - one of: true, false
## erlang.schedulers.utilization_balancing = true

## Number of partitions in the cluster (only valid when first
## creating the cluster). Must be a power of 2, minimum 8 and maximum
## 1024.
##
## Default: 64
##
## Acceptable values:
##   - an integer
## ring_size = 64

## Number of concurrent node-to-node transfers allowed.
##
## Default: 2
##
## Acceptable values:
##   - an integer
## transfer_limit = 2

## Default cert location for https can be overridden
## with the ssl config variable, for example:
##
## Acceptable values:
##   - the path to a file
## ssl.certfile = $(platform_etc_dir)/cert.pem

## Default key location for https can be overridden with the ssl
## config variable, for example:
##
## Acceptable values:
##   - the path to a file
## ssl.keyfile = $(platform_etc_dir)/key.pem

## Default signing authority location for https can be overridden
## with the ssl config variable, for example:
##
## Acceptable values:
##   - the path to a file
## ssl.cacertfile = $(platform_etc_dir)/cacertfile.pem

## DTrace support Do not enable 'dtrace' unless your Erlang/OTP
## runtime is compiled to support DTrace.  DTrace is available in
## R15B01 (supported by the Erlang/OTP official source package) and in
## R14B04 via a custom source repository & branch.
##
## Default: off
##
## Acceptable values:
##   - on or off
dtrace = off

## Platform-specific installation paths (substituted by rebar)
##
## Default: /usr/sbin
##
## Acceptable values:
##   - the path to a directory
platform_bin_dir = /usr/sbin

##
## Default: /var/lib/riak
##
## Acceptable values:
##   - the path to a directory
platform_data_dir = /var/lib/riak

##
## Default: /etc/riak
##
## Acceptable values:
##   - the path to a directory
platform_etc_dir = /etc/riak

##
## Default: /usr/lib64/riak/lib
##
## Acceptable values:
##   - the path to a directory
platform_lib_dir = /usr/lib64/riak/lib

##
## Default: /var/log/riak
##
## Acceptable values:
##   - the path to a directory
platform_log_dir = /var/log/riak

## Enable consensus subsystem. Set to 'on' to enable the
## consensus subsystem used for strongly consistent Riak operations.
##
## Default: off
##
## Acceptable values:
##   - on or off
## strong_consistency = on

## listener.http.<name> is an IP address and TCP port that the Riak
## HTTP interface will bind.
##
## Default: 127.0.0.1:8098
##
## Acceptable values:
##   - an IP/port pair, e.g. 127.0.0.1:10011
#listener.http.internal = 127.0.0.1:8098
## listener.protobuf.<name> is an IP address and TCP port that the Riak
## Protocol Buffers interface will bind.
##
## Default: 127.0.0.1:8087
##
## Acceptable values:
##   - an IP/port pair, e.g. 127.0.0.1:10011
#listener.protobuf.internal = 127.0.0.1:8087
listener.protobuf.internal = 127.0.0.1:10012

## The maximum length to which the queue of pending connections
## may grow. If set, it must be an integer > 0. If you anticipate a
## huge number of connections being initialized *simultaneously*, set
## this number higher.
##
## Default: 128
##
## Acceptable values:
##   - an integer
## protobuf.backlog = 128

## listener.https.<name> is an IP address and TCP port that the Riak
## HTTPS interface will bind.
##
## Acceptable values:
##   - an IP/port pair, e.g. 127.0.0.1:10011
## listener.https.internal = 127.0.0.1:8098
listener.https.internal = 127.0.0.1:10011

## How Riak will repair out-of-sync keys. Some features require
## this to be set to 'active', including search.
## * active: out-of-sync keys will be repaired in the background
## * passive: out-of-sync keys are only repaired on read
## * active-debug: like active, but outputs verbose debugging
## information
##
## Default: active
##
## Acceptable values:
##   - one of: active, passive, active-debug
anti_entropy = passive

## Specifies the storage engine used for Riak's key-value data
## and secondary indexes (if supported).
##
## Default: bitcask
##
## Acceptable values:
##   - one of: bitcask, leveldb, memory, multi
storage_backend = bitcask

## Controls which binary representation of a riak value is stored
## on disk.
## * 0: Original erlang:term_to_binary format. Higher space overhead.
## * 1: New format for more compact storage of small values.
##
## Default: 1
##
## Acceptable values:
##   - the integer 1
##   - the integer 0
object.format = 1

## Reading or writing objects bigger than this size will write a
## warning in the logs.
##
## Default: 5MB
##
## Acceptable values:
##   - a byte size with units, e.g. 10GB
object.size.warning_threshold = 5MB

## Writing an object bigger than this will send a failure to the
## client.
##
## Default: 50MB
##
## Acceptable values:
##   - a byte size with units, e.g. 10GB
object.size.maximum = 50MB

## Writing an object with more than this number of siblings will
## generate a warning in the logs.
##
## Default: 25
##
## Acceptable values:
##   - an integer
object.siblings.warning_threshold = 25

## Writing an object with more than this number of siblings will
## send a failure to the client.
##
## Default: 100
##
## Acceptable values:
##   - an integer
object.siblings.maximum = 100

## A path under which bitcask data files will be stored.
##
## Default: $(platform_data_dir)/bitcask
##
## Acceptable values:
##   - the path to a directory
bitcask.data_root = $(platform_data_dir)/bitcask

## Configure how Bitcask writes data to disk.
## erlang: Erlang's built-in file API
## nif: Direct calls to the POSIX C API
## The NIF mode provides higher throughput for certain
## workloads, but has the potential to negatively impact
## the Erlang VM, leading to higher worst-case latencies
## and possible throughput collapse.
##
## Default: erlang
##
## Acceptable values:
##   - one of: erlang, nif
bitcask.io_mode = erlang

## Set to 'off' to disable the admin panel.
##
## Default: off
##
## Acceptable values:
##   - on or off
riak_control = off

## Authentication mode used for access to the admin panel.
##
## Default: off
##
## Acceptable values:
##   - one of: off, userlist
riak_control.auth.mode = off

## If riak control's authentication mode (riak_control.auth.mode)
## is set to 'userlist' then this is the list of usernames and
## passwords for access to the admin panel.
## To create users with given names, add entries of the format:
## riak_control.auth.user.USERNAME.password = PASSWORD
## replacing USERNAME with the desired username and PASSWORD with the
## desired password for that user.
##
## Acceptable values:
##   - text
## riak_control.auth.user.admin.password = pass

## This parameter defines the percentage of total server memory
## to assign to LevelDB. LevelDB will dynamically adjust its internal
## cache sizes to stay within this size.  The memory size can
## alternately be assigned as a byte count via leveldb.maximum_memory
## instead.
##
## Default: 70
##
## Acceptable values:
##   - an integer
leveldb.maximum_memory.percent = 70

## To enable Search set this 'on'.
##
## Default: off
##
## Acceptable values:
##   - on or off
search = off

## How long Riak will wait for Solr to start. The start sequence
## will be tried twice. If both attempts timeout, then the Riak node
## will be shutdown. This may need to be increased as more data is
## indexed and Solr takes longer to start. Values lower than 1s will
## be rounded up to the minimum 1s.
##
## Default: 30s
##
## Acceptable values:
##   - a time duration with units, e.g. '10s' for 10 seconds
search.solr.start_timeout = 30s

## The port number which Solr binds to.
## NOTE: Binds on every interface.
##
## Default: 8093
##
## Acceptable values:
##   - an integer
search.solr.port = 8093

## The port number which Solr JMX binds to.
## NOTE: Binds on every interface.
##
## Default: 8985
##
## Acceptable values:
##   - an integer
search.solr.jmx_port = 8985

## The options to pass to the Solr JVM.  Non-standard options,
## i.e. -XX, may not be portable across JVM implementations.
## E.g. -XX:+UseCompressedStrings
##
## Default: -d64 -Xms1g -Xmx1g -XX:+UseStringCache -XX:+UseCompressedOops
##
## Acceptable values:
##   - text
search.solr.jvm_options = -d64 -Xms1g -Xmx1g -XX:+UseStringCache -XX:+UseCompressedOops

EDIT 3
Doing a netstat to check on the port:
[idf@node1 riak]$ netstat -an | grep 10011
[idf@node1 riak]$

[idf@node1 ~]$  netstat -an | grep 10012
[idf@node1 ~]$

EDIT 4:
This is at the top of the crash file /var/log/riak/erl_crash.dump
=erl_crash_dump:0.2
Tue Apr  5 12:40:30 2016
Slogan: Kernel pid terminated (application_controller) ({application_start_failure,riak_core,{{shutdown,{failed_to_start_child,riak_core_
handoff_sup,{shutdown,{failed_to_start_child,riak_core_handoff_listen
System version: Erlang R16B02_basho8 (erts-5.10.3) [source] [64-bit] [smp:16:16] [async-threads:64] [kernel-poll:true] [frame-pointer]
Compiled: Thu Apr  2 16:53:43 2015

EDIT 5
Stopped firewall and tried again same error.
[idf@node1 ~]$ sudo systemctl stop firewalld
[idf@node1 ps ax | grep firewalld
 5485 pts/3    S+     0:00 grep --color=auto firewalld
[idf@node1 ~]$

Unsure how to fix?

A: This is the error that should concern you: {error,eaddrinuse}
It basically means:

EADDRINUSE — stands for error: address already in use. It means you have a server listening on the same port.

Check the riak configuration and ensure that nothing is running on the same IP:Port, netstat -an may help.
EDIT
It's crashing in the riak_core_handoff_listener.erl file. In particular, it's using the following configuration keys to open the IP/Port:
PortNum = app_helper:get_env(riak_core, handoff_port),
IpAddr = app_helper:get_env(riak_core, handoff_ip),

In your config you are setting something different (as far as I can see):
listener.http.internal = 127.0.0.1:10011
listener.protobuf.internal = 127.0.0.1:10012

Every time you change the config Riak will re-generate it. Here it shows you where are the config files read from:
-config /var/lib/riak/generated.configs/app.2016.04.05.11.55.10.config -args_file /var/lib/riak/generated.configs/vm.2016.04.05.11.55.10.args -vm_args /var/lib/riak/generated.configs/vm.2016.04.05.11.55.10.args

Please open the latest version and check exactly what configuration options are used. If riak_core,handoff_port and riak_core, handoff_ip are not configured there then it's likely using default values. According to the riak configuration document that would be port 8099. Either change that port or use netstat -an | grep 8099 to check what's listening on that port.

A: {error,eaddrinuse} is coming for the handoff port which you have not changed and hence the default is 8099.
In installed directory (/usr/lib64/riak) go to lib/riak-<version>/ebin and open riak_core.app or grep to see {handoff_port,8099} to confirm.
Do
netstat -apn | grep 8099
to get the process name which is using the port.
To change the handoff port you can add the following in the riak.conf in /etc/riak
handoff.port = 10013
or any other unused open port

A: I met the same problem, through the following method to solve the problem:
Edit the raik config file vim /etc/riak/riak.conf, Uncomment the line
## ssl.cacertfile = $(platform_etc_dir)/cacertfile.pem
## Acceptable values:
##   - the path to a file
   ssl.cacertfile = $(platform_etc_dir)/cacertfile.pem

## DTrace support Do not enable 'dtrace' unless your Erlang/OTP


text:
Q: Probability that at least one of four hands missing at least one suit Deal each of four players a 13-card hand at random.  What is the probability that at least one of the four hands is missing at least one suit?
Let $A_i$ mean that player $i$ is missing at least one suit.
I can compute the probability that player 1 is missing at least one suit using the inclusion-exclusion principle:
$P(A_1) = \dfrac{4 {39 \choose 13} - 6 {26 \choose 13} + 4{13 \choose 13}}{52\choose 13}$
The four players are identical so that $P(A_1)=P(A_2)=P(A_3)=P(A_4)$.
Again using the inclusion-exclusion principle, the probability that at least one of the four players is missing at least one suit is $P(\cup_{i=1}^4A_i)=4*P(A_1)-{4 \choose 2}P(A_1\cap A_2) + {4\choose 3} P(A_1\cap A_2 \cap A_3) - P(A_1\cap A_2 \cap A_3 \cap A_4)$
Now we know that $P(A_1 \cap A_2)= P(A_2)P(A_1|A_2)$.  Here is where I am stuck.  So far as I can tell, $A_1$ and $A_2$ are not independent, and I can't figure out how to calculate the conditional probability $P(A_1|A_2)$.  Anyone know how to do it?


text:
Q: Eloquent JavaScript - Having Issues With The Beginning of The Robot Project In the Chapter 7 Robot Project, in Eloquent JavaScript, I am kind of having a hard time figuring the beginning portions of the robot project.
const roads = [
   "Alice's House-Bob's House", "Alice's House-Cabin",
   "Alice's House-Post Office", "Bob's House-Town Hall",
   "Daria's House-Ernie's House", "Daria's House-Town Hall",
   "Ernie's House-Grete's House", "Grete's House-Farm",
   "Grete's House-Shop", "Marketplace-Farm",
   "Marketplace-Post Office", "Marketplace-Shop",
   "Marketplace-Town Hall", "Shop-Town Hall"

];

function buildGraph(edges) {
  let graph = Object.create(null);
  function addEdge(from, to) {
    if (graph[from] == null) {
      graph[from] = [to];
      console.log()
    } else {
      graph[from].push(to);
    }
  }
  for (let [from, to] of edges.map(r => r.split("-"))) {
    addEdge(from, to);
    addEdge(to, from);
  }
  return graph;
}

const roadGraph = buildGraph(roads);
console.log(roadGraph)

Here's what I don't understand. This line here is causing my issues because of the brackets around the from, to
for (let [from, to] of edges.map(r => r.split("-")))

When I run it in the eloquent javascript sandbox, it works, but when I try to run it in the cloud9 IDE, or Visual Studio Code, it gives me an array saying
SyntaxError: Unexpected token [

Why am I getting an unexpected token error in the cloud9 IDE or VS Code?
Also, I am not sure I get what is going on, so I will write what I think I understand from the early parts of this project; I would love for someone to give me some clarification on how this project works, if possible.
function buildGraph(edges){
}

The function buildGraph, Takes an array of destinations, makes each destination, a property of an object that we will create, and each of these properties will contain an array of destinations that can be accessed from that destination property.
function buildGraph(edges){
let graph = Object.create(null)

}

This creates an object with an empty prototype, called graph.
function buildGraph(edges) {
  let graph = Object.create(null);

  //Here's Where The Confusion Starts
  function addEdge(from, to) {
    if (graph[from] == null) {
      graph[from] = [to];
    } else {
      graph[from].push(to);
    }
  }

Create a function called addEdge that takes two parameters, which I believe will be destinations. But this portion here, kills me, I honestly don't get what is going on here.
   if (graph[from] == null) {
      graph[from] = [to];
    } else {
      graph[from].push(to);
    }
  }

May someone help? This is my first question on stack overflow, so I apologize if my question wasn't asked 100% correct. But any assistance would be great.

A:
for (let [from, to] of edges.map(r => r.split("-")))

The deconstruction above is not available in older Node. It might be the case your IDE is using an old one (I don't have access to those IDEs, so this is just speculation). I've checked 5.6.0 and 10.9.0: the former doesn't support it, and the latter does.
However, I must admit I am a bit puzzled as to why, since apparently spec prohibits let there (although it is perfectly happy with const).

if (graph[from] == null) {
    graph[from] = [to];
  } else {
    graph[from].push(to);
  }
}

graph is a mapping between nodes and lists of connected destinations. At the start, given that it starts off as a blank object, graph[from] will be undefined; but JavaScript more or less ignores the difference between null and undefined when you use == (as opposed to its stricter brother ===). So when an origin doesn't have any destinations yet in the graph, we'll just set that to a one-element list containing the destination.
On the other hand, if we have already set something there, then graph[from] will already contain a list that we don't want to overwrite, so we'll just append the destination to it using .push.
For example, the first three iterations will build connections from Alice's House. The first to is Bob's House. So graph["Alice's House"] is undefined, and we put ["Bob's House"] there. In the next iteration, it's from Alice's House to Cabin; but now graph["Alice's House"] is not empty, so we append to it, resulting in ["Bob's House", "Cabin"]. At the end of the run, we'll know that if we're at Alice's House, there's three possible places we can go (Bob's House, Cabin and Post Office).

A: if (graph[from] == null) {
    graph[from] = [to];
  } else {
    graph[from].push(to);
  }
}

The code above is building a graph of the village. It will store "to" all the places you can visit "from" any given place.
So It checks whether there is already any road added to this array or not. If not, it will initialise the array with the destination to the node's array. Similarly, if the array already have some destinations from the given array, it will append all other destinations to the array.
Hope it helps.
Update:
for (let [from, to] of edges.map(r => r.split("-")))

You can understand this with an example. The map function will return an array of array. e.g passing an array [a-b, b-c] will return a new array [[a, b], [b, c]]. Now in the for loop, you will iterate through each of these elements in this new array. In interation 1, following thing happens.
[from, to] = [a, b];

So 'from = a' (a here is a location in the village), and 'to = b' (b is another location in the village such that a and b are connected with the road. These values are then passed to the addEdge function to add them to the graph.
I hope my answer makes it clear.


text:
Q: wxPython: weird visual artifacts when using custom controls with a notebook control I'm having weird visual artifacts when I use a custom control with a notebook control. I managed to get the bug isolated to a small program.
I am using Python 2.7 and wxPython, not having made the switch to Python 3 yet. I have a custom control that draws "A's." I use a vertical Box sizer and draw two A's, and then I draw a static text label. The second A is initially a black box, which is the bug. If I move the window off screen and back on, it becomes a second A. Oddly enough this only happens if there are two tabs, if I remove the two lines dealing with tab2, the bug goes away.
Also, I based my custom control off of the following link. This link used a checkbox custom control and had the same issue that my custom control had:
https://wiki.wxpython.org/CreatingCustomControls
Any help is appreciated!
import wx

class MyControl(wx.PyControl):
    def __init__(self, parent, size):
        wx.PyControl.__init__(self, parent, style=wx.BORDER_NONE)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.SetInitialSize(size)

    def OnPaint(self, event):
        dc = wx.BufferedPaintDC(self)
        dc.Clear()
        dc.DrawText("A", 0, 0)

    def OnEraseBackground(self, event):
        pass

class GUI(object):
    def __init__(self):
        app = wx.App(False)
        windowFrame = wx.Frame(None)
        windowFrame.SetSize((300, 300))

        notebook = wx.Notebook(windowFrame)
        tab1 = wx.Panel(notebook)
        tab1Sizer = wx.BoxSizer(wx.VERTICAL)
        tab1.SetSizer(tab1Sizer)
        notebook.AddPage(tab1, "Tab1")

        tab2 = wx.Panel(notebook)
        notebook.AddPage(tab2, "Tab2")

        myControl1 = MyControl(tab1, size=(20,20))
        tab1Sizer.Add(myControl1)
        myControl2 = MyControl(tab1, size=(20,20))
        tab1Sizer.Add(myControl2)
        label3 = wx.StaticText(tab1, label="Test3")
        tab1Sizer.Add(label3)

        windowFrame.Show()
        app.MainLoop()

def main():
    GUI()

main()


text:
Q: Ext Js :: "Error: [Ext.getBody] document.body does not exist at the point " When using Activity Monitor Class? I am sporadically  hitting an error [Ext.getBody] document.body does not exist at the point " in chrome. and in IE.
This is because of using https://github.com/arthurakay/ExtJS-Activity-Monitor/blob/master/Ext.ux.ActivityMonitor
my index.html do have body tags.
Anyone has any suggestion?

A: [Ext.getBody] document.body does not yet exist
load your bootstrap.js script end of the body in index.html


text:
Q: mysql access denied for user ERROR 1045 I'm trying to user mysql on my machine, but I can't access the program.
I added configuration using mysql_config_editor as such:
mysql_config_editor set --login-path=client --user=root -p --host=localhost

and when i do a print i get:
[client]
user = root
password = *****
host = localhost

But when I try to connect to mysql, I get the following error
#mysql -u root -p
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using passowd: YES)

And when I try to connect like this, i get:
#mysql -u root -p -h127.0.0.1
ERROR 1130 (HY000): Host 'localhost' is not allowed to this MYSQL server

Every other answer I found was to do a SQL command. But i can't get inside the shell to do it.
Thanks

A: Have you already tried using the --skip-grant-tables option? If you have, and it doesn't allow you to access the mysql shell, go into your mysql installation folder and open my.ini file (my.cnf for most Linux distros). Inside it you'll find a mysqld tag, add skip-grant-tables underneath it and restart your mysql server. You'll be able to access your shell and therefrom edit the rights/privileges.