text:
Q: https routes to node js production I have an application on nodejs running on a kinghost.com host, it enabled SSL we will encrypt, but my application still does not respond with https only by http. I made this setting below in the application so that the requests were turned into https, but it did not work. Could someone tell me what to do, where I am wrong, some example. I do not know what else to do.
File app.js
app.set('port', process.env.PORT || 21019);
app.listen(app.get('port'));

app.use(function(req, res, next) {
    if ((req.get('X-Forwarded-Proto') !== 'https')) {
        res.redirect('https://' + req.get('Host') + req.url);
    } else
    next();
});

Full app.js file
var express           = require('express');
var session           = require('express-session');
var cookieParser      = require('cookie-parser');
var bodyParser        = require('body-parser');
var logger            = require('morgan');
var path              = require('path');
var fileUpload        = require('express-fileupload');

var https             = require('https');

var app               = express();
var expressValidator  = require('express-validator');
var passport          = require('passport');
var flash             = require('connect-flash');

// - Cria rotas
var routes            = require('./routes/index');
var usuarios          = require('./routes/usuario');
var motorista         = require('./routes/motorista');
var login             = require('./routes/login');
var aluno             = require('./routes/aluno');
var contrato          = require('./routes/contrato');
var boleto            = require('./routes/boleto');
var pessoa            = require('./routes/pessoa');

require('./security/autenticacao')(passport);

app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(session({
    secret: 'reis&turlwaysrunning',
    resave: true,
    saveUninitialized: true
 } ));
app.use(logErrors);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function (req, res, next) {
    res.locals.login = req.user;
    next();
});
app.use(fileUpload());

app.set('port', process.env.PORT || 21019);
app.listen(app.get('port'));

app.use(function(req, res, next) {
    if ((req.get('X-Forwarded-Proto') !== 'https')) {
        res.redirect('https://' + req.get('Host') + req.url);
    } else
    next();
});

// Atriui rotas
app.use('/home', routes);
app.use('/usuarios', usuarios);
app.use('/alunos', aluno);
app.use('/motoristas', motorista);
app.use('/contratos', contrato);
app.use('/login', login);
app.use('/boletos', boleto);
app.use('/pessoas', pessoa);

//app.listen(port);

function logErrors (err, req, res, next) {
    console.error('Troxa: ' + err.stack)
    next(err)
  }

module.exports = app;

I tried that too and it did not work
File app.js
https.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Hello World!');
    res.end();
  }).listen(21019);

Full app.js file
    var express           = require('express');
    var session           = require('express-session');
    var cookieParser      = require('cookie-parser');
    var bodyParser        = require('body-parser');
    var logger            = require('morgan');
    var path              = require('path');
    var fileUpload        = require('express-fileupload');

    var https             = require('https');

    var app               = express();
    var expressValidator  = require('express-validator');
    var passport          = require('passport');
    var flash             = require('connect-flash');

    // - Cria rotas
    var routes            = require('./routes/index');
    var usuarios          = require('./routes/usuario');
    var motorista         = require('./routes/motorista');
    var login             = require('./routes/login');
    var aluno             = require('./routes/aluno');
    var contrato          = require('./routes/contrato');
    var boleto            = require('./routes/boleto');
    var pessoa            = require('./routes/pessoa');

    require('./security/autenticacao')(passport);

    app.use(logger('dev'));
    app.use(expressValidator());
    app.use(cookieParser());
    app.use(bodyParser.json({limit: "50mb"}));
    app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
    app.use(express.static(path.join(__dirname, 'public')));
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use(session({
        secret: 'reis&turlwaysrunning',
        resave: true,
        saveUninitialized: true
     } ));
    app.use(logErrors);
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(flash());
    app.use(function (req, res, next) {
        res.locals.login = req.user;
        next();
    });
    app.use(fileUpload());

    https.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Hello World!');
    res.end();
  }).listen(21019);

    // Atriui rotas
    app.use('/home', routes);
    app.use('/usuarios', usuarios);
    app.use('/alunos', aluno);
    app.use('/motoristas', motorista);
    app.use('/contratos', contrato);
    app.use('/login', login);
    app.use('/boletos', boleto);
    app.use('/pessoas', pessoa);

    //app.listen(port);

    function logErrors (err, req, res, next) {
        console.error('Troxa: ' + err.stack)
        next(err)
      }

A: You could try the method of implementing https with express as shown here Enabling HTTPS on express.js ?

A: You need to have your https credential (i.e cert and key ) to use https. You can use this to generate the credentials
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
var fs = require('fs');
var https = require('https');

var httpsServerOptions = {
  'key': fs.readFileSync('./https/key.pem'),
  'cert': fs.readFileSync('./https/cert.pem')
};

var express = require('express');
var app = express();

// your express configuration here

var httpsServer = https.createServer(httpsServerOptions, app);

httpsServer.listen(21019);

