Q: Variable Values in Java I have a quick question in regards to the value of how variable values work. I am working on a program right now, which looks like this:
public void run() {

    println("There are " + ATOMS + " initially.");

    int atoms = ATOMS;
    int year = 0;

    while (atoms > 0) {

        for (int i = atoms; i > 0; i--) {

            println(i);
            if( rgen.nextBoolean() ) {
                atoms--;
                println("The total atoms is " + atoms);
            }

            println("The total for i is " + i + "\n"  );

        }

         year++;

         println("There are " + atoms + " at the end of year " + year );
    }

}

At the part with the for loop, and setting the variable i to the value of atoms, is what has me confused. Lets say the value of atoms starts at 20. It goes through the for loop and lets assume that the first time through the RandomGenerator makes it true. So that subtracts 1 from atoms. Then after that the value of i should also be minused due to the i--. So my question is: When I set the variable i to the value of atoms does that just take i and set it to the initial value of 20? And then from there every time I adjust the value of i it is taking off of its own version of 20, and then when I change the value of atoms it, too has its own value. So when I subtract from atoms, that is not also being subtracted from i? That is the only way I can make sense of it because this program is written and works correctly, but that part has me confused.
Thank you very much in advance for any help!

A: Once you set the value of i=atoms, it no longer changes.  It is the loop initializer, and will no longer be processed.
"i" of course will be decremented continuously (because of the i-- decrement).
But you can change the value of atoms to whatever and the results will not change.

A: i=atoms is the initialization in the for loop. So then on, value of i independent of atoms.

A: yes you have answered your own question. the variable i and atoms are two separate instances.
when you start the loop you are setting i equal to the same value as atoms but they are still separate variables. therefore inside the loop when you change the value of one it does not affect the other.


Q: Installing an app to my home screen android I am looking for a way for when someone installs my application it goes in their "all applications menu". Then, after they run the app and go into the setup, when they click save on their options, it will create a shortcut on the home screen (not the all applications menu). Also, is it possible to have this shortcut not do the same thing as the other app? meaning that if I wanted to change the settings I could click on the app in the all applications menu and if I click on the app in the home screen it does something else.

A: First off, there's lots of different home screen implementations on Android. The stock Android one, Samsung, HTC and Motorola all have their own variants, then third party ones like Launcher Pro. All use different stores as to what to keep on the home screen, may provide different profiles for the home screen (home, work, etc).
Second, the home screen is prime real estate. And it is also the user's real estate. If there was programmatic access to the home screen, what happened to the Windows quick launch, desktop, favorites menu (in older versions of IE), and older pin area of the start menu (the very top of it in Win 95/98).
To quote Raymond Chen "I bet somebody got a really nice bonus for that feature". So, in short, even if it was possible, please don't. As awesome as you think your program is, the user might not think the same.


Q: Gradle runs fine under interactive account but not under NT service We have a batch file to build our Android application. It basically runs gradlew.bat assemble. When I remote desktop into the build machine (Windows 8) and run the batch file, everything builds as expected. However, when I invoke the batch file through an NT service, we start getting errors.
The account that the service runs under does have administrative privileges on the machine.
The first error was javax.net.ssl.SSLHandshakeException. Based on another post Android Studio Gradle build failed. Error:Cause: peer not authenticated, I modified gradle-wrapper.properties to use http instead of https for the distribution url. That took care of this problem.
The next error was also similar but this time it was with downloading pom file. Based on another post android- Gradle: An issue occurred configuring root project android studio, I modified build.gradle to use http://jcenter.bintray.com/ as the url instead of default https.
Now I am getting the following error:
Could not parse POM
http://jcenter.bintray.com/com/android/tools/build/gradle/1.1.0/gradle-1.1.0.pom

I am wondering why https could cause a problem in NT service account but not in normal interactive account. Is there a way to fix it? If not, would appreciate if someone has an insight on what the above error means. Regards.

A: A common source of problems when programs that execute successfully as an interactive user, but fail when run as a service, is the user settings surrounding the execution have changed.  For example, when you run Gradle, there are settings in %USERPROFILE% \ .gradle (typically c:\users\<username>, which for you logged in interactively is different than the account under which the service is running.)
When you run as a service, there is a different user profile, or possibly none at all.  Have your batch script dump the environment (add "set" near the top of the .bat file - this will dump an alphabetical list of environment variables), and compare the output when it runs as a service to when you run it interactively.  See if USERPROFILE is defined, and if it is compare the .gradle folder in the service's area to your own .gradle folder.
In addition to Gradle settings, Gradle's cache is also typically under the .gradle folder.  Your cache is likely to contain different items than the cache of the service, which may be significant if there are authentication issues in the external repositories to which your build tries to connect (again, possibly as a result of the different credentials in your user configurations!)
The tool processing the https request may look for certificates somewhere in your user profile.  You may have accepted a certificate (used to 'recognize' an https server) that is not included in the accepted certificates of the service.  These would likely be in the .keystore file in your user profile.  Java's keytool.exe can help to decode and dump this file.
Other tools involved in your build may also have settings stored in the USERPROFILE space, which differ between your space and that of the service account - for example Android (.android), Java, Maven (.m2), Git (.gitconfig), etc.


Q: problems installing scrapy ..missing gcc 4.0 I am having trouble installing scrapy with easy_install, I get:
unable to execute gcc-4.0: No such file or directory
error: Setup script exited with error: command 'gcc-4.0' failed with exit status 1
I have gcc-4.2. I've been trying to downgrade to gcc-4.0 but cannot figure out a way ...

A: You need to setup your environment:

*

