text:
Q: Karma doesn't find files specified in config file I'm writing Jasmine tests to my Angularjs app.
I generated karma.conf.js using karma init but when I run karma start i get warnings like this:
WARN [web-server]: 404: /bower_components/angular/angular.js
WARN [web-server]: 404: /js/app.js

karma.conf.js is in my app folder, which is the place for the bower_components folder as well.
I think maybe that could be because of my local test server where I'm using this approach: https://github.com/mhevery/angular-node-socketio
(I've been able to set up the tests like this in other project without a test server)
Can anybody please point me in the right direction here?

Update:
My karma.conf.js looks like this:
module.exports = function(config) {
  config.set({
    basePath: '.',
    frameworks: ['jasmine', 'requirejs'],
    files: [
      'tests/*.js',
      'js/*.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/angular-resource/angular-resource.js',
      'bower_components/d3/d3.js'
    ],
    exclude: [],
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    captureTimeout: 60000,
    singleRun: false
  });
};

Here's my directory structure:

A: Now that you've fixed the basepath (from '.' to '', see question comments above), you should change the order of files loading in your karma.conf.js :
module.exports = function(config) {
  config.set({
    basePath: '.',
    frameworks: ['jasmine', 'requirejs'],
    files: [
      //load angular.js first
      //(unless if you use jQuery which must be first if I remember well)
      'bower_components/angular/angular.js',
      //Then angular-modules
      'bower_components/angular-resource/angular-resource.js',
      'bower_components/angular-mocks/angular-mocks.js',
      //Other libs
      'bower_components/d3/d3.js',
      //Your app scripts
      'js/*.js',
      //And your specs
      'tests/*.js'
    ],
    exclude: [],
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    captureTimeout: 60000,
    singleRun: false
  });
};

You can find more info here: http://karma-runner.github.io/0.10/config/files.html

Ordering

*

*The order of patterns determines the order of files in which they are included in the browser.

*Multiple files matching a single pattern are sorted alphabetically.

*Each file is included exactly once. If multiple patterns match the same file, it's included as if it only matched the first pattern.

A: Your problem is probably the order you're loading your files in.
You may need to change the order to something like:
files: [
  'bower_components/angular/angular.js',
  'bower_components/angular-mocks/angular-mocks.js',
  'bower_components/angular-resource/angular-resource.js',
  'bower_components/d3/d3.js',
  'js/*.js',
  'tests/*.js'
],


text:
Q: Add user to database collection users after a verified email address in Firebase in my App, I use firebase database and the auth-service for new registrations.
The new user will be added to the authentification users-list, but there is still one missing part. The new user won't be added to database collection 'users'.
Is there any service in firebase to add new users to the database if they have the status emailVerified: true or do I have to do this on the client side? Thank you for your hints!
SendVerificationMail() {
  // Email verification when new user register
  return this.ngFireAuth.auth.currentUser.sendEmailVerification() .then(()=> {
    this.router.navigate(['verify-email']);
  })
}

SetUserData(user) {
  const userRef: AngularFirestoreDocument<any>=this.afStore.doc(`users/$ {
    user.uid
  }
  `);
  const userData: User= {
    uid: user.uid, email: user.email, displayName: user.displayName, photoURL: user.photoURL, emailVerified: user.emailVerified
  }
  return userRef.set(userData, {
    merge: true
  }
  )
}

A: If you are asking if there is a way to make a change to the database as soon as the user's email becomes verified, then no, there is no hook or trigger for that.  You will have to arrange for some code to check if the flag is set in Firebase Auth, then update the database as needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error Displaying On Wsod Yet Failing To Display Contents After Successful Redirect Please can someone help. When users send details through registration form or signin form,  if details are valid, it works fine, but if it invalid. The errors displays on a white page.. The white page is not empty, but displays the error I set.. It redirects to my URL.. Just doesn't show any other content apart from the error.. Please is there anyway to go about it.. I checked the error log in my Apache log files. There's no error reporting there.. I'm super confused
I have also tried using
error_reporting(E_ALL);
ini_set("display_errors", TRUE);
ini_set("display_startup_errors",TRUE);
ini_set("html_errors",0);

Still nothing is showing..
Tried using a hack around it by changing
header("Location: $comeFrom");
echo "MY ERROR HERE"
die;

To
header("refresh:0; url=$comeFrom");
echo "MY ERROR HERE"
die;

which simply shows the same WSOD with my error briefly and redirects as supposed, but I want the error to show after the page loads not before. Which is impossible for me.
Please someone help me.. Really frustrated
P. S.
$comeFrom = $_SERVER['HTTP_REFERER'];

Still tried to redirect to the index page.. Same issue..
This is my search.php file
<?php
session_start();
include_once('db.php');
if(!isset($_GET['page']) or $_GET['page']==0 or !preg_match("/^[1-9]*$/", $_GET['page'])){
header("Location: search.php?q=$_GET[q]&page=1");
}else{
$page = $_GET['page'];
}

if (isset($_GET['q']) and !empty($_GET['q'])){
$search=stripslashes(mysqli_real_escape_string($conn,$_GET["q"]));
$do="INSERT INTO search_terms".
"(terms)".
"VALUES".
"('$search')";
mysqli_query ($conn,$do);

}else{
header ("Location: index.php");
}
$pagetitle = "Search";
include_once('includes/header.php');
include_once('includes/log_reg.php');

?>

<button id="goback" onclick="back()" type="button">Go back</button>
<button id="goforward" onclick="forward()" type="button">Go Forward</button>

<button class="tablinks" id="defaultOpen" onclick="openTab(event,'Products')">Properties</button>
<button class="tablinks" onclick="openTab(event, 'Forum')">Forum</button>
<button class="tablinks" onclick="openTab(event, 'Users')">Users</button>

<?php
include_once('db.php');
$per_page=6;
$start = (($page - 1) * $per_page);
$sql="SELECT * FROM table LIKE '%$search%'";
$pages_query=mysqli_query($conn,$sql) or die("Bad Query: $sql");
$number = mysqli_num_rows($pages_query);
$number = number_format($number);
ceil($pages = $number/$per_page);

$sql2="SELECT * FROM table LIMIT $start,$per_page";
$result = mysqli_query ($conn,$sql2);
if ($number == 0) {
echo " ";}else{
   if($page > 1){
      echo "FIRST";
      if ($page > 2){
      echo "≪";
      }
      echo "<";
  }
 }
 $skipped = false;

 for ($i = 1; $i <= $pages + 1; $i++) {
 if ($page == $i){
     echo "".$i."";
 }else{
     if ($i < 1 || ($pages) - $i < 1 || abs($page - $i) < 2) {
         if($skipped)
             echo ' ... ';
         $skipped = false;
echo "".$i."";
}else{
$skipped = true;
}
}
}
if ($number == 0) {
echo "";
}else{
if($page < $pages){
      echo ">";
      if ($page < ($pages - 1)){
      echo "≫";
      }
      echo "LAST";
  }
if ($page == 1){
 if ($number < $per_page ) {
 echo "
 Current page: $page (Showing 1-$number of $number results)";
 }else{
 echo "
 Current page: $page (Showing 1-$per_page of $number results)";
 }}elseif ($page > 1){
if ($page == ceil($pages)) {
     if ($number % 2 == 1){
         if($page = $pages){
             $cal = $number % $per_page;
             $cal2 = ($number - $cal) + 1;
             echo "
 Current page: ". ceil($page). " (Showing result ".$cal2. "-".($number)."  of $number)";
         }else{
  echo "
 Current page: $page (Showing ".($start + 1)."-".($start + ($per_page - 1)) ." of $number)";
     }}elseif ($number % 2 == 0 and $page=$pages){
             $cal = $number % $start;
             $cal2 = ($number - $cal) + 1;
             echo "
 Current page: ".ceil($page)." (Showing result ".$cal2. "-".($number)."  of $number)";
             }elseif ($number % 2 == 0){
    echo "
 Current page: $page (Showing ".($start + 1)."-". ($start + ($per_page)) ." of $number)";
     }
}else{
    echo "
 Current page: $page (Showing ".($start + 1)."-".($start + $per_page) ." of $number)";
}
}
}

if ($number>0){
    echo "
" .$number. " results found for '$search' in
";
}       else{
    echo "
" .$number. " results found for '$search'. Try a   different search term
";
}
echo "
tab 1
";
echo "
"
?>
<?php
            while($row=mysqli_fetch_assoc($result)){
                $calc = round(3/2.7, 1);
?>

 //results here

<?php } ?>

my header include file from above code contains this
<?php
$root= $_SERVER['DOCUMENT_ROOT'];
include($root."/db.php");
$prefix = 'http://'.$_SERVER['SERVER_NAME'].'/';
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set('html_errors', 0);
if (isset($_POST['login'])){
require_once($root."/Hostels/login.inc.php");
}if (isset($_POST['register'])){
    require_once($root."/Hostels/register.inc.php");
}
?>

And my log_reg include is more like a pop_up login file which was included on all pages and on submision requires the register.inc.php file below
This is my register.inc.php FILE
<?php
include('db.php');
$comeFrom = $_SERVER['HTTP_REFERER'];

//session variables to be diaplayed on the profile
if ($_SERVER["REQUEST_METHOD"]==="POST"){
$_SESSION['username']=$_POST['username'];
$_SESSION['firstname']=$_POST['firstname'];
$_SESSION['lastname']=$_POST['lastname'];
$_SESSION['email']=$_POST['email'];
$_SESSION['gender']=$_POST['gender'];
$_SESSION['state']=$_POST['state'];
$_SESSION['dob']=$_POST['dob'];
$user['user_id']=@$_SESSION['user_id'];

//escaping the strings

$username=mysqli_real_escape_string($conn,$_POST['username']);
$firstname=mysqli_real_escape_string($conn,$_POST['firstname']);
$lastname=mysqli_real_escape_string($conn,$_POST['lastname']);
$email=mysqli_real_escape_string($conn,$_POST['email']);
$gender=mysqli_real_escape_string($conn,$_POST['gender']);
$state=mysqli_real_escape_string($conn,$_POST['state']);
$dob=mysqli_real_escape_string($conn,$_POST['dob']);
$password=mysqli_real_escape_string($conn,password_hash($_POST['password'],PASSWORD_BCRYPT));
$hash=mysqli_real_escape_string($conn,md5(uniqid(rand())));
$result=mysqli_query($conn,"SELECT * FROM users WHERE email='$email' OR   username='$username'");
if (strlen($username)<3) {
header ("Locaton: $comeFrom", true);
?>

<?php echo    "Username should be atleast 3 characters";?>×

<?php
die;
}elseif (strlen($firstname)<3) {
header ("Locaton: $comeFrom", true);
?>

<?php echo "Firstname should be atleast 3 characters";?>×

<?php
die;
}elseif (strlen($lastname)<3) {
header ("Locaton: $comeFrom", true); ;
?>

<?php echo "Lastname should be atleast 3 characters";?>×

<?php
die;
}elseif(strlen($_POST["password"])<8) {
header ("Locaton: $comeFrom", true);
?>

<?php echo "Password must be atleast eight characters long";?>×

<?php
die;
}elseif($_POST["password"] != $_POST["confirm_password"]) {
header ("Locaton: $comeFrom", true);
?>

<?php echo "Password in both fields do not match, please try again.";?>×

<?php
die;
}
if(mysqli_num_rows($result)>0){
header ("Locaton: $comeFrom", true);
?>

<?php echo "Email or username is already in use, please enter another";?>×

<?php
die;
}else{//does not exist so we proceed and add user to database
$sql="INSERT INTO users".
"(username,firstname,lastname,email,gender,state,dob,password,hash)".
"VALUES".
"('$username','$firstname','$lastname','$email','$gender','$state','$dob','$p assword','$hash');";
mysqli_query($conn,$sql);

$sql2="SELECT * FROM users WHERE username='$username' AND   firstname='$firstname'";
$result=mysqli_query($conn,$sql2);
if(mysqli_num_rows($result)>0){
while($user=mysqli_fetch_assoc($result)){
$user_id=$user["user_id"];
$sqlimg="INSERT INTO profile_img".
"(user_id)".
"VALUES".
"('$user_id');";
mysqli_query($conn,$sqlimg);
}
}else{
$_SESSION["error"]="Error signing up, please try again or contact us to rectify";
}

$_SESSION["active"]=0;
$user['user_id']=@$_SESSION['user_id'];
//know when the user is logged in
$_SESSION["logged_in"]=false;
if($_SESSION["logged_in"]=false){
$sqli="SELECT * FROM user WHERE email='$email' and username='$username'";
$result=mysqli_query($conn,$sqli);
while($user=mysqli_fetch_assoc($result)){
    $user['user_id']=$_SESSION["user_id"];
}
}
$_SESSION["message"]=

    "Confirmation message has been sent to your email, please click on the link for full account activation";

    $to=$email;
    $subject="Account Verification";
    $message_body='

<title>Mail Confirmation</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

Hello '.$username.',

    Thank you for signing up with us, we will do our best to provide you with an awesome experience.

    However, your account needs to be fully active, click on the button below to activate your account:

    Verify Me

';
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=UTF-8';

// Additional headers
$headers[] = 'From:';
$headers[] = 'Cc: Makzino@example.com';
$headers[] = 'Bcc: Makz@example.com';

// Mail it
mail($to, $subject, $message_body, implode("\r\n", $headers));
$_SESSION['success']="Hello $username!!! Registration was successful,   please proceed to login. Thank you";

}}else{
$_SESSION["error"]="Registration failed";
}

mysqli_close($conn);
?>

So on successful completion it sends me an email using my smtp4dev. But if an error occurs. Goes to the white page and displays just the error with no other html content.
I apologize if the codes are messy, new to stack overflow. Thanks in advance

A: Thanks,  I have sorted it out,, it was not reporting any error because there was actually no error to report.. I just placed the log_reg file before my code,  which was killing other outputs that follows because of the Die() call..  I only took the include("log_reg") file to the bottom of the page and it was sorted.. Just incase anyone runs into something similar..


text:
Q: Finding list of unique subsets of a given list of integers Looking for an efficient way to determine all unique subsets of a list of integers.
Say I have a List of integers containing 340 integers. I want a List of all possible subsets (of 5 elements each). All supplied integers will be unique, and the result should not duplicate any element in it's subset. An example given an input of 1,2,3,4,5,6,7,8,9 I am looking for an output of

*

*1,2,3,4,5

*1,2,3,4,6

*1,2,3,4,7

*1,2,3,4,8

*1,2,3,4,9

*1,2,3,5,6

*1,2,3,5,7

*...

I must do this in CSharp. can this be done in LINQ?

A: I have answered a several combinatorial questions, and everywhere I use a variation of a non recursive allocation free algorithm. For this case, it looks like this:
public static class Algorithms
{
    public static IEnumerable<T[]> GetCombinations<T>(this T[] input, int N)
    {
        var result = new T[N];
        var indices = new int[N];
        for (int pos = 0, index = 0; ;)
        {
            for (; pos < N; pos++, index++)
            {
                indices[pos] = index;
                result[pos] = input[index];
            }
            yield return result;
            do
            {
                if (pos == 0) yield break;
                index = indices[--pos] + 1;
            }
            while (index > input.Length - N + pos);
        }
    }
}

As in the other implementations, the method yields one and the same internal buffer, which is useful when you need just to iterate and process the resulting set once. If you need to store the combinations, then you need to clone the returned array before storing it. Here is a sample usage like in your scenario:
var input = Enumerable.Range(1, 20);
var result = input
    .Distinct()
    .ToArray()
    .GetCombinations(5)
    .Select(c => (int[])c.Clone())
    .ToList();

UPDATE: The GetCombinations method basically emulates N nested loops like this (in pseudo code):

for (int i0 = 0; i0 <= input.Length - N; i0++)
  for (int i1 = i0 + 1; i1 <= input.Length - N + 1; i1++)
  for (int i2 = i1 + 1; i2 <= input.Length - N + 2; i2++)
  ...
  for (int iN-1 = iN-2 + 1; iN-1 <= input.Length - 1; iN-1++)
  yield { input[i0], input[i1], input[i2], ..., input[iN-1] }

A: In case of a tractable set of 9 elements (or max 25-30) and subset of 5, the code could be based on a recursive function
   static void Main(string[] args)
    {
        foreach (var item in ListPerm())
        {
            Console.WriteLine(String.Join(",", item));
        }
        Console.Read();
    }

    private static List<List<int>> ListPerm(HashSet<int> mySet = null, int deep = 5)
    {
        if (mySet == null)
        {
            mySet = initSet(8);
        }
        if (deep <= 0)
        {
            return Enumerable.Empty<List<int>>().ToList();
        }
        List<List<int>> all = new List<List<int>>();
        for (int i = 0; i < mySet.Count - deep + 1; i++)
        {

            if (deep == 1)
            {
                var list = new List<int>() { mySet.ElementAt(i) };
                all.Add(list);
            }
            foreach (var item in ListPerm(new HashSet<int>(mySet.Skip(i+1)), deep - 1))
            {
                var list = new List<int>() { mySet.ElementAt(i) };
                list.AddRange(item);
                all.Add(list);
            }
        }
        return all;
    }

    private static HashSet<int> initSet(int lenght)
    {
        HashSet<int> ret = new HashSet<int>();
        for (int i = 0; i < lenght; i++)
        {
            ret.Add(i * 1  +  1); // just an example...
        };
        return ret;
    }

Reengineering
Now, let me optimize the above code into a more performant function, that takes 3.2 seconds to get the combinations of 8 integers out of 30 on my standard laptop.
private static int[][] ListPerm(int[] mySet, int deep)
{
    var all = new List<int[]>();
    if (deep == 1)
    {
        return mySet.Select(x => new int[] { x }).ToArray();
    }
    else
    {
        var mySubSet = new int[mySet.Length - 1];
        Array.Copy(mySet, 1, mySubSet, 0, mySubSet.Length);
        var perm1st = ListPerm(mySubSet, deep - 1);
        for (int i = 0; i < mySet.Length - deep + 1; i++)
        {
            var permn = perm1st.Select(x =>
                {
                    var z = new int[x.Length + 1];
                    z[0] = mySet[i];
                    x.CopyTo(z, 1);
                    return z;
                }
            );
            all.AddRange(permn);
            int start = Array.FindIndex(perm1st, item => item[0] != mySet[i + 1]);
                if (start > 0)
                {
                    var temp_cpy = new int[perm1st.Length - start][];
                    Array.Copy(perm1st, start, temp_cpy, 0, temp_cpy.Length);
                    perm1st = temp_cpy;
                }
        }
    }
    return all.ToArray();
}

Benchmark
Here it is a comparison of Ivan's, my and the community wiki algorithms for the combinations of 5 ints in 20.
Results

wiki perm: 00:00:00.0950055
writing wiki perm: 00:00:00.0460026
Ivan perm: 00:00:00.0400023
writing Ivan perm: 00:00:00.0260015
my perm: 00:00:00.0110006
writing my perm: 00:00:00.0300017

Test Code
    var input = Enumerable.Range(1, 20);
    int deep = 5;
    var start = DateTime.Now;

    var wiki =  Algorithms.Combinations(input, deep).ToArray();
    Console.WriteLine("wiki perm: {0}", DateTime.Now - start);
    start = DateTime.Now;
    StreamWriter sw0 = new StreamWriter(@"C:\dev\SO\Algo\perm0.txt", false);
    foreach (var item in wiki)
    {
        sw0.WriteLine(String.Join(",", item));
    }
    sw0.Close();
    Console.WriteLine("writing wiki perm: {0}", DateTime.Now - start);
    start = DateTime.Now;

    start = DateTime.Now;
    var result = input
        .Distinct()
        .ToArray()
        .GetCombinations(deep)
        .Select(c => (int[])c.Clone())
        .ToList();
    Console.WriteLine("Ivan perm: {0}", DateTime.Now - start);
    start = DateTime.Now;
    StreamWriter sw1 = new StreamWriter(@"C:\dev\SO\Algo\perm1.txt", false);
    foreach (var item in result)
    {
        sw1.WriteLine(String.Join(",", item));
    }
    sw1.Close();
    Console.WriteLine("writing Ivan perm: {0}", DateTime.Now - start);
    start = DateTime.Now;

    var myPerm = ListPermSO(input.ToArray(), deep);
    Console.WriteLine("my perm: {0}", DateTime.Now - start);
    start = DateTime.Now;
    StreamWriter sw2 = new StreamWriter(@"C:\dev\SO\Algo\perm2.txt", false);
    foreach (var item in myPerm)
    {
        sw2.WriteLine(String.Join(",", item));
    }
    sw2.Close();
    Console.WriteLine("writing my perm: {0}", DateTime.Now - start);
    Console.Read();


text:
Q: Jackson YAML Serialization Object Arrays Format I am trying to format my Jackson Yaml serialization in a certain way.
employees:
 - name: John
   age: 26
 - name: Bill
   age: 17

But, when I serialize the object, this is the format that I get.
employees:
 -
  name: John
  age: 26
 -
  name: Bill
  age: 17

Is there any way to get rid of the newline at the start of an object in the array? This is purely a personal preference/human readability issue.
These are the properties I'm currently setting on the YAMLFactory:
YAMLFactory yamlFactory = new YAMLFactory()
                .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES) //removes quotes from strings
                .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)//gets rid of -- at the start of the file.
                .enable(YAMLGenerator.Feature.INDENT_ARRAYS);// enables indentation.

