text:
Q: Java Scanner Dilimiter I'm using Scanner and a Delimiter to tokenize my .txt file (it's a homework that I've got to do). First version of the file looks like this:
5,5,5,6,5,8,9,5,6,8, good, very good, excellent, good
7,7,8,7,6,7,8,8,9,7,very good, Good, excellent, very good
8,7,6,7,8,7,5,6,8,7 ,GOOD, VERY GOOD, GOOD, AVERAGE
9,9,9,8,9,7,9,8,9,9 ,Excellent, very good, very good, excellent
7,8,8,7,8,7,8,9,6,8 ,very good, good, excellent, excellent
6,5,6,4,5,6,5,6,6,6 ,good, average, good, good
7,8,7,7,6,8,7,8,6,6 ,good, very good, good,  very good
5,7,6,7,6,7,6,7,7,7  ,excellent, very good, very good, very good

And I've used useDelimiter("[ ]*(,)[ ]*") second version of the file looks like this:
5 5 5 6 5 8 9 5 6 8 good, very good, excellent, good
7 7 8 7 6 7 8 8 9 7 very good, Good, excellent, very good
8 7 6 7 8 7  5 6 8 7 GOOD, VERY GOOD, GOOD, AVERAGE
9 9 9 8 9 7 9  8 9 9 Excellent, very good, very good, excellent
7 8 8 7 8 7 8 9 6 8 very good, good, excellent, excellent
6 5 6 4 5 6 5 6 6 6 good, average, good, good
7  8 7 7 6 8 7 8 6 6 good, very good, good,  very good
5 7 6 7 6 7 6 7 7 7  excellent, very good, very good, very good

And I can't come up with a regexp which would help me to separate numbers by space and words by comma. Esentially I need an array with 14 values (very good being a single variable)
Note there are multiple spaces (this is done on purpose to make it harder for us).
So any sort of help would be appreciated.
P.S. We're only allowed to use Delimiters only (no splits etc..)

A: This should work, the key is the positive-lookbehind ((<?=)) and alternation (|):
String input = "9 9 9 8 9 7 9  8 9 9 Excellent, very good, very good, excellent";
Scanner s = new Scanner(input).useDelimiter("(?<=\\d)[\\s,]+|\\s*,\\s*");
while (s.hasNext()) {
    System.out.println("Token: ." + s.next() + ".");
}

Prints:
Token: .9.
Token: .9.
Token: .9.
Token: .8.
Token: .9.
Token: .7.
Token: .9.
Token: .8.
Token: .9.
Token: .9.
Token: .Excellent.
Token: .very good.
Token: .very good.
Token: .excellent.

A: You can try this one (((?<=[0-9]+)\s*(?=[0-9]+))|(,\s*(?=[a-zA-Z]+))|((?<=[0-9]+)\s*(?=[a-zA-Z]+))), looks awful but should work

A: Note that Scanner allows you to change the delimiter at any time.  If you can rely on your input text always having 10 numbers at the beginning and 4 word groups at the end, then you can simply start with a delimiter that just splits on spaces (\s+) and after 10 calls to nextInt(), switch to a delimiter that splits on a
comma and spaces (\s*,\s*).
Something like:
String input = "5 5 5 6 5 8 9 5 6 8 good, very good, excellent, good";
Scanner scanner = new Scanner(input).useDelimiter("\\s+");
int[] results = new int[14];
for (int i = 0; i < 10; ++i) {
    results[i] = scanner.nextInt();
}
scanner.useDelimiter("\\s*,\\s*");
scanner.skip("\\s*");
for (int i = 10; i < 14; ++i) {
    String wordPhrase = scanner.next();
    int wordValue;
    if ("average".equalsIgnoreCase(wordPhrase))
        wordValue = 1;
    else if ("good".equalsIgnoreCase(wordPhrase))
        wordValue = 2;
    else if ("very good".equalsIgnoreCase(wordPhrase))
        wordValue = 3;
    else if ("excellent".equalsIgnoreCase(wordPhrase))
        wordValue = 4;
    else
        wordValue = 0;
    results[i] = wordValue;
}

It's also possible to do this with a single delimiter regex using zero-width lookaround assertions, but this is probably a bit advanced for a simple homework problem.

A: String[] str = expression.split("(,\\s+)|(\\s+)");

Try this:


text:
Q: How to search and replace by comparing two PHP arrays I have this string where I've put all opening tags into (array) $opened and all closing tags into (array) $closed, like so:
'

    Test

The quick

brown fox jumps over  the'

Results in these two arrays:
$opened =
array(8) {
  [0]=> string(3)  "div"         // Need removed
  [1]=> string(3)  "div"
  [2]=> string(10) "blockquote"
  [3]=> string(1)  "p"           // Need removed
  [4]=> string(10) "blockquote"
  [5]=> string(1)  "p"
  [6]=> string(4)  "span"
  [7]=> string(4)  "span"
}

$closed =
array(2) {
  [0]=> string(3) "div"
  [1]=> string(1) "p"
}