*First, install Command Line Tools for Xcode (I'm not 100% sure that you can install without XCode, if not then install XCode from App Store).

*Then install MacPorts
To complete macports setup run this command in Terminal.app:
% sudo port selfupdate

If you done, then you can install scapry from macports:
% sudo port install py27-scrapy

Afther this you should be able to use scrapy command in Terminal.app.


Q: ssh -> UNIX screen and keymaps (macbook delete key in particular) Over the years I've had various keymap issues in UNIX screen through SSH, and I assume others have as well. My question has two parts:

*

*When I SSH into my Ubuntu Dapper server (I know, I'm moving to Lenny post-haste:) from my OSX Macbook, the delete key doesn't map to backspace, but to delete (which is not the correct behavior, Apple's delete is really backspace). Has anyone else encountered this behavior? How to resolve it?

*I think I ought to know more about how keymaps work on the UNIX console in general. Where can I find general information on how to resolve inter-platform keymap issues with SSH?

A: *

*Check in Terminal -> Settings -> Advanced and make sure that your delete key is sending something sane.  Toggle this and see if it helps.

*See what $TERM is when you ssh into your server.  I get xterm-color when I ssh in to my Debian box, and screen when I'm in screen.

A: Ubuntu Linux, and UNIX systems in general, use a program called stty to configure the keyboard.  Run the command "man stty" to read the manual page for stty.  By the way, stty is in section 1 of the manual, so UNIX geeks tend to call this program "stty(1)".
The usual way to customize keyboards is to edit the startup file for your shell.  If you use the bash shell, this file is .bashrc.  You can test a shell variable called "TERM" which identifies what kind of terminal or terminal emulator you are using.  If you have no experience at editing .bashrc files, you can read about the syntax in the bash manual page: "man bash"
As far as I know, the actual key code sent by the Apple terminal emulator probably is ASCII DEL; it's up to your stty settings to turn that into backspace-erase in the shell.
Good luck!

A: You need to make yourself an .inputrc file in your home directory. Check out: http://www.macosxhints.com/article.php?story=20050525040921189.
My ~/.inputrc looks like this (I especially like the case-insensitive auto complete):
# Make fwd delete key do something useful
"\e[3~": delete-char

# Make ctrl-left and ctrl-right skip words
"\e[5C": forward-word
"\e[5D": backward-word

# ignore case in tab-autocomplete
set completion-ignore-case On


Q: pytest: selective log levels on a per-module basis I'm using pytest-3.7.1 which has good support for logging, including live logging to stdout during tests. I'm using --log-cli-level=DEBUG to dump all debug-level logging to the console as it happens.
The problem I have is that --log-cli-level=DEBUG turns on debug logging for all modules in my test program, including third-party dependencies, and it floods the log with a lot of uninteresting output.
Python's logging module has the ability to set logging levels per module. This enables selective logging - for example, in a normal Python program I can turn on debugging for just one or two of my own modules, and restrict the log output to just those, or set different log levels for each module. This enables turning off debug-level logging for noisy libraries.
So what I'd like to do is apply the same concept to pytest's logging - i.e. specify a logging level, from the command line, for specific non-root loggers. For example, if I have a module called test_foo.py then I'm looking for a way to set the log level for this module from the command line.
I'm prepared to roll-my-own if necessary (I know how to add custom arguments to pytest), but before I do that I just want to be sure that there isn't already a solution. Is anyone aware of one?

A: I had the same problem, and found a solution in another answer:
Instead of --log-cli-level=DEBUG, use --log-level DEBUG. It disables all third-party module logs (in my case, I had plenty of matplotlib logs), but still outputs your app logs for each test that fails.

A: I got this working by writing a factory class and using it to set the level of the root logger to logger.INFO and use the logging level from the command line for all the loggers obtained from the factory. If the logging level from the command line is higher than the minimum global log level you specify in the class (using constant MINIMUM_GLOBAL_LOG_LEVEL), the global log level isn't changed.
import logging

MODULE_FIELD_WIDTH_IN_CHARS = '20'
LINE_NO_FIELD_WIDTH_IN_CHARS = '3'
LEVEL_NAME_FIELD_WIDTH_IN_CHARS = '8'
MINIMUM_GLOBAL_LOG_LEVEL = logging.INFO

class EasyLogger():
    root_logger = logging.getLogger()
    specified_log_level = root_logger.level
    format_string = '{asctime} '
    format_string += '{module:>' + MODULE_FIELD_WIDTH_IN_CHARS + 's}'
    format_string += '[{lineno:' + LINE_NO_FIELD_WIDTH_IN_CHARS + 'd}]'
    format_string += '[{levelname:^' + LEVEL_NAME_FIELD_WIDTH_IN_CHARS + 's}]: '
    format_string += '{message}'
    level_change_warning_sent = False

    @classmethod
    def get_logger(cls, logger_name):
        if not EasyLogger._logger_has_format(cls.root_logger, cls.format_string):
            EasyLogger._setup_root_logger()
        logger = logging.getLogger(logger_name)
        logger.setLevel(cls.specified_log_level)
        return logger

    @classmethod
    def _setup_root_logger(cls):
        formatter = logging.Formatter(fmt=cls.format_string, style='{')
        if not cls.root_logger.hasHandlers():
            handler = logging.StreamHandler()
            cls.root_logger.addHandler(handler)
        for handler in cls.root_logger.handlers:
            handler.setFormatter(formatter)

        cls.root_logger.setLevel(MINIMUM_GLOBAL_LOG_LEVEL)
        if (cls.specified_log_level < MINIMUM_GLOBAL_LOG_LEVEL and
            cls.level_change_warning_sent is False):
            cls.root_logger.log(
                max(cls.specified_log_level, logging.WARNING),
                "Setting log level for %s class to %s, all others to %s" % (
                    __name__,
                    cls.specified_log_level,
                    MINIMUM_GLOBAL_LOG_LEVEL
                )
            )
            cls.level_change_warning_sent = True

    @staticmethod
    def _logger_has_format(logger, format_string):
        for handler in logger.handlers:
            return handler.format == format_string
        return False

The above class is then used to send logs normally as you would with a logging.logger object as follows:
from EasyLogger import EasyLogger

class MySuperAwesomeClass():
    def __init__(self):
        self.logger = EasyLogger.get_logger(__name__)

    def foo(self):
        self.logger.debug("debug message")
        self.logger.info("info message")
        self.logger.warning("warning message")
        self.logger.critical("critical message")
        self.logger.error("error message")

A: Enable/Disable/Modify the log level of any module in Python:
logging.getLogger("module_name").setLevel(logging.log_level)


Q: How to reduce the width of dropdown-menu? I am using bootstrap 3 to create a simple drop-down menu, but I want to decrease its width and I can't figure it out how to do this.
HTML:

  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Dropdown

  </button>

Action

Another

Something

Separated

CSS:
.dropdown-menu {
    width: 60px !important;
}

A: .dropdown-menu has min-width: 160px; and min-width overrides width so you can not change width you can use min-width instead of width.

.dropdown-menu {
  min-width: 60px !important;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Dropdown

  </button>

Action

Another

Something

Separated

It works. You should call bootstrap lib and jquery. Please, read bootstrap documentation.
Jsfiddle

A: Give a ID for the div and specify the min-width in the css as follows:
.dropdown #mydiv{ min-width:60px; }

Note: Do NOT use '!important'.
For more information check out this great post by Chris Coyier : Specifics on CSS Specificity


Q: Timezone changing automatically to 'Chicago' after rebooting CentOS 7 I recently switched from CentOS 6 to 7. I've noticed that every time I reboot my OS, it switches my timezone to Chicago (CDT) but I'm in EDT. It is easy enough to update the timezone with timedatectl set-timezone America/New_York but it is quite annoying to do this after every reboot. Any ideas?
Based on a similar post I checked my hwclock:
$ sudo hwclock --show
Tue 01 Aug 2017 10:40:58 AM EDT  -0.344415 seconds

So that looks fine.

A: so after digging further into my issue, it turns out that everything on the gnome/centos 7 side is working as expected. This issues is that the CradlePoint LTE modem/router we use at the office for internet connectivity is resolving the wrong timezone... which is a whole other issue for a different board.
So the solution is that I needed to look further up the tree on the networking side before assuming that such a simple feature would be failing on the OS side :-)


Q: Issue with rendering XML data in SPFx I am in a project of making a RSS feed in SPFx and using React.js and TypeScript.
When I try to retrieve XML data from a news site, the console gives error:

Because it complains about CORS, so I tried using a CORS extension in Chrome and enable CORS but the I get these errors:

The code looks like this for my attempts to fetch an XML page from a Swedish news site:
    import * as React from 'react';
import styles from '../RssApp.module.scss';
import { IRssAppProps } from './IRssAppProps';
import { escape } from '@microsoft/sp-lodash-subset';
import {IRssAppState} from './IRssAppState'

export default class RssApp extends React.Component<IRssAppProps, IRssAppState> {
  constructor(props: IRssAppProps){
    super(props);
    this.state = {

        title: 'afton',
        link: ''

    }
  }

  private async FetchDataFromXml(){
    var request = new XMLHttpRequest();
    request.onreadystatechange = () =>{
      if(request.readyState == 4 && request.status == 200){
        var myXML = JSON.parse(request.responseText);
        for(var i = 0; i < 1; i++){
          this.setState({

              title: myXML.items[i].title,
              link: myXML.items[i].link

          });
        }
      }
    }
    request.open("GET", "https://www.aftonbladet.se/nyheter/rss.xml", true)
    request.send();
    //console.log(this.FetchDataFromXml);
  }

  componentDidMount(){
    {this.FetchDataFromXml()}
  }

  public render(): React.ReactElement<IRssAppProps> {
    return (

              {this.state.title}

    );
  }
}

And nothing except my hard coded step "afton" is showing in the webpart.
Would apprieciate of someone could help me. Is there another way  to solve this? What am I doing wrong?
Thanks in advance.


Q: Increasing number once per mouse click/key press in XNA This has been bothering me lately- when I use some code like below to increase selection every mouse click:
if (m.LeftButton == ButtonState.Pressed)
currentSelection++;
Then currentSelection increases by a ton, simply because this code is in my Update() function and by design, runs every frame and so increases currentSelection. There is almost no chance you can click and release fast enough to prevent currentSelection from increasing more than one.
Now my question is what I should do to make it so everytime I click the mouse down once, it only increases currentSelection once until the next time I click down again.

A: You will need to compare the current mouse state and the last update's mouse state.
In your class you'll have MouseState mouseStateCurrent, mouseStatePrevious; declared and so it'll be something like:
mouseStateCurrent = Mouse.GetState();

if (mouseStateCurrent.LeftButton == ButtonState.Pressed &&
    mouseStatePrevious.LeftButton == ButtonState.Released)
{
    currentSelection++;
}

mouseStatePrevious = mouseStateCurrent;

So it will detect that previous time you pressed it, then you release it - only then it is considered as a click and it will add to currentSelection.


Q: The analyzer produces case_block_not_terminated in a case block with nested if/else statement, although return statement is executable I have a case that I would like to understand.
If I have following Switch Case statement with nested if/else:
f(int x, int y) {
  switch (x) {
    case 0:
      if (y > 10) {
        return 'StringA';
      } else {
        return 'StringB';
      }
    default:
      return 'Anything';
  }
}

the analyses throws an error: case_block_not_terminated

case_block_not_terminated: The last statement of the ‘case’ should be
‘break’, ‘continue’, ‘rethrow’, ‘return’, or ‘throw’.

if I add a break; at the end of the case statement the error disappears, but it is clearly dead code, because one of the return statements should be executed.
f(int x, int y) {
  switch (x) {
    case 0:
      if (y > 10) {
        return 'StringA';
      } else {
        return 'StringB';
      }
      break;
    default:
      return 'Anything';
  }
}

A: This issue should go away when you enable the null-safety feature.  The analyzer's code flow analysis has been much improved for NNBD to fix this and similar cases. (You can verify this in DartPad with null-safety enabled.)
In the meantime, you also could just remove the superfluous else:
String f(int x, int y) {
  switch (x) {
    case 0:
      if (y > 10) {
        return 'StringA';
      }
      return 'StringB';
    default:
      return 'Anything';
  }
}

or remove the superfluous default case:
String f(int x, int y) {
  switch (x) {
    case 0:
      if (y > 10) {
        return 'StringA';
      } else {
        return 'StringB';
      }
  }
  return 'Anything';
}


Q: Complementary Transmission Gate Circuit Here is the circuit.

Now what would be the voltages at Node Y on the positive edge of the clock, if Switching Time from on to off and off to on of Transmission Gates are : 0.5ns, 1ns, 2ns

A: Keep in mind that the input to a CMOS gate represents a significant capacitance that stores charge. You can think of it as a capacitor connected to ground.
When TG1 is on (and TG2 is off), node Y charges to the same voltage as X. When TG1 turns off, node Y simply keeps this same voltage, since the charge has nowhere to go, except for leakage paths that might cause the voltage to droop slightly.
The two inverters drive the voltage on the bottom end of TG2 to nominally the same value as node Y (and node X). So, when TG2 turns on, there is no appreciable change in the voltage at node Y, other than that any "droop" gets eliminated — assuming that the voltage didn't droop so far as to cause the voltage at node Z to change.


Q: slideUp different on actual page I am trying to use the slideUp() JQuery function on a bunch of items without images. The code I've written works fine in JSFiddle, but on my actual page, it collapses in a clunky way.
Why are they not acting the same way?
JSFiddle
To activate the function on the page, press the checkbox in the right menu
Real page

A: Sifting through CSS for a few minutes and I found a solution, I have made a list of corrections.
Here is the CSS code on pastebin, it does all the fixes I have mentioned below.
Manual Fix
Find #middlewrapper #content .contentbox, disable float:left.
#middlewrapper #content .contentbox {
    width: 650px;
    padding: 15px;
    /* float: left; */
    background-color: white;
}

Find #middlewrapper #content .contentbox_shadow, disable float:left.
#middlewrapper #content .contentbox_shadow {
    width: 690px;
    height: 20px;
    /* float: left; */
    background-image: url('http://xn--nstvedhandel-6cb.dk/naestved/public/css/../images/content_skygge.png');
    background-repeat: no-repeat;
}

Find #middlewrapper #content, disable float:left.
#middlewrapper #content {
    width: 690px;
    /* float: left; */
}

Finally, find #middlewrapper #content .contentbox, after it's definition, place #content.
#content {
    width: 680px;
    float: left;
}

Do not delete or alter the definition of #middlewrapper #content found a few lines later.


