text:
Q: JFET I drain vs V gate to source curves Why there are several curves on next image (datasheet for 2SK170)? What condition changes to use one or another curve?

A: Idss is what is different. Idss is a characteristic of the individual JFET, much like hFE of a BJT varies from one unit to the next, and much like hFE the JFETs are 'binned' into three broad ranges so your circuitry does not necessarily have to deal with the entire roughly 10:1 range (the 2.6~20mA range only applies at 25 degrees C junction temperature).


text:
Q: How to fix the header of mat-tab I am having 5 mat-tab and each tab is having a large amount of data so scroll is getting added to that window. Is there any way through which I can fix the header of mat-tab and let the content to be scroll able.
I tried putting position:fixed; and position:sticky inside
::ng-deep .mat-tab-label {

}

But it do not seems to solve the problem.
my html

  <mat-tab-group class="demo-tab-group" (selectedIndexChange)="loadDynamicContent($event)">
    <mat-tab matTooltip="Tooltip!" label="Pers info">

Customer Information

            {{item.key}}

          {{item.value}}

Aadhaar Address

            {{item.key}}

          {{item.value}}

Present Address

            {{item.key}}

          {{item.value}}

Financial Health Information

            {{item.key}}

          {{item.value}}

    </mat-tab>
    <mat-tab label="Bureau A">

Bureau Analysis Data

            {{item.key}}

          {{item.value}}

Bureau Score Reasons

      {{item.key}}

    {{item.value}}

Total EMI in CIBIL

            {{item.key}}

{{item.value}}

    </mat-tab>
    <mat-tab label="Bureau E">

Enquiries in last 30 days

          Number of enquiries
          Average amount

            {{item.key}}

          {{item.value}}
          {{item.value2}}

Enquiries in last 31-90 days

          Number of enquiries
          Average amount

            {{item.key}}

          {{item.value}}
          {{item.value2}}

    </mat-tab>
    <mat-tab label="SMS">

SMS Data Analysis

            {{item.key}}

          {{item.value}}

0">

Salary

        S.No
        SMS Date
        Sender Name
        Original Message

              {{i+1}}

            {{item.smsDate}}
            {{item.senderName}}
            {{item.originalMessage}}

0">

Insufficient, bounce, return, overdue

        S.No
        SMS Date
        Sender Name
        Original Message

              {{i+1}}

            {{item.smsDate}}
            {{item.senderName}}
            {{item.originalMessage}}

0">

EMI, ECS & NACH

          S.No
          SMS Date
          Sender Name
          Original Message

              {{i+1}}

            {{item.smsDate}}
            {{item.senderName}}
            {{item.originalMessage}}

0">

Bureau

          S.No
          SMS Date
          Sender Name
          Original Message

              {{i+1}}

            {{item.smsDate}}
            {{item.senderName}}
            {{item.originalMessage}}

0">

Company Salary

        S.No
        SMS Date
        Sender Name
        Original Message

              {{i+1}}

            {{item.smsDate}}
            {{item.senderName}}
            {{item.originalMessage}}

0">

Loan

        S.No
        SMS Date
        Sender Name
        Original Message

            {{i+1}}
            {{item.smsDate}}
            {{item.senderName}}
            {{item.originalMessage}}

0">

Score

        S.No
        SMS Date
        Sender Name
        Original Message

            {{i+1}}
            {{item.smsDate}}
            {{item.senderName}}
            {{item.originalMessage}}

0">

All SMS

            S.No
            SMS Date
            Sender Name
            Original Message

            {{i+1}}
            {{item.smsDate}}
            {{item.senderName}}
            {{item.originalMessage}}

    </mat-tab>
    <mat-tab label="Device">

Device Data

            {{item.key}}

          {{item.value}}

0">

Wi-Fi Connections Information

0">
          Wi-Fi Name
          No. of times connected in the last 7 days

            {{item.key}}

          {{item.value}}

0">

Account Information

          Email
          Vendor

            {{item.email}}

          {{item.vendor}}

    </mat-tab>
    <mat-tab label="Json">
      <mat-card>
        <app-ngx-json-viewer [json]="bureauJSON"></app-ngx-json-viewer>
      </mat-card>
    </mat-tab>
  </mat-tab-group>

css
mat-grid-tile {
  background: lightgrey;
}

h4 {
  color: grey;
  text-align: center;
}

.key {
  padding-left: 75px !important;
  font-weight: bold;
  color: gray;
}

.not-available {
  margin-top: 15%;
 text-align: center;
  font-size: 14px;
}

.mat-tab-body-content {
  height: 100%;
}

.value {
  padding-left: 75px !important;
  color: gray;
}

::ng-deep .mat-tab-labels {
   justify-content: center;
   padding: 0px 7px !important;
   font-size: 10px !important;
}

::ng-deep .mat-tab-label {
  justify-content: center;
  padding: 0px 7px !important;
  font-size: 12px !important;
  min-width: 85px !important;

}

.hide {
  border: none !important;
}

#customers {
  padding:0;
  margin:0;
  font-family: 'Roboto', 'Helvetica Neue', sans-serif;
  font-size: 12px;
  font-weight: 500;
  width: 100%;
  border-collapse: collapse;

}

td {
  color: #808080;
}

.container {
  overflow-y: auto;

}

#customers td,
#customers th {
  border: 1px solid #ddd;
  padding: 2px;
}

#customers tr:nth-child(even) {
  background-color: #f2f2f2;
}

#customers th {
  color: gray;
  text-align: left;
  border-collapse: collapse;
}

A: Solved it using position: fixed !important; inside
:host ::ng-deep .mat-tab-header {
}

But then the tab was not clickable so added z-index:100000; and then it starts working.

A: Solved it using
::ng-deep .mat-tab-body-wrapper {
           height: 75vh; //required height
}