I need to somehow say:
Find the first occurrence of $closed[0] (which is "div") in the $opened array and remove it from the $opened array, then repeat until all $closed tags ("div and "p") have been removed from the top of $opened.

A: Hope this helps someone. This is what I came up with:
<?php

    for ( $i = 0; $i < $num_closed; $i++ )
    {
        unset ( $opened[ array_search( $closed[ $i ], $opened ) ] );
    }

?>

I also came up with a for loop which worked, but you had to manipulate the $opened[$i] and $closed[$n] independently, and it was a bit more code, so I ultimately decided on this one.

A: I am not sure if this is what you are looking for, but this will remove the first instance of the thing you are looking for.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$opened_tags = array("div", "div", "blockquote", "p", "blockquote", "p", "span", "span");
$closed_tags = array("div", "p");

$find = "div";

$size = sizeof($closed_tags);
for($i=0; $i<$size; $i++) {
    if($closed_tags[$i] == $find){
        unset($closed_tags[$i]);
        break;
    }
}

echo "closed_tags with empty spaces: ".print_r($closed_tags, true)."

";

$closed_tags = array_values($closed_tags);
echo "closed_tags array indexed correctly: ".print_r($closed_tags, true)."
";
?>

A: I cannot tell from your question, but if your aim is to clean up a snippet of html code, why not simply use the HTMLTidy extension?
Tutorial

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to return an iterator in entries, keys and values methods of a linked list? I'm trying to implement an Array-like linked list (same methods). I have the following two classes:
class Node {
  constructor(value, next_node=null, prev_node=null) {
    this.value = value;
    this.next_node = next_node;
    this.prev_node = prev_node;
  }
}

class List {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
}

I'm trying to implement values(), entries() and keys() similar to of Array. My code:
  [Symbol.iterator]() {
    let current = this.head;
    return {
      next() {
        if (current) {
          let value = current.value;
          current = current.next;
          return {value: value, done: false};
        }
        return {done: true};
      }
    };
  }

  entries() {
    return this._entries();
  }

  keys() {
    return this._keys();
  }

  values() {
    return this._values();
  }

  * _entries() {
    var node = this.head;
    var counter = 0;
    while (node) {
      yield [counter,node.value];
      node = node.next_node;
      counter += 1;
    }
  }

  * _keys() {
    var node = this.head;
    var counter = 0;
    while (node) {
      yield counter;
      node = node.next_node;
      counter += 1;
    }
  }

  * _values() {
    var node = this.head;
    while (node) {
      yield node.value;
      node = node.next_node;
    }
  }

Comparing between array.entries() and list.entries() I see:
Object [Array Iterator] {}
Object [Generator] {}

I understand that there is a difference between an iterator and generator. Two questions:

*

*Should I keep it as Generator? Why Array uses Array Iterator instead of a Generator?

*If I should switch to an iterator, how it should be done for those methods? As you can see, I implemented [Symbol.iterator](), but how do I use it in entries(), keys() and values()?

A:
I understand that there is a difference

Only in syntax, basically a generator is syntax sugar for implementing Symbol.iterator.  It makes it so that you don't need to worry about handling internal state like done etc, and just worry about how to yield.

If I should switch to an iterator,

If you mean move away from using generators, as there both iterators internally anyway, then I would say no, generators are much easier to code and reason with, and implementing Symbol.iterator manually would be step backwards.
Also you can keep your code a little bit more DRY here, below is an example.

class X {
  [Symbol.iterator]() { return this.values(); }
  *values() {
    yield 1;
    yield 2;
    yield 3;
  }
}

const x = new X();

//Both are iterators..
console.log('x.values() is iterator? ' +(Symbol.iterator in x.values()));
console.log('x is iterator? ' + (Symbol.iterator in x));

//Both work the same.
for (const a of x.values()) console.log(a);
for (const a of x) console.log(a);

A: If you want to use [Symbol.iterator] for entries(), you have to return a new object with *[Symbol.iterator]

class List {
  constructor(min, max) {
    this.min = min
    this.max = max
  }

  entries() {
    const {
      min,
      max
    } = this
    return {
      *[Symbol.iterator]() {
        for (let i = min; i <= max; i += 1) {
          yield i
        }
      }
    }
  }
}

const list = new List(2, 7)

console.log([...list.entries()])

for (const item of list.entries()) {
  console.log(item)
}


text:
Q: How to distinguish a Wikipedia article by URL? There are many pages on Wikipedia that are not articles, e.g. talk pages etc. How to distinguish them from articles by URL?

A: The short answer is that you can't with regexes alone.
The longer answer is that MediaWiki articles are divided by namespace, which in turn use colons as markers, as in "Talk:Foo".  Articles without a colon in the title are thus definitely in the main (= content) namespace.  Problem is, articles with a colon may either be in another namespace, or be content articles that happen to contain a colon, and since WP's list of namespaces is long and ever-changing you can't (or at least shouldn't) hardcode this list in a regex.
The correct answer is thus to use the MediaWiki API to iterate/search for articles in the main namespace only.

A: You can get the list of Wikipedia namespaces and their aliases by using its API with the following query:
http://en.wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=namespaces
Then, if the part of the page title before the first colon matches any of the known namespaces, it's not an article; otherwise, it is.


text:
Q: How to decompress only a portion of a file? I have a large, repetitive text file. It compresses very well - it's about 3MB compressed. However, if decompressed, it takes 1.7GB. Since it's repetitive, I only need a fraction of the output to check the contents of the file.
It was compressed using gzip. Does gunzip provides any way to only decompress the first few megs of a file?

A: You could decompress to standard output and feed it through something like head to only capture a bit of it:
gunzip -c file.gz | head -c 20M >file.part

The -c flag to head requires the head implementation that is provided by GNU coreutils.
dd may also be used:
gunzip -c file.gz | dd of=file.part bs=1M count=20

Both of these pipelines will copy the first 20 MiB of the uncompressed file to file.part.


text:
Q: Regular Chaparral comes out bold, bold Chaparral comes out regular. Why? Chaparral.tex:
\documentclass{article}
\usepackage[english]{babel}
\usepackage{fontspec}
\setmainfont{Chaparral Pro}
\begin{document}

Hamburgefonstiv Regular

\textbf{Hamburgefonstiv Bold}

\end{document}

Chaparral.log: http://pastebin.com/wNKG07h0
Result:

Adobe [Caslon/Garamond Premier/Minion/Myriad] Pro come out correctly with equivalent syntax. The .otfs are all present in C:\Windows\Fonts. All came with CS3. LuaTeX beta-0.76.0-2013061707 (rev 4627).
Is this a bug I should report to http://tracker.luatex.org/, or is it an issue with Chaparral, or is it working correctly in a way I don't understand?
Edit: Nevermind. I just found http://tracker.luatex.org/view.php?id=572


text:
Q: Change aria attribute value using JavaScript Observer method Can someone provide me with an example of an HTML div element with an attribute of aria-highlight that changes and notifies the element using the JavaScript observer method? An example would be using a checkbox that toggles the div and changes the background of the div element. I need this done in vanilla JavaScript
Example HTML

<input type="checkbox id="highlight">Highlight Div

A: So below, you have a checkbox with an event handler to toggle the aria-highlight value.
And an observer which triggers on attribute change from the div.

// Our two elements
let square = document.querySelector("#mydiv")
let chk = document.querySelector("#highlight")

// Checkbox click handler
chk.addEventListener("click", function(){
  square.setAttribute("aria-highlight",this.checked)
})

// That is the function called when there is a mutation event
var callback = function(mutationsList) {
 for(var mutation of mutationsList) {
   if (mutation.type == 'attributes') {
    console.log("The attribute '" + mutation.attributeName + "' was modified.");
   }
 }
};

// The mutation observer
var observer = new MutationObserver(callback);
observer.observe(square, { attributes: true });

<input type="checkbox" id="highlight">Highlight Div


text:
Q: This regex isn't allowing the extra digit for some reason... why? I'm trying to make it so that the following are able to fit into the regex, but I'm not able to make it work.
I'm using js on regex101 for this.
These should pass

*

*3

*3.4

*3.5.3

*2.5.*

*3.*
These should fail

*

*33.2

*2.

*3.1.2.

*.2

*3.1.2.....

My current regex is \d?[\.?]?
This only approves 3. I try going forward and use \d?[\.?\d?]? but it still only allows 3.
Edit: 3.5 technically passes in the way that 3. and 5 pass individually but not together. How can I make it together?
Why isn't it working on the rest of the numbers? And how do I fix it?
Update: Please explain how the regex does work if you manage to find it. Thank you.

A: You can use ^(\d+\.)?(\d+\.)?(\*|\d+)$ as found in this answer for version numbering regex.
If you want only a singular digit between the dots then remove the + symbols resulting in:
^(\d\.)?(\d\.)?(\*|\d)$

A: ^\d(\.\d)*(\.\*)?$

var values=[
  "3", "3.4", "3.5.3", "2.5.*", "3.*",
  "33.2", "2.", "3.1.2.", ".2", "3.1.2."
];

values.forEach(value=>
  console.log(
    value,
    value.match(/^\d(\.\d)*(\.\*)?$/)?"Pass":"Fail"
  )
);

function test() {
  var value=document.getElementById("input").value;
  document.getElementById("result").innerText=
    value.match(/^\d(\.\d)*(\.\*)?$/)?"Pass":"Fail";
}
<input id="input" onchange="test()">
<button onclick="test()">Test</button>

Must start (^) with a single digit (\d).
May be followed by unlimited pairs of period+single digit ((\.\d)*) - pair: (\.\d), unlimited: *.
May be followed by a single pair of period+asterix ((\.\*)?) - pair: (\.\*), may(single/none): ?.
And end: $.
Should you want a non-zero digit, replace all ds with [1-9].
Should you want a number rather than a digit, add a '+' after each d: ^\d+(\.\d+)*(\.\*)?$.
And without leading zeros: ^[1-9]\d*(\.[1-9]\d*)*(\.\*)?$.

A: (?:\d\.) -> Non capturing group, with Digit \d matching 0-9. Escaped decimal matches a decimal.
? -> followed by a ? which matches 0 to 1 of the preceding token...
(?:\d\.) -> Non capturing group, with Digit \d matching 0-9. Escaped decimal matches a decimal.
? -> followed by a ? which matches 0 to 1 of the preceding token...
(?:\d) -> Non capturing group, with Digit \d matching 0-9.
$ ends string
NOTE: This will allow 0.*, *.0, 0.0.*, 0.* and 0,0,0 where * = some single digit number...
If you wish to filter out zeros as null then more logic would be...

let regEx = /^(?:\d\.)?(?:\*|\d\.)?(?:\*|\d)$/gm;

let el = document.getElementById('input');

el.addEventListener('keyup', function(){
  let thisVal = this.value;

  if(thisVal.match(regEx)){
    console.log(thisVal + " is allowed")
  }else(
    console.log(thisVal + " is NOT allowed")
  )
})
Enter a string <input id="input">

A: You could match a digit followed by an optional decimal part and an optional part to match a dot followed by either an asterix or a digit.
To prevent partial matches you can use anchors to assert the start ^ and the $ end of the string.
^\d(?:\.\d)?(?:\.[*\d])?$

Explanation

*

*^ Start of string

*\d Match a digit

*(?:\.\d)? Optionally match a dot followed by a digit

*(?:\.[*\d])? Optionally match a dot and either a * or digit

*$ End of string

Regex demo


text:
Q: Android hardware back button unexpected behavior while using drawer when app coming to foreground from background Version
react-native-router-flux 4.0.0-beta.27
react-native 0.51.0
Expected behaviour
Let's say i have screen_1 button on drawer and by clicking it I am going to screen_1. Now press the home button(App goes to background) and open the app again(App comes to foreground). Now when i press the android back button the app should go back to drawer screen (drawer in open state) and again pressing the back button should close the drawer.
Actual behaviour
I have screen_1 button on drawer and by clicking it I am going to screen_1. Now press the home button(App goes to background) and open the app again(App comes to foreground). Now when i press the android back button the app goes back to home screen (drawer in close state) and again pressing the back button open the screen_1 screen.
This is the code I am using to define scenes.
render(){
  return <Router>
      <Scene key="root" headerMode={'screen'}
      >
        <Scene key="drawer" drawer
          contentComponent={SideMenu}
          drawerOpenRoute= 'DrawerOpen'
          drawerCloseRoute= 'DrawerClose'
          drawerToggleRoute= 'DrawerToggle'
          initial={true}
          hideNavBar={true}
          // drawerWidth={400}
        >
          <Scene key="home" component={Home}/>
        </Scene>
        <Scene key="screen_1" component={Screen_1}  />
    </Scene>
  </Router>
}


text:
Q: How soon can I get a Cloyster in Shining Pearl? Cloyster was not in the original Gen IV pokedex, but it is now available in the remakes.
Looking at datamining sites, I found these capture locations for its pre-evolution (Shellder):

Location
Method
Level

Route 205 - South
Super Rod
20 - 40

Valley Windworks
Super Rod
20 - 40

Fuego Ironworks
Super Rod
20 - 40

Grand Underground - Fountainspring Cave
Underground
58 - 63

Grand Underground - Riverbank Cave
Underground
58 - 63

Grand Underground - Still-Water Cavern
Underground
58 - 63

It seems that the Super Rod can only be obtained after defeating the Elite Four.
So, is that the soonest I can get a Cloyster or is there any other way to get one?

A: The requirement to get Cloyster (and Shellder) is either a Super Rod, or the National Pokédex(for the three Grand Underground locations).  As both require you to defeat the Elite Four, the answer to your question is Yes.  (Note: the Super Rod also requires the National Pokédex, so really the singular answer is the National Pokédex).


text:
Q: Safari not showing all Facebook icons sometimes when i login facebook the profile picture icons just won't load. I tried reseting safari, nothing. When i use chrome everything is ok. I googled it and someone said something about deleting a cache file but i could not find in library the safari cache file (i have no idea what it means, i guess some of you will understand).
I have the safari Version 7.0.2 (9537.74.9) and OS X 10.9.2. Anyone got an idea of how to fix it? Thank you in advance

A: To empty the Safari caches, first you need to have the Develop menu displayed in the menu bar (Preferences | Advanced | Show Develop menu in menu bar). Then on the Develop menu, click on Empty Caches.
You can also use the keyboard shortcut: option+cmd+e.


text:
Q: If $s=1+\frac 12+\frac 13+......+\frac 1n$,then show that $(n+s)^s \gt n^n(n+1)$. I am stuck with the following problem:

If $s=1+\frac 12+\frac 13+......+\frac 1n$,then show that
  $(n+s)^s \gt n^n(n+1)$.

My try: Applying  A.M. > G.M. [where A.M. means arithmatic mean  and G.M. implies geometric mean] on the set $\{(1+1),(1+\frac 12),...................,(1+\frac 1n)\}$ we get ,
A.M.=$\frac {n+s}{n}$ and G.M. =$\{(1+1).(1+\frac 12)...................(1+\frac 1n)\}^{\frac 1n}$.
Then I am stuck. Can someone help?

A: You're pretty much there and applied the right idea.
The GM telescopes. It's ${\left(\frac{2}{1}.\frac{3}{2}.\frac{4}{3}...\frac{n+1}{n}\right)}^{\frac{1}{n}}=(n+1)^{\frac{1}{n}}$.
Presumably $n>1$.
So therefore (noting equality cannot hold as the terms are not equal)
$$\frac{n+s}{n}\gt (n+1)^{\frac{1}{n}}$$
$\implies$
$$n+s\gt n(n+1)^{\frac{1}{n}}$$
The LHS and RHS are positive, so we can exponentiate both sides by $n$.
$$(n+s)^n\gt n^n(n+1)$$


text:
Q: How do I get Liferay's Javascript PortletURL module to work with friendly URL mappings? I've set up friendly URL routing for my Liferay portlet, and it's working fine when I generate URLs with the standard JSP tags like so:
<portlet:renderURL var="resetUrl">
    <portlet:param name="start" value="5" />
</portlet:renderURL>

which, given my mapping, produces a lovely URL like:
localhost:8080/web/guest/welcome/-/myportlet/5

But when I generate URLs using the JavaScript PortletURL module, I get the full unfriendly URL. For instance:
var filterUrl = Liferay.PortletURL.createRenderURL();
filterUrl.setPortletId("<%= portletDisplay.getId() %>");
filterUrl.setParameter("start", "5");
location.href = filterUrl;

will generate
localhost:8080/web/guest/welcome?p_p_id=myportlet_WAR_MyPortletportlet&p_p_lifecycle=0&myportlet_WAR_MyPortletportlet_start=5

So my question is:
How can I generate friendly URLs from JavaScript?

A: There is no easy way to do it. You wold have to rewrite the portal_url.js and PortletURLAction.java.
An other option is to write your own portlet, witch can generate the URL as you need it and access it via AJAX.

A: One thing you can try is this approach, a bit tricky -
                <portlet:actionURL var="copyNavigationPointURL">
                    <portlet:param name="myaction" value="copy-navigation-point"></portlet:param>
                    <portlet:param name="objectTypeId" value="changeObjType"></portlet:param>
                    <portlet:param name="navigationPointId" value="changeNavPointId"></portlet:param>
                </portlet:actionURL>

then write javascript and replace param values like this -
function copyNavigationPoint(copyNavigationPointURL) {
    var copyNavId = document.getElementById("navigationPointId").value;
    if (copyNavId==null || copyNavId=='null'){
        alert('error');
        return;
    }
    var objectTypeId = document.getElementById("objectTypeId").value;
    copyNavigationPointURL = copyNavigationPointURL.replace(/changeObjType/i,objectTypeId);
    copyNavigationPointURL = copyNavigationPointURL.replace(/changeNavPointId/i,copyNavigationPointId);

    submitForm(document.hrefFm, copyNavigationPointURL);
}

And you have your friendly url.


text:
Q: Trouble Passing Data Via PrepareForSegue I am trying to pass data to a webViewController using the prepareForSegue method, which looks like:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"RBOM"])
    {
        WebViewController *destViewController = segue.destinationViewController;
        destViewController.url = [NSURL URLWithString:@"https:myURL.com/Articles.asp?ID=274"];
    }
    if([segue.identifier isEqualToString:@"Home"])
    {
        WebViewController *destViewController = segue.destinationViewController;
        destViewController.url = [NSURL URLWithString:@"http://www.myURL.com"];
    }
}