Q: How to parse HTML tags as raw text using ElementTree I have a file that has HTML within XML tags and I want that HTML as raw text, rather than have it be parsed as children of the XML tag. Here's an example:
import xml.etree.ElementTree as ET
root = ET.fromstring("<root><text>
This is some text that I want to read
</text></root>")

If i try:
root.find('text').text

It returns no output
but root.find('text/p').text will return the paragraph text without the tags. I want everything within the text tag as raw text, but I can't figure out how to get this.

A: Your solution is reasonable. An element object is the list of children. The .text attribute of the element object is related only to things (usually a text) that are not part of other (nested) elements.
There are things to be improved in your code. In Python, string concatenation is an expensive operation. It is better to build the list of substrings and to join them later -- like this:
output_lst = []
for child in root.find('text'):
    output_lst.append(ET.tostring(child, encoding="unicode"))

output_text = ''.join(output_lst)

The list can be also build using the Python list comprehension construct, so the code would change to:
output_lst = [ET.tostring(child, encoding="unicode") for child in root.find('text')]
output_text = ''.join(output_lst)

The .join can consume any iterable that produces strings. This way the list need not to be constructed in advance. Instead, a generator expression (that is what can be seen inside the [] of the list comprehension) can be used:
output_text = ''.join(ET.tostring(child, encoding="unicode") for child in root.find('text'))

The one-liner can be formatted to more lines to make it more readable:
output_text = ''.join(ET.tostring(child, encoding="unicode")
                      for child in root.find('text'))

A: I was able to get what I wanted by appending all child elements of my text tag to a string using ET.tostring:
output_text = ""
for child in root.find('text'):
    output_text += ET.tostring(child, encoding="unicode")

>>>output_text
>>>"
This is some text that I want to read
"

A: Above solutions will miss initial part of your html if your content begins with text. E.g.
<root><text>This is some text that I want to read</text></root>

You can do that:
node = root.find('text')
output_list = [node.text] if node.text else []
output_list += [ET.tostring(child, encoding="unicode") for child in node]
output_text = ''.join(output_list)


Q: Creating a REST API with MySQL and PHP formatted as a JSON response I'm trying to create a public REST API from scratch without using any framework and I've created where it retrieve all the data as JSON response when the user enter in this at the end of the address "...?list=all" However, I want to  retrieve a row by an ID or retrieving the most popular items. I know that I will probably have to change that in the query string, but how would I create the end of the address that retrieves it? like ?ID=05 (retrieving row ID 5 from database) or TOP=15 (retrieving top popular 15). If there's a better or more efficient way to rewrite my code, feel free to let me know.
<?php
    // Check Connection
if(!($db = mysqli_connect($server, $user, $password, $database))) {
    die('SQL ERROR: Connection failed: '.mysqli_error($db));
    exit;
    }
return $db;
}

    //call the passed in function
if(function_exists($_GET['list'])) {
    $_GET['list']();
}

    //methods
function all(){
    $db = getMysqlDB();
    $query = "SELECT * FROM books;";
    $books_sql = mysqli_query($db, $query);
    $books = array();
    while($book = mysqli_fetch_array($books_sql)) {
        $books[] = $book;
    }
    $books = json_encode($books);
    echo $_GET['jsoncallback'].$books;
 }
?>

A: A simple start for a PHP based REST API would be:
<?php

// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);

// connect to the mysql database
$link = mysqli_connect('localhost', 'user', 'pass', 'dbname');
mysqli_set_charset($link,'utf8');

// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;

// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
  if ($value===null) return null;
  return mysqli_real_escape_string($link,(string)$value);
},array_values($input));

// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
  $set.=($i>0?',':'').'`'.$columns[$i].'`=';
  $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}

// create SQL based on HTTP method
switch ($method) {
  case 'GET':
    $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
  case 'PUT':
    $sql = "update `$table` set $set where id=$key"; break;
  case 'POST':
    $sql = "insert into `$table` set $set"; break;
  case 'DELETE':
    $sql = "delete `$table` where id=$key"; break;
}

// excecute SQL statement
$result = mysqli_query($link,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error());
}

// print results, insert id or affected row count
if ($method == 'GET') {
  if (!$key) echo '[';
  for ($i=0;$i<mysqli_num_rows($result);$i++) {
    echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
  }
  if (!$key) echo ']';
} elseif ($method == 'POST') {
  echo mysqli_insert_id($link);
} else {
  echo mysqli_affected_rows($link);
}

// close mysql connection
mysqli_close($link);

source
For a more complete implementation check out:
https://github.com/mevdschee/php-crud-api
Disclosure: I am the author.


Q: MongoDB java drivers not compatible in Android I am trying to delete a document from MongoDB (database present at http://mlab.com) through my Android application, but since mongo-db-java-drivers are not compatible with Android so therefore I am getting different Exceptions. So please tell is there any way to delete from MongoDB through Android application?


Q: How do I get the text decoding of the Chinese? Python in the Chinese part of the result of requests.get (url) is
"æ ?? ¯ä¸? Ç§? Å? ¯ä» ¥ è ?? ªç? ± å? ¼å? ¸ç? ??? Æ ???? è§? ï¼ "
came out in this way.
How it is necessary to decode Can you print Chinese characters?
In the following method, source and other statements will be output.

*

*result.content.decode("gbk","ignore").encode("utf-8","ignore")

*content.encode('utf-8').decode('gbk')

Example of a site is here. https://lvyou.baidu.com/notes/20fd27d671563fe1e8927d21?sid=9739db6e97289b7e6b22f9ea?request_id=831992042&idx=0
Let us know would really appreciate.

A: The problem has been resolved.
Set the encoding option in requests, we were able to obtain the required value.
Thank you very much.
sub_result = requests.get(sub_url)
sub_result.encoding = 'utf-8'
sub_soup = BeautifulSoup(sub_result.text, 'lxml')


Q: JUnit @After not executing when Jenkins pipeline is stopped I'm working with a declarative Jenkins pipeline that runs some tests which make use of JUnit 4. In the tests there are @After methods where test cleanup occurs. When a pipeline is aborted during a test I've confirmed that the @After methods are never executed (confirmed using log statements in the @After methods and checking the Jenkins console log).
This leaves test data (e.g. users that the tests use) in a bad state and cause later tests (and pipeline builds) to fail, so it's an issue.
The pipeline is aborted via the Jenkins UI "stop" button, or through the pipeline hitting a timeout for that stage. In both cases the pipeline exits with code 143, which is a SIGTERM.
How can I ensure that JUnit 4.x @After methods are executed when a declarative Jenkins pipeline is aborted?

A: I have a workaround that you could use to solve the issue. Create two classes. TestClass and AfterClass. In the AfterClass, you will have to keep one test method so that after will get triggered. Now, In test execution step of declarative pipeline, you can execute
mvn clean test -PTest

and in the post always of declarative pipeline script, you can execute below maven command
mvn clean test -PCleanup

TestClass:
import org.junit.Test;

public class TestClass
{

    @Test
    public void testClass()
    {
        System.out.println("Test");
    }
}

AfterClass:
@Test
public void beforeCleanUp()
{
    System.out.println("Before Cleanup");
}
@After
public void after()
{
    System.out.println("After");
}

POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>stackovrflw-62492859</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <profiles>
        <profile>
            <id>Test</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>3.0.0-M5</version>
                        <configuration>
                            <test>com.test.junit.classes.TestClass</test>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>Cleanup</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>3.0.0-M5</version>
                        <configuration>
                            <test>com.test.junit.classes.AfterClass</test>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

Note: This is not the actual solution as I do not have much experience on JUnit. But you could use this workaround, if you do not get any proper solution. I will be also trying to find proper solution for you


Q: POST Method not using Params I dont know why the getParams() is not working in my method?
The System.out.println works fine under getHeaders but not under getParams?
    //---------------------------------------POST request with headers---------------------------------------
public void post(String url, final String param1, final String param2, String source) {

    // Request a string response from the provided URL.
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,
            getReponse(source), createMyReqErrorListener()) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<>();
            params.put("loginAlias", "username");
            params.put("loginPassword", "12345");
            System.out.println("Params are: " + params.toString());
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put(ACCEPT, ACCEPT_JSON); //Accepting JSON
            headers.put(AUTH_ID, AUTH_ID_VALUE);
            headers.put(PLATFORM, PLATFORM_VALUE);
            headers.put(CID, "");
            headers.put(DEVICE_TYPE_MOBILE, DEVICE_TYPE_MOBILE_VALUE);
            System.out.println("Headers are: " + headers.toString());
            return headers;
        }
    };
// Add the request to the RequestQueue.
    queue.add(request);
}

I have followed all the Google Volley documentation and tried a couple options on SO but for some reason, this does not work?
Thanks

A: also faced the same issue, Finally I found that there is some issue with volley - JSONObject request. (after few googling!)
the getParams() doesn't invoke because JsonObjectRequest extended JsonRequest which invoke getBody() directly to encoding the constructor second parameter(call requestBody) as contentType, that's why it ignore your getParam() method.
try this solution, it resolved my problem.
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

In activity/fragment do use this
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());

requestQueue.add(jsObjRequest);

Volley JsonObjectRequest Post request not working


Q: Let $A \subset \Bbb R^n$ and $f:A \to \Bbb R$. Show that if $A = \bigcup_{i} B_i$ and $f\mid_{B_{i}}$ is measurable for any $i$ then $f$ is measurable
Let $A \subset \Bbb R^n$ and $f:A \to \Bbb R$. Show that if $A = \bigcup_{i} B_i$ for $B_1, B_2, \dots$  and $f\mid_{B_{i}}$ is measruable for all $i$, then $f$ is measurable.

Since $f\mid_{B_{i}}$ is measurable for all $i$ we have that $E=\{x \in A \mid f\mid_{B_{i}}(x) > a \}$ is measurable for any $i$. Now since this holds for any $i$ $$E= \{x \in A \mid f\mid_{B_{i}}(x) > a \} = \{x \in A \mid f\mid_{\bigcup_i B_{i}}(x) > a \} = \{x \in A \mid f(x) > a \}$$ and so $f$ is measurable. Is the solution here correct?

A: Consider a measurable set $S \subseteq \mathbb{R}$. Then consider that
$\begin{equation}
\begin{split}
f^{-1}(S) &= f^{-1}(S) \cap A \\
&= f^{-1}(S) \cap \bigcup\limits_{i \in \mathbb{N}} B_i \\
&= \bigcup\limits_{i \in \mathbb{N}} f^{-1}(S) \cap B_i \\
&= \bigcup\limits_{i \in \mathbb{N}} f|_{B_i}^{-1}(S)
\end{split}
\end{equation}$
which is a countable union of measurable sets, hence measurable. So $f$ is measurable.
Note that the fact that $A \subseteq \mathbb{R}^n$ is not used here at all, nor is the fact that the codomain of $f$ is $\mathbb{R}$. Any measure spaces could have been used instead.
The key facts which are needed are that intersections distribute over arbitrary unions and that if $X \subseteq Y$, $g : Y \to Z$, $W \subseteq Z$, then $g^{-1}(W) \cap X = g|_X^{-1}(W)$.


