text:
Q: How do I create a country state dropdownbar I am creating a project where I need to create a signup menu with a contigent country state dropdown Bar. I just don't know how to.
Ive tried looking up other stuff but cant find how to do it. Im working in A MVC and just know the basics.
I want to make it so a country dropdown is required first and updates the the state dropdown without reloading the page

A: The majority of the code came from
https://www.c-sharpcorner.com/blogs/cascading-dropdownlist-in-asp-net-mvc
but there were many changes to convert to what you were looking for
Use this for your country and state dropdown in view

        @Html.LabelFor(model => model.CountryStr, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownListFor(model => model.CountryStr, ViewBag.Country as List<SelectListItem>, new { @class = "form-control" })

        @Html.LabelFor(model => model.StateStr, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownListFor(model => model.StateStr, new SelectList(string.Empty, "Value", "Text"), "--Select State--", new { @class = "form-control" })

and this below it

add this at the top to load a Country List (using @{   }):
string[] whwhw = ListofCountries
IEnumerable<string>
why = whwhw;
SelectList CountryLit = new SelectList(why);

and put this in your controller
public void bindCountry()
    {
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "--Select Country--", Value = "0" });

        cs.Open();
        SqlDataReader dr = (da.SelectCommand = new SqlCommand("SELECT * FROM Country", cs)).ExecuteReader();

        while (dr.Read())
        {
            li.Add(new SelectListItem { Text = dr.GetValue(1).ToString(), Value = dr.GetValue(0).ToString()});
            ViewBag.Country = li;
        }
        cs.Close();
    }
    public JsonResult getState(int id)
    {
        List<SelectListItem> liStates = new List<SelectListItem>();

        liStates.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
        cs.Open();
        SqlDataReader dr = (da.SelectCommand = new SqlCommand("SELECT * FROM State WHERE CountryId = " + id, cs)).ExecuteReader();

        int count = 0;
        while (dr.Read())
        {
            liStates.Add(new SelectListItem { Text = dr.GetValue(1).ToString(), Value = dr.GetValue(0).ToString() });
            ViewBag.State = liStates;
            count += 1;
        }
        cs.Close();
        PersonValues.Country = count;
        return Json(new SelectList(liStates, "Value", "Text", JsonRequestBehavior.AllowGet));
    }

and put
bindCountry();

before you return view for the page the dropdown bars are going to be in


text:
Q: undefined reference to a class ERROR I am working in c++ /ubuntu.
I have:
libr.hpp
#ifndef LIBR
#define LIBR

#include <string>
using namespace std;

class name
{
    public:
    name();
    ~name();
    std::string my_name;
    std::string method (std::string s);

};

#endif

and
libr.cpp
#include <iostream>
#include <string>
#include <stdlib.h>
#include "libr.hpp"
using namespace std;

name::name()
{

}
std::string name::method(std::string s)
{
    return ("YOUR NAME IS: "+s);
}

From these two I've created a libr.a.
In test.cpp:
#include <iostream>
#include <string>
#include <stdlib.h>
#include "libr.hpp"

using namespace std;

int main()
{

    name *n = new name();
    n->my_name="jack";
    cout<<n->method(n->my_name)<<endl;
    return 0;
}

I compile with g++ and libr.a. I have an error: "name::name() undefined reference", why?
I would like to mention that I've added in qt creator at qmake the .a. When I compile, I have the error. How can I solve it?

A: This is a linker error, not a compiler error. It means that you have called but you have not defined the constructor. Your allocation name *n = new name(); calls the constructor.
Since you defined the constructor in your libr.cpp, what this means is that this compilation unit is not making its way into your executable. You mentioned that you are compiling with libr.a. When you compile your libr.cpp the result is a .o file, not a .a file.
You are not linking libr.o into your executable.

A: What are the steps you're using to compile your "project"?
I performed the following steps and managed to build it with warnings/errors.
g++ -Wall -c libr.cpp

ar -cvq libr.a libr.o

g++ -Wall -o libr main.cpp libr.a

One last thing, if I change the order off the last command, like
g++ -Wall -o libr libr.a main.cpp

I get the following error:
Undefined                       first referenced
 symbol                             in file
name::name()                        /tmp/cc4Ro1ZM.o
name::method(std::basic_string<char, std::char_traits<char>, std::allocator<char
> >)/tmp/cc4Ro1ZM.o
ld: fatal: Symbol referencing errors. No output written to libr
collect2: ld returned 1 exit status

A: in fact , you needn't define the  destructor yourself because the default destructor will be used when the class calling is over.
and in the VS2008,it's all right!

redpajama_set_name: RedPajamaStackExchange


text:
Q: ggplot2: strange behaviour of geom_boxplot I want to produce a grouped boxplot, so first I modified a piece of code I found on the internet (http://www.r-bloggers.com/ggplot2-multiple-boxplots-with-metadata/) to generate a dataframe of test values:
    Y <- data.frame(
      values = c(rnorm(mean=20, sd=4, n=3), rnorm(mean=10, sd=2, n=3), rnorm(mean=50, sd=10, n=3), rnorm(mean=60, sd=12, n=3)),
      factor1 = rep(c('oil1', 'oil2'), each = 3),
      factor2 = rep(c('product1', 'product2'), each = 6)
   )

    values  factor1 factor2
1   13.527314   oil1    product1
2   23.495898   oil1    product1
3   14.881210   oil1    product1
4   9.110103    oil2    product1
5   9.330372    oil2    product1
6   10.846560   oil2    product1
7   40.786020   oil1    product2
8   43.157393   oil1    product2
9   43.050182   oil1    product2
10  39.588651   oil2    product2
11  65.963630   oil2    product2
12  63.425253   oil2    product2

Then, the code:
ggplot(Y, aes(x = factor2, y = values, fill = factor1)) +
  geom_boxplot()

produces the boxplot I want.
My real data are in this other data frame, created reading a .csv file:
    values  factor1 factor2
1   0.2 oil1    product1
2   1.7 oil1    product1
3   3.2 oil1    product1
4   27.8    oil2    product1
5   29.8    oil2    product1
6   31.8    oil2    product1
7   0   oil1    product2
8   1   oil1    product2
9   2.5 oil1    product2
10  29.3    oil2    product2
11  31.3    oil2    product2
12  33.3    oil2    product2

(I am unable to correct the misalignement in this table)
Yet when I try to create a boxplot using the code above, instead of the boxes the plot contains horizontal segments at y=value.
How can I resolve this problem?

A: In fact, I realized that geom_crossbar is better for what I want to do.
Which is, values on the Y-axis; factor2 on the X-axis; different fill colors for oil1 and oil2; one colored bar extending from minimum to maximum of value and centered around the mean for each oil+product combination (for a total of 4 bars)
The result should look like the image in this answer to a similar question:
https://stackoverflow.com/a/21561408/4518857


text:
Q: Create dropdown with buttons in every option, using angular 6 + I have a dropdown in angular 6 that I create using ngFor. Now, in every option, I would like to add a functional button.
The obvious solution would be
<select formControlName="van">
  <option *ngFor='let item of vanArray' value="{{item.id}}" > {{item.name}}
     <button type="button" (click)="whatever(item.id)" name="button">delete</button>
  </option>
</select>

This kinda works. I get no errors whatsoever, but the button is never rendered as a button, I get just a "delete " text , next to each option, that is not clickable.
How can I do this?
Thanks
PS : is it possible to use just angular and not any package?


text:
Q: XSD / XML quote escaping I need to create XSD document with restriction so that we only allow the following values in the XML element.
3"
30"
5" x 18"
4" X 12"
Other

I started creating an element with restriction with enumeration but I do not know how to specify quotes in the enumeration.
I tried adding restriction with &quote;, '"', \" but nothing is working.
<xs:element name="Diameter">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:enumeration value="3&quote;" />
      <xs:enumeration value="30&quote;" />
      <xs:enumeration value="5&quote; x 18&quote;" />
      <xs:enumeration value="4&quote; x 12&quote;" />
      <xs:enumeration value="other" />
    </xs:restriction>
  </xs:simpleType>
</xs:element>

A: Use ", not &quote;
Alternatively, use ' ... ' to deliminate the attribute values, then " internally:
  <xs:enumeration value='3"' />


text:
Q: Where did my shiny web app write the table to? I was trying to make up a shiny web app, for which I want to record each online data input and append them to an .csv file.
My current code for server.R is listed below. It can append to the csv file in my local bundle folder when I click "Run App" in RStudio. But after I upload them to https://brianzhang1994.shinyapps.io/Anqi/, I do not know where the shiny app wrote the table to. Even when I download the bundle file, the .csv file inside is exactly the same as when i uploaded.
How can I fix this question?
library(shiny)

shinyServer(function(input, output) {
output$tableforpatient <- renderDataTable({
patientall <- read.table("brian.csv")
patient <- data.frame(firstname=input$firstname,
                      lastname=input$lastname,
                      dob=input$dob,
                      number=paste0("+1",input$numbers),
                      email=input$email,
                      joined=Sys.Date())
write.table(patient, file = "brian.csv", sep = ",", append = TRUE,
            row.names = FALSE, col.names = FALSE)
patient
                                         })
                                     })

A: You probably want to use reactiveValues:
shinyServer(function(input, output) {
  my <- reactiveValues(patientall=read.table("brian.csv"))
  output$tableforpatient <- renderDataTable({my$patientall})
  observeEvent(input$submit, {
    patient <- data.frame(firstname=input$firstname,
                          lastname=input$lastname,
                          dob=input$dob,
                          number=paste0("+1",input$numbers),
                          email=input$email,
                          joined=Sys.Date())
    my$patientall <- rbind(my$patientall,patient)
  })
})

Note usage of submit action button to avoid creating incomplete patients


text:
Q: how to generate the pdf when the form is submitting in laravel 5.2 I am working on a  product management system and there is a module called purchase.
I have wrote the store() method the controller and the model part too.
Now I want to generate the invoice when I click on submit button. I used PDF generator plugin as barryvdh/laravel-dompdf. I'm new to PHP & Laravel and just wants to know instructions to do the PDF generation process.

A: You would follow the install steps for Laravel 5:

*

*Add this, Barryvdh\DomPDF\ServiceProvider::class, to your config/app.php file as a ServiceProvider

*Add this, 'PDF' => Barryvdh\DomPDF\Facade::class, to your facades in your config/app.php file

And then in your store method, after you save all the information, you could generate a PDF like so:
$pdf = \PDF::loadView('pdf.invoice', $data);
return $pdf->download('invoice.pdf');

This would load the invoice view stored in resources/views/pdf with the values stored in $data, and then return a downloadable file called invoice.pdf.
This all comes directly from the Using section of the DomPDF docs.

A: 1- Install the DOMPDF according to this Github Link
2- Form page
 <form id="FOO" method="POST" action="/pdf">

     <input type="text" name="object" >
     <button type="submit">Generate</button>

 </form>

3- Route :Route::post('pdf' , 'EventsController@PDFGenerator');
Please notice,here,that you will either need to include a hidden input,with csrf token,or simply exclude this route in the VerifyCSRFToken.php  middleware,otherwise it will not let you post(if you haven't worked with Auth yet,don't mind this notice)
4- Controller page now
public function PDFGenerator (Request $request){
    $html = <<<ENDHTML

   <!DOCTYPE html>

      <title>Foo</title>
      <meta charset="utf-8">

      {$request->object}

ENDHTML;
    $dompdf = App::make('dompdf.wrapper');
    $dompdf->loadHTML($html);
    $dompdf->stream("hello.pdf");
    return $dompdf->stream();

}

This is the Heredoc documentation in case you needed more information about how to use it.
Don't forget to include the library in your controller,waiting for your feedback.

A: Step 1 :
composer require barryvdh/laravel-dompdf

Step 2. Update config/app.php
Open config/app.php file. Add the following line to 'providers' array:
'providers' => [
....
 Barryvdh\DomPDF\ServiceProvider::class,
],

'aliases' => [
....
 'PDF' => Barryvdh\DomPDF\Facade::class,
]

Step 3. Add routes
Now open your web.php file and add following route.
<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PDFController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('generate-pdf','PDFController@generatePDF');

Step 4. Add Link In Blade File
Generate PDF

Step 5. Create Controller
Add your controller below code.
<?PHP
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;

class PDFController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function generatePDF()
{
    $data = [
      'title' => 'First PDF ',
      'heading' => 'Hello Bro',
      'content' => 'Data content'
        ];

    $pdf = PDF::loadView('generate_pdf', $data);

    return $pdf->download('Laravel.pdf');
  }
 }