I've looked in the java docs for the YAMLGenerator in Jackson, and looked at the other questions on stackoverflow, but I can't find an option to do what I'm trying to do.
I've tried CANONICAL_OUTPUT, SPLIT_LINES and LITERAL_BLOCK_STYLE properties, the last one being automatically set when MINIMIZE_QUOTES is set.
CANONICAL_OUTPUT seems to add brackets around arrays.
SPLIT_LINES and LITERAL_BLOCK_STYLE are related to how multi-line strings are handled.

A: The short answer is there is currently no way to do this through Jackson. This is due to a bug within snakeyaml where if you set the indicatorIndent property, the whitespace is not handled properly, and therefore snakeyaml adds the new line.
I have found a workaround using snakeyaml directly.
//The representer allows us to ignore null properties, and to leave off the class definitions
Representer representer = new Representer() {
    //ignore null properties
    @Override
    protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
        // if value of property is null, ignore it.
        if (propertyValue == null) {
            return null;
        }
        else {
            return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
        }
    }

    //Don't print the class definition
    @Override
    protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
        if (!classTags.containsKey(javaBean.getClass())){
            addClassTag(javaBean.getClass(), Tag.MAP);
           }

        return super.representJavaBean(properties, javaBean);
    }
};

DumperOptions dumperOptions = new DumperOptions();
//prints the yaml as nested blocks
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
//indicatorIndent indents the '-' character for lists
dumperOptions.setIndicatorIndent(2);
//This is the workaround. Indent must be set to at least 2 higher than the indicator indent because of how whitespace is handled.
//If not set to 2 higher, then the newline is added.
dumperOptions.setIndent(4);
Yaml yaml = new Yaml(representer, dumperOptions);
//prints the object to a yaml string.
yaml.dump(object);

