Converter Json em um Objeto Csharp

Question:  public IActionResult MoedaTurismo()
    {
        try
        {
            RestClient restClient = new RestClient();
            RestRequest restRequest = new RestRequest();
            restRequest.AddHeader("cache-control", "no-cache");
            restRequest.AddHeader("content-Type", "application/json");
            restClient.BaseUrl = new Uri("http://economia.awesomeapi.com.br/USD-BRLT/1");

            var response = restClient.Execute(restRequest);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var json = response.Content;
                var Moeda = JsonConvert.DeserializeObject(json);

                return (object);
            }
            return NotFound();
        }
        catch (Exception ex)
        {
            return StatusCode((int)HttpStatusCode.InternalServerError);

        }

    }

Quero converter Json para C#, esta correto ?
Comment: Em teoria sim, qual o erro?
Comment: preciso fazer a conversão Json para objeto c#.
Answer: Primeiro use json2csharp para mapear todos os campos do Json para uma classe.
Modelo:
public class Moeda
{
  public string code { get; set; }
  public string codein { get; set; }
  public string name { get; set; }
  public string high { get; set; }
  public string low { get; set; }
  public string pctChange { get; set; }
  public string open { get; set; }
  public string bid { get; set; }
  public string ask { get; set; }
  public string varBid { get; set; }
  public string timestamp { get; set; }
  public string create_date { get; set; }
}

JSON:
[
   {
      "code":"USD",
      "codein":"BRLT",
      "name":"D\u00f3lar Turismo",
      "high":"3.91",
      "low":"3.75",
      "pctChange":"-0.488",
      "open":"0",
      "bid":"3.76",
      "ask":"4.08",
      "varBid":"-0.02",
      "timestamp":"1544452500000",
      "create_date":"2018-12-10 12:40:03"
   }
]

Note que o JSON trazido na url ele é composto por [] então ele é interpretado como uma matriz e não um objeto, então use uma coleção para deserializar JSON  List<T>
Exemplo:
 public IActionResult MoedaTurismo()
 {
            try
            {
                RestClient restClient = new RestClient();
                RestRequest restRequest = new RestRequest();
                restRequest.AddHeader("cache-control", "no-cache");
                restRequest.AddHeader("content-Type", "application/json");
                restClient.BaseUrl = new Uri("http://economia.awesomeapi.com.br/USD-BRLT/1");

                var response = restClient.Execute(restRequest);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var json = response.Content;
                    List<Moeda> obj = JsonConvert.DeserializeObject<List<Moeda>>(json);

                    return (object);
                }
                return NotFound();
            }
            catch (Exception ex)
            {
                return StatusCode((int)HttpStatusCode.InternalServerError);

            }

 }

Converter Json em um Objeto Csharp


What is use of 802.11 open authentication req/response frames

Question: As far as I know, the 802.11 open authentication request/response frame is used for WEP(open/shared key) security.
Nowadays we are not using WEP security, then why these two frames are exchanged after probe response.
Can someone plz clarify that why 802.11 open authentications req/res frames are used in WPA/WPA2-akm-802.1x/psk security and in which scenario 802.11 open authentication response frame fails(status code-0x0001).
Answer: Mainly backwards compatibility. Wi-Fi technology is 20 years old but you can still connect an old 11b client to a fully fledged 2020 access point (and vice versa).


WordPress: Custom default avatar on localhost?

Question: I'm trying to add a custom default avatar to WordPress in functions.php, but the image is not displaying in Settings/Discussion or elsewhere on the site. The code works because a new radio field is added with the custom field name, but the image won't display. Is the avatar not displaying because I'm using Localhost?
I don't have enough reps to comment on similar questions.
here's the code:
add_filter( 'avatar_defaults' , 'wps_new_avatar' );
function wps_new_avatar( $avatar_defaults ){
    $new_avatar = get_stylesheet_directory_uri() . '/images/default-avatar.png';
    $avatar_defaults[$new_avatar] = "Default Avatar";
    return $avatar_defaults;
}

I've tried other examples and the 'Add-New-Default-Avatar' plugin with the same result.
Comment: try using $new_avatar =.'/images/default-avatar.png';
Comment: Maybe external access is not enabled in your local server. Avatars are normally fetched from external resources. You have to be on line, of course.
Comment: @Arunu: No that didn't work
Comment: @FelipeAlamedaA but if I'm telling it to fetch the avatar from a file location or from a media library upload, why is it not displaying? The other built in avatars display.
Answer: I was facing the same issue and came up with this completely hackish solution... It works though :)
add_filter( 'get_avatar', 'so_14088040_localhost_avatar', 10, 5 );

function so_14088040_localhost_avatar( $avatar, $id_or_email, $size, $default, $alt )
{
    $whitelist = array( 'localhost', '127.0.0.1' );

    if( !in_array( $_SERVER['SERVER_ADDR'] , $whitelist ) )
        return $avatar;

    $doc = new DOMDocument;
    $doc->loadHTML( $avatar );
    $imgs = $doc->getElementsByTagName('img');
    if ( $imgs->length > 0 )
    {
        $url = urldecode( $imgs->item(0)->getAttribute('src') );
        $url2 = explode( 'd=', $url );
        $url3 = explode( '&', $url2[1] );
        $avatar= "";
    }

    return $avatar;
}

Result:

Of course, this filter is meant for development only.
Comment: I'm quite positive this code can be greatly improved. I just went applying one hack after another *(based on SO research)* until it worked.
Comment: This works! This works with the code I used in my question, the 'Add-New-Default-Avatar' plugin, and also with an mu-plugin to change the default avatar. However, it breaks all other avatars built-in and test-user uploaded. But it works for development purposes!
Comment: @gundam00, for me the *user uploaded* avatars **do show**... [Useful Q&A's](http://wordpress.stackexchange.com/search?q=avatar_default).
Comment: since we're using the same code, for me, uploading an avatar thru the user's profile returns a blank box with the img src blank:  However, the hacked custom avatar's img src shows the avatar's file location. But your hack allowed me to display the custom default avatar for testing purposes, which is what I needed.
Comment: To me the problem has been the option on the discussion settings of WordPress: the show avatar was unchecked! I was going to be crazy!


Statistics test to compare counts

Question: I have two processes that produce the same type of event. For example, after 48 hours I may have 10,321 events from one process and 11,548 events from the other.
What statistical test do I use to determine the chance that Process B produces events at a faster rate than Process A?
Comment: One way to begin clarifying this problem is to note that over that particular 48 hour time period, the other process produced more events--period. There's no chance involved in that statement. If you are uncertain, then, it could be because (a) you're not sure the data are accurate or (b) you would like to make an inference about how the processes perform in other time periods. In either case you cannot proceed without assumptions: *exactly* how could the data be in error and *exactly* how would the process counts be related to one another during different time periods?
Answer: There are a number of approaches that could be taken.
Perhaps the simplest would be to condition on the total number of events. Then if the events were each being produced independently at a constant rate, under the null hypothesis of equal rates the 'true' population proportion of events of each type is 0.5.
One can simply run a binomial test.
However, a hypothesis test doesn't tell you "the chance that Process B produces events at a faster rate than Process A". It would allow you to reject the null against a directional alternative (or a two-tailed alternative if you didn't know beforehand which one you expected should be faster), but not give an unconditional probability statement.
If you want a statement of the form "probability B is faster than A" you'd need to perform a Bayesian analysis with some model for the rates, and with a prior on that probability.

Statistics test to compare counts


How to sort an array of objects with multiple field values in JavaScript

Question: I found a great method to sort an array of objects based on one of the properties as defined at:
Sort array of objects by string property value in JavaScript
Using that function works perfectly for a single sort (on all browsers), and even a sort within another sort EXCEPT using Google Chrome!  Here is Ege Özcan's great sort routine for arrays of objects
function dynamicSort(property) {
    return function (a,b) {
        return (a[property]  b[property]) ? 1 : 0;
    }
}

Using an array named "Data" (of course, my array has many more object pairs)...
var Data = [{Category: "Business", Value: "ABC"},{Category:"Personal", Value:"XYZ"}];

I can get a proper sort where the order is listed as all the values within each category by doing this...
Data.sort(dynamicSort("Value"));
Data.sort(dynamicSort("Category"));

By first sorting on Value, and then by Category, my array puts all values in sorted order with all the Business-base values listed first and then all the Personal-based values.  Perfect!  Except in Chrome where the data is sorted properly by category, but the order of the values within each category seems rather random.
Does any one know of a better way to do a sort within a sort that would also work in Chrome?
Comment: sorting by A and then independently sorting by B _is not the same as sorting by A **and** B_.  If it worked on some browsers it was a fluke.
Answer: I created a multi-parameter version of that dynamicSort function:
function dynamicSort(property) {
    return function (obj1,obj2) {
        return obj1[property] > obj2[property] ? 1
            : obj1[property] < obj2[property] ? -1 : 0;
    }
}

function dynamicSortMultiple() {
    /*
     * save the arguments object as it will be overwritten
     * note that arguments object is an array-like object
     * consisting of the names of the properties to sort by
     */
    var props = arguments;
    return function (obj1, obj2) {
        var i = 0, result = 0, numberOfProperties = props.length;
        /* try getting a different result from 0 (equal)
         * as long as we have extra properties to compare
         */
        while(result === 0 && i < numberOfProperties) {
            result = dynamicSort(props[i])(obj1, obj2);
            i++;
        }
        return result;
    }
}

I created an array as follows:
var arr = [
    {a:"a",b:"a",c:"a"},
    {a:"b",b:"a",c:"b"},
    {a:"b",b:"a",c:"a"},
    {a:"b",b:"a",c:"b"},
    {a:"b",b:"b",c:"a"},
    {a:"b",b:"b",c:"b"},
    {a:"b",b:"b",c:"a"},
    {a:"b",b:"b",c:"b"},
    {a:"b",b:"b",c:"a"},
    {a:"b",b:"b",c:"b"},
    {a:"b",b:"b",c:"a"},
    {a:"c",b:"b",c:"b"},
    {a:"c",b:"c",c:"a"}
];

and it worked when I did,
arr.sort(dynamicSortMultiple("c","b","a"));

And here is a working example: http://jsfiddle.net/ZXedp/
Comment: this one does, also with multiple properties: http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript/4760279#4760279
Comment: Hello, this works amazing but how you do this by passing an array of properties like ["a", "b"] and other is when the property needs to be grater that for example [{a: {gt: 5}}] "gt is grater that"
Comment: @LuisDanielMonsalveRuiz you can do dynamicSortMultiple(...myArray)

for the "greater than" example, you want to filter the results, AFAICT. you may want to look at array.prototype.filter
Answer: The easiest way to perform a Javascript Multi-Criteria Sort (or Multi-Parameter Sort), is to use .sort, concatenate the multiple parameters together, and compare the two stings.
For example:
data.sort(function (a, b) {

  var aConcat = a["property1"] + a["property2"];
  var bConcat = b["property1"] + b["property2"];

  if (aConcat > bConcat) {
    return 1;
  } else if (aConcat < bConcat) {
    return -1;
  } else {
    return 0;
  }

});