Q: Can you put a Canvas instance inside a jQuery gallery? I've made several simple particle and game examples using Canvas and KineticJS and I was thinking about the using a slider like Nivo to show them off. First thoughts are that I would need to redraw each canvas on transition of the slider, but I was just wondering if anyone has tried this already with any success or failures and if it's feasible?

A: Try:
 var mystage = stage.toImage(config);

to convert the canvas to an image, then you can transition images.
But if you want the whole stage saved as an object you just do:
 var json = stage.toJSON();

and that saves your stage for reloading later, which you can do with:
 var stage = Kinetic.Node.create(json, 'container');


Q: Not getting detailed error log for java application on Tomcat on Azure App Service We deployed a java web application (WAR file) onto an Azure App Service with newest Tomcat (8.5). The WAR file is detected by Azure but on startup we are seeing the following in the catalina.date.log

06-Feb-2018 07:57:24.494 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
  06-Feb-2018 07:57:24.512 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.20
  06-Feb-2018 07:57:27.697 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [D:\home\site\wwwroot\webapps\myapp.war]
  06-Feb-2018 07:59:16.570 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
  06-Feb-2018 07:59:16.570 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Context [/myapp] startup failed due to previous errors
  06-Feb-2018 07:59:16.629 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [D:\home\site\wwwroot\webapps\myapp.war] has finished in [108,932] ms

We cannot find this log file anywhere. We have set all possible logging settings to verbose. Should this be a separate file or are some logging settings missing?
We also see the follwing row

06-Feb-2018 12:00:43.922 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=D:\Program Files (x86)\apache-tomcat-8.5.20\conf\logging.properties

It is not possible for us to change this file.

A: Azure Web services are deployed to a Windows Server 2016.
You can access the log files and change the location of the log files using

*

*Open the url https://<app service name>.scm.azurewebsites.net/DebugConsole {or choose Menu > Debug Console  > CMD)

*Type the dir command to go the location of the tomcat install. For example dir D:\Program Files (x86)\apache-tomcat-8.5.6\conf

*Alternatively you can also click on the folder name dispalyed above the command/terminal

*In your case, to enable detailed logging, open logging.properties under \Program Files (x86)\apache-tomcat-8.5.6\conf and set 1catalina.org.apache.juli.FileHandler.level = FINE. You can read more info at Documentation on Apache Tomcat 8.5 Logging
Sample screen from my Tomcat setup as a webservice:


Q: Directive with  and indirection I have several multi-selects on a page, each with a bit of logic that fills that multi-select from the server, and I want to wrap each one up into a Directive.
Before trying to wrap these into Directives, I built each as such:
index.html
<select name="groups" ng-model="inputs.groups" ng-change="groupsChanged()" ng-options="g for g in allgroups" multiple></select>

controllers.js
In the first pass, I do my $http calls from here. Yes, I know, not best practices, but I wanted to prove that this works to myself first.
  $scope.loadSelect = function(_url) {
    $http({
      url: _url,
      method: 'POST',
      data: $scope.inputs,
      model: 'all' + _url
    }).success(function(data, status, headers, config) {
      $scope[config.model] = data;
    });
  };

  // Fill groups
  $scope.loadSelect('groups');

  // When groups change, reload other select fields that depend on groups
  $scope.groupsChanged = function() {
    $scope.loadSelect('categories');
    $scope.loadSelect('actions');
  }

Now I want to migrate this to a Directive. I see two major challenges:
1.) How do I encapsulate the entire set of options (e.g. what is now the "allgroups" model) into the Directive?
2.) Based on initial experiments, I tried to physically build the <select/> into the template, but realized that I have to manipulate the DOM to physically replace name, ng-model, and ng-options. That lead me to the compile attribute, but a.) that feels wrong and b.) setting <select ng-options="x for x in allgroups" /> doesn't actually repeat after it's been inserted into the DOM.  Using compile doesn't feel right; what's the right way to approach this?
Here is my first attempt at the Directive looks like this. It doesn't really work, and I think I'm going about it incorrectly:
index.html
<dimension ng-model="inputs.users" alloptions-model="allusers">Users</dimension>

directives.js
directive('dimension', function() {
  return {
    restrict: 'E',
    scope: {
      ngModel: '=',
      alloptionsModel: '='
    },
    template:
        '
' +
          '' +
          '<fieldset>' +
              '
' +
                '<select ng-model="{{ngModel}}" ng-options="x for x in {{alloptionsModel}}" multiple class="form-control"></select>' +
              '
' +
           '</fieldset>' +
        '
',

    replace: true,
    transclude: true
  };
});

Clearly I haven't even gotten to the server load part yet, but I plan to roll that into a controller in the Directive, with the actual $http call in a service.
I feel like I'm moving down the wrong track. If you have suggestions on how to realign, please help!

A: The main problem with your directive is that you can't use mustache binding in ngModel and ngOptions directive because they are evaluated directly. You can directly bind to the scoped property (ngModel and alloptionsModel):
directive('dimension', function() {
  return {
    restrict: 'E',
    scope: {
      ngModel: '=',
      alloptionsModel: '='
    },
    template:
        '
' +
          '' +
          '<fieldset>' +
              '
' +
                '<select ng-model="ngModel" ng-options="x for x in alloptionsModel" multiple class="form-control"></select>' +
              '
' +
           '</fieldset>' +
        '
',
    replace: true,
    transclude: true
  };
});

See this plunkr for a working example.
Edit
As for the compile route, there is nothing wrong with it. It is useful when you need to dynamically create a template which will clearly be your case when you will get to the select's item template.
compile: function(tElement, tAttrs) {
  var select = tElement.find('select'),
      value = tAttrs.value ? 'x.' + tAttrs.value : 'x',
      label = tAttrs.label ? 'x.' + tAttrs.label : 'x',
      ngOptions = value + ' as ' + label + ' for x in alloptionsModel';

      select.attr('ng-options', ngOptions);
}

// In the HTML file
<dimension ng-model="inputs.users"
           alloptions-model="allusers"
           label="name">
  Users
</dimension>

I've updated the plunkr with the compile function.


Q: Definition of Sheaf The last property that makes a presheaf a sheaf says: Let $U$ be an open set in $X$ such that $U=\bigcup_{j\in J}U_j$.
If $aj \in \mathscr{F}(U_j)$, $j \in J$, satisfies
$\rho_{U_j(U_i\cap U_j)}(a_j)=\rho_{U_i(U_j\cap U_i)}(a_i)$, $i,j \in J$,
then there exists $a \in \mathscr{F}(U)$ such that $a_j=\rho_{UU_j}(a)$.
My question is as follows, $\forall j\in J, \exists a_j \in \mathscr{F}(U_j)$ such that, $\forall i,j \in J, \rho_{U_j(U_i\cap U_j)}(a_j)=\rho_{U_i(U_j\cap U_i)}(a_i)$, then there...
How can there be both variations on $j$ at the same time? It seems to me that the second variation of $j$ (together with the variation of $i$) in $J$ doesn't happen at all.


Q: Using a Logic App Condition To Compare Multiple Values From The Same Field I am trying to setup a condition that compares multiple values in a field. So if the field contains 1,2 3 do this otherwise do something else. As shown in the attached image. However this only goes false if the field contains the first value. If the second or third value is contained it goes true. How can I make it false for all three values?


Q: Horários válidos Tenho um array com vários horários, podendo às vezes ter apenas 4 e outros N vezes.
Preciso pegar apenas alguns registros.
Segue meu código:
$array = array(
      0  => "08:00:00",
      1  => "08:02:00",
      2  => "08:04:00",
      3  => "08:08:00",
      4  => "08:10:00",
      5  => "10:59:00",
      6  => "11:00:00",
      7  => "11:05:00",
      8  => "11:11:00",
      9  => "13:00:00",
      10 => "13:03:00",
      11 => "13:06:00",
      12 => "13:08:00",
      13 => "18:00:00",
      14 => "18:03:00",
      15 => "18:06:00",
      16 => "18:35:00",
      17 => "19:15:00"
);

$auxiliar = null;
foreach ($registros as $indice => $registro) {
    if ($auxiliar === null) {
        $auxiliar = $registro;
        continue;
    }

    $registroAtual   = current($registros); //Registro atual
    $proximoRegistro = next($registros);    //Proximo registro

    //Tem um proximo registro
    if($proximoRegistro){
      //Diferença entre dois horários
      $diffHorarios = $this->calculaTempo($registroAtual, $proximoRegistro);

      //Houve registros no intervalo de 10 minutos
      if($diffHorarios <= '00:10:00'){
        unset($registros[$indice]);
      }
    }
  }

A: Sempre quando for utilizar dados do tipo de Data use as classe DateTime e a classe DateInterval:
$array = array(
    0  => "08:00:00", 1  => "08:02:00", 2  => "08:04:00", 3  => "08:08:00",
    4  => "08:10:00", 5  => "10:59:00", 6  => "11:00:00", 7  => "11:05:00",
    8  => "11:11:00", 9  => "13:00:00", 10 => "13:03:00", 11 => "13:06:00",
    12 => "13:08:00", 13 => "18:00:00", 14 => "18:03:00", 15 => "18:06:00",
    16 => "18:35:00", 17 => "19:15:00");

function result_time_array(array $values)
{
    $index = 0;
    $c = date_create_from_format('H:i:s', $values[0]);
    $agr[$index][] = $values[0];
    for ($i = 1; $i < count($values); $i++)
    {
        $d = date_create_from_format('H:i:s', $values[$i]);
        $diff = $c->diff($d);
        if (!($diff->i <= 10 && $diff->h === 0))
        {
            $index++;
        }
        $c = date_create_from_format('H:i:s', $values[$i]);
        $agr[$index][] = $values[$i];
    }
    $st = 'e';
    $index = 0;
    foreach ($agr as $key => $value)
    {
        if ($st === 'e')
        {
            $result[$index][$st] = $value[0];
            $st = 's';
        }
        else if ($st === 's')
        {
            $result[$index][$st] = end($value);
            $st = 'e';
            $index++;
        }
    }
    return $result;
}