A: mat-tab-group {
  height: 100%;
  overflow-y: auto;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angularjs pass simple string to component I'm desperately trying to pass a simple string to an AngularJS component,
I have the following angularJS component:
async-typeahead.componenet.js:
angular.module('asyncTypeahead').component('asyncTypeahead', {

    templateUrl: 'static/partials/async-typeahead/async-typeahead.template.html',
    bindings: {
        pk: '=',
        object: '=',
        objectType: '@'
    },
    controller: ['$scope','$http',
        function AsyncTypeaheadController($scope, $http) {

             var self = this;

            self.getTags = function (val) {
                console.log("async-typeahead input is: " +val);
                console.log("async-typeahead object keys are: " + angular.toJson(self.object));

                console.log("async-typeahead type is: " + angular.toJson(self.objectType));...

And following html to call the component:
<async-typeahead object="$ctrl.actor.actor_tags" objectType={{ This is just a string }}></async-typeahead>

'val' is just an input from the typeahead.
I've tried objectType={{ This is just a string }} and  objectType="This is just a string" and objectType=This is just a string I also tried changing the binding from '=' to '@' or '>' the result is the same:
whenever I look at the console I always I get:

async-typeahead input is: df
async-typeahead object kes are: [37,43,49]
async-typeahead type is: undefined

What am I doing wrong? How can I pass a simple string to an angularJS component?

A: Issue with objectType attribute which you have used in html. Directive/Component name and its all attributes should used as "-" delimited.
Correct code is attached below:
<async-typeahead object="$ctrl.actor.actor_tags" object-type="This is just a string"></async-typeahead>


text:
Q: Use of the can? method with a each When I read the documentation of cancan you can do something like this:
<% if can? :edit, @product %>

Now I have the following code and there it doesn't work.
<% @products.each do |product| %>
  <% if can? :sort, |product| %>
    MyButton
  <% end %>

How can I make sure this works as well?  What syntax do I need to use?  I hope I don't need to do a
@product = Product.find(|product|.id)

because that would clutter the views.

A: Each time you should pass to can? method Product instance, which is in product local variable, so:
<% @products.each do |product| %>
  <% if can? :sort, product %>
    MyButton
  <% end %>
<% end %>


text:
Q: java exception: No such file or directory I am trying to run a GATE application via jetty web application server in Ubuntu. I am getting
java.io.IOException:

error=2,

No such file or directory because of a particular GATE plugin (MultiPaX) which is trying to access "minipar.linux" located in
WEB-INF/gate-files/application-resources/Parser_Minipar/minipar.linux

I have set read and write permissions to this file and directory, as well as allowing executing the file as a program. I get a Permission Denied error, when disallowing program execution.  I have set all directories containing the file +x via chmod -R 755 /all/directories/up/to/file/
Is this a file permission problem? or could there be another cause?

A: Since it's a "Permission Denied" error, it'd definitely a permissions error.
Try chmod 666 and see if that fixes it. That gives everyone read/write access.
You don't want to open it up like that though, so if it does fix it, then chown the file to the user who is running Jetty and chmod it back to 644.
To find the user running Jetty:
ps aux | grep jetty

To change ownership of the file:
chown jettyuser.jettyuser /path/to/file


text:
Q: How can i understand Python about list. help me please score = [88,95,70,100,99,80,78,50]
score[1:4]=[]
print(score)

I expected this code snippet to print [95,70,100]. Instead, it printed out [88, 99, 80, 78, 50]. Why is this so?

A: On the second line, the code takes a list slice and then sets it to the empty list, effectively removing them from the original score list.
The following line prints the score list, with items originally at indices 1, 2, and 3 removed. You're mixing up the items remaining in the score list with the ones that were just removed.


text: Q: Estimating conditional probability distribution from samples I have three continuous variables, $X$, $Y_1$ and $Y_2$. All three are correlated. For a given value of $X$, the conditional probability distributions of $Y_1$ and $Y_2$ are typically bimodal. I'm given a set of samples with measurements for the three quantities, and would like to come up with a way to predict the conditional probability distributions of $Y_1$ and $Y_2$ (or at least the median and $1\sigma$ error bars) for future measurements of $X$. How would you go about doing this?


text:
Q: Would an expression tree work here? I have the below method that I currently use to get the DB length of certain string fields (each property has an attribute called MetaDataFieldAttribute). It seems to work nicely however it's very 'stringly' typed with the property name.
     public static void Main(string[] args)
        {
            ...
            obj.PropertyName = str.TrimIfRequired(obj, "PropertyName");
        }

        public static string TrimIfRequired(this string str, object obj, string property)
        {
            var pi = obj.GetType().GetProperty(property);
            var attribute = pi.GetCustomAttributes<MetaDataFieldAttribute>().FirstOrDefault();
            if (attribute == null) return str;

            int length = attribute.Precision;
            return str.Length > length ? str.Substring(0, length) : str;
        }

I have a fairly basic understanding of expression trees, and my initial thought is that I could make the object/parameter of the method strongly typed rather than just passing through the string. Is this possible?

A: Yeah, you can use Expressions here just to get strong typing for property names, so instead of writing property name as string, you can use expression with property access, and then code will get MemberInfo item for specific property from expression and will get attribute from here. So if you change propertyName in the future, this part won't compile as it will be strong typed.
here is working sample on .NetFiddle - https://dotnetfiddle.net/qYOfhE
And here is the code itself:
using System;
using System.Linq;
using System.Linq.Expressions;

public class Program
{
    public static void Main(string[] args)
    {
        var str = "TestTestTest";

        var propertyName = str.TrimIfRequired<Customer>((c) => c.FirstName);
        var propertyNameValue = str.TrimIfRequired<Customer>((c) => c.Age);
        Console.WriteLine(propertyName);
        Console.WriteLine(propertyNameValue);
    }
}

public static class Extensions
{
    public static string TrimIfRequired<T>(this string str, Expression<Func<T, object>> expr)
    {
        var me = expr.Body as MemberExpression;
        if (me == null && expr.Body is UnaryExpression)
        {
            me = ((UnaryExpression) expr.Body).Operand as MemberExpression;
        }

        if (me == null)
        {
            throw new ArgumentException("Invalid expression. It should be MemberExpression");
        }

        var pi = me.Member;
        var attribute = pi.GetCustomAttributes(typeof(MetaDataFieldAttribute), false).FirstOrDefault() as MetaDataFieldAttribute;
        if (attribute == null) return str;

        int length = attribute.Precision;
        return str.Length > length ? str.Substring(0, length) : str;
    }
}

public class Customer
{
    [MetaDataField(Precision = 6)]
    public string FirstName { get; set; }

    [MetaDataField(Precision = 2)]
    public int Age { get; set; }
}

public class MetaDataFieldAttribute : Attribute
{
    public int Precision { get; set; }
}

A: It would work, but only if inside Main the 'obj' variable had a well-known type. object is not enough, because any expression trees given object as the referred type will simply not see any actual members. But since you already assign to the PropertyName, then it seems you have that variable typed.
Your TrimIfRequired would also need to be changed, i.e. to:
public static string TrimIfRequired<T>(this string str, T obj, Expression<Func<T,object>> propexpr)

used like this:
obj.PropertyName = str.TrimIfRequired(obj, o => o.PropertyName);

or
public static string TrimIfRequired<T>(this string str, Expression<Func<T,object>> propexpr)

used like this (without object instance, but with type explicitely stated)
obj.PropertyName = str.TrimIfRequired<MyType>(o => PropertyName);

First one is nice, since you just give the obj and C# automatically picks T for that and lambda also can use it immediatelly. However, you need to have the obj variable. Second example is useful when you know the concrete type, but don't have any variable or instance to pass. That's rare however.
In both cases, you get an Expression<Func<T,..>> that you need to analyze. Most often, you will get MemberExpression (property, field) and from it you will need to extract the property name. But keep in mind that the user can write anything in the lambda - for the compiler, o => { foreach(..) {..}; return 1;} is just as good as o => o.PropertyName, so you should detect if correct expression was passed and provide at least some minimal developerror handling.
BTW1. Instead of Func you may also use Action, but I think they are odd in usage in this context.
However, since you effectively want to trim an object's property length to some restriction defined on that property, I think that following tools would be more useful or ergonomic:
1) helper that immediately writes the value (get the propertyinfo as with any other expression, then use the fact the helper was called on this obj and use it to call PropertyInfo.SetValue)
obj.TrimIfRequired(o => o.PropertyName);

2) helper that walks over properties and applies all restrictions to all properties (we know the object's runtime Type, we can scan its Properties, get their Attributes, we know exactly what needs trimming)
obj.TrimAllIfRequired();


text:
Q: Pyinstaller created exe file cannot load Decision Tree model using joblib I created an exe file of my large python script using the following command -
pyinstaller gui_final.py --onefile --hidden-import=sklearn --hidden-import=ipaddress --hidden-import=PIL --hidden-import=pickle --hidden-import=shutil --hidden-import=joblib
The exe file works fine until I load my decision tree model file (dtree.joblib) using JOBLIB.
clf = joblib.load("dtree.joblib")

The following error pops up - Here is the complete error in the terminal:
ModuleNotFoundError: No module named 'sklearn.ensemble._weight_boosting'

I tried updating the hidden_imports by adding just sklearn.ensemble and sklearn.ensemble._weight_boostin later to the spec file of the exe by following steps in this answer. steps also given below
from PyInstaller.utils.hooks import collect_submodules

hidden_imports = collect_submodules('sklearn.ensemble') #('sklearn.ensemble._weight_boosting')

a = Analysis(['gui_final.py'],
         binaries=None,
         datas=[],
         hiddenimports=hidden_imports,
         .
         .

By running the command:
pyinstaller gui_final.spec

But still got the same ModuleNotFoundError as earlier after running the exe.
I have tried looking at some issues regarding joblib with pyinstaller, but have not found any suitable issues or solutions.
Can anyone suggest steps to make the exe of the script runnable?

A: I had some similar issues and it was solved by collecting the whole sklearn module, not just the one which was missing. I do not understand why, but that solved my problem. Perhaps it will help you too
from PyInstaller.utils.hooks import collect_submodules
hidden_imports = collect_submodules('sklearn')


text:
Q: is it possible to use the .java extension files in Xcode? can I call the java extension files in the Xcode?.i.e Can I create the Object for that class.
Thanks in advance

A: I think it is not possible as far as my knowledge

A: Xcode used to have some support for Java (e.g. you could have java projects).
now, you would have to setup custom build phases for your Java sources. so, it could function as a tool, but i think most of the functionality has been pulled by now - you'd actually have better luck using older versions of Xcode, which included project and target templates for Java stuffs.
on osx, Idea or Eclipse (or others) is better suited for Java.


text:
Q: React Sub-path creates error when directly enter the URL in browser i have the below Route path in my react code.
<Route path="/company-group/:action" exact component = {CompanyGroupForm}  />

This works fine when  go to the url from my webpage using link  <Link to="/company-group/add">Add</Link>
But it gives error if I directly enter the actual path (http://localhost:8000/company-group/add) in browser
This is the error I am getting
Uncaught SyntaxError: Unexpected token '<'

Whats going wrong here


text:
Q: Are there any databases that focus on query and read performance? Are there any databases that focus more on insanely fast read/querying performance? I am looking for a good nosql document database that I don't plan for any significance writes (updating the database is only done by me on a weekly schedule). The type of query I will be doing are keyword searches that will search multiple string fields and interval searching that will look for elements within/overlap an interval.
I was looking at Redis initially, but I needed something a bit more extensive than key/value to store my data. MongoDB looks like a good choice?

A: There are many possible solutions for your problem, the right solution depends mostly on the scale and the actual use case.
Redis does quite a bit more than simple key/value storage, but I doubt that it's what you need right now.
For mostly read only storage and these type of searches I would recommend taking a look at Elasticsearch and/or Solr, should do what you need and more.
Basically... fast to read, slow to write means lots of denormalisation. You can do that yourself, you can (with some apps) let the database take care of it. But it's always a trade off.


text:
Q: Can App create by Android Studio be submitted to Google Play Store? Under iOS, one can't use beta Xcode to create submitted for AppStore.  Can Android Studio be used to develop app submitted for Play Store?

A: submitting an app to google play store requires you to upload an signed .apk file.

Can Android Studio be used to develop app submitted for Play Store?

Yes
But you need to export a signed apk file, then login to google play account, and upload it

A: Yes it's possible, I've done it myself, you'll generate a .apk with AS and it's definitely usable on Google Play Store !
Here are all the steps to get your app ready for the Google Play Store; Here is the way to sign your apk using Android Studio.
I hope this answer helps =)

A: Yes, it can. At the end do Build > Generate signed APK and fill out the relevant information (Google around if you get lost). Then, you get a Google Play Developer account for $25 (£18) and upload your apps.


text:
Q: Append all possible combinations of letters to txt file I'm trying to store all possible combinations of 4 letters from [Aa-Zz]. The problem is that I've got error 500 when I try to use the function below. When I try with a simple string it is working.
Here is the code that I have so far
function print_combinations($characters, $length, $combination = '') {
    foreach ($characters as $i) {
        print_combinations($characters, $length - 1, $combination . $i);
    }
}

$characters = array_merge(range('A', 'Z'), range('a', 'z'));

$filename = 'test.txt';
$combos = print_combinations($characters, 4);

if (is_writable($filename)) {

    if (!$fp = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    if (fwrite($fp, $combos) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($combos) to file ($filename)";

    fclose($fp);

} else {
    echo "The file $filename is not writable";
}

If I change
$combos = print_combinations($characters, 4);

to
$combos = "some text;

it is working fine. So the problem is in how I call the function probably.
Any suggestions on this?

A: Looking for something like this?
<?php

$filename = 'test.txt';

if (is_writable($filename) && ! $fp = fopen($filename, 'ab')) {
    echo "Cannot open file ($filename)";
    exit;
}

$characters = [
    array_merge(range('A', 'Z'), range('a', 'z')),
    array_merge(range('A', 'Z'), range('a', 'z')),
    array_merge(range('A', 'Z'), range('a', 'z')),
    array_merge(range('A', 'Z'), range('a', 'z')),
];

$counts = array_map("count", $characters);
$total  = array_product($counts);

$combinations = [];
$curCombs     = $total;

foreach (array_keys($characters) as $field) {
    $curCombs            /= $counts[$field];
    $combinations[$field] = $curCombs;
}

$counter = 0;

for ($i = 0; $i < $total; $i++) {
    $test = [];
    foreach ($characters as $field => $value) {
        $test[$field] = $value[(int) ($i / $combinations[$field]) % $counts[$field]];
    }

    if (! fwrite($fp, implode($test))) {
        echo "Cannot write to file ($filename)";
        exit;
    }
    ++$counter;
}

echo "Success, wrote ($counter) to file ($filename)";


text:
Q: ¿Cómo maquetar la columnas de bootstrap para dipositivos móviles? Estoy teniendo un problema con el sistema de columnas, es que ni se me rellena la pantalla ni se me oculta la columna que quiero cuando pongo la pantalla en tamaño de dispositivo móvil. Ya he probado con las dimensiones de xl,lg,md,sm y xs pero no me sale, así que probé por dejarlas todas sin definir tamaño y nada, tampoco funcionaba, la columna que quiero que desaparezca es la que sale de color rojo cosa que tampoco consigo usando d-none ni d-md-block y tampoco desaparecía y ya no sé que hacer.
<!doctype html>

    <title>Hello, world!</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,  initial-scale=1,    shrink-to-fit=
no">

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

.col-8

.col-4

                .col-8

col 6

col 6

col 2

col 2

col 4

col 2

col 2

col 2

col 2

col 4

col 2

col 2

col 12

A: Bootstrap 4 tiene un modelo de mobile first en el cual ya no se encuentra el  breakpoints xs, pero siguen: sm,md,lg y xl, siendo todos estos:
.col,//media (min-width:0px)
.col-1,
.col-10,
.col-11,
.col-12,
.col-2,
.col-3,
.col-4,
.col-5,
.col-6,
.col-7,
.col-8,
.col-9,
.col-auto,
.col-sm,//@media (min-width:576px)
.col-sm-1,
.col-sm-10,
.col-sm-11,
.col-sm-12,
.col-sm-2,
.col-sm-3,
.col-sm-4,
.col-sm-5,
.col-sm-6,
.col-sm-7,
.col-sm-8,
.col-sm-9,
.col-sm-auto,
.col-md,//@media (min-width:768px)
.col-md-1,
.col-md-10,
.col-md-11,
.col-md-12,
.col-md-2,
.col-md-3,
.col-md-4,
.col-md-5,
.col-md-6,
.col-md-7,
.col-md-8,
.col-md-9,
.col-md-auto,
.col-lg,//@media (min-width:992px)
.col-lg-1,
.col-lg-10,
.col-lg-11,
.col-lg-12,
.col-lg-2,
.col-lg-3,
.col-lg-4,
.col-lg-5,
.col-lg-6,
.col-lg-7,
.col-lg-8,
.col-lg-9,
.col-lg-auto,
.col-xl,//@media (min-width:1200px)
.col-xl-1,
.col-xl-10,
.col-xl-11,
.col-xl-12,
.col-xl-2,
.col-xl-3,
.col-xl-4,
.col-xl-5,
.col-xl-6,
.col-xl-7,
.col-xl-8,
.col-xl-9,
.col-xl-auto

Tú utilizas col-x siendo x el numero en la columna, siendo este una vista para pantallas móviles y superiores. Entonces, debes de aclarar los tamaños en cada tipo de dispositivo.
Para tu problema modifiqué las siguientes líneas:

.col-4

Indicando que la sección roja: será de tamaño 4 (col-4) desde dispositivos móviles, pero también indico que su display será none (d-none, ocultando el div) desde dispositivos móviles, pero que a partir de tabletas el display será block(d-md-block, mostrando el div).
Si le pones atención, también modifico el div hermano en dispositivos tableta.
Ademas, también añadí jquery.3.3.1 ya que es imprescindible para algunas funcionalidades de Bootstrap.
RESULTADO:

<!doctype html>

    <title>Hello, world!</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,  initial-scale=1,    shrink-to-fit=
no">

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

.col-8

.col-4

                .col-8

col 6

col 6

col 2

col 2

col 4

col 2

col 2

col 2

col 2

col 4

col 2

col 2

col 12

Para apreciar mejor los resultados debes verlo también en pagina completa.


text:
Q: Is there something like @JsonIgnoreOtherProperties? Jackson has the @JsonIgnoreProperties annotation at field level which is awesome, but sometime it can be big.
@JsonIgnoreProperties({ "name", "phone", ... "20th item"})
private User user;

I'm looking for something like:
@JsonIgnoreOtherProperties("email")
private User user;

So this would ignore all fields but email.
Is there something like @JsonIgnoreOtherProperties ?

A: I don't think that exists but there are several ways of achieving what you want (other than your existing solution):
1) Using @JsonView (http://wiki.fasterxml.com/JacksonJsonViews). See What is the JSON View class in Jackson and how does it work? for an example.
2) Creating a different User view which contains a minimal set of fields, perhaps UserMinimal. It might inherit from a common interface as your other User view to show they really represent the same entity.
3) Customizing the object mapper and using a filter. See How do I exclude fields with Jackson not using annotations? for an example.
Personally, I prefer the first solution if you have a simple use case and the second if you have a more complex one. I dislike the third option as I think customizing object mappers leads down an error prone path in my experience.
Your annotation idea sounds interesting though. I would consider putting it as a feature request (I think it would go https://github.com/FasterXML/jackson-annotations/issues).


text:
Q: What is the ( best | fast ) way to get multiple HTTP Request Header In PHP Example : But, loading pages really slow.

Any other PHP code or JavaScript.

My example code in PHP:

<?php
$aaalink = 'http://www.bbc.com/news';
function aaa_get_http_response($aaalink) {$headers = get_headers($aaalink);return substr($headers[0], 9, 3);}
$aaa_get_http_response = aaa_get_http_response($aaalink);
if ( $aaa_get_http_response == 200 )
{
echo $aaalink;
}
else
{echo "404";}
?>

<?php
$bbblink = 'http://www.independent.ie/news/';
function bbb_get_http_response($bbblink) {$headers = get_headers($bbblink);return substr($headers[0], 9, 3);}
$bbb_get_http_response = bbb_get_http_response($bbblink);
if ( $bbb_get_http_response == 200 )
{
echo $bbblink;
}
else
{echo "404";}
?>

<?php
$ccclink = 'http://www.rediff.com/news';
function ccc_get_http_response($ccclink) {$headers = get_headers($ccclink);return substr($headers[0], 9, 3);}
$ccc_get_http_response = ccc_get_http_response($ccclink);
if ( $ccc_get_http_response == 200 )
{
echo $ccclink;
}
else
{echo "404";}
?>

Image:

A: The get_headers will wait until the requested website responds, the network quality matters. aaa/bbb/ccc_get_http_response is the same, use a foreach loop instead.


text:
Q: Populating one array with elements of another array. Exceeding the length of the second array exception I have an assignment and I have come to a stumbling point where I get an exception that I am putting more elements in the array than in can hold. I have tried to make the array bigger, but it always goes beyond its bounds. Here is the code: .NetFiddle.
The problematic part starts on line 43 and the exception is thrown on line 52:
 else
        {
            int x = 0;
            int SumValue = 0;
            int[] fibArray = new int[novArr.Length];

            for (x = 0; x < novArr.Length-1; x++)
            {
                if (x + 1 < novArr.Length)
                {
                    fibArray[SumValue] = novArr[x] - novArr[x + 1];
                }
                SumValue++;
            }
            Value = (fibArray.Max(element => Math.Abs(element)));
        }


text:
Q: Setting Permission for Files in the network I need to set permission for a drive on a network where user can edit and update the file but the must not copy the files from the network drive to local system.

A: Ah! This is impossible, anyone who can edit and update files already has read permissions on the file, so he can surely copy it to his/her local machine. It can only be circumvented by using complex methods such as a web-based service.


text:
Q: finding previous rows that match current row in table I have a basketball dataset with column A representing different teams. Is there a good way to extract the last few rows in that dataset where column A matched "The Warriors" for instance?
What I mean here is I want to find the last 3 rows before the current one where column A said "The Warriors" for example. How would I do this in R (or SQL or Matlab)?

A: I can propose a solution in Matlab.
Let me create at first a random table with a single column A just for the sake of demo:
T =

          A
    ______________

    'The Warriors'
    '43'
    '38'
    '40'
    '49'
    '71'
    '69'
    '64'
    '67'
    'The Warriors'
    'The Warriors'
    'The Warriors'
    '131'
    'The Warriors'
    '119'
    '124'
    '93'
    '109'
    '77'
    'The Warriors'
    '83'
    '117'
    '75'
    '122'
    '80'
    'Smith'
    'Johnson'
    'Williams'
    'Jones'
    'Brown'

Now it's possible to create a boolean vector which contains true (1) in position i if the i-th row contains the string 'The Warriors':
matchresult=cellfun(@(x) strcmp(x,'The Warriors'),T.A);

Indeed now matchresult has the form:
matchresult =

     1
     0
     0
     0
     0
     0
     0
     0
     0
     1
     1
     1
     0
     1
     0
     0
     0
     0
     0
     1
     0
     0
     0
     0
     0
     0
     0
     0
     0
     0

And now we can scan this vector instead of the whole table to find the last 3 rows:
for i=4:length(matchresult)                 % since we want 3 rows we can start scanning from the 4th
    if(sum(matchresult(1:i-1))>=3)          % if there are at least 3 ones in previous rows
        fprintf('Scanning row #%d:\n',i);   % see the row index we're scanning
        find(matchresult((1:i-1)),3,'last') % find 1s in previous rows and display last 3 indices
    end
end


text:
Q: Convergence of linear regression coefficients Consider a sequence of linear regression problems:
$$
Y^{(n)}_n = X^{(n)}_{n \times p } \beta_{p}^{(n)}
$$
where $p$ is fixed and $X^{(n)}_{n \times p }$  is full rank for all $n$.
My question is:
What is the general topology (Banach space, locally convex space, etc) in which we can prove the convergence of $\beta$ parameters?
$$
\beta^{(n)} = (X^{{(n)}\top} X^{(n)})^{-1} X^{{(n)}\top} Y^{(n)}.
$$
Thanks in advance.


text:
Q: Format vector of numbers prettily to the same number of decimal places I am constructing pretty axis labes using pretty() function and I want to format them to the same number of decimal places. I tried this:
at <- pretty(c(0.001, 0.05), n = 7)
# [1] 0.000 0.005 0.010 0.015 0.020 0.025 0.030 0.035 0.040 0.045 0.050

prettyNum(at)
# [1] "0"     "0.005" "0.01"  "0.015" "0.02"  "0.025" "0.03"  "0.035" "0.04"  "0.045" "0.05"

You can see that prettyNum() is formatting the numbers prettily (e.g. the zero doesn't have decimal places), but it doesn't unify the number of decimal places in the other numbers (to have like "0.030" etc.). How can I do this? I tried prettyNum(at, preserve.width = "common") but the result is the same.

A: You can use sprintf, which uses the same formatting as C's printf:
sprintf("%.03f", 0.05)


text:
Q: Play 2.2.2 Heroku deploy httpclient;4.0.1 download failed Play application update runs builds/runs fine locally however Pushing to Heroku (after migrating to cedar-14) is failing with the following:
[error] (*:update) sbt.ResolveException: download failed: org.apache.httpcomponents#httpclient;4.0.1!httpclient.jar

After browsing I have tried the following to resolve the issue without any luck:
Set sbt.version to 0.13.5
The issue seems to be in Heroku's own build process.
Any help on this issue would be greatly appreciated.
DUMP:
remote:        [info]   [SUCCESSFUL ] org.scala-lang#jline;2.10.3!jline.jar (11ms)
remote:        [warn]   ::::::::::::::::::::::::::::::::::::::::::::::
remote:        [warn]   ::              FAILED DOWNLOADS            ::
remote:        [warn]   :: ^ see resolution messages for details  ^ ::
remote:        [warn]   ::::::::::::::::::::::::::::::::::::::::::::::
remote:        [warn]   :: org.apache.httpcomponents#httpclient;4.0.1!httpclient.jar
remote:        [warn]   ::::::::::::::::::::::::::::::::::::::::::::::
remote:        sbt.ResolveException: download failed: org.apache.httpcomponents#httpclient;4.0.1!httpclient.jar

Build.sbt
name := "jmpdb"

version := "1.0-SNAPSHOT"

libraryDependencies ++= Seq(
  javaJdbc,
  javaEbean,
  cache,
  "mysql" % "mysql-connector-java" % "5.1.18",
  "org.mindrot" % "jbcrypt" % "0.3m",
  "com.thoughtworks.xstream" % "xstream" % "1.4.7",
  "org.apache.velocity" % "velocity" % "1.7",
  "commons-lang" % "commons-lang" % "2.6",
  "com.google.api-client" % "google-api-client" % "1.12.0-beta",
  "com.google.http-client" % "google-http-client-jackson" % "1.12.0-beta",
  "com.google.oauth-client" % "google-oauth-client" % "1.12.0-beta",
  "com.google.apis" % "google-api-services-drive" % "v2-rev30-1.12.0-beta",
  "com.google.apis" % "google-api-services-oauth2" % "v2-rev25-1.12.0-beta",
  "org.json" % "json" % "20080701",
  "org.reflections" % "reflections" % "0.9.8",
  "com.ecwid" % "ecwid-mailchimp" % "1.3.0.7",
  "com.typesafe" %% "play-plugins-mailer" % "2.1.0"
)

resolvers += "jBCrypt Repository" at "http://repo1.maven.org/maven2/org/"

resolvers += "google-api-services" at "http://google-api-client-libraries.appspot.com/mavenrepo"

resolvers := Seq("typesafe" at "http://repo.typesafe.com/typesafe/repo")

// Only needed in development
javaOptions ++= Seq("-Xmx512M", "-Xmx2048M", "-XX:MaxPermSize=2048M")

play.Project.playJavaSettings

Plugins.sbt
// Comment to get more information during initialization
logLevel := Level.Warn

// The Typesafe repository
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

// Use the Play sbt plugin for Play projects
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.2.2")

A: After consulting with Heroku technical support the issue was related to a corruption in the SBT cache on Heroku. The steps suggested below resolved the issue (in my case the purge_cache as I had already been running sbt_clean=true):
$ heroku config:set SBT_CLEAN=true
$ git push heroku master

If that still does not work, please try purging the ivy2 and m2 caches by running these commands:
$ heroku plugins:install https://github.com/heroku/heroku-repo.git
$ heroku repo:purge_cache -a peaceful-mountain-6737
$ git push heroku master

Hopefully, this will help someone else going in circles.


text:
Q: dotnet build to specific framework version I'm using the newest .NET SDK just released the other day (1.0.1, installed from https://dotnetcli.blob.core.windows.net/dotnet/Sdk/1.0.1/dotnet-dev-debian-x64.1.0.1.tar.gz) to build projects with "dotnet publish." For reasons outside of the scope of this question, I am trying to build applications so that they run on slightly older versions of the framework (1.0.3 and 1.1.0, as opposed to the newest 1.0.4 and 1.1.0).
If I build a project that specifies <TargetFramework>netcoreapp1.1</TargetFramework>, it won't run on a platform that only has version 1.1.0 installed.
It looks like I can specify <RuntimeFrameworkVersion>1.1.0</RuntimeFrameworkVersion> in my csproj on a per-project basis, but is there any way I can configure dotnet such that targeting netcoreapp1.1 targets 1.1.0 by default?

A: You are right, when you only specify <TargetFramework>netcoreapp1.1</TargetFramework>, the default is for your application to target the latest runtime: 1.1.1.  Here's the PR that made the change. Like you mention, this means your application no longer runs on a machine with only 1.1.0 on it.

is there any way I can configure dotnet such that targeting netcoreapp1.1 targets 1.1.0 by default?

In my mind, you have two options:

*

*When you call dotnet publish, you can pass in MSBuild parameters. So you can say dotnet publish -c Release /p:RuntimeFrameworkVersion=1.1.0

*You can add a Directory.Build.props file above all the .csproj files that you want to default properties for.  This .props file will automatically be imported in all the .csproj files below it.  You can set common properties in it:
<Project>
  <PropertyGroup>
    <RuntimeFrameworkVersion>1.1.0</RuntimeFrameworkVersion>
  </PropertyGroup>
</Project>

Now all of your projects will get this property set automatically.


text:
Q: Application Didn't Work untill i restart visual studio 2017 i have implemented web app in asp.net core using visual studio 2017.
There i am facing an issue when i open visual studio and run that application i got this error in popup see this image

when i close my visual studio and restart it then it work fine it creating problem only first time when i run application


text:
Q: Capnproto - Make client request in server callback I need to do some client-requests inside a server-callback and are not sure where to store the created capnp::EzRpcClient and CompareNetwork::Client comparer objects. That's because the clients go out of scope (I think - I just get a SEGFAULT, but that seems to be the reason). It's basically a master who forwards a loading request to it's slaves (slaves can register via a REG-request and their address is stored).
So - where/how should I store the client objects? Is there any "best-practice" with this? I think temporarily storing them in some class member variable is a little dirty, isn't it?
GroupMaster2.cpp:
kj::Promise<void> GroupMaster2::CompareMasterImpl::load(LoadContext context) {
    auto loadData = context.getParams().getIds();

    slaveListLock.lock();

    auto promList = kj::Vector<kj::Promise<std::pair<std::string, CompareNetwork::Status>>>();

    for(auto& slave : slaveList) {
        try {
            capnp::EzRpcClient client(slave.second->address);
            CompareNetwork::Client comparer = client.getMain<CompareNetwork>();
            auto request = comparer.loadRequest();
            std::string addrCopy(slave.first);
            request.setIds(loadData);
            auto loadPromise = request.send();
            promList.add(loadPromise.then([addrCopy](auto response) {
                return std::make_pair(addrCopy, response.getStatus());
            },
            [&, addrCopy](kj::Exception && exception) {
                slaveListLock.lock();
                slaveList.erase(addrCopy);//something failed, remove this slave!
                slaveListLock.unlock();
                std::cout << "ErrLoad0: " << std::string(exception.getDescription()) << std::endl;
                return std::make_pair(addrCopy, CompareNetwork::Status::ERROR);
            }));
        }
        catch(...) {
            std::cout << "Error sending load to: " << slave.first << std::endl;
        }
    }

    slaveListLock.unlock();

    auto retProm = kj::joinPromises(promList.releaseAsArray()).then([&, KJ_CPCAP(context)](kj::Array<std::pair<std::string, CompareNetwork::Status>> res) mutable {
        bool error = false;

        for(auto& loadRes : res) {
            switch(loadRes.second) {
                case CompareNetwork::Status::OK: {
                        std::cout << "LOAD OK: " << loadRes.first << std::endl;
                        break;
                    }

                case CompareNetwork::Status::ERROR: {
                        std::cout << "LOAD ERROR: " << loadRes.first << std::endl;
                        error = true;
                        break;
                    }
            }
        }
        if(!error)
            context.getResults().setStatus(CompareNetwork::Status::OK);
        else
            context.getResults().setStatus(CompareNetwork::Status::ERROR);
    }, [](kj::Exception && exception) {
        std::cout << __FILE__ << ":" << __LINE__ << std::string(exception.getDescription()) << std::endl;
    }).eagerlyEvaluate([](kj::Exception && exception) {
        std::cout << __FILE__ << ":" << __LINE__ << std::string(exception.getDescription()) << std::endl;
    });
    std::cout << "ReturnedLoad" << std::endl;
    return retProm;
}

GroupNetworkData.capnp:
interface CompareNetwork {
  compare @0 (jobs :JobPartList) -> (res :JobResList);
  load @1 (ids :WIDList) -> (status :Status);

  struct JobPartList {
    jobParts @0 :List(JobPart);

    struct JobPart {
      jobs @0 :List(Job);
      startID @1 :UInt32;

      struct Job {
        wid1 @0 :UInt32;
        wid2 @1 :UInt32;
      }
    }
  }

  struct JobResList {
    jobResults @0 :List(JobRes);
    struct JobRes {
      jobIndex @0 :UInt32;
      result @1 :Float64;
    }
  }

  struct WIDList {
    ids @0 :List(WID);
    struct WID {
      id @0 :UInt32;
    }
  }

  enum Status {
    ok @0;
    error @1;
  }
}

interface CompareMaster extends(CompareNetwork) {
  reg @0 (data :SlaveData) -> (status :CompareNetwork.Status);
  struct SlaveData {
    perfInd @0 :Float64;
    maxMem @1 :UInt32;
    address @2 :Text;
  }
}

Thanks in advance!
dvs23

A: C++14 seems to have the answer:
How to capture a unique_ptr into a lambda expression?
Allocate both objects on heap with kj::heap and move the kj::Own to the callback lambda:
for(auto& slave : slaveList) {
    try {
        auto client = kj::heap<capnp::EzRpcClient>(slave.second->address);
        auto comparer = kj::heap<CompareNetwork::Client>(client->getMain<CompareNetwork>());
        auto request = comparer->loadRequest();
        std::string addrCopy(slave.first);
        request.setIds(loadData);
        auto loadPromise = request.send();
        promList.add(loadPromise.then([addrCopy, client = std::move(client), comparer = std::move(comparer)](auto response) {
            return std::make_pair(addrCopy, response.getStatus());
        },
        [&, addrCopy](kj::Exception && exception) {
            slaveListLock.lock();
            slaveList.erase(addrCopy);//something failed, remove this slave!
            slaveListLock.unlock();
            std::cout << "ErrLoad0: " << std::string(exception.getDescription()) << std::endl;
            return std::make_pair(addrCopy, CompareNetwork::Status::ERROR);
        }));
    }
    catch(...) {
        std::cout << "Error sending load to: " << slave.first << std::endl;
    }
}

Better ideas are welcome, but at the moment it seems to work pretty well :)


text:
Q: how to solve this The server does not support version 3.0 of the J2EE Web module specification.? i am trying to deploy the jsp-servlet application in tomcat5.5 but shows this error when i try to deploy in to the server.
 The server does not support version 3.0 of the J2EE Web module specification.

but i am able to do it tomcat 7.0 and above. i think it is the version of servlet. Please help me how to over come this.
thanks
Antony

A: Ways to solve the problem:
1 Change version to 2.5 to run in tomcat 5.5
2 Run your application with version 3.0 in tomcat 7
No other solutions I know

A: see the link below for details:
http://tomcat.apache.org/whichversion.html
tomcat5.5.x supports servlet/jsp spec  2.4/2.0  (Does not support annotations)
You need to upgrade to tomcat7.x to be able to run servlet/jsp spec 3.0/2.2

A: Since you are using Tomcat5.x it supports servlet version 2.4 specification.
servlet specification 3.0 acceptable from Tomcat 6.x and higher, that is why you are able to run the application by Tomcat7.


text:
Q: How to combine values from multiple rows into a single row using module? I'm looking to combine multiple rows into a single row based on a value in the code column.. I've noticed other questions on here similiar to my question but I cannot seem to extend the range..
Code    Name    Value A Value B Value C Value D Value E
101   Example      #
101   Example
101   Example                     #
101   Example                            #
101   Example                                    #
102   Example2                                   #
102   Example2                           #
102   Example2                    #
102   Example2            #
102   Example2     #

So the final result looks like this:
Code    Name    Value A Value B Value C Value D Value E
101    Example     #               #       #       #
102    Example2    #       #       #       #       #

Edit
This is what I've got so far, my plan was to shift the items to the row above before deleting the entire row as one row may have many items.
Dim RowNum, LastRow, Col As Long

RowNum = 2
Col = 3

LastRow = Cells.SpecialCells(xlCellTypeLastCell).row
Range("A2", Cells(LastRow, 7)).Select

For Each row In Selection
    With Cells
        If Cells(RowNum, 1) = Cells(RowNum + 1, 1) Then
            For Each Cell In row
                If Cell > 0 Then
                Cells(RowNum + 1, Col).Copy Destination:=Cells(RowNum, Col)
                Else
                Col = Col + 1
            End If
        Rows(RowNum + 1).EntireRow.Delete
        End If
  End With

RowNum = RowNum + 1

Next row

A: I'm kind of ashamed of the answer you based your code on. Backup your data and test on a copy!
This should work:
Sub combine()

Dim c As Range
Dim i As Integer

For Each c In Range("A2", Cells(Cells.SpecialCells(xlCellTypeLastCell).Row, 1))
If c = c.Offset(1) And c <> "" Then
       For i = 1 To 6
            If c.Offset(1, i) <> "" Then
                c.Offset(, i) = c.Offset(1, i)
            End If
       Next
       c.Offset(1).EntireRow.Delete
End If

Next

End Sub


text:
Q: I want to understand how the value of x changes when recursive function 'fun' is called #include <stdio.h>
int fun(int n)
{
    static int x = 0;
    if (n <= 0)
        return 1;
    if (n>3)
    {
        x =n;
        return fun(n-2)+ 3;
    }
    return fun(n-1)+ x;
}
int main()
{
   return fun(5);
}

How i am thinking is that when in the main() function fun(5) is called. It satisfies the if condition if(n>3). The value of 'n' which is 5 is assigned to the x by x =n;. In the next statement return fun(n-2)+3; will be fun(3)+3;. so where am i getting confused is that when fun(3) is executed will the value of be '5' or '0' after the statement static int x = 0;. I assumed it stays '5' in the block of if condition. How static variables act in these kind of recursive functions.

A: Your function
int fun(int n)
{
    static int x = 0;
    if (n <= 0)
        return 1;
    if (n > 3) {
        x = n;
        return fun(n - 2) + 3;
    }
    return fun(n - 1) + x;
}

works exactly like
static int x = 0;

int fun(int n)
{
    if (n <= 0)
        return 1;
    if (n > 3) {
        x = n;
        return fun(n - 2) + 3;
    }
    return fun(n - 1) + x;
}

except that in the former case, x can only be accessed inside fun.


text:
Q: .NET Assembly without a Disk Image? Is this even possible? For example, I would like to read the assembly as a stream of bytes from the network or from a zip archive and run it from RAM itself without having to create an image on the disk.

A: Assembly.Load(Byte[])


text:
Q: Clickable floating action button outside of YouTubePlayerSupportFragment I have an Activity with a YouTubePlayerSupportFragment and a floating action button. Before the video starts the floating button is clickable, but after the video initialization, I can't click anymore on the floating button. I would like to make it clickable after the video starts.
I know that a View cannot be over a YouTubePlayer, but in this case, the button isn't overlaying the YouTubePlayer.
Here is my activity xml which contains both YouTubePlayerFragment and the floating button:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_youtube_player_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="hanappaula.br.youtubedownloader.activities.YouTubePlayerActivity">

    <fragment
        android:id="@+id/activity_youtube_fragment"
        android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <com.melnykov.fab.FloatingActionButton
        android:id="@+id/activity_youtube_floating_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:src="@drawable/ic_content_add"
        fab:fab_colorNormal="#2196F3"
        fab:fab_colorPressed="#448AFF"
        fab:fab_colorRipple="#9E9E9E" />

</RelativeLayout>

A: I solved my problem. The thing was that I also had a PopupWindow with buttons to control de video (play, pause, fullscreen..) and it was overlaying the button. I set the heigh of the PopupWindow to coincide with the YouTubePlayerSupportFragment size.


text:
Q: Tray app takes 40mb in xp and 10mb in win7 I've developed a small application in C# (.net 3.5) which runs in the system tray. Basically it just checks a rss-feed every 5 minutes, and if there's a new feed since the last time it checked, it displays a balloontip, and also uses the text-to-speech engine in .net 3.0/3.5 to read the headline of the fetched feed.
It works fine, but I've noticed that on Windows7 it takes about 9-10mb while running, but in XP it takes 39-40mb.
I have no clue why. Does anybody know anything about what this might be?

A: Maybe because windows 7 uses .net in some of its components, so a lot of memory is shared between your process and the system.
In XP all the .Net assembly are not loaded by some process of the system, so the memory appears as private in your process.

A: Are your readings from the Mem Usage column in the taskmanager? Then you are looking at the working set size. The amount of active memory used by the application loaded into RAM. This might not be what you want to compare. Try minimizing your application. See how the Mem Usage drops significantly. It does not mean the applications is using less memory once you minimize it. It means that Windows thinks you are not going to use the application any time soon and swaps the memory from RAM to the paging file. You might want to check out the VM Size column to compare. Of course you can still ask yourself the question why the working set size differs, but that question is a lot harder to answer. Also see here for an explanation of the different memory readings.


text:
Q: does google openID issue token? Myself implementented  SSO in my application using Authentication Exchange in c# by Dotnetopenauth
My Doubts follows,

*

*On Response of my AX request , i dont receive any token. should i need to send any parameter ?

*In My Application i need user to sign in on Provider everytime , but rightnow if user clicks checkbox on "sign-in automatically next time" it never asks id and password from user next time .

*AX fetchResponse null for MyopenId. does it support only Simple Registration?

Request Code:
IAuthenticationRequest request = openid.CreateRequest(txt_openid_identifier.Text);

    var fetchRequest = new FetchRequest();
    fetchRequest.Attributes.Clear();
    fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
    fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
    fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);                       fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
            request.AddExtension(fetchRequest);

            // Issue request to OP
            request.RedirectToProvider();

Response Code:
using (var openid = new OpenIdRelyingParty())
        {
            var response = openid.GetResponse();

            if (response == null) return;

            switch (response.Status)
            {

                case AuthenticationStatus.Authenticated:
                    string emailID = string.Empty;
                    Session["email"] = string.Empty;
                    Session["name"] = string.Empty;
                    Session["country"] = string.Empty;
                    Session["Accesskey"] = string.Empty;
                    Session["SecretAccesskey"] = string.Empty;

                    var fetchResponse = response.GetExtension<FetchResponse>();

                    if (fetchResponse.Attributes.Contains(WellKnownAttributes.Contact.Email))
                    {
                        IList<string> emailAddresses =
                            fetchResponse.Attributes[WellKnownAttributes.Contact.Email].Values;
                        emailID = emailAddresses.Count > 0 ? emailAddresses[0] : null;
                    }
                    else
                        emailID = string.Empty;
            }
        }

A: I found that certain providers (i.e. myopenid.com) returned null for a FetchRequest whilst returning valid data for ClaimsRequest. It appears different providers support different mechanisms for attribute exchange. In the request:
var request = openid.CreateRequest(Request.Form["openid_identifier"]);

var sr = new ClaimsRequest
{
    Email = DemandLevel.Request,
    FullName = DemandLevel.Request
};
request.AddExtension(sr);

var fetchRequest = new FetchRequest();
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetchRequest.Attributes.AddOptional(WellKnownAttributes.Name.FullName);
request.AddExtension(fetchRequest);

return request.RedirectingResponse.AsActionResult();

and when picking up the response:
string email, fullName = String.Empty;
var fetch = response.GetExtension<FetchResponse>();
if (fetch != null)
{
    email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
    fullName = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName);
}
var claimResponse = response.GetExtension<ClaimsResponse>();
if (claimResponse != null)
{
    email = claimResponse.Email;
    fullName = claimResponse.FullName;
}

Thus we try both ways and hopefully gets the data from at least one of the methods.


text:
Q: How is this fraction simplified?
Based on the snapshot image, I don't understand how they got to the numerator: −1/13h
I actually don't understand how they got to the denominator either?
I appreciate a step by step on how they did it. It's figuratively making pull my hairs out. Thank you in advance.

A: $$\frac{\frac{1}{h+13}-\frac{1}{13}}{9+h-9}=\frac{\frac{13-(h+13)}{13(h+13)}}{h}$$
$$=\frac{\frac{-h}{13(h+13)}}{h}=\frac{1}{h}\times\frac{-h}{13(h+13)}$$
$$=\frac{-1}{13h+169.}$$


text:
Q: send email to task assignee using powershell? I want to send daily reminders to users who have tasks assigned to them. It seems like a simple way to do this would be to write a Powershell script that sends an email for each item, and set up a scheduled task to run the script once a day. However, the script  below returns something like 1;#John Doe (full name) for each item.
Is there a way to get the user's email address, or Windows username, from the task list item using Powershell? I think there must be, since SharePoint is able to send mail to the assignee when the task is created.
$web = Get-SPWeb http://mysharepointsite
$list = $web.Lists["Task List Test"]
foreach ($item in $list.items)
{
    if ($item["Status"] -ne "Completed")
    {
        write-host $item["Assigned To"]
    }
}

A: Script returns lookup value. So you can parse the num part of that string - user ID and then find it by command
$web.Users.GetById($parsedId)

whole script:
$value = "1;#user name";

$arr = $value.Split(";#");
$parsedId = $arr[0];
$user = $web.Users.GetById($parsedId);

write-host "mail:" $user.Email


text:
Q: EVITAR BUCLE o DUPLICADO EN UNA CONSULTA JAVASCRIP Bueno mis amigos primeramente reciban mi mas cordial saludo, bueno estoy realizando el cierre de sesión por inactividad, y me presento un bucle, la primera ves que se ejecuta me sale normal, pero le doy permanecer y la función me ejecuta normal pero al aparecer me crea un duplicado.

como se aprecia en la imagen, el cerrar ya esta perfecto, lo único que esta mal es el permanecer, ya que necesito que siga en la pagina pero "SIN REFRESCAR LA PAGINA" y que el contador vuelva a empezar. aquí les dejo el código.
`
var timeout;
var detener = 1; // lo cree para tratar de controlar el bucle.

document.onmousemove = function () {

    clearTimeout(timeout);
    contadorSesion();
};

function clickbutton() {
    // simulamos el click del mouse en el boton del formulario
    $("#action-button").click();

}
$('#action-button').on('click', function () {
    console.log('action button clicked');
});

function contadorSesion() {

    timeout = setTimeout(function () {
         detener = 1;

        if (detener == 1) {
            $.confirm({
                title: 'Alerta de Inactividad!',
                content: 'La sesión esta a punto de expirar.',
                autoClose: 'expirar|30000',//cuanto tiempo necesitamos para cerrar la sess automaticamente
                type: 'red',
                icon: 'fa fa-spinner fa-spin',
                buttons: {
                    expirar: {
                        text: 'Cerrar Sesión',
                        btnClass: 'btn-red',
                        action: function () {
                            clickbutton();
                        }
                    },
                    permanecer: function () {
                        contadorSesion();
                     //reinicia el conteo
                        $.alert('La Sesión ha sido reiniciada!'); //mensaje

                        location = "http://" + location.host + "/#/NewAsset";
                        detener = 0;
                    }
                }
            });

        }

        }, 10000);//10 segundos para no demorar tanto

}

`
También probé este otro que también funciona normal, pero cuando le doy permanecer la función no se vuelve a ejecutar.
var IDLE_TIMEOUT = 10; //seconds
    var _idleSecondsCounter = 0;
    var detener = false;
    document.onclick = function () {
        _idleSecondsCounter = 0;
    };

    document.onmousemove = function () {
        _idleSecondsCounter = 0;
    };

    document.onkeypress = function () {
        _idleSecondsCounter = 0;
    };

    window.setInterval(CheckIdleTime, 1000);

    function CheckIdleTime() {
        _idleSecondsCounter++;
        var oPanel = document.getElementById("SecondsUntilExpire");
        if (oPanel)
            oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
        if (_idleSecondsCounter >= IDLE_TIMEOUT) {
            if (detener == false) {
                contadorSesion();

            }
            detener = true;

    function clickbutton() {
        // simulamos el click del mouse en el boton del formulario
        $("#action-button").click();

    }
    $('#action-button').on('click', function () {
        console.log('action button clicked');
    });

    function contadorSesion() {

        $.confirm({
            title: 'Alerta de Inactividad!',
            content: 'La sesión esta a punto de expirar.',
            autoClose: 'expirar|30000',//cuanto tiempo necesitamos para cerrar la sess automaticamente
            type: 'red',
            icon: 'fa fa-spinner fa-spin',
            buttons: {
                expirar: {
                    text: 'Cerrar Sesión',
                    btnClass: 'btn-red',
                    action: function () {
                        clickbutton()
                    }
                },
                permanecer: function () {
                   //reinicia el conteo
                    $.alert('La Sesión ha sido reiniciada!'); //mensaje

                    CheckIdleTime();
                }
            }
        });
duplica
    }

Si alguien me puede ayudar por favor, lo necesito para presentar, le agradecería mucho.


text:
Q: Why do people use equivalence principle differently in Hawking radiation? In discussions of Black hole information paradox, people usually argue that the falling observer shall not see radiation at the horizon or near the horizon due to the equivalence principle. That is, for a falling observer, what around him is just vacuum in a locally Minkowski spacetime. This is because, for a falling observer, the Christoffel connection vanishes. The problem is, if the equivalence principle holds, the asymptotic static observer at infinity also has the same status of a "free-falling" observer. Because, spacetime is asymptotically flat and the static observer is a free-moving observer in locally Minkowski spacetime. Then why shall the static observer at infinity observe Hawing radiation?

A: Consider  a static observer far away from the black hole (but not at infinity) and the usual free falling observer crossing the horizon. The latter follows a geodesic, while the former must accelerate to not fall in.
In analogy to the Unruh effect, the accelerated observer will see particles. All of this can be made less naive by computing the Bogoliubov transformations relating the regular vacuum at the horizon with the singular one in schwarzschild coordinates.
Now, since the observer far away from the hole will see a flux of radiation, the one at infinity will see it too.


text:
Q: text object not updating on screen when variable value changes I have some code that creates a button and code creating some text that is displayed on-screen. The goal is to have the button when clicked add 1 to the variable and have the changed reflected on screen (ie button is clicked the value on screen goes from 0 to 1 and then 1 to 2 and so on).
The button function:
def button(message, x, y, w, h, activeRGB, inactiveRGB, action=None): #example of color param for line 61/63
    mouse = pygame.mouse.get_pos() #get location of mouse recorded by pygame
    click = pygame.mouse.get_pressed()

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, activeRGB, (x, y, w, h))
        if click[0] ==1 and action != None:
            if action == "countUP":
                clickCounter+= 1
                print(str(clickCounter)) # print to check that the button actually changes the value
                pygame.display.update()

    else:
        pygame.draw.rect(gameDisplay, inactiveRGB, (x, y, w, h))

    smallText = pygame.font.Font("freesansbold.ttf", 20)
    textSurf, textRect = textBox(message, mediumText)
    textRect.center = (  (x + (w/2)), y+(h/2))
    gameDisplay.blit(textSurf, textRect)

The logic I have so far
gameDisplay.fill(white)
pygame.display.update()
clickCounter = str(clickCounter)

textObject(clickCounter, black, mediumText, 200, 200)

closeGame = False

while not closeGame: # this keeps the window from shutting down
    for thing in pygame.event.get():
        if thing.type == pygame.QUIT:
            closeGame = True

        print(thing)

    button("Click me!", 300, 300, 100, 100, blue, brightBlue, "countUP")
    pygame.display.update()
    clock.tick(20)

gameDisplay.fill(white)
pygame.display.update()
#logicloop()

The button function does appear to be changing the value of clickCounter but it is not reflected on screen. My guess was that there is a missing blit command or screen update, though nothing i've tried has worked.
For whatever reason when I had this block of code set up as a function that is then called, it ran without the gameDisplay.fill(white) or any of the other on screen elements appearing, how would I go about setting it up as a function to make adding more to the logic easier?
All of the code:
import pygame

pygame.init()

displayWidth = 700
displayHeight = displayWidth

gameDisplay = pygame.display.set_mode((700,700))

clock = pygame.time.Clock()

black = (0, 0, 0)
brightBlue = (0, 0, 225)
blue = (0, 0, 255)

white = (255, 255, 255) #predef colors to make temp rgb value coding easier

closeGame = False

mediumText = pygame.font.Font("freesansbold.ttf", 70) #initalize font
clickCounter = 0

#def fontSize (pxsize):

    #pygame.font.Font("freesandsbold.ttf", pxsize)

def textObject (text, color, font, x, y):
    storedGenerate = font.render(text, 1, ((color)))
    gameDisplay.blit(storedGenerate, (x,y))

def textBox(text, font): #purely for returning rectangle around font// used for btn function only, tObject for displaying text

    textSurface = font.render(text, True, black) #swap black for rgb later
    return textSurface, textSurface.get_rect()

def button(message, x, y, w, h, activeRGB, inactiveRGB, action=None): #example of color param for line 61/63
    mouse = pygame.mouse.get_pos() #get location of mouse recorded by pygame
    click = pygame.mouse.get_pressed()
    global clickCounter
    clickCounter = 0

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, activeRGB, (x, y, w, h))
        if click[0] ==1 and action != None:
            if action == "countUP":
                clickCounter+= 1
                print(str(clickCounter))
                pygame.display.update()

    else:
        pygame.draw.rect(gameDisplay, inactiveRGB, (x, y, w, h))

    #smallText = pygame.font.Font("freesansbold.ttf", 20) # constant has been declared, try deleting line when done w/ proj
    smallText = pygame.font.SysFont('Times New Roman', 20)
    textSurf, textRect = textBox(message, smallText)
    textRect.center = (  (x + (w/2)), y+(h/2))
    gameDisplay.blit(textSurf, textRect)

gameDisplay.fill(white)
pygame.display.update()
clickCounter = str(clickCounter)

textObject(clickCounter, black, mediumText, 200, 200)

closeGame = False

while not closeGame: # this keeps the window from shutting down
    for thing in pygame.event.get():
        if thing.type == pygame.QUIT:
            closeGame = True

        print(thing)

    button("Click me!", 300, 300, 100, 100, blue, brightBlue, "countUP")
    pygame.display.update()
    clock.tick(20)

gameDisplay.fill(white)
pygame.display.update()
#logicloop()

pygame.quit()
quit()

A: The first issue is, that the number value stored in clickCounter is converted to a string.
Delete:
lickCounter = str(clickCounter)
In the function button, the value of clickCounter is continuously set 0. Delete this, too:
  def button(message, x, y, w, h, activeRGB, inactiveRGB, action=None):
      mouse = pygame.mouse.get_pos() #get location of mouse recorded by pygame
      click = pygame.mouse.get_pressed()
      global clickCounter
      # clickCounter = 0 <------ delete

      # [...]

You missed to draw the changed text in the main loop. Before the text is drawn the "old" text has to be cleared. Continuously redraw the entire scene in the main loop of the application.
This means the display has to be filled by the background color and the text and the button have to be redrawn:
while not closeGame: # this keeps the window from shutting down
    for thing in pygame.event.get():
        if thing.type == pygame.QUIT:
            closeGame = True

        print(thing)

    gameDisplay.fill(white)
    button("Click me!", 300, 300, 100, 100, blue, brightBlue, "countUP")
    textObject(str(clickCounter), black, mediumText, 200, 200)
    pygame.display.update()
    clock.tick(20)


text:
Q: Are there any numeric suffixes for specifying a double? void Foo(float  a){}  //1
void Foo(double a){}  //2 overloaded

Foo(1.0f);                           //calls function 1
Foo(1.0 /*double numeric suffix?*/); //calls function 2

If not, is a cast the only way this can be achieved?  I am mainly interested in
ensuring double precision math during certain operations, etc:
ulong j;
double v;

j = /*some value*/;
if(j>0UL)
  v = 1.0 / j;  //if 1.0 is set as a float by the compiler then
                //could it be likely we lose some precision here
                //if a double would allow for more precision?  Is
                //a cast the only means of ensuring double precision?

Other tips on allowing the compiler to auto-determine the types during an operation would be helpful.

A: A suffix is unnecessary in C++.  Any floating point value which lacks the 'f' suffix will be typed to the compiler type double by default.
Reference: http://en.wikipedia.org/wiki/C_0x


text:
Q: Spring OAuth2.0: Getting User Roles based on ClientId (Authorization Code Grant Type) I have a setup of spring boot OAuth for AuthServer and it is resposible for serving a number of few resource server for authentication using spring-security-jwt.
My problem is while authenticating I need to load the roles of a user but specific to the clientId.
eg: If user1 have roles ROLE_A, ROLE_B for client1 and ROLE_C, ROLE_D for client2, then when the user logins either using client1 or client2 he is able to see all the four roles ie. ROLE_A, ROLE_B, ROLE_C, ROLE_D because I am getting roles based on username.
If I need to have a role based on the client then I need clientId.
FYI,
I am using the authorization code flow for authentication.
I have seen similar question but that is based on password grant but I am trying on authorization code flow and that solution doesn't work for me.
Password grant question link

Below is my code where I need clientId
MyAuthenticationProvider.java
@Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        String userName = ((String) authentication.getPrincipal()).toLowerCase();
        String password = (String) authentication.getCredentials();
        String clientId = ? // how to get it
        ....
    }
}

MyUserDetailsService.java
@Override
    public UserDetails loadUserByUsername(String username) {
        String clientId = ? // how to get it
        ....
    }
}

A: You probably need to see OAuth2Authentication in Spring-security. When your client is authenticated by oauth2, then your "authentication" is actually instance of OAuth2Authentication that eventually implements Authentication.
If you see the implementation of OAuth2Authentication, it's done as below;
    public Object getPrincipal() {
       return this.userAuthentication == null ? this.storedRequest.getClientId() : this.userAuthentication
            .getPrincipal();
    }

so if request included "clientId', then you should be able to get clientId by calling getPrincipal() and typecasting to String as long as your request didn't include user authentication.
For your 2nd case, username is actually considered as clientId. You need to call in-memory, RDBMS, or whatever implementation that has clientId stored and returns ClientDetails. You'll be able to have some idea by looking into Spring security's ClientDetailsUserDetailsService class.

A: Since I didn't get any appropriate solution for my question, I am posting the solution that I used after digging source code and research.
MyJwtAccessTokenConverter.java (Extend JwtAccessTokenConverter and implement enhance method)
public class OAuthServerJwtAccessTokenConverter extends JwtAccessTokenConverter {
....
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    String clientId = authentication.getOAuth2Request().getClientId();
    // principal can be string or UserDetails based on whether we are generating access token or refreshing access token
    Object principal = authentication.getUserAuthentication().getPrincipal();
    ....
    }
....
}

Info:
In enhance method, we will get clientId from authentication.getOAuth2Request() and userDetails/user_name from authentication.getUserAuthentication().
Along with JwtAccessTokenConverter, AuthenticationProvider and UserDetailsService are required for authentication in generating access token step and refresh token step respectively.

A: get authorization header from request then parse from base64 to get the client-id.
something like this:
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes())
.getRequest();
String authHeader = request
.getHeader("Authorization");