I've included a JsFiddle Script here: http://jsfiddle.net/oahxg4u3/6/
Answer: I now this post is quite old, anyway I found it today and quoting Ege Özcan, I improved his excellent solution implementing DESC-ASC SQL-Like functionality for anyone interested (http://jsfiddle.net/ZXedp/65/):
function dynamicSortMultiple() {
    var props=[];
    /*Let's separate property name from ascendant or descendant keyword*/
    for(var i=0; i < arguments.length; i++){
        var splittedArg=arguments[i].split(/ +/);
        props[props.length]=[splittedArg[0], (splittedArg[1] ? splittedArg[1].toUpperCase() : "ASC")];
    }
    return function (obj1, obj2) {
        var i = 0, result = 0, numberOfProperties = props.length ;
        /*Cycle on values until find a difference!*/
        while(result === 0 && i < numberOfProperties) {
            result = dynamicSort(props[i][0], props[i][1])(obj1, obj2);
            i++;
        }
        return result;
    }
}

/*Base function returning -1,1,0 for custom sorting*/
function dynamicSort(property, isAscDesc) {
    return function (obj1,obj2) {
        if(isAscDesc==="DESC"){
            return ((obj1[property] > obj2[property]) ? (-1) : ((obj1[property] < obj2[property]) ? (1) : (0)));
        }
        /*else, if isAscDesc==="ASC"*/
        return ((obj1[property] > obj2[property]) ? (1) : ((obj1[property] < obj2[property]) ? (-1) : (0)));
    }
}

call the function by something like this:
arr.sort(dynamicSortMultiple("c DESC","b Asc","a"));

Answer: You may also want to have a look at thenBy.js: https://github.com/Teun/thenBy.js
It allows you to use the standard Array.sort, but with firstBy().thenBy().thenBy() style.
Comment: Better: `firstBy = (function() { function tb(y) { var x=this; function f(a,b) { return x(a,b)||y(a,b); } f.thenBy = tb; return f; } return function(f) { f.thenBy = tb; return f; }; })();`
Comment: I'm interested in why this is better.  Could you detail? Maybe using a pull request?
Comment: 1) only one, shared `thenBy` function 2) no unnecessary `secondaryFunction` 3) it's shorter 4) it's more functional, yours would've problems with `var a = firstBy(x), b = a.thenBy(y), c = a.thenBy(z)` because `a`==`b`==`c`
Comment: Thanks. I didn't see much of a reason to do the whole function-call-wrap circus here, but maybe you're right. I will play a bit with both and credit you if I replace it with your version.
Comment: Got my version down to 137 characters. See https://github.com/bergus/thenBy.js :-)
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/34845/discussion-between-teun-d-and-bergi)
Comment: Thank you for this reference, I messed with multi-key sorting for longer than I care to admit, then within 5 minutes it was solved by thenBy. Thanks again!
Answer: Here is my solution. It faster than lodash's _.sortBy() multi-column sort function in about two times (see http://jsperf.com/multi-column-sort.
I generate text of sorting function, then use it in standard .sort(). It works in Chrome and Firefox as well.
function multiColumnSort(arr,sf) {
    var s = '';
    sf.forEach(function(f,idx) {
        s += 'if(arguments[0].'+f+'>arguments[1].'+f+')return 1;';
        s += 'else if(arguments[0].'+f+'==arguments[1].'+f+')';
        s += (idx < sf.length-1)? '{' : 'return 0';
    });
    s += Array(sf.length).join('}')+';return -1';
    return arr.sort(new Function(s));
};

Answer:

let obj = [{ name: "Gaurav" }, { name: "nidhu" }, { name: "Abhishek" }, { name: "cat" }, { name: "here" }];
for (let i = 0; i < obj.length; i++) {
  for (let j = 1; j < obj.length; j++) {
    if (obj[j - 1].name[0].toLowerCase() > obj[j].name[0].toLowerCase()) {
      let temp = obj[j - 1];
      obj[j - 1] = obj[j]
      obj[j] = temp
    }
  }
}
console.log(obj)
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How can I tell if my CSS style changes will affect other pages?

Question: I lead a team of junior developers that would change CSS styles without the realization that their change would affect the other pages of our website as well.
Is there an extension or technique that I can use to let them know if they change this class color, ALL these pages (we have over 100 pages) with the same class would be affected as well?
Comment: I know this might sound stupid, but they should know that classes are global. A quick search in any good IDE will tell them the files those are used in and if they don't want other files to change they have to be more specific. Telling them that **should** be enough.
Comment: Your team should already know this if they are working on a production code, or they *should* know what css files they are editing and how it applies in scope to the site.
Comment: @SourceOverflow that is true.  I plan on teaching them CSS-specificity calculations
Answer: Unfortunately is not that easy. It all depends on how well your css is structured and maintained.
There are many css guidelines that can help you to solve this problem.
What you can do is use namespaces. It suggest that you use different individual namespaces to help you with css scaling.
Some of namespaces are:
o-: Signify that something is an Object, and that it may be used in any number of unrelated contexts to the one you can currently see it in. Making modifications to these types of class could potentially have knock-on effects in a lot of other unrelated places. Tread carefully.
c-: Signify that something is a Component. This is a concrete, implementation-specific piece of UI. All of the changes you make to its styles should be detectable in the context you're currently looking at. Modifying these styles should be safe and have no side effects.
u-: Signify that this class is a Utility class. It has a very specific role (often providing only one declaration) and should not be bound onto or changed. It can be reused and is not tied to any specific piece of UI. You will probably recognise this namespace from libraries and methodologies like SUIT.
t-: Signify that a class is responsible for adding a Theme to a view. It lets us know that UI Components' current cosmetic appearance may be due to the presence of a theme.
s-: Signify that a class creates a new styling context or Scope. Similar to a Theme, but not necessarily cosmetic, these should be used sparingly—they can be open to abuse and lead to poor CSS if not used wisely.
is-, has-: Signify that the piece of UI in question is currently styled a certain way because of a state or condition. This stateful namespace is gorgeous, and comes from SMACSS. It tells us that the DOM currently has a temporary, optional, or short-lived style applied to it due to a certain state being invoked.
_: Signify that this class is the worst of the worst—a hack! Sometimes, although incredibly rarely, we need to add a class in our markup in order to force something to work. If we do this, we need to let others know that this class is less than ideal, and hopefully temporary (i.e. do not bind onto this).
js-: Signify that this piece of the DOM has some behaviour acting upon it, and that JavaScript binds onto it to provide that behaviour. If you're not a developer working with JavaScript, leave these well alone.
qa-: Signify that a QA or Test Engineering team is running an automated UI test which needs to find or bind onto these parts of the DOM. Like the JavaScript namespace, this basically just reserves hooks in the DOM for non-CSS purposes.
For more read here:
https://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/
Comment: That is actually a really good idea. +1 Just two things, I'd like to add: 1) those are **not** real namespaces, but prefixes. The nearest thing to a namespace would be something like a `sidebar-container` and later I use e.g. `.sidebar-container .button` to reference the buttons in that container. 2) Unless you have to look out for performance, especially with jQuery, you should think about using attributes instead of classes with `is-, has-` prefixes for states, as that does make a cleaner distinction between style and function and is even clearer when using them.
Answer: Get license for Applitool or similar software in your company and through this you can create a visual baseline for all those pages and Applitool app will throw an error if that page changes visually.
If the change is acceptable for you then you can go ahead and accept the changes to be your new baseline if not then you need to revisit the issue.
Comment: Sure np I understand the reason plus in a corporate environment a reason why this is so difficult is cause resources might change and unless they have prior knowledge of how those changes impact they would have no idea neither would you. So automated visual testing is the way to go my friend.


systemverilog: Binary tree using systemverilog oop concepts

Question: i was wondering since systemverilog has oops concepts. Is it possible to create binary tree of n nodes in systemverilog
class node;

    int val;
    node left,right;
    function new(int data);
        val=data;
        left=null;
        right=null;
    endfunction
endclass

class btree;

    node root;

    function new(int info);
        root=new(info);
    endfunction

endclass

btree b1;

module abc();

    initial begin
        b1=new(1);
        b1.root=new(2)
        b1.root.left= new(3);
        b1.root.right= new(4);

        $display("%0p",b1);
    end
endmodule

i am trying to create a binary tree capable of adding any number of nodes, delete nth node and could tranverse through tree to print.
Comment: No. it is just printing @node@1 something like this.
basically i want to implement binary tree using systemverilog
Comment: The only answer to the your question the way you have worded it is simply "yes, it is possible". If you want someone to write the code for you, that is no longer a question, that is a homework/interview assignment.
Answer: Since there is no clear question, there is no clear answer. The following is just a place holder for an example which might or might not allow you to move forward a bit.
When you do $display(b1) it only supposed to print some info about the b1 which is an instance of class 'btree'. So, there is not much. If you want to print info about all branches and leaves, you need to create a (recursive) function which would do it.
The following example provides such a function 'print'. You can use it as a starting point for your tree exploration. You also need to implement some code to insert new nodes (or delete, if you need). If you need a balanced tree, you need to add corresponding balancing functionality.
Also, remember that this code is not synthesizable and can only be used in test benches. Synthesizable code will require a completely different approach.
class node;

    int val;
    node left,right;
    function new(int data);
        val=data;
        left=null;
        right=null;
    endfunction

  /// print function ///
  function void print();
    $display("val: %0d", val);
    if (left != null)
      left.print();
    if (right != null)
      right.print();
  endfunction
endclass

class btree;

    node root;

    function new(int info);
        root=new(info);
    endfunction

endclass

btree b1;

module abc();

    initial begin
        b1=new(1);
      b1.root=new(2);
        b1.root.left= new(3);
        b1.root.right= new(4);

        //$display("%0p",b1);
      // use the print function
      b1.root.print();
    end
endmodule


How to implement Round Shaped AppBar with Gradient Background in Flutter?

Question: I want to achieve an AppBar which has a rounded bottom radius and gradient background. Also, I need to place some other content like cards within AppBar using the bottom property.
Here is my code:
import 'package:flutter/material.dart';

void main() => runApp(const Toddly());

class Toddly extends StatelessWidget {
  const Toddly({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Toddly',
      home: Scaffold(
        appBar: AppBar(
          leading: GestureDetector(
            onTap: () {},
            child: Container(
              margin: const EdgeInsets.only(left: 10),
              padding: const EdgeInsets.all(2),
              decoration: const BoxDecoration(
                color: Color.fromARGB(255, 158, 77, 130),
                shape: BoxShape.circle,
              ),
              child: const CircleAvatar(
                backgroundImage: AssetImage('assets/images/profilePicture.png'),
              ),
            ),
          ),
          title: const Text(
            'Julia',
            style: TextStyle(
              fontFamily: 'Nunito',
            ),
          ),
          centerTitle: true,
          actions: [
            IconButton(
              onPressed: () {},
              icon: const Icon(Icons.notifications_outlined),
            ),
            IconButton(
              onPressed: () {},
              icon: const Icon(Icons.menu),
            ),
          ],
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(150.0),
            child: Container(
              height: 100,
              width: 100,
              color: Colors.white,
              alignment: Alignment.center,
              child: const Text('Some content'),
            ),
          ),
          flexibleSpace: Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Color(0xFF72326a),
                  Color(0xFF321c53),
                ],
              ),
            ),
          ),
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(
              bottom: Radius.circular(30.0),
            ),
          ),
        ),
        backgroundColor: const Color(0xFFfef1ee),
      ),
    );
  }
}

I used the shape property to implement rounded bottom AppBar.
I did gradient background using flexibleSpace.
And, I used bottom to add my other content under within AppBar.
However when I run all above code. rounded bottom appBar is not working.
image source
And, if I remove flexibleSpace it is showing, but I lost my gradient.
image source
Please, help me to figure it out and is it possible to do that without creating custom AppBars since I saw several approaches.
Thanks
Answer: All you just need to add corner radius to gradient container as well attaching you the updated code.

import 'package:flutter/material.dart';

void main() => runApp(const Toddly());

class Toddly extends StatelessWidget {
  const Toddly({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Toddly',
      home: Scaffold(
        appBar: AppBar(
          leading: GestureDetector(
            onTap: () {},
            child: Container(
              margin: const EdgeInsets.only(left: 10),
              padding: const EdgeInsets.all(2),
              decoration: const BoxDecoration(
                color: Color.fromARGB(255, 158, 77, 130),
                shape: BoxShape.circle,
              ),
              child: const CircleAvatar(
                backgroundImage: AssetImage('assets/images/profilePicture.png'),
              ),
            ),
          ),
          title: const Text(
            'Julia',
            style: TextStyle(
              fontFamily: 'Nunito',
            ),
          ),
          centerTitle: true,
          actions: [
            IconButton(
              onPressed: () {},
              icon: const Icon(Icons.notifications_outlined),
            ),
            IconButton(
              onPressed: () {},
              icon: const Icon(Icons.menu),
            ),
          ],
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(150.0),
            child: Container(
              height: 100,
              width: 100,
              color: Colors.white,
              alignment: Alignment.center,
              child: const Text('Some content'),
            ),
          ),
          flexibleSpace: Container(
            decoration: const BoxDecoration(
            borderRadius: BorderRadius.vertical(
              bottom: Radius.circular(30.0),
            ),
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Color(0xFF72326a),
                  Color(0xFF321c53),
                ],
              ),
            ),
          ),
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(
              bottom: Radius.circular(30.0),
            ),
          ),
        ),
        backgroundColor: const Color(0xFFfef1ee),
      ),
    );
  }
}