The workaround happens with setting the indent property on the DumperOptions. You need to set the indent to a value at least 2 higher than the indicatorIndent, or else the newline will be added. This is due to how whitespace is handled within snakeyaml.

A: Looking at the Jackson source code the snakeyaml dumper options are created like:
@Andrey does this look good to you?
    protected DumperOptions buildDumperOptions(int jsonFeatures, int yamlFeatures,
            org.yaml.snakeyaml.DumperOptions.Version version)
    {
        DumperOptions opt = new DumperOptions();
        // would we want canonical?
        if (Feature.CANONICAL_OUTPUT.enabledIn(_formatFeatures)) {
            opt.setCanonical(true);
        } else {
            opt.setCanonical(false);
            // if not, MUST specify flow styles
            opt.setDefaultFlowStyle(FlowStyle.BLOCK);
        }
        // split-lines for text blocks?
        opt.setSplitLines(Feature.SPLIT_LINES.enabledIn(_formatFeatures));
        // array indentation?
        if (Feature.INDENT_ARRAYS.enabledIn(_formatFeatures)) {
            // But, wrt [dataformats-text#34]: need to set both to diff values to work around bug
            // (otherwise indentation level is "invisible". Note that this should NOT be necessary
            // but is needed up to at least SnakeYAML 1.18.
            // Also looks like all kinds of values do work, except for both being 2... weird.
            opt.setIndicatorIndent(1);
            opt.setIndent(2);
        }
        // 14-May-2018: [dataformats-text#84] allow use of platform linefeed
        if (Feature.USE_PLATFORM_LINE_BREAKS.enabledIn(_formatFeatures)) {
            opt.setLineBreak(DumperOptions.LineBreak.getPlatformLineBreak());
        }
        return opt;
    }

A: I ran into this and ended up writing this blog entry to describe the solution I came up with. In short, I made a custom subclass of YAMLGenerator and YAMLFactory and used that to configure Jackson's YAMLMapper. Not "clean" but not huge and reasonably effective. Let me set arbitrary DumperOptions
Source below, but also available in this gist.
Warning - I did this all in Kotlin, but it's trivial code, and should be easily back-portable to Java:
val mapper: YAMLMapper = YAMLMapper(MyYAMLFactory()).apply {
  registerModule(KotlinModule())
  setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
}

class MyYAMLGenerator(
  ctx: IOContext,
  jsonFeatures: Int,
  yamlFeatures: Int,
  codec: ObjectCodec,
  out: Writer,
  version: DumperOptions.Version?
): YAMLGenerator(ctx, jsonFeatures, yamlFeatures, codec, out, version) {
  override fun buildDumperOptions(
    jsonFeatures: Int,
    yamlFeatures: Int,
    version: DumperOptions.Version?
  ): DumperOptions {
    return super.buildDumperOptions(jsonFeatures, yamlFeatures, version).apply {
      //
      // NOTE: CONFIGURATION HAPPENS HERE!!
      //
      defaultScalarStyle = ScalarStyle.LITERAL;
      defaultFlowStyle = FlowStyle.BLOCK
      indicatorIndent = 2
      nonPrintableStyle = ESCAPE
      indent = 4
      isPrettyFlow = true
      width = 100
      this.version = version
    }
  }
}

class MyYAMLFactory(): YAMLFactory() {
  @Throws(IOException::class)
  override fun _createGenerator(out: Writer, ctxt: IOContext): YAMLGenerator {
    val feats = _yamlGeneratorFeatures
    return MyYAMLGenerator(ctxt, _generatorFeatures, feats,_objectCodec, out, _version)
  }
}

A: In today's environment using at least version 2.12.x of jackson-dataformat-yaml thanks to the introduction of YAMLGenerator.Feature.INDENT_ARRAYS_WITH_INDICATOR, you can simply just do:
public ObjectMapper yamlObjectMapper() {
    final YAMLFactory factory = new YAMLFactory()
            .enable(YAMLGenerator.Feature.INDENT_ARRAYS_WITH_INDICATOR)
            .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)
            .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);

    return new ObjectMapper(factory);
}

Which will give you the output of:
employees:
 - name: John
   age: 26
 - name: Bill
   age: 17


text:
Q: Proof explanation: Theorem 2, Section 15, Dual Spaces, Halmos This theorem claims, that there is a $X'$ which a dual basis of $X$ such that $[x_i, y_i] = \delta_{ij}$ and subsequently dual space is n-dimensional if the space is n-dimensional.
But I am confused at the proof step that,
$$0 = \sum _j a_j[x_i, y_j] = \sum _j a_j \delta_j = a_i$$
How did that suddenly become $a_i$, If the proof setup claimed that we choose $\delta_{ij} = 1$ iff $i == j$ otherwise $0$ then I am convinced, but Halmos didn't assume anything about $\delta_{ij}$. I am confused, Can anyone help me here?

A: In standard notations $\delta_{ij} =1$ if $i=j$ and $0$ if $ i\neq j$.
This notation, called Kronecker delta, has in fact been introduced by Halmos in Section 7 (Bases).

A: Of course this will make no sense if you do not know what $\delta_{ij}$ means! (Surely it is defined in your text?)
$\delta_{ij}$ is defined to be $0$ if $i\ne j$ and 1 if $i= j$. So if our space is 4 dimensional, then $\sum_{j= 1}^4 \delta_{ij}a_j= \delta_{i1}a_1+ \delta_{i2}a_2+ \delta_{i3}a_3+ \delta_{i4}a_4$.
If i= 1, that is $(1)a_1+ (0)a_2+ (0)a_3+ (0)a_4= a_1$
If i= 2 that is $(0)a_1+ (1)a_2+ (0)a_3+ (0)a_4= a_2$
If i= 3, that is $(0)a_1+ (0)a_2+ (1)a_3+ (0)a_4= a_3$
If i= 4, that is $(0)a_1+ (0)a_2+ (0)a_3+ (1)a_4= a_4$


text:
Q: Почему запрос ничего не выводит? SELECT
    product.title,
    stock,
    price,
    GROUP_CONCAT(p.title, ': ', pv.value SEPARATOR ', ') property_values
FROM product
INNER JOIN product_property_value pv ON pv.product_id = product.id
INNER JOIN property p ON p.id = pv.property_id
  AND (p.code = 'color' AND pv.value = 'Красный')
  AND (p.code = 'width' AND (pv.value = 4 OR pv.value = 5))
  AND (p.code = 'height' AND pv.value = 5)
GROUP BY product.id;

Полный DDL с данными. Что я делаю не так? Пробовал и через ON и через WHERE, но ничего не выводит...

A: Можно, например, так.
SELECT pr.id
     , pr.title
     , GROUP_CONCAT(p.code, ': ', ppv.value separator ', ' ) AS props
FROM product_property_value  AS ppv
INNER JOIN property AS p ON (
  ppv.property_id = p.id
  AND (
      (p.code = 'color' AND ppv.value = 'Красный')
      OR (p.code = 'width' AND (ppv.value = 4 OR ppv.value = 5))
      OR (p.code = 'height' AND ppv.value = 5)
    )
)
INNER JOIN product AS pr ON pr.id = ppv.product_id
GROUP BY pr.id, pr.title
HAVING count(pr.id) = 3;

выбираем все товары, совпадающие по каждому свойству, а потом после группировки оставляем только товары, где присутствуют все 3.


text:
Q: Unable to to access Generic Views with JWT authentication I'm at a loss - I have a django backend and react frontend.  On the frontend, I have a login page that sets a JWT token, and I use that token to query data from the django backend.  This all works perfectly.
But I also have direct views to these APIs via something simple as http://localhost:8000/tables/data which will just show me a default django view of these tables (ie: a paginated "select * from data" call) ... and hooked in through a genericListAPIView.
Now, as I said, everything works fine when feeding it via a curl command (or postman, or whatnot).  I get the JWT token, set it the Authorization access in the subsequent call to the API, and get the data back and do something with in in React.
What I can't seem to figure out is how to hoo that same JWT token when calling trying to access the generic view.  When I browse to it, I get
HTTP 401 Unauthorized
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
WWW-Authenticate: JWT realm="api"

{
    "detail": "Authentication credentials were not provided."
}

Which I guess make sense since I'm not going through any React authentication.  Yet, it's the same server.  Should be same authentication (and in fact the login accounts are being managed by django).
I've googled, and read (and tried) a bunch of different things and can't seem to wrap my head around what I am doing wrong.  Any help, or any direction, would be much appreciated.

A: When you make a request from a browser, you can only rely on session cookies. The browser is not able to automatically add an access token to the request. In order to make a request with an access token, you have to make it using Javascript.


text:
Q: Close form program when close button is disabled I want to close a application when a button is pressed but I wanted to disable the close button (X button upper right).
I disabled the close button with this code:
protected override void OnFormClosing(FormClosingEventArgs e)
{
    e.Cancel = true;
}

But now when I try to close the program with this code it wont work.
private void button1_Click(object sender, EventArgs e)
{
    Application.Exit();
}

Is there a way to close this program when the button is clicked?

A: In the event handler, check the CloseReason property of the FormClosingEventArgs:
This allows you to behave differently depending on how the close was initiated, so in the case of Application Exit (or Windows Shutdown) you can allow the form to close.
protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (e.CloseReason != CloseReason.ApplicationExitCall
     && e.CloseReason != CloseReason.WindowsShutDown)
     {
          e.Cancel = true;
     }
}

A: You're cancelling ALWAYS the closign of the form, so that's why it doesn't works.
Try this:
bool blockClosing = true;

protected override void OnFormClosing(FormClosingEventArgs e)
{
    e.Cancel = blockClosing;
}

private void button1_Click(object sender, EventArgs e)
{
    blockClosing = false;
    Application.Exit();
}

In this way, when you press your button it will allow tha pp to be closed.

A: FormClosingEventArgs has a Reason member that tells you what exactly is trying to close your form. Simply allow ApplicationExitCall through without canceling it.


text: Q: Where to find http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics? On our web-service we receive several requests with elements from the http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics namespace in the SOAP header. Instead of just ignoring these elemtns, we would like to validate them instead. Unfortunately, I haven't been able to find a place for downloading the schema. If I try with the schema-url itself, all I get is a 404. Even Google has no clue!!