A: If free Let's Encrypt certificates are good enough for you, you could use Greenlock and get free SSL with automated renewal.
Greenlock: Free SSL, Automated HTTPS
Greenlock handles certificate issuance and renewal (via Let's Encrypt) and http => https redirection, out-of-the box.
Instead of calling .listen() from express, you just export your express app (or any node-http compatible function).
Simplified, that looks like this:
express-app.js:
var express = require('express');
var app = express();

app.use('/', function (req, res) {
  res.send({ msg: "Hello, Encrypted World!" })
});

// DO NOT DO app.listen()
// Instead export your app:
module.exports = app;

Then you can use node's http and https for your server, or you can use greenlock express, which sets it up for you:
server.js:
require('greenlock-express').create({
  // Let's Encrypt v2 is ACME draft 11
  version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'

  // You MUST change these to valid email and domains
, email: 'john.doe@example.com'
, approveDomains: [ 'example.com', 'www.example.com' ]
, agreeTos: true

  // This should be the directory to which certificates are saved
, configDir: "/path/to/project/acme/"

, app: require('./express-app.js')

, communityMember: true // Get notified of important updates
, telemetry: true       // Contribute telemetry data to the project
}).listen(80, 443);

Screencast
Watch the QuickStart demonstration: https://youtu.be/e8vaR4CEZ5s

More Info
See https://stackoverflow.com/a/51146209/151312


text:
Q: Show a map of map data in table format in VF Page I have a map called configMap. it is of type Map<String, Map<String, List<A__c>>> where it implies like Map<Obj, Map<Rec, List<A__c>>>.
Just for understanding I have put obj and rec here.
I need to show the data in a vf page in below format.
**Obj 1**

   **Rec 1**

   Table shows List<A__c> data for Rec 1

   **Rec 2**
   Table shows List<A__c> data for Rec 2

**Obj 2**

   **Rec 1**
   Table shows `List<A__c>` data for Rec 1

To achieve this I am trying below approach that fails to print the data.

       <apex:repeat value="{!SetofObjectNames}" var="obj">
        {!configMap[obj]}
         <apex:repeat value="{!SetofRecordTypes}" var="rec">
          <apex:column value="{!configMap[obj][rec]}"/>
         </apex:repeat>
       </apex:repeat>
    </apex:pageBlockTable>

It gives no error. Simply prints ID value for the records of that List.
Can someone please help me here?

A: Hopefully this approach might work for you.
Prepare the map and list as follows:
Map<String, Map<String, List<A__c>>> objectMap {get;set:}

//it will hold the keys like Obj1, Obj2
public List<String> lstObject {get;set;}
lstObject = objectMap.keySet();

//it will hold Rec1 of Obj1, Rec2 of Obj1
public List<String> innerMapKeys {get;set;}

public Map<String, List<A__c>> innerMap = new Map<String, List<A__c>>();

for(String : lstObject)
{
    innerMap = objectMap.get[str];
}
innerMapKeys = innerMap.keySet();

Visualforce
<apex:repeat value="{!lstObject}" var="obj">
    {!obj}
     <apex:repeat value="{!innerMapKeys}" var="rec">
        {!rec}
        <apex:pageBlockTable value="{!innerMap[rec]}" var="innerRec">
            <apex:column value="{!innerRec.Field__c"/>
        </apex:pageBlockTable>
     </apex:repeat>
</apex:repeat>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maximum call stack size exceeded (native stack depth) - React Native Android error
I have an app which works on iOS but the Android version just broke somehow over the weekend. I had a working app before the weekend, and today I opened the app and I had to check the android version as well and it's not working. I commented all the code from the App.tsx basically I have a simple Test there.
Do you guys have any idea how can I fix this issue?
Thanks

A: The reason for this issue should be, calling the setState({}) function continuously.
For example,
consider the below code snippet from class component,
class MyComponent() {
    componentDidUpdate() {
        this.setState({ someStateVariable: someValue })
    }
}

This is one of the places where the setState({}) will be called again and again.
If you are using functional component, check the useEffect(() => {}) function carefully and avoid state update inside useEffect(()=> {}), without any conditions. Also avoid any state update outside of any functions.
For example,
const MyFunction(props) => {
    useEffect(()=> {
        setSomeStateVariable(someValue);
    });
}

This is the open useEffect without any parameter which will be called every change in the component, So we cannot use state update here without wrapping up with any conditions.
Also, check for any child component that updates its local state or parent state variable continuously.
Try to avoid using multiple useEffect(()=> {}), in a functional component.


text:
Q: output variables in view that have been manipulated in controller class MyClass
class MyClass < ActiveRecord::Base

  attr_accessible :attr0, :attr1

end

controller MyController
class MyController < ApplicationController

  helper_method :set_var

  def index
    @myclasses = MyClass.all
  end

  def set_var(foo)
    @var0 = foo.attr0
    @var1 = foo.attr1
  end

end

view

      Head0
      Head1

    <% @myclasses.each do |myclass| %>
      <% set_var(myclass) %>

        <%= @var0 %>
        <%= @var1 %>

    <% end %>

I want to output var0 and var1 after they have been manipulated in set_var, but i must call set_var(myclass) first to cycle through the instances of MyClass. What I did above puts nothing in my view. Is there an elegant way to to this without handling html code in my method set_var?

edit:
as stated below this is not an option, as my example is extremely simplified
 <% @myclasses.each do |myclass| %>

     <%= myclass.attr0 %>
     <%= myclass.attr1 %>

<% end %>

A: @myclasses as written above isn't a controller instance variable, but rather an instance variable of the class itself. To use the @myclasses notation in the view it needs to be an instance variable:
class MyController < ApplicationController
  def some_method
    @myclasses = MyClass.all
  end
end

That aside, I'm not a fan of what you're doing anyway; it seems like you should either be accessing the properties directly, using a model method, using a decorator, or even a regular helper.

Edit after question edited to be correct.
Instance variables are exposed pre-render; new ones created on-the-fly wouldn't be available at that time. You could try initializing them in your action and modifying them, but major yuck.
You're conflating concerns here in a really horrible way: whatever this method is needs to be in a decorator or the model etc., calling back in to the controller in a loop to modify instance variables for each iteration has got to be considered an anti-pattern on all counts.

A: <% @myclasses.each do |myclass| %>

    <%= myclass.attr0 %>
    <%= myclass.attr1 %>

<% end %>

Any reason you cant do that?
edit: If you want to manipulate them, define it in the model.
def modify_attr0
    attr0.to_s+" foo"
end

In the view
myclass.modify_attr0


text:
Q: Is there anyway to retrieve an Instagram image identifier from the CDN link? For example, I have this link, and would it be possible to get a link like so: https://instagram.com/p/5PiBAQOwBt/ from it?

A: From https://instagram.com/p/5PiBAQOwBt/ you can get image link from source code of page:
<meta property="og:image" content="https://igcdn-photos-f-a.akamaihd.net/hphotos-ak-xpt1/t51.2885-15/10005419_943595429032221_1267327891_n.jpg" />
But, if you have just image link, only image searching by Google (etc.) helps to find canonical url.
In Instagram API use media endpoint to get both links.


text:
Q: What is the meaning of percentile? I am confused by the term percentile.
Once my teacher told me that percentile means the percentage with respect to the score of the highest achiever.
This means that if in a competition I got $80$ out of $100$ and the highest score in that competition was 90 out of 100 then my percentile would be $\frac{80}{90}*100=88.89$.
So I got $80\%$ and $88.89$ percentile.
I was believing that my above concept was right.
But when I see the definition of percentile on Wikipedia then I got something new (but I don't understand this definition) and then I thought that what my teacher told me was wrong.
Kindly tell me if my teacher right or wrong.

A: If your memory is correct, your teacher was wrong.
The percentile tells you the value below which a certain percentage of the observations fall.
Thus, if the median score on the test was $80$, a score of $80$ would put you at the fiftieth percentile regardless of what the high score was.

A: "It is an important and popular fact that things are not always what they seem." - Hitchhiker's Guide to The Galaxy
Your teacher meant Percentile Rank.
In the Wikipedia Article, it is verifiably stated that: "In test theory, the percentile rank of a raw score is interpreted as the percentages of examinees in the norm group who scored at or below the score of interest."
So, in mathematical layman's terms, for practical everyday examination purpouses,

"The $n^{\text{th}}$ Perecentile Rank in a group whose highest mark is $m$ is equivalent to $n\%$ of $m$ and vice-versa"

No one can be blamed. The terms Percentile and Percentile Rank are interchanged especially in schools and test centres where they conduct competitive examinations.
A percentile is a different concept similar to deciles in statistics.

A: First, consider the possibility that you misunderstood your teacher or that your words above do not quite capture what (s)he meant. That said, the "percentage with respect to the score of the highest achiever" has nothing to do with percentiles, and I am not sure there is a single word to express "I got within 89% of the best".
Percentiles (or, more generally, quantiles) are about relative positions compared to everyone else. It is not required that whatever you are looking at has numerical values, only that the values can be ordered. Taking an example in the spirit of @Nick's first link, consider a test where

*

*60 people got a D

*you and no one else got a C

*39 people got a B

*no-one got an A or worse than D.

How many % of a B are a C? However, one can still make statements in terms of quantiles, for example:

*

*Everyone in the lower half got a D. (Since some in the upper half did so, too, the median grade is a D, too.)

*Everyone in the highest (fourth) quartile got a B.

*Everyone in the sixth decile got a D. (= those who scored better than the bottom 50%, but worse than the top 30%.)

*Those in the 61st percentile got a C.

*Those in the 62nd percentile got a B.

Thus, quantiles are best imagined as lining up everyone in (ascending) order and putting (ascendingly numbered) separators at n equidistant steps (n=100 for percentiles, 10 for deciles, 4 for quartiles)
Your percentile rank is then the number of the marker closest to you towards the "worse" side. (Note that percentiles make most sense if the considered set has >>100 elements. See the aforementioned link on how handle sets with < 100 elements.)


text:
Q: Object controller and code not being executed I created a very simple new Cocoa application, with a new class and custom controller (or object in interface builder, the plain blue cube). I connected all outlets with interface builder and assigned the custom delegate to the class. The problem is, the code does not get executed (checked by setting breakpoints), the window presents itself, and there are no errors.
The code of the class is really irrelevant, I tried once before with a proper set up and it worked there, I couldn't spot the difference however.
The key here is a separate controller together with class instead of the standard App's Delegate, to integrate the project to a bigger one.


text:
Q: Report type/name of unspecified error in `try` statement? python 2 Here is a quick example of what I mean -
try:
    something_bad

# This works -
except IndexError as I:
    write_to_debug_file('there was an %s' % I)

# How do I do this? -
except as O:
    write_to_debug_file('there was an %s' % O)

What is the correct syntax for the second exception?
Thanks in advance :)

A: except Exception as exc:
Exception is the base class for all "built-in, non-system-exiting exceptions" and should be the base class for user-defined ones as well. except Exception will therefore catch everything except for the few that do not subclass Exception, such as SystemExit, GeneratorExit, KeyboardInterrupt.

A: You don't have to specify the error type. Just use sys.exc_info() to read out the last exception:
import sys

try:
    foobar

except:
    print "Unexpected error of type", sys.exc_info()[0].__name__
    print "Error message:", sys.exc_info()[1]

Reference: https://docs.python.org/2/tutorial/errors.html#handling-exceptions

A: As already pointed by Jason, you can use except Exception as O or except BaseException as O if you want to catch all exceptions, including KeyboardInterrupt.
If you need exception's name, you can use name = O.__class__.__name__ or name = type(O).__name__.
Hope this helps


text:
Q: Run TestNG groups both sequentially and in parallel Ok, so referring to TestNG doc I can run tests either sequentially (by default in a test suite) or in parallel using <suite parallel="tests">.
Now here is my TestNG config
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Complete test suite">
    <listeners>
        <listener class-name="com.uas.test.portlet.integration.util.WebDriverListener" />
        <listener class-name="org.uncommons.reportng.HTMLReporter" />
    </listeners>
    <test name="Parallel tests" parallel="methods" thread-count="4">
        <groups>
            <run>
              <exclude name="sequential-test"></exclude>
            </run>
        </groups>
        <packages>
            <package name="com.uas.test.portlet.integration.main" />
            <package name="com.uas.test.portlet.integration.main.categorymanager" />
            <package name="com.uas.test.portlet.integration.main.admin" />
        </packages>
    </test>
    <test name="Sequential tests" parallel="false" >
        <groups>
            <run>
                <include name="sequential-test"></include>
            </run>
        </groups>
        <packages>
            <package name="com.uas.test.portlet.integration.main" />
            <package name="com.uas.test.portlet.integration.main.categorymanager" />
            <package name="com.uas.test.portlet.integration.main.admin" />
        </packages>
    </test>
</suite>

As you can see, I have 2 types of tests : tests which can be run in parallel and others that should be run in sequential. No parallel=tests attribute in my suite so <test> tags are run sequentially, in such a manner that my first parallel test group is run first and then the sequential ones.
That is perfect, but I would like to go a bit further than this and have 2 subgroups of my sequential tests, each of which could be run in parallel with each other, but both after the main parallel tests... unfortunately I haven't been able to do that...
So to summarize what I want :
1. RUN Parallel tests main group
THEN
2. RUN Sequential tests main group
   --> Sequential subgroup A RUNS IN PARALLEL with Sequential subgroup B (test 1 from subgroup A could run in parallel with test 3 from subgroup B, they are independant)
   --> Each test within subgroup A should run sequentially
   --> Each test within subgroup B should run sequentially

Any idea on how to do that with TestNG config file ? (I would like to avoid using Ant or such).

A: Two separate suites may help. They will be executed sequentially. Just put your tests inside of them depending on what you need.
 <suite-files>
   <suite-file path="./suite1.xml" />
   <suite-file path="./suite2.xml" />
  </suite-files>

A: Steps to run separate suites from a single suite.
(1) Create a new suite xml file, say MasterSuite.xml which contains list of suites:
<suite name="allSuites">
 <suite-files>
   <suite-file path="suite1.xml" />
   <suite-file path="suite2.xml" />
  </suite-files>
</suite>

(2) To execute this suite, use the general approach on how you execute any xml suite.
Note: The suite file path is relative to where the MasterSuite.xml is located.
ref: http://testng.org/doc/documentation-main.html#parallel-running


text:
Q: Get string with number of specified length Supposing there's an array as the following:
$arr = array('foo1234bar', 'foo1234', '1234bar', 'foo12345bar');

and I just need the elements that contains 4 characters in total only. So except for foo12345bar, other 3 elements are valid.
Because '\d{4}' would match foo12345bar, so I try following clumsily:
$arr = array('foo1234bar', 'foo1234', '1234bar', 'foo12345bar');
$result = array();
foreach ($arr as $value) {
    preg_match('/\d+/', $value, $match);
    if (strlen($match[0]) != 4) {
        continue;
    }
    $result[] = $value;
}
var_dump($result);    //array('foo1234bar', 'foo1234', '1234bar')

Is there a regular expression to match directly(so the if condition can be omitted)? Thank you in advance.

A: This easy to handle with look-around regex and preg_grep function:
$arr = array('foo1234bar', 'foo1234', '1234bar', 'foo12345bar');
print_r(preg_grep('/(?<!\d)\d{4}(?!\d)/', $arr));

RegEx Breakup:
(?<!\d)  # assert previous char is not a digit
\d{4}    # match exact 4 digits
(?!\d)   # assert next char is not a digit

Output:
Array
(
    [0] => foo1234bar
    [1] => foo1234
    [2] => 1234bar
)

A: Modify your regex as follows
/^\D*\d{4}\D*$/

Explaination
^ your string must start with
\D any non-digit char
* repeated from 0 to infinite times
\d{4} followed by any digit repeated EXACTLY 4 times
\D followed by any non-digit char
* repeated from 0 to infinite times
$ end of the string
Moreover you could modify your code as follows
$arr = array('foo1234bar', 'foo1234', '1234bar', 'foo12345bar');
$result = array_filter(
    $arr,
    function($element) {
        return preg_match('/^\D*\d{4}\D*$/', $element);
    }
);

var_dump($result);

 Pay attention
As OP didn't specify it, this regex will match even 1234 (any four digit string without non-digit chars in front or behind). If he wishes to have at least a char in front or/and behind, this regex must be changed.

A: Assuming the characters in front of and after the numbers will always be alphabetical, you can use this regex:
^[a-zA-Z]*\d{4}[a-zA-Z]+$

A: the regexp will be \d{4}
 preg_match('/\d{4}/', $value, $match);

expect will help

A: you might try folowing : preg_match('/\D\d{4}\D/', $value, $match);  it searches for:
a not digit(/D)
4 digits(/d{4})
again a non digit(/D)

A: This regular expression will work on all your examples:
'/^\D*(\d{4})\D*$/'
  ││   │     │  └── end string
  ││   │     └───── zero or more NOT digits
  ││   └─────────── four digits ( match 1 )
  │└─────────────── zero or more NOT digits
  └──────────────── start string

They doesn't work if there are multiple number group in the string ( '123abc1234o' ).


text:
Q: adding two numpy.float64 numbers get wrong result I am new to numpy. I tried to add two numpy.float64 numbers, however, the numpy gave me a wrong answer.
Here's my code:(a and b are generated separately by the mean of one numpy array)
print(a)
print(type(a))
print(b)
print(type(b))
c = (a + b)/2
print(c)
print(type(c))

And here's what I got:
1.4617937201411304
<class 'numpy.float64'>
-1.4617937201411302
<class 'numpy.float64'>
1.1102230246251565e-16
<class 'numpy.float64'>

Clearly, the answer should be very close to 0, but what I got is far away from 0.
I guess the problem is that a+b caused an overflow?
However, when I tried to double a, the answer was right:
c = (a * 2)/2

The answer is:
1.4617937201411304
<class 'numpy.float64'>
-1.4617937201411302
<class 'numpy.float64'>
1.4617937201411304
<class 'numpy.float64'>

A: You missed the e-16 at the end of the print. It means the result is 1.1102230246251565 * 10^(-16), which is indeed almost zero.
It's a convention to print numbers with e (the exponent) rather then 0.000000....1110


text:
Q: Bootstrap create additional  tag This is my code:

     2013 © {$config.system.site_name} - правила - уведомление о рисках.

It shows me this in the DOM inspector (in all browsers):

When I turn off the bootstrap.min.css, the mystical  tag disappeared! Why is that?
WOW. I turned off all .css files and .js files, but the "a" tag did not disappear! How can that be?

A: Done. Just close and open browsers, and all turn back to normal, the most insane glitch i ever saw.


text:
Q: php not work on hebrew folder I have a php file php in a Hebrew folder
But the file does not work I get the following message

Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0
  Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0
  Fatal error: Unknown: Failed opening required 'C:/xampp/htdocs/demo/צור-קשר/index.php' (include_path='.;C:\xampp\php\PEAR') in Unknown on line 0

How can I make the php work with a Hebrew folder?


text:
Q: HTTPClient ConnectionKeepAliveStrategy not working as expected I have written the below code where I am sending XML content over a REST POST and then returning the response back to my calling function. I want my calling function to use the same connection for a defined time and should not create new connections again and again.
But this is not working as expected and its still creating new connections for every new request.
String out = null;
StringBuilder sb = new StringBuilder();

        DefaultConnectionKeepAliveStrategy defaultConnectionKeepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                long keepAlive = super.getKeepAliveDuration(response, context);
                if (keepAlive == -1L)
                    keepAlive = 120000L;
                return keepAlive;
            }
        };

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        HttpPost post = new HttpPost(url);
        connectionManager.setMaxTotal(100);
        connectionManager.setDefaultMaxPerRoute(100);
        final int maxRetries = 3;
        try (CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setRetryHandler((exception1, executionCount, context) -> {
            try {
                Thread.sleep(retryWaitTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return (executionCount <= maxRetries);
        }).setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
            int waitPeriod = waitTime;

            public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                this.waitPeriod *= 2;
                return (executionCount <= maxRetries && response.getStatusLine().getStatusCode() >= 500);
            }

            public long getRetryInterval() {
                return this.waitPeriod;
            }
        }).setKeepAliveStrategy(defaultConnectionKeepAliveStrategy).setConnectionTimeToLive(120L, TimeUnit.SECONDS).build()) {

            try {
                StringEntity requestEntity = new StringEntity(xml, ContentType.APPLICATION_XML);
                post.setEntity(requestEntity);

                CloseableHttpResponse response = httpClient.execute(post);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {

                    BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        sb.append(line).append("\n");
                    }

                    br.close();
                } else {
                        .....
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        post.releaseConnection();
        return out;
    }

How can i improve the code?


text:
Q: JHipster Could not resolve placeholder I extended my JHipster application and wrote a service class with the following code:
@Component
@Transactional
public class AmazonClient {

private AmazonS3 s3Client;

@Value("${amazonProperties.endpointUrl}")
private String endpointUrl;

@Value("${amazonProperties.bucketName}")
private String bucketName;

@Value("${amazonProperties.accessKey}")
private String accessKey;

@Value("${amazonProperties.secretKey}")
private String secretKey;

public AmazonClient() {

}

@PostConstruct
private void initializeAmazon() {
    AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
    this.s3Client = new AmazonS3Client(credentials);
}

my application-dev.yml includes the following:
amazonProperties:
  endpointUrl: https://s3.eu-central-1.amazonaws.com
  accessKey: XYZ
  secretKey: XYZ
  bucketName: XYZ

When I start my application with mvwn everything works. When I run my tests I get the following Exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonClient': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'amazonProperties.endpointUrl' in value "${amazonProperties.endpointUrl}"

A: Since you are using jhipster, this happens because you put the credentials in application-dev.yml, and this file will be visible only in dev profile
You need to put in the application.yml file under the src/main/test/resources folder. The test runner will look for properties in this file.


text:
Q: Given the chord, & arc length of circular segment, how to define a formula for the height that is correct when chord length equals the arc length?
In a circular segment, can we depend on the chord length, arch length, and add to it the angle between the tangent at the arc endpoints and the chord (if at all needed), to define the height of the segment.
We want the height to equal zero and the formula is still defined for chord length equal to arc length (and the angle between the tangent and chord is zero).
In other words, we need to deliberately not use radius, arc angle, or divide by the height.

The reason being that I'm using the problem solution in a computer software, and I can not deal with infinitely large radii, or even too big radii in float arithmetics. And intuitively it seems totally possible to depend on tangent angle with very small or zero value, to define a height of zero whenever encountered.

A: The answer to Calculating the height of a circular segment at all points provided only chord and arc lengths shows that you have to solve the equation (where $\phi = \theta /2\in [0,\pi/2]$)
$$\phi= \frac{s}{a} \sin \phi$$
which in general can only be done numerically. If you have determined $\phi$, then
$$h = \frac{a}{2 \sin \phi} ( 1 - \cos \phi) = \frac{a \sin\phi}{2(1+ \cos \phi)} $$
since $\frac{1 - \cos \phi}{ \sin \phi}  = \frac{\sin \phi}{1 + \cos \phi}$. This applies also for $\phi = 0$ which is the "limit angle" for $s = a$. It gives $h = 0$ as desired.
Note that $\phi= \frac{s}{a} \sin \phi$ is equivalent to
$$\frac{a}{s} = \frac{\sin \phi}{\phi} = \sum_{n=1}^\infty (-1)^n\frac{\phi^{2n}} {(2n+1)!} = 1 - \frac{\phi^{2}}{3!} + \frac{\phi^{4}}{5!} - \ldots$$
which allows to get suitable numerical approximations.
By elementary geometry you see that the angle between the tangent at the arc endpoints and the chord is nothing else than $\phi$ (draw a picture). Thus, if you know this angle, you are done.
Remark: If you know $\phi$, then you do not need to calculate $\sin \phi$ and $\cos \phi$ by using the sine and cosine functions. In fact, you have
$$\sin \phi =  \frac{a}{s} \phi \\ \cos \phi =  \sqrt{1 - \frac{a^2}{s^2} \phi^2} \\ h = \frac{a^2 \phi}{2(s + \sqrt{s^2 - a^2\phi^2})}$$


text:
Q: Rails application performance enhancement doubt I am developing an application in Rails in which I have a table that contains static data which will mostly be read-only and will be updated very very rarely.
But a same query will be executed several times on the table (the query does not involve any other table).
To avoid redoing this work, is it advisable to implement some cache mechanism through code??
If so, what is the best technique to implement that?
I am planning to have a GLOBAL hash variable with the primary key as the hash key and the value as the result of the query.

*

*Are there any drawbacks of this technique???

*One thing that I can see is that when the table is updated, the server needs to be restarted.

*Is there a nicer way to do this?
Thanks

A: *

*Yes, you redo something which exist and works perfectly.

*Well, can't see why you think that

*Of course, yes:
Your choices are more or less:

*

*built-in: memory store

*requiring some setup: memcached

*alternative key/value storage: redis http://redis.io/
Have a look here: http://railslab.newrelic.com/scaling-rails

A: You could use Rails.cache - when you need to refresh the cache, just expire the keys?

A: Simplest for dynamic data is to use Rails's own fragment caching.  To expire use a sweeper which is an observer that is called when your model changes and will expire the cache.  See the Rails guide on caching for help on Fragment Caching and Sweepers.
The only thing the guide doesn't cover is pretty obvious, that you need to use the globally keyed fragment and include your record's ID in the key string.  Like: <% cache( "foo_stuff_#{@foo.id}" ) do %>


text:
Q: After upgrading eclipse, aptana, pydev, Debugger not working I upgraded eclipse from 3.6 to 4.2 and Aptana from 2 to 3 with pydev
Now I cannot get the debugger to work. I get the following errors:

Traceback (most recent call last):
File "C:\Google\eclipse\plugins\org.python.pydev_2.6.0.2012062121\pysrc\pydevd.py", line 4, in <module>
from pydevd_comm import  CMD_CHANGE_VARIABLE, \
File "C:\Google\eclipse\plugins\org.python.pydev_2.6.0.2012062121\pysrc\pydevd_comm.py", line 78, in <module>
import pydevd_console
File "C:\Google\eclipse\plugins\org.python.pydev_2.6.0.2012062121\pysrc\pydevd_console.py", line 3, in <module>
from code import InteractiveConsole
ImportError: cannot import name InteractiveConsole

!ENTRY org.python.pydev.debug 4 4 2012-07-08 22:09:17.635
!MESSAGE Unexpected error setting up the debugger
!STACK 0
java.net.SocketException: Socket operation on nonsocket: configureBlocking

_at java.net.DualStackPlainSocketImpl.configureBlocking(Native Method)

_at java.net.DualStackPlainSocketImpl.socketAccept(Unknown Source)

_at java.net.AbstractPlainSocketImpl.accept(Unknown Source)

_at java.net.PlainSocketImpl.accept(Unknown Source)

_at java.net.ServerSocket.implAccept(Unknown Source)

_at java.net.ServerSocket.accept(Unknown Source)

_at org.python.pydev.debug.model.remote.ListenConnector.run(ListenConnector.java:57)

_at java.lang.Thread.run(Unknown Source)

A: If you're encountering this error, check to make sure you don't have any other code.py modules in your PYTHONPATH - ie, in your project. For example I was using web.py and the tutorial has you create a code.py file - renaming this to main.py, the debugger was able to import InteractiveConsole from the correct module (the one in python27\lib).

A: I think that the problem is that the import:
from code import InteractiveConsole

is giving an ImportError. Check if the 'code' module is in your PYTHONPATH (should be at the Python lib: Python/lib/code.py)
I.e.: Open a shell in the command line:
[07:55:55 X:\]python
Python 2.7.2 (default, Feb 23 2012, 00:24:32) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import code
>>> code.__file__
'c:\\bin\\python-2.7.2\\lib\\code.pyc'

If it's really not there, it's a problem in your Python install (should definitely be there).


text:
Q: SQL - Union with case when and group by - HELP needed I'm working with my first union cases, and I don't understand how should I overcome the following issue.
Will appreciate the masters' help :)
The query :)
select Team, sum(Scored) as Scored, sum(Received) as Received
from
(select  HomeTeam as Team, (case when HomeScore > 1 then sum(HomeScore) else 0 end) as Scored
from Matches as a
group by HomeTeam, HomeScore
Union
select  AwayTeam as Team, ( case when AwayScore>1 then sum(AwayScore) else 0 end) as Received
from Matches
 group by AwayTeam, AwayScore)  DERIVED GROUP BY Team

the error :(
Invalid column name 'Received'.
The table
Desired Results
(I'm halfway through, my query doesn't hold all fields)
thank you kind sirs

Updated Query
select Team, sum(Scored) as Scored, sum(Received) as Received
from
(select  HomeTeam as Team, (case when HomeScore > 0 then sum(HomeScore) else 0 end) as Scored,
( case when AwayScore>0 then sum(AwayScore) else 0 end) as Received
from Matches
group by HomeTeam, HomeScore, AwayScore
Union all
select  AwayTeam as Team,  ( case when AwayScore>0 then sum(AwayScore) else 0 end) as Received,
(case when HomeScore > 0 then sum(HomeScore) else 0 end) as Scored
from Matches
group by AwayTeam, AwayScore, HomeScore)  DERIVED GROUP BY Team

Still, the sum of Scored and received is incorrect
Desired Results

A: I think you may update your query to -
select Team, sum(Scored) as Scored, sum(Received) as Received
  from (select HomeTeam as Team,
               SUM(case when HomeScore > 0 then HomeScore else 0 end) as Scored,
               NULL     -- For sum(Received)
          from Matches as a
         group by HomeTeam
         Union
        select AwayTeam,
               NULL,  -- For sum(Scored)
               SUM(case when AwayScore>0 then AwayScore else 0 end) as Received
          from Matches
         group by AwayTeam) DERIVED
 GROUP BY Team


text:
Q: Why we are not using write stage to write the file name to store the Note pad In blue prim, to save the note pad file we are passing global send keys "^s".
After that  in order to write the File name we use a navigation stage.
Now my question is why we are not using write stage to give the note pad file name?

A: You're right - there are multiple ways to write a text. You can use write section, sendkeys, "set clipboard" or you can just write a text file using code stage. In work, you can probably can use anything you want, if it's stable and does the thing right.
I assume, you're doing some exercises, so you're probably asked to do it in a way to learn one method of doing this thing.


text:
Q: Given series $\sum a_n,\sum b_n$ converge absolutely show that $\sum c_n$ where $c_n=a_n\cdot b_n$ converges.
Given series $\sum a_n,\sum b_n$ converge absolutely to $a,b$ show that $\sum c_n$ where $c_n=a_n\cdot b_n$ converges absolutely and converges to $a\cdot b$

I believe I can show that $\sum c_n$ converges by comparison since $\sum \vert c_n\vert=\sum \vert a_n\vert\vert b_n\vert\leq \sum \vert a_n\vert\sum\vert b_n\vert$
But my issue is showing the convergence is $a\cdot b$
I want to show that $\lim_{n\to \infty}\sum_{i=0}^n \vert c_n\vert =\lim_{n\to \infty} \sum_{i=0}^n \vert a_i\vert\vert b_i\vert=ab$
But the same thing I used before no longer seems to work because I get $\lim_{n\to \infty} \sum_{i=0}^n\vert a_i\vert\vert b_i\vert\leq \lim_{n\to \infty} \sum_{i=0}^n \vert a_i\vert \sum_{i=0}^n \vert b_i\vert$
Which I don't believe is what I want, I would need to somehow show that $ab$ is also a lower bound for the limit.

A: $\sum a_nb_n=ab$ is false. Take $a_n=b_n=0$ for $n \geq 2$ and you will easily get a counter-example.
[Any choice of $a_1,a_2,b_1,b_2$ in $(0,\infty)$ will do].

A: Have a look at $$a_n=\begin{cases}2^{-n}&n\text{ odd}\\0&n\text{ even}\end{cases}$$ and $$b_n=\begin{cases}2^{-n}&n\text { even}\\0&n\text{ odd}\end{cases},$$ which makes $c_n=0$.


text:
Q: ASP.NET project size Are there any known issues around how many "pages" are in an ASP.NET project?
Does the size of the DLL created by the project matter at all?
My existing project is about 150 pages and the DLL is only around 3MB but it has increased from about 50 pages and 0.5 MB recently

A: Scott Hanselman got on the subject two years ago.
The absolute limit is your system memory. The bigger the project the more memory it will use.
Surely you can stay in a [50-200] projects in a solution.
If you find your Visual Studio taking more than memory than expected start thinking about breaking your projects up.
In my opinion the best thing to do is to make the project size a design requirement.
EDIT : I'm not really answering to your question. To make it clear. The more elements (Pages, projects, image, references, etc.) you have in your VS2003, VS2005 or VS2008 solution the more Visual Studio will take on memory.

A: I haven't run into any issues with sites up to hundreds of pages in size. How big of a site are we talking about? Are there built-in redundancies between pages which can be resolved by having a single page take parameters?

A: Often times it makes sense to break down subsections of a larger site or project into multiple ASP.NET web projects. This makes the site way more modular. Additionally, if you have common controls that are used throughout the site that often is cause for a project that has just those controls.
To address the question directly, however, I've managed projects that have many, many pages and have had no issue... aside from it becoming "fun" to browser through and develop against.

A: Technically, you can have hundereds (I'd venture to say thousands) of 'pages' in a web application project.
What Russell said though, to break it into modules, would potentially make it easier to maintain.
Is there a limit? No.  Should you organize your project so that it's easier to manage? Yes.

A: There aren't concerns unless you are trying to debug it (or turn off batch compilation).  Or if you have a bunch of folders.  Each folder will have one DLL for all the files with batch turned on.  So if you break things up into a bunch of folders, that could cause fragmentation problems of the processes memory.  Otherwise, no issues for lots of pages.


text:
Q: What is the difference between using pointer vector or non pointer vector? private:
    vector<float*>  m_values;
    vector<float> *m_index;
    vector<float*> *m_rowptr;

What would be the best way to save a large data structure, using vectors?

A: The way to store a large quantity of floats is:
vector<float> m_index;

The vector manages the block of floats for you.
Making a pointer to the vector is pointless (hah!).
Making a vector of pointers is (usually*) not correct for your task, and it introduces a host of performance problems.
Making both things a pointer combines the two problems.

* Depending what you mean by "index", this may be one of those times. If you want a vector of "pointers to float", then make that thing.


text:
Q: Why does my code giving me "mismatch in formal parameter list"? I am trying to transfer the elements from a source stack to a destination stack. And for that i am using some variables and making sure that get transfered into the destination stack in the same order as they were in the source stack. I wrote the following code
#include <iostream>
#include <stack>
using namespace std;

template <typename S>
void transferByVar(stack<S> &source, stack<S> &dest)
{
    int var = 0;
    S topVal;
    if (source.empty())
        return;
    else if (source.size() == 1)
    {
        dest.push(source.top());
        source.pop();
    }

    int size = source.size();
    while (count != size)
    {
        topVal = source.top();
        source.pop();
        while (source.size() != count)
        {
            dest.push(source.top());
            source.pop();
        }
        source.push(topVal);
        while (!dest.empty())
        {
            source.push(dest.top());
            dest.pop();
        }
        ++count;
    }
}

int main()
{
    stack <int> s1;
    stack<int> s2;
    s1.push(0);
    s1.push(1);
    s1.push(2);
    s1.push(3);
    s1.push(4);
    s1.push(5);
    s1.push(6);
    s1.push(7);
    s1.push(8);
    s1.push(9);
    transferByVar(s1, s2);
    int size = s2.size();
    for (int i = 0; i < size; i++)
    {
        cout << s2.top() << " ";
        s2.pop();
    }
    return 0;
}

but it gives me an error of C2563: mismatch of formal parameter list. What can I do to fix this?


text:
Q: HTMLPanel can be used in uiBinder even though it doesn't have a no-args constructor. How come? In http://www.gwtproject.org/doc/latest/DevGuideUiBinder.html
it states that to use a widget in an uiBinder template:

they must be default instantiable; that is, they must provide a zero-argument constructor. However, there are a few ways to get around that. In addition to the @UiFactory and @UiField(provided = true) mechanisms described under Shared resource instances, you can mark your own widgets with the @UiConstructor annotation.

HTMLPanel fills none of these requirements and yet it can be used in an UiBinder template. How come?

A: Some built-in widgets within GWT have custom support in UiBinder so that they can do their work. For these cases, attributes or elements are specially handled (think about <ui:with>, <ui:field>, and of course <g:HTMLPanel>, etc) so that uibinder makes sense to use.
HTMLPanel is a special case, where it can't simply exist by implementing HasHtml and HasWidgets, since those child widgets need to be appended at a certain point inside the html structure. So, instead of working with the public API (as you found in the docs), they... cheated a bit.
The end result is something that you can't replicate in your own code without actually forking uibinder and editing it directly. This has been done in other projects, but runs the high risk of breaking when later changes to UiBinder take place, so generally should be avoided.
TL;DR: Treat HTMLPanel like a special case, which can bend the rules slightly to be more useful. In your own code, try to stick with the UiFactory/UiConstructor/UiChild annotations, setters for attributes, and implementing one of the supported interfaces for child content.


text:
Q: Codeigniter - white strape while getting value I have a problem with CodeIgniter:
A white strip appears on the top of the website while transfering values between pages. You can see it here: http://i.imgur.com/dYMsRs5.png?1
I deleted all styles but it didn't solve the problem.
I think that my configuration in CodeIgniter could be wrong, but I don't know what I can change.
Have you ever seen something like this?

A: it is your browser default padding margin problem . in your css file use
*{
padding : 0;
margin:0;
}

your problem will be solve

A: Your CI-Configuration is not wrong, but the image itself have a white space of visible height..that is why no css apply on it..
But you can do it using
.your_image {
 background-position : pos1 pos2;
}
Hope it would help u..


text:
Q: How to access variable outside js function Probably trivial, but I have no idea how to do it... I want to access img outside of createThumbnail. How can I do that?
Function
function createThumbnail(){
    canvas.deactivateAll().renderAll();
    html2canvas($('#chartdiv'), {
        onrendered: function(canvas) {
            var img = canvas.toDataURL("image/png"),
                elem = document.getElementById("thumbnail_img");
                elem.src = img;
        }
    });
}

A: You are setting a local variable to the onrendered callback. Move that outside of the function and then just assign that variable from within the function.
var img; //Set empty variable here.

function createThumbnail(){
  canvas.deactivateAll().renderAll();
  html2canvas($('#chartdiv'), {
    onrendered: function(canvas) {
      var elem;
      img = canvas.toDataURL("image/png");
      elem = document.getElementById("thumbnail_img");
      elem.src = img;
    }
  });
}

See this article about closures

A: best is to return an object. so you can "use" createThumbnail multiple times (this isn't possible with a global variable).
This way your code is nice and you don't make the function depending on your global scope / global variables.
function createThumbnail(){
    canvas.deactivateAll().renderAll();
    var img = {}, elem;
    html2canvas($('#chartdiv'), {
        onrendered: function(canvas) {
            img.dataUrl = canvas.toDataURL("image/png"),
            elem = document.getElementById("thumbnail_img");
            elem.src = img;
        }
    });
    return img;
}

var img = createThumbnail();
var dataUrl = img.dataUrl; // contains the dataUrl from the canvas when onrendered was called

A: You can't by default, since img is declared inside the anonymous function. You'll have to assign it to something accessible from the outside.
var accessibleImg;

function createThumbnail(){
    canvas.deactivateAll().renderAll();
    html2canvas($('#chartdiv'), {
        onrendered: function(canvas) {
            var img = canvas.toDataURL("image/png"),
                elem = document.getElementById("thumbnail_img");
                elem.src = img;
            accessibleImg = img;
        }
    });
}


text:
Q: How do I get a value in a BehaviorSubject to return within a getter? From my understanding, when you subscribe to a BehaviorSubject, that subscription is asynchronous. I am trying to get a value from an object within a BehaviorSubject and return that value in a getter. The getter needs to return the type 'number'. How do I approach this?
Below, I have a getter userId, which should return the user Id from an object held in the BehaviorSubject _loggedInUser

export class AuthServiceService {

  private _loggedInUser: BehaviorSubject<LoggedInUserData> = new BehaviorSubject(null);

  constructor(
    private http: HttpClient,
    private storage: Storage
  ) { }

 /// This method below!!! --------------

  public get userId(): number{

    this._loggedInUser.pipe(
      take(1),
      map(((loggedInUserData: LoggedInUserData) => {
        if(loggedInUserData){
          return loggedInUserData.user_id
        }
        return null;
      }))
    ).subscribe((userId: number | null) => {
      return userId;
    });

  }

 //// -----------------

  public doLogin(loginData: LoginFormData): Observable<any>{

    return this.http.post<LoggedInUserData>(`${authURL}/token`, loginData)
    .pipe(
      catchError(err => {

        if(err.status && err.status === 403)
          return throwError('The credentials you have entered are invalid or do not exist.');
        else
          return throwError('There was an issue processing your request.');

      }),
      tap(respData => {

        console.log('LOGGED IN USER DATA: ', respData);

        this._loggedInUser.next(respData);
        this.storage.set('userData', respData);

      })
    );

  }

  public async autoLogin(){

  }

  public doLogout(){

  }

}

A: Having an access to the Subject, you can obtain its value synchronously via getValue() mothod, as following:
public get userId(): number {
  return this._loggedInUser.getValue()?.userId
}

A: If you simply need the result synchronious, you should use the example as provided by Rafi Henig:
    public get userId(): number {
      return this._loggedInUser.getValue()?.userId
    }

If you want it to be async, you could return an Observable<number> instead and use an async pipe in your html if you need to show it there. If not, you can subscribe to that Observable where you need it or keep the subscription if you want to track changes of the value. I am not sure if this is what you want, but here is an example of that:
  public get userId(): Observable<number> {
    return this._loggedInUser.pipe(
      map((item) => item?.userId)
    );
  }

For HTML, use: {{ userId | async }} and for typescript code you can use:
    this.userId.pipe(take(1)).subscribe((userId) => {
      console.log(userId);
    });

If you want to keep track the changes in your typescript, you should remove take(1) and simply subscribe to it. Remember to clean the subscription in ngOnDestroy.

A: Another approach - convert Observable to Promise, then use async/await:
const user = await this._loggedInUser.toPromise();
return user && user.userId;


text:
Q: RecyclerView divider lost when change item background colour I have RecyclerView item decoration and add my RecyclerView. RecyclerView divider lost when change item background color.
My RecyclerView with divider:

When RecyclerView items selected, not show divider:

setBackgroundColor:
private void setBackgroundColor() {

    if (selectedItem.isEmpty() || !selectedItem.contains(item)) {
        this.setBackgroundColor(Color.TRANSPARENT);
    } else {
        this.setBackgroundColor(0xffffedc7);
    }
}

DividerItemDecoration:
public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private Drawable mDivider;

    public DividerItemDecoration(int resId) {
        mDivider = ContextCompat.getDrawable(MyApplication.getContext(), resId);
    }

    @Override
    public void onDraw(@NonNull Canvas canvas, RecyclerView parent, @NonNull RecyclerView.State state) {
        int left = MyApplication.getContext().getResources().getDimensionPixelSize(R.dimen.profileImageSizeDivider);
        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(canvas);
        }
    }
}

A: Try this:
/**
 * Draws left or right inset dividers at the bottom of every recycler item view. Only supports
 * vertical orientations.
 */
public class InsetDividerItemDecoration extends RecyclerView.ItemDecoration {

    private int mLeftInset = 0;
    private int mRightInset = 0;
    private int mStartPosition = 0;

    final private Paint mLinePaint = new Paint();
    final private List<Integer> mPositionsToIgnore = new ArrayList<>();

    public InsetDividerItemDecoration(int leftInset, int rightInset, int dividerColor) {
        mLeftInset = leftInset;
        mRightInset = rightInset;
        setColor(dividerColor);
    }

    public InsetDividerItemDecoration(int leftInset, int rightInset, int dividerColor, int startPosition) {
        mLeftInset = leftInset;
        mRightInset = rightInset;
        mStartPosition = startPosition;
        setColor(dividerColor);
    }

    public InsetDividerItemDecoration(int leftInset, int rightInset, int dividerColor, int startPosition, int dividerHeight) {
        mLeftInset = leftInset;
        mRightInset = rightInset;
        mStartPosition = startPosition;
        setColor(dividerColor);
        setDividerHeight(dividerHeight);
    }

    public InsetDividerItemDecoration(int leftInset, int rightInset) {
        this(leftInset, rightInset, 0);
    }

    public int getColor() {
        return mLinePaint.getColor();
    }

    public void setColor(int color) {
        mLinePaint.setColor(color);
    }

    public int getLeftInset() {
        return mLeftInset;
    }

    public void setLeftInset(int leftInset) {
        mLeftInset = leftInset;
    }

    public int getRightInset() {
        return mRightInset;
    }

    public void setRightInset(int rightInset) {
        mRightInset = rightInset;
    }

    public void setDividerHeight(int height) {
        mLinePaint.setStrokeWidth(height);
    }

    public int getDividerHeight() {
        return (int) mLinePaint.getStrokeWidth();
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        final int visibleItems = parent.getLayoutManager().getChildCount();

        for (int i = 0; i < visibleItems; i++) {
            View itemView = parent.getLayoutManager().getChildAt(i);
            final int adapterPosition = parent.getChildAdapterPosition(itemView);

            final boolean shouldDraw = adapterPosition != RecyclerView.NO_POSITION
                    && adapterPosition != parent.getAdapter().getItemCount() - 1
                    && adapterPosition >= mStartPosition
                    && !shouldIgnoreAdapterPosition(adapterPosition);

            if (shouldDraw) {
                Rect itemRect = new Rect();
                itemView.getDrawingRect(itemRect);

                parent.offsetDescendantRectToMyCoords(itemView, itemRect);

                final int lineStartX = mLeftInset;
                final int lineStartY = itemRect.bottom;

                final int lineEndX = itemRect.right - mRightInset;
                final int lineEndY = lineStartY;

                c.drawLine(lineStartX, lineStartY, lineEndX, lineEndY, mLinePaint);
            }
        }
    }

    protected boolean shouldIgnoreAdapterPosition(int position) {
        return mPositionsToIgnore.size() > 0 && mPositionsToIgnore.contains(position);
    }

    public void setStartPosition(int startPosition) {
        mStartPosition = startPosition;
    }

    public void setPositionsToIgnore(List<Integer> positionsToIgnore) {
        mPositionsToIgnore.clear();
        if (positionsToIgnore != null) {
            mPositionsToIgnore.addAll(positionsToIgnore);
        }
    }

    public void setPositionsToIgnore(Integer[] positionsToIgnore) {
        setPositionsToIgnore(Arrays.asList(positionsToIgnore));
    }
}


text:
Q: ConstantForce and RigidBody Im quite new to programming and working with the coding system in Unity.  I have searched the web for this but I still haven't found a solution or proper answer.
Could ConstantForce affect a GameObject without a RigidBody?
I am wanting to create a magnetic like effect on my GameObject so that it is pushed backwards like a strong wind on an incline while I am trying to move forward.  I tried to use a RigidBody but the gravity of the RigidBody makes the GameObject slide down the incline.  Because of this effect I haven't started scripting the movement because I dont want the gameObject to start sliding backwards when forward motion stops.  I want this to be done by the ConstantForce.
Thank you in advance for any answers and I hope I was able to explain this well.

A: You will need the RigidBody to be able to apply ConstantForce.

Constant Force is a quick utility for adding constant forces to a
  Rigidbody. This works great for one shot objects like rockets, if you
  don't want it to start with a large velocity but instead accelerate.

You can disable the gravity on a RigidBody to solve your problem.
if(collider.attachedRigidbody)
   collider.attachedRigidbody.useGravity = false;


text:
Q: Java - Camunda BPMN model API: how to save valid xml? I'm building some test BPMN 2.0 models and saving them to xml files, in a Java project, by following the examples provided by the official doc, in this case the example 2.
I imported the lib in my pom like below:
<!-- https://mvnrepository.com/artifact/org.camunda.bpm.model/camunda-bpmn-model -->
<dependency>
    <groupId>org.camunda.bpm.model</groupId>
    <artifactId>camunda-bpmn-model</artifactId>
    <version>7.10.0</version>
</dependency>

and this is my test class, following the example 2:
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.*;
import org.camunda.bpm.model.bpmn.instance.Process;

import java.io.File;
import java.io.IOException;

public class Test {
    protected static <T extends BpmnModelElementInstance> T createElement(BpmnModelInstance modelInstance, BpmnModelElementInstance parentElement, String id, Class<T> elementClass) {
        T element = modelInstance.newInstance(elementClass);
        element.setAttributeValue("id", id, true);
        parentElement.addChildElement(element);
        return element;
    }

    public static SequenceFlow createSequenceFlow(BpmnModelInstance modelInstance, Process process, FlowNode from, FlowNode to) {
        String identifier = from.getId() + "-" + to.getId();
        SequenceFlow sequenceFlow = createElement(modelInstance, process, identifier, SequenceFlow.class);
        process.addChildElement(sequenceFlow);
        sequenceFlow.setSource(from);
        from.getOutgoing().add(sequenceFlow);
        sequenceFlow.setTarget(to);
        to.getIncoming().add(sequenceFlow);
        return sequenceFlow;
    }

    public static void main(String[] args) throws IOException {
        // create an empty model
        BpmnModelInstance modelInstance = Bpmn.createEmptyModel();
        Definitions definitions = modelInstance.newInstance(Definitions.class);
        definitions.setTargetNamespace("http://camunda.org/examples");
        modelInstance.setDefinitions(definitions);

        // create a process
        Process process = modelInstance.newInstance(Process.class);
        process.setId("process");
        definitions.addChildElement(process);

        // create elements
        StartEvent startEvent = createElement(modelInstance, process, "start", StartEvent.class);
        ParallelGateway fork = createElement(modelInstance, process, "fork", ParallelGateway.class);
        ServiceTask task1 = createElement(modelInstance, process, "task1", ServiceTask.class);
        task1.setName("Service Task");
        UserTask task2 = createElement(modelInstance, process, "task2", UserTask.class);
        task2.setName("User Task");
        ParallelGateway join = createElement(modelInstance, process, "join", ParallelGateway.class);
        EndEvent endEvent = createElement(modelInstance, process, "end", EndEvent.class);

        // create flows
        createSequenceFlow(modelInstance, process, startEvent, fork);
        createSequenceFlow(modelInstance, process, fork, task1);
        createSequenceFlow(modelInstance, process, fork, task2);
        createSequenceFlow(modelInstance, process, task1, join);
        createSequenceFlow(modelInstance, process, task2, join);
        createSequenceFlow(modelInstance, process, join, endEvent);

        // validate and write model to file
        Bpmn.validateModel(modelInstance);
        File file = new File("bpmn-model.bpmn.xml");
        file.createNewFile();
        Bpmn.writeModelToFile(file, modelInstance);
    }
}

Here the generated BPMN 2.0 xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<definitions id="definitions_7b2df680-1d9c-4897-ba8b-a83548ab937f" targetNamespace="http://camunda.org/examples" xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <process id="process">
    <startEvent id="start">
      <outgoing>start-fork</outgoing>
    </startEvent>
    <parallelGateway id="fork">
      <incoming>start-fork</incoming>
      <outgoing>fork-task1</outgoing>
      <outgoing>fork-task2</outgoing>
    </parallelGateway>
    <serviceTask id="task1" name="Service Task">
      <incoming>fork-task1</incoming>
      <outgoing>task1-join</outgoing>
    </serviceTask>
    <userTask id="task2" name="User Task">
      <incoming>fork-task2</incoming>
      <outgoing>task2-join</outgoing>
    </userTask>
    <parallelGateway id="join">
      <incoming>task1-join</incoming>
      <incoming>task2-join</incoming>
      <outgoing>join-end</outgoing>
    </parallelGateway>
    <endEvent id="end">
      <incoming>join-end</incoming>
    </endEvent>
    <sequenceFlow id="start-fork" sourceRef="start" targetRef="fork"/>
    <sequenceFlow id="fork-task1" sourceRef="fork" targetRef="task1"/>
    <sequenceFlow id="fork-task2" sourceRef="fork" targetRef="task2"/>
    <sequenceFlow id="task1-join" sourceRef="task1" targetRef="join"/>
    <sequenceFlow id="task2-join" sourceRef="task2" targetRef="join"/>
    <sequenceFlow id="join-end" sourceRef="join" targetRef="end"/>
  </process>
</definitions>

Altough the validation method, the generated xml appears to be invalid when trying to display the BPMN using both the Camunda Modeler app and bpmn.io.
What is wrong with this example, hence with my code?
How can I make the generated xml to be valid? Since bpmn 2.0 is a standard, I'm also a bit surprised of this problem.

A: I finally got it working by switching to the fluent model builder API, following this https://blog.camunda.com/post/2014/02/the-new-camunda-bpmn-model-api/
This is my updated test calss:
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.GatewayDirection;

import java.io.File;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        BpmnModelInstance modelInstance = Bpmn.createProcess()
            .name("BPMN API Invoice Process")
            .executable()
            .startEvent()
            .name("Invoice received")
            .camundaFormKey("embedded:app:forms/start-form.html")
            .userTask()
            .name("Assign Approver")
            .camundaFormKey("embedded:app:forms/assign-approver.html")
            .camundaAssignee("demo")
            .userTask()
            .id("approveInvoice")
            .name("Approve Invoice")
            .camundaFormKey("embedded:app:forms/approve-invoice.html")
            .camundaAssignee("${approver}")
            .exclusiveGateway()
            .name("Invoice approved?")
            .gatewayDirection(GatewayDirection.Diverging)
            .condition("yes", "${approved}")
            .userTask()
            .name("Prepare Bank Transfer")
            .camundaFormKey("embedded:app:forms/prepare-bank-transfer.html")
            .camundaCandidateGroups("accounting")
            .serviceTask()
            .name("Archive Invoice")
            .endEvent()
            .name("Invoice processed")
            .moveToLastGateway()
            .condition("no", "${!approved}")
            .userTask()
            .name("Review Invoice")
            .camundaFormKey("embedded:app:forms/review-invoice.html")
            .camundaAssignee("demo")
            .exclusiveGateway()
            .name("Review successful?")
            .gatewayDirection(GatewayDirection.Diverging)
            .condition("no", "${!clarified}")
            .endEvent()
            .name("Invoice not processed")
            .moveToLastGateway()
            .condition("yes", "${clarified}")
            .connectTo("approveInvoice")
            .done();

        // validate and write model to file
        Bpmn.validateModel(modelInstance);
        File file = new File("bpmn-model.bpmn.xml");
        file.createNewFile();

        String bpmnString = Bpmn.convertToString(modelInstance);
        System.out.println("bpmnString");
        System.out.println(bpmnString);

        Bpmn.writeModelToFile(file, modelInstance);
    }
}