Step 6. Create Blade File
Let's create generate_pdf.blade.php for layout of pdf file and put
following code:
<!DOCTYPE html>

    <title>Generate Pdf</title>

{{ $heading}}

{{$content}}


text:
Q: how to disabled asp-action link after one click i would like to disabled asp=action link after one click
i have a foreach loop to display my book in table in my view
my asp-action for add book in the cart is in the loop but i want to disabled just the book who already in the cart not all books
  Ajouter

i try something with jquery but its dont work well
i tried this
  tag:
@section scripts{

}

*copy the script code inside a newFile.js and add it to your view

*You may decide to bundle this newFile.js


text:
Q: How to properly replace inline images with styled floating divs via PHP's DOMDocument? I'm stuck on the following problem and would like to know if you got an advise.
A WYSIWYG editor allows the user to upload and embed images. However, my users are mostly scientists but don't have any knowledge of how to use HTML or even how to re-size images properly for a web page. That's why I am re-sizing the images automatically server-side to a thumbnail and a full view size. Clicking on a thumbnail shall open a lightbox with full image.
The WYSIWYG editor throws images into
 tags just like this (see last paragraph):

Intro Text

List point 1

List point 2

Some text before an image.

   Maybe some text in between, nobody knows what the scientists are up to.

   And even more text right after that.

What I would like to do is get the images out of the
 Tags and add them before the respective paragraph within floating
s:

Intro Text

List point 1

List point 2

Some text before an image.
   Maybe some text in between, nobody knows what the scientists are up to.
   And even more text right after that.

So what I need to do is to get all the image nodes of the html produced by the editor, process them, insert the divs and remove the image nodes.
After reading quite a lot of similar questions I'm missing something and can't get it to work. Probably, I am still misunderstanding the whole concept behind DOM manipulation.
Here's what I came up with til now:
// create DOMDocument
$doc = new DOMDocument();
// load WYSIWYG html into DOMDocument
$doc->loadHTML($html_from_editor);
// create DOMXpath
$xpath = new DOMXpath($doc);
// create list of all first level DOMNodes (these are p's or ul's in most cases)
$children = $xpath->query("/");
foreach ( $children AS $child ) {
    // now get all images
    $cpath = new DOMXpath($child);
    $images = $cpath->query('//img');
    foreach ( $images AS $img ) {
        // get attributes
        $atts = $img->attributes;
        // create replacement
        $lb_div = $doc->createElement('div');
        $lb_a = $doc->createElement('a');
        $lb_img = $doc->createElement('img');
        $lb_img->setAttribute("src", '/files/thumbs'.$atts->src);
        $lb_a->setAttribute("href", '/files/fullview'.$atts->src);
        $lb_a->setAttribute("rel", "lightbox[slide][".$atts->alt."]");
        $lb_a->appendChild($lb_img);
        $lb_div->setAttribute("class", "custom");
        $lb_div->appendChild($lb_a);
        $child->insertBefore($lb_div);
        // remove original node
        $child->removeChild($img);
    }
}

Problems I ran into:

*
*`$atts` is not populated with values. It does contain the right attribute names, but values are missing.

*`insertBefore` should be called on the child's parent node if I understood that right. So, it should rather be `$child->parentNode->insertBefore($lb_div, $child);` but the parent node is not defined.

*Removal of original img tag does not work.

I'd be thankful for any advise what I am missing. Am I on the right track or should this be done completely different?
Thans in advance,
Paul

A: This should do it (demo):
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXML("
$xhtml
"); // we need the div as root element

// find all img elements in paragraphs in the partial body
$xp = new DOMXPath($dom);
foreach ($xp->query('/div/p/img') as $img) {

    $parentNode = $img->parentNode; // store for later
    $parentNode->removeChild($img); // unlink all found img elements

    // create a element
    $a = $dom->createElement('a');
    $a->setAttribute('href', '/files/fullview/' . basename($img->getAttribute('src')));
    $a->setAttribute('rel', sprintf('lightbox[group][%s]', $img->getAttribute('alt')));
    $a->appendChild($img);

    // prepend img src with path to thumbs and remove alt attribute
    $img->setAttribute('href', '/files/thumbs' . $img->getAttribute('src'));
    $img->removeAttribute('alt'); // imo you should keep it for accessibility though

    // create the holding div
    $div = $dom->createElement('div');
    $div->setAttribute('class', 'custom');
    $div->appendChild($a);

    // insert the holding div
    $parentNode->parentNode->insertBefore($div, $parentNode);
}

$dom->formatOutput = true;
echo $dom->saveXml($dom->documentElement);

A: As I commented, your code had multiple errors which prevented you from getting started. Your concept looks quite well from what I see and the code itself only had minor issues.

*

*You were iterating over the document root element. That's just one element, so picking up all images therein.

*The second xpath must be relative to the child, so starting with ..

*If you load in a HTML chunk, DomDocument will create the missing elements like body around it. So you need to address that for your xpath queries and the output.

*The way you accessed the attributes was wrong. With error reporting on, this would have given you error information about that.

Just take a look through the working code I was able to assemble (Demo). I've left some notes:
$html_from_editor = <<<EOD

Intro Text

List point 1

List point 2

Some text before an image.

   Maybe some text in between, nobody knows what the scientists are up to.

   And even more text right after that.

EOD;

// create DOMDocument
$doc = new DOMDocument();
// load WYSIWYG html into DOMDocument
$doc->loadHTML($html_from_editor);
// create DOMXpath
$xpath = new DOMXpath($doc);

// create list of all first level DOMNodes (these are p's or ul's in most cases)
# NOTE: this is XHTML now
$children = $xpath->query("/html/body/p");

foreach ( $children AS $child ) {
    // now get all images
    $cpath = new DOMXpath($doc);
    $images = $cpath->query('.//img', $child); # NOTE relative to $child, mind the .

    // if no images are found, continue
    if (!$images->length) continue;

    // insert replacement node
    $lb_div = $doc->createElement('div');
    $lb_div->setAttribute("class", "custom");
    $lb_div = $child->parentNode->insertBefore($lb_div, $child);

    foreach ( $images AS $img ) {
        // get attributes
        $atts = $img->attributes;
        $atts = (object) iterator_to_array($atts); // make $atts more accessible

        // create the new link with lighbox and full view
        $lb_a = $doc->createElement('a');
        $lb_a->setAttribute("href", '/files/fullview'.$atts->src->value);
        $lb_a->setAttribute("rel", "lightbox[slide][".$atts->alt->value."]");

        // create the new image tag for thumbnail
        $lb_img = $img->cloneNode(); # NOTE clone instead of creating new
        $lb_img->setAttribute("src", '/files/thumbs'.$atts->src->value);

        // bring the new nodes together and insert them
        $lb_a->appendChild($lb_img);
        $lb_div->appendChild($lb_a);

        // remove the original image
        $child->removeChild($img);
    }
}

// get body content (original content)
$result = '';
foreach ($xpath->query("/html/body/*") as $child) {
    $result .= $doc->saveXML($child); # NOTE or saveHtml
}

echo $result;


text:
Q: Copying variable value form shell script to constant file I have appcenter-pre-build.sh in which I am executing another script depend on environment type. If environment is UAT then it will execute uat-pre-build.sh.
Here is appcenter-pre-build.sh
if [ -z "$ENV_TYPE" ]
then
    echo "You need define the ENV_TYPE variable in App Center"
    exit
fi
echo "ENV_TYPE is : - $ENV_TYPE"
if [ "UAT" = "$ENV_TYPE" ]
then
    echo "Environment type : UAT"
    ENV_FILE=$APPCENTER_SOURCE_DIRECTORY/ABC/config/uat-pre-build.sh
else
    echo "you need to mentioned correct envrionment type"
    exit
fi
echo "Environment file : $ENV_FILE"
sh "$ENV_FILE"

I have three different script depends on build environment.

*

*uat-pre-build.sh

*dev-pre-build.sh

*prod-pre-build.sh

In above script I am reading variable value and trying to assigning it into ConfigurationHelper.cs.
Here is my uat-pre-build.sh
APP_ID=b1a4a39f-4d89-4f04-98d8-2a20eda89aad
# Get ConfigurationHelper.cs from project
APP_CONSTANT_FILE=$APPCENTER_SOURCE_DIRECTORY/helpers/ConfigurationHelper.cs

if [ -e "$APP_CONSTANT_FILE" ]
then
    echo "Updating environment configs in AppConstant.cs"

    sed -i '' 's#ApplicationID = "[-A-Za-z0-9:_./]*"#ApplicationID = "'$APP_ID'"#' $APP_CONSTANT_FILE

    echo "File content:"
    cat $APP_CONSTANT_FILE
else
        echo "Can not locate $APP_CONSTANT_FILE file"
fi

Here is ConfigurationHelper.cs
public class ConfigurationHelper
{
    public static string ApplicationID = string.Empty;
    static ConfigurationHelper(){}

}

I am able to execute script but unable to assign APP_ID value from uat-pre-build.sh to ApplicationID in ConfigurationHelper.cs. Seems following line is not executing correctly.
sed -i '' 's#ApplicationID = "[-A-Za-z0-9:_./]*"#ApplicationID = "'$APP_ID'"#' $APP_CONSTANT_FILE

Here is output from app center.
[command]/bin/bash

/Users/vsts/agent/2.153.1/work/1/s/ABC.Android/appcenter-pre-build.sh
ENV_TYPE is : - UAT
Environment type : UAT
Environment file : /Users/vsts/agent/2.153.1/work/1/s/ABC/config/uat-pre-build.sh
Updating environment configs in AppConstant.cs
File content:

namespace ABC.Business.Helpers
{
/// <summary>
/// The configuration helper.
/// </summary>
public class ConfigurationHelper
{
    public static string ApplicationID = string.Empty;

    /// <summary>
    /// Initializes static members of the <see cref="ConfigurationHelper"/> class.
    /// </summary>
    static ConfigurationHelper()
    {
    }

    }

}

Please help me out to resolve this issue.

A: You appear to want to substitute the string.Empty in your ConfigurationHelper.cs file but as you've discovered, the substitution you're using will never match. You've got ApplicationID = "[-A-Za-z0-9:_./]*". This could match
public static string ApplicationID = "string.Empty";

but since you've explicitly specified the double quote characters in the match pattern they have to be present in the source.
You could try a straight match, ApplicationID = string.Empty. If you really need the complexity of either string.Empty or a quoted string, what about ApplicationID = \(string.Empty|".*"\)


text:
Q: Chess: bitscanning I'm writing a chess engine in C# with magic bitboards and it's very slow right now. It takes 2 minutes to calculate perft 6 (119,060,324 positions) from the initial position when other engines can do it in 1-3 seconds. I'm currently using this method to find the indices of all 1s in the bitboard:
public static readonly int[] index64 = {
         0, 47,  1, 56, 48, 27,  2, 60,
         57, 49, 41, 37, 28, 16,  3, 61,
         54, 58, 35, 52, 50, 42, 21, 44,
         38, 32, 29, 23, 17, 11,  4, 62,
         46, 55, 26, 59, 40, 36, 15, 53,
         34, 51, 20, 43, 31, 22, 10, 45,
         25, 39, 14, 33, 19, 30,  9, 24,
         13, 18,  8, 12,  7,  6,  5, 63
    };

public static List<int> bitScan(ulong bitboard) {
        var indices = new List<int>(30);
        const ulong deBruijn64 = 0x03f79d71b4cb0a89UL;

        while (bitboard != 0) {
            indices.Add(index64[((bitboard ^ (bitboard - 1)) * deBruijn64) >> 58]);
            bitboard &= bitboard - 1;
        }
        return indices;
    }

This is the method that is called the most, and I want to speed it up. Is there a faster way to do this? I want to return an array instead of a list, but I can't figure out how since the number of bits is unknown (and I don't want empty elements since I have lots of foreach loops).
Any advice is appreciated.