text:
Q: Replace element that has changed in array I have an array of attendees, 2 of them are also instructors. I want to update one of the instructors by replacing him/her and leave the remaining attendees intact in the array.
Here's an example:
    {
      attendees: [
        { email: 'instructor1@gmail.com' },
        { email: 'instructor2@gmail.com' },
        { email: 'attendee@gmail.com' },
        { email: 'attendee1@gmail.com' },
        { email: 'attendee2@gmail.com' }
      ]
    }

Now I submit a new array of instructors with one of them changed:
    {
      instructors: [
        { email : 'test@gmail.com' },
        { email : 'instructor2@gmail.com' }
      ]
    }

And my final result should be:
    {
      attendees: [
        { email: 'test@gmail.com' },
        { email: 'instructor2@gmail.com' },
        { email: 'attendee@gmail.com' },
        { email: 'attendee1@gmail.com' },
        { email: 'attendee2@gmail.com' }
      ]
    }

Where test@gmail.com has replaced instructor1@gmail.com as the new instructor. I think I can use _.differenceBy with lodash but can't figure out how to replace the changed element in the array. Is there an elegant way to do this?

A: Here is a few solutions that either 1) puts the updates in a new variable or 2) updates the attendees variable. Of course, this is pretty limited because your data doesn't have something akin to a primary key (ie: an ID field). If you do have a primary key, then you can modify these examples to check the id.
var attendees = [
    { email: 'instructor1@gmail.com' },
    { email: 'instructor2@gmail.com' },
    { email: 'attendee@gmail.com' },
    { email: 'attendee1@gmail.com' },
    { email: 'attendee2@gmail.com' }
]