and this is the generated xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<definitions xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="definitions_3bd3e094-3e53-4644-af0c-1a048653920c" targetNamespace="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <process id="process_e14ca74e-6095-4a2b-bced-debcb3b37954" isExecutable="true" name="BPMN API Invoice Process">
    <startEvent camunda:formKey="embedded:app:forms/start-form.html" id="startEvent_e8daa33a-af99-4b7a-87ee-200b0e7bedcd" name="Invoice received">
      <outgoing>sequenceFlow_cb28e7e5-ebc0-4f27-b8b2-24403ab87ce3</outgoing>
    </startEvent>
    <userTask camunda:assignee="demo" camunda:formKey="embedded:app:forms/assign-approver.html" id="userTask_029f48b9-de24-4292-af49-845e81fdcc4b" name="Assign Approver">
      <incoming>sequenceFlow_cb28e7e5-ebc0-4f27-b8b2-24403ab87ce3</incoming>
      <outgoing>sequenceFlow_57a81fcd-fb35-42cd-afca-7c4c7914936d</outgoing>
    </userTask>
    <sequenceFlow id="sequenceFlow_cb28e7e5-ebc0-4f27-b8b2-24403ab87ce3" sourceRef="startEvent_e8daa33a-af99-4b7a-87ee-200b0e7bedcd" targetRef="userTask_029f48b9-de24-4292-af49-845e81fdcc4b"/>
    <userTask camunda:assignee="${approver}" camunda:formKey="embedded:app:forms/approve-invoice.html" id="approveInvoice" name="Approve Invoice">
      <incoming>sequenceFlow_57a81fcd-fb35-42cd-afca-7c4c7914936d</incoming>
      <incoming>sequenceFlow_6987bcb8-5f6a-467b-9b25-e21b90dd0d4d</incoming>
      <outgoing>sequenceFlow_1fe15a36-427e-4000-8fc7-50b8925ea1e5</outgoing>
    </userTask>
    <sequenceFlow id="sequenceFlow_57a81fcd-fb35-42cd-afca-7c4c7914936d" sourceRef="userTask_029f48b9-de24-4292-af49-845e81fdcc4b" targetRef="approveInvoice"/>
    <exclusiveGateway gatewayDirection="Diverging" id="exclusiveGateway_b66a0444-2889-4cae-ac78-c1f65405ba0b" name="Invoice approved?">
      <incoming>sequenceFlow_1fe15a36-427e-4000-8fc7-50b8925ea1e5</incoming>
      <outgoing>sequenceFlow_9156c1d4-f756-447b-a384-e3bf17c43ff4</outgoing>
      <outgoing>sequenceFlow_29bab2ba-6108-4731-94c3-93a6955d1946</outgoing>
    </exclusiveGateway>
    <sequenceFlow id="sequenceFlow_1fe15a36-427e-4000-8fc7-50b8925ea1e5" sourceRef="approveInvoice" targetRef="exclusiveGateway_b66a0444-2889-4cae-ac78-c1f65405ba0b"/>
    <sequenceFlow id="sequenceFlow_9156c1d4-f756-447b-a384-e3bf17c43ff4" name="yes" sourceRef="exclusiveGateway_b66a0444-2889-4cae-ac78-c1f65405ba0b" targetRef="userTask_79a63b4f-96a7-43d7-aab3-e8e0e83769e5">
      <conditionExpression id="conditionExpression_13d7607b-d7e7-4fa4-a364-aeabff28a0f1">${approved}</conditionExpression>
    </sequenceFlow>
    <userTask camunda:candidateGroups="accounting" camunda:formKey="embedded:app:forms/prepare-bank-transfer.html" id="userTask_79a63b4f-96a7-43d7-aab3-e8e0e83769e5" name="Prepare Bank Transfer">
      <incoming>sequenceFlow_9156c1d4-f756-447b-a384-e3bf17c43ff4</incoming>
      <outgoing>sequenceFlow_b82e04ab-a0cc-4969-989a-1ec64d74d990</outgoing>
    </userTask>
    <serviceTask id="serviceTask_9d976f99-f8fb-4705-ae6d-a606758111f4" name="Archive Invoice">
      <incoming>sequenceFlow_b82e04ab-a0cc-4969-989a-1ec64d74d990</incoming>
      <outgoing>sequenceFlow_f0f99688-25b1-417e-9a5d-0d17503cb3ba</outgoing>
    </serviceTask>
    <sequenceFlow id="sequenceFlow_b82e04ab-a0cc-4969-989a-1ec64d74d990" sourceRef="userTask_79a63b4f-96a7-43d7-aab3-e8e0e83769e5" targetRef="serviceTask_9d976f99-f8fb-4705-ae6d-a606758111f4"/>
    <endEvent id="endEvent_affc9949-819a-4b79-98bd-0f2fd844d014" name="Invoice processed">
      <incoming>sequenceFlow_f0f99688-25b1-417e-9a5d-0d17503cb3ba</incoming>
    </endEvent>
    <sequenceFlow id="sequenceFlow_f0f99688-25b1-417e-9a5d-0d17503cb3ba" sourceRef="serviceTask_9d976f99-f8fb-4705-ae6d-a606758111f4" targetRef="endEvent_affc9949-819a-4b79-98bd-0f2fd844d014"/>
    <sequenceFlow id="sequenceFlow_29bab2ba-6108-4731-94c3-93a6955d1946" name="no" sourceRef="exclusiveGateway_b66a0444-2889-4cae-ac78-c1f65405ba0b" targetRef="userTask_7b955191-5741-44df-b7ba-d154ddfbe616">
      <conditionExpression id="conditionExpression_ce06d35f-8638-4699-802b-7f1b94732f46">${!approved}</conditionExpression>
    </sequenceFlow>
    <userTask camunda:assignee="demo" camunda:formKey="embedded:app:forms/review-invoice.html" id="userTask_7b955191-5741-44df-b7ba-d154ddfbe616" name="Review Invoice">
      <incoming>sequenceFlow_29bab2ba-6108-4731-94c3-93a6955d1946</incoming>
      <outgoing>sequenceFlow_74d95e16-7907-4000-9ffb-cdba8c3ddde4</outgoing>
    </userTask>
    <exclusiveGateway gatewayDirection="Diverging" id="exclusiveGateway_5aa645c5-a5e7-4453-8498-8462092b85b1" name="Review successful?">
      <incoming>sequenceFlow_74d95e16-7907-4000-9ffb-cdba8c3ddde4</incoming>
      <outgoing>sequenceFlow_3bf21b37-c534-4541-b84f-03d3fe05c989</outgoing>
      <outgoing>sequenceFlow_6987bcb8-5f6a-467b-9b25-e21b90dd0d4d</outgoing>
    </exclusiveGateway>
    <sequenceFlow id="sequenceFlow_74d95e16-7907-4000-9ffb-cdba8c3ddde4" sourceRef="userTask_7b955191-5741-44df-b7ba-d154ddfbe616" targetRef="exclusiveGateway_5aa645c5-a5e7-4453-8498-8462092b85b1"/>
    <sequenceFlow id="sequenceFlow_3bf21b37-c534-4541-b84f-03d3fe05c989" name="no" sourceRef="exclusiveGateway_5aa645c5-a5e7-4453-8498-8462092b85b1" targetRef="endEvent_68057c88-fa46-43cc-a93c-774b26be7b50">
      <conditionExpression id="conditionExpression_8bb43e50-dd2f-40ba-9cc9-91a69813a835">${!clarified}</conditionExpression>
    </sequenceFlow>
    <endEvent id="endEvent_68057c88-fa46-43cc-a93c-774b26be7b50" name="Invoice not processed">
      <incoming>sequenceFlow_3bf21b37-c534-4541-b84f-03d3fe05c989</incoming>
    </endEvent>
    <sequenceFlow id="sequenceFlow_6987bcb8-5f6a-467b-9b25-e21b90dd0d4d" name="yes" sourceRef="exclusiveGateway_5aa645c5-a5e7-4453-8498-8462092b85b1" targetRef="approveInvoice">
      <conditionExpression id="conditionExpression_c3fb4bcf-905a-47dd-84cf-6cfe1980ca2e">${clarified}</conditionExpression>
    </sequenceFlow>
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_946186ab-976d-40e2-9ed2-4672566340a2">
    <bpmndi:BPMNPlane bpmnElement="process_e14ca74e-6095-4a2b-bced-debcb3b37954" id="BPMNPlane_78d2c2b7-e5e7-414f-abae-0dcddaefbdfd">
      <bpmndi:BPMNShape bpmnElement="startEvent_e8daa33a-af99-4b7a-87ee-200b0e7bedcd" id="BPMNShape_2da46013-859f-418a-8612-25bd57aabb52">
        <dc:Bounds height="36.0" width="36.0" x="100.0" y="100.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="userTask_029f48b9-de24-4292-af49-845e81fdcc4b" id="BPMNShape_79fd4553-cfb0-4740-b4fe-093d1c96474b">
        <dc:Bounds height="80.0" width="100.0" x="186.0" y="78.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_cb28e7e5-ebc0-4f27-b8b2-24403ab87ce3" id="BPMNEdge_77315869-b425-4daf-85b6-6121867d91bc">
        <di:waypoint x="136.0" y="118.0"/>
        <di:waypoint x="186.0" y="118.0"/>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape bpmnElement="approveInvoice" id="BPMNShape_b54e1244-b4fb-4e70-8c0d-4b76eb2798b0">
        <dc:Bounds height="80.0" width="100.0" x="336.0" y="78.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_57a81fcd-fb35-42cd-afca-7c4c7914936d" id="BPMNEdge_dfa41f0e-273b-4d62-b8b8-ef9286b24f7d">
        <di:waypoint x="286.0" y="118.0"/>
        <di:waypoint x="336.0" y="118.0"/>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape bpmnElement="exclusiveGateway_b66a0444-2889-4cae-ac78-c1f65405ba0b" id="BPMNShape_bc1af4c3-ef1f-4c26-a42c-b1c2982bf35c" isMarkerVisible="true">
        <dc:Bounds height="50.0" width="50.0" x="486.0" y="93.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_1fe15a36-427e-4000-8fc7-50b8925ea1e5" id="BPMNEdge_9e81a730-2822-4c70-8061-9bbecf05022d">
        <di:waypoint x="436.0" y="118.0"/>
        <di:waypoint x="486.0" y="118.0"/>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape bpmnElement="userTask_79a63b4f-96a7-43d7-aab3-e8e0e83769e5" id="BPMNShape_8c455164-1097-43ca-814f-6d601735b27a">
        <dc:Bounds height="80.0" width="100.0" x="586.0" y="78.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_9156c1d4-f756-447b-a384-e3bf17c43ff4" id="BPMNEdge_47ba6c2b-fd10-4faf-8ee9-cbe019282080">
        <di:waypoint x="536.0" y="118.0"/>
        <di:waypoint x="586.0" y="118.0"/>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape bpmnElement="serviceTask_9d976f99-f8fb-4705-ae6d-a606758111f4" id="BPMNShape_d2e257f4-4c63-44e6-a8ab-d3179a83682c">
        <dc:Bounds height="80.0" width="100.0" x="736.0" y="78.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_b82e04ab-a0cc-4969-989a-1ec64d74d990" id="BPMNEdge_e5727f31-71a0-4f03-8a9d-7aca2cd9999a">
        <di:waypoint x="686.0" y="118.0"/>
        <di:waypoint x="736.0" y="118.0"/>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape bpmnElement="endEvent_affc9949-819a-4b79-98bd-0f2fd844d014" id="BPMNShape_4a1b2f6f-6929-4fd7-b6cf-9f49410242d7">
        <dc:Bounds height="36.0" width="36.0" x="886.0" y="100.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_f0f99688-25b1-417e-9a5d-0d17503cb3ba" id="BPMNEdge_28346c07-6da9-41d2-bcf2-76a9583ea933">
        <di:waypoint x="836.0" y="118.0"/>
        <di:waypoint x="886.0" y="118.0"/>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape bpmnElement="userTask_7b955191-5741-44df-b7ba-d154ddfbe616" id="BPMNShape_1c62b32d-2c17-48b0-bbc7-ac0074c97e62">
        <dc:Bounds height="80.0" width="100.0" x="586.0" y="208.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_29bab2ba-6108-4731-94c3-93a6955d1946" id="BPMNEdge_40c826c8-638d-4cd2-b9a1-ccdfa9a5ee6e">
        <di:waypoint x="511.0" y="143.0"/>
        <di:waypoint x="511.0" y="248.0"/>
        <di:waypoint x="586.0" y="248.0"/>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape bpmnElement="exclusiveGateway_5aa645c5-a5e7-4453-8498-8462092b85b1" id="BPMNShape_36d66f18-3b46-4fde-9342-3ccd8d0f838d" isMarkerVisible="true">
        <dc:Bounds height="50.0" width="50.0" x="736.0" y="223.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_74d95e16-7907-4000-9ffb-cdba8c3ddde4" id="BPMNEdge_257a94d2-a5f6-4a88-9503-f5b9fd65cc7e">
        <di:waypoint x="686.0" y="248.0"/>
        <di:waypoint x="736.0" y="248.0"/>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape bpmnElement="endEvent_68057c88-fa46-43cc-a93c-774b26be7b50" id="BPMNShape_2dff264a-5f15-44d9-ba38-b962be76ea74">
        <dc:Bounds height="36.0" width="36.0" x="836.0" y="230.0"/>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_3bf21b37-c534-4541-b84f-03d3fe05c989" id="BPMNEdge_0a149725-d17c-4b6f-b7db-7854d0a27b00">
        <di:waypoint x="786.0" y="248.0"/>
        <di:waypoint x="836.0" y="248.0"/>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="sequenceFlow_6987bcb8-5f6a-467b-9b25-e21b90dd0d4d" id="BPMNEdge_8b25f14c-9653-42ab-a57f-48fc07bd7ee8">
        <di:waypoint x="761.0" y="273.0"/>
        <di:waypoint x="761.0" y="118.0"/>
        <di:waypoint x="336.0" y="118.0"/>
      </bpmndi:BPMNEdge>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</definitions>