A: I would say that the List<T> is the biggest performance thief. How does this work compared to your own implementation?:
public static readonly byte[] index64 = {
         0, 47,  1, 56, 48, 27,  2, 60,
         57, 49, 41, 37, 28, 16,  3, 61,
         54, 58, 35, 52, 50, 42, 21, 44,
         38, 32, 29, 23, 17, 11,  4, 62,
         46, 55, 26, 59, 40, 36, 15, 53,
         34, 51, 20, 43, 31, 22, 10, 45,
         25, 39, 14, 33, 19, 30,  9, 24,
         13, 18,  8, 12,  7,  6,  5, 63
    };

private static const ulong deBruijn64 = 0x03f79d71b4cb0a89UL; // Do not initialize many times
public static byte[] bitScan(ulong bitboard) {
  // Should never be more than that right, queen can hit maximum 28 squares?
  var indices = new byte[28];
  var index = 0;
  while (bitboard != 0) {
    indices[index++] = index64[((bitboard ^ (bitboard - 1)) * deBruijn64) >> 58];
    bitboard &= bitboard - 1;
  }
  return indices;
}

When using it outside of the method, just don't care about the 0's in the array.

A: In C/Assembly you can use the TZCNT, LZCNT and POPCNT commands for bit-scanning which you find on processors nowadays. Using JNI for Java I programmed just that and to my surprise found that it was not faster than Java's Long.numberOfTrailingZeroCount(). The explanation was that the JVM optimizes using TZCNT anyway so I was just adding JNI overhead.
This is from Java 7 onwards, but I am sure Microsoft must have the same optimization for .Net.


text:
Q: Multiple firebase user login First of all thanks for your time.
I'm trying to add a two option login in my app. One for a doctor and one for patient. I achieved to store both of them in realtime database as you can see below.
patient / doctor --> realtime database
As you can see, i have one tag ("isDoctor") with true o false for distinguish between both users.
Wat i want to is to check the value of this "isDoctor" tag to send the user to the corresponding activity. If isDoctor is true i want to send the user to Doctor activity and if is a patient to the corresponding one. Is thinks that this checking should go in "State.Succes" once the user is sign in but i don't know how to perform it.
Here is my login code from RemoteDataSource class and from the login activity. I am using mvvm with flow for this project.
 mBinding.btnLogin.setOnClickListener {
        if (areFieldsReady()) {
            lifecycleScope.launchWhenStarted {

                loginViewModel.login(email, password).collect { loginResult ->
                    when (loginResult) {
                        is State.Loading -> {
                            if (loginResult.flag == true) loadingDialog.startLoading()
                        }
                        is State.Succes -> {
                            loadingDialog.stopLoading()
                            Snackbar.make(
                                mBinding.root,
                                loginResult.data.toString(),
                                Snackbar.LENGTH_SHORT
                            ).show()

                        }
                        is State.Failed -> {
                            loadingDialog.stopLoading()
                            Snackbar.make(
                                mBinding.root,
                                loginResult.error,
                                Snackbar.LENGTH_SHORT
                            ).show()
                        }
                    }
                }

            }
        }

    }

fun login(email: String, password: String): Flow<State<Any>> = flow<State<Any>> {
    emit(State.loading(true))
    val auth = Firebase.auth

    val data = auth.signInWithEmailAndPassword(email, password).await()
    //if the task was performend in backend
    data?.let {
        if (auth.currentUser?.isEmailVerified!!) {
            emit(State.succes(R.string.login_succes)) //emiting the class directly by using the function
        } else {
            auth.currentUser?.sendEmailVerification()?.await()
            emit(State.failed(R.string.verify_email_first.toString()))
        }
    }
}.catch {
    emit(State.failed(it.message!!))
}.flowOn(Dispatchers.IO)

Of course before the login I have a "sing up" method for this propuse. I don't added here because i thinks it is not adding more information about the code and question

A: Since the "doctors" and the "patients" nodes exist in a different hierarchy in your database, you cannot perform a query to filter them. The queries in the Realtime Database work on a flat list of nodes, where the value on which you want to perform the filter must be at a fixed path under each direct child node. That being said, you should use a simpler database schema that can allow you to perform the desired query.
Please note that we are structuring a Realtime Database database according to the queries that we want to perform. Since both doctors and patients can be considered users of your app, and since you already differentiate them using the boolean field "doctor", then there is no need to create two different nodes inside your database. So a simpler solution for structuring such a schema would be:
Firebase-root
  |
  --- users
       |
       --- $uid
       |    |
       |    --- doctor: true
       |    |
       |    --- email: "robert@beatingbrain.com"
       |
       --- $uid
            |
            --- doctor: false
            |
            --- email: "rober19neuro@gmail.com"

So to be able to redirect a user to the corresponding activity, inside your State.Succes you should use the following lines of code:
val uid = FirebaseAuth.getInstance().currentUser?.uid
val db = FirebaseDatabase.getInstance().reference
val uidRef = db.child("users").child(uid)
val valueEventListener = object : ValueEventListener {
    override fun onDataChange(snapshot: DataSnapshot) {
        val doctor = snapshot.child("doctor").getValue(Boolean.class)
        if(doctor) {
            startActivity(Intent(context, DoctorActivity::class.java));
        } else () {
            startActivity(Intent(context, PatientActivity::class.java));
        }
    }

    override fun onCancelled(databaseError: error) {
        Log.d("TAG", error.getMessage()) //Don't ignore potential errors!
    }
}
uidRef.addListenerForSingleValueEvent(valueEventListener)