var instructors = [
    { email : 'test@gmail.com' },
    { email : 'instructor2@gmail.com' }
]

// 1) in a new variable
var updatedAttendees = attendees.map(function(item, index) {
    return instructors[index] || item;
})

// 2) In the same variable
for (var i = 0; i < attendees.length; i++) {
    if (instructors[i]) {
        attendees[i] = instructors[i];
    }
}

If you did have a primary key, it might look like this.  Note that we now have two nested loops.  This example is not optimized at all, but just to give you the general idea:
var attendeesWithId = [
    { id: 1, email: 'instructor1@gmail.com' },
    { id: 2, email: 'instructor2@gmail.com' },
    { id: 3, email: 'attendee@gmail.com' },
    { id: 4, email: 'attendee1@gmail.com' },
    { id: 5, email: 'attendee2@gmail.com' }
]

var updates = [
    { id: 4, email: 'something-different@gmail.com' },
]

for (var j = 0; j < updates.length; j++) {
    var update = updates[j];

    for (var i = 0; i < attendeesWithId.length; i++) {
        if (update.id === attendeesWithId[i].id) {
            attendeesWithId[i] = update;
        }
    }
}

A: Does this help

var initialData =  {
      attendees: [
        { email: 'instructor1@gmail.com' },
        { email: 'instructor2@gmail.com' },
        { email: 'attendee@gmail.com' },
        { email: 'attendee1@gmail.com' },
        { email: 'attendee2@gmail.com' }
      ]
    }

