text:
Q: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly? I did a lot of searching and also read the PHP $_SERVER docs. Do I have this right regarding which to use for my PHP scripts for simple link definitions used throughout my site?
$_SERVER['SERVER_NAME'] is based on your web server's config file (Apache2 in my case), and varies depending on a few directives: (1) VirtualHost, (2) ServerName, (3) UseCanonicalName, etc.
$_SERVER['HTTP_HOST'] is based on the request from the client.
Therefore, it would seem to me that the proper one to use in order to make my scripts as compatible as possible would be $_SERVER['HTTP_HOST']. Is this assumption correct?
Followup comments:
I guess I got a little paranoid after reading this article and noting that some folks said "they wouldn't trust any of the $_SERVER vars":

*

*http://markjaquith.wordpress.com/2009/09/21/php-server-vars-not-safe-in-forms-or-links/

*http://php.net/manual/en/reserved.variables.server.php#89567 (comment: Vladimir Kornea 14-Mar-2009 01:06)
Apparently the discussion is mainly about $_SERVER['PHP_SELF'] and why you shouldn't use it in the form action attribute without proper escaping to prevent XSS attacks.
My conclusion about my original question above is that it is "safe" to use $_SERVER['HTTP_HOST'] for all links on a site without having to worry about XSS attacks, even when used in forms.
Please correct me if I'm wrong.

A: Just an additional note - if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.
$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)
As Mike has noted below, HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

A: The major difference between the two is that $_SERVER['SERVER_NAME'] is a server controlled variable, while $_SERVER['HTTP_HOST'] is a user-controlled value.
The rule of thumb is to never trust values from the user, so $_SERVER['SERVER_NAME'] is the better choice.
As Gumbo pointed out, Apache will construct SERVER_NAME from user-supplied values if you don't set UseCanonicalName On.
Edit: Having said all that, if the site is using a name-based virtual host, the HTTP Host header is the only way to reach sites that aren't the default site.

A: I am not sure and not really trust $_SERVER['HTTP_HOST'] because it depend on header from client. In another way, if a domain requested by client is not mine one, they will not getting into my site because DNS and TCP/IP protocol point it to the correct destination. However I don't know if possible to hijack the DNS, network or even Apache server. To be safe, I define host name in environment and compare it with $_SERVER['HTTP_HOST'].
Add SetEnv MyHost domain.com in .htaccess file on root and add ths code in Common.php
if (getenv('MyHost')!=$_SERVER['HTTP_HOST']) {
  header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
  exit();
}

I include this Common.php file in every php page. This page doing anything required for each request like session_start(), modify session cookie and reject if post method come from different domain.

A: Use either. They are both equally (in)secure, as in many cases SERVER_NAME is just populated from HTTP_HOST anyway. I normally go for HTTP_HOST, so that the user stays on the exact host name they started on. For example if I have the same site on a .com and .org domain, I don't want to send someone from .org to .com, particularly if they might have login tokens on .org that they'd lose if sent to the other domain.
Either way, you just need to be sure that your webapp will only ever respond for known-good domains. This can be done either (a) with an application-side check like Gumbo's, or (b) by using a virtual host on the domain name(s) you want that does not respond to requests that give an unknown Host header.
The reason for this is that if you allow your site to be accessed under any old name, you lay yourself open to DNS rebinding attacks (where another site's hostname points to your IP, a user accesses your site with the attacker's hostname, then the hostname is moved to the attacker's IP, taking your cookies/auth with it) and search engine hijacking (where an attacker points their own hostname at your site and tries to make search engines see it as the 'best' primary hostname).

Apparently the discussion is mainly about $_SERVER['PHP_SELF'] and why you shouldn't use it in the form action attribute without proper escaping to prevent XSS attacks.

Pfft. Well you shouldn't use anything in any attribute without escaping with htmlspecialchars($string, ENT_QUOTES), so there's nothing special about server variables there.

A: This is a verbose translation of what Symfony uses to get the host name (see the second example for a more literal translation):
function getHost() {
    $possibleHostSources = array('HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR');
    $sourceTransformations = array(
        "HTTP_X_FORWARDED_HOST" => function($value) {
            $elements = explode(',', $value);
            return trim(end($elements));
        }
    );
    $host = '';
    foreach ($possibleHostSources as $source)
    {
        if (!empty($host)) break;
        if (empty($_SERVER[$source])) continue;
        $host = $_SERVER[$source];
        if (array_key_exists($source, $sourceTransformations))
        {
            $host = $sourceTransformations[$source]($host);
        }
    }

    // Remove port number from host
    $host = preg_replace('/:\d+$/', '', $host);

    return trim($host);
}

Outdated:
This is my translation to bare PHP of a method used in Symfony framework that tries to get the hostname from every way possible in order of best practice:
function get_host() {
    if ($host = $_SERVER['HTTP_X_FORWARDED_HOST'])
    {
        $elements = explode(',', $host);

        $host = trim(end($elements));
    }
    else
    {
        if (!$host = $_SERVER['HTTP_HOST'])
        {
            if (!$host = $_SERVER['SERVER_NAME'])
            {
                $host = !empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '';
            }
        }
    }

    // Remove port number from host
    $host = preg_replace('/:\d+$/', '', $host);

    return trim($host);
}

A: That's probably everyone's first thought. But it's a little bit more difficult. See Chris Shiflett's article SERVER_NAME Versus HTTP_HOST.
It seems that there is no silver bullet. Only when you force Apache to use the canonical name you will always get the right server name with SERVER_NAME.
So you either go with that or you check the host name against a white list:
$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
    header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
    exit;
}

A:
Is it "safe" to use $_SERVER['HTTP_HOST'] for all links on a site without having to worry about XSS attacks, even when used in forms?

Yes, it's safe to use $_SERVER['HTTP_HOST'], (and even $_GET and $_POST) as long as you verify them before accepting them. This is what I do for secure production servers:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
$reject_request = true;
if(array_key_exists('HTTP_HOST', $_SERVER)){
    $host_name = $_SERVER['HTTP_HOST'];
    // [ need to cater for `host:port` since some "buggy" SAPI(s) have been known to return the port too, see http://goo.gl/bFrbCO
    $strpos = strpos($host_name, ':');
    if($strpos !== false){
        $host_name = substr($host_name, $strpos);
    }
    // ]
    // [ for dynamic verification, replace this chunk with db/file/curl queries
    $reject_request = !array_key_exists($host_name, array(
        'a.com' => null,
        'a.a.com' => null,
        'b.com' => null,
        'b.b.com' => null
    ));
    // ]
}
if($reject_request){
    // log errors
    // display errors (optional)
    exit;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
echo 'Hello World!';
// ...

The advantage of $_SERVER['HTTP_HOST'] is that its behavior is more well-defined than $_SERVER['SERVER_NAME']. Contrast ➫➫:

Contents of the Host: header from the current request, if there is one.

with:

The name of the server host under which the current script is executing.

Using a better defined interface like  $_SERVER['HTTP_HOST'] means that more SAPIs will implement it using reliable well-defined behavior. (Unlike the other.) However, it is still totally SAPI dependent ➫➫:

There is no guarantee that every web server will provide any of these [$_SERVER entries]; servers may omit some, or provide others not listed here.

To understand how to properly retrieve the host name, first and foremost you need to understand that a server which contains only code has no means of knowing (pre-requisite for verifying) its own name on the network. It needs to interface with a component that supplies it its own name. This can be done via:

*

*local config file

*local database

*hardcoded source code

*external request (curl)

*client/attacker's Host: request

*etc
Usually its done via the local (SAPI) config file. Note that you have configured it correctly, e.g. in Apache ➫➫:

A couple of things need to be 'faked' to make the dynamic virtual host look like a normal one.
The most important is the server name which is used by Apache to generate self-referential URLs, etc. It is configured with the ServerName directive, and it is available to CGIs via the SERVER_NAME environment variable.
The actual value used at run time is controlled by the UseCanonicalName setting.
With UseCanonicalName Off the server name comes from the contents of the Host: header in the request. With UseCanonicalName DNS it comes from a reverse DNS lookup of the virtual host's IP address. The former setting is used for name-based dynamic virtual hosting, and the latter is used for** IP-based hosting.
If Apache cannot work out the server name because there is no Host: header or the DNS lookup fails then the value configured with ServerName is used instead.

A: XSS will always be there even if you use $_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME'] OR $_SERVER['PHP_SELF']

A: First I want to thank you for all the good answers and explanations.
This is the method I created based upon all your answer to get the base url. I only use it in very rare situations. So there is NOT a big focus on security issues, like XSS attacks. Maybe someone needs it.
// Get base url
function getBaseUrl($array=false) {
    $protocol = "";
    $host = "";
    $port = "";
    $dir = "";

    // Get protocol
    if(array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] != "") {
        if($_SERVER["HTTPS"] == "on") { $protocol = "https"; }
        else { $protocol = "http"; }
    } elseif(array_key_exists("REQUEST_SCHEME", $_SERVER) && $_SERVER["REQUEST_SCHEME"] != "") { $protocol = $_SERVER["REQUEST_SCHEME"]; }

    // Get host
    if(array_key_exists("HTTP_X_FORWARDED_HOST", $_SERVER) && $_SERVER["HTTP_X_FORWARDED_HOST"] != "") { $host = trim(end(explode(',', $_SERVER["HTTP_X_FORWARDED_HOST"]))); }
    elseif(array_key_exists("SERVER_NAME", $_SERVER) && $_SERVER["SERVER_NAME"] != "") { $host = $_SERVER["SERVER_NAME"]; }
    elseif(array_key_exists("HTTP_HOST", $_SERVER) && $_SERVER["HTTP_HOST"] != "") { $host = $_SERVER["HTTP_HOST"]; }
    elseif(array_key_exists("SERVER_ADDR", $_SERVER) && $_SERVER["SERVER_ADDR"] != "") { $host = $_SERVER["SERVER_ADDR"]; }
    //elseif(array_key_exists("SSL_TLS_SNI", $_SERVER) && $_SERVER["SSL_TLS_SNI"] != "") { $host = $_SERVER["SSL_TLS_SNI"]; }

    // Get port
    if(array_key_exists("SERVER_PORT", $_SERVER) && $_SERVER["SERVER_PORT"] != "") { $port = $_SERVER["SERVER_PORT"]; }
    elseif(stripos($host, ":") !== false) { $port = substr($host, (stripos($host, ":")+1)); }
    // Remove port from host
    $host = preg_replace("/:\d+$/", "", $host);

    // Get dir
    if(array_key_exists("SCRIPT_NAME", $_SERVER) && $_SERVER["SCRIPT_NAME"] != "") { $dir = $_SERVER["SCRIPT_NAME"]; }
    elseif(array_key_exists("PHP_SELF", $_SERVER) && $_SERVER["PHP_SELF"] != "") { $dir = $_SERVER["PHP_SELF"]; }
    elseif(array_key_exists("REQUEST_URI", $_SERVER) && $_SERVER["REQUEST_URI"] != "") { $dir = $_SERVER["REQUEST_URI"]; }
    // Shorten to main dir
    if(stripos($dir, "/") !== false) { $dir = substr($dir, 0, (strripos($dir, "/")+1)); }

    // Create return value
    if(!$array) {
        if($port == "80" || $port == "443" || $port == "") { $port = ""; }
        else { $port = ":".$port; }
        return htmlspecialchars($protocol."://".$host.$port.$dir, ENT_QUOTES);
    } else { return ["protocol" => $protocol, "host" => $host, "port" => $port, "dir" => $dir]; }
}