Mysterious behavior when using CSS "object-fit:contain" property on images inside a flexbox container having a specific height

Question: I've got a flexbox container in which I'm trying to display two images with drop-shadows side-by-side. I want them to take equal amounts of horizontal space even though the images differ in size. I'm using a container with style "display: flex" and using "object-fit: contain" for the images to cause them to scale. My code works if I don't give the container a specific height. If I give the container a specific height, such as 300px, the images scale down, but the drop-shadow appears at a distance from the image edges as though there's a box wrapping them. This seems odd behavior. Can anyone explain this odd-seeming behavior, and is there a way in which I can give the container a height and still get it to work?
Fiddle to illustrate: https://jsfiddle.net/Lej1a6vp/
html:

css:
.container {
  display: flex;
  margin: 1em auto 3em auto;
  width: 500px;
  height: 200px;
  justify-content: center;
  align-items: center;
}
img {
  box-shadow: 8px -8px 10px #00000080;
  height: 100%;
  width: 40%;
  margin-left: 1em;
  object-fit: contain;
}

Comment: use `object-fit: cover` instead
Comment: related: https://stackoverflow.com/a/54376890/8620333
Comment: Should have mentioned that I want to maintain the aspect ratio of the real images.
Answer: If you set the height to auto it will make them the same width but height will be different, if you want them to be the same height and width then you have to use an image with the same aspect-ratio for this to work since it is not possible to make it the same width and height without cropping if aspect ratios are different.
There is a #FutureCSS property called aspect-ratio: 16 / 9; in which you can lock elements to a specific ratio but it's still not available in all browsers;
    .container {
  display: flex;
  margin: 1em auto 3em auto;
  width: 500px;
  height: auto;
  justify-content: center;
  align-items: center;
}

img {
  box-shadow: 8px -8px 10px #00000080;
  height: auto;
  width: 50%;
  margin-left: 1em;
  object-fit: contain;
}

Answer: BDB88 provided me with the clue I needed, and thanks for that. My objective is to make a responsive layout that will show the drop shadow around the images and not some ghostly outline that's at a distance, and I want to keep the images' aspect ratios. I also want to mandate a particular height for the container, and not have the images overflow outside of it. My use of "height: 100%;" for the img tag was what was causing the problem. Combining that with the "width: 40%;" was causing conflict because both requirements can't always be satisfied simultaneously. By changing to "max-height: 100%;" and "max-width: 40%;" for the img tag, I'm getting the behavior that I was after. The CSS is now (I made some additional edits to make the behavior more apparent when viewing and scaling the window to simulate larger/smaller screen sizes):
.container {
  background: yellow;
  display: flex;
  margin: 1em auto 3em auto;
  width: auto;
  height: 200px;
  justify-content: center;
  align-items: center;
}
img {
  box-shadow: 8px -8px 10px #00000080;
  max-width: 40%;
  max-height: 100%;
  margin-left: 1em;
  object-fit: contain;
}


Why is left-skewed called negatively skewed and right-skewed called positively skewed?

Question: I'm curious about the nomenclature: why is left-skewed called negatively skewed and right-skewed called positively skewed?
Comment: Let's underline that the terms left and right depend on a tacit convention that the magnitude axis of a graph showing a distribution s horizontal with negative values to the left. This may seem too obvious to state, except to those who do things differently.
Answer: My short answer is that it is by design. The skewness measures are usually constructed so that the positive skewness indicates right-skewed distributions.
Today the most common measure of skewness, that is also usually taught in schools, is based on the third central moment equation as follows:
$$\mu_3=E[(X-\mu)^3]$$
Look at the expression above. When there's more weight (of the distribution function) to the right of the mean then $(x-\mu)^3$ will contribute more positive values. The right of the mean is positive, because $x>\mu$ and the left is negative because $x<\mu$. So, mechanically it would seem to answer exactly your question.
However, as @Nick Cox brought up, there is more than one measure of skewness, such as Pearson's first coefficient of skewness, which is based on the difference $mean-mode$. Potentially, different measures of skewness could lead to different relations between positive skewness and the tendency to have heavier tails on the right.
Hence, it is interesting to look at why these measures of skewness were introduced in the first place, and why do they have their particular formulations.
In this context it is useful to look at the exposition of skewness by Yule in An Introduction to the Theory of Statistics (1912). In the following excerpt he describes the desired properties of a reasonable skewness measure. Basically, he requires that the positive skewness should correspond to right skewed distributions, like in your picture:
Comment: Correct, but incomplete in so far as there are several other ways to measure skewness. But all I that know of follow the same convention that right-skewed and left-skewed typically yield positive and negative results respectively, as for example (mean $-$ median)/SD.  The only certain thing, however, is that symmetrical distributions have zero skewness. It is possible to have asymmetrical distributions for which different skewness measures don't even agree in sign.
Comment: I believe you, but the question remains general and benefits from a general answer. In a century or so, considerable confusion has already been caused by conflating a general idea of skewness with particular ways of defining it. (I won't mention kurtosis.)
Comment: The historical details here are very interesting to me. My own attempt at a miniature review emphasises that moment-based skewness predates Pearson, although Pearson was mostly more concerned with measuring skewness relative to the mode, as Yule's comments reflect. See  http://www.stata-journal.com/sjpdf.html?articlenum=st0204 (Indeed, Pearson was obfuscatory in his acknowledgement of prior work on the moment-based measure.)
Comment: The extract from Yule helps us see past the extraneous details to the essence of the answer: a distribution in which the positive tail is deemed to be "longer" than the negative tail has positive skewness.  Everything else comes down to how one determines the tails and measures their lengths.
Comment: I don't see how the answer would lose anything by mentioning one or two other measures of skewness (such as the median-skewness / second Pearson skewness measure) and pointing out that the discussion carries over (just as Nick suggests).
Comment: (mean $−$ median)/SD has attractive small properties: easy to calculate, easy to explain and usefully bounded in $[-1, 1]$. It is surprising to me that more textbooks can't find space to mention it. Of course, it lacks the embedding in more general families which skewness has in moment-based measures and L-skewness has in L-moments.
Comment: @NickCox, he was using the same pic as in Wiki page, so I figured he'd follow the same definition, but you're right that there are more than one definition
Comment: +1 Although I share some of the reservations expressed by @NickCox, I don't see how we can separate the calculation of skewness from its definition.  How, otherwise, could we define or characterize skewness if not by means of some definite property of a distribution?  Once we acknowledge that the most common and well-known definition is the standardized third moment, then this answer settles the question.
Comment: Indeed, in most cases in experience, it is easy to match positive and right, negative and left. It's just important to be prepared for complications and exceptions.
Comment: @NickCox, I updated my post, basically, saying that the positive skew for longer right tail is by construction (definition).
Comment: Of many related threads, http://stats.stackexchange.com/questions/145159/how-to-tell-if-my-data-distribution-is-symmetric went through some similar issues with all the persons so far in the discussion of this answer
Comment: I'd flag that although using the mode in a measure can be linked to simple sketches, this was easier for Karl Pearson than it is now because his context was fitting his own family of distributions for which the mode can be estimated once you have estimated the parameters for that family. Now mode estimation for continuous variables implies to most statistical people first getting a density estimate and then identifying the value with the highest density, which raises the small but not trivial problems of exactly how you do that.  Mode estimation for discrete variables is usually easier.


Free resolution of a group $G$ and the chain complex of the universal cover of $K(G,1)$

Question: Consider a group $G$ having
a finite, free resolution $C_*(G)\to \mathbb Z$ over the group ring of $G$.
I want to understand why this resolution may be viewed as the equivariant chain complex of the universal cover $\widetilde X$ of the Eilenberg-MacLane space $X=K(G, 1)$.
I found this problem when I was computing the homology group of the circle with local coefficients, I read that the chain complex of the universal cover of $X=S^1$ which is $\widetilde X=\mathbb R$  is the same as a free resolution of $\mathbb Z$. So I wanted to understand this relation between the free resolution of the group and the equivariant chain complex of the universal cover of its corresponding $K(G,1)$. Thank you for your help!
Answer: It is actually other way around: every classifying space gives rise to a free resolution. Why is so? Take your favourite CW structure on this space. Then chain complex of universal cover under monodromy action becomes a resolution of a trivial module. Modules will be free because cellular action is free, and homology will be $\Bbb Z$ in degree $0$ as for any contractible space.
And it is actually only in this way. Not every free resolution of a trivial module can be obtained as a chain complex of contractible free $G$-space. For example, there are groups which have free resolution of finite rank in each dimension, but are not finitely presented; not-finitely presented group cannot have a classifying space with finite 2-skeleton, so this resolution does not come from topology.
Comment: With all the conditions on $G$ that makes this possible, how can we start from a free resolution of $G$ and view it as an equivariant chain complex $C_*(\widetilde X)$ of the universal cover $\widetilde X$ of $X=K(G,1)$?


List of objects to Dictionary with distinct keys and selected values

Question: I have a List of objects of following class:
class Entry
{
    public ulong ID {get; set;}
    public DateTime Time {get; set;}
}

The list contains several object per ID value, each with different DateTime.
Can I use Linq to convert this List<Entry> to a Dictionary<ulong, DateTime> where the key is the ID and the value is Min<DateTime>() of the DateTimes of that ID?
Answer: Sounds like you want to group by ID and then convert to a dictionary, so that you end up with one dictionary entry per ID:
var dictionary = entries.GroupBy(x => x.ID)
                        .ToDictionary(g => g.Key,
                                      // Find the earliest time for each group
                                      g => g.Min(x => x.Time));

Or:
                         // Group by ID, with each value being the time
var dictionary = entries.GroupBy(x => x.ID, x => x.Time)
                         // Find the earliest value in each group
                        .ToDictionary(g => g.Key, g => g.Min())

Comment: @vipirtti: Yup, there are two deleted answers, although one is less efficient and the other wouldn't work yet.
Comment: I think you scared away all the other answers as I'm sure there were at least two of them just a moment ago.


How can I use one component (page) for multiple route in Next JS

Question: As you all know Next JS doesn't have any route, I am trying to build a web app in next JS in which I have to use the same component for multiple routes without copy pasting in to different directory.
Directroy structure:
src
    pages
        new (AddListComponent)
        edit-[id] (AddListComponent)

AddListComponent
import React from 'react'
import { withRouter } from 'next/router'

class Listing extends React.Component {
    constructor(props){
        super(props)
        this.state = {
        }
    }
    render () {
        return (

This is my new component

        )
    }
}
export default withRouter(Listing)

Comment: Have a look at https://nextjs.org/docs/routing/dynamic-routes.
Answer: Inside the route directory you can import and export the component from another directory.
Inside your second route /myPage2/index.js :
import MyPage from ../myPage.js
export default MyPage

Comment: I would like to know how to do it when we have dynamic routes
Answer: You can create a page with optional parameters.
pages
 ┣ tasks
 ┃ ┣ manage
 ┃ ┃ ┗ [[...id]].jsx
 ┃ ┣ index.jsx
 ┃ ┗ service.js
 ┣ _app.jsx
 ┣ dashboard.jsx
 ┣ index.jsx
 ┗ login.jsx

/tasks/manage and tasks/manage/14 will route the same component [[...id]].jsx

Do not forget to use  double brackets and three dots.
[[...foo]].jsx

Catch all routes can be made optional by including the parameter in
double brackets ([[...slug]]).
For example, pages/post/[[...slug]].js will match /post, /post/a,
/post/a/b, and so on.

Please check for more info.
Answer: NextResponse.rewrite is one way to reuse components among different routes.
This feature allows us to map a route to another. It retains parameters from the requested route for use in the resolved route as well.
Your example has two routes:
/new
/edit-[id]
Including the rewrites function in next.config.js as below will route requests from /edit-[id] to /new and will populate the router.query.id parameter as expected. We don't even need to define @/pages/edit-[id].jsx
// next.config.js

module.exports = {
  ...other next config parameters...
  async rewrites() {
    return [
      {
        source: "/edit-:id",
        destination: "/new"
      }
    ]
  }
}

// @pages/new.jsx
// the configuration above means this component will be used as though @pages/edit-[id].jsx uses this same file.
import { NextRouter, withRouter } from 'next/router'
import { NextResponse } from 'next/server'
import React from 'react'

class EditForm extends React.Component {
    constructor(props){
        super(props)
    }
    render () {

        const id = this.props.router.query.id ?? "empty"
        return (

path id param: {id}

        )
    }
}

export default withRouter(EditForm)

// files
/pages/new.jsx
/next.config.js

Usage

Empty form, no id provided
localhost/new

path id param: no id

Populated for, with an id
localhost/edit-something

path id param: something


Give an integer where the class modulo 840 is an element of maximum order of (840Z)^x

Question: I started the question by proving that (840Z)× is isomorphic to (2Z)4 × 3Z × 4Z.
Then I found that the maximum value of order of the elements in (840Z)^× is 12.
How do I proceed from here ? Any help is very appreciated.
Comment: $$840=2^3\cdot3\cdot5\cdot7\;$$ ...
Answer: One way to do it is to ask that it be congruent to $2\bmod 5$ and to be congruent to $2\bmod 7$. Then in order for $2^a$ to be $1\bmod 5$ and $1\bmod 7$ we need for $a$ to be a multiple of $4$ and $3$.
A good example of such a number is $2$. By the way good job doing the previous part, I think that was the hardest.


Função do Moq no teste do controller

Question: Depois de algumas horas tentando, eu cheguei a este código de teste, mas ainda não consegui entender bem a função do Mock, sendo que, sem ele funciona do mesmo jeito.
Obs. A intenção é aprender TDD com Moq...
---- Controller
private List<Compras> _comprasList;

public ComprasController(List<Compras> comprasList)
{
    _comprasList = comprasList;
}

[HttpGet]
public ActionResult GetAll()
{
    return _comprasList.ToList();
}

--- Test
private ComprasController _controller;
private Mock<List<Compras>> _listCompras;

public TestControllerCompras()
{
    _listCompras= new Mock<List<Compras>>();
    _controller = new ComprasController (_listCompras.Object);
}

[Fact]
public void Test_Get()
{
    //Arrang
    var compras = new List<Compras>
    {
        new Compras(){Id = 1, Produto = "produto1"},
        new Compras(){Id = 2, Produto = "produto2"},
        new Compras(){Id = 3, Produto = "produto3"},
        new Compras(){Id = 4, Produto = "produto4"}
    };

    _listCompras.Object.AddRange(compras);
    //Act
    var resul = _controller.GetAll();

    //Assert
    Assert.IsAssignableFrom<ActionResult<List<Compras>>>(resul);

}

Comment: Se você escreveu o teste depois do código real não está aprendendo TDD. De que `Mock` está falando?
Comment: A unica coisa que eu criei foi uma classe e um controller só com o Get msm. Estou usando o Moq4. O teste seria antes mesmo da classe e do Controller?
Comment: Não sei bem o que está tentando fazer, mas não parece que precisa *mockar* alguma coisa aí.
Comment: Acho que fiz coisa errada então.... Se quiser fechar a pergunta, sem problemas... Vou tentar entender os testes antes de entrar no Moq.
Answer: O framework Moq tem como objetivo simular o banco de dados para que você não precise necessariamente acessar o banco para testar suas regras de negócio. Sendo assim, não faz muito sentido utilizar o Moq nessa lista. O que você pode fazer, é criar um repositório Compras e utilizar a injeção de dependência no Moq, para que você possa injetar a dependência do repositório Compras e simular dados para testar o seu serviço. Ficaria algo mais ou menos assim:
[TestClass]
public class ComprasServiceTest()
{
    private ComprasService GetService()
    {
        var service = new ComprasService();
        service.IComprasRepository = new Mock<IComprasRepository>().Objetct();
    }
}

[Fact]
public void Test_Get()
{

    var service = GetService();

    var comprasList = new List<Compras>()
    {
        new Compras { Id = 1, Produto =  "Produto" },
        new Compras { Id = 2, Produto =  "Produto2"}
    };

    //Arrange
    var mockComprasRepo = new Mock<IComprasRepository>();
    mockComprasRepo.Setup(x=> x.ListAll()).Returns(comprasList)

service.IComprasRepository= new Lazy<IComprasRepository>(() => mockComprasRepo .Object);

    //Act
    var result = service.SeuMetodoTeste();

    // Assert
    Assert.IsNotNull(result);

}

Acima é um exemplo bem simples pra você entender um pouco como realizar seu teste e utilizar o Moq, você simula os dados com o Moq para seu método de serviço ser testado e chamar o repositório, isso seria o conceito de camadas. Você testa as regras de negócios da sua aplicação que fica no serviço e chama o repositório.
Um outro adendo é, eu utilizo muito os testes unitários para testar meus serviços as regras de negócios, até da pra você testar seu controller, confesso que nunca testei mas sei que é um pouco trabalhoso, mas ai vai muito do seu propósito de teste.
Pode olhar nesse projeto de teste https://github.com/JessicaNathany/unit-test
pra ter como referência e entender o funcionamento do Moq e os testes unitários, acho que pode ajudar. :)
Answer: Não entendi porque retornar a _comprasList com .ToList() se ja é uma lista, e ali não tem nenhum action result também.
Quando você faz Mock de algo, você está dizendo o que aquilo representa sem entrar realmente no objeto, normalmente utilizamos Mocks para evitar entrar em métodos do repository por exemplo, mas isso também funciona com uma service e afins.
Não vejo muito sentido em Mockar essa lista, mas você pode fazer um _comprasList.Setup() e explorar as opções.