text:
Q: AttributeError| Model object has no attribute 'get' This is my model
class Leave_Management(models.Model):
    employee = models.ForeignKey('employeeModel', on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    reason = models.TextField(max_length=200)
    date_to = models.DateField(null=True)
    date_from = models.DateField(null=True)
    leave_balance = models.IntegerField(default=14)
    paid_leave = models.IntegerField(default=0)
    unpaid_leave = models.IntegerField(default=0)

    time_generated = models.DateTimeField(auto_now_add=True)
    time_approved = models.DateTimeField(null=True, blank=True)

    def get_absolute_url(self):
        return reverse('approve',kwargs={'pk':self.pk})

    def __str__(self):
        return str(self.employee)

    def get_total_days(self):
        dt = (self.date_to - self.date_from).days
        return dt

I have created two instances of above model. So when i try to access those instances in Django Shell it works fine
>>> form = Leave_Management.objects.all().get(pk=1)
>>> form
<Leave_Management: Emp001>

But when i  try such thing in views.py It raises error that  E
Exception Type: AttributeError
Exception Value:
'Leave_Management' object has no attribute 'get'

views.py
def approve(request,pk):
    form = Leave_Management.objects.get(pk=pk)
    return form

Is there anything wrong in my views.py?

A: You can't return an instance directly from a view, you need to return a response. Usually that is by rendering a template:
return render(request, 'mytemplate.html', {'form': form})

although conceivably you could return the form itself wrapped in an HttpResponse:
return HttpResponse(form)

but it would look horrible.
(Also you should think about calling things what they are; a model instance is not a form.)


text:
Q: How to make html button call external javascript drawing function So my end goal is to have a simple webpage with say 10 buttons and each button, upon being clicked, calls a different javascript function. Each of these functions would be some sort of drawing. To start I'm just trying to get used to buttons calling external js files.

    <button onclick="setup();draw();">
        Draw me a circle!
    </button>

Above is my html file and below is the javascript file from which I am trying to call the function.
function setup() {
  createCanvas(1300, 800);
}

function draw(){
    ellipse(100,100,80,80);
}

The button appears but after it is clicked nothing else happens. I would like the button to disappear after being clicked and only the ellipse to remain. Is this a possibility? I'm very new to web development (I started yesterday) so I'm sorry if this is a really easy problem to solve.

A: I don't know if this can help but.. As shown you can call the second function draw() inside the setup() function,  JSFiddle
Updated
HTML:
<button id="myBtn">Draw me a circle!</button>

JS:
btn = document.getElementById("myBtn");
btn.onclick = function setup() {
    btn.remove();
    //alert("Function Setup!");
    document.getElementById("holder").innerHTML = '<canvas id="myCanvas" width="490" height="220"></canvas>';
    draw();
}

function draw() {
    //alert("Function Draw!");
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var centerX = canvas.width / 2;
    var centerY = canvas.height / 2;
    var radius = 70;

    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();
}

for more than one button just give each one of them an id and make a js var for each one:
btn1 = document.getElementById("myBtn1");
btn2 = document.getElementById("myBtn2");

Note:
code802, just something worthy to mention, I'd go with SVG drawing over canvas for:

*

*more support

*SVG is vector graphics mean no pixel-ating or blurry edges no matter how much you zoom on or what the screen resolution is.

*It can be external or css, img, object or inner-html or src.

*It could be cached in many cases.

*you can also manipulate it and animate it almost any way you want and anything you can do with canvas can do with svg

https://css-tricks.com/using-svg/


text:
Q: How to create GridLayout Dynamically and clear its widgets in Kivy? I have a problem on clearing widgets in Gridlayout which was created in KY File.
I added self.ids.gridsonuc.clear_widgets() command on a button so when i click on that button, it successfully removes widgets but after removing widgets since i am not dynamically creating the gridlayout through python code that's why when i click the button for the second time i get an error because there exists no gridlayout with that ID. So, instead of declaring child gridlayout directly in .kv file, i should use main.py to create the child gridlayout and then i should use the object of the child gridlayout for removing it from screen instead of its id. But i don't know how to do this?
My usage is in below form!
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.metrics import dp
from kivy.uix.image import Image
from kivy.uix.behaviors import ButtonBehavior
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.factory import Factory
from kivy.properties import ObjectProperty
import requests

class PopupBox(Popup):

    pop_up_text = ObjectProperty()
    def update_pop_up_text(self, p_message):
        self.pop_up_text.text = p_message

class Updown(ButtonBehavior, Image):

    def __init__(self, **kwargs):
        super(Updown, self).__init__(**kwargs)

class WrappedLabel(Label):

    def __init__(self, **kwargs):
        super(WrappedLabel, self).__init__(**kwargs)

        self.bind(
            width=lambda *x: self.setter('text_size')(self, (self.width, None)),
            texture_size = lambda *x: self.setter('height')(self, self.texture_size[1]))

class Predictor(BoxLayout):

    def __init__(self, **kwargs):
        super(Predictor, self).__init__(**kwargs)

        self.status = True
        self.data = self.datas()
        self.Today = self.todayMatches()

    def homepage(self, s_image, screenmanager):

        screenmanager.current = 'homepage_screen'

    def show_popup(self):

        self.pop_up = Factory.PopupBox()
        self.pop_up.update_pop_up_text('Loading...')
        self.pop_up.open()

    def underOver(self, s_image, screenmanager):

        screenmanager.current = 'underover_screen'

        self.show_popup()
        #mythread = threading.Thread(target=self.underOver_hesaplama)
        #mythread.start()
        #self.ids.gridsonuc.clear_widgets()
        Clock.schedule_once(self.datas)
        Clock.schedule_once(self.underOver_hesaplama)

    #@mainthread
    def underOver_hesaplama(self, *args):

        print("""
        Welcome to Under Over Goal Statics
        """)

        #self.ids.gridsonuc.remove_widget(box)

        for i in range(len(self.Today[0])):
            try:
                sonuc = some calculations
            except:
                sonuc = int(0)

            box = BoxLayout(size_hint_y = None, height = dp(50))
            sira = WrappedLabel(text = f'{i+1}', font_name = 'fonts/Lcd.ttf', font_size = dp(15), size_hint = (0.10, 1), halign='center' )
            evsahibi = WrappedLabel(text = f'{self.Today[0][i]}', font_name = 'Roboto', font_size = dp(15), size_hint = (0.225, 1), halign='center', bold = True )
            deplasman = WrappedLabel(text = f'{self.Today[1][i]}', font_name = 'Roboto', font_size = dp(15), size_hint = (0.225, 1), halign='center', bold = True )
            macbasigol = WrappedLabel(text = f'{sonuc}', font_name = 'fonts/Lcd.ttf', font_size = dp(20), size_hint = (0.15, 1), halign='center', color= (1, 0.4, 0.769, 1) )
            if sonuc == int(0):
                ust_2_5 = Updown(size_hint = (0.15, 1), source = 'images/error.png')
                ust_3_5 = Updown(size_hint = (0.15, 1), source = 'images/error.png')
            elif sonuc < 2.50:
                ust_2_5 = Updown(size_hint = (0.15, 1), source = 'images/down.png')
                ust_3_5 = Updown(size_hint = (0.15, 1), source = 'images/down.png')
            elif sonuc >= 2.50 and sonuc < 3.50:
                ust_2_5 = Updown(size_hint = (0.15, 1), source = 'images/up.png')
                ust_3_5 = Updown(size_hint = (0.15, 1), source = 'images/down.png')
            else:
                ust_2_5 = Updown(size_hint = (0.15, 1), source = 'images/up.png')
                ust_3_5 = Updown(size_hint = (0.15, 1), source = 'images/up.png')
            box.add_widget(sira)
            box.add_widget(evsahibi)
            box.add_widget(deplasman)
            box.add_widget(macbasigol)
            box.add_widget(ust_2_5)
            box.add_widget(ust_3_5)
            self.ids.gridsonuc.add_widget(box)

        self.pop_up.dismiss()

My KV file:
#:import NoTransition kivy.uix.screenmanager.NoTransition
<Predictor>:
    ScreenManager:
        transition: NoTransition()
        id: sm
        size: root.width, root.height
        Screen:
            name: 'homepage_screen'
            Image:
                source: 'images/homepage_background.png'
                allow_stretch: True
                keep_ratio: False
            BoxLayout:
                size_hint: 1, 0.10
                Button:
                    id: underOver_button_homepage
                    on_press: root.underOver(img_underOver, sm)
                    background_color: 0, 0, 0, 0
                    Image:
                        id: img_underOver
                        source: 'images/underover_button.png'
                        allow_stretch: True
                        keep_ratio: False
                        size: self.parent.size
                        pos: underOver_button_homepage.pos
                Button:
                    id: side_button_homepage
                    on_press: root.side(img_side, sm)
                    background_color: 0, 0, 0, 0
                    Image:
                        id: img_side
                        source: 'images/side_button.png'
                        allow_stretch: True
                        keep_ratio: False
                        size: self.parent.size
                        pos: side_button_homepage.pos
        Screen:
            name: 'underover_screen'
            Image:
                source: 'images/screen_background.png'
                allow_stretch: True
                keep_ratio: False
            BoxLayout:
                spacing: '20dp'
                orientation: 'vertical'
                BoxLayout:
                    size_hint: 1, 0.10
                    Label:
                        size_hint: 0.10, 1
                        text: '#'
                        font_name: 'fonts/Lcd.ttf'
                        font_size: '30dp'
                        color: 1, 0.4, 0.769, 1
                    Label:
                        size_hint: 0.225, 1
                        text: 'T1'
                        font_name: 'fonts/Lcd.ttf'
                        font_size: '30dp'
                        color: 1, 0.4, 0.769, 1
                    Label:
                        size_hint: 0.225, 1
                        text: 'T2'
                        font_name: 'fonts/Lcd.ttf'
                        font_size: '30dp'
                        color: 1, 0.4, 0.769, 1
                    Label:
                        size_hint: 0.15, 1
                        text: 'G.A'
                        font_name: 'fonts/Lcd.ttf'
                        font_size: '30dp'
                        color: 1, 0.4, 0.769, 1
                    Label:
                        size_hint: 0.15, 1
                        text: '2.5'
                        font_name: 'fonts/Lcd.ttf'
                        font_size: '30dp'
                        color: 1, 0.4, 0.769, 1
                    Label:
                        size_hint: 0.15, 1
                        text: '3.5'
                        font_name: 'fonts/Lcd.ttf'
                        font_size: '30dp'
                        color: 1, 0.4, 0.769, 1
                BoxLayout:
                    size_hint: 1, 0.80
                    ScrollView:
                        bar_margin: '5dp'
                        bar_color: 1, 0.4, 0.769, 1
                        bar_width: '5dp'
                        bar_inactive_color: 1, 0.4, 0.769, 1
                        GridLayout:
                            id: gridsonuc
                            cols: 1
                            spacing: '50dp'
                            size_hint_y: None
                            height: self.minimum_height
                BoxLayout:
                    size_hint: 1, 0.10
                    Button:
                        id: home_button_underOver
                        on_press: root.homepage(img_home, sm)
                        background_color: 0, 0, 0, 0
                        Image:
                            id: img_home
                            source: 'images/home_button.png'
                            allow_stretch: True
                            keep_ratio: False
                            size: self.parent.size
                            pos: home_button_underOver.pos
                    Button:
                        id: side_button_underOver
                        on_press: root.side(img_side, sm)
                        background_color: 0, 0, 0, 0
                        Image:
                            id: img_side
                            source: 'images/side_button.png'
                            allow_stretch: True
                            keep_ratio: False
                            size: self.parent.size
                            pos: side_button_underOver.pos

How can i create GridLayout Dynamically and clear its widgets in this project?
What i tried:
I added a Gridlayout class to main.py
from kivy.uix.gridlayout import GridLayout
class Kafes(GridLayout):

    def __init__(self, **kwargs):
        super(Kafes, self).__init__(**kwargs)

What are the problems?

*

*How can i add these to Gridlayout class in Pure Python?
cols: 1
size_hint_y: None
height: self.minimum_height

*In class Predictor(BoxLayout):
def underOver_hesaplama(self, *args): function
adds all (box) boxlayout to Gridlayout with an ID
self.ids.gridsonuc.add_widget(box) in a for loop!
If i create a new Gridlayout class this time; there will be two different classes!
One class Predictor(BoxLayout):
Other class Kafes(GridLayout):
How can i add the widgets to another (class Kafes(GridLayout):) which are already created in  class Predictor(BoxLayout): > def underOver_hesaplama(self, *args): function?

*lastly how can i clear this widgets in Gridlayout Class?

Thanks very much


text:
Q: SSRS BIDS 2008 Bubble chart - Bubble size I am using SSRS BIDS 2008 to produce a bubble chart. My chart has around 80 bubbles that are sized on a certain field, however the majority of my bubbles are tiny with 5/6 being massive. I need to somehow adjust the sizing ranges and believe I do this by using BubbleSizeMin and BubbleSizeMax how ever I cannot find these fields anywhere. Can anyone tell me step by step how to get to these fields...? (I have tried right clicking on the bubble in design view, clicking 'Series Properties' and going through all these but cannot see the min/max options)

A: Some properties aren't exposed through the dialogs, but are still listed in the BIDS properties window. View -> Properties (or F4) will make this window visible if it isn't currently.
Below is a screen shot of BIDS with these properties shown.
I've run into situations though where setting the minimum bubble size wouldn't make the dots any smaller than the default size, so there seems to be some auto-calculation that can override these.


text:
Q: Why Eigen vector dot is slower than manual for loop I'm a newbie for eigen.
I test the eigen's vector dot performance, and found it's slower than manual for loop.
code as below:
#include <Eigen/Dense>
#include <iostream>
#include <vector>

int main()
{
  Eigen::VectorXf neu1 = Eigen::VectorXf::Random(100000000);
  std::vector<float> x(100000000);

  for(int i = 0; i < 100000000; ++i)
    x[i] = neu1[i];

  clock_t t1 = clock();
  float r = 0.0f;
  for(int i = 0; i < 100000000; ++i)
    r += x[i]*x[i];

  clock_t t2 = clock();
  std::cout<<"time: "<<t2-t1<<std::endl;

  t1 = clock();
  r = neu1.dot(neu1);
  t2 = clock();
  std::cout<<"time: "<<t2-t1<<std::endl;
}

The result is:
g++ test.cpp -otest -I/usr/local/include/eigen/
time: 1070000
time: 1910000

g++ test.cpp -otest -I/usr/local/include/eigen/ -Ofast -march=native
time: 0
time: 50000

And, #define EIGEN_NO_DEBUG seems has no effect.
I thought eigen should be optimized and had no reason slower than for loop.
Did I do something wrong?
Or, how can i optimize the eigen performance?
thx

A: You are not doing anything with the result of the first computation and assign to it afterwards. The first computation is optimized out entirely. You can fix this by printing the value of r after the computation:
#include <iostream>
#include <vector>
#include <eigen3/Eigen/Core>
#include <time.h>

int main()
{
  Eigen::VectorXf neu1 = Eigen::VectorXf::Random(100000000);
  std::vector<float> x(100000000);

  for(int i = 0; i < 100000000; ++i)
    x[i] = neu1[i];

  clock_t t1 = clock();
  float r = 0.0f;
  for(int i = 0; i < 100000000; ++i)
    r += x[i]*x[i];

  clock_t t2 = clock();
  std::cout<<"time: "<<t2-t1<<std::endl;
  std::cout << r << std::endl;

  t1 = clock();
  r = neu1.dot(neu1);
  t2 = clock();
  std::cout<<"time: "<<t2-t1<<std::endl;
  std::cout << r << std::endl;
  return 0;
}

Here is  a sample run produces:
/tmp $ g++ -Wall -Wextra -pedantic -O3 -std=c++14 bla.cpp
/tmp $ ./a.out
time: 272958
1.67772e+07
time: 29003
3.29441e+07

or
/tmp $ g++ -Wall -Wextra -pedantic -Ofast -std=c++14 bla.cpp
/tmp $ ./a.out
time: 29953
3.23292e+07
time: 28853
3.29441e+07

This change wont make your benchmark much better, but the results wont be horribly wrong anymore.
You still should consider average over multiple runs with different datasets. Also don't generate different test data for every run, because your results wont be reproducible.
Finally, as commented below, the difference in results is likely to be due to overflow and/or round-off error. It is suggested to change to double precision or reduce the length of the arrays and run the test again.

A: You're running into over-optimization: the compiler is smarter than you and optimizes out the loop calculation.
I get these timings on my machine:
time: 0
time: 23422

If you need to be sure something is read/written to in a benchmark, use volatile:
#include <Eigen/Dense>
#include <iostream>
#include <vector>

int main()
{
  Eigen::VectorXf neu1 = Eigen::VectorXf::Random(100000000);
  std::vector<float> x(100000000);

  for(int i = 0; i < 100000000; ++i)
    x[i] = neu1[i];

  clock_t t1 = clock();
  float temp = 0.0f;
  for(int i = 0; i < 100000000; ++i)
    temp += x[i]*x[i];
  volatile float result = temp;

  clock_t t2 = clock();
  std::cout<<"time: "<<t2-t1<<std::endl;

  t1 = clock();
  result = neu1.dot(neu1);
  t2 = clock();
  std::cout<<"time: "<<t2-t1<<std::endl;
}

Then, timings on my machine become:
time: 79060
time: 21542


text:
Q: Spring boot client and cloud config server HTTP authentication I'm configuring a spring boot 1.5.4 client with spring cloud config server 1.3.1.  The client and the server works without any authentication. However, I'm trying to configure HTTP Basic authentication which is not working. It continues to be accessible even without authentication when I reach the spring cloud config server URL over browser. I may be missing something fundamental.
My client bootstrap.properties file is

spring.application.name=service1
spring.cloud.config.uri=https://config.example.com
spring.cloud.config.username=username
spring.cloud.config.password=xxxx
spring.profiles.active=profile1,profile2
management.security.enabled=true

And my cloud config server application.properties looks like -

server.port=443
spring.application.name=spring-config
spring.cloud.config.server.git.uri=https://gitlab.com/services/service1.git
spring.cloud.config.server.git.username=serviceuser
spring.cloud.config.server.git.password=servicepass
spring.cloud.config.server.git.clone-on-start=true
security.user.name=username
security.user.password=xxxx
spring.cloud.config.server.health.enabled=false
spring.cloud.config.server.bootstrap=true
spring.cloud.config.server.prefix=/config

When I access `https://config.example.com/service1/label I do not get any sort of authentication but I do see my config service1-label.properties in JSON
Any help is appreciated!

A: To use the default Spring Boot configured HTTP Basic security, just include Spring Security on the classpath (e.g. through spring-boot-starter-security).


text:
Q: How to adjust line wrap formatting rules in Eclipse? I can't remember what it is called, as I am new to java, but I want to know where to find this in the Eclipse formatter. In my getBookData method, I want the stuff after the comma not start a new line.
package input;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFile {

    public static Object[] currentBookData;

    public static void getBookData() throws IOException {
        try (Stream<String> stream = Files.lines(Paths.get("C:/test.txt"), Charset.defaultCharset())) { // I want the stuff after the comma to be on the same line.
            currentBookData = stream.toArray();
        }

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

    }
}

A: Navigate:
"Window -> Preferences -> Java ->Code Style -> Formatter".

Adjust the existing template or create/import new one and use the same.
To change the max line width, select a profile and then navigate:
"Edit -> Line Wrapping"

and set a desired character length in "Maximum Line Width" field e.g. "100".


text:
Q: Pointwise convergence and uniform convergence of a sequence of functions Let $\{f_{n}\}_{n\geq 1}$ be a sequence of function given by $f_{n}(x)=\frac{1}{x}+\frac{1}{n}$. Does $f$ converge pointwise on $\mathbb{R}\setminus\{0\}$? Does $f$ converge uniformly $\mathbb{R}\setminus\{0\}$?
I think yes, to both since.
Pointwise convergence: $\{f_{n}(x)\}_{n\geq 1}$ converges for every $x\in\mathbb{R}\setminus\{0\}$ to $f(x)=\frac{1}{x}$.
Uniform convergence: Let $\epsilon > 0$ and take $N=\frac{1}{\epsilon}$. Then $|f_{n}(x)-f(x)|=\frac{1}{n}<\frac{1}{N}=\epsilon$ whenever $n>N$, which holds for every $x\in\mathbb{R}\setminus\{0\}$.
Alternatively; $\lim_{n\rightarrow\infty}\sup\{|f_{n}(x)-f(x)|\mid x\in\mathbb{R}\setminus\{0\}\}=0$.
Is this correctly done ?

A: Yes, your solution is correct.
You may wish to observe the following more general fact: if $f$ is any real-valued function and $(a_n)$ is a sequence of real numbers converging to zero, then the functions $f_n=f+a_n$ converge to $f$ uniformly.


text:
Q: Show the terms of a sequence $u_n$ is $0$. Given $u_n=\sum_{k=1}^{\infty} u_{n+k}^2$ and $\sum_{n=1}^{\infty}u_n$ converge. Show $u_k=0 \forall k \in \mathbb{N}$.
Remark:This sequence is not increasing as $u_n-u_{n+1}=u_{n+1}^2\geq0$.
It is bounded below by $0$.
If we can show $u_n=u_{n+1}$, we are done.
Help!

A: Note that $u_n=u_{n+1}+u_{n+1}^2$.
Thus, if for some $N$, $u_N=0$, we are done. Now we assume that $u$ is positive. Hence it is decreasing so converges to some $l \geq 0$ such that $l=l+l^2$ thus $l=0$.
Now, let $a < 0$ be a real number, then $u_{n+1}^a-u_n^a=u_{n+1}^a(1-(1+u_{n+1})^a)\sim -au_{n+1}^{a+1}$.
Take $a=-1$, then $u_{n+1}^a-u_n^a \rightarrow 1$, thus $u_n \sim 1/n$ and $\sum_n {u_n}=\infty$, a contradiction.


text:
Q: Universal ImageLoader java.io.EOFException I'm trying to fetch JSON data and display it in my ListView using ArrayAdapter. Anyways, in my adapter, I'm using Universal Image Loader from https://github.com/nostra13/Android-Universal-Image-Loader and the other data were loaded correctly except for the images. Some images were displayed correctly, some should not be on a specific item, and some were not loaded completely.
This is my calling fragment:
public class SampleFragment extends Fragment implements
    OnItemClickListener {

private ListView songsListView;
private ArrayList<String> list;
private ArrayAdapter<String> dataAdapter;
private View rootView;
private Button selectReferenceSong;
private Fragment memberFragment;
private String[] songsArray;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<ReferenceTracks> arrayOfList;
private String bufferString;

private static final String rssFeed = "https://dl.dropboxusercontent.com/u/32769459/reference_tracks.json";

private static final String TAG_MUSIC = "music";
private static final String TAG_SONG = "song";
private static final String TAG_TITLE = "title";
private static final String TAG_ARTIST = "artist";
private static final String TAG_DURATION = "duration";
private static final String TAG_THUMBURL = "thumb_url";

public SampleFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.sample_layout, container, false);

    songsListView = (ListView) rootView.findViewById(R.id.songsListView);
    songsListView.setOnItemClickListener(this);

    arrayOfList = new ArrayList<ReferenceTracks>();

    if (Utility.isNetworkAvailable(getActivity())) {
        new AsynchronousTask().execute(rssFeed);
    } else {
        Toast.makeText(getActivity().getApplicationContext(),
                "No Network Connection!", Toast.LENGTH_SHORT).show();
    }

    return rootView;
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub

}

/**
 *
 * @Asynchronous class
 */
public class AsynchronousTask extends AsyncTask<String, Void, String> {

    ProgressDialog pDialog;
    private RowAdapter objRowAdapter;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        return Utility.getJSONString(params[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (null == result || result.length() == 0) {
            Toast.makeText(getActivity().getApplicationContext(),
                    "No data found from web.", Toast.LENGTH_SHORT).show();
        } else {

            try {
                JSONObject topObject = new JSONObject(result);
                JSONObject musicObject = topObject.getJSONObject(TAG_MUSIC);
                JSONArray jsonArray = musicObject.getJSONArray(TAG_SONG);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject objJson = jsonArray.getJSONObject(i);

                    ReferenceTracks objItem = new ReferenceTracks();
                    objItem.setTitle(objJson.getString(TAG_TITLE));
                    objItem.setArtist(objJson.getString(TAG_ARTIST));
                    objItem.setDuration(objJson.getString(TAG_DURATION));
                    objItem.setThumbUrl(objJson.getString(TAG_THUMBURL));

                    arrayOfList.add(objItem);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            setAdapterToListview();

        }

    }

    public void setAdapterToListview() {
        objRowAdapter = new RowAdapter(getActivity(), R.layout.reference_song_list_item, arrayOfList);
        songsListView.setAdapter(objRowAdapter);
    }
}}

This is my custom Adapter:
public class RowAdapter extends ArrayAdapter<ReferenceTracks> {

private Context activity;
private ArrayList<ReferenceTracks> items;
private ReferenceTracks objBean;
private int row;
private ImageLoader imageLoader;
private DisplayImageOptions options;

public RowAdapter(Context act, int resource, ArrayList<ReferenceTracks> arrayList) {
    super(act, resource, arrayList);
    this.activity = act;
    this.row = resource;
    this.items = arrayList;
    imageLoader = ImageLoader.getInstance();
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    ViewHolder holder;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(row, null);

        holder = new ViewHolder();
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    if ((items == null) || ((position + 1) > items.size()))
        return view;

    objBean = items.get(position);

    holder.tvImage = (ImageView) view.findViewById(R.id.list_image);
    holder.tvTitle = (TextView) view.findViewById(R.id.title);
    holder.tvArtist = (TextView) view.findViewById(R.id.artist);
    holder.tvDuration = (TextView) view.findViewById(R.id.duration);
    holder.pbar = (ProgressBar) view.findViewById(R.id.progressbar);

    if (holder.tvImage != null) {
        if (null != objBean.getThumbUrl()
                && objBean.getThumbUrl().trim().length() > 0) {
            final ProgressBar pbar = holder.pbar;

            imageLoader.destroy();
            imageLoader.init(ImageLoaderConfiguration.createDefault(activity));
            imageLoader.displayImage(objBean.getThumbUrl(), holder.tvImage,
                    options, new ImageLoadingListener() {

                        @Override
                        public void onLoadingStarted(String imageUri,
                                View view) {
                            // TODO Auto-generated method stub
                            pbar.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onLoadingFailed(String imageUri,
                                View view, FailReason failReason) {
                            // TODO Auto-generated method stub
                            pbar.setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onLoadingComplete(String imageUri,
                                View view, Bitmap loadedImage) {
                            // TODO Auto-generated method stub
                            pbar.setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onLoadingCancelled(String imageUri,
                                View view) {
                            // TODO Auto-generated method stub

                        }
                    });

        } else {
            holder.tvImage.setImageResource(R.drawable.ic_launcher);
        }
    }

    if (holder.tvTitle != null && null != objBean.getTitle()
            && objBean.getTitle().trim().length() > 0) {
        holder.tvTitle.setText(Html.fromHtml(objBean.getTitle()));
    }
    if (holder.tvArtist != null && null != objBean.getArtist()
            && objBean.getArtist().trim().length() > 0) {
        holder.tvArtist.setText(Html.fromHtml(objBean.getArtist()));
    }
    if (holder.tvDuration != null && null != objBean.getDuration()
            && objBean.getDuration().trim().length() > 0) {
        holder.tvDuration.setText(Html.fromHtml(objBean.getDuration()));
    }

    return view;
}

public class ViewHolder {
    public ImageView tvImage;
    public ProgressBar pbar;
    public TextView tvTitle, tvArtist, tvDuration;
}}

While this is my application class:
public class SampleApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();

    DisplayImageOptions displayimageOptions = new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.ic_stub)
            .showImageOnFail(R.drawable.ic_error)
            .showImageForEmptyUri(R.drawable.ic_empty)
            .cacheInMemory()
            .cacheOnDisc()
            .bitmapConfig(Bitmap.Config.RGB_565)
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
            .build();

    File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
    .threadPoolSize(4)
    .threadPriority(Thread.NORM_PRIORITY)
    .tasksProcessingOrder(QueueProcessingType.LIFO)
    .defaultDisplayImageOptions(displayimageOptions)
    .discCacheSize(50 * 1024 * 1024)
    .discCacheFileCount(1000000)
    .memoryCache(new WeakMemoryCache())
        .build();
    ImageLoader.getInstance().init(config);
}}

This is also the log:
    06-24 11:18:12.935: E/ImageLoader(6428): null
06-24 11:18:12.935: E/ImageLoader(6428): java.io.EOFException
06-24 11:18:12.935: E/ImageLoader(6428):    at libcore.io.Streams.readAsciiLine(Streams.java:203)
06-24 11:18:12.935: E/ImageLoader(6428):    at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:561)
06-24 11:18:12.935: E/ImageLoader(6428):    at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:801)
06-24 11:18:12.935: E/ImageLoader(6428):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:274)
06-24 11:18:12.935: E/ImageLoader(6428):    at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:479)
06-24 11:18:12.935: E/ImageLoader(6428):    at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStreamFromNetwork(BaseImageDownloader.java:113)
06-24 11:18:12.935: E/ImageLoader(6428):    at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:84)
06-24 11:18:12.935: E/ImageLoader(6428):    at com.nostra13.universalimageloader.core.decode.BaseImageDecoder.getImageStream(BaseImageDecoder.java:84)
06-24 11:18:12.935: E/ImageLoader(6428):    at com.nostra13.universalimageloader.core.decode.BaseImageDecoder.decode(BaseImageDecoder.java:73)
06-24 11:18:12.935: E/ImageLoader(6428):    at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.decodeImage(LoadAndDisplayImageTask.java:290)
06-24 11:18:12.935: E/ImageLoader(6428):    at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:250)
06-24 11:18:12.935: E/ImageLoader(6428):    at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:131)
06-24 11:18:12.935: E/ImageLoader(6428):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-24 11:18:12.935: E/ImageLoader(6428):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-24 11:18:12.935: E/ImageLoader(6428):    at java.lang.Thread.run(Thread.java:856)

Were there any settings I made wrong or missed on my application class for the imageloader? I've been searching for the same exception but nothing seems getting close to the fix. Any help will do. Many thanks!

A: I'm working with Universal image loader for a long time. So, I prefer to have it's settings in a class then my application is able to access it simply.
This is setting class of Universal image loader. I have a utility package and this class is under this package. You are able to make corners of image curve by commenting out of lines in onLoadingComplete().
public class ImageDownloader {

    private static final  String TAG = "ImageDownloader";
    public static final String DIRECTORY_NAME = "YOUR_DIRECTORY_NAME";

    private static ImageDownloader instance = null;
    private ImageLoader imageLoader;

    protected ImageDownloader(Context context) {
        // Exists only to defeat instantiation.
        configImageDownloader(context);
    }

    public static ImageDownloader getInstance(Context context) {
        if(instance == null) {
            instance = new ImageDownloader(context);
        }
        return instance;
    }

    /**
     * This constructor will configure loader object in order to display image.
     * @param context
     */
    private void configImageDownloader(Context context) {

        File cacheDir = StorageUtils.getOwnCacheDirectory(context, DIRECTORY_NAME + "/Cache");

        // Get singleton instance of ImageLoader
        imageLoader = ImageLoader.getInstance();

        // Create configuration for ImageLoader (all options are optional)
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).denyCacheImageMultipleSizesInMemory()
                .memoryCache(new UsingFreqLimitedMemoryCache(4 * 1024 * 1024))
                .discCache(new UnlimitedDiscCache(cacheDir))
                .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
                .defaultDisplayImageOptions(
                        new DisplayImageOptions.Builder()
                                .showStubImage(R.drawable.ic_default_logo)
                                .resetViewBeforeLoading()
                                .cacheInMemory()
                                .cacheOnDisc()
                                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                                .build())
                .tasksProcessingOrder(QueueProcessingType.FIFO)
                .build();

        // Initialize ImageLoader with created configuration.
        imageLoader.init(config);
    }

    public void displayImage(final ImageView imageView, String imageURI) {
        if(imageView == null  ||  imageURI == null) {
            Log.e(TAG, "Either of image view or image uri is null");
            return;
        }

        // Load and display image
        imageLoader.displayImage(imageURI, imageView, new ImageLoadingListener() {

            @Override
            public void onLoadingStarted(String imageUri, View view) {}

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {}

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//                Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
//                imageView.setImageBitmap(getRoundedCornerBitmap(bitmap, 30));
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {}
        });
    }

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
}

In your adapter class, first you need move all definitions into if (view == null) {...}method. My sample adapter which is like this. You can ignore my listener which is because of a button that I have in my each row.
public class MyCrowdAdapter extends BaseAdapter {

    public interface OnCrowdRemoveUserListener {
        public void OnRemoveUserClicked(User user);
    }

    private final String TAG = "*** MyCrowdAdapter ***";

    private Context context;
    private OnCrowdRemoveUserListener listener;
    private LayoutInflater myInflater;
    private ImageDownloader imageDownloader;
    private List<User> userList;

    public MyCrowdAdapter(Context context) {
        this.context = context;
        myInflater = LayoutInflater.from(context);

        imageDownloader = ImageDownloader.getInstance(context);
    }

    public void setData(List<User> userList) {
        this.userList = userList;

        Log.i(TAG, "List passed to the adapter.");
    }

    @Override
    public int getCount() {
        try {
            return userList.size();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = myInflater.inflate(R.layout.list_my_crowd_row, null);
            holder = new ViewHolder();

            Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/ITCAvantGardeStd-Demi.ttf");
            holder.tvUserName = (TextView) convertView.findViewById(R.id.tvUserName);
            holder.tvUserName.setTypeface(font);
            holder.ivPicture = (ImageView) convertView.findViewById(R.id.ivPicture);
            holder.btnRemove = (Button) convertView.findViewById(R.id.btnRemove);
            holder.btnRemove.setFocusable(false);
            holder.btnRemove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Integer pos = (Integer)v.getTag();
                    Log.i(TAG, "Item: " + pos);
                    listener.OnRemoveUserClicked(userList.get(pos));
                }
            });

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.btnRemove.setTag(position);
        holder.tvUserName.setText(userList.get(position).getFirstName());
        imageDownloader.displayImage(holder.ivPicture, userList.get(position).getProfilePictureUrl());

        return convertView;
    }

    public void setOnRemoveClickedListener(OnCrowdRemoveUserListener listener) {
        this.listener = listener;
    }

    static class ViewHolder {
        TextView tvUserName;
        ImageView ivPicture;
        Button btnRemove;
    }
}

One suggestion, instead of validation like this:
if (holder.tvTitle != null && null != objBean.getTitle()
            && objBean.getTitle().trim().length() > 0) {...}
simply use TextUtils which is static method, like this:
if(!TextUtils.isEmpty(objBean.getTitle);
===========
Update
===========
About your question regard displaying progressbar on top of image:
It's simple and complex :) there are two ways,
1st way is based on your code:
1-define an interface inside ImageDownloader class like my interface inside adapter. should be something like this:
public interface OnImageDownloaderListener {
    public void OnDownloadStarted();
    public void OnDownloadFinished();
}

2- Declare it in decleration part
OnImageDownloaderListener listener;

3- Change thosr two listeners like this
@Override
            public void onLoadingStarted(String imageUri, View view) {
        listener.OnDownloadStarted();
}

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//                Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
//                imageView.setImageBitmap(getRoundedCornerBitmap(bitmap, 30));
        listener.OnDownloadFinished();
            }

4- Add this method to ImageDownloader class
public void setOnImageDownloaderListener(OnImageDownloaderListener listener) {
        this.listener = listener;
    }

5- In your adapter and below this line:
imageDownloader = ImageDownloader.getInstance(context);

implement those two methodes like this:
imageDownloader.setOnImageDownloaderListener(new ImageDownloader.OnImageDownloaderListener{
    @Override
    public void OnDownloadStarted() {
        pbar.start();
    }

    @Override
    public void OnDownloadFinished(){
        pbar.stop();
    }
}
);

It should help you. However, if I were you I does second approach which is creating new component. The component includes two views an image view and progressbar on top (same to what you have currently). Then add all above method inside that component class. So, easily through your app you in whatever activity you want you can add your view and just pass URL then the component is responsible to display progressbar and stop it. Based on your code if you have 10 similr activities you need to copy/paste above code.
Hope it helps you :)


text:
Q: change cell styling in KendoGrid Just discovered the KendoGrid and was trying to change the style of an individual column(cell) after changing another cellvalue. For example I have a grid with a shipname and shipcity column. Suppose I have a business rule that says :
'Make shipcity cell value disabled when the shipname on the same row has the same value'

I found this sample which uses the blur event which I probably use, what would be a good way of implementing this rule?
Also nice to know your opinion in relation to asp.net mvc integration.
jsfiddle link:http://jsfiddle.net/dingen2010/begjT/1/

A: Updated the link:
You can try the updated fiddle example here

A: Basically conditional editor templates are not supported out of the box. You have two options.
Either use the edit event of the Grid find the editor inside e.containder and disable it the way it needs to be (if using Kendo widget use the enable(false) method, or add the readonly attribute if regular input).
The other options is to define custom editor like demonstrated in this JsBin example.


text:
Q: Exclude all 0s in foreach count I want to update all my custom_field by giving specific number to each of my posts. Problem : I don't want to add numbers with 0 inside.
$i = 1; // Start from 1

if ($ajax_query->have_posts()) :
    while ($ajax_query->have_posts()) :
        $ajax_query->the_post();

        update_post_meta( get_the_ID(), 'the_custom_field', $i++ );
        // $i++ will be the specific number for each my post.

    endwhile;
endif;

Now, my post 1 has the_custom_field 1, my post 2 has the_custom_field 2.... my post 10 has the_custom_field 10
But it should be this way :

*

*the_custom_field of post1 should be 1

*the_custom_field of post2 should be 2

*the_custom_field of post3 should be 3

*...

*the_custom_field of post10 should be 11

*the_custom_field of post11 should be 12
etc

A: <?php

if ($ajax_query->have_posts()) :
    while ($ajax_query->have_posts()) :
        $ajax_query->the_post();

        update_post_meta( get_the_ID(), 'the_custom_field', $i++);
        while (strpos(strval($i),'0') !== false):
            $i++;
        endwhile;

    endwhile;
endif;

Well, once we assign the ID, we run a while loop afterwards till the time we get a value which doesn't contain the 0.


text:
Q: Compute $\lim \limits_{n\to \infty} n^{1/n}$ Two part question that I want to make sure I did correctly.
a) Let $x_n = \sqrt[n]{n} - 1$. Use the fact that $(1 + x_n)^n = n$ to show that $x_n^2 \leq \frac{2}{n}$.
Hint given to use the binomial theorem and throw away most terms.
Expanding $(1+x_n)^n$ using the binomial theorem gives us ${{n}\choose{0}}x_n^{n-0}1^0 + {{n}\choose{1}}x_n^{n-1}1^1 + \cdots + {{n}\choose{n}}x_n^{0}1^n = n$.
Want to show $x_n^2 \leq 2/n$, that is $(\sqrt[n]{n} - 1)^2 \leq \frac{2}{{{n}\choose{0}}x_n^{n-0}1^0 + {{n}\choose{1}}x_n^{n-1}1^1 + \cdots + {{n}\choose{n}}x_n^{0}1^n}$ or $n^{2/n} - 2\sqrt[n]{n} + 1\leq {{n}\choose{0}}x_n^{n-0}1^0 + {{n}\choose{1}}x_n^{n-1}1^1 + \cdots + {{n}\choose{n}}x_n^{0}1^n$ which we can see is true by getting rid of the right terms
b) Compute $\lim \limits_{n\to \infty} n^{1/n}$
Using our inequality in part a), we can use Squeeze Theorem to compute the limit.
We have $1^{1/n} \leq n^{1/n} \leq 2/n + 1$
Since $1^{1/n} \rightarrow 1$ and $2/n +1 \rightarrow 1$, we have that $ n^{1/n} \rightarrow 1$.
So $\lim \limits_{n\to \infty} n^{1/n} = 1$.
Just wanted to double check this.

A: You do not really need the binomial theorem. For any $n\geq 2$ we have
$$ n = \frac{n}{n-1}\cdot\frac{n-1}{n-2}\cdot\ldots\cdot\frac{2}{1}\cdot \frac{1}{1}\tag{1}$$
hence $n^{1/n}$ is the geometric mean of $1,1+1,1+\frac{1}{2},\ldots,1+\frac{1}{n-1}$, which by the AM-GM inequality is less than
$$ \frac{1}{n}\left[1+\sum_{k=1}^{n-1}\left(1+\frac{1}{k}\right)\right]=1+\frac{H_{n-1}}{n}\leq 1+\frac{1+\int_{1}^{n}\frac{dx}{x}}{n}=1+\frac{1+\log(n)}{n}\tag{2} $$
but clearly greater than one. Squeezing then leads to $\lim_{n\to +\infty} n^{1/n}=1$, as expected from the fact that this limit equals $\exp\lim_{n\to +\infty}\frac{\log n}{n}$.

A: Here is a slight modification of the approach given by the hints:
Note that
$$
\begin{align}
\left(1+\sqrt{\frac2n}\right)^n
&\ge1+\binom{n}{1}\sqrt{\frac2n}+\binom{n}{2}\frac2n\tag{1a}\\
&=n+\sqrt{2n}\tag{1b}\\[6pt]
&\ge n\tag{1c}
\end{align}
$$
Explanation:
$\text{(1a)}$: truncation of the Binomial Theorem
$\text{(1b)}$: $\binom{n}{1}\sqrt{\frac2n}=\sqrt{2n}$ and $\binom{n}{2}\frac2n=n-1$
$\text{(1c)}$: $\sqrt{2n}\ge0$

Relation to the hint: $(1)$ and the definition of $x_n$ imply
$$
(1+x_n)^n=n\le\left(1+\sqrt{\frac2n}\right)^n\tag2
$$
$(2)$ says that $x_n\le\sqrt{\frac2n}$ .

Taking the $n^\text{th}$ root of $(1)$ yields
$$
1\le n^{1/n}\le1+\sqrt{\frac2n}\tag3
$$
and by the Squeeze Theorem,
$$
\lim_{n\to\infty}n^{1/n}=1\tag4
$$


text:
Q: Why math.pi and math.e constants are written in lowercase in Python? In most Python modules the constants are written in uppercase, i.e.:
datetime module:

*

*datetime.MINYEAR

*datetime.MINYEAR
locale module:

*

*locale.LC_MONETARY

*locale.LC_TIME

*locale.DAY_1
os module:

*

*os.PRIO_PGRP

*os.PRIO_USER
But in the math module, the only 2 constants that has in it are written in lowercase:
math.pi and math.e.
This could be explained if the math module were a third party library, but it isn't, it's a part of the standard library.
Yes, I know that in Python there aren't authentic constants, but this is style writting is used in most modules as said by the PEP 8
So, why these two constants aren't written in uppercase in Python?  Are there any reason for it?

A: PEP 8 was created on 05-Jul-2001, whereas these constants exist at least since 1990, as can be seen in this initial revision of math module implementation. tobias_k in his comment made a good guess IMHO, that lowercase in this case seems more natural from mathematician's point of view. Another possible reason is that Python was heavily influenced by the ABC programming language, in which pi is also lowercase (reference).
Still I think you're right that this is an inconsistency with commonly accepted coding style rules (as they are nowadays), present not only in Python.
Note also that it's not the only inconsistency, PEP 8 mentions also the threading module being not consistent with the guidelines in terms of Function names:

mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

The obvious reason not to fix this is, as noted by jonrsharpe in his comment, is also mentioned in PEP 8:

In particular: do not break backwards compatibility just to comply with this PEP!

Probably it would be a good idea to add aliases that conform to the guidelines, as the OP have mentioned in the comment below.

A: You could always submit a proposal to introduce uppercase aliases for math.eand math.pi.
Since in mathematics e and pi are lowercase, I suggest math.LOWERCASE_E and math.LOWERCASE_PI.


text:
Q: BingMaps Is it possible to disable clustering below certain zoom level? My map pushpins are relatively close to each other and even on a big zoom I still see them clustered.
I solved this issue by spreading the clustered pushpins by some random distance 5-10 meters.
I need more accurate solution so my idea is to disable the clustering below the certain zoom level, but I didn't find any way how to do it.

A: There is no option to disable clustering in the clustering layer in Bing Maps, but what you can do is monitor the zoom level of the map, and when it gets to a certain point, hide the cluster layer and load a new layer that isn't clustered. Unfortunately this means having two copies of your data in memory.
If you haven't fully committed to using the Bing Maps platform, you may also want to take a look at Azure Maps. The Azure Maps web SDK does things a bit differently where you would keep your data in a single data source and attach rendering layers to it. Clustering is turned on in the data source and has a max zoom level option for clustering.
Here is some examples: https://azuremapscodesamples.azurewebsites.net/index.html?search=cluster
Here is documentation: https://learn.microsoft.com/en-us/azure/azure-maps/clustering-point-data-web-sdk

A: There is an option clusteringEnabled now on ClusterLayerOptions which will disable clustering without losing the whole layer.
eg:
  Microsoft.Maps.Events.addHandler(this.map, 'viewchangeend', () => {
              // de-cluster at highest zoom level
              this.clusterLayer?.setOptions({
                clusteringEnabled:
                  this.map.getZoom() < this.map.getZoomRange().max
              });
            });


text:
Q: "400 Bad Request" exception error with optional parameter using JQuery Ajax with Web API I read the ASP.NET documentation and I'm getting there but I get "400 Bad Request" exception error that I do not understand.
What is it about the "optional parameter" error, that cause exception error and what's the workaround to it?  The exception error is
--snip--
{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Post(Int32)' in 'BIO.Dealer.WebApp.WebApi.Member.AmazonServerDigitalLoanJacketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."}
--snip--
Source code below.
//Web API Config
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "MemberApi",
            routeTemplate: "WebApi/Member/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

//JQuery
var jsonRequest = { "Id": 3, "Name": "Scott Fletcher"};

$.ajax({
    type: "POST",
    async: false, /*false, //This need to be synchronous to the client can wait for webserver response...*/
    url: https://localhost:44301/WebApi/Member/AmazonServerDigitalLoanJacket/Upload",
    data: JSON.stringify(jsonRequest),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (parmData, parmTextStatus, parmXmlHttpRequest) {
        //alert("AjaxStatus: " + parmTextStatus + "\nReadyState - " + parmXmlHttpRequest.readyState + "\nStatus: " + parmXmlHttpRequest.status + "\nStatusText: " + parmXmlHttpRequest.statusText + "\nResponseText: " + parmXmlHttpRequest.responseText);
        jsonResponse = parmData;
    },
    error: function (parmXmlHttpRequest, parmTextStatus, parmErrorThrown) {
        //alert("AjaxStatus: " + parmTextStatus + "\nReadyState - " + parmXmlHttpRequest.readyState + "\nStatus: " + parmXmlHttpRequest.status + "\nStatusText: " + parmXmlHttpRequest.statusText + "\nResponseText: " + parmXmlHttpRequest.responseText);
    }
});

//Web API Controller
public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class AmazonServerDigitalLoanJacketController : ApiController
{
    [ActionName("Upload")]  //Upload File(s)...
    [HttpPost]
    public string Post(Foo parmFoo)
    {
        return "object of ID " + parmFoo.Id.ToString() + " (Upload) & Name: " + parmFoo.Name;
    }
}

A: You are passing multiple parameters when your method only accepts one. But it chokes on the default route before that. Put those data values in a form and serialize it so it may be interpreted as the object you expect. Otherwise ask for 2 parameters, an int id and a string name, then you can create the object yourself.


text:
Q: Rails: cannot load such file - spec.rb I'm working through chapter 9 of Hartl's rails tutorial.  I just added some tests for the 'edit' page, but it won't run on the command line.
I'm trying to run 'bundle exec rspec spec/requests/user_pages_spec.rb -e "edit page"'
I think there may be a problem with my user_pages_spec.rb . I might have too many 'end' at the bottom.
C:\Sites\sample_app>bundle exec rspec spec/requests/user_page_spec.rb -e "edit p
age"
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec
/core/configuration.rb:819:in `load': cannot load such file -- C:/Sites/sample_a
pp/spec/requests/user_page_spec.rb (LoadError)
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-2.1
3.1/lib/rspec/core/configuration.rb:819:in `block in load_spec_files'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-2.1
3.1/lib/rspec/core/configuration.rb:819:in `each'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-2.1
3.1/lib/rspec/core/configuration.rb:819:in `load_spec_files'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-2.1
3.1/lib/rspec/core/command_line.rb:22:in `run'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-2.1
3.1/lib/rspec/core/runner.rb:80:in `run'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-2.1
3.1/lib/rspec/core/runner.rb:17:in `block in autorun'

user_pages_spec.rb
require 'spec_helper'

describe "User pages" do

  subject { page }

  describe "profile page" do
    let(:user) { FactoryGirl.create(:user) }
    before { visit user_path(user) }

    it { should have_content(user.name) }
    it { should have_title(user.name) }
  end

  describe "signup page" do
    before { visit signup_path }

    it { should have_content('Sign up') }
    it { should have_title(full_title('Sign up')) }
  end

  describe "signup" do

    before { visit signup_path }

    let(:submit) { "Create my account" }

    describe "with invalid information" do
      it "should not create a user" do
        expect { click_button submit }.not_to change(User, :count)
      end
    end

    describe "with valid information" do
      before do
        fill_in "Name",         with: "Example User"
        fill_in "Email",        with: "user@example.com"
        fill_in "Password",     with: "foobar"
        fill_in "Confirmation", with: "foobar"
      end

      it "should create a user" do
        expect { click_button submit }.to change(User, :count).by(1)
      end

      describe "after saving the user" do
        before { click_button submit }
        let(:user) { User.find_by(email: 'user@example.com') }

        it { should have_link('Sign out') }
        it { should have_title(user.name) }
        it { should have_selector('div.alert.alert-success', text: 'Welcome') }
      end
  describe "edit" do
    let(:user) { FactoryGirl.create(:user) }
    before { visit edit_user_path(user) }

    describe "page" do
      it { should have_content("Update your profile") }
      it { should have_title("Edit user") }
      it { should have_link('change', href: 'http://gravatar.com/emails') }
    end

    describe "with invalid information" do
      before { click_button "Save changes" }

      it { should have_content('error') }
    end
  end
 end
 end
end

gemfile
source 'https://rubygems.org'
ruby '2.0.0'
#ruby-gemset=railstutorial_rails_4_0

gem 'rails', '4.0.8'
gem 'bootstrap-sass', '2.3.2.0'
gem 'sprockets', '2.11.0'
gem 'bcrypt-ruby', '3.1.2'
gem 'faker', '1.1.2'
gem 'will_paginate', '3.0.4'
gem 'bootstrap-will_paginate', '0.0.9'

group :development, :test do
  gem 'sqlite3', '1.3.8'
  gem 'rspec-rails', '2.13.1'
  # The following optional lines are part of the advanced setup.
  # gem 'guard-rspec', '2.5.0'
  # gem 'spork-rails', '4.0.0'
  # gem 'guard-spork', '1.5.0'
  # gem 'childprocess', '0.3.6'
end

group :test do
  gem 'selenium-webdriver', '2.35.1'
  gem 'capybara', '2.1.0'
  gem 'factory_girl_rails', '4.2.0'
  gem 'cucumber-rails', '1.4.0', :require => false
  gem 'database_cleaner', github: 'bmabey/database_cleaner'

  # Uncomment this line on OS X.
  # gem 'growl', '1.0.3'

  # Uncomment these lines on Linux.
  # gem 'libnotify', '0.8.0'

  # Uncomment these lines on Windows.
gem 'rb-notifu', '0.0.4'
gem 'wdm', '0.1.0'
end

gem 'sass-rails', '4.0.1'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.1'
gem 'jquery-rails', '3.0.4'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'

group :doc do
  gem 'sdoc', '0.3.20', require: false
end

group :production do
  gem 'pg', '0.15.1'
  gem 'rails_12factor', '0.0.2'
end

A: I can see that you're executing the wrong file:
Change this:
bundle exec rspec spec/requests/user_page_spec.rb -e "edit p
age"

To:
bundle exec rspec spec/requests/user_pages_spec.rb -e "edit p
age"

A: It should be
bundle exec rspec spec/requests/user_pages_spec.rb

as your file is user_pages_spec.rb


text:
Q: What is the meaning of the ^[OP in terminal? Ok-- so I've got a mystery on my hands.
I'm currently manually PXE installing via IPMI, working in the terminal, and throughout the process of watching the terminal display information regarding the installation, I keep seeing ^[OP being repeated over and over--like someone is sitting on the keyboard.
The closest I've gotten to discovering what key this could be is this question
However, I can find no documentation of what the OP portion represents.
This happens on multiple devices I've used with different keyboards, so it is not a keyboard malfunction. It also does not occur on other machines running the same installers.
Any insight would be greatly appreciated!
EDIT: (expanding off of the accepted answer) Ok so extension on the mystery. I'm pretty sure these codes only return if the system does not know how to deal with the input. It only shows up at a random point during the installation--and when I try to hit the F1 key to force the ^[OP to show up, it does not (where the arrow keys will continue to show ^[[A, etc.) This would lead me to believe it is able to handle the F1 key somewhere within the boot (to be expected for a boot program). Any explanation on how this mystery location could be getting the character code to show up?

A: It is a representation of the F1 key...
Try for instance to execute a arbitrary command that hangs your terminal and then press F1. For example:
root@martinipc:somewhere/# read
^[OP^[OP^[OP

As you see i pressed F1 3 times and then ^[OP appeared 3 times.
Maybe your machine required you to press the F1 key before the point you are running, or maybe there is a temporary problem with the keyboard detection in the mother board, that is emulating the press of the F1 key.
Another possibility occurs if you pressed it only one time, but the system is with a lot of lag..  this can causes this strange behavior too, you press a and get something like aaaaaaaa.


text:
Q: What is `Cat.name` in NestJS mongoose docs? Reading the NestJS docs on the MongoDB technique, I've came along a confusing example:
@Injectable()
export class CatsService {
  constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}

  async create(createCatDto: CreateCatDto): Promise<Cat> {
    const createdCat = new this.catModel(createCatDto);
    return createdCat.save();
  }

  async findAll(): Promise<Cat[]> {
    return this.catModel.find().exec();
  }
}

The line that confuses me is the constructor one; where to @InjectModel is given Cat.name. But, in the cats.schema.ts file, there's no inheritance from another class, nor any valorised static property with that name:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type CatDocument = Cat & Document;

@Schema()
export class Cat {
  @Prop()
  name: string;

  @Prop()
  age: number;

  @Prop()
  breed: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);

Am I missing something or could it be a "bug" in the docs?

A: Cat.name in this case refers to the inherent static property name that all classes have (really all functions have). This gives us a built in constant that we can refer to without having to write our own, but if you'd prefer you can use the string 'Cat' as well. In this case, Cat.name is the string 'Cat', just a different way to reference it that is built in to all classes (and functions).
JavaScript docs on Function.name