var updateWithThis = {
      instructors: [
        { email : 'test@gmail.com' },
        { email : 'instructor2@gmail.com' }
      ]
    }

for(var i=0; i< updateWithThis.instructors.length;i++){
    initialData.attendees[i] = updateWithThis.instructors[i];
}

document.write(JSON.stringify(initialData));


text:
Q: Why is there a space on the right on small mobile screens?

body {
    margin: 0;
}
div {
    box-sizing: border-box;
    background-color: red;
    width: 100%;
    height: 300px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>Text that overflooooooooooooooooooooooooooooooooooooooooooooooooooooooooooows </div>
</body>
</html>

When I inspect the above page with Chrome devtools, turn on Device Toolbar

and set device width to anything below 450 (so that the text overflows)

and device type to Mobile,

there is a gap of space to the right from div.

And as I adjust the width of the device the width of the div is always smaller than the width of the screen. Though the text overflows I expect the div to always be as wide as the screen because the div is a child of the body and it has width: 100%;. Moreover, the devtools say that the div has the same width as the screen.
This issue does not happen on desktop (i.e. if I set device type to Desktop).

What is even weirder is that the devtools say that the div is as wide as the screen.

If I switch to Desktop device type and then back to Mobile than the issue disappears but the page seems zoomed in.

Also when I launch this page on a real mobile device where text still overflows, the issue seems to disappear

but when I zoom out it is still there.

So I assume that when I initially opened the page on the real mobile device, the browser set the zoom value automatically so that the div seems to be as wide as the parent.
What piece of HTML and CSS theory do I miss so that I don't understand the reason behind the issue? Why does it happen? How do I fix the problem?

A: Try this instead:

div {
       box-sizing: border-box;
       background-color: red;
       width: 100vmax;
       height: 300px;
    }

A: I think the problem is the word 'overflooooooooooooooooooooooooooooooooooooooooooooooooooooooooooows' is so long and exceeding the div.
Now, I'm not sure why it's just happen on desktop using mobile mode.
But you can fix it using in your CSS div class the following line
word-break: break-all;

This will force the word break.
Result
Result after add "word-break: break-all;"


text:
Q: Gnome Themes Not showing I recently upgraded from 19.04 to 19.10 and now my user themes are not showing as options in gnome tweak tool.  I have user themes extension installed, but still no luck with themes.  Also, none of the themes show for the shell dropdown either.  Any guidance appreciated.

A: I also had trouble recently setting up themes in Gnome Tweak... had to do it from terminal. Maybe that can help you:
# Applications
gsettings set org.gnome.desktop.interface gtk-theme 'Pop'

# Icons
gsettings set org.gnome.desktop.interface icon-theme 'Pop'

# Cursor
gsettings set org.gnome.desktop.interface cursor-theme 'Pop'


text:
Q: Architecture for remoting to call a Windows Service method I have added remoting calls to my Windows Service so my GUI application can talk to it. It works great, but my channel implementation has no knowledge of my service.
How should I layer my classes so that my remoting channel implementation can call methods in my service class?
Channel Interface:
public interface IMyService
{
    string Ping();
    string SomeMethod(string input);
}

Channel Implementation:
public class MyServiceChannel : MarshalByRefObject, IMyService
{
    public string Ping()
    {
        return "Pong";
    }

    public string SomeMethod(string input)
    {
        MethodForChannelToCall(input); // in Service class. How to reference?
        return "Some Output";
    }
}

Service Class
class MyService : ServiceBase
{
    public void MethodForChannelToCall(string input)
    {
        // do service stuff for remoting call
    }

    public MyService()
    {
        // Set up remoting channel
        try
        {
            TcpChannel tcpChannel = new TcpChannel(12345);
            ChannelServices.RegisterChannel(tcpChannel, false);

            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(MyServiceChannel),
                "MyServiceChannel",
                WellKnownObjectMode.SingleCall);

            // Should I pass an instance of my service to my channel somehow here?
        }
        catch (Exception ex)
        {
            this.EventLog.WriteEntry("Remoting error: " + ex.ToString());
        }
    }
}