Função do Moq no teste do controller


Compute $\int_0^1\frac{\ln^2(1+x)\operatorname{Li}_2(-x)}{x}dx$

Question: How to prove

$$\int_0^1\frac{\ln^2(1+x)\operatorname{Li}_2(-x)}{x}dx=4\operatorname{Li}_5\left(\frac12\right)+4\ln2\operatorname{Li}_4\left(\frac12\right)-\frac{125}{32}\zeta(5)-\frac{1}{8}\zeta(2)\zeta(3)\\+\frac{7}{4}\ln^22\zeta(3)-\frac2{3}\ln^32\zeta(2)+\frac{2}{15}\ln^52$$

This integral was nicely computed by Cornel here in page $5$ using tricky manipulation.
Another form of the integral, after subbing and applying integration by parts is
$$\int_0^1\frac{\ln^2(1-x)\operatorname{Li}_2(x/2)}{x}dx$$
My question is how to evaluate any of these integrals in a different way?
Thanks
Comment: \begin{align}\int_0^1\frac{\ln^2(1+x)\operatorname{Li}_2(-x)}{x}dx&=\frac{1}{2}\int_0^1\frac{\left(\operatorname{Li}_2(-x)\right)^2}{1+x}dx-\frac{1}{8}\zeta(2)^2\ln 2\end{align}
Comment: Then what? You just applied IBP I dont see any progress ?
Comment: That's the reason i have posted it as a comment. This formula is nice for me.
Comment: I see , I thought you had an idea.
Comment: Do you like this one? I hope it's not obvious. \begin{align}\int_0^1\frac{\ln^2(1+x)\operatorname{Li}_2(-x)}{x}dx=-\int_0^1\frac{\operatorname{Li}_2\left(\frac{x}{1+x}\right)\ln^2(1+x)}{x}\,dx-\frac{1}{2}\int_0^1 \frac{\ln^4(1+x)}{x}\,dx\end{align}
Answer: Finally I got the idea:
Starting with $\frac{1}{1+x}\mapsto x$ then using Landens identity $\operatorname{Li}_2\left(\frac{x-1}{x}\right)=-\frac12\ln^2x-\operatorname{Li}_2(1-x)$ we obtain
$$\mathcal{I}=\int_0^1\frac{\ln^2(1+x)\operatorname{Li}_2(-x)}{x}dx=\int_{1/2}^1\frac{\ln^2x\operatorname{Li}_2\left(\frac{x-1}{x}\right)}{x(1-x)}dx$$
$$=-\frac12\underbrace{\int_{1/2}^1\frac{\ln^4x}{x(1-x)}dx}_{\mathcal{\large J}}-\underbrace{\int_{1/2}^1\frac{\ln^2x\operatorname{Li}_2(1-x)}{x}dx}_{ IBP}-\underbrace{\int_{1/2}^1\frac{\ln^2x\operatorname{Li}_2(1-x)}{1-x}dx}_{ IBP}$$
$$\text{Note for the third integral that} \int\frac{\ln x}{1-x}dx=\operatorname{Li}_2(1-x)$$
$$=-\frac12\mathcal{J}-\frac13\ln^32\operatorname{Li}_2(1/2)+\frac13\underbrace{\int_{1/2}^1\frac{\ln^4x}{1-x}dx}_{\frac1{1-x}=\frac1{x(1-x)}-\frac1x}-\frac12\ln2\operatorname{Li}_2^2(1/2)+\frac12\underbrace{\int_{1/2}^1\frac{\operatorname{Li}_2^2(1-x)}{x}dx}_{\mathcal{\large K}}$$
and the integral simplifies into

$$\mathcal{I}=\frac12\mathcal{K}-\frac16\mathcal{J}+\frac1{12}\ln^32\zeta(2)-\frac5{16}\ln2\zeta(4)-\frac1{40}\ln^52$$

where we substituted $\operatorname{Li}_2(1/2)=\frac12\zeta(2)-\frac12\ln^22$