Here is why my webViewController class looks like:
#import "WebViewController.h"

@interface WebViewController ()

@end

@implementation WebViewController
@synthesize webView;
@synthesize url;

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:NO];
    self.title = @"MyURL.com";
    self.webView.delegate = self;
    NSLog(@"URL: %@", self.url); <---- This is null

    NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:requestURL];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end

Here is the webViewController.h:
#import <UIKit/UIKit.h>

@interface WebViewController : UIViewController <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) NSURL *url;

@end

The problem is that my URL is null. Can someone tell me why?

A: For your UI elements it is generally ok to declare them weak because your view will retain them.  For your other ivars you want to declare them strong so that your class instance will retain them.  In this particular case your url property is weak, so the NSURL was not retained and was set to nil after prepareForSegue:'s scope went away.

A: You are bound to run into this kind of trouble with prepareForSegue.
I suggest you keep strong instances of the data you want to pass in your source as:
NSURL *tempURL = [NSURL URLWithString:@"https:myURL.com/Articles.asp?ID=274"];

and then in the prepareForSegue only do this :
destViewController.url = tempURL;

I have experienced similar problems before, this seems to solve it. I don't have a clear picture about the reason for this.


text:
Q: Скрывать input если пустой Подскажите как скрывать input если он пустой.
<input class="form-check-inline" type="radio" name="question" value="'.$scripts['scripts_url13'].'"/>
'.$scripts['scripts_answer13'].'
';

Пробовал:
if($('.form-check-inline').text() == ' '){
  $('.form-check-inline').css({'display': 'none'});
} else {
  $('.form-check-inline').css({'display': 'form-check-inline'});
}

Но результата не дало

A: Я так понял, нужно скрыть input,если в него не передано значение.

$(document).ready(function(){
  $('.form-check-inline').each(function(){
    if(this.value == '' || this.value == undefined){
      $(this).hide();
    }
  })
})

<input class="form-check-inline" type="radio" name="question" value="'.$scripts['scripts_url13'].'"/>

<input class="form-check-inline" type="radio" name="question" value=""/>

A: А нужен ли вам Javascript (и AJAX) вообще? Скрыть элемент с пустым атрибутом можно и силами CSS2, поддерживаемым всеми браузерами без исключения:

input[value=''] {display: none}
<input class="form-check-inline" type="radio" name="question" value="'.$scripts['scripts_url13'].'"/>
<input class="form-check-inline" type="radio" name="question" value=""/>

A: Я так понял какой-то вопросник. Не знаю зачем скрывать, но вижу как минимум, что
$('.form-check-inline').css({'display': 'form-check-inline'});

В css нет display:form-check-inline. Поменяй хотя бы на display:block(inline-block). И поставь как тебе выше писали text().length == 0

A: Я бы лучше обернул радио кнопки в лейблы и проверял текст уже в лейблах

$('.radio-label').each(function() {
  if (!$(this).text().length) $(this).hide();
  else $(this).show();
});

<input type="radio" name="question" value="lul">
<input type="radio" name="question" value="lulz">choose me!


text:
Q: Loop through and retrieve xml values with Powershell export csv I've spent a lot of time trying to pull this data - from the following XML - I've "re-purposed a working script that worked well for someone else needs - and is really really close to what I need.
Example XML -
<?xml version="1.0"?>
 <GET_EMBEDDED_HEALTH_DATA>
    <FANS>
      <FAN type="object">
           <ZONE VALUE="System"/>
           <LABEL VALUE="Fan 1"/>
           <STATUS VALUE="OK"/>
           <SPEED VALUE="26" UNIT="Percentage"/>
      </FAN>
           <FAN type="object">
           <ZONE VALUE = "System"/>
           <LABEL VALUE = "Fan 10"/>
           <STATUS VALUE = "OK"/>
           <SPEED VALUE = "26" UNIT="Percentage"/>
      </FAN>
</FANS>
<TEMPERATURE>
      <TEMP>
           <LABEL VALUE = "01-Inlet Ambient"/>
           <LOCATION VALUE = "Ambient"/>
           <STATUS VALUE = "OK"/>
           <CURRENTREADING VALUE = "20" UNIT="Celsius"/>
           <CAUTION VALUE = "42" UNIT="Celsius"/>
           <CRITICAL VALUE = "46" UNIT="Celsius"/>
      </TEMP>
     </TEMPERATURE>
<POWER_SUPPLIES>
           <SUPPLY>
           <LABEL VALUE = "Power Supply 1"/>
           <PRESENT VALUE = "Yes"/>
           <STATUS VALUE = "Good, In Use"/>
           <PDS VALUE = "No"/>
           <HOTPLUG_CAPABLE VALUE = "Yes"/>
           <MODEL VALUE = "656364-B21                      "/>
           <SPARE VALUE = "Unknown"/>
           <SERIAL_NUMBER VALUE = "5BXRK0DLL7B0S1  "/>
           <CAPACITY VALUE = "1200 Watts"/>
           <FIRMWARE_VERSION VALUE = "N/A"/>
      </SUPPLY>
</POWER_SUPPLIES>
</GET_EMBEDDED_HEALTH_DATA>

There are a lot more than "FAN/TEMP/POWER" etc, hence me attempting to not define this whole "piece" and looking for a loop solution. that will output the values in csv format .  SOOOO, the following scripts when the data is formatted as follows works correctly,however, I don't receive the data in that format, unfortunately.  Also as I move into TEMP, Power, they have different labels/criteria
    SYSTEM
    FAN 1
the code I have so far is as follows (this block is for FAN)  Optimally, I would love to be up one more level, so that it spits out FAN/ZONE/LABEL/... then TEMP/LABEL/LOCATION....   but I can live with doing multiple code blocks for each type, if I can avoid specifying each inner or is it outer member..
[xml]$convertMe = Get-Content .\new.xml
[Array]$MeConverted = $convertMe.GetElementsByTagName('FAN')
$Collection = @()
ForEach($Record in $MeConverted){
 $Output = new-object psobject
$Record.selectnodes("*")|%{Add-Member -InputObject $Output -MemberType NoteProperty -Name $_.Name -Value $_.'#text'}
If($Collection){
    $T2Keys = $Collection|gm|?{$_.MemberType -match "VALUE"}|Select-Xml -XPath -Debug
    $T1Keys = $Output|gm |?{$_.MemberType -match "VALUE"}|Select -ExpandProperty Name
    $KeysToAdd = $T2Keys|?{$T1Keys -notcontains $_}
    $KeysToAdd|%{$Collection|Add-Member $_ ""}
}
$Collection += $Output
}
$Collection | Export-CSV FAN.csv -notype

...repeat for TEMP/POWER/...
I literally spent hours trying to modify the above script to read the value of "VALUE" and studied, get-member, select, etc. but I'm still face-palming at the moment.  And I will likely Face Palm when someone shows me how close I may have been and simple this is!  Thanks in Advance

A: So, I had worked on this FOREVER, and must have had a typo the very first time I made an attempt to modify for my needs. and then went down the rabbithole of attempting to figure out how to do this.
I only had to change one thing for my needs.
$Record.selectnodes("*")|%{Add-Member -InputObject $Output -MemberType NoteProperty -Name $_.Name -Value $_.'#text'

to
$Record.selectnodes("*")|%{Add-Member -InputObject $Output -MemberType NoteProperty -Name $_.Name -Value $_.'VALUE'

I'm wondering if I had possibly typed VALUES last night and not realized it.


text:
Q: How to display image from URL in Android I use this code to display image from url it work but the image is stored in device this is the problem because I want to display this image only if the user is connected to internet
ImageView imageView=(ImageView) findViewById(R.id.imageView3);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);

How do I display image from URL in Android?

A: compile "com.squareup.picasso:picasso:2.4.0"

Use this library to load images.
Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.placeholder) //optional
       .resize(imgWidth, imgHeight)         //optional
       .centerCrop()                        //optional
       .into(image);                        //Your image view object.

A: Try this solution..
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(image);

it will help you.

A: Glide library is better than Picasso I'm suggesting you to use Glide
for doing this in Build.gradle file in dependency section add this code:
compile 'com.github.bumptech.glide:glide:3.7.0'

then in your Activity that you want to show Image use this code in your onCreate method:
String myUrl = "https://github.com/bumptech/glide/raw/master/static/glide_logo.png";

ImageView imageView = (ImageView)findViewById(R.id.yourImageView);

Glide.with(getApplicationContext())
     .load(myUrl)
     .into(imageView);