How should I structure my classes so that my channel can call my service methods?

A: In this case you should use WCF. WCF replaces .net remoting.
If both your client and service are on the same machine you can use named pipes binding.
If they are on different machines you can use net tcpip binding.


text:
Q: JQuery Scroll Top my image when onmousever I want to scroll a photo when mouse over that photo. I have a code, but i don't how to do that. Please help me.
This is my jquery code,

            $('.arrow').on('click', function(){
            var gallery = $('#image_container');
             var height = gallery.height();
            var up = $(this).is('.up_arrow');

            if (up) {
                gallery.animate({'scrollTop': '-=' + height});
              } else {
                  gallery.animate({'scrollTop': '+=' + height});
             }
            });

and html is listed below,

 Back to Green

The #image_container contains the photos

A: Try using marginTop instead of scrollTop. Also, you need to add px after the height-to-scroll.
$('.arrow').on('click', function(){
  var gallery = $('#image_container');
  var height = gallery.height();
  var up = $(this).is('.up_arrow');

  if (up) {
    gallery.animate({'marginTop': '-=' + height+'px'},700);
  } else {
    gallery.animate({'marginTop': '+=' + height+'px'});
  }
});

 Back to Green


text:
Q: Charge conjugation in Dirac equation According to Dirac equation we can write,
\begin{equation}
\left(i\gamma^\mu( \partial_\mu +ie A_\mu)- m \right)\psi(x,t) = 0
\end{equation}
We seek an equation where $e\rightarrow -e $ and which relates to the new wave functions to $\psi(x,t)$ .
Now taking the complex conjugate of this equation we get
\begin{equation}
\left[-i(\gamma^\mu)^* \partial_\mu   -e(\gamma^\mu)^* A_\mu - m \right] \psi^*(x,t) = 0
\end{equation}
If we can identify a matrix U such that
\begin{equation}
 \tilde{U} (\gamma^\mu)^* ( \tilde{U} )^{-1} = -\gamma^\mu