var_dump(result_time_array($array));

Saida:
array(3) {
  [0]=>
  array(2) {
    ["e"]=>
    string(8) "08:00:00"
    ["s"]=>
    string(8) "11:11:00"
  }
  [1]=>
  array(2) {
    ["e"]=>
    string(8) "13:00:00"
    ["s"]=>
    string(8) "18:06:00"
  }
  [2]=>
  array(2) {
    ["e"]=>
    string(8) "18:35:00"
    ["s"]=>
    string(8) "19:15:00"
  }
}

PHP Sandbox


Q: How to pass input html data to a javascript function as its variables and get a response My problem: I can't get to pass the input data from html to js function as its variables and get the appropriate response.
My goal: when the user clics on submit button he receives whatever response the js function provided.
I have two files in the same directory:
- index.html
- index.js
index.js content:
function quEq(a, b, c) {
var delta = (b ** 2) - (4 * a * c);
  if (a == 0) {
  return "Not a quadratic equation";
  };
if (delta < 0) {
    return "Complex root! No solution in real numbers";
    } else {
        var first= (-b + Math.sqrt(delta)) / (2*a);
        var second= (-b - Math.sqrt(delta)) / (2*a);
        return {first, second};
        };
};

index.html content:
    <!doctype html>

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

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

    <title>Quadratic Equation</title>

                  <form>

                      Enter 'a' value
                      <input type="number" class="form-control" id="a" placeholder="1">
                      Enter 'b' value
                      <input type="number" class="form-control" id="b" placeholder="5">
                      Enter 'c' value
                      <input type="number" class="form-control" id="c" placeholder="6">
                      <button onclick="quEq(document.getElementById('a').nodeValue, document.getElementById('b').value, document.getElementById('c').value)" type="submit" class="btn btn-primary">Submit</button>

                  </form>

THANK YOU FOR YOUR HELP
I HOPE I AM NOT BREAKING ANY RULES

A: Your onclick event handler should successfully handle the click event, but it isn't clear what you want to do with the return value of your function. The browser will not do anything by default. Instead, you need to manage this yourself.
For example, you could write the results into some other part of the DOM.
In your HTML you can create some nodes to hold the output:

Then in your event handler:
document.getElementById('result-1').innerText = first;
document.getElementById('result-2').innerText = second;

A: You have a variety of HTML and JavaScript syntax errors.
See comments in the code below:

// Get references to the DOM elements that you'll work with
var btn = document.querySelector("button");
var a = document.getElementById('a');
var b = document.getElementById('b');
var c = document.getElementById('c');

// Do event binding in JavaScript, not with inline HTML attributes
btn.addEventListener("click", function(){
  // Use "value", not "nodeValue"
  quEq(a.value, b.value, c.value);
});

function quEq(a, b, c) {
  // Carefull with syntax!
  var delta = (b * 2) - (4 * a * c);
  if (a == 0) {
    // return doesn't show up anywhere
    alert("Not a quadratic equation");
  } else if (delta < 0) {
    alert("Complex root! No solution in real numbers");
  } else {
    var first= (-b + Math.sqrt(delta)) / (2*a);
    var second= (-b - Math.sqrt(delta)) / (2*a);
    alert(first + " " + second);
  }
}
<!doctype html>

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

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

    <title>Quadratic Equation</title>

                  <form>

                      Enter 'a' value
                      <input type="number" class="form-control" id="a" placeholder="1">
                      Enter 'b' value
                      <input type="number" class="form-control" id="b" placeholder="5">
                      Enter 'c' value
                      <input type="number" class="form-control" id="c" placeholder="6">
                      <button type="button" class="btn btn-primary">Submit</button>

                  </form>

A: I see two flaws in this code
1)
document.getElementById('a').nodeValue

instead of
document.getElementById('a').value

2) you should be aware that placeholder is just a text, it seems strange that you can see 6 but there's no number yet, so instead of placeholder set value attribute directly if you want some default numbers
<input type="number" class="form-control" id="a" value="1">

A: Now its working
  a: <input type="number" name="a" id="a">

  b: <input type="number" name="b" id="b">

  c: <input type="number" name="c" id="c">

  <button onclick="quEq(document.getElementById('a').value,document.getElementById('b').value,document.getElementById('c').value)">Submit</button>

A: There are a couple of things in your index.html file that are not correct, for example, you opened a second div with a class "form-group" yet you did not close it, also you did not pass properly the value for "a" (.nodeValue when it should be .value).
I made some changes to your code and appended the response in the div you weren't using (the second "form-group") and changed it's name, also I added type="button" to your button so it won't submit as soon as you click on it, you can find the html and js in codepen
Here is your function:
function quEq() {
 var a = document.getElementById('a').value
 var b = document.getElementById('b').value
 var c = document.getElementById('c').value

 var delta = (b ** 2) - (4 * a * c)

 if (a == 0) {
  document.getElementsByClassName("info")[0].innerHTML = "Not a quadratic equation"
 }

 if (delta < 0) {
    document.getElementsByClassName("info")[0].innerHTML = "Complex root! No solution in real numbers"
 }
 else {
   var first= (-b + Math.sqrt(delta)) / (2*a)
   var second= (-b - Math.sqrt(delta)) / (2*a);
   document.getElementsByClassName("info")[0].innerHTML = first + ", " + second
 }
}

Here is your div changed:

                <form>

                        Enter 'a' value
                        <input type="number" class="form-control" id="a" placeholder="1" value="1"/>

                        Enter 'b' value
                        <input type="number" class="form-control" id="b" placeholder="5" value="5" />

                        Enter 'c' value
                        <input type="number" class="form-control" id="c" placeholder="6" value="6" />

                        <button onclick="quEq()" type="button" class="btn btn-primary">Submit</button>

                </form>


Q: Per-character-set font size in Firefox not working? Firefox has a setting (Preferences -> Content -> Fonts & Colors -> Advanced) that is supposed to let you set font preferences for different character sets.  I've tried setting larger minimum font sizes for some non-Western character sets (I'm still learning, and have to see extra detail to tell them apart!) and nothing seems to happen.  For example, if there's Hangul on a page (like this one), it will show in the same size as the Latin characters around it, even if I set "minimum font size" to 24.
Am I misunderstanding how that setting is supposed to work, or does it just not do anything?  Is there any other way to blow up only non-Western characters while leaving the letters I know how to read intact?

A: This feature appears to be for when a page is in a specific character encoding, not for all characters of a specific language type on a page.
The majority of sites displaying mostly latin characters while allowing the usage of non-latin characters use UTF-8 as the character encoding which is considered Western (it may be possible to change this). Wikipedia uses UTF-8 so the entire page you linked used the Western settings.
If you go to a site using a non-latin character encoding such as www.2chan.net which uses Shift_JIS, then setting the minimum font size for Japanese works and effects the entire page.
For the specific usage you are wanting, this should be possible using a browser addon or userscript that detects characters of specific languages and alters their styling. The Firefox plugin Rikaichan shows that this is possible because it adds a mouseover highlight style and tooltip popup to foreign words. I am not aware of any addon or userscript that does exactly what you want but they could exist already.


Q: "All else equal" Looking for a way to articulate "holding all else equal." In my context, I'm writing about economists' (unrealistic) love for holding all else equal

A: Economists like to use the Latin phrase:
ceteris paribus - other things equal.
https://economictimes.indiatimes.com/definition/ceteris-paribus


Q: "Book like" view in Openseadragon (several "2 pages" sequences) Openseadragon newbbie here !
I'm trying to display images by group of 2 AND keeping sequence mode activated, so I can "turn pages".
I managed to display 2 pages, I managed to read pages 1 by 1 in sequence mode, ...
But I just didn't find a way to do both.
To display 2 pages, I loaded 2 tiles sets and configured "sequenceMode=false". Then I set coordinates, to display visuals aside.
To read pages 1 by 1, I loaded several tiles and configured "sequenceMode = true".
What I would like to do is display two visuals (= tiles sets) aside (like an open book). And then, on "next" button click, display the two next visuals from my "tilesSources" array... and so on !
Thank you for your help !

A: I recommend keeping sequence mode off, like you did for the two pages, and lay out the entire sequence (in pairs) that way. You should then create your own next/previous buttons and use viewer.viewport.fitBounds to animate the viewer to each pair as needed.
Here's an example of a system that does something like that (plus a lot more):
https://iangilman.com/osd/test/demo/m2/
Press the "book" button at the top to see the "two-page" mode. The code for this is here:
https://github.com/openseadragon/openseadragon/tree/master/test/demo/m2
Of course you don't need all of that code, but hopefully it can be a helpful reference.


Q: move camera with player [unity] using System.Collections.Generic;
using UnityEngine;

public class follow_mainship : MonoBehaviour
{
    public Transform Playerposition;
    private Vector3 cameraoffset;
    // Start is called before the first frame update
    void Start()
    {
        cameraoffset = Playerposition.position - transform.position;

    }

    // Update is called once per frame
    void Update()
    {
        Vector3 newpos = Playerposition.position + cameraoffset;
    }
}

I am using this code to move camera with my player, but it is not working. I have added my object in the Playerposition box. What should I do?
Update:
As per the answer, camera is following my ship, whenever the ship touches the ground, the camera flies back a long distance. Is there any way to fix it?

A: Your logic to get the new position is correct, but in your Update() function, you have to update the position of the camera using transform.position, assuming this script is a component you have added to the Camera in the scene.
// Update is called once per frame
void Update()
{
    Vector3 newpos = Playerposition.position + cameraoffset;
    transform.position = newpos;
}

If this script isn't on the camera, you'll need a reference to the camera by taking it as an input in the Unity inspector (declaring public Camera cam; at the top of your class) and then set in in the inspector by dragging the camera object onto that input. Then you can do cam.transform.position = newpos; in Update().


Q: PhoneGap/Cordova blank screen on pause/resume I have a simple html/javascript app that starts and works up fine on an Android device. However, when the app is put in background by using the 'home button' and then brought back to the foreground by clicking on the app again - it starts with a blank screen (white blank screen on android ) and stays that way until the 'back button' is pressed.
Once the 'back button' is pressed the screen refreshes to the last page displayed by the app.
I am new to PhoneGap and I am sure there is something simple/fundamental that I am missing - in terms of how to handle the 'resume' event/etc.. I have followed the instructions provided on this link by Phil Mitchell http://wiki.phonegap.com/w/page/35501397/Tutorials (which is a great resource btw..)
Thanks.
Update :
After looking at the DroidGap code, I have tried to add the following line :-
        super.setBooleanProperty("keepRunning", false);