A: You can use Picasso library to load image into imageView. It is easy to use.
Add dependency in your app level build.gradle file
compile 'com.squareup.picasso:picasso:2.5.2'
Load image from a url like this
Picasso.with(this).load(url).into(imageView);

Read more about Picasso enter link description here

A: To check internet connectivity use following code
            ConnectivityManager connectivity = (ConnectivityManager) _Context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivity != null) {
            NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        available = true;
                    }
                }
            }
        }
        if (available == false) {
            NetworkInfo wiMax = connectivity.getNetworkInfo(6);
            if (wiMax != null && wiMax.isConnected()) {
                available = true;
            }
        }

And After that use to download image
class DownloadTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
String image_name, studentName;
TextDrawable drawable;

public DownloadTask(ImageView bmImage, String file_name) {
    this.bmImage = bmImage;
    this.image_name = file_name;
}

protected Bitmap doInBackground(String... urls) {
    InputStream input = new java.net.URL(image_name).openStream();
    if(input.available()!=0) {
        return BitmapFactory.decodeStream(input);
    }
    return null;
}

protected void onPostExecute(Bitmap result) {
    try {
        if(result == null)
            bmImage.setImageDrawable(drawable);
        else
        bmImage.setImageBitmap(result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

A: I have also same problem solve using below code.
Picasso.with(context).load(uri).networkPolicy(NetworkPolicy.NO_CACHE)
        .memoryPolicy(MemoryPolicy.NO_CACHE)
        .placeholder(R.drawable.bv_logo_default)
        .into(viewImage_imageView);

A: Try this also Fix the size according to you..or see the resize with universal loader
<ImageView
android:id="@id/ivImage"
android:layout_width="150dp"
android:layout_height="150dp"
android:adjustViewBounds="true"

android:scaleType="fitCenter" />

Used the Android Universal Image-Loader

Declare

    private ImageLoader imageLoader1;

On Create

 imageLoader1 = ImageLoader.getInstance();

 imageLoader1.init(ImageLoaderConfiguration.createDefault(youractivity.this));

no_image here a drawable image without any image load in Cache

   DisplayImageOptions
            options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .showImageOnLoading(R.drawable.no_image) // resource or drawable
            .showImageForEmptyUri(R.drawable.no_image) // resource or drawable
            .showImageOnFail(R.drawable.no_image)
            .considerExifParams(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    imageLoader1.displayImage(yourpathURl.replace(" ", "%20"), ivImage, options);

Add gradle dependencies also... download the latest jar of universal loader
The download link of jar
  compile files('libs/universal-image-loader-1.9.5-with-sources.jar')

You Can Use Piccaso Also and Glide also

A: Glide.with(context).load(uri).asBitmap().placeholder(R.drawable.yourimage).error(R.drawable.yourimage).into(yourview);

Apart from the above answer if the image URL return null you can load default image into the view as like above.

A: I end up with something like this for kotlin.
//download
val result = lifecycleScope.async(Dispatchers.IO){
    try {
        val url = URL("url")
        return@async BitmapFactory.decodeStream(url.openConnection().getInputStream())
    } catch (e: IOException){
        println("Error")
    } catch (e: UnknownServiceException){
        println("Error2")
    } catch (e: MalformedURLException){
        println("Error3")
    }
}

lifecycleScope.launch {
    val bitmap = result.await() as Bitmap
    val imageView: ImageView = findViewById(R.id.post_image)
    imageView.setImageBitmap(bitmap)
}


text:
Q: how to disregard empty href and image I need help with the below coding. Thank you.
Problem:
If "website" or my image is not available, "name" will still display as a link.
And a broken image will show.
Is there a way where if "website" is empty, the "name" will just display as a normal text. And if I don't have the image, it will not display a broken image link?
Code:

My Contacts

Thanks, Mel

A: You can use the event onerror on your img tag to make what you want if the img is not loaded.

With jquery
$('.cid-logo').html("")
$('.img').on( "error", function () { $(this).hide(); });


text:
Q: How to add a value from a dict to a list only if the dict has a specific key? Say I have a class Node, with attributes left, right, val. Then suppose we have internal and leaf, where leaf has None for left and right. Then iterating through my_list = [internal, leaf], I only want to add the child nodes to an array only if they exist, so I would do something like
[x.left if x.left is not None for x in my_list]

Is something like this possible? When I try this I get a invalid syntax error

A: You're almost there! You need to switch the ordering of the for and if clauses:
[x.left for x in my_list if x.left is not None]


text:
Q: Send json object as body in a POST request I develop a project in Angular 9 which reads a csv file and send its content to the server.
I  have a model for the file's records.
The request shows the object in "Request payload" but when it get to the API conntroller the data doesn't recognized as [FromBody] parameter.
Do you have any solution for me?
This is my code:
Model:
export class CSVRecord {
public code: string;
public date: Date;
public value: number;
public period: string;

}
Type script:
    export class AppComponent {
  title = 'FastWayToSerieses-Client';

  constructor(public apiService: ApiService, private http: HttpClient ) {
}

  public records: any[] = [];
  @ViewChild('csvReader') csvReader: any;

  uploadListener($event: any): void {

    const text = [];
    const files = $event.srcElement.files;

    if (this.isValidCSVFile(files[0])) {

      const input = $event.target;
      const reader = new FileReader();
      reader.readAsText(input.files[0]);
      console.log('after read as text');

      reader.onload = (e) => {
        console.log('onload');
        const csvData = reader.result;

        const temp = ( csvData as string).replace(/\r/g, '\n');
        const csvRecordsArray = ( temp as string).split(/\r\n|\n/);

        const headersRow = this.getHeaderArray(csvRecordsArray);
        this.records = this.getDataRecordsArrayFromCSVFile(csvRecordsArray, headersRow.length);
        (document.getElementById('sendButton') as HTMLInputElement).disabled = false;

      };

    } else {
      alert('Please import valid .csv file.');
      this.fileReset();
    }
  }

  getDataRecordsArrayFromCSVFile(csvRecordsArray: any, headerLength: any) {
    console.log('getDataRecordsArrayFromCSVFile');
    const csvArr = [];

    for (let i = 1; i < csvRecordsArray.length; i++) {
      const curruntRecord = (csvRecordsArray[i] as string).split(',');
      if (curruntRecord.length === headerLength) {
        const csvRecord: CSVRecord = new CSVRecord();
        csvRecord.code = curruntRecord[0].trim();
        csvRecord.date = new Date(curruntRecord[1].trim());
        csvRecord.value = Number(curruntRecord[2].trim());
        csvRecord.period = curruntRecord[3].trim();

        csvArr.push(csvRecord);
      }
    }
    return csvArr;
  }

  isValidCSVFile(file: any) {
    return file.name.endsWith('.csv');
  }
  getHeaderArray(csvRecordsArr: any) {
    console.log('getHeaderArray');

    const headers = (csvRecordsArr[0] as string).split(',');
    const headerArray = [];

    for (const header of headers){
      headerArray.push(header);
    }
    return headerArray;
  }

  fileReset() {
    this.csvReader.nativeElement.value = '';
    this.records = [];
  }

This is the function ehich dend the data to the server:
sendCSV(){
    console.log('click');

    const url = this.apiService.baseUrl + 'API/SeriesAPI/UploadSeriesData?option=1';

    // const body = JSON.stringify(this.records);

    this.http.post(url, this.records  ,
    {
       headers: new HttpHeaders({
       'Content-Type':  'application/json;chrset=UTF-8'
      })
    }
    )
    .subscribe(x =>
      {
        console.log(x);

      });

  }

Debugger chrome


text:
Q: partial search and lowercase search in nodejs I'm trying to implement multiple search functionality such as userName and userId with separate input for userName and userId. If I give userName as "Dave Steve" or "dave steve" or "Dave" or "steve" or "dav" and click on the search button I should get the result But When I give "Dave steve" it working fine but not with other case How do I implement it ?
Json data:
let logData={
"dataLog":
[
    {
        "userId":"1",
        "userName":"Dave Steve",
    },
    {
        "userId":"2",
        "userName":"John Doe",
    }
],
}

Here is my code
app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName === userNameData)
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});

A: Please try it
app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName.toLowerCase().includes(userNameData.toLowerCase()))
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});

A: It's because Dave Steve isn't really equal to Dave steve when you are comparing strings using ===. It's case sensitive.
You can use .toLowerCase() to both userName and userNameData when comparing the two.
So your comparison would look like:
userName.toLowerCase() === userNameData.toLowerCase()

EDIT:
I completely glossed over that you want partial string comparison. So you should instead use .includes(string) instead.
userName.toLowerCase().includes(userNameData.toLowerCase())

A: Here is an implemented stackblitz link for you, go through it.
The comparison need to happen with both cases with an or statement :
userName.toLowerCase() === data.userName.toLowerCase() ||
userName.toLowerCase().indexOf(data.userName.toLowerCase()) === -1


text:
Q: namespace issue in xml XmlElement xmlElementSAPD = xmlDocument.CreateElement("SAPD");
root.AppendChild(xmlElementSAPD);

xmlElementSAPD.AppendChild(XmlFunctions.GetXMLElement(xmlDocument, "smu", dr.GetString("sma").Trim()));

The c# code above creates XML below.
<SAPD>
<smu>123</smu>
</SAPD>

How can I change the code above so that I can get
<ns0:SAPD>
<ns0:smu>123</ns0:smu>
</ns0:SAPD>

Anyone? How can I add ns0: in xml nodes?

A: You have to add the namespace to your xml document.
Just to give you an idea have a look at the below
XmlDocument doc = new XmlDocument();
XmlSchema schema = new XmlSchema();
schema.Namespaces.Add("ns0", "http://www.sample.com/file");
doc.Schemas.Add(schema);

A: You prefix ns0 needs to be mapped with a namespace else the xml would not be valid.
Assumning ns0 is mapped to http://tempuri.org the below code can be used:
        XmlDocument doc = new XmlDocument();
        XmlElement sapd= doc.CreateElement("ns0","SAPD","http://tempuri.org");
        XmlElement smu = doc.CreateElement("ns0", "smu", "http://tempuri.org");
        smu.InnerText = "123";
        sapd.AppendChild(smu);
        doc.AppendChild(sapd);
        doc.InnerXml.ToString();


text:
Q: Modifying .tim and .tip files in Lucene Index I have a Lucene application with multiple indices in which the relevancy scoring suffers due to differences in the term frequencies across the different indices.  My understanding is that the Term Dictionary (.tim  file) contains "term statistics" such as the document frequency statistics on each term.  I was thinking that one approach might be to modify the .tim files for each index (and related segments) and update the "term statistics".  Is it possible to overwrite or modify the .tim and .tip files in such a way?

A:
relevancy scoring suffers

From the FAQ:

score values are meaningful only for purposes of comparison between
  other documents for the exact same query and the exact same index.
  when you try to compute a percentage, you are setting up an implicit
  comparison with scores from other queries.

A: Is it possible?  I suppose, but it strikes me as about as good an idea as attempting to change an application by directly modifying the compiled binaries.
If you need very specific things from scoring, then you should generally implement a Similarity that does what you need.  Extending TFIDFSimilarity is often a good idea.  Really not clear on what the exact problem is, so I can't provide any more specific guidance than that, but perhaps that provides a point in the right general direction.


text:
Q: How to test controller without hitting the database? I have a controller:
class InvoicesController < ApplicationController
  def edit
    @invoice = Invoice.includes(:client, :document_status).find(params[:id])
    return head :forbidden unless @invoice.editable?
  end
end

I want to write a test but without hitting the database:
describe InvoicesController do
  describe '#edit' do
    let(:invoice_id) { '1' }
    let(:invoice) { double(Invoice, editable?: false) }
    let(:invoice_includes) { double }

    before do
      allow(invoice_includes).to receive(:find).with(invoice_id) { invoice }
      allow(Invoice).to receive(:includes).with(:client, :document_status) { invoice_includes }
    end

    subject { get :edit, params: {id: invoice_id} }

    it { is_expected.to have_http_status(403) }
  end
end

Is there a better approach? I don't like this chain of allows but I can't think of anything better. Setting the @invoice instance variable in the test would be bad, because then I would rely on the implementation.
I could obviously just create the invoice in the DB and don't bother about all the mocks and stubs. However, doing this in all the specs would slow down the whole test suite.

A: You can move the query part to the query object so then you can have this code:
class InvoiceQuery
  def find(id)
    ::Invoice.includes(:client, :document_status).find(id)
  end
end

class InvoicesController < ApplicationController
  def edit
    @invoice = invoice_query.find(params[:id])
    return head :forbidden unless @invoice.editable?
  end

  private

  def invoice_query
    ::InvoiceQuery.new
  end
end

then you can easily test your controller without hitting database
describe InvoicesController do
  describe '#edit' do
    let(:invoice_query) do
      instance_double(InvoiceQuery, find: double)
    end

    let(:invoice)
      instance_double(Invoice, editable?: false)
    end

    let(:invoice_id) { '1' }

    before do
      allow(InvoiceQuery).to receive(:new).and_return(invoice_query)
      allow(invoice_query).to receive(:find).with(invoice_id).and_return(invoice)
    end

    subject { get :edit, params: {id: invoice_id} }

    it { is_expected.to have_http_status(403) }
  end
end

Is recommended to test InvoiceQuery with database as it's query object and it performs calls to database directly


text:
Q: Button spanning 2 fragments (xml layout) Can't figure out how to set this up in XML...
Trying to get a button to lay over 2 fragments that sit behind it.
What I want:

What I have:

My code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".VulgarActivity"
    >
    <Button
        android:id="@+id/luckBtn"
        android:layout_gravity="bottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/feel_lucky"
        android:textColor="#ffffff"
        />
    <fragment
        android:name="com.wizardknight.visionaryvulgarity.FirstWord"
        android:id="@+id/firstWord"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        />
    <fragment
        android:name="com.wizardknight.visionaryvulgarity.LastWord"
        android:id="@+id/lastWord"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        />
</LinearLayout>

A: You can do this with a RelativeLayout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <fragment
            android:id="@+id/firstWord"
            android:name="com.wizardknight.visionaryvulgarity.FirstWord"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <fragment
            android:id="@+id/lastWord"
            android:name="com.wizardknight.visionaryvulgarity.LastWord"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <Button
        android:id="@+id/luckBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="bottom"
        android:text="@string/feel_lucky"
        android:textColor="#ffffff" />

</RelativeLayout>

Explanation:
The difference between RelativeLayout and LinearLayout is simple. LinearLayouts order their child views, like the name already says, linearly. That means, that the child will order themselves, depending on the orientation of the LinearLayout, vertically or horizontally to each other. The child view of a RelativeLayout on the other hand order themselves relative to the parent view or to other views. In this layout I just changed the parent layout to RelativeLayout and wrapped your fragments in a LinearLayout, so it they can use the layout_weight attribute. Then I set this to the button:
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"

This aligns the button to the bottom and centers them horizontally. Now, since it does this relative to the top level layout, it overlaps the fragment.


text:
Q: Save XML in Outlook public folder May this is not the right place to ask, but prior to an Outlook plugin development I would like to get clarification.
As I understand, public Outlook folders used to share information among several accounts.
Can I save XML files, or that sort of files, in the public folder, or only Outlook objects such as Tasks, Notes?


text:
Q: For how long 12.04 LTS will be supported ? 5 or 3 years? Hey everyone today my friend call me and he told me that 12.04LTS it will be support for 3 years is that correct ? because i think it will be supported for 5 years, i am not sure but i heard from different person told me that 12.04 will be supported for 5 , so please someone tell me 5 OR 3 years ?
i am speaking about desktop NOT server version
thanks

A: Canonical will provide security updates for 12.04 LTS through April 2017 on the desktop and server. That's five years total from release.

You can read about Canonical's support plan here.


text:
Q: Pointer address of a struct Consider this code :
package main

import "fmt"

type S struct {
    Val  int
}

func main() {
    e1 := S{Val: 1}
    fmt.Printf("%p\n", &e1)
    fmt.Printf("%p\n", &e1.Val)
}

After running it, we'll get something like that:
0xc00001c030
0xc00001c030

What confuses me is why pointer's address of the struct and it's member are the same?
Link to Go Playground: https://go.dev/play/p/Wl4tnD9TFmA

A: Struct is memory area with all fields put there one by one (if alignment present, then they could be with gaps). Same as array. So first element of struct obviously should have same address as struct itself.


text:
Q: Could not resolve serviceType [controller name] When trying to refactor an existing asp.net-mvc application to use Turbine as an IoC I get the following result:

MvcTurbine.ComponentModel.ServiceResolutionException
Could not resolve serviceType 'CommonProject.Web.Shared.Controllers.SearchController'
Source Object: at MvcTurbine.Unity.UnityServiceLocator.Resolve[T](Type type)

The (only) ctor for my SearchController looks like this
public SearchController(ISearchService searchService):base(new SearchViewData())
{
    this.searchService = searchService;
}

And my registration looks like this
public class SearchServiceRegistration: IServiceRegistration
{
    public void Register(IServiceLocator locator)
    {
        locator.Register<ISearchService>(typeof(LuceneSearchService));
    }
}

UPDATE
I found it (it was a bit stupid)
locator.Register<ISearchService>(typeof(LuceneSearchService));

should have been
locator.Register<ISearchService,LuceneSearchService>();

Don't know what the first syntax is supposed to do though.

A: Do you miss a registration for the SearchController?


text:
Q: How to hook fopen using Frida in Android? I have an android application into which I load a library and at some point I read a file. This is the code that is being used in the app.
    FILE *fp = fopen(file_name, "r");
    if (fp == NULL) {
        return res;
    }

Now I am attempting using Frida to hook that fopen in order to force it to return null but I do not seem to be able to find out how.
The library that is included in the application is called libnative-lib.so and my attempt in hooking fopen includes the following code for frida
 Module.enumerateExports("libnative-lib.so", {
      onMatch: function(e) {
          if(e.type == 'function') {
              if(e.name == "fopen") {
        console.log("Function recognized by name");
        Interceptor.attach(e.address, {
        onEnter: function(args) {
            console.log("Interceptor attached onEnter...");
            },
        onLeave: function(retval){
            console.log("Interceptor attached onLeave...");
            }
        });
              }
          }
      },
      onComplete: function() {}
  });