text:
Q: libvirtd: No more available PCI slots Ahoy.
Today I wanted to set up a new virtual machine to manage my 8 hard disk devices.
Currently I use Fedora 31 as host, and Debian 9 as guest system.
I want to pass through the block devices to the virtual machine, but unfortunately it doesn't work, and it's quite hard to find proper information without being a RedHat subscriber.
So what did I do? I try to attach the hard disk using, the following command.
virsh attach-disk Storage_ZFS_\(Debian\) /dev/sdb vdc

Unfortunately I receive the following error.
error: Failed to attach disk
error: internal error: No more available PCI slots

So what did I try? I did some research, and found something what has worked on SUSE, adding <controller type='pci' model='pcie-to-pci-bridge'/> somewhere in the VM's  section, but unfortunately it didn't work as well.
Only received the following error.
[root@millenium-fbe48 chairman]# virsh edit Storage_ZFS_\(Debian\)
error: internal error: Cannot automatically add a new PCI bus for a device with connect flags 800
Failed. Try again? [y,n,i,f,?]:
error: XML error: The PCI controller with index='0' must be model='pcie-root' for this machine type, but model='pcie-to-pci-bridge' was found instead
Failed. Try again? [y,n,i,f,?]:
error: XML error: The PCI controller with index='0' must be model='pcie-root' for this machine type, but model='pcie-to-pci-bridge' was found instead
Failed. Try again? [y,n,i,f,?]:
error: XML error: The PCI controller with index='0' must be model='pcie-root' for this machine type, but model='pcie-to-pci-bridge' was found instead
Failed. Try again? [y,n,i,f,?]:
error: XML error: The PCI controller with index='0' must be model='pcie-root' for this machine type, but model='pcie-to-pci-bridge' was found instead
Failed. Try again? [y,n,i,f,?]:
error: XML error: The PCI controller with index='0' must be model='pcie-root' for this machine type, but model='pcie-to-pci-bridge' was found instead
Failed. Try again? [y,n,i,f,?]:

Does someone knows how to deal with it, and how to add the hard disks to my guest VM?

A: I was able to add multiple PCI passthrough device using the following approach.
If you do the attach-interface command with --config only (remove the
--live), libvirt will be able to automatically add the pcie-root-port
that it knows is required. Then you'll just need to shutdown and restart
the guest for the device to be added to the running guest instance (a
simple reboot from the guest is insufficient, you need to fully shut it
down, so that a new qemu process is started)
So basically .

*

*virsh attach-device VM_NAME PCI_entry.xml --config

*virsh destroy VM_NAME

*virsh start VM_NAME
Source: Re: [libvirt-users] unable to add pci network to existing vm

A: The problem has been solved.
There is a way to solve this problem by adding PCI/PCIe bridges, but it seems to be quite complicated, and there is a lack of information.
So i found a libvirt documentation page provided by RedHat, having a load of information.
To sum up: There are 3 ways to add block devices to the guest VM, i used an easy one.
Simply editing the xml file of the desired target, by using virsh edit "domain", and adding the following content bellow the last  statement, appearing in the file.
<disk type='block' device='disk'>
      <driver name='qemu' type='raw' cache='none'/>
      <source dev='/dev/sdx'/>
      <target dev='vda' bus='virtio'/>
</disk>

In order to get it work you still have to replace "vda" and "sdx" in your case.
Using this method, PCI bridges will be created automatically. Very easy to solve this problem using this way.
Link to the article. 13.3.2. Adding Hard Drives and Other Block Devices to a Guest

A: Use --live while machine is working do not use it if its offline
to create some test disks in bash :
for i in {1..12};do sudo qemu-img create -f raw testdisk$i.raw 10G;done

to attach disks in python3:
import os
y='g,h,i,j,k,l,m,n,o,p,r,s,t,u,v,y,z'.split(',')
for i in range(1,13):
    s='virsh attach-disk optmb_fileserver '+'/home/gediz/Desktop/testdisk'+str(i)+'.raw '+'vd'+y[i]+' --config --live'
    print(os.popen(s).read())

A: Shut down your VM, then use --persistent:
virsh attach-disk GuestVM /dev/sda1 vda --persistent


text:
Q: Solr: Empty results when document is present Could you say why I have empty searching results.
Say, I have the following document in Solr:
{
  "srcphrase": "in case if",
  "id": "d77a6c9e463652c9",
  "_version_": 1479240921712164900
}

In my schema.xml:
<field name="id"
       type="string"
       indexed="true"
       stored="true"
       required="true"
       multiValued="false" />
<field name="srcphrase"
       type="text_en"
       indexed="true"
       stored="true"/>
...
<fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
    <filter class="solr.PorterStemFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
    <filter class="solr.PorterStemFilterFactory"/>
  </analyzer>
</fieldType>

When submitting the query localhost:8983/solr/collection/select?q=srcphrase%3A%22in+case+if%22 I get empty results. Here is what analysis show:

Do you have some ideas why I have empty results for existing phrase?

A: Seems now the problem is solved for me. I have already tried to re-index the documents, but after I have re-indexed the core once again, Solr starts returning the results.
query: srcphrase:in AND srcphrase:case AND srcphrase:if, the phrase found
query: srcphrase:"case if in"~3, the phrase found
query: srcphrase:"in case if", the phrase found
query (as suggested by akshayb): srcphrase:in AND case AND if, the results are empty
So re-indexing the documents matters if you change the chain of filters for index analyzer.
To re-index the documents it is needed:

*

*To remove all the existing documents
curl http://{host}:{port}/solr/{collection}/update -H "Content-Type: text/xml" --data-binary '<delete><query>*:*</query></delete>'

*To submit the documents once again, e.g.:
java -Durl=http://{host}:{port}/solr/{collection}/update -jar /path/to/solr/post.jar my-doc.txt


text:
Q: Number of posts next to user in users.php excluding Custom Post Types I have noticed that the list of users generated by users.php in my dashboard doesn't take into account custom post types when it displays the number of posts by each user.
So even if a user has 20 posts of a custom post type, it will still show '0' next to their name.
Does anyone know how to resolve this and add custom post types to this number?

A: For anyone else looking to achieve the same, I managed to resolve it using this solution...
function my_manage_users_columns($columns) {
    $columns['post_type_count'] = __( 'Books', 'textdomain' );

    return $columns;
}
add_filter('manage_users_columns', 'my_manage_users_columns');

With 'Books' being the name of the custom field


text:
Q: POST becomes GET on outgoing traffice I have a web instance on a Google Cloud virtual machine, built as UBUNTU
I am trying to POST data to an external API, but when I watch the traffic the POST is clearly becoming a GET.
I have checked the server .htaccess and site.conf file and can see no eveidence of rewrites or limiting
I have tried both PHP CURL and JQUery. Here are the IMPORTANT snippets of code from each attempt
curl_setopt($ch, CURLOPT_POST, 1); // I have also tried TRUE
curl_setopt($ch, CURLOPT_POSTFIELDS,"\$xmldata=".urlencode($xmldata));
ob_start();

and the Jquery method (in full)
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<script type="application/javascript">
    $(function () {
        var example = {
            "Title": "REST DN transaction (JSON)",
            "Description": "REST DN transaction (JSON)",
            "TransactionType": 0,
            "Partner": {
                "PartnerId": xxxx },
            "Buyer": {
                "Email": "xxxx@hotmail.com", "Initiator": false,
                "CompanyChk": false,
                "AutoAgree": false, "AgreementChecked": false
            }, "Seller": {
                "Email": "xxxx@hotmail.com", "Initiator": true,
                "CompanyChk": false,
                "AutoAgree": false, "AgreementChecked": false
            }, "LineItems": [
                {
                    "ItemName": "test.com", "Description": "DN description", "Quantity": 1,
                    "Price": 2000,
                    "Accept": true,
                    "SellComm": 9.1,
                    "BuyComm": 10.1,
                }],
            "EPayment": 0,
            "ShipmentFee": 0,
            "ShipmentPayment":0,
            "DomainNameType": 0,
            "InspectionLength": 6,
            "Currency": "USD",
            "Fulfillment": 2,
            "CommissionType": 1,
            "InitiationDate": "2014-04-15",
            "TermsLocked": true,
            "AllowReject": true
        };

        $.post({
            type: "POST",
            method: "POST",
            dataType: 'jsonp',
            data :JSON.stringify(example),
            url: "https://thedomain.com/api/Transaction",
            contentType: "application/json"
        });
    });
</script>