text:
Q: xCode Console Errors when recording Audio I get the following console errors when recording a sound.. Any ideas what I'm doing wrong? The recordings work, except that the outputs are REALLY soft.
TIA
2011-04-17 12:51:25.707 FlashCards[18561:1210f] Cannot find executable for CFBundle/CFPlugIn 0x5a64780 </Library/Audio/Plug-Ins/HAL/DVCPROHDAudio.plugin> (not loaded)
2011-04-17 12:51:25.708 FlashCards[18561:1210f] Cannot find function pointer NewPlugIn for factory C5A4CE5B-0BB8-11D8-9D75-0003939615B6 in CFBundle/CFPlugIn 0x5a64780 </Library/Audio/Plug-Ins/HAL/DVCPROHDAudio.plugin> (not loaded)
2011-04-17 12:51:25.712 FlashCards[18561:1210f] Cannot find executable for CFBundle/CFPlugIn 0x5c69e90 </Library/Audio/Plug-Ins/HAL/iSightAudio.plugin> (not loaded)
2011-04-17 12:51:25.713 FlashCards[18561:1210f] Cannot find function pointer iSightAudioNewPlugIn for factory 9BE7661E-8AEF-11D7-8692-000A959F49B0 in CFBundle/CFPlugIn 0x5c69e90 </Library/Audio/Plug-Ins/HAL/iSightAudio.plugin> (not loaded)
2011-04-17 12:51:25.729 FlashCards[18561:c503] start recording

As requested, I am adding code:
.h file snippet:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
#import <AudioToolbox/AudioToolbox.h>

@protocol BackViewControllerDelegate;

@interface BackViewController : UIViewController <UITextViewDelegate, AVAudioRecorderDelegate, AVAudioPlayerDelegate, UIAlertViewDelegate>
{
AVAudioRecorder *audioRecorder;
AVAudioPlayer *audioPlayer;
IBOutlet UIButton *playButton;
IBOutlet UIButton *recordButton;
IBOutlet UIActivityIndicatorView *autoCog;
BOOL toggle;
}

@property (nonatomic, retain) IBOutlet UIButton *playButton;
@property (nonatomic, retain) IBOutlet UIButton *recordButton;
@property (nonatomic, retain) IBOutlet UIActivityIndicatorView *autoCog;

-(IBAction) recordAudio;
-(IBAction) playAudio;

.m snippet
@synthesize playButton;
@synthesize recordButton;
@synthesize autoCog;

- (void)viewWillAppear:(BOOL)animated {
    NSLog(@"%s", __FUNCTION__);
    [super viewWillAppear:animated];

    //Start the toggle in false mode. PREMISE: WHEN WE GET HERE FIRST, WE ARE NOT RECORDING
    toggle = NO;

    NSError *error = nil;

    //Instantiate an instance of the AVAudioSession object.
    AVAudioSession * audioSession = [AVAudioSession sharedInstance];

    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];

    //Activate the session
    [audioSession setActive:YES error: &error];
}

-(void) playAudio
{
    NSLog(@"%s", __FUNCTION__);

    if (audioPlayer.playing) {
        [audioPlayer stop];
    }

    if (toggle == NO)
    {
        recordButton.enabled = NO;
        if (audioPlayer)
            [audioPlayer release];
        NSError *error;

        // GET THE APPROPRIATE SOUND FILE NAME
.....

        //CHECK FOR EXISTING SOUNDFILE

        if (![[NSFileManager defaultManager] fileExistsAtPath:soundFilePath])
        {
            UIAlertView *someError = [[UIAlertView alloc] initWithTitle: @"Oops!" message: @"There is not a sound for this word. Press REC to record one. Press cancel to stop" delegate: self
                                                      cancelButtonTitle: @"REC" otherButtonTitles:@"CANCEL", nil];

            [someError show];
            [someError release];
        }

        NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

        AudioSessionSetProperty (
                                 kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
                                 sizeof (doChangeDefaultRoute),
                                 &doChangeDefaultRoute
                                 );

        audioPlayer = [[AVAudioPlayer alloc]
                       initWithContentsOfURL:soundFileURL
                       error:&error];
        audioPlayer.volume = 1.0;
        audioPlayer.delegate = self;

        if (error){
            NSLog(@"Error: %@",
                  [error localizedDescription]);
        }
        else
        {
            [audioPlayer play];

        }
    }
    recordButton.enabled = YES;
    //NSLog(@"end of playAudio");
}

A: I've seen these warnings before,  what happens is you copied another older project? if so this is what i did,  I simply created a new blank project with the newest version of Xcode,  and then started copying the old files into it.
this seemed to clear out those errors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mplot3D plot freezes when plotting in PyCharm Professional Recently when I am doing MatPlotLib 3D plots in PyCharm, the debugging and the plot window are freezing when excuting the plt.show() command. In the top bar of the plot is mentioned (Not Responding). This happens both in PyCharm Community edition 2019 and PyCharm Professional 2021. I am running v3.8 of Python. If I execute plt.show(Block=True), the interactive 3D plot will come up, but I will need to close the figure to continue the debugging.
Does anyone have an idea how I can plot the figure with plt.show(), get up the interactive window, and continue debugging while still having the interactive window open? This worked in my previous version of Python v3.7, but the problem happened recently when upgrading to v3.8.

A: I recently faced the same issue when using matplotlib to plot. This seems to be related to a change in the order of precedence that matplotlib uses to pick its default backend. According to the matplotlibrc file that is bundled with the Python package, the order used to be

MacOSX Qt5Agg Gtk3Agg TkAgg WxAgg Agg

in previous versions (e.g., v3.4.2), while in more recent versions (e.g., v3.5.0) it has been be changed to

MacOSX QtAgg Gtk4Agg Gtk3Agg TkAgg WxAgg Agg

For me, setting the backend to Qt5Agg right after importing matplotlib in Python via
import matplotlib
matplotlib.use("Qt5Agg")

indeed solved the "Not responding" issue. Alternatively, we can specify it through the environment variable MPLBACKEND=Qt5Agg.
Likely, we could also set Qt5Agg as default backend in matplotlibrc either by modifying the bundled matplotlibrc file or by providing our own.
PS: Not sure whether the core issue that prevents the QtAgg backend from working correctly is in PyCharm, matplotlib, or PyQt...


text:
Q: Determining offsetX of a mouseEvent from a particular element with overflow-x: auto I have an element with overflow-x: auto, and I want to be able to click inside this element and determine the left offset (in px) from the left edge of the element. The issue is that this element contains some other elements within it, so I can't just use the raw offsetX property on MouseEvent, as if I ever accidentally click inside one of the nested divs, it will give me the offset from the left padding edge of that inner div, not the element I want to be targeted.
Additionally, I can't just use MouseEvent.clientX - element.offsetLeft, as if I am scrolled into the element at all, it won't return the value that accounts for the now-hidden scrolled-past part of my element.
How can I either:
1 - Determine the distance between the X pos of the mouse event and the left padding edge of my element?
OR
2 - create a workaround to somehow specify the target of the mouseEvent (this is a read-only property, so I'm unsure if this is even possible)?
I am using Typescript and Angular4, and I dob't want to use jQuery, so please don't suggest a jQuery based solution.  Thanks!
Thanks.

A: EDIT
This can also be done by using the HTML DOM property scrollLeft on the container element

Figured out a solution.
We can make sure to only perform mouse movement logic when the offsetX property is with regard to our container element by adding a conditional like so:
if (mouseMoveEvent.clientX - myElement.offsetLeft) <= mouseMoveEvent.offsetX) {
    // Handle mousemove
}
else {
    // Do nothing
}

In the case of this overflow-x:auto element, mouseMoveEvent.offsetX should only ever be greater than or equal to (mouseMoveEvent.clientX - this.element.offsetLeft).
Therefore, if it isn't, that means our mouseMoveEvent.offsetX property is targeting an inner element, and we can just skip the logic in that case.


text:
Q: Material-UI Can't resolve '@material-ui/core/styles/createMuiTheme I know people have posted similar question on StackOverflow, but nothing worked for me, the errors are not the same nor are the fixes, so I am creating a new post.
The firm that is testing me sent me their Github repository and I need to check out that code, it is a Telegram Web app and they are using Material-UI for their design, I cloned the repo installed node_modules and then I got the error from Material-UI ,I followed instructions from other StackOverflow posts but nothing worked for me, uninstalled @material-ui/core and @material-ui/icons, installed them again and still got the same error.
I have tried both NPM and Yarn for installation and nothing. Hope you can help, it is important.
./src/Theme.js
Module not found: Can't resolve '@material-ui/core/styles/createMuiTheme' in '/Users/Faruk/Desktop/int/telegram-react/src'

A: As @Ryan mentioned, createMuiTheme has been renamed to createTheme in the latest v4 and in v5. See the migration guide here for reference.
V5
import { createTheme } from '@mui/material/styles';

V4
import { createTheme } from '@material-ui/core/styles';

A: If you are using material UI V5 or higher, this works;
import { createTheme } from '@mui/material/styles';

A: Don't know about createMuiTheme. but you can use this for importing Styles in Mui. This solved mine on importing styles only,
import styled from '@material-ui/core';

Also it works for Material-ui Box, Paper, Link, Grid all of them. Use like this,
import { Grid, Link, makeStyles, Paper,Box, styled} from '@material-ui/core';

But I'm not sure with your theme .