A: Instead of enumerating the exports of a specific library, you can try calling Module.findExportByName(null, "fopen") to get the address of fopen (the null argument tells frida to look through the exports of all of the loaded libraries) and use the Interceptor API the same way you did.
This should look somewhat like this:
Interceptor.attach(Module.findExportByName(null, "fopen"), {
    onEnter: function(args) {
        console.log("Interceptor attached onEnter...");
    },
    onLeave: function(args) {
        console.log("Interceptor attached onLeave...");
    }
}

You haven't stated exactly how your code fails, but to make sure that the library you are talking about is actually loaded in the app, you can list all of the loaded modules:
Process.enumerateModules()
    .forEach(function(m) {
        // You can print just the name by using m.name or the entire system path with m.path
        console.log(JSON.stringify(m));
    });

Another way would be using Process.enumerateModules() to find the correct module and then calling enumerateExports on the Module object you got.
This will make sure you are searching for fopen in the correct module if the name of the module is not exactly libnative-lib.so:
Process.enumerateModules()
    .filter(function(m){ return m["path"].toLowerCase().indexOf("libnative") != -1 ; })
    .forEach(function(mod) {
        console.log(JSON.stringify(mod));
        mod.enumerateExports().forEach(function (exp) {
            if (exp.name.indexOf("fopen") != -1) {
                console.log("fopen found!");
            }
        })
    });

HTH, if this still doesn't solve your problem post some additional information in your question.

A: fopen will invoke open
I would suggest use a condition to assert it opens your specific file & not to replace/override.
Interceptor.attach(Module.findExportByName(null, "open"), {
  onEnter: function(args) {
    this.file_name = Memory.readCString(ptr(args[0]));
  },
  onLeave: function(retval) {
    if ("your file name" === this.file_name) // passed from onEnter
      retval.replace(0x0); // return null
  }
});

BTW, if you enable the flag --enable-jit you could filter with ECMAScript6
Module.enumerateExports(moduleName).filter(ex => ex.name.includes('fopen')).forEach(ex => { .. })


text:
Q: Getting the value of a paper-radio-button inside a template I have set up a template that pulls the headers from some data from a JSON file then creates a set of paper-radio-buttons from those headers. When I call this template (in a paper-shadow) I am having trouble capturing the value of the selected paper-radio-button when I click submit (in the paper-shadow).
Here's what is generated in the paper-shadow:
<polymer-element name="add-graphItem">
    <template>

            <paper-button raised class="colored" self-center>Upload File</paper-button>
            <paper-input-decorator label="Enter URL for Dataset" floatingLabel error="A URL is required!" flex self-center>
                <input is="core-input" id="graphSource" required>
            </paper-input-decorator>

            <paper-shadow class="card upload-options-box" z="1">
                <core-header-panel flex id="graphHeaderList">
                    <core-toolbar class="upload-option-header">
                      Variable
                    </core-toolbar>
                    <graph-optionsLoadTest><graph-optionsLoadTest>

            </core-header-panel>
        </paper-shadow>
        <paper-shadow class="card upload-options-box" z="1">
            <core-header-panel flex>
                <core-toolbar class="upload-option-header top">
                  Transform
                </core-toolbar>

                    <graph-functionsLoad><graph-functionsLoad>

            </core-header-panel>
        </paper-shadow>

    <paper-button dismissive hover on-tap="{{cancelGraph}}">Cancel</paper-button>
    <paper-button affirmative hover on-tap="{{addNewGraph}}">Submit</paper-button>

</template>

And here is the paper-radio-button template:
<link rel="import" href="/static/bower_components/core-ajax/core-ajax.html">

<polymer-element name="graph-optionsLoadTest">
    <template>
        <core-ajax auto url="/getDataHeaders"
               handleAs="json" response="{{headerList}}"></core-ajax>

        <paper-radio-group id="headerValue">
            <template repeat="{{h in headerList.headers}}">
                <paper-radio-button name='{{h}}' label='{{h}}'></paper-radio-button>
            </template>
        </paper-radio-group>

    </template>

</polymer-element>

I've tried numerous ways to get the value of the selected paper-radio-group with no success, any help would be appreciated

A: Mike, I see a few issues that might help you.
First, you can only use the $ hash to access nodes defined with an id attribute in your template. To access other nodes, such as those defined dynamically or without an id attribute, you can use the querySelector method. This method also lets you search by selector (somewhat like JQuery). In addition, to access nodes within the shadow DOM of a Polymer component that do not have id attributes, you may use the shadowRoot member. These ideas are discussed in the Polymer documentation for Automatic Node Finding and, in more detail, in the section on Shadow DOM. (In addition, the closing tag for the <graph-optionsLoadTest> element is missing a /.)
The upshot is that in order to access a node within a nested component's shadow DOM, you need to use something either like

*

*this.$.idOfgraphOptionsLoadTest.$.idOfRadioGroup, when you have defined id attributes for your elements;

*this.shadowRoot.querySelector('graphOptionsLoadTest').shadowRoot.querySelector('paper-radio-group'), whether or not id attributes are defined; or

*some combination of the two, when one component has ids and the other does not.

I would suggest giving the <graph-optionsLoadTest> element an id and using the first option above.
Example Code
Unfortunately, your code is rather difficult to use without the pieces that I surmise are hosting it. Therefore, I created the following to illustrate the principle:
<!doctype html>

        <title>Home</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">

        <link rel="import" href="bower_components/paper-radio-button/paper-radio-button.html">
        <link rel="import" href="bower_components/paper-radio-group/paper-radio-group.html">

        <polymer-element name="options-load" attributes="selected">
            <template>
                <paper-radio-group id="headerValue" selected="{{selected}}">
                    <template repeat="{{h in headerList.headers}}">
                        <paper-radio-button name='{{h}}' label='{{h}}' style="height: 100px"></paper-radio-button>
                    </template>
                </paper-radio-group>
            </template>

        </polymer-element>

        <polymer-element name="add-graph-item">
            <template>

Options:

                    <options-load id="optionsLoad"></options-load>
                    <button on-tap="{{doIt}}">Go</button>

Results:

                </template>

            </polymer-element>

            <add-graph-item></add-graph-item>

Good luck!


text:
Q: Max occurrences of a foreign key inside query I'm trying to get an item with the most occurrences of a foreign key (votes), inside of a queryset (Questions, Choices).
I.E. I need to get the most popular vote to set the 'winner' attribute in the JsonResponse.
Any help on how I can figure this out?
Here is my view.
allchoices = [{
    'id':i.id,
    'question':i.question.id,
    'choice_text':i.choice_text,
    'votes':i.voter_set.all().count()
} for i in poll_choices]
return JsonResponse({
    "votes":choice.voter_set.all().count(),
    'winner':True,
    'success':True,
    'allchoices':allchoices
},safe=False,)

These are my models:
class Voter(models.Model):
    # Authentication of anonymous users
    choice = models.ForeignKey('PollChoice', on_delete=models.CASCADE)
    question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE)

class PollChoice(models.Model):
    question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)

    def __str__(self):
        return self.choice_text

class PollQuestion(models.Model):
    question = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)
    creator = models.ForeignKey('poll_creator',/\
         on_delete=models.CASCADE, null=False, blank=False)
    uuid = ShortUUIDField(length=8, max_length=12)

    def poll_choices(self):
        return self.pollchoice_set.all().annotate(voters=/\
            models.Count(models.F('voter'))).order_by('-voters')

    def choices(self):
        return self.pollchoice_set.all()

    def __str__(self):
        return f'{self.question}'

A: You can order by the number of related Voters, with:
from django.db.models import Count

poll_choice = PollChoice.objects.alias(
    num_voters=Count('voter')
).latest('num_voters')
this will retrieve the PollChoice with the largest amount of related Voters. You can filter the PollChoice further, for example to only consider PollChoices for a certain PollQuestion with:
from django.db.models import Count

poll_choice = PollChoice.objects.filter(question=my_question).alias(
    num_voters=Count('voter')
).latest('num_voters')


text:
Q: Paperclip don't show the image well i have this problem
i have this in my model service
class Service < ApplicationRecord
  belongs_to :user

    has_attached_file :images, :styles => {:md => "300x300>", :large => "500x500>" , :xl => "700x700#"}, :default_url => "/app/assets/images/thumb/missing.png"
    validates_attachment_content_type :images, :content_type => /\Aimage\/.*\Z/

end

and this in my view Services#index
    <div>
      <%= image_tag service.images(:md)%>
    </div>

but there's a problem in my view the image set when i put :large or :xl but when i put :md the images don't shows. i don't know what's happening

A: If :largeand :xl are working when you replace it with :md in your index view, then I would guess that there's simply no version for :md available to show. Have you added :md to the model, after you actually already uploaded an image? I would delete the image and try that again.


text:
Q: Creating a vector of numbers based on letters So, this is the question:
"Create a function that given one word, return the position
of word's letters on letters vector. For example, if the word
is 'abba', the function will return 1 2 2 1."
What I have so far is this:
l <- function(word) {
    chr <- c()
    y <- c()
    strsplit(chr,word)
    i<-1
    while(i<length) {
           o<-letters[i]
           x<-chr[i]
           if(o==x) {
                    y[i]<-i
           }
           i+1
    }
    y
}

I have tried running l("hello") and it returns NULL. I'm very lost and would appreciate any help! Thank you!

A: With base R:
lapply(strsplit(x, "", fixed = TRUE), match, letters)

[[1]]
[1] 1 2 2 1

A: I provide another interesting function in base:
x <- "abcxyz"
strtoi(strsplit(x, "")[[1]], 36) - 9
# [1]  1  2  3 24 25 26

strtoi() transforms the base-n numeral system into base-10 (i.e. decimal) numeral system. Take base-16 (i.e. hexadecimal) for example, strtoi("12", base = 16) will get 18 because 12 in hexadecimal is 18 in decimal. If base is 36, strtoi() will map (1~9, a~z) to 1~35, namely, a~z in a base-36 system is 10~35 in decimal. -9 in my code will convert 10~35 to 1~26, which is what the OP requires. Another common use is to transform binary number into decimal. E.g. strtoi("01001", base = 2) gets 9.

A: library(purrr)
my_fun <- function(x) {
  x %>%
    strsplit("") %>%
    map(factor, levels = letters) %>%
    map(as.numeric)
}

x <- c("abba", "hello")
my_fun(x)
#> [[1]]
#> [1] 1 2 2 1
#>
#> [[2]]
#> [1]  8  5 12 12 15

Here we use that factors are integers under the hood.
Let str be a character vector, e.g. str <- c('a', 'b', 'b', 'a'). When we run factor(str, levels = letters) we convert it to a factor with 26 levels: 'a', 'b', 'c', and so on. If we apply as.integer to it, a will become 1, because it's the first level, 'b' - 2 and so on.


text:
Q: Butchering allies? So, recently my colony came under attack while an allied trading caravan was visiting. With the help of my allies I managed to defeat the raid with no small losses on both sides. Some of my allies died too.
Now my food is running low and I was wondering, will my allies get mad at me if I butcher their dead? My colonists dont really mind, they're all on mental breaks regardless most of the time, but I can deal with that.

A: No, your allies won't mind. Once they're dead you can pretty much do to the bodies what you want. You can even turn their skin into human leather hats and sell those back to your allies.


text:
Q: Finding $\iiint_R e^{\sqrt{(x^2+y^2+z^2)^3}} dA$ with spherical coordinates How to integrate the following expression
$$\iiint_R e^{\sqrt{(x^2+y^2+z^2)^3}} dA\,,$$
where $R$ is a sphere with radius $1$ centered in the origin?
I did
$$\iiint_R e^{\sqrt{(x^2+y^2+z^2)^3}} dA = 4\int_0^{\pi/2} \int_0^{\pi/2} \int_0^1 e^{\sqrt{\rho^3}} \rho^2 \sin{\phi} \,d\rho \,d \phi \,d \theta$$
But my question is if it's correct to consider the first octant, as I did, and then just multiplying it by $4$ since the exponential function relies on positive $z$-axis.

A: The exponent is actually $\sqrt{(\rho^2)^3}=\rho^3$, i.e. your last $\sqrt{}$ operator is unneeded. Then$$\int_0^1\rho^2e^{\rho^3}d\rho=[e^{\rho^3}/3]_0^1=(e-1)/3.$$The rest of the integral is just a factor of the sphere's surface, $4\pi$.
The variable $\sqrt{x^2+y^2+z^2}$ is more normally denoted $r$, though, with $\rho$ preserved for a cylindrical coordinate $\sqrt{x^2+y^2}$.


text:
Q: singleton example how works I've found this singleton example in C++ language:
#include <iostream>

class singleton {
private:
    // ecco il costruttore privato in modo che l'utente non possa istanziare direttamante
    singleton() { };
public:
    static singleton& get_instance()
    {
            // l'unica istanza della classe viene creata alla prima chiamata di get_instance()
            // e verrà distrutta solo all'uscita dal programma
        static singleton instance;
        return instance;
    }
    bool method() { return true; };
};

int main() {
    std::cout << singleton::get_instance().method() << std::endl;

    return 0;
}

But, how can this be a singleton class?
Where is the control of only one istance is created?
Do not miss a static attribute?
What happens if in main function I write another get_instance() call?

A: The one-instance control is done using the function-scope static inside get_instance. Such objects are constructed once upon program flow first passing through them and destructed at program exit. As such, the first time you call get_instance, the singleton will be constructed and returned. Every other time the same object will be returned.
This is often known as the Meyers singleton.

A: I'd like to point you to a rather general description of the pattern and then to a deeper dissertation with a C++ example.
It seems to me more effective than trying to explain (once more again).
P.S.
And yes, you need some static definition too.