The integral $\mathcal{J}$ is classical and can be done using the generalization
$$(-1)^n\int_{1/2}^1\frac{\ln^nx}{x(1-x)}dx=\frac{\ln^{n+1}(2)}{n+1}+n!\zeta(n+1)+\sum_{k=0}^n k!{n\choose k}\ln^{n-k}(2)\operatorname{Li}_{k+1}\left(\frac12\right)$$
so
$$\boxed{\mathcal{J}=24\zeta(5)-\frac{21}2\ln^22\zeta(3)+4\ln^32\zeta(2)-\frac45\ln^52-24\ln2\operatorname{Li}_4\left(\frac12\right)-24\operatorname{Li}_5\left(\frac12\right)}$$
where we substituted $\operatorname{Li}_3(1/2)=\frac78\zeta(3)-\frac12\ln2\zeta(2)+\frac16\ln^32$
For the integral $\mathcal{K}$, we can just use the dilogarithm reflection formula: $$\operatorname{Li}_2(1-x)=\zeta(2)-\ln x\ln(1-x)-\operatorname{Li}_2(x)$$
upon expanding $\operatorname{Li}_2^2(1-x)$ we get
$$\mathcal{K}=\underbrace{\int_{1/2}^1\frac{\zeta^2(2)-2\zeta(2)\operatorname{Li}_2(x)}{x}dx}_{\mathcal{\large {K_1}}}-2\zeta(2)\underbrace{\int_{1/2}^1\frac{\ln x\ln(1-x)}{x}dx}_{\mathcal{\large {K_2}}}+\underbrace{\int_{1/2}^1\frac{\ln^2x\ln^2(1-x)}{x}dx}_{\mathcal{\large {K_3}}}\\+2\underbrace{\int_{1/2}^1\frac{\ln x\ln(1-x)\operatorname{Li}_2(x)}{x}dx}_{\mathcal{\large {K_4}}}+\underbrace{\int_{1/2}^1\frac{\operatorname{Li}_2^2(x)}{x}dx}_{\mathcal{\large {K_5}}}$$
$$\mathcal{K_1}=\frac52\ln2\zeta(4)-2\zeta(2)[\zeta(3)-\operatorname{Li}_3(1/2)]$$
$$\boxed{\mathcal{K_1}=\frac13\ln^32\zeta(2)-\frac14\zeta(2)\zeta(3)}$$
$$\mathcal{K_2}\overset{IBP}{=}-\ln2\operatorname{Li}_2(1/2)+\int_{1/2}^1\frac{\operatorname{Li}_2(x)}{x}dx$$
$$=-\ln2\operatorname{Li}_2(1/2)+\zeta(3)-\operatorname{Li}_3(1/2)$$
$$\boxed{\mathcal{K_2}=\frac18\zeta(3)+\frac13\ln^32}$$
$$\mathcal{K_3}=\int_0^{1/2}\frac{\ln^2x\ln^2(1-x)}{x}dx\overset{IBP}{=}\frac23{\int_{0}^{1/2}\frac{\ln^3x\ln(1-x)}{1-x}}dx=\frac23\color{blue}{\int_{1/2}^1\frac{\ln^3(1-x)\ln x}{x}dx}$$
I proved in this solution
$$\color{blue}{\int_{1/2}^1\frac{\ln^3(1-x)\ln x}{x}\ dx}=\frac3{16}\zeta(5)+\frac3{20}\ln^52-\frac14\int_{1/2}^1\frac{\ln^4x}{1-x}\ dx+\frac12\int_0^1\frac{\ln^3(1-x)\ln x}{x}\ dx$$
where
$$\int_{1/2}^1\frac{\ln^4x}{1-x}=\mathcal{J}-\int_{1/2}^1\frac{\ln^4x}{x}dx$$
$$=24\zeta(5)-\frac{21}2\ln^22\zeta(3)+4\ln^32\zeta(2)-\ln^52-24\ln2\operatorname{Li}_4\left(\frac12\right)-24\operatorname{Li}_5\left(\frac12\right)$$
and
$$\int_0^1\frac{\ln^3(1-x)\ln x}{x}\ dx=\int_0^1\frac{\ln^3x\ln(1-x)}{1-x}\ dx=-\sum_{n=1}^\infty H_n\int_0^1x^n\ln^3x=6\sum_{n=1}^\infty\frac{H_n}{(n+1)^4}$$
$$=6\sum_{n=1}^\infty\frac{H_n}{n^4}-6\zeta(5)=6\left(3\zeta(5)-\zeta(2)\zeta(3)\right)-6\zeta(5)=12\zeta(5)-6\zeta(2)\zeta(3)$$
combine the two integrals to get
$$\color{blue}{\int_{1/2}^1\frac{\ln^3(1-x)\ln x}{x}\ dx}\\=\frac3{16}\zeta(5)-3\zeta(2)\zeta(3)+\frac{21}8\ln^22\zeta(3)-\ln^32\zeta(2)+\frac25\ln^52+6\ln2\operatorname{Li}_4\left(\frac12\right)+6\operatorname{Li}_5\left(\frac12\right)$$
which gives
$$\boxed{\mathcal{K_3}=\frac1{8}\zeta(5)-2\zeta(2)\zeta(3)+\frac{7}4\ln^22\zeta(3)-\frac23\ln^32\zeta(2)+\frac4{15}\ln^52+4\ln2\operatorname{Li}_4\left(\frac12\right)+4\operatorname{Li}_5\left(\frac12\right)}$$
$$\mathcal{K_4}\overset{IBP}{=}-\frac12\ln2\operatorname{Li}_2^2(1/2)+\frac12\underbrace{\int_{1/2}^1\frac{\operatorname{Li}_2^2(x)}{x}dx}_{\mathcal{\large{K_5}}}$$
so
$$2\mathcal{K_4}+\mathcal{K_5}=-\ln2\operatorname{Li}_2^2(1/2)+2\int_{1/2}^1\frac{\operatorname{Li}_2^2(x)}{x}dx$$
where
$$\int_{1/2}^1\frac{\operatorname{Li}_2^2(x)}{x}dx=\int_0^{1}\frac{\operatorname{Li}_2^2(x)}{x}dx-\int_0^{1/2}\frac{\operatorname{Li}_2^2(x)}{x}dx$$
we have
$$\int_0^{1}\frac{\operatorname{Li}_2^2(x)}{x}dx=\sum_{n=1}^\infty\frac1{n^2}\int_0^1 x^{n-1}\operatorname{Li}_2(x)dx=\sum_{n=1}^\infty\frac1{n^2}\left(\frac{\zeta(2)}{n}-\frac{H_n}{n^2}\right)$$
$$=\zeta(2)\zeta(3)-\sum_{n=1}^\infty\frac{H_n}{n^4}=2\zeta(2)\zeta(3)-3\zeta(5)$$
and @Song proved here
$$\int_0^{1/2}\frac{\operatorname{Li}_2^2(x)}{x}dx=\frac12\ln^32\zeta(2)-\frac78\ln^22\zeta(3)-\frac58\ln2\zeta(4)+\frac{27}{32}\zeta(5)+\frac78\zeta(2)\zeta(3)\\-\frac{7}{60}\ln^52-2\ln2\operatorname{Li}_4\left(\frac12\right)-2\operatorname{Li}_5\left(\frac12\right)$$
giving us
$$\int_{1/2}^1\frac{\operatorname{Li}_2^2(x)}{x}dx=-\frac12\ln^32\zeta(2)+\frac78\ln^22\zeta(3)+\frac58\ln2\zeta(4)-\frac{123}{32}\zeta(5)+\frac98\zeta(2)\zeta(3)\\+\frac{7}{60}\ln^52+2\ln2\operatorname{Li}_4\left(\frac12\right)+2\operatorname{Li}_5\left(\frac12\right)$$
consequently
$$\boxed{2\mathcal{K_4}+\mathcal{K_5}=-\frac12\ln^32\zeta(2)+\frac74\ln^22\zeta(3)+\frac{5}8\ln2\zeta(4)-\frac{123}{16}\zeta(5)+\frac94\zeta(2)\zeta(3)\\ \qquad\qquad\qquad-\frac{1}{60}\ln^52+4\ln2\operatorname{Li}_4\left(\frac12\right)+4\operatorname{Li}_5\left(\frac12\right)}$$
Finally combine the boxed results we obtain