But this does not seem to help. I am happy for the app to exit every time the home button is entered and then do a full restart when the app is clicked on the mobile.
Any help is much appreciated..

A: I was having the same problem and I want to share a hack that worked for me.
My app is based on ionic/angular/cordova and the android version was giving me a white screen around 50% the times on pause/resume.
When it happened, tapping anywhere on the screen or hitting the back button would make the screen to render again just fine.
I added a div tied to a scope variable named random, like this:
  <body ng-app="starter" id="body">
    <div>{{ random }}</div>
    <ion-nav-view>
    </ion-nav-view>
  </body>

Then I added a listener inside my app.js to capture the resume event fired by cordova, to then change the random variable and call $apply(), like this:
document.addEventListener("resume", function() {
  angular.element(document.querySelector('#body')).scope().random = Math.random();
  angular.element(document.querySelector('#body')).scope().$apply();
})

Since the ion-nav-view takes over the whole screen that div never shows up, but angular doesn't know that and refreshes the page, causing the whole thing to work.
(I tried to tie the variable to an invisible element but then angular doesn't refresh the page)
I hope this helps someone!

A: There seem to be issues around rendering the pages thru PhoneGap and 'Dialog'ing thru Client side FB authentication flow using the JS SDK. If I disable the client side authentication, then the rendering and display of the page works very well, when the app is brought to foreground from background (pause/resume/etc).
I am assuming that the page will need to sense that it is being displayed over a mobile device and use the IOS or Androi SDK for client side authentication.. (if/when I get around to testing that, I update the answer - if there is anybody who has any more light to shed, please feel free to embellish).

A: If you still say "I am happy for the app to exit every time the home button is entered and then do a full restart when the app is clicked on the mobile." then go for it.
@Override
protected void onStop(){
super.onStop();
}

Try this from where you create activity or from the class which "extends DroidGap".


Q: Javascript check to see if an event has already been fired or clicked I have a function that needs to fire when I click on a chevron tab.  However I only need that function to fire that first time we load the page.  How can I prevent it form firing every time the tab is clicked?
    $('#navi a').bind('click',function(e){
        var $this   = $(this);
        var prevButton  = current;
        $this.closest('ul').find('li').removeClass('selected');

        if ( $(this).attr('id') == 'tab2')
        {
            //fire function only once
        }

    });

A: Use the .one binding instead. This will attach it to fire on the first click and remove itself.

A: In case you need only part of your event handler to run once :
$("div").on("click",function(){
    if (!$(this).data("fired")) {
        console.log("Running once");
        $(this).data("fired",true);
    }

    console.log("Things as usual");
});

Demo

A: Use:
var isalreadyclicked=false;
  $('#navi a').bind('click',function(e){
    var $this   = $(this);
    var prevButton  = current;
    $this.closest('ul').find('li').removeClass('selected');

    if ( $(this).attr('id') == 'tab2')
    {
    if(!isalreadyclicked){
        //fire function only once
    isalreadyclicked=true;
    }
    }

  });


Q: Derivative of the determinant Let $A\in\mathbb{R}^{n\times n}$ be an invertible matrix, $T\in\mathbb{R}^{n\times n}$ arbitrary.

Show $$(\det)'(A)(T)=\det(A)\operatorname{tr}(A^{-1}T)$$

Fist I need to determine $(\det)'(I)(T)=\lim_{\epsilon\to 0}\frac{\det(I+\epsilon T)-\det(I)}{\epsilon}$ and then use chain rule.
I have found many identical questions and a similar proof on Wikipedia https://en.wikipedia.org/wiki/Jacobi%27s_formula#Derivation (via chain rule) but I don't understand them. Why is $\lim_{\epsilon\to 0}\frac{\det(I+\epsilon T)-\det(I)}{\epsilon} = \operatorname{tr}(T)$? Thank you!

A: The key is to consider the polynomial $\det(I + \epsilon T)$. One way to get its linear term is to consider its relation to the characteristic polynomial. In particular, we have
$$
\det(I + \epsilon T) = \det(\epsilon \cdot [\epsilon^{-1} I -(-T)]) = \epsilon^n \det(\epsilon^{-1} I - (-T)).
$$
If the characteristic polynomial of $-T$ is $p(t) = \det(tI - (-T))$, then $\det(I + \epsilon T) = \epsilon^n p(\epsilon^{-1})$. Notably, this is simply the polynomial whose coefficients are the coefficients of $p$ in reverse order. Because the coefficient of $t^{n-1}$ in $p(t)$ is $\operatorname{tr}(T)$, it follows that the coefficient of $\epsilon^1$ in $\epsilon^{n}p(\epsilon^{-1})$ is also $\operatorname{tr}(T)$.
Alternatively, you can derive this fact directly using the Leibniz formula for the determinant $\det(I + \epsilon T)$.


Q: addClass function working properly but removeClass function not working on input text field for form? Creating an Online form and I'd like only the field that the user is focused on to be notfaded so i decided to add some jQuery to my form but the remove class function is not working. addClass works when I click into a field it shows brightly and not faded as it adds the Focused class but as soon as I click away or am no longer focused on that field the Focused class remains.
I've seen some similar posts but the solutions on the other posts don't seem to pertain to my issue.
Below is my form
<form name="contactform" method="post">

Name *

Please provide your full name
<input type="text" maxlength="100" class="form-control discuss" name="projectname">

    <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">

</form>

Below is my jQuery
$(document).ready(function(){
   $('input[type="text"]').on('focus', function() {
       $('.inputFaded').addClass('Focused');
   });

   $('input[type="text"]').off('focus', function() {
       $('.inputFaded').removeClass('Focused');
   });
});

Any help greatly appreciated!
Thanks,

A: You are misunderstanding .off()

Description: Remove an event handler.

So it seems that you need to listen focusin and focusout event.

$(document).ready(function(){
$('input[type="text"]').focusin(function() {
    $('.inputFaded').addClass('Focused');
});

$('input[type="text"]').focusout(function() {
    $('.inputFaded').removeClass('Focused');
});
});
.Focused{
    background-color: #FFFFCC;
}

<form name="contactform" method="post">

Name *

Please provide your full name
<input type="text" maxlength="100" class="form-control discuss" name="projectname">

    <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">

</form>

Updated

$(document).ready(function(){
    $('input[type="text"]').focusin(function() {
        $(this).addClass('Focused');
    });

    $('input[type="text"]').focusout(function() {
        $(this).removeClass('Focused');
    });
});
.Focused{
   border-color: red;
}

<form name="contactform" method="post">

Name *

Please provide your full name
<input type="text" maxlength="100" class="form-control discuss" name="projectname">

    <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">

</form>

A: The .off function is not used for running a function but for removing a function from an Event tied to an element, as already pointed out by @Phong. Instead use the .focusout() function or .on("focusout", ..)
Please note that if this is also quite simple in Vanilla JS:
// Vanilla JS solution
(function(){
  let input = document.querySelector("input[type='text']"),
      inputFaded = document.querySelector(".inputFaded");

  input.addEventListener('focus', function() {
    console.log("focused now!");
    inputFaded.classList.add('Focused');
  });

  input.addEventListener('focusout', function(){
    console.log("I will also be run! :)");
    inputFaded.classList.remove('Focused');
  })
})()

$(document).ready(function(){
    $('input[type="text"]').on('focus', function() {
        console.log("focused now!");
        $('.inputFaded').addClass('Focused');
    });

    // Removing function from focus event that does not exist as a function to an eventlistener
    $('input[type="text"]').off('focus', function() {
        console.log("I will never be run? :(");
        $('.inputFaded').removeClass('Focused');
    });

    // adding focusout eventlistener
    $('input[type="text"]').on('focusout', function() {
        console.log("I will be run! :)");
        $('.inputFaded').removeClass('Focused');
    });

    // alternative way of adding focusout eventlistener
    $('input[type="text"]').focusout( function() {
        console.log("I will also be run! :)");
        $('.inputFaded').removeClass('Focused');
    });

});

<form name="contactform" method="post">

Name *

Please provide your full name
<input type="text" maxlength="100" class="form-control discuss" name="projectname">

    <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">

</form>

A: You can also try like this :
$(document).ready(function(){
  $("input").focus(function(){
    $('.inputFaded').addClass('Focused');
  });

   $("input").on('blur', function() {
    $('div').removeClass('Focused');
  });

});


Q: Trying to get Azimuth difference in a loop I have a micropython program on a ESP32 connected to a stepper motor via a driver board.
The software runs in a while true loop. I'm trying to get the azimuth difference between 30 second previous azimuth reading and the post 30 second azimuth reading, then send the difference to the stepper motor. Unfortunately they will not let me post all my code, so here is a small example.....
import math
import time
import Stepper
from machine import Pin
s1 = Stepper.create(Pin(26,Pin.OUT),Pin(25,Pin.OUT),Pin(33,Pin.OUT),Pin(32,Pin.OUT),
delay=2)

while True:

   xxxxx loop in here I have working code that updates the Azimuth of the sun in
   realtime every 30 seconds XXXXXXX

   s1.angle(azimuth, -1)

   time.sleep(30)


Q: Simple slopes test for merMod object with R package interactions (jtools) I'm trying to conduct a simple slopes analysis for a mixed effects model obtained with lmer.
The model is similar to the following:
data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)

When trying to conduct a simple slopes analysis with the function sim_slopes in the package interactions, I obtain the following error message.
interactions::sim_slopes(model=mod, pred=age, modx=Sex)

Error: One of the requested columns does not exist.
  Backtrace:
  1. interactions::sim_slopes(model = mod, pred = age, modx = Sex)
  5. jtools:::summ.merMod(...)
  6. jtools:::create_table(...)
  In addition: Warning message:
  Johnson-Neyman intervals are not available for factor moderators.

Would any one have any thoughts on what the problem might be?
Note that it works well with the package reghelper, but I need p values for these tests, which reghelper does not provide.
reghelper::simple_slopes(mod)

The output of sessionInfo() is:

R version 3.6.0 (2019-04-26)
  Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 18.04.2
  LTS
Matrix products: default BLAS:
  /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 LAPACK:
  /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1
locale:  [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C
  LC_TIME=en_CA.UTF-8         [4] LC_COLLATE=en_CA.UTF-8
  LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8     [7]
  LC_PAPER=en_CA.UTF-8       LC_NAME=C                  LC_ADDRESS=C
  [10] LC_TELEPHONE=C             LC_MEASUREMENT=en_CA.UTF-8
  LC_IDENTIFICATION=C
attached base packages: [1] stats     graphics  grDevices utils
  datasets  methods   base
loaded via a namespace (and not attached):
  [1] Rcpp_1.0.1        magrittr_1.5       splines_3.6.0      MASS_7.3-51.1
  [5] munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38    rlang_0.3.4
  [9] minqa_1.2.4        plyr_1.8.4         tools_3.6.0       grid_3.6.0
  [13] gtable_0.3.0       nlme_3.1-140       cli_1.1.0          assertthat_0.2.1
  [17] digest_0.6.19      lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2
  [21] crayon_1.3.4       Matrix_1.2-17      reghelper_0.3.4    nloptr_1.2.1
[25] ggplot2_3.1.1      interactions_1.1.0 jtools_2.0.1       pander_0.6.3
  [29] compiler_3.6.0     pillar_1.4.1       scales_1.0.0       boot_1.3-20
  [33] pkgconfig_2.0.2

A: (Not an answer but way too long for a comment.  Will delete later if appropriate.)
In a clean R session, this works for me:
data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)
interactions::sim_slopes(model=mod, pred=age, modx=Sex)
sessionInfo()

SIMPLE SLOPES ANALYSIS
  Slope of age when Sex = Female:
   Est.   S.E.    t val.      p
  ------ ------ -------- ------
   0.48   0.09     5.13   0.00
  Slope of age when Sex = Male:
   Est.   S.E.   t val.      p
  ------ ------ -------- ------
    0.78   0.08    10.12   0.00
  Warning message:
  Johnson-Neyman intervals are not available for factor moderators.

Here is my sessionInfo(): the important stuff looks the same as yours (lme4 1.1-21, interactions 1.1.0, jtools 2.0.1), but it's certainly not identical ... ??
R Under development (unstable) (2019-05-21 r76566)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.6 LTS

[matrix product and locale info deleted]

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1         magrittr_1.5       splines_3.7.0      MASS_7.3-51.4
 [5] tidyselect_0.2.5   munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38
 [9] R6_2.4.0           rlang_0.3.4        minqa_1.2.4        plyr_1.8.4
[13] dplyr_0.8.1        tools_3.7.0        grid_3.7.0         gtable_0.3.0
[17] nlme_3.1-140       cli_1.1.0          digest_0.6.19      assertthat_0.2.1
[21] lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2       numDeriv_2016.8-1
[25] crayon_1.3.4       Matrix_1.2-17      purrr_0.3.2        nloptr_1.2.1
[29] ggplot2_3.1.1      jtools_2.0.1       interactions_1.1.0 glue_1.3.1
[33] pander_0.6.3       compiler_3.7.0     pillar_1.4.1       scales_1.0.0
[37] lmerTest_3.1-0     boot_1.3-22        pkgconfig_2.0.2

A: I solved the problem by detaching lmerTest.


Q: Next Js - Providers/getProviders() - FetchError - next build I am trying to build my application next js.
I use providers with next-auth.
It works fine when I use npm run dev.
But when I use npm run build I get this:

However, I use the variable NEXTAUTH_URL = localhost: 3000 in a .env.local
The error appears when I have "getProviders ()" in a file like this:

import {getProviders, useSession} from 'next-auth/client'
import Layout from "../components/layout";

export default function Page({providers}) {
    const [session, loading] = useSession()

    return (
        <Layout providers={providers}>Page index</Layout>
    )
}

export async function getStaticProps() {
    const providers = await getProviders()

    return {
        props: {providers}
    }
}

A: I think same probrem this.
ECONNREFUSED during 'next build'. Works fine with 'next dev'
It is working.
import {getProviders, useSession} from 'next-auth/client'
import Layout from "../components/layout";

export default function Page() {
    const [session, loading] = useSession()
    const [providers, setProviders] = useState({});

    useEffect(() => {
      (async () => {
        const res = await getProviders();
        setProviders(res);
      })();
    }, []);

    return (
        <Layout providers={providers}>Page index</Layout>
    )
}


Q: How to get the Description to the product quick view page? I have to display description on product list view page, But I want to display description to click quick view popup page.

plz, check image?

A: To get product description in the quickview pop-up do the following:

*

*Create a new template file (new .phtml file) and place it in your theme directory Vendor/theme/Magento_Catalog/templates/product/view

*In your template file, say quickview-descr.phtml place this code:
 <?php
  // @codingStandardsIgnoreFile
  /**
  * Product description template
  *
  * @var $block \Magento\Catalog\Block\Product\View\Description
  * @var $block \Magento\Catalog\Block\Product\View\Attributes
  */
  ?>

<?= /* @escapeNotVerified */ $this->helper('Magento\Catalog\Helper\Output')->productAttribute($block->getProduct(), $block->getProduct()->getShortDescription(), 'short_description') ?>

*You can use
->getDescription(), 'description'

For the full product description.

*Then, you need to locate your theme's XML layout file for the quick view feature.
Say, it may be located in your parent theme (if you're using a child theme) Magento_Catalog/layout or it may be located in something like Customtheme_Quickview/layout

The layout name will be similar to: quickview_product_view.xml
In the layout file, find
 <container name="product.info.main"> or <container name="product.info.details">

and locate the position within the quick view page layout where you want to place the product description.
Say, you may want to place it under the product title container
 <block class="Magento\Theme\Block\Html\Title" name="page.main.title" template="html/title.phtml"/>

*Call your template file from the quick view layout at the desired location:
 <block class="Magento\Catalog\Block\Product\View\Description" name="product.info.details" template="product/view/quickview-descr.phtml" after="page.main.title" />

Save. Clear cache
php bin/magento cache:flush


Q: How to simplify exponential of a matrix into Cosine and Sine Hyperbolic terms? In Peskin and Schroeder book "An Introduction to QFT" there is an equation (eq. 3.48):

I know that exp(x)=cosh(x)+sinh(x). But, I couldn't understand how the above equation is obtained. Any help is welcome.
Also why is the above matrix chosen for boost from four momentum (m,0) to (E,p^3)?

A: Consider Taylor expansion of an exponent and even and odd powers of the matrix under the exponent.

A: You don't even need to consider the series: for any function $f$ of any variable $x$ (scalar, vector, matrix, operator...) taking its value in any vector space, you always have the even/odd decomposition:
$$f(x) = \frac{f(x)+f(-x)}{2}+ \frac{f(x)-f(-x)}{2}.$$
If $f$ is the exponential function, the first term on the right hand side above is called $\cosh$ and the second term is called $\sinh$.


Q: How to set radio button selected value using jquery How to set radio button selected value in javascript:
HTML Code :
<input type="radio" name="RBLExperienceApplicable" class="radio" value="1" >
<input type="radio" name="RBLExperienceApplicable" class="radio" value="0" >

<input type="radio" name="RBLExperienceApplicable2" class="radio" value="1" >
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="0" >

ASPX Code
     <asp:RadioButtonList ID="RBLExperienceApplicable" runat="server" class="radio"    RepeatDirection="Horizontal" EnableViewState="false">
            <asp:ListItem Value="1" Text="Yes   "></asp:ListItem>
                <asp:ListItem Value="0" Text="No"></asp:ListItem>
        </asp:RadioButtonList>

     <asp:RadioButtonList ID="RBLExperienceApplicable2" runat="server" class="radio"  RepeatDirection="Horizontal" EnableViewState="false">
            <asp:ListItem Value="1" Text="Yes   "></asp:ListItem>
                <asp:ListItem Value="0" Text="No"></asp:ListItem>
        </asp:RadioButtonList>

// Some Code Fetch from db
// Based on db value script block will execute
 <script type="text/javascript">
        RadionButtonSelectedValueSet('1');
 </script>

Script Block :
function RadionButtonSelectedValueSet(SelectdValue) {
    $('#RBLExperienceApplicable').val(SelectdValue);
        //$("input[name='RBLExperienceApplicable']:checked").val(SelectdValue);
}

A: Try
function RadionButtonSelectedValueSet(name, SelectdValue) {
    $('input[name="' + name+ '"][value="' + SelectdValue + '"]').prop('checked', true);
}

also call the method on dom ready
<script type="text/javascript">
jQuery(function(){
    RadionButtonSelectedValueSet('RBLExperienceApplicable', '1');
})
</script>

A: You can try this also
function SetRadiobuttonValue(selectedValue)
{
  $(':radio[value="' + selectedValue + '"]').attr('checked', 'checked');
}

A: You can do more elegantly.
function RadionButtonSelectedValueSet(name, SelectedValue) {
    $('input[name="' + name+ '"]').val([SelectedValue]);
}

A: Below script works fine in all browser:
function RadionButtonSelectedValueSet(name, SelectdValue) {
     $('input[name="' + name + '"][value="' + SelectdValue + '"]').attr('checked',true);
}

A: $('input[name="RBLExperienceApplicable"]').prop('checked',true);

Thanks dude...

A: If the selection changes, make sure to clear the other checks first. al la...

$('input[name="' + value.id + '"]').attr('checked', false);
$('input[name="' + value.id + '"][value="' + thing[value.prop] + '"]').attr('checked',  true);

A: for multiple dropdowns
$('[id^=RBLExperienceApplicable][value='+ SelectedVAlue +']').attr("checked","checked");

here RBLExperienceApplicable is the matching part of the radio button groups input tag ids.
and [id^=RBLExperienceApplicable] matches all the radio button whose id start with RBLExperienceApplicable

A:   <input type="radio" name="RBLExperienceApplicable" class="radio" value="1" checked >
 //       For Example it is checked
 <input type="radio" name="RBLExperienceApplicable" class="radio" value="0" >

<input type="radio" name="RBLExperienceApplicable2" class="radio" value="1" >
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="0" >

      $( "input[type='radio']" ).change(function() //on change radio buttons
   {

    alert('Test');
   if($('input[name=RBLExperienceApplicable]:checked').val() != '') //Testing value
 {

$('input[name=RBLExperienceApplicable]:checked').val('Your value Without Quotes');

}
    });

http://jsfiddle.net/6d6FJ/1/
Demo

A:   <asp:RadioButtonList ID="rblRequestType">
        <asp:ListItem Selected="True" Value="value1">Value1</asp:ListItem>
        <asp:ListItem Value="Value2">Value2</asp:ListItem>
  </asp:RadioButtonList>

You can set checked like this.
var radio0 = $("#rblRequestType_0");
var radio1 = $("#rblRequestType_1");

radio0.checked = true;
radio1.checked = true;

A: A clean approach I find is by giving an ID for each radio button and then setting it by using the following statement:
document.getElementById('publicedit').checked = true;

A: Can be done using the id of the element
example
<label><input type="radio" name="travel_mode"  value="Flight" id="Flight"> Flight </label>
<label><input type="radio" name="travel_mode"  value="Train" id="Train"> Train </label>
<label><input type="radio" name="travel_mode"  value="Bus" id="Bus"> Bus </label>
<label><input type="radio" name="travel_mode"  value="Road" id="Road"> Other </label>

js:
$('#' + selected).prop('checked',true);

A: This is the only syntax that worked for me
$('input[name="assReq"][value="' + obj["AssociationReq"] + '"]').prop('checked', 'checked');

A: document.getElementById("TestToggleRadioButtonList").rows[0].cells[0].childNodes[0].checked = true;

where TestToggleRadioButtonList is the id of the RadioButtonList.


Q: Spring service periodic task Lets suppose there is spring boot web app with 2 classes mapped as @Controller and @Service. Service is injected into controller's field. I need my service to run task once a second to update some external data. Is there something wrong with this code?
@Component
public class MyService implements Runnable{
    public MyService() {
        new Thread(this).start();
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                // operations here
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

A: Though there are a lot of ways of creating a task, using job or spring task scheduler, below is one straightforward way.
Below task will run every second.
Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            System.out.println("hello");
        }
    }, 0, 1000); // o is delay time after which it starts, 1000 is time interval