text:
Q: Modernizr classes are not applied to the HTML I'm using Modernizr to detect browser features. But this time when I started a project it seems that Modernizr does not apply its classes to the html.
I just realized when I replace my local source to the JS:
<script src="js/libs/modernizr-2.7.1.js"></script>
with:
<script src="http://ajax.cdnjs.com/ajax/libs/modernizr/1.7/modernizr-1.7.min.js"></script>
Then it works like a charm. Why local copy of Modernizr does not work?
CHMODS are 777 and I'm viewing the source by Shift+CTRL+I in Firefox.

A: sounds like your build doesn't have the cssclasses option included from the builder.


text:
Q: Is it possible to use a View inside a RadioButton? I'm trying to create a Fragment where the user can select the line width from 4 options. When they select one of the widths, I set the background with a blue highlight. Is it possible to use a radio group with views inside radio buttons?

Currently this is how I'm doing it:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Checkbox test"
        android:padding="16dp"
        android:textColor="@color/colorBlack"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/background_selected_width_outline"
        android:layout_margin="16dp">

        <View
            android:layout_width="match_parent"
            android:layout_height="15dp"
            android:background="@color/colorBlack"
            android:layout_margin="32dp"/>

    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:background="@color/colorBlack"
        android:layout_margin="32dp"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:background="@color/colorBlack"
        android:layout_margin="32dp"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorBlack"
        android:layout_margin="32dp"/>

</LinearLayout>

A: No its not possible . Check the source code of RadioGroup it directly bypass the add View call to super if if (child instanceof RadioButton) is false . You can create a Custom group to act it like RadioGroup by extending it from LinearLayout.


text:
Q: Swift 3 (SpriteKit): Making a projectile move I was wondering how to apply a force or thrust to a projectile (specifically an SKSpriteNode) to make it continuously move until it hits something. I have tried some ways like setting the velocity like this:
let node = SKSpriteNode(imageNamed: "node")
node.physicsBody = SKPhysicsBody(rectangleOf: node.size)
node.physicsBody.velocity = CGVector(dx: 5, dy: 5)

or instead of changing the node's velocity value at the end, I tried:
node.physicsBody?.applyImpulse(CGVector(dx: 5, dy: 5))

or
node.physicsBody?.applyForce(CGVector(dx: 5, dy: 5))

None of these actually move the projectile. I have even tried adding the same impulse and force forever each frame with an SKAction and there is still no movement. I would really appreciate any help :) Thanks.

A: Try adding a sure fire dynamism to the object:
let node = SKSpriteNode(imageNamed: "node")
node.physicsBody = SKPhysicsBody(rectangleOf: node.size)
// add this, to ensure dynamism:
node.physicsBody.isDynamic = true

Now all forces and impulses should work. Although I'd suggest using much larger numbers. Depends on the size and mass of the object, but you might need numbers a couple of orders of magnitude higher to get rapid movement.


text:
Q: Initializing with GaussianBlurBackgroundProcessor causes tab to freeze on some devices? We have isolated an unusual problem in our ReactJS app with Twilio GaussianBlurBackgroundProcessor occuring with some webcam devices, where enabling GaussianBlurBackgroundProcessor when initializing the video component causes the tab to freeze.
The problem has been observed on Google Chrome 107.0.5304.108 on Windows 10.
One hardware device which triggers this problem reliably is HDP Webcam USB (0c45:636b), however there others (I don't have the model numbers). Most webcams we tested do not experience this problem.
The steps to reproduce are:

*

*Have an affected webcam device

*Add GaussianBlurBackgroundProcessor process on initializing the video component

*Start the video streaming / join the room

*Google Chrome tab freezes - no out of memory, no Javascript error, no console logs, it just stops

Note that:

*

*Initializing the room without GaussianBlurBackgroundProcessor works fine

*Initializing with a background image ie. VirtualBackgroundProcessor also works fine

*Selecting GaussianBlurBackgroundProcessor after the room is already in progress works fine

Our workaround for now is to not load any BackgroundProcessor on initialization, but we would like to preserve the user's default background settings for their next session which necessitates loading GaussianBlurBackgroundProcessor on initialization, if selected.
Can anyone shed some light on why this is happening and how we can avoid it?


text: Q: Finding Riemannian metric explicitly from the conformal structure on a surface Each Riemann surface structure $S'$ on a topological surface $S$ can be obtained from a Riemannian metric which looks like $ds^{2} = g_{11}dx^{2} + 2g_{12}dxdy + g_{22}dy^{2}$ in local coordinates where $g = \begin{pmatrix}g_{11}&g_{12}\\g_{12}&g_{22}\end{pmatrix}$ is a smooth metric. My question is can we find the metric explicitly from a given conformal structure on the topological surface $S$ in certain cases? For example, in the case of a classical Schottky groups for which $2g$ disjoint circles in $\hat{\mathbb{C}}$ are paired by Mobius transformations $a_{i}$, $1\leq i\leq g$, this gives an explicit conformal structure on the genus $g$ handlebody, is there a way to find the metric explicitly? My goal is to find the Beltrami differential associated with such a structure.


text:
Q: Chrome extension AJAX/XHR request handling Couple questions about the implementation of the XHR request:
I am trying to make a form in popup.html that allows for the filling of a box with text (in popup.html) and submits that to a remote website using get and replaces the contents of the box with the return of the php (json).
Heres the code so far:
Any idea why when I click submit nothing happens?
Also the manifest permissions:
  "permissions": [

"https://*/",

"https://*/*"

]
}

A: forms don't need permissions at all to do a cross domain post (in theory).  That being said, the popup.html never reloads in a browser action (or page action) when a form is submitted.
An easy thing to do is to capture onsubmit on the form and simply do an XMLHttpRequest attaching the form as per the Mozilla MDC site.
Which in summary is (copied from mozilla):
var formElement = document.getElementById("myFormElement");
var xhr = new XMLHttpRequest();
xhr.open("POST", "submitform.php");
xhr.send(new FormData(formElement));


text:
Q: how can i fix this error when i try to Using External Database and API's with swift i try to using external database and api's. so i follow from this video in youtube
https://www.youtube.com/watch?v=Ixk93yx-v28
and i see this error
"Value of optional type 'NSURL?' not unwrapped; " on that line
    func request(url:String,callback:(NSDictionary)->()) {
    var nsURL = NSURL(string: url)
    ///////////////////////////on this line/////////////////////////////////
    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
    /////////////////////////////////////////////////////////////////
        (data,response,error) in
        var error:NSError?
        var response = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
        callback(response)
    }
    task.resume()
}

and when i try to fix by put ! in nsURL like this
xCode return this error "Extra argument 'error' in call "
func request(url:String,callback:(NSDictionary)->()) {
    var nsURL = NSURL(string: url)

    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!) {
        (data,response,error) in
        var error:NSError?
////////////////////////////Error Here/////////////////////////////////////
            var response = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
/////////////////////////////////////////////////////////////////////////////////
        callback(response)
    }
    task.resume()
}

have any ideal ? sorry for my english

A: Update your function as shown below for swift 2.0:
func request(url:String,callback:(NSDictionary)->()) {
    guard let nsURL = NSURL(string: url) else { return }
    ///////////////////////////on this line/////////////////////////////////
    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
        /////////////////////////////////////////////////////////////////
        (data, response, error) in
        guard let data = data where error == nil else { return }
        do {
            if let response = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                callback(response)
            }
        } catch let error as NSError {
            print("json error: \(error.localizedDescription)")
        }

    }
    task.resume()
}


text:
Q: iOS: how do you use URL as names of file? I mean how to encode the URL so that it can be converted to a string compatible as a file name, and also it can be decoded back to original URL.

A: First Download base64 encode / decode class
then use the below Code to encode and Decode.
For encoding :
[Base64 initialize];

NSString *str=@"http://www.cogzentappz.com";

NSData *data1 = [str dataUsingEncoding:NSUTF8StringEncoding];

NSString *data2=[Base64 encode:data1];

NSLog(@"data2=%@",data2);

For Decoding below Code :
 NSData * data3 = [Base64 decode:data2]; // data2 is encoded string

NSString * actualString = [[NSString alloc] initWithData:data3 encoding:NSUTF8StringEncoding];
NSLog(@"actualString=%@",actualString);


text:
Q: How to keep sticky navbar within defined body width? My sticky navbar goes from body width (max 1450px) to 100% screen width when scrolling. https://biogenity.com/RC19/index.html
I've defined the body width using CSS:
    body {
      max-width: 1450px;
    }

For the sticky navbar I currently use 100% width, but it doesn't apply within the width of body. I'm not quite sure what to use instead.
    .sticky.is-sticky {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        z-index: 1000;
        width: 100%;
    }

Could this maybe be fixed through the .js?
            $(document).ready(function () {
            // Custom function which toggles between sticky class (is-sticky)
            var stickyToggle = function (sticky, stickyWrapper, scrollElement) {
                var stickyHeight = sticky.outerHeight();
                var stickyTop = stickyWrapper.offset().top;
                if (scrollElement.scrollTop() >= stickyTop) {
                    stickyWrapper.height(stickyHeight);
                    sticky.addClass("is-sticky");
                }
                else {
                    sticky.removeClass("is-sticky");
                    stickyWrapper.height('auto');
                }
            };

            // Find all data-toggle="sticky-onscroll" elements
            $('[data-toggle="sticky-onscroll"]').each(function () {
                var sticky = $(this);
                var stickyWrapper = $('<div>').addClass('sticky-wrapper'); // insert hidden element to maintain actual top offset on page
                sticky.before(stickyWrapper);
                sticky.addClass('sticky');

                // Scroll & resize events
                $(window).on('scroll.sticky-onscroll resize.sticky-onscroll', function () {
                    stickyToggle(sticky, stickyWrapper, $(this));
                });

                // On page load
                stickyToggle(sticky, stickyWrapper, $(window));
            });
        });

Thanks in advance.

A: By using position:fixed you remove the element from the normal document flow so I don't believe the body styles apply.
From position - CSS: Cascading Style Sheets | MDN

The element is removed from the normal document flow, and no space is
  created for the element in the page layout.

So you should set the max-width for it and allow it to be centered by setting left and right to auto:
.sticky.is-sticky {
    position: fixed;
    max-width: 1450px;
    left: auto;
    right: auto;
    top: 0;
    z-index: 1000;
    width: 100%;
}


text:
Q: Combine wrapping and parent element in SASS? I have a specificity issue where styles from a CSS library are overwriting my SASS styles.
My HTML is:
<form class="some-library-class my-form-class">
  <input type="text" class="my-form-class__text">