By comparing it to the above xml, I notice a few new <bpmndi ...> elements not present before.

A: Missing isExecutable parameter in process
// create a process
Process process = modelInstance.newInstance(Process.class);
process.setExecutable(true);


text:
Q: Iterate a block of HTML, regardless of element type, with Nokogiri? I'm trying to iterate a block of HTML with Nokogiri, regardless of what the element type is.
For example, given this variable html, passed through Nokogiri:
require 'nokogiri'

html = "
Some text

List item 1

List item 2

Last bit of text
"

parsed_html = Nokogiri::HTML(html)

I know I can iterate over each
 by doing:
parsed_html.css("p").each do |p|
  puts p
end

But again that only grabs all
 tags and not the
 and its children.
I also know I can grab the
 by doing:
parsed_html.css("p, ol").each do |p|
  puts p
end

But how can I iterate over all the elements regardless of explicitly stating which ones I want to iterate over?
For example, given another html block:
html = "
text 1

item 1

item 2

item 1

header
"

How can I return something like:

text 1

item 1

item 2

item 1

header

Thanks in advance.

A: Use the CSS child selector:
parsed_html.css('body > *')

This selects only direct children of the element(s).
irb(main):015:0> parsed_html = Nokogiri::HTML(html)
irb(main):016:0> parsed_html.css('body > *')
=> [#<Nokogiri::XML::Element:0x3c00 name="p" children=[#<Nokogiri::XML::Text:0x3bec "text 1">]>, #<Nokogiri::XML::Element:0x3c64 name="ol" children=[#<Nokogiri::XML::Element:0x3c28 name="li" children=[#<Nokogiri::XML::Text:0x3c14 "item 1">]>, #<Nokogiri::XML::Element:0x3c50 name="li" children=[#<Nokogiri::XML::Text:0x3c3c "item 2">]>]>, #<Nokogiri::XML::Element:0x3ca0 name="ul" children=[#<Nokogiri::XML::Element:0x3c8c name="li" children=[#<Nokogiri::XML::Text:0x3c78 "item 1">]>]>, #<Nokogiri::XML::Element:0x3cc8 name="h2" children=[#<Nokogiri::XML::Text:0x3cb4 "header">]>]
irb(main):017:0> parsed_html.css('body > *').map {|e| e.name }
=> ["p", "ol", "ul", "h2"]

This works since Nokogiri will create a skeleton when you use Nokogiri::HTML:
irb(main):018:0> parsed_html.to_s
=> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n\n
text 1
\n
\n
item 1
\n
item 2
\n
\n

item 1

\n
header
\n\n"

You can also just use Nokogiri::HTML.fragment instead of HTML():
frag = Nokogiri::HTML.fragment(html)
frag.children.map(&:to_html).join("\n")

A: Just answering the questions you wrote:
how can I iterate over all the elements
CSS accepts wildcards, so you can just:
Nokogiri::HTML(html).css("*").map(&:name)
# => ["html", "body", "p", "ol", "li", "li", "p"]

given "this html" how do I return "something like"
html = "
text 1

item 1

item 2

item 1

header
"

puts Nokogiri::HTML(html).css('body').inner_html
#
text 1

#

#
item 1

#
item 2

#

#

item 1

#
header

I want to be able to iterate over all the first level child elements (p, ol, ul, h2)
Nokogiri::HTML(html).css('body').children.map(&:name)
# => ["p", "ol", "ul", "h2"]


text:
Q: How to list all the folders that have a subfolder with a specific name inside them using CLI Bash I would like to use cli to list all the folders in my Documents directory that have a subfolder called "images" is there any way to list them easily?
Thank you

A: Using GNU find:
find ~/Documents/ -type d -name images -printf '%h\n'

From the -printf section of man find:
          %h     Leading directories of file's name (all but the last ele‐
                 ment).  If the file name contains no slashes (since it is
                 in the current directory) the  %h  specifier  expands  to
                 `.'.


text:
Q: BIBO Stability considerations for Transfer Functions So I was wondering if you have a system, consider it \$G(s)\$ and it has no initial energy i.e. \$x(0) = 0\$ for the initial condition. If the transfer function exhibits: pole cancellation, would it be considered stable. I know this is a common paradox in the discipline ,but with the knowledge of an already "energyless" system that will only respond to a simple input/output relationship. Does this actually affect the stability for controller purposes?

A: If \$G(s)\$ is an arbitrary transfer function it is BIBO stable if and only if it is linearly stable. The proof is simple. Let \$x(t)\$ be a bounded input and put \$x_0\$ as the least-upper-bound of \$x(t)\$. The Laplace transform gives
$$\frac{x_0}{s} > X(s)$$
hence
$$G(s)\frac{x_0}{s} > G(s)X(s)$$
hence
$$\mathscr{L}^{-1} \left\{G(s)\frac{x_0}{s} \right\} > \mathscr{L}^{-1}\{G(s)X(s)\}.$$
But since \$G(s)\$ is stable, \$\frac{G(s)}{s}\$ is also at least quasi-stable (has poles no further than the origin), so \$\mathscr{L}^{-1}\left\{G(s)\frac{x_0}{s} \right\}\$ is also bounded.
Indeed \$\mathscr{L}^{-1} \{G(s)X(s)\} \$ will be a linear combination of terms within a collection of exponentially-decreasing envelopes, so the BIBO-linear stability correspondence is actually quite intuitive.
Pole cancellation can be done while maintaining stability, but it's risky because closed-loop poles move from their open-loop position and modeling / control uncertainties can cause the zeros to move off of the poles. If you use pole-zero cancellation to delete unstable poles the actual positions of the poles and zeros may not quite align, and the response will be unstable. SO NEVER DO THIS!!! The initial energy does not matter, as your inputs will excite modes corresponding to every pole which is not completely cancelled. The recommended approach for unstable poles, as always, is to use feedback to stabilize them.


text:
Q: Can ffmpeg extract the motion vectors from VP9 videos? And if it can, are the motion vectors similar to how they are in H264?
I ask because I can run a command like
ffmpeg -y -loglevel error -flags2 +export_mvs -i "$1" -vf codecview=mv=pf+bf+bb /tmp/mot
    ion_vectors.mp4

then view it with VLC and see the motion vectors superimposed upon the video. If I try this with a VP9 encoded video I'm unable to see them.


text:
Q: Large Scenario Outline tables without having to explicitly mention all parameters in the step definitons In Python's behave library, I can write a feature file with a parametrised Scenario Outline like so (adapted from this tutorial):
# feature file
Feature: Scenario Outline Example

  Scenario Outline: Use Blender with <thing>
    Given I put "<thing>" in a blender
    When I switch the blender on
    Then it should transform into "<other thing>"

    Examples: Amphibians
        | thing         | other thing |
        | Red Tree Frog | mush        |
        | apples        | apple juice |

The according step definitions would look like this:
# steps file
from behave   import given, when, then
from hamcrest import assert_that, equal_to
from blender  import Blender

@given('I put "{thing}" in a blender')
def step_given_put_thing_into_blender(context, thing):
    context.blender = Blender()
    context.blender.add(thing)

@when('I switch the blender on')
def step_when_switch_blender_on(context):
    context.blender.switch_on()

@then('it should transform into "{other_thing}"')
def step_then_should_transform_into(context, other_thing):
    assert_that(context.blender.result, equal_to(other_thing))

As one can see, the way to pass the parameters from the feature file into the step functions is

*

*by explicitly mentioning them in the feature file enclosed in angle brackets

*then include the same words enclosed in curly brackets (why not angle brackets again?!) in the decorator of the step function

*and finally insert these words as function arguments of the step function.

However, given a larger example table with a lot of columns, this quickly gets annoying to write and read:
# feature file
Feature: Large Table Example

  Scenario Outline: Use Blender with a lot of things
    Given I put "<first_thing>", "<second_thing>", "<third_thing>", "<fourth_thing>", "<fifth_thing>", "<sixth_thing>", "<seventh_thing>" in a blender
    When I switch the blender on
    Then it should transform into "<other thing>"

    Examples: Things
        | first thing | second thing | third thing | fourth thing | fifth thing | sixth thing | seventh thing |
        | a     | b             | c  | d           | e            | f           | g           | h             |
        | i     | j             | k  | l           | m            | n           | o           | p             |

# steps file
@given('I put "{first_thing}", "{second_thing}", "{third_thing}", "{fourth_thing}", "{fifth_thing}", "{sixth_thing}", "{seventh_thing}",  in a blender')
def step_given_put_thing_into_blender(context, first_thing, second_thing, third_thing, fourth_thing, fifth_thing, sixth_thing, seventh_thing):
    context.blender = Blender()
    context.blender.add(thing)
...

I think the point is clear. Is there any possibility to transfer the examples from a large table into the step definition without having to mention all of them explicitly? Are they, for instance, saved somewhere in the context variable even without mentioning them in the text (could not find them there yet)?

A: Apart from considering if one really needs to work with large scenario outline tables (see the other answer), it is indeed possible to access the current table row without explicitly mentioning all parameters in the given/when/then step via context.active_outline (which is a bit hidden in the appendix of the documentation).
context.active_outline returns a behave.model.row object which can be accessed in the following ways:

*

*context.active_outline.headings returns a list of the table headers, no matter what the currently iterated row is (first_thing, second_thing etc. in the example from the question )

*context.active_outline.cells returns a list of the cell values for the currently iterated row (a, b, c etc. in the example from the question)

*index-based access like context.active_outline[0] returns the cell value from the first column (no matter the heading) etc.

*named-based access like context.active_outline['first_thing'] returns the cell value for the column with the first_thing header, no matter its index

As context.active_outline.headings and context.active_outline.cells return lists, one can also do useful stuff like for heading, cell in zip(context.active_outline.headings, context.active_outline.cells) to iterate over the heading-value pairs etc.

A: The point is clear.
Ask yourself why you really need all those variables?
Are you trying to do too much in one scenario outline? Is it possible to split your problem in two?
How would a scenario look like if you just implemented one of them, i.e. skipped the outline? Would it be large and cumbersome?
Unfortunately, I don't think your problem is that there are many parameter to mention. Your problem is that you are trying to use too many parameters. From where I sit, it looks like you are trying to do too much. Sorry.


text:
Q: How to silent disabled commands? I want to silent disabled commands in Emacs. Possibly unbind them altogether.
When I slip on a disabled-command binding (e.g. a in Dired) — which I am not allowing because I don't want to use it — I'd like it to fail silently, instead of having me cancel what I didn't intend to do. On a per-command basis would be nice, but I don't mind removing them all.
I'm aware of Enable all disabled commands permanently, but I'm after disabling them permanently. I could unbind them one by one, I guess, but that would mean sourcing what map they're defined in, which I cannot do (apart from being a hassle).

A: The simplest way is
(setq disabled-command-function 'ignore)

Then the disabled keys are ignored, nothing happens when you hit, e.g., C-x n n.

A: Because I was annoyed a couple of times that I hit C-x C-c by mistake, I made a function:
(defun not-anymore ()
"For overwriting wrong keybindings"
  (interactive)
  (message "not anymore")
)

(global-set-key (kbd "C-x C-c") 'not-anymore)

You could just omit the message line, ofcourse.
This allows you to exclude commands as you choose.


text:
Q: Why we take V a non empty set in vector space? In functional analysis why we take V as a non-empty set? And when we say that a vector space V over F.can we say that F is any field?

A:
In functional analysis why we take V as a non-empty set?

Really there's no fundamental reason. It's just that the special case where $V$ is empty would not add anything (it obviously wouldn't be a very interesting case) and it would add special cases to many theorems to deal with this pesky "vector space". It would be not unlike taking 1 as a prime, or deciding that 0 is neither even nor odd. Fundamentally unimportant but it makes many theorems uglier.

A: If $V$ is a vector space, then $V$ is never empty, since $V$ contains at least one element: the "null-vector".
In functional analysis the vector spaces are usually normed spaces or topological vector spaces over the field $F \in \{ \mathbb R, \mathbb C\}$.

A: $F$ can be any field,  yes. However,  it is usually the case that $F $ is either the field of complex numbers or the field real numbers. As the answer of @Fred pointed out,  by definition: a vector space $V $ has to contain the 'null vector'. Therefore,  its nonempty by definition.

A: If $V$ were the empty set, it would not be a vector space, because a vector space is an abelian group, and an abelian group has a neutral element, and the empty set clearly contains no neutral element.
For a vector space, $F$ can be any field. However you asked about functional analysis, not linear algebra, and in functional analysis we want to do limits, therefore we want the field to be topological (so we can define limits). We'd also like to have as many sequences as possible to have limits; the best way to ensure that is if the field is also a complete metric space. This pretty much restricts the field to be either $\mathbb R$ or $\mathbb C$.


text:
Q: Cryogenic Particle Detectors Recently, I started reading about Neutrinos, their types, oscillations and their detection.
Today many experiments are being conducted to detect and measure oscillations of sterile neutrinos and anti-neutrinos such as DUNE, SLAC and others. The common thing in all these experiments is use of liquid argon (cryogenic).
Someone please explain why supercooled substances are used for detection of Neutrinos.

A:
When a neutrino bumps into an argon atom's core, it produces particles that knock loose electrons in the liquid argon. A high voltage draws these electrons to wire planes installed inside each detector module. This results in a distinctive, precise signal that yields important information about the neutrino interaction and allows for a 3D reconstruction of the particles' trajectories.

The denser the target , the higher the probability of interaction and liquid argon is used , but also if you look at the list of neutrino experiments, liquid  Xenon and water etc is are used.


text:
Q: Как сохранить изображение на сервер и вернуть в переменную ссылку на файл? window.onload = function() {
document.getElementById("qq").onclick = function() {
    html2canvas(field).then(function(canvas) {
        var my_screen = canvas.toDataURL('image/jpeg', 0.5)
        console.log(my_screen)
      document.getElementById("vk").addEventListener('click', function(){
        window.open('https://vkontakte.ru/share.php?url='+my_screen+',sharer,status=0,toolbar=0,width=650,height=500')
    })
    });
};

}
Подскажите как на fetch отправить из переменной my_screen код base64 с помощью php сохранить ее и вернуть ссылку на данный файл. Как это сделать на ajax+php знаю, а вот ванильный javascript для меня тяжеловат.