text:
Q: All my Node.js apps crash unpredictably at the same time I've written two simple Node.js apps, each of which run a server on a port (1337 and 1338), and using PM2 (and Keymetrics) to keep them alive, but every few days all three Node.js apps (including PM2) crash simultaneously. I'm fairly new to Node.js and am not sure how to investigate the source of the problem.
DETAILS:
The two servers respond to incoming GET requests. One is to automatically do a GIT fetch/pull in response to a Bitbucket trigger, and the other converts a URL to PDF and sends the PDF back to the browser (using wkhtmltopdf). They both work fine while they're running.
I'm running Node.js v0.12.4.
When the three apps go down, my first indication is from my Uptime (https://github.com/fzaninotto/uptime) instance on OpenShift which emails me to say one of my Node.js servers is down, returning "connect ECONNREFUSED".
A couple of minutes later Keymetrics emails me saying "Agent is offline: Keymetrics Agent seems to be offline".
In other words, ALL my node.js stuff seems to go down at the same time; neither of the two apps nor even PM2 are running. I thought Node spawned a process for each app, so how could they all go down at once?
WHAT I'VE TRIED:
I've tried digging through the ~/.pm2/pm2.log but haven't been able to find anything useful in there. Maybe I just don't know what to look for.
$ pm2 resurrect always brings everything back to life just fine.

A: Please upgrade to latest PM2 version:
$ npm install pm2 -g
$ pm2 update


text:
Q: How to solve Missing CURL extension on nginx server? My site is a wordpress platform, hosted with AWS EC2. I have installed a plugin and it said "You'll need to contact your hosting provider and ask them to enable CURL for PHP.".
I have checked on my server using "service apache2 status" and "service httpd status" and it said "unrecognised service". While "service nginx status" shows "* nginx is running"
Anyone know can I enable CURL for PHP? I only found this step https://www.digitalocean.com/community/questions/curl-is-not-installed-in-your-php-installation but I think that is for Apache.

A: It's not related with apache or nginx. You need to install the php libcurl package
On deb systems you could do it with the following command:
sudo apt-get install php-curl

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ubuntu 20.04 minimal: "Unable to locate package python-pip" Launching some small VMs in GCP and thought I would give Ubuntu 20.04 LTS minimal a try.  After doing an "apt update; apt upgrade" I'm able to install packages like Apache, but having zero luck with PIP:
root@ubuntu-rr58:/home/me# apt install python-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python-pip

I have verified the Universe, Multiverse and Restricted repositories are available:
root@ubuntu-rr58:~# grep ^deb /etc/apt/sources.list
deb http://us-central1.gce.archive.ubuntu.com/ubuntu/ focal main restricted
deb http://us-central1.gce.archive.ubuntu.com/ubuntu/ focal-updates main restricted
deb http://us-central1.gce.archive.ubuntu.com/ubuntu/ focal universe
deb http://us-central1.gce.archive.ubuntu.com/ubuntu/ focal-updates universe
deb http://us-central1.gce.archive.ubuntu.com/ubuntu/ focal multiverse
deb http://us-central1.gce.archive.ubuntu.com/ubuntu/ focal-updates multiverse
deb http://us-central1.gce.archive.ubuntu.com/ubuntu/ focal-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu focal-security main restricted
deb http://security.ubuntu.com/ubuntu focal-security universe
deb http://security.ubuntu.com/ubuntu focal-security multiverse

A: The package is called python3-pip. Python 2.7 is not shipped anymore with Ubuntu 20.04, nearly all python related packages are now called python3-*.

A: To get the Python 2 version of pip back, you can use get-pip, which is a single script that downloads and installs the latest version of pip (for Python 2 or 3, whichever version you run the script with):
$ curl -O https://raw.githubusercontent.com/pypa/get-pip/master/get-pip.py
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 1824k  100 1824k    0     0  2211k      0 --:--:-- --:--:-- --:--:-- 2211k

$ python get-pip.py
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Defaulting to user installation because normal site-packages is not writeable
Collecting pip
  Using cached pip-20.1-py2.py3-none-any.whl (1.5 MB)
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1
    Uninstalling pip-20.1:
      Successfully uninstalled pip-20.1
  WARNING: The scripts pip, pip2 and pip2.7 are installed in '~/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-20.1

Then add ~/.local/bin/ to your PATH (e.g. in your ~/.bashrc):
PATH=$HOME/.local/bin/:$PATH

After that you should have a working pip command for Python 2. Or use pip2 / pip2.7 if you want to make sure you're not targeting Python 3.


text:
Q: Trouble implementing Regex in Python I'm having trouble implementing a regex pattern in python. My expression works in on  https://regexr.com/ but I can't get it to work in python.
Here is my expression: [abcd][(]\d+[)]|(ab)[(]\d+[)]|(abcd)[(]\d+[)]
I want to find and return instances a(\d+), b(\d+), c(\d+), d(\d+), ab(\d+), or abcd(\d+)
expressions = re.findall(r"[abcd][(]\d+[)]|(ab)[(]\d+[)]|(abcd)[(]\d+[)]",line)
print(expressions)

I think it might be working because when I have something in the string that should match the pattern I get [('', '')] as my output instead of []
Any thoughts?

A: I think you misused [(]or [)].
And \(\d+\) part is redundant. So you can optimize it:
import re

line = 'a(123) b(11) ab(35) bc(45) abcd(1234)'

expressions = re.findall(
    r'(?:[abcd]|ab|abcd)\(\d+\)',
    line)
print(expressions)

output:
['a(123)', 'b(11)', 'ab(35)', 'c(45)', 'abcd(1234)']

explanation:

*

*(?:...) is non-capturing group. It is only for grouping not capturing.

*\( and \): \ is escape character for special characters like ( or ). \( matches literal (.

A: expressions = re.findall(r"[abcd](\d+)|(ab)(\d+)|(abcd)(\d+)",line)
print(expressions)

This should work.
problem was: In Python, you don't put ( in brackets.
If you mean the parentheses in (d+) literally, you have to use escaped paranthese \( and \).
Be aware, if you put paranthese around ab or abcd
they will be listed when referencing to groupings.
I would not put parantheses as long as it is not necessary.
expressions = re.findall(r"[abcd]\(\d+\)|ab\(\d+\)|abcd\(\d+\)",line)
print(expressions)

If you want to just match a1236, ab12, abcd12342, then use
expressions = re.findall(r"[abcd]\d+|ab\d+|abcd\d+",line)
print(expressions)

However, if you want to capture certain parts with their repetitions, put parantheses around them.


text: Q: Python Selenium, wait for a javascript to finish Is there any way to get a web element event (javascript) and wait for the script to finish? I'm having a lot of issues with this events because it affects other web elements when I'm filling forms. I don't want to make a staleness_of web element or make an implicitly_wait. I just want to get the event like Selenium gets a webelement and then wait until the script has finished.


text:
Q: How to pass a paramater to run method WITHOUT specifying it in contructor I need to pass a parameter to the run method, but all solutions specify to declare the parameters in in the class constructor.
Is there any other way? What if I created an object via a spring bean, I cant instantiate that object again.

A: Sure, you can set a property on the Runnable after construction.
Just make sure that you have proper synchronization, because this property might be changed after the executing thread is started.
final class MyTask implements Runnable {
  private volatile int parameter;
  void setParameter(int parameter) { this.parameter = parameter; }
  @Override public void run() { System.out.printf("parameter: %d%n", parameter); }
}


text:
Q: Max Value for xorShift128+ (or what's wrong with my implementation) I'm reading up random number generators and tweaked an implementation of the xorShift128+ algorithm in javascript.  I understand how bit shift operators work and how the xor bit operations work, though I'm still learning why they're useful, and why their use in xorShift128+ produces a uniform random distribution.
But more to the point, I just need to know what the range of possible numbers it works with is.  It outputs integers, I'm trying to get numbers between 0 and 1.  Inductively, I see that it's in the order of 2**32.  So I use that as the divisor.  However, when I check for uniformity, I notice a bias in the numbers.  They seem to be repelled in the areas of 0.2 <= val < 0.3 and val >= 0.7.
So I've either got the calibrating divisor wrong, I've got my implementation wrong, or I'm confused about the uniformity property.  Any help would be appreciated.  Below is my code and my analysis:

function xorShift128p(seed) {

    // seeds
    this.x = seed || this.x || 1;
    this.y = seed + 1 || this.y || 2;

    // swap seeds
    let x = this.y;
    let y = this.x;

    // bit manipulations that are still a little
    // obscure to me as to why they work well
    y ^= y << 23;
    y ^= y >> 17;
    y ^= x;
    y ^= x >> 26;

    // reset seeds
    this.x = x;
    this.y = y;

    // output, with calibration for 0-1 range.
    let realResult = x + y;
    let myCalibration = realResult / (2**32);
    return myCalibration;

}

// produce an array of 100 random numbers using xorShift128p
let rands =
    [...new Array(100).keys()]
    .map(() => xorShift128p());

// bin the random numbers into units of 0.1
let binCounts =
    [...new Array(10).keys()]
    .map(key =>
        `lead: ${(key / 10).toFixed(1)}, ` +
        `count: ${rands.filter(r => r >= key / 10 && r < (key + 1) / 10).length}`
    );

// notice the non-uniformity
console.log(binCounts);

A: In xorshift128+, x and y are supposed to be uint64_t. That causes a number of differences between this implementation and the actual xorshift128+:

*

*The right shifts are arithmetic shifts but should have been logical shifts. I don't know how bad that is, but it's definitely different.

*The final addition is supposed be modular, but here it is a (floating point) double precision sum. That's very bad.

*There aren't 128 bits of state. This makes the PRNG less strong but in a way that is non-trivial to detect.

The final sum not being modular makes the result non-uniform and with a different range than the scale factor assumes: the sum of two IID numbers in [-231 .. 231-1] (the result of using Number instead of uint64_t) is in [-232 .. 232-2] and biased towards numbers of smaller magnitude. That's the same kind of effect as the sum of two fair die rolls. This could be worked around by adding >>> 0, but then the code still would not implement xorshift128+.
Fixing the fundamental issue would be a bit painful, requiring the 64bit integer operations to be emulated. There are some libraries that can do that job for you.


text:
Q: svglib - Convert SVG to PNG with a transparent background? I am utilizing svglib and report lab to convert an SVG file to a PNG file.
renderPM.drawToFile(drawing, png_file_path, fmt="PNG", configPIL={'transparent': None})
And it works to convert the file, unfortunately the background of the image is not transparent.
I have tried adding a colour to the transparent attribute of the configPIL and making it transparent that way, but it seems to not affect the background at all.
How can I convert from SVG to PNG with a transparent background using python?


text:
Q: Is JLayer supported by Android I've seen a lot of question about playing .mp3 files using JLayer in Android, a lot of these questions have accepted answers meaning that they succeeded in using JLayer to process .mp3 files.
I downloaded the .jar and imported it into my project. I then implemented the following to test if it is working:
AssetFileDescriptor assetFileDescriptor = getApplication().getAssets().openFd("testing.mp3");
FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();
FileInputStream stream = new FileInputStream(fileDescriptor);
//JLayer below
Player player = new Player(stream);
player.play();

When I run my application I get the following error:
java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/sound/sampled/AudioFormat;

I did some research and found that javax is not supported by android. I had a look through JLayer.jar and found that in JavaSoundAudioDevice.java is the following imports:
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.DataLine.Info;

so, if javax is not supported by android and JLayer uses javax, how does other people get it working? - as shown in this question..


text:
Q: DLL file for Modbus protocol in windows 7 I'm looking for a Modbus dll for Windows 7 with his header file.
I need it to create a driver for communicating with a MultiMeter via
Modbus protocol in ATEasy environment.

A: Hello I know a website that can help you.
I hope I have been helpful. :)
Website click here!


text:
Q: Past of it'd better be I was just watching TV and one of the characters in the show said something like "I don't know what happened there, but it'd've better been good".
Realizing that the deconstruction of that sentence is "it had have better been good" sounds like a tonguestwist, my first impression is that it's incorrect, but if it is, then what construction is actually correct to express the idea of "it would be desirable that it was good"?


text:
Q: continuation from real to complex Let z=x+iy.
I have an equation of the form f(x)=g(x).
Under what conditions, if any, is it true (if it IS true) that f(z)=g(z) for all z?
It looks like analytic continuation, but not quite, since analytic continuation begins with the supposition that f(z)=g(z) over the region y=0, and I'm not sure that that is the same thing.
I vaguely recall a theorem from my long-ago undergraduate days that says something about when it is allowed to replace x by z in the argument of a function, but cannot find it now. Can someone give me a reference?
Thank you.


text:
Q: Sending post data from Joomla to CodeIgniter I have a system implemented in CodeIgniter, I am trying to send some data in a text area of Rsform component via POST to the url referring to my CodeIgniter system, I have tried usign AJAX request to send the post data using the following code
<script>
alert("jsc");
  var data;
  data='test from joomla!';
      $.ajax({
                type: "POST",
                url : 'http://localhost/cii/index.php/login/getNews/',
                data: {news:data},
                cache: false,

                success: function(html){
                alert(html);
                }
            });

getNews controller:
function getNews() {
  //print_r($this->session->userdata);
  header('Access-Control-Allow-Origin: *');
  echo "news is ".$news=$_POST['news'];
  $data = array ( 'username' => "null", 'is_logged_in' => false, 'news'=>$news);
  $this->session->set_userdata($data); //var_dump($_POST); //
  print_r($this->session->userdata); session_start(); echo session_id();
}

but it failed, is there any other options ?

A: Use something like Firebug in mozilla firefox to observe what data is being posted to the app to check if your ajax call is working.
Then in your codeigniter controller method, simply put this code to see if the data is getting to it.
function getNews()
{
    foreach($_POST as $key => $val)
    {
        $options[$key] = $this->input->post($key);
    }

    var_dump($options);
}


text:
Q: Moved app from Paid to Free (with IAB) resulted in massive ranking drop Yesterday I moved my app which was quite highly ranked from a Paid to a Free app (with in app billing). The app instantly dropped to literal obscurity the second I did it. It was almost as if my ranking value in the database had been reset!
Has anyone experienced this? Will the app recover in the next few days once the rankings get calculated again?
Thanks!


text:
Q: Does this operator exist already? Is there any pre-established operator or function that is zero if any of its operands is zero, otherwise negative if any of its operands is negative, otherwise positive?
The sign is the most important thing here; the magnitude (in the non-zero case) could be anything from the largest absolute value to the product or sum of the absolute values of the operands.
I'm tempted to define such an operator in my work (neural network modelling), but I'd first like to be sure that none already exist.
If there is none, would it be common practice to pick an operator (eg. $\otimes$ or $\star$) and redefine it, or should I stick to function notation?

A: You could define it as:
$$\left|x_1x_2\cdots x_n\right|\min(x_1,x_2,\dots,x_n)$$
If any are zero, it is zero. Otherwise, it is the same sign as the minimum of the $x_i$, so negative if any $x_i<0$ and positive otherwise.
This has the advantage that it is a continuous function.
I have never heard of such an operator with a name.
For a binary operator, you can write it as:
$$a\star b = \min(a^3b^2,a^2b^3)$$
I wouldn't re-use most operator symbols that are well-known, but you can use $\star$ or $\odot$ or plenty of others that have few common meanings. I'd prefer function notation, personally.
As noted in comments, in response to a question I asked in an earlier version of this comment, $$a\star b = \left|ab\right|\min(\mathrm{sgn}(a),\mathrm{sgn}(b))$$ is a continuous, commutative and associative operation of this sort.


text:
Q: Google Chrome: how to find original line from minified line using a source map? I'm using the Closure Compiler to minify my JS code, and it also generates a source map file. I can open my site in Chrome and load the source map to see the original source code. I can set a breakpoint in the original source code and step through the code, so far so good.
How do I see what a specific line/column of the minified code maps to in the original code, and vice versa, without using breakpoints?
Let's say I get a bug report "Cannot set property 'b' of null, line 512, column 315". I can find the section in the minified code, it is "Ba.b=!0;" How can I use Chrome to find out where in my original source code that is from?

A: cant you reproduce the error with either sourcemap files or running the unminified file?


text:
Q: What are the differences between Custom Elements v0 and v1? What are the differences between Custom Elements v0 and v1?
See caniuse.com before using v1 or even v0.

A: v1 replaces v0 which was an experimental try.
v0 was a Google-only proposed specification while v1 is a WHATWG Web Standard adopted by all major browser vendors (implemented in Chrome, Opera, Firefox, Edge and partially in Safari).
More details on some Internet publications:

*

*All about HTML Custom Elements (v0 and v1).

*What's New in Custom Elements (from one of the author).
If you're new at Custom Elements, forget v0.


text:
Q: Using MD5 engine in POCO libraries to hash binary array New to Poco libraries.
I want to calculate a MD5 value on a binary array.  I first wrote in hex decimal format, then convert to a binary string.  Then I call MD5 engine.  Why my code does not work?
 std::istringstream message1 ("0162010d00000000000000000000000000000000000103030303030303030303030301a0c000033131394040767a7733672e636f6d2c06313030300506000056cc2806000000011a0c00003297c806000000001f11300003297cf12303030303030303030303030303030301a0c00003297cb06000000011a0e000028af08083331313237301a0a000028af17040a001a15000028af160f821301845802130184015ae401");

 Poco::HexBinaryDecoder message2 (message1);
 std::string message3;
 message2 >> message3;

 MD5Engine engine;
 engine.update (message3.data(), message1.str().length() / 2);
 cout << "\n digest1: " << DigestEngine::digestToHex(engine.digest());

Thanks for help!.
DD


text:
Q: React-Redux Connected Component testing correct action has been dispatch on click event I'm a newbie to testing react-redux components with jest and enzyme, and so far i've be finding this a challenge.
I have a login page, and i want to test that the correct error action is dispatch if login fails after the login button is clicked.
So this is how  I'm testing my connected component,
require('../jsDomSetup');
import React from 'react';
import { Provider } from 'react-redux';
import loginDefault, {Login}  from '../../app/routes/Login/LoginContainer';
import {mount, shallow} from 'enzyme';
import loginActions from '../../app/redux/actions/loginActions';
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';
import nock from 'nock';

describe("login container component", function(){

 afterEach(() => {
   nock.cleanAll();
 });

test("loginFailure action is called when login failed due to no crendetials", () =>{
  nock('http://192.168.0.2:3000')
  .get('/graphql?prettify=true')
  .replyWithError('login failed');

    // Error message: Incorrect username and password please try again
    const mockStore = configureMockStore([thunk]);
    const store = mockStore();
    const output = mount(<Provider store={store}><loginDefault></loginDefault></Provider>)
    let loginButton = output.ref('loginButton');
    expect(store.getActions().length).toBe(0);
    loginButton.simulate('click');
    expect(store.getActions().length).toBe(1);
});

At the moment when i run this test, it's failing when trying to simulate the click it can't find the button element. However this ref exists, and when I try a simple search like a button it's still can't find any Button. So i assume the mount is returning some silent error or something.
I just want to check that the correct action is called when login fails.
How do i make this test pass?

A: You are almost there, this works for me.
e.g.

test("loginFailure action is called when login failed due to no crendetials", () =>{
    nock('http://192.168.0.2:3000')
   .get('/graphql?prettify=true')
 .replyWithError('login failed');

    // Error message: Incorrect username and password please try again
    const mockStore = configureMockStore([thunk]);
    const store = mockStore();

    const withProvider = (
            <Provider store={store}>
                <loginDefault />
            </Provider>
        );

    const wrapper = mount(withProvider);
    let loginButton = wrapper.find('button'); //here you can use other selector like #myButton or .btn, but be sure it can find it.
    loginButton.simulate('click');

    const unsubscribe = store.subscribe(() => {
                    const actions = store.getActions();
      //here your expectation after the action is raised
                    expect(actions.length).to.have.length.above(0);
                });

    expect(store.getActions().length).toBe(0);

});

Hope this help.


text:
Q: create multiple views with a mysql stored procedure I wanted to build around 900 views(1 view for 1 table and based on 2 conditions) and i have all the table names in a table in mysql environment. I have created a stored proc . For test purpose i used limit 1.
I get below error when i call the sp.
Actually I re-wrote a mssql sp, did i miss anything here. please help

CALL ca_uim.sp_viewcreation_ontime()  Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1    0.000 sec

    USE `ca_uim`;
DROP procedure IF EXISTS `sp_viewcreation_ontime`;

DELIMITER $$
USE `ca_uim`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_viewcreation_ontime`()
BEGIN
DECLARE qos varchar(255);
DECLARE pos int;
DECLARE r_table varchar(255);
DECLARE view varchar(255);
DECLARE cview varchar(2048);
DECLARE done int default 0;

DECLARE qos_cursor CURSOR FOR SELECT DISTINCT qos,r_table FROM S_QOS_DATA ORDER BY 2 limit 1;
DECLARE continue handler for not found set done = 1;

OPEN qos_cursor;

-- Perform the first fetch.
FETCH qos_cursor INTO qos, r_table;

-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE not done
DO

                -- Check QOS name for '-' character & replace with '_' if exist
                SET pos = LOCATE('-',qos, 1);
                IF pos != 0
                THEN
                                SET qos = INSERT(qos, pos, 1, '_');
                END IF;

                -- Check QOS name for '/' character & replace with '_' if exist
                SET pos = LOCATE('/',qos, 1);
                IF pos != 0
                THEN
                                SET qos = INSERT(qos, pos, 1, '_');
                END IF;

                -- Check QOS name for '(' character & replace with '_' if exist
                SET pos = LOCATE('(',qos, 1);
                IF pos != 0
                THEN
                                SET qos = INSERT(qos, pos, 1, '_');
                END IF;

                -- Check QOS name for ')' character & replace with '_' if exist
                SET pos = LOCATE(')',qos, 1);
                IF pos != 0
                THEN
                                SET qos = INSERT(qos, pos, 1, '_');
                END IF;

                -- Create view
                SET view = CONCAT('V_',qos);
                SET cview = CONCAT('CREATE VIEW ',view,' AS ',
                                'SELECT Q.source,Q.target,Q.origin,Q.robot,Q.probe,D.sampletime,D.samplevalue,D.samplestdev,D.samplerate,D.tz_offset ',
                                'FROM S_QOS_DATA Q JOIN ',r_table,' D ON Q.table_id=D.table_id');

                BEGIN
                                -- Suppress Error message for Views that don't exist
                                DECLARE CONTINUE HANDLER FOR 1051
                                set @stmt_str =  CONCAT('DROP VIEW ',view);
                                prepare stmt from @stmt_str;
                                execute stmt;
                                deallocate prepare stmt;
                END;

                BEGIN
                                -- Create the View, Catch tables that don't have samplestdev & samplerate fields
                                DECLARE CONTINUE HANDLER FOR 1054
                                set @stmt_str =  cview;
                                prepare stmt from @stmt_str;
                                execute stmt;
                                deallocate prepare stmt;
                                /* PRINT CONCAT('Created View: ' , view) */
                END;
                BEGIN
                                DECLARE CONTINUE HANDLER FOR 1054
                                SET cview = CONCAT('CREATE VIEW ',view,' AS ',
                                'SELECT Q.source,Q.target,Q.origin,Q.robot,Q.probe,D.sampletime,D.samplevalue,D.tz_offset ',
                                'FROM S_QOS_DATA Q JOIN ',r_table,' D ON Q.table_id=D.table_id');
                                set @stmt_str =  cview;
                                prepare stmt from @stmt_str;
                                execute stmt;
                                deallocate prepare stmt;
                                /* PRINT CONCAT('Created View: ' , view) */
                END;

                -- PRINT 'qos: ' + @qos + ' ' +  @r_table+' '+@view
                -- PRINT @cview
                -- This is executed as long as the previous fetch succeeds.
                FETCH qos_cursor INTO qos, r_table;

END WHILE;

CLOSE qos_cursor;
END$$

DELIMITER ;

Thanks


text:
Q: What is controlling the desktop display? I have two Ubuntu systems and in the course of changing configurations something has become muddled.
I have disabled Unity in favor of gnome shell, the older style display of the desktop. Then I installed xfce 4. Seemed everything would be working okay, and for the most part it does.
Except I noticed that on one system there's something else controlling settings.
On one, if I right click the desktop, I get the menu with the options:
open in new window
create launcher...
create url link...
create folder...
create from template ->
open terminal here
paste
desktop settings...
properties...
applications ->

On system two, right clicking brings up the menu:
Create new folder
Create new document ->
organize desktop by name
keep aligned
paste
Change Desktop Background

Additionally, even though I set the background with the xfce settings manager, on system two that background will appear for a few seconds before it's replaced by something that looks like a background from Ubuntu's original desktop. And it's being controlled by what comes up with the "change desktop background" when right clicking, which isn't the xfce settings manager.
On the first system, that right click does bring up the xfce settings tool.
In short, something is controlling/overriding the xfce settings on machine two, but I can't find what file or configuration tool is doing it. How can I get system two to behave as system one, giving control of settings and configuration of X to XFCE's tools?

A: XFCE uses more Gnome settings than we'd like to believe. Delete the following directories in your /home/bart directory:
.config
.gnome2
.cache

Log out and log back in. Your XFCE desktop should be set to post-install defaults.


text:
Q: Как избавиться от ложных срабатываний антивируса на крайне простую программу Python? У меня есть код на Python. Все что он делает, это принимает в виде аргумента консоли ссылку, а затем скачивает содержащийся там файл.
Код:
import urllib.request
import sys

if len(sys.argv) > 1:
    try:
        urllib.request.urlretrieve(sys.argv[1], 'File.exe')
        print('\nФайл загружен')
    except Exception as e:
        print(f'\nНе удалось загрузить файл\n{e}')

Это всего лишь вспомогательный файл для основной программы. Нужен для скачивания обновлений с GitHub.
Суть в том, что после компиляции в .exe, на VirusTotal он получает 33 срабатывания.
Ссылка на страницу проверки на VirusTotal
Как с этим вообще бороться?

Я прибегал к использованию Cython, чтобы затем скомпилировать уже C-Код, но с этим возникает куча проблем (при конвертации кода в C, постоянно возникают какие-то ошибки). Капаться в других языках ради написания такой простой проги тоже не сильно хочется. Что можно сделать?

A: Для данного скрипта проблема решилась по предложению из комментариев - скачал embedded python и просто запускаю код через него.
Для более крупных программ, исходный код которых раскрывать не хочется, самое простое решение - написать во все антивирусы с просьбой перепроверить программу и добавить ее в список исключений.
Также помогло добавление SSL-сертификата, но это платно.
В совокупности, эти 2 решения снизили у полноценной Python-программы кол-во антивирусов с 31 до 4.


text:
Q: Two uiwebview but only one works I am trying to implement 2 Web views using the storyboard, both linked to another online webpage.
For some reason I don't get any errors, but only the PricesViewController works.
The other VC generates a white page......
I am using these 4 files:
PricesViewcontroller.h
#import <UIKit/UIKit.h>

 @interface PricesViewController : UIViewController

 {
     IBOutlet UIWebView *WebView; }

 @property (nonatomic, retain) UIWebView *WebView;

 @end

PricesViewController.m
 #import "PricesViewController.h"

 @interface PricesViewController ()

 @end

 @implementation PricesViewController @synthesize WebView;

 - (void)viewDidLoad {
    [WebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.sparein.be/full_pricelist.pdf"]]];
      [super viewDidLoad];

 }

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     if (self) {
         // Custom initialization
     }
     return self; }

 - (void)didReceiveMemoryWarning {
     [super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated. }

 @end

ReservationsViewController.h
#import <UIKit/UIKit.h>

 @interface ReservationsViewController : UIViewController

 {
     IBOutlet UIWebView *WebView2; }

 @property (nonatomic, retain) UIWebView *WebView2;

 @end

ReservationsViewController.m
#import "ReservationsViewController.h"

 @interface ReservationsViewController ()
   @end

 @implementation ReservationsViewController @synthesize WebView2;

 - (void)viewDidLoad {
     [WebView2 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.be"]]];

     [super viewDidLoad];
     }

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     if (self) {
         // Custom initialization
     }
     return self; }

 - (void)didReceiveMemoryWarning {
     [super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated. }

 @end

A: This may not fix your problem, but try this. Change your PricesViewController.h and ReservationsViewController.h similarly. Also, what version of Xcode are you using, and what version of iOS are you targeting? You shouldn't need @synthesize in your .m if you're using a recent version of Xcode and iOS.
@interface PricesViewController : UIViewController

@property (nonatomic, weak) IBOutlet UIWebView *WebView;

@end

IBOutlets should not be retained, as this can cause retain cycles. May not be the cause, but good programming practice anyway.


text:
Q: Skip unittest test without decorator syntax I have a suite of tests that I have loaded using TestLoader's (from the unittest module) loadTestsFromModule() method, i.e.,
suite = loader.loadTestsFromModule(module)

This gives me a perfectly ample list of tests that works fine. My problem is that the test harness I'm working with sometimes needs to skip certain tests based on various criteria. What I want to do is something like this:
for test in suite:
    mark the test as 'to-skip' if it meets certain criteria

Note that I can't just remove the test from the list of tests because I want the unittest test runner to actually skip the tests, add them to the skipped count, and all of that jazz.
The unittest documentation suggests using decorators around the test methods or classes. Since I'm loading these tests from a module and determining to skip based on criteria not contained within the tests themselves, I can't really use decorators. Is there a way I can iterate over each individual test and some how mark it as a "to-skip" test without having to directly access the test class or methods within the class?

A: This is a bit of a hack, but because you only need to raise unittest.SkipTest you can walk through your suite and modify each test to raise it for you instead of running the actual test code:
import unittest
from unittest import SkipTest

class MyTestCase(unittest.TestCase):
    def test_this_should_skip(self):
        pass

    def test_this_should_get_skipped_too(self):
        pass

def _skip_test(reason):
    raise SkipTest(reason)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase)
    for test in suite:
        skipped_test_method = lambda: _skip_test("reason")
        setattr(test, test._testMethodName, skipped_test_method)
    unittest.TextTestRunner(verbosity=2).run(suite)

When I run this, this is the output I get:
test_this_should_get_skipped_too (__main__.MyTestCase) ... skipped 'reason'
test_this_should_skip (__main__.MyTestCase) ... skipped 'reason'

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK (skipped=2)

A: Google brought me here.
I found the easiest way to do this is by raising a SkipTest exception when your skip criteria is met.
from unittest.case import SkipTest

def test_this_foo(self):
    if <skip conditsion>:
        raise SkipTest

And that test will be marked as skipped.

A: Using unittest.TestCase.skipTest:
import unittest

class TestFoo(unittest.TestCase):
    def setUp(self): print('setup')
    def tearDown(self): print('teardown')
    def test_spam(self): pass
    def test_egg(self): pass
    def test_ham(self): pass

if __name__ == '__main__':
    import sys
    loader = unittest.loader.defaultTestLoader
    runner = unittest.TextTestRunner(verbosity=2)
    suite = loader.loadTestsFromModule(sys.modules['__main__'])
    for ts in suite:
        for t in ts:
            if t.id().endswith('am'): # To skip `test_spam` and `test_ham`
                setattr(t, 'setUp', lambda: t.skipTest('criteria'))
    runner.run(suite)

prints
test_egg (__main__.TestFoo) ... setup
teardown
ok
test_ham (__main__.TestFoo) ... skipped 'criteria'
test_spam (__main__.TestFoo) ... skipped 'criteria'

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK (skipped=2)

----------------------------------------------------------------------
Ran 3 tests in 0.002s

OK (skipped=2)

UPDATE
Updated the code to patch setUp instead of test method. Otherwise, setUp/tearDown methods will be executed for test to be skipped.
NOTE
unittest.TestCase.skipTest (Test skipping) was introduced in Python 2.7, 3.1. So this method only work in Python 2.7+, 3.1+.

A: Some observations:

*

*A test is a callable object with a __call__(result) method

*TestCase provides a higher-level interface, allowing test methods to throw a SkipTest exception to skip themselves

*The skip decorators do exactly this

*Skipped tests are recorded calling the TestResult.addSkip(test, reason) method.

So you just need to replace the to-be-skipped tests with a custom test that calls addSkip:
class Skipper(object):
    def __init__(self, test, reason):
        self.test = test
        self.reason = reason

    def __call__(self, result):
        result.addSkip(self.test, self.reason)


text:
Q: iPhone Safari full size & PC versions different This site displays the correct logo at top left of the content in Chrome, but displays the incorrect logo in Safari on an iPhone, at full size browsing.  The incorrect logo says "Dandelion".  The correct logo says "Incredible Concepts".
The incorrect logo belongs to the Wordpress theme's parent theme.  The child theme is activated.
If Safari is viewing at full size desktop version, it should show the same content as Chrome on a PC, and this content is produced by the Wordpress child theme.
If the theme had reverted to the parent theme, the header would be totally different.  Why is the logo the only incorrect item?

A: as user15... sugested you may have a mobile specific CSS in your child or parent theme - that is conflicting with the logo, have you tried loading the site from the desktop pc with cross browser plat form site ? http://www.onbile.com/info/tools-for-testing-how-your-site-looks-on-mobile-devices/ and http://www.fingermarketing.com/comparemysite.php tools the let you see how your website looks in mobile ? and please try loading the site in desktop safar browser - www.apple.com/safari/ download it on your pc and try running the site in safari browser. might help you detect problem -
The second thing is apple safari blocks many javascript's that are safe - but it blocks them it has some unsual behavior to handle java - make sure you are not showing your logo enclosing  it with java -
if you define in more details with code and css it will be much better to assist you.


text:
Q: ACM template: Where should I put \acmprice{} to avoid "undefined control sequence"? The editor told me to put \acmPrice{} right after \isbn{}, but I got an "undefined control sequence" error and a "missing \begin{document}" error.

A: The acmart class defines \acmPrice and uses it to initialise things as
\acmPrice{15}

Note you have \acmprice with a small p in the question.
acmconf class does not define this command.


text:
Q: Local deformation ring of representations with equal generalized Hodge-Tate weights Let $K$ be a finite extension of $\mathbb{Q}_p$, and let $\overline{\rho}:\mathrm{Gal}(\overline{K}/K)\rightarrow \mathrm{GL}_2(\mathbb{F})$ be a characteristic $p$ representation. According to a theorem of Kisin, if $a \neq b$ are integers, there exists a $p$-torsionfree universal (framed) deformation ring $R_\overline{\rho}^{a,b}$, parametrizing lifts whose generic fiber is crystalline of Hodge-Tate weights $a$ and $b$. This can be carried out more generally for potentially semistable representations, but one needs to fix an inertial type for this to work.
Does there exist a $p$-torsionfree universal (framed) deformation ring $R_\overline{\rho}^{a,a}$ parametrizing those lifts whose generic fiber has generalized Hodge-Tate weights equal to the multiset $\{a,a\}$? What if we impose some extra (but not too restrictive) conditions? What about the case $K=\mathbb{Q}_p$?
A rigid analytic space parametrizing this condition certainly exists, but I am asking if the stronger condition that the Hodge-Tate weights are both equal to some number can be cut out inside the universal deformation space by some integral algebraic equation.
Thanks!


text: Q: Configure Freeradius To Only Authenticate Members Of Specific FreeIPA LDAP Groups I'm having trouble configuring Freeradius to only allow authentication from specific groups LDAP groups in FreeIPA. Currently, Freeradius is able to authenticate any LDAP users as long as the correct credentials are provided.Any help will be appreciated.


text:
Q: No lauch activity found i have a problem with my Android Application. The Error occures when i want to run my Application on the emulator or a real device:
[2012-03-27 12:01:30 - CallApp] Android Launch!
[2012-03-27 12:01:30 - CallApp] adb is running normally.
[2012-03-27 12:01:30 - CallApp] No Launcher activity found!
[2012-03-27 12:01:30 - CallApp] The launch will only sync the application package on the device!
[2012-03-27 12:01:30 - CallApp] Performing sync
[2012-03-27 12:01:30 - CallApp] Automatic Target Mode: Several compatible targets. Please select a target device.
[2012-03-27 12:01:32 - CallApp] Uploading CallApp.apk onto device 'emulator-5554'
[2012-03-27 12:01:33 - CallApp] Installing CallApp.apk...
[2012-03-27 12:01:36 - CallApp] Success!
[2012-03-27 12:01:36 - CallApp] \CallApp\bin\CallApp.apk installed on device
[2012-03-27 12:01:36 - CallApp] Done!

I already checked my Manifest-File, but there are the necessary Launcher and MAIN statements:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.CallApp.CallApp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BATTERY_STATS" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <receiver android:name=".receiver.BootBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <receiver android:name=".receiver.SmsBroadcastReceiver" >
            <intent-filter android:priority="99999999" >
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

        <activity
            android:name="de.CallApp.CallApp.CallAppActivity"
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/app_name" >
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER" />

                <action android:name="android.intent.action.MAIN" />

                <action android:name="android.intent.action.ACTION_BATTERY_LOW" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </activity>
    </application>

</manifest>

A: You should split the actions to multiple intent-filters.
Like:
        <intent-filter>
            <category android:name="android.intent.category.LAUNCHER" />
            <action android:name="android.intent.action.MAIN" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.ACTION_BATTERY_LOW" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        </intent-filter>

Else it wont be recognized

A: Set the intent filters for your activity de.CallApp.CallApp.CallAppActivity as below:
  <intent-filter>
     <action android:name="android.intent.action.MAIN" />
     <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>

  <intent-filter>
     <action android:name="android.intent.action.ACTION_BATTERY_LOW" />
  </intent-filter>

  <intent-filter>
     <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
  </intent-filter>


text:
Q: background-image no-repeat position: right not appearing. Image reference OK. What gives? I have a really noob question but since I can't get it to work I need to ask anyway. This exact same code works on my other site. So why isn't this code displaying the separator to the right of the header?
http://jsfiddle.net/jay_t55/2g13bfz2/1/

Assessment Site

Welcome...

header
{
    width: 100%;
    height: 100%;

    padding-top: 30%;

    border-image: url("http://i.imgur.com/2jE2sDU.png");
    background-repeat: no-repeat;
    background-position: right;
}

header > h1, h2
{
    font-size: 22pt;
    color: #131313;

    margin-left: 25%;
}

A: Your code says 'border-image', change that to 'background-image'.
The background-position entry should have two arguments in it as well. Horizontal and vertical. I've added center as the vertical.
header
{
    width: 100%;
    height: 100%;
    padding-top: 30%;
    background-image: url("http://i.imgur.com/2jE2sDU.png");
    background-repeat: no-repeat;
    background-position: right center;
}


text:
Q: LyX and Nomenclatures I'm using LyX and trying to use the nomenclature package to insert a bunch of acronyms into my document.
I've inserted a Nomenclature table (Insert -> List/TOC -> Nomenclature).
I've then created a Nomenclature entry (Insert -> Nomenclature entry), and I can insert one fine.
And I've also just figured out how to insert another one - you just delete the old text and enter in new details. It's not the most intuitive, and I would have thought LyX could supply you with a list of previously used acronyms to reinsert, but ah well.
However, how do I get the actual acronyms to print the text? As it is, I have to type in both the text I want displayed, and the acronym entry. I'm fairly certain there's an easier way, but I'm not sure if I can do it within LyX or I have to use LaTeX directly?

A: This has nothing to do with LyX in the first place, it is just nomencl's standard behaviour. The \nomenclature command just stores the entry for the list, but it does not print any text. However, you can redefine the \nomenclature command in order to print the text as well. You could, for instance, put the following in the preamble of your document:
\let\nomenclOrig\nomenclature
\renewcommand*{\nomenclature}[3][]{#2\nomenclOrig[#1]{#2}{#3}}

The first line stores the \nomenclature command in \nomenclOrig. This is necessary, since we have to redefince the \nomenclature command. This is done in the second line. Since the \nomenclature command has two mandatory arguments and one optional argument, we have to specify 3 arguments (the [3] bit). The optional argument has no standard value (the [] bit). Then we print the second argument (which is the first mandatory argument, since the optional argument is always #1) as normal text and use the original command that we have stored in \nomenclOrig.
I tried this with LyX, without problems. Note, though, that the two lines will give an error in a document without a nomenclature entry or list, because then LyX will not load the nomencl package and thus the \renewcommand will throw an error.


text:
Q: C#.net WinForms how to causes text in textbox to disappear when textbox is on focus? is there a way in which i could create light grey text that disappears when a textbox is on focus?
Currently, i have text written in the textbox but i have to select the text and manually delete it (somewhat annoying...)
I know i can do something when i get focus on the box (using events) however, i don't want it to clear the text every time the user selects that box... rather just the first time. In other words, i just want the hint text to disappear (not the text they enter if they were to select the box after typing in it once)...
I also realize i could use something like a counter to keep track of if it's the first time that box is being clicked on.. however, i was looking for a cleaner way to do this.....

A: Something like the code below.
Please note, this is not a compiled code. Just sharing the idea, plus you may like to retain the default settings if user did not enter any text. For that handle a lost focus  and reset to default.
   public class FancyTextBox : TextBox{

private bool _isDefaultText;
public FancyTextBox(){
     UpdateDefaultSettings(true);
}

protected override void OnGotFocus(EventArgs e)
{
    base.OnGotFocus(e);
    UpdateDefaultSettings(false);
}

protected override void OnLostFocus(EventArgs e)
{
    base.OnLostFocus(e);
    if (String.IsNullOrEmpty(Text))
    {
        //Retain Default Setting.
        UpdateDefaultSettings(true);
    }
}

private void UpdateDefaultSettings(bool isDefault){
    _isDefaultText = isDefault;
    if(_isDefaultText){
       Text = "Please enter";
       this.ForeColor= Color.Gray;
    }
    else{
       Text = "";
       ForeColor = Color.Black;
    }
}

}

A: A simpler answer is
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);

public static void SetHint(TextBox textBox, string hintText)
{
 const uint EmSetCueBanner = 0x1501;
 SendMessage(textBox.Handle, EmSetCueBanner, 0, hintText);
}


text:
Q: fopen matlab code in Python I have the following code written in Matlab:
>>> fid = fopen('filename.bin', 'r', 'b')
>>> %separated r and b
>>> dim = fread(dim, 2, 'uint32');

if I use a "equivalent" code in Python
>>> fid = open('filename.bin', 'rb')
>>> dim = np.fromfile(fid, dtype=np.uint32)

I got a different value of dim when I use Python.
Someone knows how to open this file with permission like Matlab ('r' and 'b' separated) in Python?
Thanks in advance,
Rhenan

A: From Matlab docs I learn that your third parameter 'b' stands for Big-Endian ordering, is not a permission.
Most probably Numpy uses the little-endian order on your machine. To fix the problem try to specify explicitly the ordering in Numpy (as you do in Matlab):
>>> fid = open('filename.bin', 'rb')
>>> dim = np.fromfile(fid, dtype='>u4')

the dtype string stands for Big-Endian ('>'), unsigned integer ('u'), 4-bytes number.
See also Data type objects (dtype) in Numpy reference.


text:
Q: Split up the total of a value when merging dataframes with rows that contain id multiple times I have two dataframes that I would like to merge. The first dataframe contains a customer id and a column with a value. The second dataframe contains the customer id and a purchase id. When merging i would like to split up the total value in the first dataframe based on how many times the customer id is present in the second dataframe and attribute every row the correct split of the total value.
Example: Customer with id 1 has a total value of 3000 but has bought products two times in its lifetime the value 3000 should then be split when merging so that each row gets 1500.
First dataframe:
import pandas as pd

df_first = pd.DataFrame({'customer_id': [1,2,3,4,5], 'value': [3000,4000,5000,6000,7000]})

df_first.head()

    Out[1]:
customer_id value
0   1   3000
1   2   4000
2   3   5000
3   4   6000
4   5   7000

Second dataframe:
df_second = pd.DataFrame({'customer_id': [1,2,3,4,5,1,2,3,4,5], 'purchase_id': [11,12,13,14,15,21,22,23,24,25]})

df_second.head(10)

    Out[2]:
customer_id purchase_id
0   1   11
1   2   12
2   3   13
3   4   14
4   5   15
5   1   21
6   2   22
7   3   23
8   4   24
9   5   25

Expected output when merging:
    Out[3]:
customer_id value   purchase_id
0   1   1500    11
1   1   1500    21
2   2   2000    12
3   2   2000    22
4   3   2500    13
5   3   2500    23
6   4   3000    14
7   4   3000    24
8   5   3500    15
9   5   3500    25

A: Use DataFrame.merge with left join and sorted values by customer_id and then divide values by length of groups mapped by Series.map with Series.value_counts :
df = df_second.sort_values('customer_id').merge(df_first, on='customer_id', how='left')
df['value'] /= df['customer_id'].map(df['customer_id'].value_counts())
#alternative
#df['value'] /= df.groupby('customer_id')['customer_id'].transform('size')
print (df)
   customer_id  purchase_id   value
0            1           11  1500.0
1            1           21  1500.0
2            2           12  2000.0
3            2           22  2000.0
4            3           13  2500.0
5            3           23  2500.0
6            4           14  3000.0
7            4           24  3000.0
8            5           15  3500.0
9            5           25  3500.0


text:
Q: define and call a method inside CreateElement I am new to reactjs and still learning, I need to define a method and call that method inside the CreateElement in Reactjs. Not sure if that is possible or i might be doing something in wrong way.
I am trying to test a method that has a if-else condition in it based on that a text should be dispayed thought react.
render: function render() {
    test_method:  function test_method(){  // <= if this should be placed here or
    // outside render, Tried placing it outside render with this.
    // but not reading the value of a
    if (this.a == true){
        return a;
    } else {
        return b;
    },

    React.createElement(
        'li',
        null,
        this.test_method
    );
};

A: First, as a parameter to createElement, when you pass this.test_method, you should instead use this.test_method(). The first, this.test_method will pass in the function itself. The second, with () added, will call the function and pass in what that function returns - ie, your child element.
As for your test_method, there's a few ways you can do it:
1) Define your test_method as a variable inside your render function
render: function render() {
    const test_method = () => {
        if (this.a == true){
            return a;
        } else {
            return b;
        }
    }

    return React.createElement(
        'li',
        null,
        test_method()
    );
};

2) Pull it outside your render, but bind the value of this to your function in your class' constructor. Something like:
constructor: function(props) {
    super(props)
    this.test_method = this.test_method.bind(this)
}

test_method: function() {
    if (this.a == true){
        return a;
    } else {
        return b;
    }
}

render: function render() {
    return React.createElement(
        'li',
        null,
        this.test_method()
    );
};

A: Try this:
export default class My_Class extends React.Component {
    constructor() {
        super();
        this.a = "MY_VALUE";
        this.b = "My other value";
    }

    test_method = () => {
        if (this.a == true){
            return this.a;
        } else {
            return this.b;
        }
    }

    render() {
        return (

this.test_method()

        );
    }
}

Right now I can not prove it but it must go there. In any case the following may be simpler:
export default class My_Class extends React.Component {
    constructor() {
        super();
    }

    test_method(MY_A_VALUE) {
        if (MY_A_VALUE == true){
            return MY_A_VALUE;
        } else {
            return "MY_B_VALUE";
        }
    }

    render() {
        return (

this.test_method(MY_A_VALUE)

        );
    }
}


text:
Q: validation fails when not using an input property/tag I have the following code that contains validation:

    @Html.LabelFor(model => model.subject)
    @Html.TextBoxFor(model => model.subject, new { @class = "AboutControls" })
    @Html.ValidationMessageFor(model => model.subject)

    @Html.LabelFor(model => model.from)
    @Html.TextBoxFor(model => model.from, new { @class = "AboutControls" })
    @Html.ValidationMessageFor(model => model.from)

    @Html.LabelFor(model => model.body)
    @Html.TextAreaFor(model => model.body, new { @class = "AboutControls" })
    @Html.ValidationMessageFor(model => model.body)

This code is executed from JQuery ajax code. Because of this, the validation is not triggered. All the fields are required, but since they are not called through an <input type="submit" value="..." /> the validation is not triggered, and they will go through even when they are null, resulting in an exception. How can I make sure the validation is triggered even when no using an <input ... />?


text:
Q: Increment operators and "undefined behaviour" As mentioned in the comp.lang.c FAQ, the C standard states:

Between the previous and next sequence point an object shall have its
  stored value modified at most once by the evaluation of an expression.
  Furthermore, the prior value shall be accessed only to determine the
  value to be stored.

But, this (now deleted) article says that a = ++b + ++c; is undefined. Could someone please explain why this is undefined behaviour?

A: Provided the objects involved (a, b and c) in the expression a = ++b + ++c; are distinct, that expression is well-defined.
Perhaps, the author meant to use the same variable twice such as a = ++b + ++b;. I can only speculate. But there's no undefinedness in the given expression.


text:
Q: Probability of independent event combinations There are four balls in a box, one blue, one red, one yellow, one green. When a ball is picked out at random, all the balls are put back in the box for the next drawing.
How many balls do you need to take out to have a 50% chance of getting 10 yellow balls or more?
I tried with $\binom{30}{20}\cdot\left(\frac34\right)^{30}$, but it doesn't make sense. I'd like to see the methodology for solving this type of problem too, if possible. Thanks!

A: The probability of drawing at least $10$ yellow balls out of $n$ attempts is:
$$\sum\limits_{k=10}^{n}\binom{n}{k}\cdot\left(\frac14\right)^{k}\cdot\left(1-\frac14\right)^{n-k}$$
You need to find the minimum value of $n$ such that the above is $\geq\frac12$.


text:
Q: Time Reversal of a signal and convolution sum Why do we often time reverse the impulse response of a signal while performing convolution sum?It can be done even without time reversing the impulse response.
By time reversing the impulse response how does it really helps us,what are the advantages of it?

A: Picture an input signal to an LTI system as being composed of an impulse train, where the individual strengths of the impulses are proportional to the instantaneous values of the signal.
The system responds to each impulse as and when it arrives, so the total system response at any instant of time will be the response to the present impulse plus all the remnants of the responses to the impulses that happened in the past.
The convolution sum is an intuitive graphical interpretation of this physical process.
Perhaps it's more intuitively appealing to time reverse ('fold') the input signal rather than the impulse response. This will produce exactly the same mathematical result, but the visualisation is then of the signal sliding through the system as time proceeds.


text:
Q: Sum of the tangents of an infinite number of concentric circles should equal the diameter of the first circle First of all this is the same question as: Determine the ratio $k$ so that the sum of the series $\sum_{i=0}^{\infty} l_{i}$ is equal to the circumference of the outermost circle.
But I am attempting a different method of solving it.
Question:
So imagine that we have an infinite number of concentric circles with the radiuses:
$$r_0, r_1, r_2, ...$$
Where the radiuses is a geometric series with the ratio $k$, $0 < k < 1$. From a point on the outer circle a tangent is drawn to the next closest circle and so on. The length of the tangents can be written as $l_0, l_1, l_2, ... $.
Define the ratio $k$ So that the sum of the series:
$$\sum_{i=0}^{\infty} l_i$$
Is equal to the outer circle circumference. Like this:

My attempt at a solution:
The sum of the geometric series should be $$S_n = \sum_{n=0}^{\infty} l_i = 2 r \pi $$
Since the circles gets smaller with the factor $k$, this could be viewed as a uniform scaling and rotation of the top circle (and tangent) we arrive at the following equality:
$$\sum_{n=0}^{\infty} l_i = l_i \frac{1 - k^n}{1 - k} = l_i \frac{1}{1 - k} = 2 r \pi $$
Without loss of generality we can set the radius to one:
$$l_i \frac{1}{1 - k} = 2 \pi $$
Looking at this picture we can see that: $l_0 = k, l_1 = k^2, ... Etc$

This means that we can write:
$$\sum_{n=0}^{\infty} l_i = k \frac{1 - k^n}{1 - k} = k \frac{1}{1 - k} = 2 \pi $$
This gives us:
$$\frac{k}{1 - k} = 2 \pi \implies k = \frac{2\pi}{2\pi + 1}$$
But this is appearantly wrong. My textbook says the answer should be:
$$k = \frac{4\pi^2 -1}{4\pi^2 + 1}$$

A: Let the first circle have radius $a$ and $r < 1$ be the ratio. Let the circles be $C_0, C_1, \dots,$.
Let's calculate $l_n$, the distance between circle $C_n$ and $C_{n+1}$.
We first draw the segment $l_n$ that is tangent to $C_{n+1}$ and intersects $C_n$. This forms a right angle, so by pythagorean theorem we have
$$l_n^2 = (ar^n)^2 - (ar^{n+1})^2$$
Hence, $l_n = \sqrt{1 - r^2} ar^n$.
Now, we solve the series:
\begin{align}
\sum_{n=0}^{\infty} l_n = \sum_{n=0}^{\infty} \sqrt{1-r^2} ar^n &= 2 \pi a \\
\frac{\sqrt{1 - r^2}}{1 - r} = \sqrt{\frac{1-r}{1+r}}&= 2 \pi \\
\frac{1-r}{1+r} &= 4 \pi ^2 \\
r &= \frac{4 \pi^2 - 1}{4 \pi^2 + 1}
\end{align}
as desired.


text:
Q: How to connect MS Access Database using Java program? I want to write a program to retrieve data from MS Access database. I wrote program as bellow:
package db;

import java.sql.*;

public class MSaccess_archive {
    public static void main(String[] args) {

        try {

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            String accessFileName = "E:/L4_project/sample/db/Database";

            String connURL="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+accessFileName+".accdb;";

            Connection con = DriverManager.getConnection(connURL, "","");

            Statement stmt = con.createStatement();

            stmt.execute("select * from student"); // execute query in table student

            ResultSet rs = stmt.getResultSet(); // get any Result that came from our query

            if (rs != null)
             while ( rs.next() ){

                System.out.println("Name: " + rs.getString("Name") + " ID: "+rs.getString("ID"));
                }

                stmt.close();
                con.close();
            }
            catch (Exception err) {
                System.out.println("ERROR: " + err);
            }
    }

}

But I got Exception as below:

ERROR: java.sql.SQLException: [Microsoft][ODBC Microsoft Access
  Driver] Could not find file '(unknown)'.

When I used a .mdb file the above program works correctly but if I use a .accdb file it gives the above exception.
Any ideas why?

A: You may revisit steps,
Control panel>Administrative Tools>Data Sources>Add>Microsoft Access Drivers(*mdb,*accdb)>ok>ok>ok.
It might work.for ODBC connection.

A: The JDBC-ODBC Bridge has been removed from Java 8 and is not supported (ref: here and here). UCanAccess is a popular alternative. For details, see
Manipulating an Access database from Java without ODBC

A: unless you specifically need to be able to run arbitrary sql queries, you can always give jackcess a try.

A: I think you need to specify jdbc:odbc:my_access_odbc_dsn as the URL, where my_access_odbc_dsn is your DSN name as configured in the ODBC.  In my case, I was accessing an MS Access 2013 database called "PavoDB", so my URL was:
private static final String url="jdbc:odbc:PavoDB";

A: The driver probably hasn't been updated to read that format.  .mdb is the original one for Access; .accdb must have been revised and the ODBC driver hasn't kept up.


text:
Q: How can I access another server with Python? I have two servers, and one updates with a DNSBL of 100k domains every 15 minutes. I want to process these domains through a Python script with information from Safebrowsing, Siteadvisor, and other services. Unfortunately, the server with the DNSBL is rather slow. Is there a way I can transfer the files over from the other server with SSH in Python?

A: If it's just files (and directories) you are transferring, why not just use rsync over ssh (in a bash script perhaps). A proven, mature method.
Or you could mount the remote filesystem (over ssh) into your own filesystem using sshfs (fuse) and then use something like pyrobocopy (implementing a basic version of rsync functionality in Python) to transfer the files.
If you don't need incremental copying, you could go the simple route: mount the remote filesystem using sshfs (link above) and then use shutil.copytree to copy the correct directory.
Or yet another option: implement it using the paramiko Python ssh module.

A: There is a module called pexpect which is pretty nice.
This allows you to ssh, telnet, etc. It also supports ftp which might be handy in transferring files.


text:
Q: Executar arquivo .SAS com DotNet Por gentileza, já precisaram fazer alguma integração SAS, executando o arquivo .sas e retornando o resultado com DotNet, via DataSet, String, etc.?
Se sim, qual objeto ou classe costuma-se a utilizar? Atualmente estou utilizando o SASIOM, fornecido pela própria SAS, mas não encontro nenhum método de execução para arquivos .sas, seja no Workspace, LanguageService ou FileService.
Muito obrigado desde já pela contribuição.

A: Tem um artigo na própria comunidade SAS com um exemplo de utilização de arquivos .sas com .NET.
Segue o link do artigo:
https://communities.sas.com/t5/General-SAS-Programming/How-to-read-SAS-data-set-using-C-NET/td-p/168660
Caso dê algum erro com o link, segue um exemplo de utiização:
DataSet sasDs = new DataSet();
String sasLibrary = @"C\pasta_com_arquivo_sas\";

OleDbConnection connection= new OleDbConnection("Provider=sas.LocalProvider; Data Source=" + sasLibrary);
connection.Open();

OleDbCommand cmd= connection.CreateCommand();
cmd.CommandType = CommandType.TableDirect;
cmd.CommandText = "TableName";

//outra opção seria utilizar cmd.ExecuteReader();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(sasDs);

//sasDs deve conter o DataTable carregado nesse ponto.
//para filtrar os resultados, pode usar DataTable.Select()

connection.Close();


text:
Q: Parse returned C# list in AJAX success function I am using web forms and I have a webmethod in the code behind that my ajax function is calling. It appears that the webmethod is returning data but I am having trouble parsing the returned json string into table rows
Here is my code behind method (Web Method):
public class Part
{
    public string Number { get; set; }
    public string Price { get; set; }
    public string NetAvailable { get; set; }
    public string Location { get; set; }
    public string Distance { get; set; }
    public string Phone { get; set; }
}

[WebMethod]
public static List<Part> GetParts(string partnumber)
{
    List<Part> parts = new List<Part>();

    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NXT"].ToString()))
    {
        con.Open();
        using (SqlCommand command = new SqlCommand("SELECT prod, qtyonhand, whse, listprice FROM icsw where prod LIKE @partnumber", con))
        {
            command.Parameters.AddWithValue("@partnumber", "%" + partnumber + "%");

            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Part part = new Part
                    {
                        Number = reader[0].ToString(),
                        Price = reader[3].ToString(),
                        NetAvailable = reader[1].ToString(),
                        Distance = "0.0",
                        Location = reader[2].ToString(),
                        Phone = GetBranchPhoneNumber(reader[2].ToString())
                    };
                    parts.Add(part);

                }
            }
        }
    }

    return parts;
}

Here is my AJAX call:
$("#searchbtn").click(function() {
    $.ajax({
        url: 'partslocator.aspx/GetParts',
        type: 'POST',
        data: JSON.stringify({ 'partnumber': $("#searchtbx").val()}),
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {

            for (var i in data) {
                alert(JSON.stringify(data[i]));
                $('#searchresultstble').append("
" + data[i].Number + "	" + data[i].Price + "	" + data[i].NetAvailable + "	" + data[i].Location + "	" + data[i].Distance + "	" + data[i].Phone + "
");
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
});

Here is what data is coming back as:
{"d":[{"__type":"partslocator+Part","Number":"0-2809 1025","Price":"2.50000","NetAvailable":"0.00","Location":"82pk","Distance":"0.0","Phone":"test"},{"__type":"partslocator+Part","Number":"0-2809 1025","Price":"2.58000","NetAvailable":"0.00","Location":"Phx","Distance":"0.0","Phone":"test"}]}

Why am I getting undefined for all the rows that are being added?

A: You'll note that the returned data is not actually an array, but an object with a value (d) that contains that array. Try this:
    success: function (returnedData) {
        var data = returnedData.d;
        for (var i in data) {
            alert(JSON.stringify(data[i]));
            $('#searchresultstble').append("
" + data[i].Number + "	" + data[i].Price + "	" + data[i].NetAvailable + "	" + data[i].Location + "	" + data[i].Distance + "	" + data[i].Phone + "
");
        }
    },


text:
Q: Using Recyclerview and Cardview WITHOUT Gradle I am using IntelliJ and have a large number of apps that do not use Gradle.
I would like to start using the RecycleView and Cardview.
What is the best way to add these? I have added in the two modules in a similar way to AppCompat.
However, when I try to run the code and show the RecycleView, I get this error...
android.view.InflateException: Binary XML file line #8: Error inflating class RecyclerView

Any help greatly appreciated.

A: Since you wanted it to wotk without adding them in gradle dependency
navigate to your sdk location from that sdk folder-->extras-->android-->support-->v7
under this you will find recyclerview and cardview folders add them as library pojects respectively and you can proceed normally. THis can be done in eclipse also

A: Your xml probably looks a bit like this:
<Recyclerview....

It needs to look like this:
<android.support.v7.widget.RecyclerView....

Sorry if the formatting is off, posting from my phone!


text:
Q: Detect Duplicate data input on different dates I have the following data that will be input everyday, Column A = Input Date, Column B = Model #. I am just wondering if I could do a conditional formatting for detecting the same models that is inserted on different days.

For instance, on Date (1/1), I input two A's and one B, since those two A's are inserted on the same day, there is no alarm. But when I insert another A on a different date (1/2), is it possible to set up a conditional formatting for this duplicate entry?
I did try the following code, but then it applies to all three A's.
=countif(B:B,B1)>1
Do I need to combine both column A [Date] and Column B[Model #] so that whenever another A is inserted on a different date, then the conditional formatting is applied.
Thanks!

A: Yes, you may use conditional formatting with custom formula.

*

*First select range A2:B1000

*Go to Format → Conditional Formatting

*Use custom formula

This formula should work, paste it as your formula:
=NOT(ISNA(FILTER($A$2:A,$A$2:$A<>$A2,$B$2:$B=$B2)))
The result is similiar to this:

A: Use the below formula Validation (Select B:B as range)
=INDEX(A:A,MATCH(B1,B:B,0))=A1

Or Use Conditional Formatting with the below formula (Select B:B as range)
=INDEX(A:A,MATCH(B1,B:B,0))<>A1


text:
Q: Import ArcToolbox Log History on ArcGis I do not know what  happened but I have lost all my ArcToolbox log history that was available trough "Results" menu.
The strange thing is that I can access the log files that are saved on my harddrive. Those files are on .xml format but I do not know how to import them back to the "Results" history menu. In this picture you can see that I have very few logs in the "Results" history, but I have all of the history files!

Is there any way I can import back these files to the "Results" menu?
Can someone give me a help on this? To me is extremely useful to see the results history! It helps me a lot!

A: I suspect this is an issue with your geo-processing environment settings. Have you gone into that and changed it? If you go into that (Geoprocessing > Geoprocessing Options...) look at what your Results Management say. If you've never changed that then you will have accepted the default of 2 Weeks.
If you read the help page Using geoprocessing options to control tool execution it discusses what this means and the implications of extending the time period.


text:
Q: Why is there a red line next to my logo? I have an odd redline next to my logo, and I can't for the life of me work out why.
Take a look:
http://www.pdf-explode.com.au/index.php
Here's the red line I'm talking about:
http://www.bounceapp.com/66618

*

*I've tried looking at all the borders, there's no red.

*searched through backgrounds, no red.

*inspector can't inspect it.

*it's not in the image

Let me know if you can find it.

A: The background is repeated (the red line is a part of the letter D), so add: no-repeat to your css

A: It's the repeat of the background image on #menu a.logo (so it is the D of Document showing up again to the right). Remove the repeat.

A: your css:
#menu a.logo {
    background: url("../images/logo1.png") repeat scroll 0 0 transparent;
    height: 45px;
    left: 0;
    position: absolute;
    text-indent: -10000px !important;
    top: 5px;
    width: 265px;
    z-index: 10;
}

the correct css:
#menu a.logo {
    background: url("../images/logo1.png") no-repeat scroll 0 0 transparent; //edited
    height: 45px;
    left: 0;
    position: absolute;
    text-indent: -10000px !important;
    top: 5px;
    width: 263px; //edited
    z-index: 10;
}

your logo's width is 263px;

A: This is because your logo starts repeating itself. The line is coming from the red "D". add background-repeat: no-repeat; or shorten the logo width for about 2 pixels.


text:
Q: didSelectrow doesn't work with scrollview and tableview (iOS) At the moment I'm creating an app which has a scrollview and tableview.
I used the code like here: http://johansorensen.com/articles/touches-and-uiscrollview-inside-a-uitableview.html
but cause of the combination of the scrollview and tableview the didSelectrow function doesn't work anymore.
Thanks for helping!
Please notice: answer clear, I'm not the most experienced iOS developer.

A: In your case UIScrollView hide your cell, so you can not touch cell of UITableView therefor didSelectRowAtIndexPath method is not work.
Write following code form your link for add scrollView with in UITableView
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"ScrollCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        UIScrollView *scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 25, 320, 25)];
        scroller.showsHorizontalScrollIndicator = NO;

        UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320*4, 25)];
        contentLabel.backgroundColor = [UIColor clearColor];
        contentLabel.textColor = [UIColor whiteColor];
        NSMutableString *str = [[NSMutableString alloc] init];
        for (NSUInteger i = 0; i < 100; i++) { [str appendFormat:@"%i ", i]; }
        contentLabel.text = str;

        [scroller addSubview:contentLabel];
        scroller.contentSize = contentLabel.frame.size;
        [cell addSubview:scroller];
    }

    return cell;
}

and then use
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

It may be useful for you.


text:
Q: How to fill color in an image i use ColorFilter with BlendMo[enter image description here][3]de.srcOut,the problem is how to remove red color?
the code
the widget

A: ColorFilter.mode(Colors.transparent);
//currently it is Colors.red


text:
Q: -g option break conservative linux sort hi I just ran into either a bug or more certainly an error from me.
I am trying to sort a file that has 5 column by three specific column.
I am using -k option.
sort  -k1,1 -k3,3  -k4,4 < abundance_key_60.tsv

SO90    TARA_031_SRF    M00370  0.0004796352593680699   5380.716788521779
SO90    TARA_072_MES    M00370  6.704622779795495   889.5003464019538
WDU TARA_072_MES    M00165  0.00010342611234558623  1372.1512123790574
WDU TARA_046_SRF    M00165  0.00011353279569781544  582.9204804414709
WDU TARA_025_DCM    M00165  0.00028966684296873025  2486.7113286682593

Everything work fine then I realised one of my column is numeric and I add the -g option for this column. At this point sort seems to only filter by this column :
sort -k1,1 -k3,3  -gk4,4 <  test_.sort.txt

SO90    TARA_031_SRF    M00370 0.0004796352593680699    5380.716788521779
WDU TARA_025_DCM    M00165  0.00028966684296873025  2486.7113286682593
WDU TARA_046_SRF    M00165  0.00011353279569781544  582.9204804414709
WDU TARA_072_MES    M00165  0.00010342611234558623  1372.1512123790574
SO90    TARA_072_MES    M00370  6.704622779795495   889.5003464019538

I try to use -s option but I did not change the results.
any help appreciated!
ps: this is sample from my file that reproduce the bug.
I am on ubuntu 16.04 with default bash and sort for this distribution.

A: You want to specify the g only for -k4,4, like this:
bash$ sort -k1,1 -k3,3 -k4,4g test_.sort.txt
SO90    TARA_031_SRF    M00370 0.0004796352593680699    5380.716788521779
SO90    TARA_072_MES    M00370  6.704622779795495   889.5003464019538
WDU TARA_072_MES    M00165  0.00010342611234558623  1372.1512123790574
WDU TARA_046_SRF    M00165  0.00011353279569781544  582.9204804414709
WDU TARA_025_DCM    M00165  0.00028966684296873025  2486.7113286682593

(Experimentally verified by changing the number to 6.704622779795495E-10 and observing how that changes the sort order. A better test case would contain samples which trivially reveal when you get the correct result.)


text:
Q: How do I transform a claim to a HMACSHA256 claim in an Azure B2C custom policy? I am creating a custom policy to use Azure B2C as an IdP to integrate with a legacy auth service. The legacy service and the new IdP share a secret.
The legacy auth service has a custom authentication flow and requires that an HMACSHA256-based challenge token is sent to it as part of its Auth process using the shared secret as the key.
I am unable to find a way to create/transform a token to an HMACSHA256-based output claim. What are the recommended patterns to address a situation such as mine?
I tried https://learn.microsoft.com/en-us/azure/active-directory-b2c/general-transformations#hash
but the computed hashes do not match.

A: Azure AD B2C doesn't create or transform HMACSHA254 token.
Also, it is not possible to do transformations on the resulting token. Claim transformation will only apply to claims in the claims bag.


text:
Q: Is it possible to reference the output of an IronPython project from within a c# project? I would like to build a code library in IronPython and have another C# project reference it. Can I do this? How?
Is this just as simple as building the project and referencing the dll? Is there any conflict with the dynamic aspect of it?

A: There is currently no way to build CLS-compliant assemblies from IronPython. The pyc tool will generate a DLL from Python code, but it's really only useful from IronPython.
If you want to use IronPython from a C# app, you'll have to use the hosting interfaces (gory details). You could also check out IronPython in Action, which describes the hosting process quite well.


text:
Q: Reading KML Simple Data to a popup in Open Layers I have created a pop up for markers read from a KML file, however The KML file data is not being read and I assume due to it being in a <SimpleData> tag and in a <name> tag
How would I be able to read this to get the name of the listed buildings from the file as well as the Grade and Broad Class from this file to the PopContent Variable
Pop up Script
Omap.on('click', function (evt){
    var feature = Omap.forEachFeatureAtPixel(evt.pixel,
        function (feature,layer) {
            return feature;
            });
        if (feature) {
            var Popgeom = feature.getGeometry();
            var Popcoord = Popgeom.getCoordinates();

            var PopContent = '
' + feature.get('name') + '
';
            PopContent += '
' + feature.get('Grade') + '
' + '
The listed property is a ' + feature.get('BroadClass') + ' building
';

            content.innerHTML = PopContent;
            overlay.setPosition(Popcoord);

            console.info(feature.getProperties());
        }
    });

An extract from the KML file:
<Placemark>
    <name>Kelsterton Hall</name>
    <ExtendedData><SchemaData schemaUrl="#LSB">
        <SimpleData name="id">Cadw_ListedBuildings.fid--3eda8af5_1772a727fac_-6786</SimpleData>
        <SimpleData name="RecordNumber">1</SimpleData>
        <SimpleData name="DesignationDate">1949/08/08 00:00:00</SimpleData>
        <SimpleData name="Grade">II</SimpleData>
        <SimpleData name="Location">Set back slightly from the road at the junction of Kelsterton Road and Kelsterton Lane.</SimpleData>
        <SimpleData name="BroadClass">Recreational</SimpleData>
        <SimpleData name="BroadClass_cy">Hamdden</SimpleData>
        <SimpleData name="Report">http://cadwpublic-api.azurewebsites.net/reports/listedbuilding/FullReport?lang=en&id=1</SimpleData>
    </SchemaData></ExtendedData>
      <Point><coordinates>-3.08246357229187,53.2285595916199</coordinates></Point>
  </Placemark>

A: As Mike stated in the comments

Even when you have a cluster of one you will need to extract the real feature from the cluster

this means the return feature; will need to instead be return feature.get('features')[0];
so the code became
Omap.on('click', function (evt){
    var feature = Omap.forEachFeatureAtPixel(evt.pixel,
        function (feature,layer) {
            return feature.get('features')[0];
            });
        if (feature) {
            var Popgeom = feature.getGeometry();
            var Popcoord = Popgeom.getCoordinates();

            var PopContent = '
' + feature.get('name') + '
';
            PopContent += '
' + feature.get('Grade') + '
' + '
The listed property is a ' + feature.get('BroadClass') + ' building
';

            content.innerHTML = PopContent;
            overlay.setPosition(Popcoord);

            console.info(feature.getProperties());
        }
    });


text:
Q: Invoking Integer.parseInt method using reflection how can I call a parseInt function on some variable ?  I want to do something like
parseInt.invoke("23");
Note : I have an array of methods where parseInt is stored
Method[] methods contains the parseInt method

so... it's like
      methods[0].invoke("23");
but when i do this i get
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at myproject.MyProject.main(MyProject.java:114)

A: Method#invoke(Object, Object...) takes the first argument as the object on which this method is invoked, and 2nd argument onwards, it takes the arguments of the method. First argument has to be a reference for an instance method, and simply null for a static method. Since Integer#parseInt(String) is a static method. The first argument to the invoke method has to be null for that:
methods[0].invoke(null, "23");

A: Is method[0] returning the parseInt method of Integer class ?
May be this will help you :-
 Method m =Integer.class.getMethod("parseInt", String.class);
 System.out.println(m.invoke(null, "23"));

String.class is parameter passing to parseInt i.e "23"


text:
Q: Convert HttpPostedBase to format usable with File.ReadAllLines() I want to be able to use the code block below, but instead of using a saved file I have an uploaded file as a HttpPostedFileBase. How to I convert that to an equivalent format where I can use the contents of the uploaded file with the code below without saving it first?
  List<DailyValues> values = File.ReadAllLines("C:\\Users\\Josh\\Sample.csv")
                                               .Skip(1)
                                               .Select(v => DailyValues.FromCsv(v))
                                               .ToList();

A: You can't. The best way is to read the data as a Stream from the InputStream property on that object.


text:
Q: How to remove multiple apps? I tried to remove multiple apps from the software centre GUI by Ctrl+Select but nothing happens. After each removal, it refreshes its screen.
I have many Thai fonts (that I could see after selecting Show xxxx technical items). I cannot remove each one by one. That eats up a lot of CPU and is time consuming.
Please give some alternative on how I can remove multiple packages, preferably in GUI, but commands would do too.

A: Well you could try and remove them from terminal. It seems that all the files you want to remove start with fonts-tlwg so you could do:
sudo apt-get remove fonts-tlwg-*

And that does the trick.

A: first install synaptic, it's a software manager like software center by this command
sudo apt-get install synaptic

or install it from software center, after installing open synaptic from main menu, enter your password, from the top bar press search and enter your keyword, then select all, right click and mark for removal, in the end click apply.

A: If you want a GUI, install synaptic package manager which allows you to add/remove multiple packages.


text:
Q: Allowing custom attribute to element with htmlpurifier Got stuck half-way through my little process, need help with this last step.
Needed to add a custom element to accept a custom book element that would be passed through a textarea form.
$dirty = 'you should check this out: <book author="me">my book title</book>!';

$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'book');
$def = $config->getHTMLDefinition(true);
$def->addElement('book',  'Inline', 'Inline', 'Common');
$purifier = new HTMLPurifier($config);
echo $purifier->purify($dirty);

Returns:
you should check this out: <book>my book title</book>!
But it is stripping out the author="me"
If I add in the standard htmlpurifier attr allowance, such as:
`$config->set('HTML.Allowed', 'book[author]');`

it returns error:
Attribute 'author' in element 'book' not supported
I need it so that the author="me" can be included or not included.
Can somebody please share the code change/addition I need to get the author="me" to be allowed - thanks!
I am running htmlpurifier 4.6.0

A: Have you tried using $def->addAttribute('book', 'author', 'CDATA'); after your $def->addElement(...) call?


text:
Q: THREEJS Can't clone FBX model I am loading FBX models for my project. I Want to create multiple objects of the same FBX model but loading each separately is very inefficient so I would like to save one loaded model and clone it. This concept is working with the .OBJ format.
Everything works as expected but then I use "model.clone();" nothing really happens.
The model is no longer visible but I get no errors. If you compare the cloned model with the original they look exactly the same so I don't know why it's not showing up.
This is how it looks when it's working:

When it's not working it's just a blank canvas.
Here is some simplified working source code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="https://vitalkia.com/jsLibraries/zlib.min.js"></script>
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/loaders/FBXLoader.js">
</script>
<script>
    var aspectRatio = 240 / 135;
    var scene;
    var renderer;
    var loaderFBX;
    var camera = new THREE.PerspectiveCamera(45, aspectRatio, 1, 10000);

    //Actual code
    //Setus up scene and renderer
    sceneSetup();

    //Load fbx and render
    //IGNORE ERROR ABOUT NOT FINDING THE RIGHT TEXTURE. It still works
    loaderFBX.load("https://threejs.org/examples/models/fbx/Samba Dancing.fbx", function(model){
        //Sending the object "model" works
        //But using model.clone() does not. It doesn't give any errors or anything, it's just not visible
        //If you compare the cloned model with the original they look exactly the same.

        var sendModel = model;//Works
        //var sendModel = model.clone();//Doesn't works
        console.log("Original: ");
        console.log(model);
        console.log("Cloned: ");
        console.log(model.clone());

        calcDistance(sendModel);

        scene.add(sendModel);
        renderer.render(scene, camera);
    });

    function calcDistance(model){
        var bbox = new THREE.Box3().setFromObject(model);

        var camDistance = bbox.max.z;
        if(bbox.max.x > camDistance){
            camDistance = bbox.max.x;
        }
        if(bbox.max.y*aspectRatio > camDistance){
            camDistance = bbox.max.y*aspectRatio;
        }

        camera.position.z = camDistance;
        model.position.x -= bbox.getCenter().x;
        model.position.y -= bbox.getCenter().y;
    }

    function sceneSetup(){
        loaderFBX = new THREE.FBXLoader();
        scene = new THREE.Scene();
        renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});
        renderer.setSize(240, 135);
        document.body.appendChild(renderer.domElement);
        var light1 = new THREE.PointLight(0xffffff, 1, 100000000);
        light1.position.set(0, 0, 15);
        scene.add(light1);
        var newLightPoint = new THREE.HemisphereLight(0x8be2ff, 0xfff9cf, 0.55);
        scene.add(newLightPoint);
        camera.position.set(0, 0, 100);
        scene.add(camera);
    }
</script>

Is this how you should do it to reuse models instead of having to reload them for every object? Or is there a better way?


text:
Q: Scrapy crawls only one page I have made a scrapy spider that I would like to crawl all the pages but it only crawls to the second page and then stops.
It seems that within the if next_page: loop the url only changes to the second page and then sticks there. I think I am misunderstanding how http responses work because it seems to only grab the next page link on the starting page.
import scrapy

from tutorial.items import TriniCarsItem

class TCS(scrapy.Spider):
    name = "TCS"
    allowed_domains = ["TCS.com"]
    start_urls = [
        "http://www.TCS.com/database/featuredcarsList.php"]

    def parse(self, response):
        for href in response.css("table > tr > td > a::attr('href')"):
            url = response.urljoin(href.extract())
            yield(scrapy.Request(url, callback=self.parse_dir_contents))
        next_page = response.css("body > table > tr > td > font > b > a::attr('href')")
        if next_page:
            url = response.urljoin(next_page[0].extract())
            print("THIS IS THE URL =----------------------------- " + url)
            yield(scrapy.Request(url, self.parse))

    def parse_dir_contents(self, response):
        for sel in response.xpath('//table[@width="543"]/tr/td/table/tr/td[2]/table'):
            item = TCSItem()
            item['id'] = sel.xpath('tr[1]/td[1]//text()').extract()
            item['make'] = sel.xpath('tr[3]/td[2]//text()').extract()
            item['model'] = sel.xpath('tr[4]/td[2]//text()').extract()
            item['year'] = sel.xpath('tr[5]/td[2]//text()').extract()
            item['colour'] = sel.xpath('tr[6]/td[2]//text()').extract()
            item['engine_size'] = sel.xpath('tr[7]/td[2]//text()').extract()
            item['mileage'] = sel.xpath('tr[8]/td[2]//text()').extract()
            item['transmission'] = sel.xpath('tr[9]/td[2]//text()').extract()
            item['features'] = sel.xpath('tr[11]/td[2]//text()').extract()
            item['additional_info'] = sel.xpath('tr[12]/td[2]//text()').extract()
            item['contact_name'] = sel.xpath('tr[14]/td[2]//text()').extract()
            item['contact_phone'] = sel.xpath('tr[15]/td[2]//text()').extract()
            item['contact_email'] = sel.xpath('tr[16]/td[2]//text()').extract()
            item['asking_price'] = sel.xpath('tr[17]/td[2]//text()').extract()
            item['date_added'] = sel.xpath('tr[19]/td[2]//text()').extract()
            item['page_views'] = sel.xpath('tr[20]/td[2]//text()').extract()
            #print(make, model, year, colour, engine_size, mileage, transmission, features,
            #additional_info, contact_name, contact_phone, contact_email, asking_price, date_added,
            #page_views)
            yield(item)

A: On the 2nd page the 1st link (the one you choose) is the one pointing to the previous page. Just send any links in order and let the de-duplicator cancel out any duplicates:
    if next_page:
        for i in next_page
            url = response.urljoin(i.extract())
            print("THIS IS THE URL =----------------------------- " + url)
            yield(scrapy.Request(url, self.parse))

P.S. In your case, consider also the significantly easier and way more massively parallel:
start_urls = [
    "http://www.trinicarsforsale.com/database/featuredcarsList.php?page=%d" % i for i in xrange(1, 460)]

def parse(self, response):
    return self.parse_dir_contents(response):


text:
Q: RTL8723DE device bluetooth driver I have updated to kernel 4.17.0-041700-genericand installed the Bluetooth driver going through How to activate bluetooth device for RTL8723DE?. In earlier kernel driver it was doing well.
Edit : Now I have installed 5.6.0-050600-generic and bluetooth is working but wi-fi has gone
sudo dkms install rtlwifi-new/0.6
Kernel preparation unnecessary for this kernel.  Skipping...
Building module:
cleaning build area......(bad exit status: 2)
make -j2 KERNELRELEASE=5.3.0-46-generic -C /lib/modules/5.3.0-46-generic/build M=/var/lib/dkms/rtlwifi-new/0.6/build.........................................(bad exit status: 2)
ERROR (dkms apport): binary package for rtlwifi-new: 0.6 not found
Error! Bad return status for module build on kernel: 5.3.0-46-generic (x86_64)
Consult /var/lib/dkms/rtlwifi-new/0.6/build/make.log for more information.

A: If you read the answer carefully, you could have noticed that supported kernels are 4.4-4.15.
You installed for an unknown reason the 4.17 mainline kernel. That's why the module is not building or working.
At present the RTL8723DE bluetooth device is suppored by the 5.3 kernel out of the box. This kernel is preinstalled with Ubuntu 18.04 iso and installable on the initial 18.04 release by
sudo apt install linux-generic-hwe-18.04


text:
Q: How to specify Javascript path when calling Javascript method from C# using Xamarin android? I have this Xamarin Android project in which I need to call a Javascript method from C#. The name of the method is "drawMap". I have used the following technique to call the method.
webView.EvaluateJavascript(string.Format("mapDraw(" + ConvertToRadians(degree) + ")"), null);

But this MainActivity class is at the root of the project and Javascript class is inside Views-> test.js. How do I set the path to look for this method in that class?
Below code exists in the RazorView.cshtml file.
 $(document).ready(function () {
     function mapDraw(radValue) {
            var updatedPoint = mapImg.getMapCoordinates(currentPoint[0] + Math.sin(radValue), currentPoint[1] - Math.cos(radValue), false);
            console.log(currentPoint);
            console.log(updatedPoint);
            var line = new fabric.Line([currentPoint[0], currentPoint[1], currentPoint[0], currentPoint[1]], {
                stroke: 'red',
                originX: 'center',
                originY: 'center'
            });

            canvas.add(line);
            line.set({
                x2: updatedPoint[0],
                y2: updatedPoint[1]
            });
            canvas.renderAll();
            currentPoint = updatedPoint;
        }
 }

This drawMap is the method I have to call from C#

A: You can call JS in WebView by LoadUrl method, first be sure you set Enable to true for Settings.JavaScriptEnabled.
WebView wv = FindViewById<WebView>(Resource.Id.webView1);
wv.Settings.JavaScriptEnabled = true;
wv.Settings.AllowFileAccess = true;

webview.LoadUrl("javascript:mapDraw(\"" + ConvertToRadians(degree) + "\")");