I have ALSO tried $.ajax(
Domain name is a placeholder
Can anyone advise why in google developer console when I watch the timeline the outgoing request is always a GET
The API is also returning a messging indicating GET is no=t allowed

A: The problem was not the code (no surprises) but the API. Thanks for those who took time to respond


text:
Q: Opencascade Android Studio I am trying to build an  Android application on Opencascade with the help of below url.
http://www.opencascade.com/doc/occt-7.0.0/overview/html/samples_java_android_occt.html
Everything works fine except I am stuck in below errors :
07-12 17:13:09.711: E/occtJniViewer(16333): Error: native library "gnustl_shared" is unavailable:

07-12 17:13:09.711: E/occtJniViewer(16333):   dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.opencascade.jnisample-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libgnustl_shared.so"

Error: native library "freetype" is unavailable:

07-12 17:13:09.711: E/occtJniViewer(16333):   dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.opencascade.jnisample-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libfreetype.so"

Error: native library "freeimage" is unavailable:

07-12 17:13:09.711: E/occtJniViewer(16333):   dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.opencascade.jnisample-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libfreeimage.so"

Error: native library "TKernel" is unavailable:

07-12 17:13:09.711: E/occtJniViewer(16333):   dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.opencascade.jnisample-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libTKernel.so"

I am not able to add gnustl_shared library and other .so files. Please suggest steps as the above link does not provide much detail about these.
Any help will be of great assistance. Thanks.

A: OpenCascade does not provide any binaries for building an application.
Build your own .so binaries file for Android in Windows OS :

*

*Follow the steps carefully given here Building with CMake for Android

*Use only Freetype that comes with Open Cascade installer. FreeImageand others are not required for this sample.

*After successful configuration and generation of CMake files, follow the step 1 URL.

*There will be lots of issues while creating binary files for Android. Follow the below tricks :
a.    Error related to declspec(dllexport) x. It comes in 3rd party library freetype that comes with OCC inside freetype-x.x.x/include/config/ftoption.h. It can resolved by commenting out the line number (282 if OCC 7.0.0 is used) given in the error and entering #define FT_EXPORT_DEF(x)  x in place of it.
b.    Use the make command to start building again.
c.    Paste freetype.so in freetype-xx/lib. Copy libEGL.so from ..\android-ndk\platforms\android-xx\arch-arm\usr\lib and paste it in freetype-xx/lib.
d.    Open inc folder for CMake output folder given in step 1. Copy the contents in ..\android-ndk\platforms\android-xx\arch-arm\usr\include and paste in inc folder. Follow step 4.b.
NOTE : android-xx depends on ANDROID_NATIVE_API_LEVEL. It can be android-15.

*If no errors are there then continue to follow the step 1 URL.

*After successful installation, go to CMake output directory and look for lib folder in any subfolders (may be lin32/gcc/lib). Inside lib folder all the required binary files will be there.

*I've created the binaries. download from here and copy the binaries in jnilibs folder in project.

*Apart from freetype no other 3rd party library is required.

Now coming back to the question - gnustl_shared is not reuired to add as an external binary.
Inside app\build.gradle use below code
apply plugin: 'com.android.model.application'

model {
    android {
        compileSdkVersion = 24
        buildToolsVersion = "24.0.2"

        defaultConfig.with {
            applicationId = "com.occ_poc_as"
            minSdkVersion.apiLevel = 21
            targetSdkVersion.apiLevel = 24
            versionCode = 1
            versionName = "1.0"
        }
        buildTypes {
            release {
                minifyEnabled = false
                proguardFiles.add(file('proguard-android.txt'))
            }
        }

        ndk {
            moduleName = "OcctJni_Viewer"
            cppFlags.add("-I${file(getOpenCascadeDir())}".toString())
            cppFlags.add("-frtti")
            cppFlags.add("-fexceptions")
            stl = "gnustl_shared"
            toolchain = 'clang'
            ldLibs.addAll(['android', 'log', 'EGL', 'GLESv2'])
            cppFlags.addAll(['-Wall', '-std=c++11'])
            CFlags.addAll(['-Wall', '-std=c++11'])
        }

        productFlavors {
            // for detailed abiFilter descriptions, refer to "Supported ABIs" @
            // https://developer.android.com/ndk/guides/abis.html#sa
            create("arm7") {
                ndk.with {
                    abiFilters.add("armeabi-v7a")
                    ldFlags.add("-L${file('src/main/jniLibs/armeabi-v7a')}".toString())
                    File curDir = file('./')
                    curDir = file(curDir.absolutePath)
                    String libsDir = curDir.absolutePath + "\\src\\main\\jniLibs\\armeabi-v7a\\"
                    ldLibs.add(libsDir + "libfreetype.so")

                ldLibs.add(libsDir + "libTKBRep.so")
                ldLibs.add(libsDir + "libTKernel.so")
                ldLibs.add(libsDir + "libTKG2d.so")
                ldLibs.add(libsDir + "libTKG3d.so")
                ldLibs.add(libsDir + "libTKGeomAlgo.so")

                ldLibs.add(libsDir + "libTKGeomBase.so")
                ldLibs.add(libsDir + "libTKMath.so")
                ldLibs.add(libsDir + "libTKPrim.so")
                ldLibs.add(libsDir + "libTKTopAlgo.so")
                ldLibs.add(libsDir + "libTKBO.so")

                ldLibs.add(libsDir + "libTKBool.so")
                ldLibs.add(libsDir + "libTKFillet.so")
                ldLibs.add(libsDir + "libTKHLR.so")
                ldLibs.add(libsDir + "libTKIGES.so")
                ldLibs.add(libsDir + "libTKMesh.so")

                ldLibs.add(libsDir + "libTKOffset.so")
                ldLibs.add(libsDir + "libTKOpenGl.so")
                ldLibs.add(libsDir + "libTKService.so")
                ldLibs.add(libsDir + "libTKShHealing.so")
                ldLibs.add(libsDir + "libTKSTEP.so")

                ldLibs.add(libsDir + "libTKSTEP209.so")
                ldLibs.add(libsDir + "libTKSTEPAttr.so")
                ldLibs.add(libsDir + "libTKSTEPBase.so")
                ldLibs.add(libsDir + "libTKV3d.so")
                ldLibs.add(libsDir + "libTKXSBase.so")

                }

            }

        }
    }

}

def getOpenCascadeDir() {
    Properties properties = new Properties()
    properties.load(new File(rootDir.absolutePath + "/local.properties").newDataInputStream())
    def externalModuleDir = properties.getProperty('occ.dir', null)
    if (externalModuleDir == null) {
        throw new GradleException(
                "OpenCascade location not found. Define location with occ.dir in the local.properties file!")
    }
    return externalModuleDir
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar', '.so'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
}

Inside local.properties add below snippets.
sdk.dir=D\:\\Software\\android_sdk
ndk.dir=D\:\\Software\\android-ndk-r12b-windows-x86_64\\android-ndk-r12b
occ.dir=D\:\\Workspace\\OCCT\\inc

For OcctJniActivity.java remove freeimage. replace TKJniSample with
     // application code
     || !loadLibVerbose ("OcctJni_Viewer",  aLoaded, aFailed))

NOTE :

*

*Use latest gradle experiment for the sample.

*Don't forget to add Shaders in assest folder. Others are not required for this sample

*I have used OCC 7.0.0 and latest Android Studio.
I am attaching source code and OCC/include folder.


text:
Q: iphone ui date picker I have a problem with datepicker.
I would like to change the black/grey boarder surrounding the spindle to a transparent colour.i want to clear the border colour of the picker i want to display only pickerview without border is that possible to clear the border colour.
    please suggest me.
thanks..!
picker

A: I don't think you can do it.
If you really want that effect, you may want to put an image on top of the picker view, with the center of the image (in the shape of the spindle) has the alpha of 0. Depending on what is shown on the 'pane' area of the picker this may be successful, but I would ask myself if I really need that first...

A: It is not possible to Delete it.
But in one of my apps I just created an background image in photoshop with a transparent area in the middle of it in the size of the picker.
good luck