Or you may want to refer here to implement spring task scheduler .


Q: How to use a variable to pass a crop string argument to cpdf in bash This question is about how, in bash, one can (and cannot) pass a string—which is contained in a bash variable—as an argument to a binary executable. I am using a particular binary executable, but the question is broader, because we may want to pass string arguments to all kinds of binary executables.
I understand that the behavior described below may turn out to be very special to the binary executable I am calling. But I suspect that what I am describing is a reflection of something basic in how bash works, in which case it could be of interest to a border range of people.
Background
This question arose in the course of me writing a bash script that uses cpdf (link), which is a binary executable. The program cpdf is open source; the source code (in OCaml) is available here.
Basic usage of the binary executable in question
Suppose, in a bash terminal, the working directory contains a one-page pdf file called in.pdf.
Then the following command produces a pdf file called out.pdf containing a cropped window from in.pdf:
cpdf -crop "10pt 10pt 200pt 500pt" in.pdf -o out.pdf

The size of the crop is specified by the string "10pt 10pt 200pt 500pt" (For completeness: if the crop window has its lower-left corner at (x1,y1) and upper-right corner ar (x2,y2), then the string format is x1 y1 x2 y2—plus the units, all enclosed in quote marks.)
Using a variable to pass the crop string
The following will work:
cropstring="10pt 10pt 200pt 500pt"
cpdf -crop "$cropstring"  $filein -o out1.pdf

But the following will not:
cropstring="\"10pt 10pt 200pt 500pt\""
cpdf -crop $cropstring  $filein -o out2.pdf

If you execute the latter, it returns the error message
Bad rectangle specification "10pt

The difference is that in the first case, the enclosing quote marks are not part of the string which is contained in the variable cropstring, while in the second case, they are part of it.
Questions
Is this behavior likely to be very specific to cpdf, or is it reflective of some general properties of bash? If the latter, then two more questions: why doesn't the second way work? Is there a way to define the variable cropstring so that the second way (meaning, all required quote marks are somehow included in the content of the variable) does work?

A: The problem you have here is that cpdf is not a string interpreter like echo or printf and so on. In your case cpdf doesn't know how to interpret your escaped string and when you pass this "so called" variable (cropstring) to cpdf binary you actually tell to bash like this: pass to cpdf script this argument in which you close double-quote and after \"10pt you have a space which means cpdf jump to next argument (input file) and leave away this part of string 10pt 200pt 500pt\" (that means that your script will take 10pt as a single argument and that is unfortunate because your binary script expect other 3 arguments). This is why your binary raise an error because it cannot crop a window having just one argument 10pt. It expects yet 3 arguments in a string.
This is how your binary script will exit (with an error) and tell you that there is a Bad rectangle specification "10pt.
The arguments that you pass to cpdf are good in first example but in the second example are wrong. I described earlier how bash interpret parameters. In the first example your binary script treat cropstring as a string variable and in the second example it will pass only the first argument which is 10pt.
To respond to your answer, it is the way bash interpret strings and your script and not a problem of cpdf binary.
The line in which you write:
cropstring="\"10pt 10pt 200pt 500pt\""
can be interpreted well only by a text interpreter (you can play writing echo -e $cropstring) but NEVER in bash command line. When you pass your variable as an argument to some bash script, bash see your variable like cpdf -crop ""10pt. That's all because the rest of the string will be seen as file.in argument. The error occurs because your string parameter asked by crop argument is just 10pt and thus, the binary doesn't know how to crop that window.


Q: how to split one string in a column into two string pandas I have 2 STRING dataframe, each data is given name as dataset and colloquial.
dataframe colloquial:
|**wrong**  | **correct** |
|sheis      | she is      |
|taht       | that        |
|diedwhen   | died when   |

The second dataframe is dataset with specific column that I use that look like this:
dataframe dataset['review'] :
review
[shewas, wrong, but, her, intentions, are, good]
[is, taht, you]
[he, diedwhen, he, was, young]

I want to change the wrong word in the dataset['review'] into the correct word according to dataframe colloquial. I use this:
normalizad_word = pd.read_excel("colloquial.xlsx")

normalizad_word_dict = {}

for index, row in normalizad_word.iterrows():
    if row[0] not in normalizad_word_dict:
        normalizad_word_dict[row[0]] = row[1]

def normalized_term(document):
    return [normalizad_word_dict[term] if term in normalizad_word_dict else term for term in document]

dataset['review_normalized'] = dataset['review'].apply(normalized_term)

dataset['review_normalized']

BUT the result is like this:
review_normalized
[she was, wrong, but, her, intentions, are, good]
[is, that, you]
[he, died when, he, was, young]

I want it to be like this:
review_normalized
[she, was, wrong, but, her, intentions, are, good]
[is, that, you]
[he, died, when, he, was, young]

A: Change normalized_term function:
def normalized_term(document):
    result = []
    for term in document:
        if term in normalizad_word_dict:
            for word in normalizad_word_dict[term].split(' '):
                result.append(word)
        else:
            result.append(term)
    return result

Or if you want to use inline loop:
import itertools
def normalized_term(document):
    return list(itertools.chain(*[normalizad_word_dict[term].split() if term in normalizad_word_dict else term.split() for term in document]))


Q: resigning the keyboard swift 1.2 So I just updated to swift 1.2 and now my code to resign the keyboard wont work?
the code is:
override func touchesBegan(touches:NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)

the error says Overriding method with selector "touchesBegan:withEvent:" has incompatible type

A: Try replacing NSSet with Set<NSObject>
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

The syntax has been edited in swift 1.2. The NSSet was replaced by Set<NSObject>
See the Blog Post and the Xcode 6.3 release notes


Q: PHP separate acces to some links I have a table in DB where I put all the admins and their rights. I am setting theri rights with letters A-Z and each letter has access to something else. The thing is I want to check where they have access and show links only to those areas. For now I got an idea to put all those letters in some aray with for loop and then when rendering the menu output only those items where they have access with if (in_array(letter, rights)) I think this would work but I would like to know whether there is another way

A: I wrote a PHP class that I use in all my projects that require different access for different roles.  I put a copy of the class out on paste bin: class_role_restrictions.php.
This class also requires another class I wrote, which can be obtained here: better_mysqli.php
The initial setup involves the creation of some database tables (The SQL create statements are found in comments at end of the class_role_restrictions.php file) and adding roles / user memberships via it's admin interface.
Detailed setup/usage can be obtained here: role_restrictions_detailed_example.php
Once it is setup you can use it like this:
<?php

  include_once('class_role_restrictions.php');
  include_once('better_mysqli.php');

  $mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
  if (mysqli_connect_errno()) {
     error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
     exit;
  }

  $role = new role_restrictions($mysqli, 'http://your_server.com/path/to/this/page/example.php');

  // == Restrict an entire page to authorized users only ==
    $role->restrict_to('role_name, to_restrict user_to', 'username_currently_logged_in');
  // .. now do stuff that only users in any of the roles listed are allowed to do

  // -- OR --

  // == Only do certain things if the username given is a member of any of the roles given ==
  if( $role->has_role('a_list, of_roles, allowed', 'username_currently_logged_in') ){
      // .. do stuff that only users in the given role(s) are allowed to do ..
  }

?>


Q: Duplicates removal from different excel files at a time I have 5 folders and each folder consists of around 20 excel sheets.
And these excel sheets contain duplicates within it. It is becoming very hectic to open every file and remove duplicates.
Is there anyother way to remove duplicates from all these files at once ?
All the files contain different set of duplicates and no common columns will be present.

A: XD I'm really understanding your situation but I think that the solution will be one of two :) :
1-make a program with any programming language you can use and try to load the files one by one to do what you want
2-(the easiest one)Try to find a good converter to convert all your files to SQL tables then come here to this site and ask how to delete duplicated rows from different SQL tables after doing that reconvert the SQL tables to EXCEL files again and it will be done (y) ;)


Q: Bash: using parameter expansion to add variables at front and end simultaneously How can i use parameter expansion to add strings at front and end at the same time.
Currently i'm doing this in two steps:
base_test_path=something
folder=anotherthing
test=(abc cde)

halfPaths=("${test[@]/#/$base_test_path}")
fullPath=("${halfPaths[@]/%//$folder/}")

can i eliminate one step here.