$$\small{\mathcal{I}=4\operatorname{Li}_5\left(\frac12\right)+4\ln2\operatorname{Li}_4\left(\frac12\right)-\frac{125}{32}\zeta(5)-\frac{1}{8}\zeta(2)\zeta(3)+\frac{7}{4}\ln^22\zeta(3)-\frac2{3}\ln^32\zeta(2)+\frac{2}{15}\ln^52}$$
Comment: $-\int_{1/2}^1\frac{\ln^2x\operatorname{Li}_2(1-x)}{1-x}dx$ can computed using $\int_{1/2}^1 \frac{(\operatorname{Li}_2(x))^2}{x}dx$ the other is the sister of your "first integral".
Comment: Yes this integral appeared along with other hard integrals but i did them all. I will complete my solution soon
Answer: Incomplete solution is following,
\begin{align}
J&=\int_0^1\frac{\ln^2(1+x)\operatorname{Li}_2(-x)}{x}dx\\
&=-\int_0^1 \int_0^1\frac{\ln(1+tx)\ln^2(1+x)}{tx}\,dt\,dx\\
&\overset{u=\frac{1-t}{1+tx}}=-\int_0^1 \int_0^1 \frac{(1+x)\ln^2(1+x)\ln\left(\frac{1+x}{1+ux}\right)}{x(1-u)(1+ux)}\,du\,dx\\
&=-\int_0^1 \frac{(1+x)\ln^2(1+x)}{x}\left(\int_0^1\frac{x\ln\left(\frac{1+x}{1+ux}\right)}{(1+x)(1+ux)}+\frac{\ln\left(\frac{1+x}{1+ux}\right)}{(1-u)(1+x)}\,du\right)dx\\
&=\frac{1}{2}\int_0^1 \frac{(1+x)\ln^2(1+x)}{x}\left[\frac{\ln^2 \left(\frac{1+x}{1+ux}\right)}{1+x}\right]_{u=0}^{u=1} dx-\int_0^1\int_0^1 \frac{\ln^2(1+x)\ln\left(\frac{1+x}{1+ux}\right)}{x(1-u)}dudx\\
&=-\frac{1}{2}\int_0^1 \frac{\ln^4(1+x)}{x}\,dx-\int_0^1\int_0^1 \frac{\ln^2(1+x)\ln\left(\frac{1+x}{1+ux}\right)}{x(1-u)}dudx\\
\end{align}
Let $0<\alpha<1$,
\begin{align}
A(\alpha)&=\int_0^1\frac{\ln^2(1+x)}{x}\left(\int_0^\alpha \frac{\ln\left(\frac{1+x}{1+ux}\right)}{1-u}du\right)dx\\
&=-\ln\left(1-\alpha\right)\left(\int_0^1 \frac{\ln^3(1+x)}{x}\,dx\right)-\int_0^1 \frac{\ln^2(1+x)}{x}\left(\int_0^{\alpha}\frac{\ln(1+ux)}{1-u}du\right)dx\\
&=-\ln\left(1-\alpha\right)\left(\int_0^1 \frac{\ln^3(1+x)}{x}\,dx\right)+\\
&\int_0^1 \frac{\ln^2(1+x)}{x}\left[\ln(1+ux)\ln\left(\frac{(1-u)x}{1+x}\right)+\operatorname{Li}_2\left(\frac{1+ux}{1+x}\right)\right]_{u=0}^{u=\alpha}\,dx\\
&=\ln(1-\alpha)\int_0^1 \frac{\ln^2(1+x)\ln\left(\frac{1+\alpha x}{1+x}\right)}{x}\,dx-\int_0^1 \frac{\ln^3(1+x)\ln(1+\alpha x)}{x}\,dx+\\
&\int_0^1 \frac{\ln^2(1+x)\ln(1+ux)\ln x}{x}\,dx+\int_0^1 \frac{\ln^2(1+x)\left(\operatorname{Li}_2\left(\frac{1+\alpha x}{1+x}\right)-\operatorname{Li}_2(1)\right)}{x}\,dx\\
\end{align}
Therefore,
\begin{align}
&\int_0^1\int_0^1 \frac{\ln^2(1+x)\ln\left(\frac{1+x}{1+ux}\right)}{x(1-u)}dudx\\
&=\lim_{\alpha \rightarrow 1}J(\alpha)\\
&=\int_0^1 \frac{\ln^3(1+x)\ln\left(\frac{x}{1+x}\right)}{x}\,dx-\int_0^1 \frac{\ln^2(1+x)\left(\operatorname{Li}_2\left(\frac{1}{1+x}\right)-\operatorname{Li}_2(1)\right)}{x}\,dx\\
R&=\int_0^1 \frac{\ln^2(1+x)\left(\operatorname{Li}_2\left(\frac{1}{1+x}\right)-\operatorname{Li}_2(1)\right)}{x}\,dx\\
&\overset{y=\frac{1}{1+x}}=\int_{\frac{1}{2}}^1 \frac{\ln^2 x\big(\operatorname{Li}_2\left(x\right)-\operatorname{Li}_2(1)\big)}{x(1-x)}\,dx\\
&=\int_{\frac{1}{2}}^1 \frac{\ln^2 x\big(\operatorname{Li}_2\left(x\right)-\operatorname{Li}_2(1)\big)}{x}\,dx+\int_{\frac{1}{2}}^1 \frac{\ln^2 x\big(\operatorname{Li}_2\left(x\right)-\operatorname{Li}_2(1)\big)}{1-x}\,dx\\
&\overset{\text{IBP}}=\frac{1}{3}\ln^3 2\left(\operatorname{Li}_2\left(\frac{1}{2}\right)-\operatorname{Li}_2(1)\right)+\frac{1}{3}\int_{\frac{1}{2}}^1 \frac{\ln^3 x\ln(1-x)}{x}\,dx+\\
&\int_{\frac{1}{2}}^1 \frac{\ln^2 x\big(\operatorname{Li}_2\left(x\right)-\operatorname{Li}_2(1)\big)}{1-x}\,dx\\
&\overset{\text{IBP}}=\frac{1}{3}\ln^3 2\left(\operatorname{Li}_2\left(\frac{1}{2}\right)-\operatorname{Li}_2(1)\right)+\frac{1}{3}\int_{\frac{1}{2}}^1 \frac{\ln^3 x\ln(1-x)}{x}\,dx+\\
&\left[\left(\int_0^x \frac{\ln^2 t}{1-t}\,dt\right)\left(\operatorname{Li}_2\left(x\right)-\operatorname{Li}_2(1)\right)\right]_{\frac{1}{2}}^1+\\&\int_{\frac{1}{2}}^1 \left(-\ln(1-x)\ln^2 x+2\int_0^x \frac{\ln (1-t)\ln t}{t}\,dt\right)\frac{\ln(1-x)}{x}\,dx\\
&=\left(\frac{1}{3}\ln^3 2-\left(\int_0^{\frac{1}{2}} \frac{\ln^2 t}{1-t}\,dt\right)\right)\left(\operatorname{Li}_2\left(\frac{1}{2}\right)-\operatorname{Li}_2(1)\right)+\frac{1}{3}\int_{\frac{1}{2}}^1 \frac{\ln^3 x\ln(1-x)}{x}\,dx-\\
&\int_{\frac{1}{2}}^1 \frac{\ln^2 x\ln^2(1-x)}{x}\,dx+2\int_{\frac{1}{2}}^1 \frac{\ln(1-x)}{x}\left(\int_0^x\frac{\ln (1-t)\ln t}{t}\,dt\right)\,dx\\
&\overset{\text{IBP}}=\left(\frac{1}{3}\ln^3 2-\left(\int_0^{\frac{1}{2}} \frac{\ln^2 t}{1-t}\,dt\right)\right)\left(\operatorname{Li}_2\left(\frac{1}{2}\right)-\operatorname{Li}_2(1)\right)+\frac{1}{3}\int_{\frac{1}{2}}^1 \frac{\ln^3 x\ln(1-x)}{x}\,dx-\\
&\int_{\frac{1}{2}}^1 \frac{\ln^2 x\ln^2(1-x)}{x}\,dx+2\left[-\operatorname{Li}_2(x)\left(\int_0^x\frac{\ln (1-t)\ln t}{t}\,dt\right)\right]_{\frac{1}{2}}^1+\\
&2\int_0^{\frac{1}{2}} \frac{\operatorname{Li}_2(x)\ln (1-x)\ln x}{x}\,dx\\
&=\left(\frac{1}{3}\ln^3 2-\left(\int_0^{\frac{1}{2}} \frac{\ln^2 t}{1-t}\,dt\right)\right)\left(\operatorname{Li}_2\left(\frac{1}{2}\right)-\operatorname{Li}_2(1)\right)+\frac{1}{3}\int_{\frac{1}{2}}^1 \frac{\ln^3 x\ln(1-x)}{x}\,dx-\\
&\int_{\frac{1}{2}}^1 \frac{\ln^2 x\ln^2(1-x)}{x}\,dx+2\operatorname{Li}_2\left(\frac{1}{2}\right)\left(\int_0^{\frac{1}{2}}\frac{\ln (1-t)\ln t}{t}\,dt\right)-\\
&2\operatorname{Li}_2\left(1\right)\left(\int_0^{1}\frac{\ln (1-t)\ln t}{t}\,dt\right)+2\int_{\frac{1}{2}}^1 \frac{\operatorname{Li}_2(x)\ln (1-x)\ln x}{x}\,dx\\
\end{align}
Since,
\begin{align}
\frac{\partial}{\partial x}\left(\operatorname{Li}_2(x)\right)^2&=-2\operatorname{Li}_2(x)\frac{\ln(1-x)}{x}
\end{align}
then,
\begin{align}
R&\overset{\text{IBP}}=\left(\frac{1}{3}\ln^3 2-\left(\int_0^{\frac{1}{2}} \frac{\ln^2 t}{1-t}\,dt\right)\right)\left(\operatorname{Li}_2\left(\frac{1}{2}\right)-\operatorname{Li}_2(1)\right)+\frac{1}{3}\int_{\frac{1}{2}}^1 \frac{\ln^3 x\ln(1-x)}{x}\,dx-\\
&\int_{\frac{1}{2}}^1 \frac{\ln^2 x\ln^2(1-x)}{x}\,dx+2\operatorname{Li}_2\left(\frac{1}{2}\right)\left(\int_0^{\frac{1}{2}}\frac{\ln (1-t)\ln t}{t}\,dt\right)-\\
&2\operatorname{Li}_2\left(1\right)\left(\int_0^{1}\frac{\ln (1-t)\ln t}{t}\,dt\right)-\left(\operatorname{Li}_2\left(\frac{1}{2}\right)\right)^2\ln 2+ \int_{\frac{1}{2}}^1 \frac{\left(\operatorname{Li}_2(x)\right)^2}{x}\,dx\\
\end{align}
Therefore,
\begin{align}
J&=-\frac{1}{2}\int_0^1 \frac{\ln^4(1+x)}{x}\,dx-\int_0^1 \frac{\ln^3(1+x)\ln\left(\frac{x}{1+x}\right)}{x}\,dx+\\
&\left(\frac{1}{3}\ln^3 2-\left(\int_0^{\frac{1}{2}} \frac{\ln^2 t}{1-t}\,dt\right)\right)\left(\operatorname{Li}_2\left(\frac{1}{2}\right)-\operatorname{Li}_2(1)\right)+\frac{1}{3}\int_{\frac{1}{2}}^1 \frac{\ln^3 x\ln(1-x)}{x}\,dx-\\
&\int_{\frac{1}{2}}^1 \frac{\ln^2 x\ln^2(1-x)}{x}\,dx+2\operatorname{Li}_2\left(\frac{1}{2}\right)\left(\int_0^{\frac{1}{2}}\frac{\ln (1-t)\ln t}{t}\,dt\right)-\\
&2\operatorname{Li}_2\left(1\right)\left(\int_0^{1}\frac{\ln (1-t)\ln t}{t}\,dt\right)-\left(\operatorname{Li}_2\left(\frac{1}{2}\right)\right)^2\ln 2+ \int_{\frac{1}{2}}^1 \frac{\left(\operatorname{Li}_2(x)\right)^2}{x}\,dx
\end{align}
For the very last integral see:
Compute $\int_0^{1/2}\frac{\left(\operatorname{Li}_2(x)\right)^2}{x}dx$
Definite Dilogarithm integral $\int^1_0 \frac{\operatorname{Li}_2^2(x)}{x}\, dx $
Addendum:
See How to find ${\large\int}_0^1\frac{\ln^3(1+x)\ln x}x\mathrm dx$
Comment: Very nice (+1) i appreciate your efforts. all these sub integrals at the end are manageable but $\int_0^1\frac{\ln^3(1+x)\ln\left(\frac{x}{1+x}\right)}{x}dx$ but i will give it a try.
Comment: $\displaystyle \int_0^1\frac{\ln^3(1+x)\ln x}{x}dx$ is the problem here. Equivalently $\displaystyle \int_0^1\frac{\ln^2(1+x)\ln^2 x}{1+x}dx$
Comment: ah i missed that. so your solution is complete why you mentioned its not?
Comment: I haven't computed most of the integrals at the end. For now, i think one of these integrals could be not straightforward to compute. That's $\displaystyle \int_0^1\frac{\ln^3(1+x)\ln x}{x}dx$
Comment: Actually you have computed it: https://math.stackexchange.com/questions/908108/how-to-find-large-int-01-frac-ln31x-ln-xx-mathrm-dx/3329621#3329621


write/read float array in java fast way

Question: I am trying to write and read float array(pretty large actually, 640*480) in android devices with java codes.
like this one
    DataOutputStream out = ...;
for (int i=0; i<floatarray.length; ++i)
    out.writeFloat(floatarray[i]);

is very slow and I have try it in this.
WRITE:
            float[] test=new float[3];
        test[0]=1.0f;
        test[1]=1.2f;
        test[2]=1.5f;
        //long timeBeforeWrite = System.nanoTime();
        try {
            BufferedOutputStream  dataOut = new BufferedOutputStream (
                    new FileOutputStream("/sdcard/DCIM/Camera/Dual/demo.bin"));

            byte buf[]=new byte[4*test.length];

            long timeBeforeWrite = System.nanoTime();

            for (int i=0; i<test.length; ++i)
            {
                int val = Float.floatToRawIntBits(test[i]);
                buf[4 * i] = (byte) (val >> 24);
                buf[4 * i + 1] = (byte) (val >> 16) ;
                buf[4 * i + 2] = (byte) (val >> 8);
                buf[4 * i + 3] = (byte) (val);
            }

            dataOut.write(buf);

            long ct_write = System.nanoTime();
            long offset_write = ct_write - timeBeforeWrite;
            float mOffsetInMs_write = (float)(offset_write)/1000000;
            Log.e("ETA", "write float[]  " + Float.toString(mOffsetInMs_write));

            dataOut.flush();
            dataOut.close();
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }

READ:
            float[] read=new float[3];

        try{
            BufferedInputStream  dataIn=new BufferedInputStream (new FileInputStream("/sdcard/DCIM/Camera/Dual/demo.txt"));
            byte buf[]=new byte[4*read.length];
            long timeBeforeWrite = System.nanoTime();

            dataIn.read(buf);

            for (int i=0; i<read.length; ++i)
            {
                    int val;
val = buf[4 * i] << 24;
                    val += buf[4 * i + 1] << 16;
                    val += buf[4 * i + 2] << 8;
                    val += buf[4 * i + 3];

                read[i]=Float.valueOf(Integer.toBinaryString(val));

                //int val = Float.floatToRawIntBits(disparityMap[i]);

            }

            long ct_write = System.nanoTime();
            long offset_write = ct_write - timeBeforeWrite;
            float mOffsetInMs_write = (float)(offset_write)/1000000;
            Log.e("ETA", "read float[]  " + Float.toString(mOffsetInMs_write));

            dataIn.close();

        }catch (IOException ex) {
            System.err.println(ex.getMessage());
        }

things read back is pretty strange floating point values, and what's wrong with this?BTW, read back runs pretty slow, don't know why.
 Or any other good idea for fast read/write float array?
Thanks!
//Thanks to Larry, I have try bytebuffer.asfloatbuffer() ways like:
//WRITE
    float[] test = new float[3];
    test[0]=1.1f;
    test[1]=1.2f;
    test[2]=1.5f;
    try{
        RandomAccessFile aFile = new RandomAccessFile("/sdcard/demo.data", "rw");
        FileChannel outChannel = aFile.getChannel();

        //one float 3 bytes
        ByteBuffer buf = ByteBuffer.allocate(12);
        buf.clear();
        buf.asFloatBuffer().put(test);

        //while(buf.hasRemaining())
        {
            outChannel.write(buf);
        }

        outChannel.close();

    }
    catch (IOException ex) {
        System.err.println(ex.getMessage());
    }

    //READ
    float[] readback=new float[3];
    try{

        RandomAccessFile rFile = new RandomAccessFile("/sdcard/demo.data", "rw");
        FileChannel inChannel = rFile.getChannel();
        ByteBuffer buf_in = ByteBuffer.allocate(12);
        buf_in.clear();

        inChannel.read(buf_in);

        buf_in.asFloatBuffer().get(readback);

        inChannel.close();

    }
    catch (IOException ex) {
        System.err.println(ex.getMessage());
    }

and the program crashes in buf_in.asFloatBuffer().get(readback);
any idea and is there goods ways to goes in and debug inside in java, Sorry completely new in java world. Thanks again
Comment: I've the same problem as you... "buf_in.asFloatBuffer().get(readback);" crashes... Have you solved the problem?
Comment: The problem missing here is that the position of the buffer is wrong. You need to call position(0) on it.
Answer: Thanks to Larry, I am just sharing my codes and hopefully it helps someone else.
I just figure it out, we need to rewind to buffers after read/write to file channels. following codes just works, and runs pretty fast.
float[] disparity=new float[640*480];

    disparity[1]=1.5f;
    disparity[2]=4.566f;