\end{equation}
where $ 1 =U^{-1} U$.
I want to know that, why and how did we do the last two equation. More precisely, I want to know  more details and significance of the last two equations.

A: The Dirac equation for a particle with charge $e$ is $$ \left[\gamma^\mu (i\partial_\mu - e A_\mu) - m \right] \psi = 0 $$
We want to know if we can construct a spinor $\psi^c$ with the opposite charge from $\psi$. This would obey the equation
$$ \left[\gamma^\mu (i\partial_\mu + e A_\mu) - m \right] \psi^c = 0 $$
If you know about gauge transformations $$ \psi \rightarrow \exp\left( i e \phi\right) \psi $$ (together with the compensating transformation for $A_\mu$, which we don't need here), this suggests that complex conjugation is the thing to do:
$$ \psi^\star \rightarrow \exp\left( i (-e) \phi\right) \psi^\star $$
So it looks like $\psi^\star$ has the opposite charge. Let's take the complex conjugate of the Dirac equation:
$$ \left[-\gamma^{\mu\star} (i\partial_\mu + e A_\mu) - m \right] \psi^\star = 0 $$
Unfortunately this isn't what we want. But remember that spinors and $\gamma$ matrices are only defined up to a change of basis $\psi \rightarrow S \psi$ and $\gamma^\mu \rightarrow S \gamma^\mu S^{-1}$. Possibly we can find a change of basis that brings the Dirac equation into the form we want.
Introduce an invertible matrix $C$ by multiplying on the left and inserting $ 1 = C^{-1}C $ (note that $C$ is the more common notation for your $\tilde{U}$):
$$ \begin{array}{lcl}
0 &= & C \left[-\gamma^{\mu\star} (i\partial_\mu + e A_\mu) - m \right] C^{-1} C\psi^\star \\
&= & \left[-C\gamma^{\mu\star}C^{-1} (i\partial_\mu + e A_\mu) - m \right] C\psi^\star \end{array}$$
Note that if we can find a $C$ which obeys $-C\gamma^{\mu\star}C^{-1} = \gamma^\mu$ then $C\psi^\star$ makes a perfectly good candidate for $\psi^c$! It turns out that one can indeed construct $C$ satisfying the condition and define charge conjugation as $$ \psi \rightarrow \psi^c = C\psi^\star $$
You can see this more explicitly in terms of two component spinors in the Weyl basis:
$$ \psi = \left( \begin{matrix} \chi_\alpha \\ \eta^{\dagger}_{\dot{\alpha}} \end{matrix} \right) $$
(the notation follows the tome on the subject). The charge conjugate spinor in this representation is
$$ \psi^c = \left( \begin{matrix} \eta_\alpha \\ \chi^{\dagger}_{\dot{\alpha}} \end{matrix} \right) $$
So charge conjugation is
$$ \eta \leftrightarrow \chi $$
This representation explicitly brings out the two oppositely charged components of the Dirac spinor, $\eta$ and $\chi$, and shows that charge conjugation acts by swapping them.
To recap: we want to define a charge conjugation operation so that given a $\psi$ with some electric charge $e$, we can get a $\psi^c$ with charge $-e$. Complex conjugating the Dirac equation gets us there, but the resulting spinor $\psi^\star$ is in a different spinor basis so the Dirac equation is not in standard form. We introduce a change of basis $C$ to get the Dirac equation back in standard form. The necessary conditions for this to work are that $C$ is invertible (otherwise it wouldn't be a change of basis and bad things would happen) and $-C\gamma^{\mu\star}C^{-1} = \gamma^\mu$.

A: The key here is that the gamma matrices are given by their commutation relationships and those do not determine a unique representation for the matrices.
If you start from the Dirac equation
$$\gamma^\mu (i\partial_\mu - e A_\mu) \Psi = m \Psi$$
and make the following generic transformation $\Psi = U \Psi'$ with $U$ a constant matrix with inverse $UU^{-1}=1$ the equation becomes
$$\gamma^\mu U (i\partial_\mu - e A_\mu) \Psi' = m U \Psi'$$
multiplying by the inverse matrix
$$U^{-1} \gamma^\mu U (i\partial_\mu - e A_\mu) \Psi' = m \Psi'$$
this is equivalent to the original equation if $\gamma^\mu{'} = U^{-1} \gamma^\mu U$. This relation guarantee that the new matrices satisfy the same commutation relationships than the original.
Regarding the specific case of charge conjugation I think the most fundamental approach uses the CPT theorem. In this case parity is trivial therefore it remains charge conjugation (C) and time reversal (T). The Dirac equation is invariant if both the sign of the charge and time are reversed. This is the basis for Stuckelberg Feynman interpretation of antiparticles as particles travelling backward in time.


text:
Q: Python SMTP Client - error in sendmail method TypeError: sendmail() missing 1 required positional argument: 'msg'
from smtplib import SMTP

def signin():
    email='example@example.com'
    password='password'
    conn.ehlo_or_helo_if_needed()
    conn.starttls()
    conn.login(adresa,lozinka)

def write_send_message():
    message=dict()

    message['From:']='example@example.com'
    message['To:']='example2@example.com'
    message['Subject:']='Test message'
    message['Message:']=r'''Test message from Python interpeter'''

    print('Sending the message...:')
    for key in message:
        print(unos,poruka[unos])
    SMTP.sendmail(message['From:'],message['To:'],message['Message:'])

host='smtpserver.smtp.com'
port=587
conn=SMTP(host,port)

signin()

write_send_message ()

I'm not sure where did I make the mistake. Third argument (message['Message']) is my variable containing the text of the message (the value of key 'Message' of the same named dictionary). What do you suggest me to change ?
There's a simallar question (about 6 years old now, was programmed with Tkinter) with the same error. That didn't help here.
https://docs.python.org/3/library/smtplib.html \n
In Python's documentation it says that 'msg' should be a string which is true in my case. I've tried with sendmail but since I've established a connection with the server successfully with ehlo method, it actually wasn't needed.

A: I think you need conn.sendmail rather than SMPT.sendmail.


text:
Q: How to test if strdup() is available? I'm using this:
#if !defined(_SVID_SOURCE) || !defined(_BSD_SOURCE) || _XOPEN_SOURCE < 500 || !(_XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) \
|| _POSIX_C_SOURCE < 200809L
char * strdup(const char *s)
{
  char *buffer = malloc(strlen(s) + 1);

  if(buffer != NULL)
    strcpy(buffer, s);

  return buffer;
}
#endif

But is there the possibility to get a redeclaration error? Maybe into some gcc version or gcc-like compiler? I want to make it compatible with versions (standards) where there is no strdup(), -ansi, for example.
Also, how can I make it more portable?

A: This is absolutely the wrong use of feature test macros. Feature test macros are not defined by the implementation to tell the application what's available; they're defined by the application to request that the implementation provide conformance to (a particular version of) a particular standard.
The macros you should be using to test for a what the implementation supports are in unistd.h:

*

*_POSIX_VERSION - version of POSIX supported. 200809L is latest.

*_XOPEN_VERSION - version of X/Open Portability Guide, now called the "XSI" option of POSIX. Latest is 700 (from SUSv4). 600 (SUSv3) is common. 500 (SUSv2) is badly outdated.

*_POSIX_THREADS - version of pthreads (should be the same as _POSIX_VERSION; mandatory since POSIX 2008)

*...

A: Yes, if it's already defined you will get redeclaration on strdup. The only way I know to get around this type of issue is to macro strdup to something else (say _strdup) and then define strdup with that other name. This is a little ugly but it gets the job done.
To your first question, no you can't determine if a function exists with the preprocessor. See this post.

A: Looking in the string.h on my platform (linux, gnu libc 2.16) I found :
#if defined __USE_SVID || defined __USE_BSD || defined __USE_XOPEN_EXTENDED \
    || defined __USE_XOPEN2K8
/* Duplicate S, returning an identical malloc'd string.  */
extern char *strdup (const char *__s)
     __THROW __attribute_malloc__ __nonnull ((1));
#endif

The #ifs are slightly different, I don't know the influence between those I found in my header and the ones your are using.
About the second question, you could use the autotools to create a config.h header describing the capabilities of the compiling platform, and use your own versions of missing functions.
In addition you could also use the gnulib "source library" which provides implementation of defective or missing functions (like strdup)
Using autotools should prevent any redeclaration error.


text:
Q: How to customize logout options under Kubuntu I'm running a machine with Kubuntu and Windows XP in dual-boot.
I recently learned about the very useful grub-reboot command, and id like to know if it is possible to customize the logout options (like seen on Kickoff last tab, on the dialog that appears when pressing the PC power button, and so on) in order to integrate a "Reboot as Windows" option.
How can I do this?

A: if you use kdm you can get a drop down after you click [reboot|shutdown]!
I don't know if this option actaly calls grub(2)-set-default (do until you select an other option) or grub(2)-reboot (once)
you should make sure you have the following entry in sudo nano /etc/default/grub:
GRUB_DEFAULT=saved

and if you want to save the entry after it is selected in grub use:
GRUB_SAVEDEFAULT=true

afer this run:
sudo update-grub

then in kde go to:
K-menu => Settings => System Settings => Login Screen( under System Administration)
go to the Shutdown tab and there set your boot manager to Grub2
you will have to restart kdm to make this effective with
sudo /etc/init.d/kdm restart


text:
Q: Stored procedure conversion failed when converting the varchar value to data type int? In my stored procedure, I am facing the following problem - how can i fix this?
CREATE PROC RupeshTest(@QueID int, @Answer varchar(250)) as
BEGIN
   DECLARE @STR varchar(4000)

   SELECT @STR = COALESCE(@str + ';','') + AnswerText
   FROM SurveyQuestionAnswerTypes
   WHERE AnswerType = (SELECT AnswerType
                       FROM SurveyQuestions
                       WHERE QuestionID = CAST(@QueId AS VARCHAR(4)))
                         AND AnswerValue IN (REPLACE(@Answer,'^',','))
END

When I run it
RupeshTest 25, '2^3^5^7^8'

I get following error

Msg 245, Level 16, State 1, Procedure RupeshTest, Line 4
  Conversion failed when converting the varchar value '2,3,5,7,8' to data type int.

Although I understand the problem, but unable to fix it, could some body tell me how can I fix it.

A: This wont work, since the final Query being formed is :
SELECT @STR = COALESCE(@str + ';','') + AnswerText
   FROM SurveyQuestionAnswerTypes
   WHERE AnswerType = (SELECT AnswerType
                       FROM SurveyQuestions
                       WHERE QuestionID = CAST(@QueId AS VARCHAR(4)))
                         AND AnswerValue IN ('2,3,5,7,8')

Where as you want something like this:
SELECT @STR = COALESCE(@str + ';','') + AnswerText
   FROM SurveyQuestionAnswerTypes
   WHERE AnswerType = (SELECT AnswerType
                       FROM SurveyQuestions
                       WHERE QuestionID = CAST(@QueId AS VARCHAR(4)))
                         AND AnswerValue IN (2,3,5,7,8)

I would advice you to make a UDF String_To_Table, pass the string to that UDF and use for the IN clause.
String_To_Table UDF:
CREATE FUNCTION [dbo].[String_To_Table]
                    (@string      VARCHAR(4000),
                     @delimiter CHAR(1) = ';')
         RETURNS @tbl TABLE (ord INT IDENTITY(1, 1) NOT NULL,
                             token     VARCHAR(500)) AS

   BEGIN
      DECLARE @pos      int,
              @textpos  int,
              @chunklen smallint,
              @tmpstr   varchar(4000),
              @leftover varchar(4000),
              @tmpval   varchar(4000)

      SET @textpos = 1
      SET @leftover = ''
      WHILE @textpos <= datalength(@string)
      BEGIN
         SET @chunklen = 4000 - datalength(@leftover)
         SET @tmpstr = @leftover + substring(@string, @textpos, @chunklen)
         SET @textpos = @textpos + @chunklen

         SET @pos = charindex(@delimiter, @tmpstr)

         WHILE @pos > 0
         BEGIN
            SET @tmpval = ltrim(rtrim(left(@tmpstr, @pos - 1)))
            INSERT @tbl (token) VALUES(@tmpval)
            SET @tmpstr = substring(@tmpstr, @pos + 1, len(@tmpstr))
            SET @pos = charindex(@delimiter, @tmpstr)
         END

         SET @leftover = @tmpstr
      END

    IF ltrim(rtrim(@leftover)) <> ''
        INSERT @tbl(token) VALUES (ltrim(rtrim(@leftover)))

 RETURN
   END

Then you can change your SP as below:
CREATE PROC RupeshTest(@QueID int, @Answer varchar(250)) as
BEGIN
   DECLARE @STR varchar(4000)

   SELECT @STR = COALESCE(@str + ';','') + AnswerText
   FROM SurveyQuestionAnswerTypes
   WHERE AnswerType = (SELECT AnswerType
                       FROM SurveyQuestions
                       WHERE QuestionID = CAST(@QueId AS VARCHAR(4)))
                         AND AnswerValue IN (SELECT Token FROM dbo.String_To_Table(@Answer,'^'))
END

A: The problem you are facing here is the part  AnswerValue IN (2,3,5,7,8) and how to make it valid SQL because the values are a list of Integers and you have them as strings. One trick for me is to make all the SQL command a string and Execute it:
DECLARE @SQLQuery AS varchar(4000)

SET SQLQuery =
'SELECT AnswerText '
+ ' FROM SurveyQuestionAnswerTypes '
+ ' WHERE AnswerType = (SELECT AnswerType '
                   + ' FROM SurveyQuestions '
                   + ' WHERE QuestionID = ' + CAST(@QueId AS VARCHAR(4)))
                    + ' AND AnswerValue IN (' + (REPLACE(@Answer,'^',',')) + ')'

EXECUTE(@SQLQuery)

by the way, there is no reason to send the numbers with the ^ and then change it.

A: You could replace the last condition with
AND CHARINDEX(CONCAT("^", CAST(AnswerValue AS CHAR), "^"), CONCAT("^", @Answer, "^"))

It doesn't seem totally right, but it might do the trick.
edited
Thanks for the corrections.