text:
Q: How to prove oracle properties in Fan and Li (2001) paper I am studying Fan and Li's 2001 paper "Variable selection via nonconcave penalized Likelihood andits oracle properties" but I am having troubles understanding Theorem 1 proof (page 1359). I follow the authors steps until equation (A.2).
$D_n(u)\leq\alpha_nL'(\beta_0)^Tu-\frac{1}{2}u^tI(\beta_0)un\alpha^2_n\{1+o_p(1)\}-\sum_{j=1}^s[n\alpha_np^{'}_{\lambda_n}(\vert\beta_0\vert)sgn(\beta_0)u_j+n\alpha^2_np^{''}_{\lambda_n}(\vert\beta_0\vert)u_j^2\{1+o(1)\}]$
Is here where I get lost. I know what the taylor expansion is (in its simplest case is, for instance $f(x) = f(a) + f(a)'(x-a) + \frac{1}{2}f(a)''(x-a)^2...$) but I dont see how is this formula applied here.
I assume that the Taylor formula is applied over the maximum likelihood function, but if so,  why does  $un\alpha^2_n\{1+o_p(1)\}$ appear in the second term of the equation? and where does the third term  come from?
I also have some problems understanding what the authors mean while saying in (in the paragraph just under this equation) that By choosing a sufficiently large C, the second term dominates the first term uniformly in $\|u\|=C$
I would appreciate any hint for understanding this proof itself, or any reading recommendation useful for this purpose.


text:
Q: Validating a single text box against two different rules with jQuery Validation skips the second error message Consider the following HTML:
<form id="frm">
    <input type="text" id="txt" name="txt" />
    <input type="submit" value="click me" />
</form>

I need to validate the text box against 2 different rules using jQuery Validation Plugin v1.13.1 and jQuery 1.7.2 and hence:
$(function(){
    var validator = $('#frm').validate({
        errorPlacement: function (error, element) {
            element.attr('title', error.text());
        }
    });

    $.validator.addMethod('rule1', function (value, element) {
        return value != null && value.length;
    }, 'Rule 1 failed!');

    $.validator.addMethod('rule2', function (value, element) {
        return false;
    }, 'Rule 2 failed!');

    //Assign both rules to the text box.
    $('#txt').rules('add', { rule1: true, rule2: true });

    $('input[type="submit"]').click(function() {
        if(!validator.form()) {
            return false;
        }
    });
});

*

*Click the above button (leave the text box intact).

*Hover the text box, it says that the Rule1 has failed.

*Now, enter something in the text box so that Rule1 validates correctly.

*Press the button again.

*Hover the text box again. Although the Rule1 has been successfully validated, however, it still says Rule1 failed, instead of Rule2.

The question is why? Here's the associated JSFiddle.
Thank you.

A: By default, jQuery validation tries to read the error message from the element's title attribute if it is present. Of course, since you're setting the error message in the title, this becomes permanent. This odd behavior is apparently deprecated now and will soon be gone.
In the meantime, however, the fix is to use the ignoreTitle option when creating your validator:
var validator = $('#frm').validate({
    ignoreTitle: true,
    ...
}

See the fiddle here: http://jsfiddle.net/dp5pLr8x/4/

A: I am not 100% sure but I think the problem you are running into is value.length does not return null/T/F, it returns a range from 0-whatever so Rule 1 will never validate.
Try (value.length > 0) for T/F.


text:
Q: Please help me troubleshoot MacPro Kernel Panic I am getting a lot of Kernel Panics recently, sometimes several per day. Here is the most recent one which occured when running Pro Tools HD on my MacPr 2,1:
Interval Since Last Panic Report:  290582 sec
Panics Since Last Report:          11
Anonymous UUID:                    E8982051-0F07-453E-8F94-F6379BC6CA63

Fri Jan 23 00:21:59 2015
Machine-check capabilities 0x0000000000000806:
 family: 6 model: 15 stepping: 11 microcode: 0
 Intel(R) Xeon(R) CPU           X5365  @ 3.00GHz
 6 error-reporting banks
 threshold-based error status present
Processor 0: no machine-check status reported
Processor 1: no machine-check status reported
Processor 2: no machine-check status reported
Processor 3: no machine-check status reported
Processor 4: machine-check status 0x0000000000000005:
 restart IP valid
 machine-check in progress
MCA error-reporting registers:
 IA32_MC0_STATUS(0x401): 0xb200004000000800 valid
  MCA error code:            0x0800
  Model specific error code: 0x0000
  Other information:         0x00000040
  Threshold-based status:    Undefined
  Status bits:
   Processor context corrupt
   Error enabled
   Uncorrected error
 IA32_MC1_STATUS(0x405): 0x0000000000000000 invalid
 IA32_MC2_STATUS(0x409): 0x0000000000000000 invalid
 IA32_MC3_STATUS(0x40d): 0x0020000000000000 invalid
 IA32_MC4_STATUS(0x411): 0x0000000000000011 invalid
 IA32_MC5_STATUS(0x415): 0xb200221024080400 valid
  MCA error code:            0x0400
  Model specific error code: 0x2408
  Other information:         0x00002210
  Threshold-based status:    Undefined
  Status bits:
   Processor context corrupt
   Error enabled
   Uncorrected error
Processor 5: no machine-check status reported
Processor 6: no machine-check status reported
Processor 7: no machine-check status reported
panic(cpu 4 caller 0xffffff80098b91b9): "Machine Check at
0xffffff7f8b0123ce, registers:\n" "CR0: 0x0000000080010033, CR2:
0x000000010fc8b000, CR3: 0x000000002e9b2000, CR4: 0x0000000000000660\n"
"RAX: 0x0000000000000000, RBX: 0xffffff802a508800, RCX:
0x0000000000000001, RDX: 0x0000000000000000\n" "RSP: 0xffffff81dae3b9a0,
RBP: 0xffffff81dae3b9d0, RSI: 0x0000000000000001, RDI:
0xffffff81d091d148\n" "R8:  0x1000000000000000, R9:  0x0000000000988a00,
R10: 0xffffff8009ef3b00, R11: 0x0000000000000246\n" "R12:
0x0000000000000001, R13: 0xffffff802a35cac0, R14: 0x0000000000000000, R15:
0x0000000000000148\n" "RFL: 0x0000000000000046, RIP: 0xffffff7f8b0123ce,
CS:  0x0000000000000008, SS:  0x0000000000000010\n" "Error code:
0x0000000000000000\n"@/SourceCache/xnu/xnu-
2050.48.12/osfmk/i386/trap_native.c:280
Backtrace (CPU 4), Frame : Return Address
0xffffff81d092cec0 : 0xffffff800981d636
0xffffff81d092cf30 : 0xffffff80098b91b9
0xffffff81d092d0a0 : 0xffffff80098cf4df
0xffffff81dae3b9d0 : 0xffffff7f8b00b6d2
0xffffff81dae3bab0 : 0xffffff7f8b00aa6e
0xffffff81dae3bb60 : 0xffffff80098ba19a
0xffffff81dae3bb80 : 0xffffff800982f35d
0xffffff81dae3bbc0 : 0xffffff800982de11
0xffffff81dae3bc20 : 0xffffff800982db83
0xffffff81dae3bc60 : 0xffffff80098342f7
0xffffff81dae3bcc0 : 0xffffff7f8a6b671e
0xffffff81dae3bcf0 : 0xffffff7f8a6b69a5
0xffffff81dae3bd20 : 0xffffff8009927806
0xffffff81dae3bd70 : 0xffffff80099190e4
0xffffff81dae3bde0 : 0xffffff800990f509
0xffffff81dae3be30 : 0xffffff8009b52f83
0xffffff81dae3be60 : 0xffffff8009b7fa23
0xffffff81dae3bf60 : 0xffffff8009be94c3
0xffffff81dae3bfb0 : 0xffffff80098cf130
      Kernel Extensions in backtrace:
         com.apple.driver.AppleIntelCPUPowerManagement(214.0)[3B20B0E5-
0D48-36D9-BA2C-B6208BC6E795]@0xffffff7f8b008000->0xffffff7f8b035fff
         com.digidesign.iokit.DigiDal(10.3.8f123)[07139795-3C93-8119-8513-
2884210177D9]@0xffffff7f8a6aa000->0xffffff7f8a6e9fff
            dependency: com.apple.iokit.IOPCIFamily(2.8)[6C1D646D-7E5E-
3D7F-A557-2CBA398FF878]@0xffffff7f89e08000

BSD process name corresponding to current thread: Pro Tools
Boot args:  kext-dev-mode=1 -v

Mac OS version:
12F45

Kernel version:
Darwin Kernel Version 12.5.0: Sun Sep 29 13:33:47 PDT 2013; root:xnu-
2050.48.12~1/RELEASE_X86_64
Kernel UUID: EA38B02E-2B88-309F-BA68-1DE29F605DD8
Kernel slide:     0x0000000009600000
Kernel text base: 0xffffff8009800000
System model name: MacPro2,1 (Mac-F4208DC8)

System uptime in nanoseconds: 1461343421554
last loaded kext at 1309568223737: com.apple.filesystems.smbfs  1.8.4
(addr 0xffffff7f8b85e000, size 229376)
last unloaded kext at 308132683319: com.apple.filesystems.msdosfs   1.8.1
(addr 0xffffff7f8b850000, size 57344)
loaded kexts:
com.paceap.kext.pacesupport.snowleopard 5.9.1
com.kensington.trackballworks.driver    1.2.0
com.digidesign.iokit.DigiDal    10.3.8f123
com.apple.filesystems.smbfs 1.8.4
com.apple.driver.AudioAUUC  1.60
com.apple.iokit.IOBluetoothSerialManager    4.1.7f4
com.apple.filesystems.autofs    3.0
com.apple.driver.AppleHDA   2.4.7fc4
com.apple.driver.AppleUpstreamUserClient    3.5.12
com.apple.iokit.IOUserEthernet  1.0.0d1
com.apple.driver.AppleMCCSControl   1.1.11
com.apple.driver.AppleMCEDriver 1.1.9
com.apple.kext.AMDFramebuffer   8.1.6
com.apple.Dont_Steal_Mac_OS_X   7.0.0
com.apple.driver.AppleLPC   1.6.3
com.apple.AMDRadeonAccelerator  1.0.8
com.apple.driver.ApplePolicyControl 3.4.5
com.apple.driver.ACPI_SMC_PlatformPlugin    1.0.0
com.apple.iokit.SCSITaskUserClient  3.5.6
com.apple.driver.XsanFilter 404
com.apple.driver.AppleUSBHub    635.4.0
com.apple.iokit.IOAHCIBlockStorage  2.3.5
com.apple.driver.AppleIntel8254XEthernet    3.1.1b1
com.apple.driver.AppleFWOHCI    4.9.9
com.apple.driver.AppleAHCIPort  2.6.6
com.apple.driver.AppleUSBEHCI   621.4.6
com.apple.driver.AppleIntelPIIXATA  2.5.1
com.apple.driver.AppleUSBUHCI   621.4.0
com.apple.AppleFSCompression.AppleFSCompressionTypeDataless 1.0.0d1
com.apple.AppleFSCompression.AppleFSCompressionTypeZlib 1.0.0d1
com.apple.BootCache 34
com.apple.driver.AppleACPIButtons   1.8
com.apple.driver.AppleHPET  1.8
com.apple.driver.AppleRTC   1.5
com.apple.driver.AppleSMBIOS    1.9
com.apple.driver.AppleACPIEC    1.8
com.apple.driver.AppleAPIC  1.7
com.apple.driver.AppleIntelCPUPowerManagementClient 214.0.0
com.apple.nke.applicationfirewall   4.0.39
com.apple.security.quarantine   2.1
com.apple.driver.AppleIntelCPUPowerManagement   214.0.0
com.apple.iokit.IOSerialFamily  10.0.6
com.apple.kext.triggers 1.0
com.apple.driver.DspFuncLib 2.4.7fc4
com.apple.iokit.IOAudioFamily   1.9.2fc7
com.apple.kext.OSvKernDSPLib    1.12
com.apple.driver.AppleSMBusController   1.0.11d1
com.apple.iokit.IOSurface   86.0.4
com.apple.iokit.IOFireWireIP    2.2.5
com.apple.iokit.IOBluetoothFamily   4.1.7f4
com.apple.driver.AppleHDAController 2.4.7fc4
com.apple.iokit.IOHDAFamily 2.4.7fc4
com.apple.iokit.IOAcceleratorFamily 74.17
com.apple.kext.AMD7000Controller    8.1.6
com.apple.kext.AMDSupport   8.1.6
com.apple.driver.AppleGraphicsControl   3.4.5
com.apple.iokit.IONDRVSupport   2.3.7
com.apple.iokit.IOGraphicsFamily    2.3.7
com.apple.driver.AppleSMC   3.1.0d5
com.apple.driver.IOPlatformPluginLegacy 1.0.0
com.apple.driver.IOPlatformPluginFamily 5.4.1d13
com.apple.driver.AppleUSBHIDKeyboard    170.2.4
com.apple.driver.AppleHIDKeyboard   170.2.4
com.apple.iokit.IOUSBHIDDriver  623.4.0
com.apple.driver.AppleUSBMergeNub   621.4.6
com.apple.driver.AppleUSBComposite  621.4.0
com.apple.iokit.IOSCSIMultimediaCommandsDevice  3.5.6
com.apple.iokit.IOBDStorageFamily   1.7
com.apple.iokit.IODVDStorageFamily  1.7.1
com.apple.iokit.IOCDStorageFamily   1.7.1
com.apple.iokit.IOATAPIProtocolTransport    3.5.0
com.apple.iokit.IOSCSIArchitectureModelFamily   3.5.6
com.apple.iokit.IOUSBUserClient 630.4.4
com.apple.iokit.IOFireWireFamily    4.5.5
com.apple.iokit.IOAHCIFamily    2.5.1
com.apple.iokit.IOATAFamily 2.5.1
com.apple.iokit.IOUSBFamily 635.4.0
com.apple.iokit.IONetworkingFamily  3.0
com.apple.driver.AppleEFINVRAM  2.0
com.apple.iokit.IOHIDFamily 1.8.1
com.apple.driver.AppleEFIRuntime    2.0
com.apple.iokit.IOSMBusFamily   1.1
com.apple.security.sandbox  220.3
com.apple.kext.AppleMatch   1.0.0d1
com.apple.security.TMSafetyNet  7
com.apple.driver.DiskImages 345
com.apple.iokit.IOStorageFamily 1.8
com.apple.driver.AppleKeyStore  28.21
com.apple.driver.AppleACPIPlatform  1.8
com.apple.iokit.IOPCIFamily 2.8
com.apple.iokit.IOACPIFamily    1.4
com.apple.kec.corecrypto    1.0
Model: MacPro2,1, BootROM MP21.007F.B06, 8 processors, Quad-Core Intel
Xeon, 3 GHz, 16 GB, SMC 1.7f10
Graphics: AMD Radeon HD 7950, AMD Radeon HD 7950, PCIe, 3072 MB
Memory Module: DIMM Riser A/DIMM 1, 2 GB, DDR2 FB-DIMM, 667 MHz, 0x0198,
0x4B494E4753544F4E00000000000000000000
Memory Module: DIMM Riser A/DIMM 2, 2 GB, DDR2 FB-DIMM, 667 MHz, 0x0198,
0x4B494E4753544F4E00000000000000000000
Memory Module: DIMM Riser B/DIMM 1, 2 GB, DDR2 FB-DIMM, 667 MHz, 0x0198,
0x4B494E4753544F4E00000000000000000000
Memory Module: DIMM Riser B/DIMM 2, 2 GB, DDR2 FB-DIMM, 667 MHz, 0x0198,
0x4B494E4753544F4E00000000000000000000
Memory Module: DIMM Riser A/DIMM 3, 2 GB, DDR2 FB-DIMM, 667 MHz, 0x0198,
0x4B494E4753544F4E20202020202020202020
Memory Module: DIMM Riser A/DIMM 4, 2 GB, DDR2 FB-DIMM, 667 MHz, 0x0198,
0x4B494E4753544F4E20202020202020202020
Memory Module: DIMM Riser B/DIMM 3, 2 GB, DDR2 FB-DIMM, 667 MHz, 0x0198,
0x000000000000000000000000000000000000
Memory Module: DIMM Riser B/DIMM 4, 2 GB, DDR2 FB-DIMM, 667 MHz, 0x0198,
0x000000000000000000000000000000000000
Network Service: Ethernet 1, Ethernet, en0
PCI Card: AMD Radeon HD 7950, sppci_displaycontroller, Slot-1
PCI Card: AMD Radeon HD 7950, ATY,HamachiParent, Slot-1
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@8,4,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@6,4,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@8,5,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@8,6,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@6,5,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@6,6,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@10,4,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@16,4,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@18,4,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@16,5,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@10,5,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@18,5,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@14,4,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@16,6,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@10,6,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@18,6,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@12,4,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@14,5,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@12,5,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@12,6,0
PCI Card: pci1057,3410, sppci_othermultimedia, Slot-4@14,6,0
Serial ATA Device: Samsung SSD 840 EVO 250GB, 250.06 GB
Serial ATA Device: Hitachi HDS722020ALA330, 2 TB
Serial ATA Device: WDC WD20EARX-00PASB0, 2 TB
Serial ATA Device: Hitachi HDS722020ALA330, 2 TB
Serial ATA Device: Samsung SSD 840 EVO 120GB, 120.03 GB
Serial ATA Device: WDC WD3000HLFS-01G6U0, 300.07 GB
Parallel ATA Device: _NEC DVD_RW ND-4570A
USB Device: USB 2.0 Hub [MTT], 0x1a40  (TERMINUS TECHNOLOGY INC.), 0x0101,
0xfd400000 / 3
USB Device: MT4, 0x086a  (Emagic Soft-und Hardware Gmbh), 0x0003,
0xfd440000 / 8
USB Device: CTH-470, 0x056a  (WACOM Co., Ltd.), 0x00de, 0xfd430000 / 7
USB Device: Keyboard Hub, apple_vendor_id, 0x1006, 0xfd420000 / 6
USB Device: Kensington Expert Mouse, 0x047d  (Kensington), 0x1020,
0xfd423000 / 10
USB Device: Apple Keyboard, apple_vendor_id, 0x0250, 0xfd422000 / 9
USB Device: hub_device, 0x050d  (Belkin Corporation), 0x0237, 0xfd300000 /
2
USB Device: iLok, 0x088e, 0x5036, 0xfd370000 / 5
USB Device: iLok, 0x088e, 0x5036, 0xfd360000 / 4
FireWire Device: built-in_hub, 800mbit_speed

I have done MemTest and the RAM is apparently ok. My machine is an upgraded MacPro 1,1 with X5365's and a flashed AMD7950 running 10.8.5. I have an expansion chassis connected with the host card in slot 4.
Really appreciate any help with this.

A: For anyone finding this thread via a Google search, I have found and eliminated the cause of the kernel panics.
The problem was a failing PSU, both, inside the MacPro as well as the Magma expansion chassis. See here for details:
I have since built a Hackintosh and have not had any further problems with intermittent kernel panics.

A: Some years ago I had the problem of frequent kernel panics with my Mac Pro 1,1 ... it turned out that the inside of the case had lots of dust.  When I cleared that out, the kernel panics stopped.
I'm sure every case is different.  This may not help you, but I will put it here for future people who have this problem.


text:
Q: ServiceNow integration with C# and dotnet core application protected void Button1_Click(object sender, EventArgs e)
      {
//Incident Service

        IncidentService.ServiceNowSoapClient soapClient = new IncidentService.ServiceNowSoapClient();
        soapClient.ClientCredentials.UserName.UserName = "username"; // username have SOAP role in SNow.
        soapClient.ClientCredentials.UserName.Password = "Password1";
        IncidentService.getRecords _getRecords = new IncidentService.getRecords();
        IncidentService.getRecordsResponseGetRecordsResult[] getRecordsResponses = soapClient.getRecords(_getRecords);
        _getRecords.active = true;

        // Note: Please enable SOAP/REST services in your SNow dev instance table(s), Also,
        // Go to system web services --> properties -> enable the 3rd option from the bottom.(This property sets the elementFormDefault attribute of the embedded XML schema to the value of unqualified)
        //ServiceNowSoapClient client = new ServiceNowSoapClient();
        //client.ClientCredentials.UserName.UserName = "username"; // username have SOAP role in SNow.
        //client.ClientCredentials.UserName.Password = "Password1";

        //insert newRecord = new insert();
        //insertResponse insertResponse = new insertResponse();
        //newRecord.first_name = "Jackson";
        //newRecord.last_name = "Chris";
        //newRecord.phone_number = "911-911-9999";
        //newRecord.number = "CUS3048232";
        try
        {
            //insertResponse = client.insert(newRecord);
            //TextBox1.Text = insertResponse.sys_id;

            getRecordsResponses = soapClient.getRecords(_getRecords);
            for (int i = 0; i < getRecordsResponses.Length; i++)
            {
                TextBox2.Text = getRecordsResponses[i].short_description;
                TextBox3.Text = getRecordsResponses[i].category;
            }
        }
        catch (Exception ex)
        {
            TextBox1.Text = ex.Message;
        }
        //finally { client.Close(); }

        }
How do you leverage ServiceNow data that reside in enterprise servicenow(CMDB,ITIL,various enterprise dbs, new dbs) dev,prod instances
to create End to End automated applications with C#, dotnetcore.
our goal is to Automate applications end to end with ServiceNow, dotnetcore, C#, docker containers, Ansible, Automic.

A: I know you probably don't need, maybe someone looking for the same finds this question.
I developed an library just for that.
https://emersonbottero.github.io/ServiceNow.Core/


text:
Q: Is Cartopy capable of plotting georeferenced data from another planet (e.g., Mars, the Moon)? I'm working with several data sets from the Moon and Mars (topography, crustal thickness) and was wondering if Cartopy can manipulate these data given the reference ellipsoids are different. Do custom ellipsoids need to be created, or are they built in to Cartopy?

A: I figured out how to do this on my own. Here's the solution I came up with...
Step 1
Import Cartopy...
import cartopy.crs as ccrs

After importing Cartopy and loading your data set, you need to change Cartopy's Globe class such that it does not use the WGS84 ellipse. Simply define new semi-major and semi-minor axes and tell Cartopy to refrain from using a terrestrial ellipse.
img_globe = ccrs.Globe(semimajor_axis = semimajor, semiminor_axis = semiminor, ellipse = None)

Step 2
Next, choose a map projection for plotting and identify your data's format. I decided to plot my data using a Mollweide coordinate system and found my data is defined in the Plate Carree coordinate system. Now we can define the map projection and coordinate system for the data using the new Globe class defined above.
projection = ccrs.Mollweide(globe = img_globe)
data_crs   = ccrs.PlateCarree(globe = img_globe)

Step 3
Lastly, plot your data using standard Matplotlib syntax with two important caveats. First create axes that implement the map projection.
fig = plt.figure(figsize = (6,6))
ax  = plt.axes(projection = projection)

When plotting the data, you have to inform Matplotlib how your data are formatted using the transform argument.
ax.imshow(data, extent = extent, cmap = 'viridis', transform = data_crs)

The end result looks like this...


text:
Q: How to listen submit event from popup window to parent page- cross domain I want to listen click/submit event from popup window to parent page.
Here below code works if both parent and popup window belongs to same domain say http://localhost (check below commented line in code) but it will not call eventHandler method if popup has different domain say echosign.com.
In below code parent window is localhost or anything other than popup.
var newWindow;
function OpenPopup() {
    //newWindow = window.open("http://localhost:21930/Popup.htm", "PopupWindow", "width=300,height=100");
    newWindow = window.open("https://secure.echosign.com", "PopupWindow", "width=300,height=100");
    if (newWindow.addEventListener) {
        newWindow.addEventListener('click', eventHandler, false);
    } else {
        newWindow.attachEvent('onclick', eventHandler);
    }
}

function eventHandler(e) {
    if (e.currentTarget.origin == "https://secure.echosign.com") {
        console.log("Event from Adobe Sign!", JSON.parse(e.data));
    } else {
        console.log(e.currentTarget.origin);
    }
}

A: If you have control on both domains you can set the headers to accept the other domain.
Access-Control-Allow-Origin: http://localhost


text:
Q: References in Chapter Titles I am currently writing a manuscript using \documentclass{book}.  I would like to devote one of the chapters in the manuscript to a proof of an earlier result.  I have named the Chapter:
\chapter{Proof of Theorem \ref{Theorem1}}

and the actual chapter itself (including the chapter name in the table of contents and the chapter title) looks fine.  I have include an image below.

However, in the even numbered pages of the chapter at the top right-hand side of the page is an all-capitalized version of the chapter title, and the reference there does not seem to go through:

I have compiled the code multiple times, so I am sure it is not a compiling error.  Is there any way I can keep the Theorem reference in the title and have it properly show up at the top of the even pages of the chapter?

A: i believe (but am unable to check) that when the chapter title is upper cased for the running head, the name specified with \ref is also uppercased.  this will not match the original label.
make this label "THEOREM1" instead of "Theorem1" and all should be resolved.

A: The following option uses refcount to extract the reference number, but you lose hyperlinking:

\documentclass{book}
\usepackage[paper=a6paper]{geometry}% Just for this example
\usepackage{hyperref,refcount}
\newtheorem{theorem}{Theorem}
\renewcommand{\thetheorem}{\thechapter.\arabic{theorem}}
\begin{document}
\chapter{Proofs of Theorem~\getrefnumber{Theorem1}}
\begin{theorem}\label{Theorem1}
An important theorem.
\end{theorem}
\newpage
Some text.
\end{document}

So, instead of using \ref{Theorem1}, you would use \getrefnumber{Theorem1}.

A: The problem is partly caused by what I believe is a major flaw in the standard classes, that is applying \MakeUppercase to the titles as part of the definition of \chaptermark and \sectionmark, whereas it should be, if desired, applied when typesetting the headers.
However, changing this is not sufficient because \MakeUppercase would capitalize also the label before computing the reference. The package textcase could come to the rescue, but, alas, hyperref redefines \ref with \DeclareRobustCommand so what's seen by \MakeTextUppercase is not \ref (which the macro knows how to handle), but \ref• (where the bullet represents a space in the name): the first level expansion of \foo after
\DeclareRobustCommand{\foo}{...}

is indeed \protect\foo•. This first level expansion happens because the title is passed through \protected@edef.
Here's a possible solution, which

*

*modifies the headings page style definition in order to exchange the place where the uppercasing is performed;

*uses textcase for the uppercasing macros

*modifies the definition of \ref with the help of etoolbox so that it becomes a \protected macro which survives \protected@edef unchanged.
\documentclass{book}
\usepackage[paper=a6paper]{geometry}% Just for this example

\usepackage{textcase}
\usepackage{etoolbox}
\usepackage{hyperref}

\makeatletter
% modify \ps@headings so the uppercasing is done at the right place
\def\ps@headings{%
  \let\@oddfoot\@empty\let\@evenfoot\@empty
  \def\@evenhead{\thepage\hfil\slshape\MakeTextUppercase{\leftmark}}%
  \def\@oddhead{{\slshape\MakeTextUppercase{\rightmark}}\hfil\thepage}%
  \let\@mkboth\markboth
  \def\chaptermark##1{%
    \markboth{%
      \ifnum \c@secnumdepth >\m@ne
        \if@mainmatter
          \@chapapp\ \thechapter. \ %
        \fi
      \fi
      ##1}{}%
   }%
 \def\sectionmark##1{%
   \markright{%
     \ifnum \c@secnumdepth >\z@
       \thesection. \ %
     \fi
     ##1}%
  }%
}
% issue again the style declaration to renew it
\pagestyle{headings}
\makeatother
% modify \ref to become \protected; it needs to be done
% \AtBeginDocument because hyperref delays its redefinitions
\AtBeginDocument{\robustify{\ref}}

\newtheorem{theorem}{Theorem}

\begin{document}

\chapter{Proof of Theorem \ref{theorem1}}

\begin{theorem}\label{theorem1}
An important theorem.
\end{theorem}

\newpage

Some text.

\end{document}

A: This is merely a demonstration of barbara beeton's answer. It does not break hyperlinking.
\documentclass{book}
\usepackage[paper=a6paper]{geometry}% Just for this example
\usepackage{hyperref}
\newtheorem{theorem}{Theorem}
\begin{document}
\chapter{Proof of Theorem \ref{THEOREM1}}
\begin{theorem}\label{THEOREM1}
An important theorem.
\end{theorem}
\newpage
Some text.
\end{document}


text:
Q: Retrieving file name while it's being downloaded For reasons i'm not going to get into i need to get the name of the file that is being downloaded in the instance of that browser.
Is there a way using selenium to get the name of the file being downloaded? Not talking about waiting for it to download and get the name after
I am using selenium with chrome and python.

A: So i ended up going in another direction with this, i am simply creating folders for each browser instance i open and each instance only downloads in that folder and retrieve the name from there.


text:
Q: MS Teams - automatic addin integration I built a MS Teams Add-In. If I create a new meeting, I have to add the Add-In every time manually to this meeting.
Is there any way to integrate it to every (new) meeting by default?
Thank you!

A: Currently there is no way to integrate automatic addin in meeting. Alternatively you can create an event as online meeting using Graph API with below request.
POST https://graph.microsoft.com/v1.0/me/events
Prefer: outlook.timezone="Pacific Standard Time"
Content-type: application/json

{
  "subject": "Let's go for lunch",
  "body": {
    "contentType": "HTML",
    "content": "Does noon work for you?"
  },
  "start": {
      "dateTime": "2017-04-15T12:00:00",
      "timeZone": "Pacific Standard Time"
  },
  "end": {
      "dateTime": "2017-04-15T14:00:00",
      "timeZone": "Pacific Standard Time"
  },
  "location":{
      "displayName":"Harry's Bar"
  },
  "attendees": [
    {
      "emailAddress": {
        "address":"samanthab@contoso.onmicrosoft.com",
        "name": "Samantha Booth"
      },
      "type": "required"
    }
  ],
  "allowNewTimeProposals": true,
  "isOnlineMeeting": true,
  "onlineMeetingProvider": "teamsForBusiness"
}

Please go through this documentation for more info.


text:
Q: Compatibility of ANSI codes in python? I use ANSI colour codes in my python programs ( like this print("\u001b[36;1mExample!") ) and once I sent one of my programs to my friend but for them it printed "\u001b[36;1mExample!" instead of changing the colour of the text and printing "Example!" like it does for me on WINDOWS10 and as it should do.
So I was curious which OS's will actually change the colour as it should and which will just print the colour code? Or does it depend on something other than OS?
Thanks!


text:
Q: Will my app get rejected on warnings? Will my app be rejected on warnings in the console like:
Unable to simultaneously satisfy constraints
Or does this not matter?

A: Your app will only get rejected if it doesn't comply to Apple's standards (which you can look up), i.e. it crashes, has some weird behaviour, inappropriate content, plagiarism and so on. However warnings usually show you that there is something unusual in your code (or StoryBoard/XIB file). Even if it doesn't directly jeopardize your chances of getting your app into the app store I suggest you try to reorganize your constraints. Apple might change the way Xcode resolves these conflicts in the future and could possibly break your User Interface.


text:
Q: *ngFor is not working angular for calling data from api I am trying to get data from api and show it on frontend but *ngFor is not working I checked all variables are working correctly and the data is showing in console.log but not showing on frontend, below I have shared you screenshot for the same
Thank you in advance,

A: you declear the projects property in any but this is array.so  projects property declear projects:any=[]; like this


text:
Q: In Python what is the best way to read a pdf table with no outline? I am trying to read data from a table in a pdf into a pandas dataframe. I am able to do so using tabula-py when the pdf has outlines around the table, but when I try on the pdf without an outline the script produces an error.
For example, I am looking at the pdfs available from two different urls. I have downloaded the pdfs from the urls and saved them as 'JSE Opts.pdf' and 'JSE Divs.pdf' respectively.
import requests
import pandas as pd

url='https://clientportal.jse.co.za/JSE%20Equity%20Derivatives/Dividends/ED_DividendsReport.pdf'
response = requests.get(url)
fname = 'JSE Divs.pdf'
f= open(fname, 'wb')
f.write(response.content)
f.close()

url='https://clientportal.jse.co.za/JSE%20Equity%20Derivatives/Options%20Daily%20Traded%20Report/ED_OptionsDailyTradedReport.pdf'
response = requests.get(url)
fname = 'JSE Opts.pdf'
f= open(fname, 'wb')
f.write(response.content)
f.close()

I am able to read the 'JSE Opts.pdf' into a pandas dataframe using the code:
import tabula as tb

pdf = './JSE Opts.pdf'
data = tb.read_pdf(pdf,pages = 1)
data = data[0]
print(data)

When I try to do the same for 'JSE Divs.pdf', I get errors and tabula-py is only able to read the header:
pdf = './JSE Divs.pdf'
data = tb.read_pdf(pdf,pages = 1)
data = data[0]
print(data)

I suspect that this is because there are no lines around the table. If that is the case, what is the best way to go about reading the data from 'JSE Divs.pdf' into pandas?

A: I was able to read the data into a string using pdfplumber, save the string as a CSV file (after cleaning the data to suit my needs) and then import into pandas.
import pdfplumber
pdf = pdfplumber.open("./JSE Divs.pdf")

text = ''
i = 0
while True:
    try:
        text += pdf.pages[i].extract_text() + '\n'
        i = i+1
    except IndexError:
        break

for replace_s in [' DN',' CA1',' ANY',' CSH',' PHY',' QUANTO']:
    text = text.replace(replace_s,'')

while True:
    try:
        idx = text.index('EXO')
        replace_s =text[idx-1:idx+8]
        text = text.replace(replace_s,'')
    except ValueError:
        break

cols ='EXPIRY_s,USYM,EXPIRY,EX_DATE,CUM_PV_DIVS,CUM_DIVS,ISIN,INSTR_ID\n'
text = text[text.index('Div\n')+4:]
text = cols + text
text = text.replace(' ',',')

f = open('divs.csv','w')
f.write(text)
f.close()


text:
Q: Show internal server error? I have the following output when running my web application:
The page cannot be displayed because an internal server error has occurred.

Screenshot:

In my web.config, the following are set:
<system.web>
    <customErrors mode="Off"/>
</system.web>
<system.webServer>
    <asp scriptErrorSentToBrowser="true"/>
    <httpErrors errorMode="Detailed"/>
</system.webServer>

How do I see what the error is?
This is hosted locally in the Azure Compute Emulator.

A: In addition to the configurations you have done, if you are using Internet Explorer, turn off the option "Show friendly HTTP error messages" in the "Advanced" tab.
Another option is to enable tracing in your application so you can use the trace viewer to look for exceptions.
You might also find value in deploying ELMAH with your application for improved error handling.

A: It can be due to various reasons. Most likely some misconfiguration.
In my case it was the LocalWebDevelopmentServer setting. Setting it to IISExpress fixed the problem.


text:
Q: React Native App renders nothing without errors I am building react native app and when I run it on android it renders nothing, as well it doesn't throw any errors...
I don't know which piece of code to put here so please tell me in the comments what should I add from the code here.
This is App.js file(react-native-navigation is being used here!):
Navigation.startTabBasedApp({
  tabs:[
      {
        screen:"APB.ChoosePlatformScreen",
        label: "Log In",
        title:"Log In",
        icon: HomeIcon,
      },
      {
        screen: "APB.ResgisterScreen",
        label: "Register",
        title:"Register",
        icon: HomeIcon
      },
],
appStyle: {
  tabBarBackgroundColor: "#e8e8e8",
  tabBarButtonColor: "#555",
  tabBarSelectedButtonColor: 'black',
  tabBarSelectedBackgroundColor: "#e8e8e8",
  forceTitlesDisplay: true,
  showLabel: true,
},
tabBarOptions: {
  showLabel: true
}
})

Above all of this are all the file imports an all screens are registered, I didn't put it in so the code is not too long.


text:
Q: Test if a component is passing an @Input to another I'm fairly new to unit testing. I wonder how I could test if a smart component is passing some as an @Input() to a dumb one (using Angular 4+).
At first, I thought about checking if the property exists:
it('should have some data', async(() => {
  expect(component.data).toBeTruthy();
}));

However, I faced two issues: 1) that tells me if data is true but doesn't necessarily means it's being passed as an input to my dumb component; 2) if the data property doesn't exist, then the test suite won't be executed.
Any tips? Is there a better way to approach this? Thanks.