//WRITE
    try{
        RandomAccessFile aFile = new RandomAccessFile("/sdcard/demo.data", "rw");
        FileChannel outChannel = aFile.getChannel();

        //one float 4 bytes
        ByteBuffer buf = ByteBuffer.allocate(4*640*480);
        buf.clear();
        buf.asFloatBuffer().put(disparity);

        //while(buf.hasRemaining())
        {
            outChannel.write(buf);
        }

        //outChannel.close();
        buf.rewind();

        float[] out=new float[3];
        buf.asFloatBuffer().get(out);

        outChannel.close();

    }
    catch (IOException ex) {
        System.err.println(ex.getMessage());
    }

    //READ
    float[] readback=new float[640*480];
    try{

        RandomAccessFile rFile = new RandomAccessFile("/sdcard/demo.data", "rw");
        FileChannel inChannel = rFile.getChannel();
        ByteBuffer buf_in = ByteBuffer.allocate(640*480*4);
        buf_in.clear();

        inChannel.read(buf_in);

        buf_in.rewind();
        buf_in.asFloatBuffer().get(readback);

        inChannel.close();

    }
    catch (IOException ex) {
        System.err.println(ex.getMessage());
    }

Thanks again.
Comment: You must close the file in a `finally` block or use `try-with-resources`! You are correct about rewinding during read, but not during write. I suggest you do: `try (ByteChannel channel = Files.newByteChannel( path, WRITE, CREATE, TRUNCATE_EXISTING )) { ByteBuffer buf = ByteBuffer.allocate(disparity.length * 4); buf.asFloatBuffer().put(disparity); channel.write (buf); }`
Answer: Try using FileChannel for your file access and a ByteBuffer for the data.  You can put the data into the ByteBuffer using the ByteBuffer.putFloat() methods and write it out with FileChannel.write().  When you read it back, you can call FileChannel.read() to get a ByteBuffer representing the data, then call ByteBuffer.asFloatBuffer() to get a FloatBuffer representing the data which can then be used to get a float[].
Comment: thanks a lot and I have update my problems, read back is not working in buf_in.asFloatBuffer().get(readback); any ideas about this?
Answer: Just add a BufferedOutputStream between your DataOutputStream and your FileOutputStream.

write/read float array in java fast way


Is there a way to Remote Desktop to a local session in Server 2008, without being restricted to a single session?

Question: The usability of the /console and /admin switches for Remote Desktop sessions has been removed after Windows XP/2003.  Microsoft claims that the functionality of connecting to a local session in newer versions of Windows should be enabled by restricting users to a single session.

Because the physical console session is never session 0, you can always reconnect to your existing session on the physical console. The Restrict Terminal Services users to a single remote session Group Policy setting determines whether you can connect to your existing physical console session. This setting is available in the Computer Configuration\Administrative Templates\Windows Components\Terminal Services\Terminal Server\Connections node of the Local Group Policy Editor. You can also configure this setting in Terminal Services Configuration. The Restrict each user to a single session setting appears in Edit settings in the General section.
  http://support.microsoft.com/kb/947723