text:
Q: Git: don't update certain files on Windows We work with a git respository that has over 20,000 files.
My group maintains local versions of about 100 or so of configuration and source files from this repository. THe original acts as a sort of base that several groups modify and tweak to their own needs (some core things are not allowed to be changed, but front end and some custom DB stuff are different between groups)
So we want to update to the latest version generally, but not have the git update overwrite the files that we keep local modifications for.
The machines we use are windows based. Currently the repository gets cloned to a windows server that then gets checked out/cloned to the development machines (which are also windows). The developers make changes as necessary and recommit to our local repo. The local repo updates against the master daily. We never commit back to the master.
So we want all the files that haven't been changed by our group to update, but any that have been changed (ever) won't get updated.
Is there a way to allow this to happen automatically, so the windows server just automatically updates daily, ignoring those files we keep modifications for. And if we want to add a new file to this "don't update" list its just a right-click (or even a flat file list away). I looked at git-ignore but it seems to be for committing, not for updating.
Even better would be a way to automatically download the vanilla files but have them renamed automatically. For example settings.conf is a file we want to keep changes on generally, but if they modify the way entries in that file are handled or add extra options it would be nice it it downloaded it as settings.conf.vanilla or something so we just run a diff on .vanilla files against ours and see what we want to keep. Though this feature is not absolutely necessary and seems unlikely.
If this cannot be accomplished on a windows machine (the software for windows doesn't support such features), please list some Linux options as well if available. We do have an option to use a Linux server for hosting the local git repo if needed.
Thanks.

A: It sounds like you're working with a third party code base that's under active development and you have your own customisations which you need to apply.
I think the answer you're looking for is rebase. You shouldn't need to write any external logic to achieve this, except for a job which regularly pulls in the third party changes and rebases your modifications on top of them.
This should also be more correct than simply ignoring the files you've modified, as you won't then accidentally ignore changes that the third party has made to those files (you may sometimes get a conflict, which could be frustrating, but better than silently missing an important change).
Assuming that your local repo is indeed simply a fork, maintain your changes on your own branch, and every time you update the remote repository, simply rebase your local branch on top of those changes:
git pull origin master
git checkout custom_branch
git rebase master

Edit
After you've done this, you'll end up with all the changes you made on your custom_branch sitting on top of master. You can then continue to make your customisations on your own branch, and development of the third party code can continue independently.
The next time you want to pull in the extra changes, you'll repeat the process:
Make sure you're on the master branch before pulling in changes to the third party code:
git checkout master

Pull in the changes:
git pull origin master

Change to your customised branch:
git checkout custom_branch

Move your changes on top of the third party changes:
git rebase master

This will then put all your own changes on top of master again. master itself won't be changed.
Remember that the structure of your repo just comes from a whole set of "hashes" which form a tree. Your branches are just like "post it" notes which are attached to a particular hash, and can be moved to another hash as your branch grows.
The rebase is like chopping off a branch and re-attaching it somewhere else. In this case, you're saying something like "chop off our changes and re-attach them on top of the main trunk".
If you can install a visual tool like GitX, it will really help to see how the branch tags move around when you rebase. The command line is ideal for working with but I find something like GitX is invaluable for getting a handle on the structure of your repo.


text:
Q: Javascript: Efficiently move items in and out of a fixed-size array If I have an array that I want to be of fixed size N for the purpose of caching the most recent of N items, then once limit N is reached, I'll have to get rid of the oldest item while adding the newest item.
Note: I don't care if the newest item is at the beginning or end of the array, just as long as the items get removed in the order that they are added.
The obvious ways are either:

*

*push() and shift() (so that cache[0] contains the oldest item), or

*unshift() and pop() (so that cache[0] contains the newest item)

Basic idea:
var cache = [], limit = 10000;

function cacheItem( item ) {

    // In case we want to do anything with the oldest item
    // before it's gone forever.
    var oldest = [];

    cache.push( item );

    // Use WHILE and >= instead of just IF in case the cache
    // was altered by more than one item at some point.
    while ( cache.length >= limit ) {
        oldest.push( cache.shift() );
    }

    return oldest;
}

However, I've read about memory issues with shift and unshift since they alter the beginning of the array and move everything else around, but unfortunately, one of those methods has to be used to do it this way!
Qs:

*

*Are there other ways to do this that would be better performance-wise?

*If the two ways I already mentioned are the best, are there specific advantages/disadvantages I need to be aware of?

Conclusion
After doing some more research into data structures (I've never programmed in other languages, so if it's not native to Javascript, I likely haven't heard of it!) and doing a bunch of benchmarking in multiple browsers with both small and large arrays as well as small and large numbers of reads / writes, here's what I found:

*

*The 'circular buffer' method proposed by Bergi is hands-down THE best as far performance (for reasons explained in the answer and comments), and hence it has been accepted as the answer. However, it's not as intuitive, and makes it difficult to write your own 'extra' functions (since you always have to take offset into account). If you're going to use this method, I recommend an already-created one like this circular buffer on GitHub.

*The 'pop/unpush' method is much more intuitive, and performs fairly well, accept at the most extreme numbers.

*The 'copyWithin' method is, sadly, terrible for performance (tested in multiple browsers), quickly creating unacceptable latency. It also has no IE support. It's such a simple method! I wish it worked better.

*The 'linked list' method, proposed in the comments by Felix Kling, is actually a really good option. I initially disregarded it because it seemed like a lot of extra stuff I didn't need, but to my surprise....

What I actually needed was a Least Recently Used (LRU) Map (which employs a doubly-linked list). Now, since I didn't specify my additional requirements in my original question, I'm still marking Bergi's answer as the best answer to that specific question. However, since I needed to know if a value already existed in my cache, and if so, mark it as the newest item in the cache, the additional logic I had to add to my circular buffer's add() method (primarily indexOf()) made it not much more efficient than the 'pop/unpush' method. HOWEVER, the performance of the LRUMap in these situations blew both of the other two out of the water!
So to summarize:

*

*Linked List -- most options while still maintaining great performance

*Circular Buffer -- best performance for just adding and getting

*Pop / Unpush -- most intuitive and simplest

*copyWithin -- terrible performance currently, no reason to use

A:
If I have an array that caches the most recent of N items, once limit N is reached, I'll have to get rid of the oldest while adding the newest.

You are not looking to copy stuff around within the array, which would take O(n) steps every time.
Instead, this is the perfect use case for a ring buffer. Just keep an offset to the "start" and "end" of the list, then access your buffer with that offset and modulo its length.
var cache = new Array(10000);
cache.offset = 0;

function cacheItem(item) {
    cache[cache.offset++] = item;
    cache.offset %= cache.length;
}
function cacheGet(i) { // backwards, 0 is most recent
    return cache[(cache.offset - 1 - i + cache.length) % cache.length];
}

A: You could use Array#copyWithin.

The copyWithin() method shallow copies part of an array to another location in the same array and returns it, without modifying its size.
Description
The copyWithin works like C and C++'s memmove, and is a high-performance method to shift the data of an Array. This especially applies to the TypedArray method of the same name. The sequence is copied and pasted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap.
The copyWithin function is intentionally generic, it does not require that its this value be an Array object.
The copyWithin method is a mutable method. It does not alter the length of this, but will change its content and create new properties if necessary.

var array = [0, 1, 2, 3, 4, 5];

array.copyWithin(0, 1);

console.log(array);

A: You need to splice the existing item and put it in the front using unshift (as the newest item). If the item doesn't already exist in your cache, then you can unshift and pop.
function cacheItem( item )
{
    var index = cache.indexOf( item );
    index != -1 ?  cache.splice( index, 1 ) : cache.pop();
    cache.unshift( item );
}

item needs to be a String or Number, or otherwise you'll need to write your own implementation of indexOf using findIndex to locate and object (if item is an object).


text:
Q: Issue with SwiftUI Segmented Picker I am relatively new to SwiftUI and I'm trying to work on my first app. I am trying to use a segmented picker to give the user an option of changing between a DayView and a Week View. In each on of those Views, there would be specific user data that whould be shown as a graph. The issue I am having is loading the data. I posted the code below, but from what I can see, the issue comes down to the following:
When the view loads in, it starts with loading the dayView, since the selectedTimeInterval = 0. Which is fine, but then when the users presses on the "Week" in the segmented Picker, the data does not display. This due to the rest of the View loading prior to the .onChange() function from the segmented picker running. Since the .onChange is what puts the call into the viewModel to load the new data, there is no data. You can see this in the print statements if you run the code below.
I would have thought that the view load order would have been
load segmented picker
run the .onChange if the value changed
load the rest of the view
but the order actual is
load segmented picker,
load the rest of the view (graph loads with no data here!!!!!)
run the .onChange if the value has changed.
I am pretty lost so any help would be great! Thank you so much!
import SwiftUI
import OrderedCollections

class ViewModel: ObservableObject{
    @Published var testDictionary: OrderedDictionary<String, Int> = ["":0]

    public func daySelected() {
        testDictionary = ["Day View Data": 100]
    }

    public func weekSelected() {
        testDictionary = ["Week View Data": 200]
    }
}

struct ContentView: View {
    @State private var selectedTimeInterval = 0
    @StateObject private var vm = ViewModel()

    var body: some View {
        VStack {
            Picker("Selected Date", selection: $selectedTimeInterval) {
                Text("Day").tag(0)
                Text("Week").tag(1)
            }
            .pickerStyle(SegmentedPickerStyle())
            .onChange(of: selectedTimeInterval) { _ in
                let _ = print("In on change")
                //Logic to handle different presses of the selector
                switch selectedTimeInterval {
                case 0:
                    vm.daySelected()
                case 1:
                    vm.weekSelected()
                default:
                    print("Unknown Selected Case")
                }
            }
            switch selectedTimeInterval {
            case 0:
                let _ = print("In view change")
                Day_View()
            case 1:
                let _ = print("In view change")
                Week_View(inputDictionary: vm.testDictionary)
            default:
                Text("Whoops")
            }
        }
    }
}

struct Day_View: View {

    var body: some View {
        Text("Day View!")
    }
}

struct Week_View: View {
    @State private var inputDictionary: OrderedDictionary<String,Int>

    init(inputDictionary: OrderedDictionary<String,Int>) {
        self.inputDictionary = inputDictionary
    }

    var body: some View {

        let keys = Array(inputDictionary.keys)
        let values = Array(inputDictionary.values)
        VStack {
            Text(keys[0])
            Text(String(values[0]))
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: In your WeekView, change
@State private var inputDictionary: OrderedDictionary<String,Int>

to
private let inputDictionary: OrderedDictionary<String,Int>

@State is for the local state of the view. The idea is that you are initing it with initial state and from then on the view itself will change it and cause re-renders. When the WeekView is re-rendered, SwiftUI is ignoring the parameter you pass into the init and copying it from the previous WeekView to maintain state.
But, you want to keep passing in the dictionary from ContentView and cause re-renders from the parent view.

A: The main issue is that the initialization of the @State property wrapper is wrong.
You must use this syntax
@State private var inputDictionary: OrderedDictionary<String,Int>

init(inputDictionary: OrderedDictionary<String,Int>) {
    _inputDictionary = State(wrappedValue:  inputDictionary)
}

Or – if inputDictionary is not going to be modified – just declare it as (non-private) constant and remove the init method
let inputDictionary: OrderedDictionary<String,Int>


text:
Q: Solving For Value in Product Series Consider the function
$$f(x)=\frac{(1+2x)^\frac{1}{2}(1+4x)^\frac{1}{4}\cdot\cdot\cdot(1+2nx)^\frac{1}{2n}}{(1+3x)^\frac{1}{3}(1+5x)^\frac{1}{5}\cdot\cdot\cdot(1+(2m+1)x)^\frac{1}{2m+1}}$$
where $n$ and $m$ are positive integers satisfying $n+m-20=f'(0)=2010$. Then $n=$?
Not sure how to approach this question.

A: $f(x)$ is given in the form $$f(x)=\dfrac{\displaystyle\prod_{j=1}^n (1+2jx)^{1/2j}}{\displaystyle\prod_{k=1}^m\Big(1+(2k+1)x\Big)^{1/(2k+1)}}\\ \implies \ln (f(x))=\sum_{j=1}^n \dfrac1{2j}\ln\Big(1+2jx\Big)-\sum_{k=1}^m \dfrac{1}{2k+1}\ln\Big(1+(2k+1)x\Big)$$ and differentiating with respect to $x$ on both sides, you should get $$\dfrac{f'(x)}{f(x)}=\sum_{j=1}^n \dfrac1{2j}\dfrac{2j}{(1+2jx)}-\sum_{k=1}^m\dfrac{1}{2k+1}\dfrac{2k+1}{(1+(2k+1)x)} \qquad (1)$$
You already have $n+m=2010+20$, what do you get when you put $x=0$ in $(1)$? Value of $f'(0)$ is given to you, and $f(0)=?\cdots$

The final result should be $n=2020$.


text:
Q: Frequency of a response to occur Suppose I have three data sets (a control group, a group under the first medication and a group under the second medication). The data is non-parametric, groups are equally distributed and their size is small. I want to analyse the frequency of a certain response (so it is a "yes or no" type of problem; they either had the response or didn't have). What method works better to calculate the probability that this response will occur in each group?
I was told Fisher's exact test is probably the best method, but I'm not sure how I would do it. From what I've read the tables are $2 \times 2$ and I'm not sure how I would fit the control group in it. Does it even make sense to use this method? Is there a way to analyse three groups with this test? Is there any other method? I need some answers.
Help?

A: You could use a chi-squared test on a $2\times 3$ matrix of counts, where columns are 'Control', '1st', and '2nd' groups. Hypothetical data below.
y = c(21, 32, 38)
n = c(79, 68, 62)
MAT = rbind(y, n)
chisq.test(MAT)

        Pearson's Chi-squared test

data:  MAT
X-squared = 7.0351, df = 2, p-value = 0.02967

From the P-value, we see that the result is significant at the 5% level (also the 3% level). That is, we reject the null hypothesis that positive and negative responses are equally likely in all three groups.
If counts are very small so that you get error messages, then you could use the simulation option
of chisq.test (with parameter sim=T) or Fisher's exact test in R using 'fisher.test` which will work with a $2\times 3$ matrix (giving P-value $0.0207).$
Addendum per comment: Data with no Yes's in Control group.
y = c(0, 32, 38)
n = c(100, 68, 62)
MAT = rbind(y, n)
chisq.test(MAT)

        Pearson's Chi-squared test

data:  MAT
X-squared = 46.658, df = 2, p-value = 7.383e-11

Even though there are no Yes's in the Control group, the expected counts are all well above 5. However, maybe you should consider what it means to include the control group.
 chisq.test(MAT)$exp
      [,1]     [,2]     [,3]
y 23.33333 23.33333 23.33333
n 76.66667 76.66667 76.66667


text:
Q: Wrong path when downloading in Backpack CRUD view i added an upload field in my CRUD Controller.
Upload works fine and file gets loaded in my /storage/private directory.
Here is filesystems.php file:
    'private' => [
        'driver' => 'local',
        'root' => storage_path('private')
    ],

Here are my custom functions in the File.php Model:
public static function boot()
{
    parent::boot();
    static::deleting(function($file) {
        \Storage::disk('private')->delete($file->file);
    });
}

public function setFileAttribute($value)
{
    $attribute_name = "file";
    $disk = "private";
    $destination_path = "";
    // Cifratura del file
    file_put_contents($value->getRealPath(), file_get_contents($value->getRealPath()));
    $this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path);
}

And here is my FileCRUDController.php code:
    $this->crud->addField(
    [   // Upload
        'name' => 'file',
        'label' => 'File to upload',
        'type' => 'upload',
        'upload' => true,
        'disk' => 'private'
    ]);

When i try to download the file, however, it tries to fetch it from http://localhost:8000/storage/myfile.png instead of http://localhost:8000/storage/private/myfile.png
What i'm doing wrong? Thank you very much.
I would also like to know if there is a way to hook a custom function instead downloading the file directly from the CRUD view. My files are encrypted and i need a controller that cares about decrypting before sending the files to the user.

A: Method url() is still not usable for the files are placed in subdirectories.
You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:
$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');

In reference to Issue #13610
The following works for version 5.3:
'my-disk' => [
    'driver' => 'local',
    'root'   => storage_path(),
    'url'    => '/storage'
],

\Storage::disk('my-disk')->url('private/myfile.png')

this should return "/storage/private/myfile.png"


text:
Q: need to display main headers and sub headers in table view dynamically ios I need to display tableview with two headers.

need to load those data dynamically, with two headers.

A: Use
 override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch section {
        case 0:
            return "Bat-and-ball"
        case 1:
            return "Hockey"
        default:
            return "other header"
        }
    }


text:
Q: How to export every TikZ image to a separate pdf file? I'm creating some graphs for my thesis in a single .tex file using the TikZ package in LaTeX.
I'm using the standalone document class so that my graphs are generated without whitespaces.
How can I export every graph in a separate PDF file so I can load them individually in another project?

A: When you compile generate1.tex file, it will produce generate1.pdf file. When you rename the .tex file (f.e. generate2.tex), new pdf will also have different name (generate2.pdf), thus the old pdf won't be deleted.
If you want to display TikZ images only, use \PreviewEnvironment{tikzpicture}. If you are interested, you can find the sample code here.
If you want to load them, use includepdf.

A: The tikz library external does just what you want:
\usetikzlibrary{external}
\tikzexternalize

It will generate one PDF per tikzpicture. You can define an output directory with:
\tikzexternalize[prefix=./dir]


text:
Q: Apache mod rewrite not working in Mac Sierra Apache version is 2.4,rewrite mod is active in httpd.conf
AllowOverRide is set to all and require all granted in vhost config
I am just getting a 404 not found error.
Am I missing any setting?

A: Double check that all the document roots have AllowOveride All. It should listen to the closest node in the folder hierarchy but in my experience wasn't the case.
The primary <Directory /> section in http.conf was defaulted as None.

A: I had the same thing, but in my case I had multiple PHP version, and was editting the wrong httpd.conf file.
The configuration of OSX native PHP is in /etc/apache2/httpd.conf
Hope this helps.


text:
Q: How to constrain randomness I'm drawing a random shape with vertices onto a canvas.
Sometimes the shape is very narrow and small.
Is there a way to constrain the randomness so this wont happen.
As I am very new to p5 any tips would be appreciated.
Thanks for your time and help
let noOfShapes = 3;

function setup(){
    createCanvas(1240, 1754);
    noLoop();
    background(0,230)
    colorMode(RGB)
    rectMode(CENTER);
    strokeWeight(3);

}

function draw(){
    //fill(56, 37, 34);

    for(let x = 0; x < noOfShapes; x++) {
      beginShape();
      stroke(255);
      fill(25, 255, 255,100);
      //noFill();
        for(let y = 2; y < 6; y++) {
          vertex(random(10,width), random(10,width))
          // vertex(random(10,width), random(10,width))
          // vertex(random(10,width), random(10,width))
          // vertex(random(10,width), random(10,width))
        }
      endShape(CLOSE);
    }
    stroke(255);

    for(let x=20; x<= width; x = x+20){
        blendMode(DODGE);
        //fill(200,200,200)
        stroke(255);
        beginShape();
          vertex(x, 0)
          vertex(x, height+20)
        endShape();
    }

}

A: Create a list of random numbers for the x and y coordinates:
rx = []; ry = [];
for (let y = 0; y < 4; y++) {
    rx.push(random(10, width-20));
    ry.push(random(10, height-20));
}

Compute the difference between the minimum (min) and maximum (max) for each list:
drx = max(rx) - min(rx);
dry = max(ry) - min(ry);

Define a threshold an repeat the process as long any of the differences is below the threshold:
let threshold = 200;
do {

  // [...]
}
while (drx < threshold || dry < threshold)

The algorithm can be further improved, by taking into account the distance between the points along 45° diagonals. Use the Dot product to calculate the distances:
rd1.push(rx[y]*0.707 + ry[y]*0.707);
rd2.push(rx[y]*0.707 - ry[y]*0.707);

Use the random coordinates to generate the shape:
let threshold = 400;
let rx, ry, drx, dry, rd1, rd2, drd1, drd2;
do {
    rx = []; ry = []; rd1 = []; rd2 = [];
    for (let y = 0; y < 4; y++) {
        rx.push(random(10, width-20));
        ry.push(random(10, height-20));
        rd1.push(rx[y]*0.707 + ry[y]*0.707);
        rd2.push(rx[y]*0.707 - ry[y]*0.707);
    }
    drx = max(rx) - min(rx);
    dry = max(ry) - min(ry);
    drd1 = max(rd1) - min(rd1);
    drd2 = max(rd2) - min(rd2);
}
while (drx < threshold || dry < threshold || drd1 < threshold || drd2 < threshold)

beginShape();
stroke(255);
fill(25, 255, 255,100);
//noFill();
for (let y = 0; y < rx.length; y++) {
    vertex(rx[y], ry[y]);
}
endShape(CLOSE);

let noOfShapes = 1;

function setup(){
    createCanvas(1240, 1754);
    noLoop();
    background(0,230)
    colorMode(RGB)
    rectMode(CENTER);
    strokeWeight(3);
}

function draw(){
    for(let x = 0; x < noOfShapes; x++) {

        let threshold = 400;
        let rx, ry, drx, dry, rd1, rd2, drd1, drd2;
        do {
            rx = []; ry = []; rd1 = []; rd2 = [];
            for (let y = 0; y < 4; y++) {
                rx.push(random(10, width-20));
                ry.push(random(10, height-20));
                rd1.push(rx[y]*0.707 + ry[y]*0.707);
                rd2.push(rx[y]*0.707 - ry[y]*0.707);
            }
            drx = max(rx) - min(rx);
            dry = max(ry) - min(ry);
            drd1 = max(rd1) - min(rd1);
            drd2 = max(rd2) - min(rd2);
        }
        while (drx < threshold || dry < threshold || drd1 < threshold || drd2 < threshold)

        beginShape();
        stroke(255);
        fill(25, 255, 255,100);
        //noFill();
        for (let y = 0; y < rx.length; y++) {
            vertex(rx[y], ry[y]);
        }
        endShape(CLOSE);
    }
    stroke(255);

    for(let x=20; x<= width; x = x+20){
        blendMode(DODGE);
        //fill(200,200,200)
        stroke(255);
        beginShape();
          vertex(x, 0)
          vertex(x, height+20)
        endShape();
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>


text:
Q: Internal exception has occured: Type '<>f__AnonymousType2`6[...]' cannot be serialized I have written an endpoint in ASP.net (which should give back a nice JSON) and the following error puzzles me since via my Swagger interface, everything works fine, but if I call the endpoint directly in a browser with http://localhost:63291/api/AutoUpload/, I receive:

Internal exception has occured: Type '<>f__AnonymousType2`6[System.String,System.DateTime]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized  with the DataMemberAttribute attribute.  If the type is a collection, consider marking it with the CollectionDataContractAttribute.
  See the Microsoft .NET Framework documentation for other supported types.

This seems strange, because I was thinking that I did indeed implement a parameter-less (default) constructor. My code reads as follows
using AutoMapper;
using myProject.API.Filters;
using myProject.API.Models;
using myProject.Entity.DAL;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
namespace myProject.API.Controllers
{
    [UserAuthenticationFilter]
    public class AutoUploadController : BaseController
    {
        public AutoUploadController() {
            System.Diagnostics.Debug.WriteLine("Parameterless default constructor only for serialization");
        }

        // GET: api/AutoUpload
        [ResponseType(typeof(IEnumerable<FilesDetailsDto>))]
        public IHttpActionResult GetAutoUpload(string OptionString = "status")
        {
            if (OptionString == "status")
            {
                var rootLocation = ConfigurationManager.AppSettings["ROOT-FOLDER-LOCATION"];
                string[] entries = Directory.GetFiles(rootLocation, "*.csv", SearchOption.AllDirectories);
                var convList = entries.Select(x => new
                {
                    FullPath = x,
                    LastModifed = System.IO.File.GetLastWriteTime(x)
                });

                return Ok(convList.AsEnumerable());
            } // end IF-clause for optional parameter
            else
            {
                return NotFound();
            }
        }
    }
}

The above piece of code uses the following data transfer object (DTO) definition:
using System;

namespace myProject.API.Models
{
    public class FilesDetailsDto
    {
        public string FileName { get; set; }
        public DateTime LastModifiedOnFilesystem { get; set; }
    }
}

References

*

*Datacontract exception. Cannot be serialized

A: You are returning collection of anonymous type instead of your actual type defined as attribute which can be the culprit for this error.
You can try to be more explicit when using the Select here something like:
var convList = entries.Select(x => new FilesDetailsDto()
            {
                FullPath = x,
                LastModifiedOnFilesystem = System.IO.File.GetLastWriteTime(x)
            });


text:
Q: How to set line width as zero for one line in google line chart

In above example how to set line width=0 for Expenses.so that I can see only dots for expenses line. Actually I need to implement in project.
In project for each sub I created a line graph and in each graph one line for student marks in that subject and another line contains highest marks in that subject for each exam.Highest mark in subject in not belong to only one student so I d'not want show it line.
Thank you for any help in this.
I have one working Example but it working when user click legend text.I want it work on page load.

            https://www.google.com/jsapi'>

Working Solution

        https://www.google.com/jsapi'>


text:
Q: TeamCity - Cucumber Acceptance Tests failing during day but passing in overnight build We're testing a web app using Cucumber and the PageObject gem, running CI on TeamCity. We've hit on a problem that none of us can solve.
We're accessing two drop-downs whose combined contents generate a field of radio selections. When I run this from my local machine, it passes but when run from the integration server against the same environment, it fails most of the time...
...except at night. I configured some scheduled builds so I could observe it in a stable environment and it consistently passes overnight.
The error it throws is that the country drop-down (the second field, dependent on 'client', which is the first) doesn't contain the value for selection. I've examined it manually and it appears that the Client box is empty.
The automation code giving rise to the error is below. Please note that I've tried several methods to access this including dropping down to Watir Webdriver but none have made any difference.
DO you think this is just a simple performance issue? I don't see how it can be because the test agents only run one project at a time so theoretically they should perform the same regardless of build load.
def safe_select_client(value, attempts = 10)

  count_attempts_to(attempts)do
    self.client_code = value
    if self.client_code_element.selected? value
      next
    else
      $stdout.puts attempts-1
      safe_select_client(value, attempts-1)
    end
  end
end

def safe_select_country(value, attempts = 10)
  count_attempts_to(attempts) do
    self.client_country = value
    if self.client_country_element.selected? value
      next
    else
      safe_select_country(value, attempts-1) unless self.client_country_element.selected? value
    end
  end
end

def safe_select_proposition(value, attempts = 10)
  count_attempts_to(attempts) do
    self.select_default_proposition
    safe_select_proposition(value, attempts-1) unless default_proposition_selected?
  end
end

A: I have a solution for this.
The app developers looked into this and discovered that the bug was related to application robustness, not test code: the client was caching the values for the drop-downs. It's bug which would never have been uncovered - or would have been discovered in production, with a far costlier fix - if it weren't for automated acceptance testing.
Thanks all.

A: It seems like a performance issue in that the script is trying to set the country dropdown before it has finished loading.
Without knowing what the count_attempts_to method does, it looks like your code attempts to set the dropdown value and re-attempt it many times. However, if the value does not exist, the re-tries probably do not get run since an exception would already have been thrown. Even if the retry portion worked, the retries appear immediate, so the dropdown may still not have loaded.
You should likely be using the built in waiting methods instead - see http://watirwebdriver.com/waiting/.
Assuming that count_attempts_to is just part of your retry mechanism, I think you could rewrite the country method (and the others) like:
def safe_select_country(value)
  self.client_country_element.option(:value => value).when_present.set
end

This says wait for the option for up to 30 seconds. When it is found, select it.


text:
Q: power supply for electrophoresis [100 V from 230V mains] i am trying to make a power supply for electrophoresis, which requires 100V DC. The project is a funded non-profit for some schools, where there are strict requirements when it comes to the individual price.
One way to make the power supply is as posted in this instructable, where they use a boost converter from a 15v DC supply: http://www.instructables.com/id/Gel-electrophoresis-power-supply/. I have found that this in components will cost about 10$ plus the power supply.
Another way, would be to use the mains directly with a bridge rectifier trough a series resistor to a zener diode with breakdown of 100 volt. I know that it should supply between 200mA and 350mA of current when it is connected.

simulate this circuit – Schematic created using CircuitLab
The top circuit is the one i have tried and the only problem is that the resistor has to dissipate quite a lot of heat. But is has been tested to work.
The bottom circuit is one i found somewhere, which has next to no power dissipation, except for in the load.
The question stands, is there a better way to do it or is the proposed circuit safe. And will the alternative circuit work when you put 230V RMS on it? The circuit was found for lower voltages around 12V, so can i find a transistor that can handle my specs? The benefit of the zener versions is that they can be connected directly to the mains and doesn't need a separate dc power supply, which saves money.

A: The circuits you propose are dangerous ones. The reason for this is that your circuits are directly mains connected and therefore live.
That means that if you (or any other person) touches part of the circuit or the liquid you use for the electrophoresis might get an electric shock.
What is needed to fix this (I hope that you agree that a mains live setup is not desirable) is mains isolation. That's why the instructable example uses a 15 V adapter. This provides the much needed mains isolation. That 15 V output voltage is safe to touch.
Of course one can still get a shock from the 100 V but then you'd need to touch at two points (with 100 V between them) (and assuming the setup is not grounded) instead of getting a shock from touching it at any point.
Also the 100 V for the electrophoresis will be low-current so you might get a shock but since the current cannot be maintained, it will not be lethal. In your circuits the current can keep flowing so they are lethal !
Since the 100 V you need for the electrophoresis needs very little current, only a relatively simple circuit is needed.
You do not need (to buy) that specific 15 V adapter, almost any mains adapter you already have for charging a phone, laptop or some other household appliance, might suffice. The circuit used to make the 100 V DC from the adapter's output voltage might need some modifications though but these will be minor.
But please forget about the circuits you proposed, they're dangerous and also very inefficient ways of getting the voltage you need. Sure, going down to 15 V and then up again to 100 V might sound silly as well but it does not consume much power and is much safer.

A: 1) You need to talk to somebody who is competent in these matters to find out what your load requirements really are. 300 mA for electrophoresis is an outrageous current level. Put it this way - at a 100 volt level this implies that the medium will be dissipating 30 watts. To which I can only say, oh really? Are you trying to cook the sample as well as analyze it? So go find a second opinion on your current level. This will greatly impact your design requirements.
2) Your tested design is, well, I don't think you've thought it through. Not only does the 600 ohm resistor dissipate "quite a lot of heat", like 30 watts or more, but it will have to do so in an enclosed volume, and I don't think you realize just how hot it will get unless you include provisions for forced air flow to cool it. This, of course, will make it difficult to make your enclosure safe for school use. You will have three safety issues, rather than two. Shock, heat AND fan blades. Oh yes, and if the load is disconnected for any reason the zener diode must dissipate the entire 30 watts, and a zener of that size (plus the heat sink required) is going to set you back a pretty penny.
3) Your proposed circuit will give better performance than your first, but at the least you need a power transistor mounted on a heat sink. A 3904 will fail almost immediately. Additionally, your 40k zener resistor will only allow about 3 mA of current to the zener (less when you consider the transistor base requirements) and this will not be enough to drive the zener properly.
4) In either case, your 47 uF capacitors are entirely inadequate for the job, unless you don't mind major voltage changes at a 100 Hz rate. Neither circuit is up to the job of providing 100 volts DC at 300 mA.


text:
Q: Dynamic active class with variables php I want to add class= "active" to my link using php but the challenge am having is that my links have variables attached to them .php?foobar=somevariable. so, some how the class active is being ignored. Here is my snippet
<?php
//we need to set a var to find what page we are on
$pageOn2 = basename($_SERVER['PHP_SELF']);

?>

And below is my html
<li class="<?php if($pageOn2 == 'regionalsummits.php?summit=eastern'){?> current-menu-item <?php }?>">
                                Eastern Region

                             <li class="<?php if($pageOn2 == 'regionalsummits.php?summit=southern'){?> current-menu-item<?php }?>">
                                South Western Region

                            <li class="<?php if($pageOn2 == 'regionalsummits.php?summit=western'){?> current-menu-item<?php }?>">
                                Western Region

Any help on where am goinh wrong

A: try saving paramater in variable and then check
<?php
$variable = $_GET['foobar'];
?>

<li class="<?php if($variable == 'eastern'){ echo 'current-menu-item'; } ?>"> Eastern Region

<li class="<?php if($variable == 'southern'){ echo 'current-menu-item'; }?>"> South Western Region

<li class="<?php if($variable == 'western'){ echo 'current-menu-item'; } ?>"> Western Region

A: $pageOn2 = basename($_SERVER['PHP_SELF']); in this line of code the variable $pageOn2 will recieve the value regionalsummits.php it will not get the query string cuz basename($_SERVER['PHP_SELF']); this will not return the query string
so you can do this like:
$pageOn2 = basename($_SERVER['PHP_SELF'])."?".$_SERVER['QUERY_STRING'];

A: Try in this way ,you can do it some other way .
I have added a snippet for the better understanding.

<?php
$pageOn2 = $_SERVER["QUERY_STRING"];
?>
<li class="<?php if ($pageOn2 == 'summit=eastern') { ?> current-menu-item <?php } ?>">
    Eastern Region

<li class="<?php if ($pageOn2 == 'summit=southern') { ?> current-menu-item<?php } ?>">
    South Western Region

<li class="<?php if ($pageOn2 == 'summit=western') { ?> current-menu-item<?php } ?>">
    Western Region


text:
Q: AngularJS2: NgFor template inside Template is not working correctly UPDATE: This a bug in Angular <=2.4.1. See my "proof" posting below.
I have a problem with AngularJS (2.2) with For loop templates inside templates to display an array inside an array.
See the MWE below. The first picture shows the start situation, If you press the button once, I get the desired output, however if I press the button again I get strange output (FIELD: 2 SUBFIELD: 2 expected)
It seems that the for loop does not work correctly anymore once initialized. How can I fix this?
If I remove the inner-For template, I get the desired output for only FIELD again.

MWE
import {Component} from '@angular/core';
import {Button,DataList} from 'primeng/primeng';

@Component({
    selector: 'my-app',
    template: `<button (click)="refreshData(dlist)">Press Me</button>
        <p-dataList #dlist  [value]="dataItems" [paginator]="true" [rows]="20" [lazy]="true" (onLazyLoad)="loadData($event)" [totalRecords]="totalRecords">
      <header>Run {{run}}</header>
      <template let-dataItem>
        FIELD: {{dataItem.field}}
        <template ngFor let-n [ngForOf]="dataItem.array">
            SUBFIELD: {{n.item}}
        </template>
      </template>
    </p-dataList>`
})

export class AppComponent  {
    dataItems : DataItem[];
    totalRecords : number;
    run : number;

    constructor() {
        this.run = 0;
    }
    loadData(event : any ) {
    }
    refreshData(dtree : any ) {
        this.run++;
        var json = "{ \"data\": [{\"field\": \""+this.run+"\", \"array\" : [{ \"item\": \""+this.run+"\"}]}]}";
        console.log(json);
        this.dataItems = <DataItem[]> JSON.parse(json).data;
        // force paginator back to first page.
        dtree.paginate({ first: 0 , rows: dtree.rows});
    }
}

export interface DataItem {
    array : MyValue[];
    field: String;
}

export interface MyValue {
    item : String;
}

A: How about:
<template *ngFor="let item of dataItem.array">
        SUBFIELD: {{item.item}}
</template>

A: I found the root cause. This is a bug in AngularJS <=2.4.1. This Plunker snippet
demonstrates the problem. Click multiple times on the button, to see the effect.
If you copy/fork the snippet and change the Angualar version in this Plunker snippet by changing systemjs.config.js:
var V =   '2.4.1';
to
var V =   '2.4.2';
You see that clicking multiple times on the button now produces the desired effect, without other modifications.
However, I could not find in the Angular 2 change log the related bug. However there are some fixes reported related to templates/ngFor.


text:
Q: Difference between "time" and "timing"? I want to ask regarding the time at which I will be interviewed. Which option is correct? Or both are incorrect? I am confused regarding the usage of "time" and "timing"?

*

*What is the timing of the interview on Monday?

*What is the time of the interview on Monday?

A: Technically, "what is the time" is preferred if you want to know the time the interview starts.
Timing is often used in similar concepts; but they way it is used differs.

*

*Timing can be used to describe a time within a repeating period.  For example, a timing chain (part of a car) is used to make sure the engine performs operations in the correct order for each revolution of the crankshaft.

*Timing  can be used to describe relationships between items, or to describe those relationships in a general manner.  The timing of the events is critical.  The timing of the play will follow the announcement by the Master of Ceremonies.
Timing is rarely used in good speech to specify an exact time; but, many people use the word timing in less-than-good speech.  So, if you used timing, keep in mind that you might get a response like "sometime Wednesday" or "after we get ten candidates to interview".  When you use time, you will more likely get a response like "3 PM Wednesday the 28th".


text:
Q: Unable to access the controller in subfolder As stated in my previous question, I some how managed to cop up with this one, by using the URL like myproject-local.com/admin/index
But now I have added another controller, say category in admin directory and when I go to myproject-local.com/admin/category, it gives me 404
Routes.php
$route['default_controller'] = "welcome";
$route['admin/(:any)'] = "admin/admin/$1";
$route['404_override'] = '';

.htaccess
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>

  ErrorDocument 404 /index.php
</IfModule>

and I have set $config['index'] = ''; in my config.php

A: Even though that using routes seems to be the right n' easy way to go I found it so annoying to add a route for each new controller.
As a more stable solution to this you can bring the feature of multi-level controller subfolders to CodeIgniter by extending the locate() method of core Router class. Here is my extended HMVC router class. If you're not using HMVC, you might need to write your own fork with a little modification. The code is well commented, read through and let me know if you have any questions.
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

// Load HMVC Router
require APPPATH . 'third_party/MX/Router.php';

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

/**
 * Better HMVC Router for CodeIgniter.
 *
 * @package     CodeIgniter
 * @author      Sepehr Lajevardi <me@sepehr.ws>
 * @copyright   Copyright (c) 2011 Sepehr Lajevardi.
 * @license     http://codeigniter.com/user_guide/license.html
 * @link        https://github.com/sepehr/ci-mx-router
 * @version     Version 1.0
 * @filesource
 */

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

/**
 * HMVC Router extension to support multilevel controller subfolders.
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Libraries
 * @author      Sepehr Lajevardi <me@sepehr.ws>
 * @link        https://github.com/sepehr/ci-mx-router
 */
class MY_Router extends MX_Router {

    /**
     * Routes URI segments to the proper module/app controller.
     *
     * It's a override of MX_Router's locate() method
     * to support multilevel controller subfolders.
     *
     * @param  array $segments URI segments
     * @return array
     */
    public function locate($segments)
    {
        $this->module = $this->directory = '';
        $ext = $this->config->item('controller_suffix') . EXT;

        // Use module route if available
        if (isset($segments[0]) AND $routes = Modules::parse_routes($segments[0], implode('/', $segments)))
        {
            $segments = $routes;
        }

        // Get the segments array elements
        list($module, $directory, $controller) = array_pad($segments, 3, NULL);

        // ------------------------------------------------------------------------
        // 1. Check modules (recursive)
        // ------------------------------------------------------------------------
        foreach (Modules::$locations as $location => $offset)
        {
            // Module controllers/ exists?
            if (is_dir($source = $location . $module . '/controllers/'))
            {
                $this->module    = $module;
                $this->directory = $offset . $module . '/controllers/';

                // Temporary helper variables
                $base_directory = $this->directory;
                $segments_copy  = array_slice($segments, 1);

                do {
                    // Update directory, if not in the first round
                    if (isset($segments_copy[0]) AND $directory !== $segments_copy[0])
                    {
                        $this->directory  = $base_directory . $directory . '/';
                        $directory       .= '/' . $segments_copy[0];
                    }

                    // Check if controller file exists
                    if ($directory AND is_file($source . $directory . $ext))
                    {
                        return $segments_copy;
                    }

                    // Move forward through the segments
                    $segments_copy = array_slice($segments_copy, 1);
                }
                while ( ! empty($segments_copy) AND $directory AND is_dir($source . $directory . '/'));

                // Check for default module-named controller
                if (is_file($source . $module . $ext))
                {
                    $this->directory = $base_directory;
                    return $segments;
                }
            }
        } // foreach

        // ------------------------------------------------------------------------
        // 2. Check app controllers in APPPATH/controllers/
        // ------------------------------------------------------------------------
        if (is_file(APPPATH . 'controllers/' . $module . $ext))
        {
            return $segments;
        }

        // Application sub-directory controller exists?
        if ($directory AND is_file(APPPATH . 'controllers/' . $module . '/' . $directory . $ext))
        {
            $this->directory = $module . '/';
            return array_slice($segments, 1);
        }

        // ------------------------------------------------------------------------
        // 4. Check multilevel sub-directories in APPPATH/controllers/
        // ------------------------------------------------------------------------
        if ($directory)
        {
            $dir = '';

            do {
                // Go forward in segments to check for directories
                empty($dir) OR $dir .= '/';
                $dir .= $segments[0];

                // Update segments array
                $segments = array_slice($segments, 1);
            }
            while (count($segments) > 0 AND is_dir(APPPATH . 'controllers/' . $dir . '/' . $segments[0]));

            // Set the directory and remove it from the segments array
            $this->directory = str_replace('.', '', $dir) . '/';

            // If no controller found, use 'default_controller' as defined in 'config/routes.php'
            if (count($segments) > 0
                AND ! file_exists(APPPATH . 'controllers/' . $this->fetch_directory() . $segments[0] . EXT))
            {
                array_unshift($segments, $this->default_controller);
            }
            else if (empty($segments) AND is_dir(APPPATH . 'controllers/' . $this->directory))
            {
                $segments = array($this->default_controller);
            }

            if (count($segments) > 0)
            {
                // Does the requested controller exist in the sub-folder?
                if ( ! file_exists(APPPATH . 'controllers/' . $this->fetch_directory() . $segments[0] . EXT))
                {
                    $this->directory = '';
                }
            }

            if ($this->directory . $segments[0] != $module . '/' . $this->default_controller
                AND count($segments) > 0
                AND file_exists(APPPATH . 'controllers/' . $this->fetch_directory() . $segments[0] . EXT ) )
            {
                return $segments;
            }
        }

        // ------------------------------------------------------------------------
        // 5. Check application sub-directory default controller
        // ------------------------------------------------------------------------
        if (is_file(APPPATH . 'controllers/' . $module . '/' . $this->default_controller . $ext))
        {
            $this->directory = $module . '/';
            return array($this->default_controller);
        }
    }

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

}
// End of MY_Router class

/* End of file MY_Router.php */
/* Location: ./application/core/MY_Router.php */

Hope it helps.

A: Try this way
$route['default_controller'] = "welcome";
$route['admin/category/(:any)'] = "admin/category/$1";
$route['admin/(:any)'] = "admin/admin/$1";
$route['404_override'] = '';

A: If find if I use hmvc with routes it all works fine with HMVC. Because this is way I use it with hmvc routes if download latest version you must include the function in route like shown below. No need to add other script for hmvc in the route only use what they have.
$route['default_controller'] = "folder/file/index"; //Works
$route['404_override'] = '';
$route['some_controller_name_a'] = "folder/file/index"; //Works
$route['some_controller_name_b'] = "folder/file/yourfunction"; //Works

//My Way

$route['default_controller'] = "install/common/step_1/index";
$route['404_override'] = '';

// If default controller does not work with sub folder add it like so then should work.

$route['step_1'] = "install/common/step_1/index";
$route['step_2'] = "install/common/step_2/index";
$route['step_3'] = "install/common/step_3/index";
$route['step_4'] = "install/common/step_4/index";

And if use redirect can make it like redirect('some_controller_name_a'); Works
Use
Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Also remove the index.php from config file in application
Also on the view file load controller
<?php echo Modules::run('install/common/header/index');?>


text:
Q: Add array data by name php I'm new to arrays. I'd like to know if you can add data to the array by name.
This would be an example of what I want to achieve
example:
$guitars = ['names',['Warvick', 'Gibson', 'Fender']];
$guitars[names][] = "Ibanez";
echo "
";
var_dump($guitars);
echo "
";

result
WARNING Use of undefined constant names - assumed 'names' (this will throw an Error in a future version of PHP) on line number 3
array(3) {
  [0]=>
  string(5) "names"
  [1]=>
  array(3) {
    [0]=>
    string(7) "Warvick"
    [1]=>
    string(6) "Gibson"
    [2]=>
    string(6) "Fender"
  }
  ["names"]=>
  array(1) {
    [0]=>
    string(6) "Ibanez"
  }

what I want is to add the data "ibanez" to the array "names" but nevertheless create a new one.
I need it to stay this way. Is there any way to access the data directly by the name "names"?
array(2) {
  [0]=>
  string(5) "names"
  [1]=>
  array(4) {
    [0]=>
    string(7) "Warvick"
    [1]=>
    string(6) "Gibson"
    [2]=>
    string(6) "Fender"
    [3]=>
    string(6) "Ibanez"
  }
}

A: You want to use associative arrays. In this case, for example, use the arrow token to associate the guitar names with the "names" key.
$guitars = ['names' => ['Warvick', 'Gibson', 'Fender']];
$guitars['names'][] = "Ibanez";
echo "
";
var_dump($guitars);
echo "
";


text:
Q: how to use sqlite3_create_function in android using ndk Okay, so I successfully was able to build sqlite using android NDK and my code that it used for sqlite3_create_function, but when I try to use it in a cursor query, it says there is no function. I heard somewhere else on Stackoverflow that it is because the Java implementation of SQLite doesn't have the function, but the C one does. How do I counteract this and make it work? Is it better to just recompile sqlite3 from the android sdk with the function or will this not make a difference? Here is the Android.mk file I used.
LOCAL_PATH := $(call my-dir)

#####################################################################

#            build sqlite3                                          #

#####################################################################

include $(CLEAR_VARS)

LOCAL_C_INCLUDES := sqlite-amalgamation-3071700

LOCAL_MODULE := sqlite3

LOCAL_SRC_FILES := sqlite-amalgamation-3071700/sqlite3.c

include $(BUILD_STATIC_LIBRARY)

#include $(BUILD_SHARED_LIBRARY)

#####################################################################

#            build our code                    #

#####################################################################

include $(CLEAR_VARS)

LOCAL_C_INCLUDES := $(LOCAL_PATH)/sqlite-amalgamation-3071700

LOCAL_MODULE := fts3-rank

LOCAL_SRC_FILES := fts3-rank.c

LOCAL_STATIC_LIBRARIES := libsqlite3

#LOCAL_SHARED_LIBRARIES:=libsqlite3

LOCAL_LDLIBS := -llog -lm

include $(BUILD_SHARED_LIBRARY)

#need main function to have executable

#include $(BUILD_EXECUTABLE)

The code I used for fts3-rank is at https://github.com/coolaj86/sqlite3-fts4-rank/blob/master/fts4-rank.c
I am correctly using rank() and not rankfunc() in my query. I also do not have a JNI include in my C code or native method in my Activity because I do not see how that is useful when I am not calling the method in the activity. I just need it within the query. Yes, I did loadLibrary and am not getting that error on the device. There are like no guides on how to do this online so hopefully someone can answer. The purpose is relevance ranking in Android without Lucene (can you even use it in Android?).


text:
Q: why won't my code work? new to java I am very new to the whole CS scene but quickly getting into it, I chose Java as the first language I wanted to learn.
I'm using an online resource that asks me to make a simple program which asks the user to enter a number, and then it spits back out the sum of the powers.
So if you input 4, I want it to give you 2^0 + 2^1 + 2^2 + 2^3 + 2^4  This is what I have so far, but it's not working, any suggestions?
I am using NetBeans.
System.out.println("Type a number: ");
int number = Integer.parseInt(reader.nextLine());
int i = 0;
int exponent = (int)Math.pow(2,i);
int sum = 0;
while (i <= number) {
     sum += exponent;
 i++;
}
System.out.println("The result is: " + sum);

A: You're assigning a value to exponent outside the loop.
This means that it's value won't change every time i is incremented.
To fix this:
    System.out.println("Type a number: ");
    int number = Integer.parseInt(reader.nextLine());
    int sum = 0;
    for (int i = 0; i <= number; i++) {
        sum += Math.pow(2,i);
    }
    System.out.println("The result is: " + sum);

}

In addition to producing the desired output, this code is more efficient as I've removed the exponent variable (as it can be added straight to sum), and I've used a for loop (so that there's no need for the line where i is declared or for the line where i is incremented).

A: Try this:
    int exponent = 0;
    int sum = 0;

    while (i < number) {
        sum += exponent;
        i++;
        exponent = (int) Math.pow(2, i);
    }
    System.out.println("The result is: " + sum);

A: Whole case with for loop
public static void test(){
    java.util.Scanner reader = new java.util.Scanner(System.in);
    System.out.println("Type a number: ");

    int sum = 0;
    int number = Integer.parseInt(reader.nextLine());

    for (int i = 0; i <= number; i++){
        int exponent = (int) Math.pow(2, i);
        sum = sum + exponent;
    //    System.out.println(i); if you want to see the exponent uncomment this line
    }

    System.out.println("The result is: " + sum);
}


text:
Q: Register Javascript file to aspx page from WebReousrce How do i add my javascript file as an embeded resource to the page after the ajax javascript already on the page?  NB want to do this part dynamically to have code wrapped up in usercontrol.
in aspx page: scriptmanager
Code: Assembly: WebResource("Functions.js", "text/javascript")
Code: onPreRender:
ScriptManager.RegisterClientScriptResource(Me.Page, Me.GetType().BaseType, "Functions.js")
This code successfully adds my javascript code to the page but not after the AJAX javascript and so not all of my functions work correctly.
Thanks, Dave

A: You could use GetWebResourceUrl() to get the path string to your embeded script as it should be in the page (probably something like websresource.axd?XXXX). Then manually insert a script tag pointing to the path using RegisterStartupScript to force it to be added at the end of the page. Something like below...
path = ScriptManager.GetWebResourceUrl(this.GetType(), "Fucntion.js");
ScriptManger.RegisterStartupScript(this.GetType(), "MyScript", "<script type=\"text/javascript\" src=\"" + path + "\"/>");

From the server you could also try adding your script later in the load process for example in the prerender event. Or from the client side can wrap your script into a load so that it doesn't run the code until the last possible moment as below...
function RunOnLoad()
{

     button.onclick = function()
     {
       alert("Clicked!");
     }

}
window.onload = RunOnLoad;


text:
Q: What is the most powerful spell? What is the most powerful spell in Wizard101?
My friend says it is Heck Hound with damage over time with power pips.
But is the spell storm owl or tempest?
I really want to know!
I did search it up.... but I also need to know if damage over time counts in this category?

A: Looking at the wording available for the Heck Hound spell:

Deals 130 Fire Damage per Pip over 3 Rounds (accuracy 75%)

It can be seen that the damage this spell can give is dependent on how many rounds you manage to stay fighting, as 1 more Pip is added for every round you stay fighting.
Thus, the only way to compare this spell in regards to damage is by comparing it to other spells that use the same number of Pips.
So, for the number of pips, this is the total average (Damage * Pips * Accuracy * 3 rounds) damage done by Heck Hound:
1   -   292.5
2   -   585
3   -   877.5
4   -   1170
5   -   1462.5
6   -   1755
7   -   2047.5
8   -   2340
9   -   2632.5
10  -   2925

We can see here that the spell's damage is quite high. Let's also assume that there is only one enemy, so that spells that target all enemies can be considered fairly.
Running down all math, I was able to produce an Excel file detailing all spells' damage. By analyzing the data one can check that Heck Hound is indeed the most powerful (in terms of damage) spell, except for the 8 Pips case, where King Artorius (Myth) alone gains a small advantage.
The Judgement spell from the Balance School has similar mechanics to this spell, but falls a lot short, due to the round bonus.

A: If multiple I would say Call of Kuruhulu with colossal. It gives you 1k base damage. With blades against 4 people yout get health back instantly while crippling all. Alone I would probably say Judgement.


text:
Q: How to display bundle in fragment with RecyclerView I'm trying to figure out how I would display Bundle data that I have in my fragment and display it in a RecyclerView. In the onClick method of my activity, I get the input from the user and wrap the values in a Bundle. I then send it to the fragment to be displayed in the RecyclerView. I'm a bit stumped on how I would go about setting up my RecyclerView Adapter to display the Bundle data Any help would be greatly appreciated. I can show data in recyclerview but i can display just 1 item i want to show more item when i sending data from activity to fragment.
This is my Fragment
public class BlankFragment extends Fragment {
List<Mydata> mydataList = new ArrayList<>();

public BlankFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View vi =  inflater.inflate(R.layout.fragment_blank, container, false);
    RecyclerView recyclerView = vi.findViewById(R.id.recyclerShop);
    Bundle extras = this.getArguments();
    if(extras != null)
    {
        String nameExtra = extras.getString("name");
        String amountExtra = extras.getString("color");

        //Just add your data in list
        Mydata mydata = new Mydata();  // object of Model Class
        mydata.setAmountExtra(amountExtra );
        mydata.setNameExtra(nameExtra);
        mydataList.add(mydata);

    }

    MyAdapter myAdapter = new MyAdapter(getContext());
    myAdapter.setMyDataList(mydataList);
    recyclerView.setAdapter(myAdapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    return vi;
  }
}

Here is the Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

private Context context;
private List<Mydata> myDataList;

public MyAdapter(Context context) {
    this.context = context;
    myDataList = new ArrayList<>();
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    // Replace with your layout
    View view = LayoutInflater.from(context).inflate(R.layout.shop_item_layout, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // Set Your Data here to yout Layout Components..
    holder.tvName.setText(myDataList.get(position).getNameExtra());
    holder.tvColor.setText(myDataList.get(position).getAmountExtra());
    // to get Amount
   // myDataList.get(position).getAmountExtra();

}

@Override
public int getItemCount() {
    if (myDataList.size() != 0) {
        // return Size of List if not empty!
        return myDataList.size();
    }
    return 0;
}

public void setMyDataList(List<Mydata> myDataList) {
    // getting list from Fragment.
    this.myDataList = myDataList;
    notifyDataSetChanged();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    ImageView imageShop;
    TextView tvName,tvColor,tvamount;
    EditText etBodySize,etAllAmount;
    public ViewHolder(View itemView) {
        super(itemView);
        imageShop = itemView.findViewById(R.id.imgShop);
        tvName = itemView.findViewById(R.id.tvClothesName);
        tvColor =itemView.findViewById(R.id.tvColor);
        tvamount = itemView.findViewById(R.id.tvfiyat);
        etBodySize = itemView.findViewById(R.id.etAmount);
        etAllAmount = itemView.findViewById(R.id.etAllAmount);

        // itemView.findViewById
    }
  }
}

Lastly here is the MyData Class
public class Mydata {
    String nameExtra;

    String amountExtra;

    public Mydata(String nameExtra, String amountExtra) {
        this.nameExtra = nameExtra;
        this.amountExtra = amountExtra;
    }

    public Mydata() {
    }

    public String getAmountExtra() {
        return amountExtra;
    }

    public void setAmountExtra(String amountExtra) {
        this.amountExtra = amountExtra;
    }

    public String getNameExtra() {
        return nameExtra;
    }

    public void setNameExtra(String nameExtra) {
        this.nameExtra = nameExtra;
    }
}

Then when i sending data and open fragment
blankFragment = new BlankFragment();
            Bundle bundle = new Bundle();
            bundle.putString("name",clothesRecycler.data.get(position).getName());
            bundle.putString("color",clothesRecycler.data.get(position).getColor());
            blankFragment.setArguments(bundle);
            manager = getSupportFragmentManager();
            manager.beginTransaction().add(R.id.container,blankFragment).addToBackStack(null).commit();

A: Add exras.hasExtras() in your name extras, then getStringExtra() and add break point to see if you are passing valid data. I am assuming you are not retrieving the data you expect. I see no problem with the adapter.
if(this.getArguments().hasExtras("name") && this.getArguments().hasExtras("color")){
    //do whatever
}


text:
Q: Checking stock of every size for a specific product using requests and BS4 So here is my code to check stock of sizes 7.5-9 of a certain product:
import requests
from bs4 import BeautifulSoup
r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
soup = BeautifulSoup(r.text, 'html.parser')
attrs = soup.find_all(class_="box_wrapper")[0].findChildren()

output = str(attrs[0].attrs)
if "piunavailable" in output:
    print("Size 7.5 OOS")
else:
    print("Size 7.5 in stock!")

output = str(attrs[1].attrs)
if "piunavailable" in output:
    print("Size 8 OOS")
else:
    print("Size 8 in stock!")

output = str(attrs[2].attrs)
if "piunavailable" in output:
    print("Size 8.5 OOS")
else:
    print("Size 8.5 in stock!")

output = str(attrs[3].attrs)
if "piunavailable" in output:
    print("Size 9 OOS")
else:
    print("Size 9 in stock!")

The actual htmls for the sizes on that website is as follows:

     7.5
     8
     8.5
     9
     9.5
     10
     10.5
     11
     11.5
     12
     13
     14

So when i run my code, as expected, i get:
PS C:\Users\jokzc\Desktop\python\learning requests> py test3.py
Size 7.5 in stock!
Size 8 OOS
Size 8.5 OOS
Size 9 OOS

What i would like to do is be able to check every size and return if it is in stock or out of stock without 10 different output blocks in my main code. Is there some forevery function or something i could do that would satisfy this need?

A: Yes you can do it like this.
import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
soup = BeautifulSoup(r.text, 'html.parser')
for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
    if "piunavailable" in anchor_tag['class']:
        print(f"Size {anchor_tag.text} OOS")
    else:
        print(f"Size {anchor_tag.text}  in stock!")

Outputs:
Size 7.5  in stock!
Size 8 OOS
Size 8.5 OOS
Size 9 OOS
Size 9.5 OOS
Size 10 OOS
Size 10.5 OOS
Size 11 OOS
Size 11.5 OOS
Size 12 OOS
Size 13 OOS
Size 14 OOS

You can also use for anchor_tag in soup.select('div.box_wrapper a'): instead of for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():


text:
Q: Xcode: Altering MainStoryboard.storyboard Hi I initially created a Single View application in Xcode 4.1 for iPhone. So obviously my storyBoard file was sized accordingly.
Later I changed my settings device's Application target to iPad, but my storyboard file doesn't resize its interface its still sized for the iPhone, how can I change this?
Also how can I orientate the storyboard file to landscape?

A: You have to create new storyboard for iPad from scratch.


text:
Q: jboss 4: enable UsersRolesLoginModule, where must users.properties files be placed? I have an application (CQ5)  that requires enabling unauthenticatedIdentity on jbossdir/conf/login-config.xml
I used:
   <authentication>
      <login-module code = "org.jboss.security.auth.spi.UsersRolesLoginModule"
         flag = "required" >
      <module-option name="unauthenticatedIdentity">nobody</module-option>
    </login-module>
   </authentication>

then I tried to copy jbossdir/conf/props/jmx-console-users.properties,jmx-console-roles.properties
into users.properties and roles.properies (same dir).
I still get this error:

ERROR
  [org.jboss.security.auth.spi.UsersRolesLoginModule]
  Failed to load  users/passwords/role
  files java.io.IOException: No
  properties file: users.properties or
  defaults: defaultUsers.properties
  found

where should I put those files?

A: As I know there is 2 places where you can put these files:

*

*In conf dir, and then you reference to them by:
<module-option name="usersProperties">props/jmx-console-users.properties<module-option>

*You can put these file in WEB-INF/classess dir and reference to them just by name:
<module-option name="usersProperties">web-console-users.properties</module-option>
You can find these in web-console definition. The file with user names is located under: ./deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-users.properties


text:
Q: How to prove this identity in a combinatorial way? \begin{equation}
\sum_{k=0}^{n}\left(\begin{array}{c}{2 n+1} \\ {k}\end{array}\right)=2^{2 n}
\end{equation}
I managed to prove it in an algebric way but not in combinatorial one.
Thanks!
Not a duplicate.

A: Let $S=\{1,2,\dots,2n+1\}$.
We wish to prove that $\mathcal{A}=\{A\subseteq S:~|A|\leq n\}$ is in bijection with $\mathcal{B}=\{B\subseteq S:~2n+1\notin B\}$.  It is clear that $|\mathcal{A}|$ is counted by the LHS of your identity while $|\mathcal{B}|$ is counted by the RHS of your identity.
Consider the function $f:\mathcal{A}\to\mathcal{B}$ given by:
$$f(A) = \begin{cases} A&\text{if }2n+1\notin A\\ S\setminus A&\text{if }2n+1\in A\end{cases}$$
Notice that if $2n+1\notin A$ then $|f(A)|=|A|\leq n$.  On the other hand, if $2n+1\in A$ then $|f(A)|=|S\setminus A| = 2n+1-|A|\geq n+1$
Suppose then that $f(A_1) = f(A_2)$.  This implies that either $2n+1$ is in both $A_1$ and $A_2$ or it is in neither.  In the first case, that would imply that $A_1=A_2$.  Otherwise, that would imply that $S\setminus A_1=S\setminus A_2$ which in turn implies that $A_1=A_2$.  Therefore, the function is injective.
For surjectivity, consider an arbitrary subset $B$ not containing $2n+1$ of $S$.  In the event that $|B|\leq n$ then $B\in\mathcal{A}$ and $f(B)=B$.  Otherwise, if $|B|\geq n+1$ we have $S\setminus B\in \mathcal{A}$ and that $f(S\setminus B)=B$.
Thus the function is a bijection and the identity is proven.


text:
Q: How to force a mod_rewrite RewriteRule to display as rewritten even if the un-rewritten url is entered is it possible to make it so that url rewrites are forced?
Here is an example of what works, http://localhost/home/ goes to http://localhost/index.php?page=home but the url stays the same to the user.
What I can't get to work is forcing http://localhost/index.php?page=home to display as
http://localhost/home/.
I don't know if I'm using the right terminology, but I want it so that if you type the non rewritten url, I want the rewritten url to appear in the user's browser.
Here is what I have working so far:
RewriteEngine on
Options +FollowSymLinks

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond $1 !^(index\.php)
RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/?$ index.php?page=$1&a=$2&b=$3 [L,NC,QSA]

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond $1 !^(index\.php)
RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)$ index.php?page=$1&a=$2 [L,NC,QSA]

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond $1 !^(index\.php)
RewriteRule ^([a-zA-Z0-9_]*)$ index.php?page=$1 [L,NC,QSA]

A: That's what the [R] flag is for.  If you have a correctly-working rewrite, you'll want to add [R] to your other flags at the end of your RewriteRule.

A: Try adding some code to your index.php.
Look at the $_SERVER['SCRIPT_URL'] variable for your answer.  When you enter "localhost/index.php?page=home" in your browser, SCRIPT_URL should equal '/index.php'.  If you enter "localhost/home", SCRIPT_URL should equal '/home'.  You can do a check for this in your PHP script and redirect appropriately from there.


text:
Q: wix component condition evalulation I have a component that needs to be installed if another feature ( not the parent feature of the component) is being installed.
The component conditions seems to be evaulated during CostFinalize action, so i created a property and set the value of that property, I then force CostInitialize action using a custom action
but the component still doesnt get installed, any clues ?

A: Component conditions are only evaluated for components that belong to features that are being installed.  They can only exclude the component not include the component.
Install you must make the component belong to the other feature  by using a ComponentRef element.    Components are allowed to be associated with more then one feature.
<Directory....>
  <Component Id="test1"...>
  <Component Id="test2"...>
  <Component Id="testcommon"...>
</Directory>

<Feature Id="A"...>
  <ComponentRef Id="test1"/>
  <ComponentRef Id="testcommon"/>
</Feature>
<Feature Id="B"...>
  <ComponentRef Id="test2".../>
  <ComponentRef Id="testcommon".../>
</Feature>