A: Since input bindings are processed as part of change detection you can basically change the property used in bindings on the parent component, then run detectChanges() on the parent component and check if the input property has changed in the child component. Something along these lines:
parentComponent = TestBed.createComponent(BannerComponent);
const childComponentEl = fixture.debugElement.query(By.directive(ChildComponent));
const childComponent = childComponentEl.injector.get(ChildComponent);

it('should have some data', async(() => {
  parentComponent.componentInstance.boundProperty = 3;
  parentComponent.detectChanges();
  expect(childComponent.inputProperty).toBe(3);
}));

You can read more about why input bindings update in:

*

*Everything you need to know about change detection in Angular

*The mechanics of property bindings update in Angular


text:
Q: Sending an object over the Internet I define a class, and then I instate an object of that class type. I want to send this object to another Java application running on a different computer transparently. What is the best technology to accomplish this?

A: There are a lot of ways to do this. Here are some things to look into and you can pick the one that would work best for your application.

*

*J2EE

*RMI

*Object Serialization pushing the bits over a Socket

*Webservices

Pretty much any communication framework will allow you to push objects over a network in one way or another.  You just need to review them and see which works for your application.  A quick google should find even more methods.

A: A (de facto) standard to implement this would be to use a web service, for example using JAX-WS which is bundled in Java 6. See this tutorial for a java-first sample (i.e. using annotations). This is pretty straight forward and easy.
There are other approaches such as Serialization over a Socket, RMI, EJBs but, when working over the Internet, web services are a kind of natural choice as they rely on existing standards (SOAP, HTTP) and deal easily with firewalls (which might be a real issue for all other solutions).

A: Java provides (binary) object serialization using the ObjectOutputStream (and ObjectInputStream). You can just writeObject() into the stream and readObject() on the other end. All you need to do for this to work is implement the Serializable interface.
But rather than doing that manually, you may be interested in taken it one level up and using Remote Method Invocation. With RMI you can call methods on objects that live in another JVM, and all the serialization and networking happens under the hood.
And for the sake of completeness, there is also XML bean serialization, if you cannot use the binary format. That XML format is very generic (read: verbose and ugly), but there are some popular libraries (like XStream) that create alternative XML serializations.

A: You'll want to start by looking into serialization with the Java Serializable interface.  Sun has a good article on it called Discover the secrets of the Java Serialization API.
Refer to the Java Sockets tutorial for information on actually transferring the serialized object over the network.

A: you can create object streams using the java API and send any serializable object. but you'll have to mind that these go unencrypted through the network:
on the sender's side:
CustomObject objectToSend=new CustomObject();
Socket s = new Socket("yourhostname", 1234);
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
out.writeObject(objectToSend);
out.flush();

and on the receiving end:
ServerSocket server = new ServerSocket(1234);
Socket s = server.accept();
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
CustomObject objectReceived = (CustomObject) in.readObject();