Is there any way - for those who don't want to generally impose this restriction, or in organizations with existing GPOs that just don't - to work around this?
I'd like to be able to connect to a specific session that is already open (i.e.: a local session left open at the physical console) on a system that does not restrict users to single sessions.
Comment: What do you want to achieve here? To force the user to always reconnect to there open session (if possible) rather than create a new one?
Comment: Work around what? I don't understand what you're asking. Do you mean allow the same user to have multiple RDP sessions? If so, then yes you can "disable" this restriction by disabling the setting.
Comment: Are you asking if you can RDP in, and get connected to a session started on the console?
Comment: For a server in remote administration mode, do you really want a single person to have more then one open session, when the maximum you can have is two total?
Comment: Edited question for clarity.  This is for use on a "workstation server" where I do not have control over the Group Policy.  I'm not looking so much to force the user to always reconnect to an existing session, as I am wanting to just give the user (me, really) the option to do so.
Comment: @Iszi, Even after the edit we're still not getting the question actually. If you are  [looking to connect to a specific session, such as one you might leave open at the local terminal,](http://serverfault.com/questions/226746/is-there-a-way-to-remote-desktop-to-a-local-session-in-server-2008-without-bein#comment-203821) then **simply disconnect** your session (as opposed to logging out) when you are done. Come back the next day and reconnect. Problem solved. Is that what you wanted?
Answer: RDP in, open Task Manager, find the session you want and connect to it.
Comment: A bit more involved than I was hoping for, but that would work.  Would be *really* nice if there was some automated client-side method to do this.
Comment: @Iszi, I think I have a better solution. But [I'm not really getting](http://serverfault.com/questions/226746/is-there-a-way-to-remote-desktop-to-a-local-session-in-server-2008-without-bein#comment822391_226746) your question...
Answer: This can be automated.  Try the following script:
SETLOCAL
SET SESSIONNUMBER=-1
FOR /F "skip=1 tokens=3" %%i in ('query session %username% ^| find /v ">"') DO SET SESSIONNUMBER=%%i
IF {%SESSIONNUMBER%}=={-1} GOTO :EOF
tscon.exe %SESSIONNUMBER%
ENDLOCAL
logoff.exe

Comment: Interesting-looking script.  What shell is this for?  Also, could you comment it to explain the steps for those unfamiliar with this particular syntax?
Comment: This is a native CMD shell script.  This could be saved as a CMD file and run as a typical logon script.  This should be run first before any other scripts, as the rationale for this is to reconnect to another session if it exists.
Answer: I also don't understand the entire question, but according to Microsoft, you can no longer RDP into the "console" in Windows Server 2008 and Windows Server 2008 R2, because the "console" is no longer session 0, as session 0 is a noninteractive session that is reserved for services.
Also, even if you were to log into the console, there is only one console, so you can't have multiple connections to it. Perhaps you are looking at something like VNC instead to control the server's console?
Comment: Edited title for clarity.  I'm not looking to connect to "session 0".  I'm looking to connect to a specific session, such as one I might leave open at the local terminal.
Answer: I'm confused here.  Sounds like you wanted the functionality of the deprecated functionality of the /console switch in RDP 5.x.  You can try /admin, but I am not sure of the result when done locally.  You seem to be under the impression both are deprecated.  I think only one, the /console switch, was put to rest.  See below, ripped from here:

Changes to remote administration in
  Windows Server 2008 and Windows Server
  2008 R2 In Windows Server 2003, you
  can start the RDC client (Mstsc.exe)
  by using the /console switch to
  remotely connect to the physical
  console session on the server (also
  known as session 0). In Windows Server
  2008 or Windows Server 2008 R2, the
  /console switch has been deprecated.
  For more information, see the "Why the
  /console switch is no longer needed"
  section. In Windows Server 2008 and
  Windows Server 2008 R2, session 0 is a
  noninteractive session that is
  reserved for services.
You can use the new /admin switch to
  remotely connect to a Windows Server
  2008-based server for administrative
  purposes. The /admin switch is
  introduced in RDC 6.1. RDC 6.1 is
  included in the following operating
  systems:
* Windows Server 2008
* Windows Server 2008 R2
* Windows Vista Service Pack 1 (SP1)
* Windows XP Service Pack 3 (SP3)

Comment: Good point about console vs. admin, but I'm pretty sure the latter still does not provide the functionality I'm looking for.
Comment: @lszi OK.  I am honestly not sure, but I just wanted to let you know. I am famous for skimming docs, only to find I did not read carefully enough.
Answer: In the OP's question Iszi explictly excludes solutions that limit the user to one session. However, the CMD script provided by Greg Askew does exactly that--once automated as suggested, i.e. installed as login script, you cannot have more than one session because the script will find and join the existing session.
It should be noted that no script is needed if you want that. Changing a registry key via Policy Editor is sufficent. See this post for the details.
Answer: source: http://support.microsoft.com/kb/278845
How to Connect to the Console Session
When you connect to the console session of a Windows Server 2003-based server, no other user has to be already logged on to the console session. Even if no one is logged on to the console, you are logged on just as if you were sitting at the physical console.
To connect from the remote Windows Server 2003-based computer, open a command prompt, and then type the following command:
mstsc -v:servername /F -console
where mstsc is the Remote Desktop connection executable file, -v indicates a server to connect to, /F indicates full screen mode, and -console is the instruction to connect to the console session.
When you use this command, you open the Remote Desktop session, and when the logon is authenticated, you are connected to the console session that is running on the Windows Server 2003-based server. If a user is currently working on the console session at the computer, you receive the following error message:
The user domain\username is logged locally on to this computer. The user has been idled for number minutes. The desktop is unlocked. If you continue, this user's session will end and any unsaved data will be lost. Do you want to continue?
The user of the current console session is then logged off, and you receive a message that states that the computer is currently locked and only an administrator can unlock it.
Note: If the console session user and the Terminal Services session user are the same, you can connect without any problems.
Comment: The tags show that the OP is looking for a way to do connect to the console session from Windows 2008 Server, where the `-console` switch from the KB article you refer is no longer available in Server 2008.


Is it possible to automatically handle List.Contains by comparing a property on the item?

Question: Can we do something similar to List.Contains(myItem) in order to check if a property on an item in the list equals a property on myItem.
(We have considered Contains and Exists, something like:

if (orderLines.Contains(myLine)) { ... }

but cannot get a simple expression.)
We would like something as simple as the following:

if (orderLines.[MethodName](myLine))
{
}

and this method should automagically return true if at least one item orderLines[i] fulfills:

myLine.Product.Equals(orderLines[i].Product)

We have implemented IEquatable<OrderLine> which equates by the Product property, but cannot find how to proceed from there.
Answer: Are you using .NET 3.5? If so, use LINQ:
if (orderLines.Any(order => order.Product == myLine.Product))
{
    ...
}


How to perform join with multiple columns using db_select?

Question: How to perform join with multiple columns using db_select? Any help?
Here below is the sample, which I'm looking for.
SELECT * FROM digitaliq_flds_by_node a
JOIN digitaliq_fld_category b ON
  a.fld_id = b.fld_id AND
  a.fld_collection_id = b.fld_collection_id AND
  a.fld_group_name = b.fld_group_name

Answer: You can use the following code.
$query = db_select('digitaliq_flds_by_node', 'a')->fields('a');
$alias = $query->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name');
$terms = $query->execute();

Calls to SelectQuery::join() (like SelectQuery::leftJoin(), SelectQuery::innerJoin(), and SelectQuery::addJoin()) aren't chain-able because those methods don't return a SelectQuery object, but the actual alias used for the join. If you execute the following code, you would get an error.
$query = db_select('digitaliq_flds_by_node', 'a')
  ->fields('a')
  ->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name')
  ->execute();

Strings in PHP are not objects nor they define an execute() method.
To verify the code is executing the right SQL query, cast $query to a string, and print it. You will get the SQL query that would be executed from your code.
$query = db_select('digitaliq_flds_by_node', 'a')->fields('a');
$alias = $query->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name');
print $query;

With that code, I get the following output.
SELECT a.*
FROM
{digitaliq_flds_by_node} a
INNER JOIN {digitaliq_fld_category} b ON a.fld_id = b.fld_id AND a.fld_collection_id = b.fld_collection_id AND a.fld_group_name = b.fld_group_name

Answer: Try this
$query = db_select('digitaliq_flds_by_node', 'a');
$query->join('digitaliq_fld_category', 'b', 'a.fld_id = b.fld_id');
$query->condition('a.fld_collection_id', 'b.fld_collection_id' '=');
$query->condition('a.fld_group_name', 'b.fld_group_name', '=');
$query->fields('a');
$query->execute();

Comment: The code you are using doesn't work: `leftJoin()` doesn't return a `SelectQuery` object. The code is calling `condition()` for something that is not an object.
Comment: Still the answer is incorrect. check the answer by kiamlaluno
Comment: In other words join is not chain able
Comment: @Mathankumar That is the word I was looking for: chain-able calls. `:)`
Comment: Now its fine. Additional note, by default the operator for condition is equal to(=), so its not necessary to specify them.


VM Folders in ESXi 5.1 Hypervisor (free)

Question: Is there any way to create folders for my VMs on ESXi Hypervisor 5.1? I can create folders for my VMs on my licensed ESXi hosts with vCenter. The closest I can get on ESXi Hypervisor is to create Resource Pools for them, but that's obviously not the correct methodology and I don't want to do it.
Is this another limitation of ESXi Hypervisor?
Comment: AFAIK there isn't a way to do this without vCenter, and you're right, creating Resource Pools to visually/organizationally organize VM's is the wrong way to do it.
Comment: If you do not have money you could consider migrating to Cloudstack/KVM which is free.
Answer: There is no way to organize them into folders. If you get creative with the naming scheme you can get away with it, though. ESXi allows VMs to have special characters in their names, so you could prefix the name with a tag (like... (WEB) for web servers, or something) so it'll appear in a certain spot on the list.
vCenter is definitely the way to go if you have enough VMs to need organizing.
Comment: Exactly. You shouldn't have so many VMs in a single ESXi install that you need folder organization... And if you do, the $500 tier of vSphere Essentials will *buy* you the ability to do so.
Comment: If you're looking to restrict certain VM's to certain users then create the users and grant them the appropriate permissions on the VM's.
Comment: Thank you for the response. This is just a lab environment and I was looking for a way to group VMs so a few users could have their own sandbox without access to another's VMs. I guess it's a no go.


Not able to `replace` content in `style` - where the `html` is stored in variable

Question: I am trying to update the style html - by replacing a string, but not working. i am not able to get the final updated html.
here is my try:
var html = "
testing
"

html += $(html).html(function(_,h){
  $(h).find('style').html().replace(/^\w+ (\.\w+)/gm,'$1');
});

console.log(html); //throws the error.

jsfiddle
Comment: Why down vote? - the content `html`, i am getting from `server`. for sample i made hard coded.
Comment: It's an error thrown by jQuery, not `console.log`. A tag name starting with a number? Maybe you've to check the server-side code, `043BF83A8FB24A418DA4248840101D` doesn't look like a tag.
Comment: I know that, this is not an element. my question is to pick the `style` element and replace the stuff what i looking..
Comment: But the content of the `style` (i.e. `html` variable) is invalid, jQuery can't parse it and throws an error. If you're passing HTML to `$()`, it must be valid.
Comment: yes. I agree with you.. can you place this as an answer to agree..? Possibly put your implementation. that may make sense.
Comment: I would, but I'm not sure what you're actually trying to replace and with what? What ever it is, you should fix the string itself to be valid HTML before passing it to `$`.
Answer: It works for me..
var html = "
testing
";

var $h = $('
'+html+'
');
$h.find('style').html(function(_,h){ return h.replace(/^\w+ (\.\w+)/gm,'$1'); });
var updated = $h.html();

console.log(updated);

Thanks every one!


Is there a way to get a default e-mail recipient by default when adding a new webform node?

Question: When I add a new Webform node type, this have no e-mail recipien by default. You can read this message:

Currently not sending e-mails, add an e-mail recipient below.

Is there a way to get a e-mail recipient value by default when creating a webform node?
Answer: You can do this with a custom module and hook_node_presave(). After you have a custom module created, you can use code like this to create a default e-mail configuration for any created Webforms.
Assuming your module were called myexample.module, the hook would look like this:
<code><?php
/**
 * Implements hook_node_presave().
 */
function myexample_node_presave($node) {
  // Add a default e-mail configuration for new nodes.
  if (empty($node->nid) && $node->type == 'webform') {
    $node->webform['emails'][] = array(
      'email' => 'firstname.lastname@example.com',
      'subject' => 'default',
      'from_name' => 'default',
      'from_address' => 'default',
      'template' => 'default',
      'excluded_components' => array(),
      'html' => 0,
      'attachments' => 0,
    );
  }
}
?>
</code>
Comment: `hook_node_presave` will execute before each `insert` and `update` operation, and after each update new `recipient` will attached to `webform`, so add `$node->is_new` to `if statement` or use `hook_node_insert`
Comment: Thanks it works as expected. Could I also set a default email template text, something like 'Hello, a message is sent from %title...' ?
Comment: I already get the default email template text by setting 'template' in the array. What about setting 'from_address' to the email component?
Comment: Adding $node->is_new isn't needed since I checked empty($node->nid). hook_node_insert() fires *after* the node has already been saved, so if you want webform to do the saving for you, it has to be in hook_node_presave().

You can set the email text by changing the "template" portion. Using the special word "default" will use the default webform template, as produced by the theme system and webform-mail.tpl.php. The same principle applies to from_name and from_address.
Comment: I would like to add that you might want to make sure that when you're doing this on hook_node_insert you need to make sure that your module is on a higher weight then the `webform` module, since it'll delete your e-mails elsewise. Hope this helps some others out, been at this for hours.
Answer: Yes, you can.
You go to your webform node, click on "webform" then "email's", you should set up one if you don't have one, and on "E-mail to address" you can write your default email.
You can even set up the subject and the body.
You can print the whole email through %email_values token value, or field by field with label using  %email[yourfield] or without label using %value[yourfield].
I'm editing my answer:
You can set a defaul email recipient you have three choices:

You create an email field with a defaul value (your email) and the user can change that value;
create an email field with your email such as default value and click on "disable" if you don't want the user changes the email but he can still see it;
create a email field with your email such as default and click on "hidden", the user won't be able to see and change that email;

I hope this time will be useful :D
Comment: The OP is asking if you can automatically have the e-mail to address populated.  This doesn't answer his question.
Comment: I need the e-mail automatically added when I create the node.
Comment: Sorry, I've edited my answer.
Comment: This still isn't a sufficient answer.  OP wants e-mail recipients automatically added at time of creation. He doesn't want to have to click through to Add an e-mail recipient every time.

I've taken a look at using `hook_node_insert`, but it doesn't seem to save the webform data at that point.  Might be worth checking out `hook_node_update`.
Comment: what about rules, can this be done with a rule?


Simple PHP AJAX File Read Progress Problems!

Question: Okay, im not very good at describing these things, so bear with me..
Im trying to find a way of showing a status/progress bar kind of thing to show the percentage (or whatever) of how much of a text file has been read/parsed by php. I know roughly what I need to do (be it by counting the lines, or filesize and that of the actual text file) but I cant for the life of me work out how to actually implement it. I'm using PHP/AJAX and all I really want is for a single div to be updated every so often (5 seconds or something) to show the status until all is done, then show the output. Easy huh, though how the hell I'm supposed to do it, I dont know. I have found some really useful posts on here with regards to it but nothing that I can quite get to work with what I have.
If anyone can give me some rough tips/ideas I would be stupidly grateful (this is really doing my head in)!
Thanks in advance!
Answer: How about...
We have to assume that there is some way to determine the total job (100%) and the point that the php script is at (the % done status), so if it's reading/parsing a text file, you could have the parsing function start by writing the total line count to a db or text file. Then it can also write which line number it's on to that same file every 5 seconds. The js ajax function calls to that text file to get the total and the point it is on. When the php text parser is done, it destroys the status file to prevent it from taking up server space, file name conflicts, etc.

Example:
First, the (jquery) ajax function POSTs to the server:
<code> $.post("parser.php", { file: "somefile.txt"} );
 //I admit, I'm not sure if this is how a file would be posted with ajax
</code>
Next, the php pulls the file and starts the parser function:
<code>    $tmpName  = $_FILES['userfile']['tmp_name'];
    $fileName  = $_FILES['userfile']['name'];

    //Turn the file into an array, so that you can use the array count for status:
    $content = file($tmpName);

    // Get the array count as the total, as it equals the line count:
    $total = count($content);

    //Write the filesize to a unique "total" txt file:
    $total_file = fopen($fileName."-total.txt", 'x');
    fwrite($total_file, $total);
    fclose($total_file);

    //Pass the Array to the parser function:
    parser($content, $fileName);

    //Kill the file when the function is done:
    unlink($fileName);

    function parser ($file_array, $filename) {
           //creates the status file and then closes it, to ensure that it
           //exists for the loop but gets overwritten each time

           $status_file = fopen($filename."-status.txt", 'x');
           fclose($status_file);

           foreach($file_array as $position => $data) {
                  //Do your parsing here //
                   .............
                  //reopen status file and wipe out what is in it already:
                  $status_file = fopen($filename."-status.txt", 'w');
                  fwrite($status_file, $position);
                  fclose($status_file);
             }

       }
</code>
So since the status and total file share the hopefully unique name of the uploaded file, the ajax function knows where to look. It can do this:
<code> total = $.get("somefile-total.txt");

 current = $.get("somefile-status.txt");

 status = current/total;
</code>
Comment: Hey, thanks for the help. I had not thought about doing it that way, and it makes sense, although would writing to a seperate text file not be a bit of a security issue? Shall have a play about with it and see how we go. Thanks
Comment: I was trying to imagine some way to have the script that was parsing be able to respond to an ajax request WHILE it was parsing, or have another script check the status, but I'm pretty sure both of those are pretty unlikely. The other option would be to open a "long polling" server push type situation, where the connection between ajax and the script remains open and ever loop in the above example returns the position to the ajax function instead of to the text file.
Comment: Yeah, its a bit of a nightmare really this... I may stick with just the traditional graphic... hmm
Thanks for all your help though, its hugely appreciated! May look into the long polling stuff, I did look at it as it seemed relevant.
Comment: @Anthony, your general approach is correct and a good starting point, but it could be tweaked some. I have a feeling the first line to send the actual file isn't going to work. Also, If you write the current progress and ttoal bytes to *one* file you avoid the wto separate ajax requests. so just: `status = $.get("somefile-status.txt");` and then split up status on `/`
Comment: @Josh, i was pretty unsure about the file upload bit, for sure. As far as writing it to two files, I was thinking it would simplify things since the total would be the same every time, so the php doesn't have to output it each time and the ajax would only have to request it once (which I didn't in my code, as I was being sloppy).
Answer: There are some really good libraries available from JQuery that do just what you're asking. Unless this is purely for learning purposes, I'd take a look at those and avoid rebuilding the wheel.
http://plugins.jquery.com/search/node/upload
Comment: Ah, I lknow... I have used jquery in the past with good results. But for this I really didn't want to use it, also this isn't for an upload.. Thanks though, I may have to go down that route.


Unexplainable error "Please use the /MD switch for _AFXDLL builds"

Question: I use VisualStudio2010 and CMake 184.108.40.206. I created a CMakeLists.txt for a MFC project. MFC capability was done by following lines in the CMake file:
add_definitions(-D_AFXDLL) #enables MFC
set(CMAKE_MFC_FLAG 2)      #use shared MFC library

Furthermore the project will be build with MD as runtime library (default). But now I want my project to be build as MT (which also requires to specify static MFC library). So I replaced the lines above with:
add_definitions(-D_AFXDLL)          #enables MFC
set(CMAKE_MFC_FLAG 1)               #use static MFC library
set(CMAKE_CXX_FLAGS_RELEASE "/MT")  #set release configuration to MT
set(CMAKE_CXX_FLAGS_DEBUG "/MTd")   #set debug configuration to MTd

If I build my project now, I get error message:
fatal error C1189: #error :  Please use the /MD switch for _AFXDLL builds
As far as I know this means that there's a mismatch between MT/MD on one side and static/shared MFC library on the other side. I checked the configuration in my project settings once again. Runtime library IS set to MT and MFC library IS set to static. So I do not understand the error. Does anybody know help? Did I miss something?
Regards,
Michael
Comment: Already answered http://stackoverflow.com/questions/4229120/error-please-use-the-md-switch-for-afxdll-builds
Comment: Unfortunately, this is not the answer. As mentioned in my questions, the runtime library and the MFC library ARE(!) set coherent (MT + static) and the error message still occurs. That's why I'm asking for help.
Comment: As you see in my answer, they are not ;)
Answer: _AFXDLL is never used with a static MFC build! _AFXDLL.
_AFXDLL is only set when the shared MFC builds are used.
Also static MFC build implies a static CRT.