My SASS is:
.my-form-class {
  //Some wrapper stlyes

  &__text {
    margin: 1rem;
  }
}

However, the library overwrites my style with:
.some-library-class input[type=text] {
  margin: 2rem;
}

Before I go and add extra wrapping classes to my neat SASS and creating too much depth, or start using !important; I wanted to see if there was a way I could modify my existing SASS so the CSS returned is:
.my-form-class .my-form-class__text {
  margin: 1rem;
}

Is there a neat SASS way to achieve the above without messing up my existing SASS too much?

A: .my-form-class {
  //Some wrapper stlyes

  & &__text {
    margin: 1rem;
  }
}

generates
.my-form-class .my-form-class__text {
  margin: 1rem;
}


text:
Q: upload an image with a comments form I have got a comments area on my website. It displays a default image and then a persons comment. I would like to set up the form so that when a person sends a comment they have the option to upload a small image of themselves to the images folder. When the form sends I would like the image_path record to populate where the image is within the images folder. ie images/myphoto.jpg
HERE IS THE FORM
   <form method="post" enctype="multipart/form-data" class="comment-form" action="form-post.php">

First Name:

            <input type="text" name="First" />

Last Name

            <input type="text" name="Last" />

Your Comment:

            <textarea name="Comment" rows="10" cols="60"></textarea>

        <input type="file" name="image_path" accept=".jpeg,.jpg,.png" />

Feel free to upload a small photo of yourself (Optional)

 <input type="submit" name="submit" class="btn btn-primary" value="submit"/>	  All Comments are moderated and will be posted once approved.

</form>

HERE is the FORM HANDLER
 <?php

//$sql = "SELECT ID, firstname, Comment, Image_path FROM comment";
//
//$result = $conn->query($sql);

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$firstname = $_POST["First"];
$lastname = $_POST["Last"];
$comment = $_POST["Comment"];
$imagepath = $_POST["image_path"];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO comment (Comment, firstname, lastname, Image_path, Approved)
VALUES ('$comment', '$firstname','$lastname','$imagepath','2')";

if ($conn->query($sql) === TRUE) {

    echo "
Thankyou - We have received your comment.
";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}
}

$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["image_path"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);

// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {

    if ($target_file == "upload/") {
        $msg = "cannot be empty";
        $uploadOk = 0;
    } // Check if file already exists
    else if (file_exists($target_file)) {
        $msg = "Sorry, file already exists.";
        $uploadOk = 0;
    } // Check file size
    else if ($_FILES["image_path"]["size"] > 5000000) {
        $msg = "Sorry, your file is too large.";
        $uploadOk = 0;
    } // Check if $uploadOk is set to 0 by an error
    else if ($uploadOk == 0) {
        $msg = "Sorry, your file was not uploaded.";

        // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["image_path"]["tmp_name"], $target_file)) {
            $msg = "The file " . basename($_FILES["image_path"]["name"]) . " has been uploaded.";
        }
    }
}
$conn->close();

?>

I have got the information uploading to the database and image uploading to the images folder but the file is not being linked to the image path. Can someone please tell me how to go about this. Thanks.

A: I managed to answer my own question, It was actually quite simple. I used the target file variable and placed it as a value for the image path
<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {

$firstname = $_POST["First"];
$lastname = $_POST["Last"];
$comment = $_POST["Comment"];
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["image_path"]["name"]);
$uploadOk = 1;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO comment (Comment, firstname, lastname, Image_path, Approved)
VALUES ('$comment', '$firstname','$lastname','$target_file','2')";

if ($conn->query($sql) === TRUE) {

    echo "
Thankyou - We have received your comment.
";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}
}

$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["image_path"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);

// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {

    if ($target_file == "upload/") {
        $msg = "cannot be empty";
        $uploadOk = 0;
    } // Check if file already exists
    else if (file_exists($target_file)) {
        $msg = "Sorry, file already exists.";
        $uploadOk = 0;
    } // Check file size
    else if ($_FILES["image_path"]["size"] > 5000000) {
        $msg = "Sorry, your file is too large.";
        $uploadOk = 0;
    } // Check if $uploadOk is set to 0 by an error
    else if ($uploadOk == 0) {
        $msg = "Sorry, your file was not uploaded.";

        // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["image_path"]["tmp_name"], $target_file)) {
            $msg = "The file " . basename($_FILES["image_path"]["name"]) . " has been uploaded.";
        }
    }
}
$conn->close();
?>


text:
Q: Why do the first two functions not execute once the "/" get request is received? Individually, I have verified that the two functions in fact work properly. However, they do not execute when the /dashboard route is loaded. Only res.render works and does its task.
I have tried using promises and such but I just keep getting errors and I do not understand them. Do they need to be in the functions themselves or the code I provided?
// Display the Dashboard Page and Verify User Profile
router.get("/", (req, res) => {
  verifyUser.checkUserExists;
  verifyUser.loadProfileInfo;
  res.render("dashboard");
});

Only res.render("dashboard"); happens and the other two functions dont send anything to my console

A: You need to call your functions.
verifyUser.checkUserExists();
verifyUser.loadProfileInfo();


text:
Q: Can checkpoint flags be turned off? I just bought Forza Horizon 3 yesterday and am loving it so far but I'm wondering if there is a way to turn off checkpoint flags in races? I don't recall seeing anything related to checkpoints in the Difficulty settings but perhaps it's somewhere else.
Thanks in advance.

A: Based on what I've read here:

As long as you keep within the checkpoints, it's fair game.

It sounds like the checkpoints are a core mechanic and not able to be turned off. This is actually the source of a complaint in this review (cached version, original link is actually dead):

the checkpoint placement can be a little frustrating at points – where you'll narrowly miss a checkpoint banner by inches and then be forced to restart the race – which breaks the sheer pace and momentum that Horizon champions everywhere else in the game.

Actually you're not forced to restart the race, your car position is just reset to a place before the missed checkpoint and you just go from there, without stopping the race.


text:
Q: continuous servo position control With a continuous rotation servo I can control the direction and the speed of the servo, but I need to control the position as well. I know it's not possible directly due to lack of feedback control in a continuous servo, but I found some hints about adding an encoder to let you control the position.
Is it possible to add an encoder to a continuous servo to control its position, and if so, how?
Also, can I add a thing to block the motion of the servo like the picture below or would having such a stop effect and damage the servo?

A: Yes, a rotary encoder can be added to any motor, including a servo that has been modified for continuous rotation, and used for position control.
However, this is a bit counter-intuitive, since the servo's internal circuitry already provides position control, using the integrated potentiometer as a rotary sensor. Disconnecting this positioning mechanism, then adding an external position determination sensor or encoder to achieve the same result seems unnecessary.
Be that as it may, the usual method to obtain such position control with a rotary encoder involves bonding the rotary encoder to the shaft of the motor, then taking the encoded values into a microcontroller, using a PID algorithm in the microcontroller, driven as a function of this position information, to control voltage and polarity of the motor for bringing the motor to a halt at the desired position.
In very simplified terms, if the servo's detected position, courtesy the rotary encoder, is clockwise to the desired position, the PID algorithm would rotate the motor anti-clockwise until the two positions are identical. Vice versa for detected position being anti-clockwise to the desired position. If any external torque moves the shaft away from the rest position subsequently, the rotary encoder feeds fresh angular data to the PID code, which then applies the logic outlined above.

Regarding addition of a mechanical stop to a servo motor, this is a feasible approach in general - the motor will draw its stall current, which is higher than normal operating current. You do need to check the datasheet of the motor in question to verify how long it can withstand stall current, though. Not all motors can cope with constant stall.
The solution in such case can be one of the following:

*

*Use code in the microcontroller, along with appropriate current sensing circuitry, to detect when the motor current goes over a calibrated threshold, i.e. the motor stops at the mechanical stop. At such time, stop powering the motor. This is complex, and non-trivial at the circuitry end due to power losses in the sense resistor you use. For large current motors, Hall current sensors or non-invasive sensors can be used, reducing the power loss.

*Use a limit switch instead of a mechanical hard stop, and use the switch close signal as a digital input to your microcontroller, and use code to stop powering the motor when the limit is triggered. This is the simplest and least expensive solution, and safe for the motor as well.

A: The only servos that "lack" movement or position sensing are cheap hobby servos. Those are the worst kind to use for any kind of rugged system. Not only do they only read feedback over a partial arc (not 360 degrees,) but they also don't even return any feedback to the commander at all.
You can buy higher-quality servos with real position encoders, real current sensors, PID controllers for motion control, RS-485 serial communciation both ways, and much more. Those servos can "go to a point" or "rotate at a speed" or do any other kind of motion you want.
For example, I'm putting this guy in my current project:
http://support.robotis.com/en/product/dynamixel/mx_series/mx-64.htm
It's still a "hobby" style servo, but quite capable and so far, real


text:
Q: Date format from 26.09.2011 to 26.9.2011
Possible Duplicate:
Remove leading zeros from abbreviated date with PHP

I have a problem formating date from 26.09.2011 to 26.9.2011.
Of course if there is two digits month there should be two digits (26.12.2011).
I am looking for answer all over web. Could anyone tell me how to acomplish that.
Thanks for answer.

A: http://php.net/manual/en/function.date.php
echo date("j.n.Y");

will print current date in the format you specified.

A: $date = new DateTime('26.09.2011');
echo $date->format('d.n.Y');

m prints two digits month, n prints month without leading zeros.


text:
Q: Filter objects based on a specific category name I'm trying to filter all products whose category name is 'Books'. See below what I have tried but I'm getting an empty queryset.
Here is my models.py just in case:
from django.db import models
from django.urls import reverse

[...]

class Product(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    price = models.DecimalField(decimal_places=2, max_digits=10)
    year = models.PositiveSmallIntegerField()
    image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
    date_added = models.DateTimeField(auto_now=True, null=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE)

    [...]

class Category(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

I have tried this:
>>> from products.models import Product, Category
>>> c = Category(name='Books')
>>> c1 = Category(name='Textbooks', parent=c)
>>> c2 = Category(name='Primary school', parent=c1)
>>> p = Product(title='spam', description='spameggs', price=200, year=2018, category=c2)
>>> for x in (c, c1, c2, p):
...     x.save()
...
>>> Product.objects.get(category=c2)
<Product: Product object (1)>
>>> Product.objects.filter(category__name='Books')
<QuerySet []>
>>> Product.objects.filter(Q(category__name='Books') | Q(category__parent__name='Books') | Q(category__parent__parent__name="Books"))
<QuerySet []>

A: After inspecting the database with a database tool I realised that Category ForeignKey is NULL. The problem was that I was assigning the parents before the parents are saved, which meant that they had no PrimaryKey, so the ForeignKey gets set to NULL.