How can I read blackslashes from a file correctly?

Question: The following code:
key = open("C:\Scripts\private.ppk",'rb').read()

reads the file and assigns its data to the var key.
For a reason, backslashes are multiplied in the process. How can I make sure they don't get multiplied?
Answer: You ... don't.  They are escaped when they are read in so that they will process properly when they are written out / used.  If you're declaring strings and don't want to double up the back slashes you can use raw strings r'c:\myfile.txt', but that doesn't really apply to the contents of a file you're reading in.
>>> s = r'c:\boot.ini'
>>> s
'c:\\boot.ini'
>>> repr(s)
"'c:\\\\boot.ini'"
>>> print s
c:\boot.ini
>>>

As you can see, the extra slashes are stored internally, but when you use the value in a print statement (write a file, test for values, etc.) they're evaluated properly.
Comment: Why does this answer have six upvotes? "They are escaped when they are read in" is exactly the opposite of what happens. The extra slashes are added by `repr()`; they are not stored in the string, and therefore don't need to be "evaluated" by `print` when printing normally.
Answer: You should read this great blog post on python and the backslash escape character.

And under some circumstances, if
  Python prints information to the
  console, you will see the two
  backslashes rather than one. For
  example, this is part of the
  difference between the repr() function
  and the str() function.
myFilename =
  "c:\newproject\typenames.txt" print
  repr(myFilename), str(myFilename)
  produces
'c:\newproject\typenames.txt'
  c:\newproject\typenames.txt
Answer: Backslashes are represented as escaped. You'll see two backslashes for each real one existing on the file, but that is normal behaviour.
The reason is that the backslash is used in order to create codes that represent characters that cannot be easily represented, such as new line '\n' or tab '\t'.
Answer: Are you trying to put single backslashes in a string? Strings with backslashes require and escape character, in this case "\". It will print to the screen with a single slash
Answer: In fact there is a solution - using eval, as long as the file content can be wrapped into quotes of some kind. Following worked for me (PATH contains some script that executes Matlab):
MATLAB_EXE = "C:\Program Files (x86)\MATLAB\R2012b\bin\matlab.exe"
content = open(PATH).read()
MATLAB_EXE in content  # False
content = eval(f'r"""{content}"""')
MATLAB_EXE in content  # True

This works by evaluating the content as python string literal, making double escapes transform into single ones. Raw string is used to prevent escapes forming special characters.


how would i clear previously echoed result without affecting any other functions in php?

Question: I am currently working on website where it has a search box to search for specific items. The page echos out results in table format. So far everything works perfectly but when I try to filter the result(depending on features), I get two sets of results. One with previously displayed result table and the other is the filtered result. I do not want previous result to display back again on screen without affecting any other procedure. Something like sessions?? I do not know exactly how to deal with this situation.
<?php

include'search.php';// form for a search box.

         if (isset($_POST['search_name']))  {
$search_name=mysql_real_escape_string(htmlentities(trim($_POST['search_name'])));
$errors = array();

if (empty($search_name)){

    $errors[] ='please enter a search term';
    }
else if (strlen($search_name)<3){
    $errors[] = 'your search term must be three or more characters';
    }
else if (1==2){
    $errors[] ='your search for '.$search_name.' returened no results';
    }
if (empty($errors)){

   filter($search_name); //it display another form in the navigation bar to filter the search result.

   search_results($search_name);//searches for all the result onthe database depending on the keyword  entered in searchbox.

    } else{

    foreach($errors as $error)  {
        echo $error,'
';
        }
    }

}

?>

Comment: Code would be useful here
Comment: Yes, let's see your code!
Comment: Please provide some code.
And use the SEARCH function to see if there are another questions like this.
Comment: my code is quite nested in different files so i've edited the code where all the things begin from. hope it helps.
Comment: I can already tell you the problem is most likely in your AJAX/Javascript code.
Comment: i haven't used any AJAX/Javascript code. but do i need to? i mean the problem is when the two function: filter($search_name ) and search_results($search_name) runs. i get the result list through search_results and another form in navigation bar through filter and when i submit the filter form it runs another function and it displays the filter result, and filter form in navigation bar and also the search_result function's result. the problem is i don't want search_results function to run when filtering the search. it's kinda confusing, i'm sorry.i'm not very good with explaining.
Answer: See this code:
echo 'world';
echo 'hello !';

You can intercept the echo using ob_start(), ob_get_contents() and ob_clean().
ob_start();
echo 'world';

var $echoed = ob_get_contents();
ob_clean();

// real echo
echo 'hello ' . $echoed . '!';

// now you see
// hello world!

Because the ob 'output buffering' is native to PHP, you can use it with anything like functions, includes and so on. I'm using this approach, to intercept (1.) outputs in my controller flow, and to intercept (2.) the view's output, so I can compose them later (for example to render PHP errors into a debug div.
Comment: thank you. i'm glad u understood the problem.:) i really really appreciate your help.:)


Php date format is outputting the wrong date

Question: I have dates and times setup in the database separately. start is in YYYY-MM-DD format and time is in HH:MM:SS format.  I'm trying to modify the start date to show the date in a readable format.
I've tried to output using php and I get "Wednesday, Dec 31 1969" which is nothing like I want. (right format, but the date isn't anything I have in the database).
And i've used  DATE_FORMAT('start','%W, %M %d %Y') AS startbut my select function has it order by start and it doesn't give me the right order and values specified. but format is right.
my php code is
$sql = "SELECT `title`, `time`, `start`, `showFeed` FROM calender WHERE length('column') > '0' and showFeed=1 ORDER BY `start` ASC LIMIT 0,4";

/*  DATE_FORMAT(`start`,'%W, %M %d %Y') AS start   */

    $result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);

echo "
";
echo "
";

foreach ($result as $row){
$dt = $row['start'];
$ts = $row['time'];

$date = strtotime( $dateout );
$dateout = date( 'l, M j Y', $phpdate );

    echo "
";
    echo "
". $row['title']. "
";
    echo "
".  $dateout;
    echo "
";

}

echo "
";
echo "
";

$dbh = null;

I don't know what possibly I'm doing wrong. I've done this before and for some reason formatting dates isn't working this time around.
Answer: Try this:
<?php
$dt = $row['start'] . ' ' . $row['time'];
echo date('l, M j Y', strtotime($dt));

I'm not sure if it was just a typo, or if it's your code, but - you're referencing $dateout before it's set, and $phpdate, which is never set.


Insert the "Ubuntu 20.04.2 LTS _Focal Fossa_ - Release amd64 (20210204)" called CD to the /cdrom/ drive and press enter

Question: So I have ran into some trouble installing g++. When I try to use the "sudo apt install g++", command it asks me if I really want to install it, and when I say yes, it just leaves me this message: "Insert the "Ubuntu 20.04.2 LTS Focal Fossa - Release amd64 (20210204)" called CD to the /cdrom/ drive and press enter" (Or something like that, I tried to translate it from Hungarian)
I give you an image of my problem, however my Ubuntu is in Hungarian, so i don't think that it would be useful. Here it is: My terminal, under Ubuntu 20.04.02.0
I have already tried to get the .iso file and just mount it to my cd drive, but it didn't solve the problem.
Should I just reinstall Ubuntu or what should I do?
Comment: If you need help with the translations from the pictures, just let us know.
Comment: Best to include text in the quest not as a screen shot. In this case any one reading your question could also  use translation to read in English.
Answer: The problem looks like you must have put your sources (where Ubuntu gets the packages) to only the install CD.
Fix this by opening the Software and Updates app, and ticking everything (you want to install) listed under Downloadable from the Internet.
Comment: g++ is in 'main', so only one of those five boxes need be checked.

Insert the „Ubuntu 20.04.2 LTS _Focal Fossa_ - Release amd64 (20210204)” called CD to the /cdrom/ drive and press enter


How can I specify a section as NOBITS in linker scripts?

Question: My linker script is like this:
SECTIONS {
    .uninit : {
        PROVIDE(_uninit_start = .);

        PROVIDE(_stack_start = .);
        . += CONFIG_STACK_SIZE * CONSTS_HARTS_NUMBER;
        PROVIDE(_stack_end = .);

        . = ALIGN(4K);
        PROVIDE(_uninit_end = .);
    }
}

However, the output sections are like this:
  [ 7] .bss              NOBITS           0000000080357000  00158000
       0000000000034000  0000000000000000  WA       0     0     4096
  [ 8] .uninit           PROGBITS         000000008038b000  0018c000
       0000000001020000  0000000000000000  WA       0     0     1

If I use objcopy to copy the elf file to the binary file, the output size would be much larger than it should be.
Now my question is: how can I set a NOBITS flag for my custom section in the linker script?
Answer: You can not specify section attributes in linker scripts, only in assembly:
.section    .uninit,"wa",@nobits

Answer: Just use NOLOAD linker directive.
SECTIONS {
    .uninit (NOLOAD) : {
    ...


SpriteKit Main Menu button issue

Question: Wondering if you could help, I created a main menu with a background and button node. When I tap on the PLAY button, the game does not navigate to my GameScene and instead calls my print statement. Here is the code below:
import Foundation
import SpriteKit
import GameplayKit

class MainMenu: SKScene, SKPhysicsContactDelegate {
    override func didMove(to view: SKView) {

        background()
        playButton()

    }

    func background()
    {
        let back = SKSpriteNode(imageNamed: "MainMenu")
        back.anchorPoint = CGPoint(x: 0, y: 0)
        back.zPosition = 1
        back.size = CGSize(width: frame.width,height: frame.height)
        back.name = "Background"

        addChild(back)

    }

    func playButton()
    {
        let button = SKSpriteNode(imageNamed: "button")
        button.zPosition = 2
        button.name = "Play Button"
        button.position = CGPoint(x: frame.width/2, y: frame.height/2)
        button.setScale(0.3)

        addChild(button)
    }

    func loadGame(){

        guard let skView = self.view as SKView? else{
            print("Could not get Skview")
            return
        }
        guard let scene = GameScene(fileNamed: "GameScene") else {
            print("Error Getting GameScene")
            return
        }
        //let skView = view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true
        skView.ignoresSiblingOrder = true
        skView.showsPhysics = true

        scene.scaleMode = .aspectFill

        skView.presentScene(scene)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else{
            return
        }

        let touchLoation = touch.location(in: self)
        let touchNodes = nodes(at: touchLoation)
        let firstTouchedNode = atPoint(touchLoation).name
        print(firstTouchedNode)

        if firstTouchedNode == "Play Button"{
        loadGame()

            }

        }
}

Answer: func loadGame(){

guard let skView = self.view as SKView? else{
    print("Could not get Skview")
    return
}
var scene:SKScene = GameScene(size: self.size)
}
//let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
skView.showsPhysics = true

scene.scaleMode = .aspectFill

var transition:SKTransition = SKTransition.fadeWithDuration(1)
self.view?.presentScene(scene, transition: transition)

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

for touch in touches {
        let location = touch.location(in: self)
        let node = self.atPoint(location)

        if node.name == "Play Button"{
          //when playbutton is pressed execute code here
          loadGame()

     }
 }

Comment: thank you for your response, the else clause in guard keeps triggering and not taking me to the game scene. guard let scene = GameScene(fileNamed: "GameScene") else {
        print("Error Getting GameScene")
        return
    }
Comment: Can you give me the checkmark if it worked? Thanks!

SpriteKit Main Menu button issue


Mismatched types when trying to parse JSON from curl with serde_json

Question: I've got JSON output from an API for open WIFI which I want to put into a database. The data is in this form.
I already got the information via curl:
let mut easy = Easy::new();
easy.url("https://map.freifunk-rhein-neckar.de/data/nodes.json")
    .unwrap();
easy.write_function(|data| Ok(stdout().write(data).unwrap()))
    .unwrap();
easy.perform().unwrap();

let mut json = easy.response_code().unwrap();

I tried to use serde_json:
extern crate curl;
extern crate serde;
extern crate serde_json;

use std::io::{stdout, Write};
use curl::easy::Easy;
#[macro_use]
extern crate serde_derive;

use serde_json::Error;

#[derive(Serialize, Deserialize)]
struct Freifunk {
    timestamp: u32,
    version: i8,
    nodes: u32,
}

fn json_to_rust() -> Result<(), Error> {
    //Json von Homepage "Auslesen/Downloaden"
    let mut easy = Easy::new();
    easy.url("https://map.freifunk-rhein-neckar.de/data/nodes.json")
        .unwrap();
    easy.write_function(|data| Ok(stdout().write(data).unwrap()))
        .unwrap();
    easy.perform().unwrap();

    let mut json = easy.response_code().unwrap();

    let to_string: Freifunk = serde_json::from_value(json)?;
}

fn main() {}

I always get an error:
error[E0308]: mismatched types
  --> src/main.rs:29:54
   |
29 |     let to_string: Freifunk = serde_json::from_value(json)?;
   |                                                      ^^^^ expected enum `serde_json::Value`, found u32
   |
   = note: expected type `serde_json::Value`
              found type `u32`

error[E0308]: mismatched types
  --> src/main.rs:18:40
   |
18 |   fn json_to_rust() -> Result<(), Error> {
   |  ________________________________________^
19 | |     //Json von Homepage "Auslesen/Downloaden"
20 | |     let mut easy = Easy::new();
21 | |     easy.url("https://map.freifunk-rhein-neckar.de/data/nodes.json")
...  |
29 | |     let to_string: Freifunk = serde_json::from_value(json)?;
30 | | }
   | |_^ expected enum `std::result::Result`, found ()
   |
   = note: expected type `std::result::Result<(), serde_json::Error>`
              found type `()`

Could you give me an example of how to process the data to get it into a database?
Answer:
I already got the information via curl:

No, you didn't. You downloaded it but then wrote it to standard out:
easy.write_function(|data| Ok(stdout().write(data).unwrap()))

What you have called json is the HTTP response code. This is a value of type u32:
let mut json = easy.response_code().unwrap();

Getting the data into a vector is described in the curl documentation. The compiler told you you had incorrect types; you need to read and understand it, then figure out why the types are wrong:
   = note: expected type `serde_json::Value`
              found type `u32`

Additionally, you can't use from_value because you don't have a serde_json::Value to read from.
Your second error is because you've declared that your function returns a Result, but you don't return such at the end of your function. You just... stop, which returns a ()
   = note: expected type `std::result::Result<(), serde_json::Error>`
              found type `()`

extern crate curl;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

use curl::easy::Easy;
use serde_json::Error;

#[derive(Debug, Serialize, Deserialize)]
struct Freifunk {
    timestamp: u32,
    version: i8,
    nodes: u32,
}

fn json_to_rust() -> Result<(), Error> {
    let mut json = Vec::new();

    let mut easy = Easy::new();
    easy.url("https://map.freifunk-rhein-neckar.de/data/nodes.json")
        .unwrap();
    {
        let mut transfer = easy.transfer();
        transfer
            .write_function(|data| {
                json.extend_from_slice(data);
                Ok(data.len())
            })
            .unwrap();
        transfer.perform().unwrap();
    }

    assert_eq!(200, easy.response_code().unwrap());

    let freifunk: Freifunk = serde_json::from_slice(&json)?;

    println!("{:?}", freifunk);

    Ok(())
}

fn main() {}


Using bootstrap with Zepto Undefined is not a function

Question: in html with jade
link(rel="stylesheet",href="/stylesheets/index/index.css")
script(src="/javascripts/assets/jquery_loader.js")
script(src="/javascripts/assets/bootstrap/bootstrap.js")

im using modernizr to load zepto or jquery if IE is the browser
Modernizr.load(
{
    test: /(msie) ([\w.]+)/.test(navigator.userAgent),
    yep: '/javascripts/assets/jquery/jquery-1.9.1.min.js',
    nope: '/javascripts/assets/zepto/zepto.min.js',
    complete:function()
    {
        if(!window.jQuery)
        {
            Zepto.browser = {webkit: true}
            window.jQuery = Zepto
        }
    }
});

i receive this error
Uncaught TypeError: undefined is not a function
(anonymous function) bootstrap.js:60

on line :60
}(window.jQuery);

i try to load bootstrap with modernizr
Modernizr.load(
{
    test: /(msie) ([\w.]+)/.test(navigator.userAgent),
    yep: ['/javascripts/assets/jquery/jquery-1.9.1.min.js','/javascripts/assets/bootstrap/bootstrap.js'],
    nope: ['/javascripts/assets/zepto/zepto.min.js','/javascripts/assets/bootstrap/bootstrap.js'],
    complete:function()
    {
        if(!window.jQuery)
        {
            Zepto.browser = {webkit: true}
            window.jQuery = Zepto
        }
    }
});

and the error disapear but bootstrap doesnt work
so i test in console
typeof $().modal == 'function'

and the result is 'false', this means that bootstrap doesnt download from server
how can i solve this?? tnx
Comment: I don't see you loading Bootstrap **anywhere**
Comment: sry my bad, i correct the error
Comment: Are you sure the Bootstrap library being used has the Modal feature included? Also, as a suggestion, if you want to include a library for both `yep` **and** `nope`, you can use `both`.
Comment: yes bootstrap has the modal feature, and yes i use both too, i still getting the error
Answer: i solve the problem using this script, tnx all!
Modernizr.load(
{
    test: /MSIE ([0-9]{1,}[\.0-9]{0,})/.test(navigator.userAgent),
    yep: '/javascripts/assets/jquery/jquery-1.9.1.min.js',
    nope: '/javascripts/assets/zepto/zepto.min.js',
    complete:function()
    {
        if(!window.jQuery)
        {
            Zepto.browser = {webkit: true}
            window.jQuery = Zepto
            console.log('Zepto')
        }
        Modernizr.load(
        {
            load:'/javascripts/assets/bootstrap/bootstrap.js',
            complete:function()
            {
                console.log('Loaded!')
            },
        })
    },
});


How to save the state of an Fragment in android?

Question: I only have a switch toggle on my fragment. What is the app doing now: The user opens the app and selects "Laptop" over the navigation drawer and then he sees a switch (it is a "slider" which you can move to on or off...hope you understand what I mean). The user sets switch to ON then closes the app and reopens it and the switch is off...but it shouldn't be off...it should be on, like the user sets it How can I do that? The switch should save its state, how the user selects it.
Do I need mysql or something?
(By the way, I am using Android Studio)
I hope you understand what I mean
Thanks
Comment: This question was answered here: http://stackoverflow.com/a/24889044/3834076
Answer: try using shared preferences to save application data, Application can save data in share preferences when application start again it can load data from shared preferences again ... hope it help :)
Answer: You should use SharedPreferences to save the data captured by the Switch. Try the following.
(in your onViewCreated after you initialize your other stuff)
Switch mySwitch = (Switch) findViewById(R.id.mySwitch); // or however else you want to initialize it
final String SWITCH_BOOLEAN = "switchBoolean";
final String PREFERENCE_NAME = "sharedPreferenceFile";
final SharedPreferences prefs = getActivity().getSharedPreferences(PREFERENCE_NAME, 0); // change the name to what you want, this is an xml file that stores your preferences
final SharedPreferences.Editor prefsEditor = prefs.getEditor();

mySwitch.setChecked(prefs.getBoolean(SWITCH_BOOLEAN, false); //also change this name to what you want.

mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        prefsEditor.putBoolean(SWITCH_BOOLEAN, isChecked);
        prefsEditor.apply();
    }
});

Please refer to SharedPreferences for information on SharedPreferences and this for information on the Switch.
Remember that the Strings supplied for the preference names are case sensitive and need to be the same for it to get the same preference.
Comment: thanks for your help but the question has been answered


Navigation Jetpack Compose: IllegalArgumentException: No destination with ID is on the NavController's back stack

Question: In my application, I want to be able to navigate to the CodeDetails screen from different places (from History and from Scanner). I made 2 nested navigation graphs. As a result, I can successfully move from the History screen to the CodeDetails screen, but when I move from the Scanner screen, I get an application crash with an error

java.lang.IllegalArgumentException: No destination with ID -1689679215 is on the NavController's back stack. The current destination is Destination(0x4a873559) route=code_details/{code_id}  at androidx.navigation.NavController.getBackStackEntry(NavController.kt:2209)   at androidx.navigation.NavController.addEntryToBackStack(NavController.kt:1918) at androidx.navigation.NavController.addEntryToBackStack$default(NavController.kt:1813) at androidx.navigation.NavController$navigate$4.invoke(NavController.kt:1721)   at androidx.navigation.NavController$navigate$4.invoke(NavController.kt:1719)   at androidx.navigation.NavController$NavControllerNavigatorState.push(NavController.kt:287) at androidx.navigation.NavigatorState.pushWithTransition(NavigatorState.kt:88)  at androidx.navigation.compose.ComposeNavigator.navigate(ComposeNavigator.kt:50)    at androidx.navigation.NavController.navigateInternal(NavController.kt:260) at androidx.navigation.NavController.navigate(NavController.kt:1719)    at androidx.navigation.NavController.navigate(NavController.kt:1662)    at androidx.navigation.NavController.navigate(NavController.kt:1984)    at androidx.navigation.NavController.navigate$default(NavController.kt:1979)    at com.t_ovchinnikova.android.scandroid_2.navigation.NavigationState.navigateToCodeDetails(NavigationState.kt:24)   at com.t_ovchinnikova.android.scandroid_2.ui.MainScreenKt$MainScreen$2$1$1.invoke(MainScreen.kt:34) at com.t_ovchinnikova.android.scandroid_2.ui.MainScreenKt$MainScreen$2$1$1.invoke(MainScreen.kt:31) at com.t_ovchinnikova.android.scandroid_2.presentation.viewmodel.ScanningViewModel$handleCode$1.invokeSuspend(ScanningViewModel.kt:67)  at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)   at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106) at android.os.Handler.handleCallback(Handler.java:883)  at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:221)  at android.app.ActivityThread.main(ActivityThread.java:7542)    at java.lang.reflect.Method.invoke(Native Method)   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@f1fcaaf, Dispatchers.Main.immediate]

Graph for scanner:
fun NavGraphBuilder.scannerScreenNavGraph(
    scannerScreenContent: @Composable () -> Unit,
    codeDetailsScreenContent: @Composable (codeId: UUID) -> Unit
) {
    navigation(
        startDestination = Screen.Scanner.route,
        route = Screen.ScannerMain.route
    ) {
        composable(Screen.Scanner.route) {
            scannerScreenContent()
        }
        composable(
            route = Screen.CodeDetails.route,
            arguments = listOf(
                navArgument(KEY_CODE_ID) {
                    type = CodeNavigationType
                }
            )
        ) {
            val codeId = it.arguments?.getSerializable(KEY_CODE_ID) as UUID?
                ?: throw RuntimeException("Args is null")
            codeDetailsScreenContent(codeId)
        }
    }
}

Graph for history
fun NavGraphBuilder.historyScreenNavGraph(
    historyScreenContent: @Composable () -> Unit,
    codeDetailsScreenContent: @Composable (codeId: UUID) -> Unit
) {
    navigation(
        startDestination = Screen.History.route,
        route = Screen.HistoryMain.route
    ) {
        composable(Screen.History.route) {
            historyScreenContent()
        }
        composable(
            route = Screen.CodeDetails.route,
            arguments = listOf(
                navArgument(Screen.KEY_CODE_ID) {
                    type = CodeNavigationType
                }
            )
        ) {
            val codeId = it.arguments?.getSerializable(Screen.KEY_CODE_ID) as UUID?
                ?: throw RuntimeException("Args is null")
            codeDetailsScreenContent(codeId)
        }
    }
}

AppNavGraph
@Composable
fun AppNavGraph(
    navHostController: NavHostController,
    scannerScreenContent: @Composable () -> Unit,
    codeDetailsScreenContent: @Composable (codeId: UUID) -> Unit,
    historyScreenContent: @Composable () -> Unit,
    settingsScreenContent: @Composable () -> Unit
) {
    NavHost(
        navController = navHostController,
        startDestination = Screen.ScannerMain.route
    ) {
        historyScreenNavGraph(
            historyScreenContent,
            codeDetailsScreenContent
        )
        scannerScreenNavGraph(
            scannerScreenContent,
            codeDetailsScreenContent
        )
        composable(Screen.Settings.route) {
            settingsScreenContent()
        }
    }
}

Screens
sealed class Screen(
    val route: String
) {
    object ScannerMain : Screen(ROUTE_SCANNER_MAIN)
    object Scanner : Screen(ROUTE_SCANNER)
    object CodeDetails : Screen(ROUTE_CODE_DETAILS) {

        private const val ROUTE_FOR_ARGS = "code_details"

        fun getRouteWithArgs(codeId: UUID): String {
            return "$ROUTE_FOR_ARGS/$codeId"
        }
    }
    object HistoryMain : Screen(ROUTE_HISTORY_MAIN)
    object History : Screen(ROUTE_HISTORY)
    object Settings : Screen(ROUTE_SETTINGS)

    companion object {
        const val KEY_CODE_ID = "code_id"

        const val ROUTE_SCANNER_MAIN = "main"
        const val ROUTE_SCANNER = "scanner"
        const val ROUTE_CODE_DETAILS = "code_details/{$KEY_CODE_ID}"
        const val ROUTE_HISTORY = "history"
        const val ROUTE_HISTORY_MAIN = "history_main"
        const val ROUTE_SETTINGS = "settings"
    }
}

class NavigationState(
    val navHostController: NavHostController
) {
    fun navigateTo(route: String) {
        navHostController.navigate(route) {
            popUpTo(navHostController.graph.findStartDestination().id) {
                saveState = true
            }
            launchSingleTop = true
            restoreState = true
        }
    }

    fun navigateToCodeDetails(codeId: UUID) {
        navHostController.navigate(Screen.CodeDetails.getRouteWithArgs(codeId))
    }
}

My MainScreen
@Composable
fun MainScreen() {

    val navigationState = rememberNavigationState()

    Scaffold(
        bottomBar = {
            BottomBar(navigationState)
        }
    ) { paddingValues ->
        AppNavGraph(
            navHostController = navigationState.navHostController,
            scannerScreenContent = {
                ScannerScreen(
                    paddingValues = paddingValues,
                    onScanListener = {
                        navigationState.navigateToCodeDetails(it)
                    }
                )
            },
            codeDetailsScreenContent = {
                CodeDetailsScreen(
                    codeId = it,
                    onBackPressed = {
                        navigationState.navHostController.popBackStack()
                    }
                )
            },
            historyScreenContent = {
                HistoryScreen(
                    codeItemClickListener = {
                        navigationState.navigateToCodeDetails(it)
                    }
                )
            },
            settingsScreenContent = {
                SettingsScreen()
            }
        )
    }
}

If I create a separate class with a different route and a separate method for navigating to the details screen, then everything works successfully. But why can't I use the same route to go from different places to the same screen?
@Composable
fun AppNavGraph(
    navHostController: NavHostController,
    scannerScreenContent: @Composable () -> Unit,
    codeDetailsScreenContent: @Composable (codeId: UUID) -> Unit,
    historyScreenContent: @Composable () -> Unit,
    settingsScreenContent: @Composable () -> Unit
) {
    NavHost(
        navController = navHostController,
        startDestination = Screen.ScannerMain.route
    ) {
        scannerScreenNavGraph(
            scannerScreenContent,
            codeDetailsScreenContent
        )
        historyScreenNavGraph(
            historyScreenContent,
            codeDetailsScreenContent
        )
        composable(Screen.Settings.route) {
            settingsScreenContent()
        }
    }
}

fun NavGraphBuilder.historyScreenNavGraph(
    historyScreenContent: @Composable () -> Unit,
    codeDetailsScreenContent: @Composable (codeId: UUID) -> Unit
) {
    navigation(
        startDestination = Screen.History.route,
        route = Screen.HistoryMain.route
    ) {
        composable(Screen.History.route) {
            historyScreenContent()
        }
        composable(
            route = Screen.HistoryCodeDetails.route,
            arguments = listOf(
                navArgument(Screen.KEY_CODE_ID) {
                    type = CodeNavigationType
                }
            )
        ) {
            val codeId = it.arguments?.getSerializable(Screen.KEY_CODE_ID) as UUID?
                ?: throw RuntimeException("Args is null")
            codeDetailsScreenContent(codeId)
        }
    }
}

@Composable
fun MainScreen() {
...
            historyScreenContent = {
                HistoryScreen(
                    codeItemClickListener = {
                        navigationState.navigateToHistoryCodeDetails(it)
                    }
                )
            },
...
}

class NavigationState(
    val navHostController: NavHostController
) {
    fun navigateTo(route: String) {
        navHostController.navigate(route) {
            popUpTo(navHostController.graph.findStartDestination().id) {
                saveState = true
            }
            launchSingleTop = true
            restoreState = true
        }
    }

    fun navigateToCodeDetails(codeId: UUID) {
        navHostController.navigate(Screen.CodeDetails.getRouteWithArgs(codeId))
    }

    fun navigateToHistoryCodeDetails(codeId: UUID) {
        navHostController.navigate(Screen.HistoryCodeDetails.getRouteWithArgs(codeId))
    }
}

sealed class Screen(
    val route: String
) {
    object ScannerMain : Screen(ROUTE_SCANNER_MAIN)
    object Scanner : Screen(ROUTE_SCANNER)
    object CodeDetails : Screen(ROUTE_CODE_DETAILS) {

        private const val ROUTE_FOR_ARGS = "code_details"

        fun getRouteWithArgs(codeId: UUID): String {
            return "$ROUTE_FOR_ARGS/$codeId"
        }
    }
    object HistoryCodeDetails : Screen(ROUTE_CODE_INFO_FROM_HISTORY) {

        private const val ROUTE_FOR_ARGS = "history_code_details"

        fun getRouteWithArgs(codeId: UUID): String {
            return "$ROUTE_FOR_ARGS/$codeId"
        }
    }
    object HistoryMain : Screen(ROUTE_HISTORY_MAIN)
    object History : Screen(ROUTE_HISTORY)
    object Settings : Screen(ROUTE_SETTINGS)

    companion object {
        const val KEY_CODE_ID = "code_id"

        const val ROUTE_SCANNER_MAIN = "main"
        const val ROUTE_SCANNER = "scanner"
        const val ROUTE_CODE_DETAILS = "code_details/{$KEY_CODE_ID}"
        const val ROUTE_CODE_INFO_FROM_HISTORY = "history_code_details/{$KEY_CODE_ID}"
        const val ROUTE_HISTORY = "history"
        const val ROUTE_HISTORY_MAIN = "history_main"
        const val ROUTE_SETTINGS = "settings"
    }
}

Comment: The code is so separated and hard to read. It'd be nicer if you can shorten the size of code.
Comment: What version of Navigation are you using?
Comment: @ianhanniballake androidx.navigation:navigation-compose:2.5.3
Answer: I recommend you to change routes' name to
const val ROUTE_SCANNER_MAIN = "main"
const val ROUTE_SCANNER = "scanner"
const val ROUTE_CODE_DETAILS = "code_details"
const val ROUTE_CODE_INFO_FROM_HISTORY = "history_code_details"
const val ROUTE_HISTORY = "history"
const val ROUTE_HISTORY_MAIN = "history_main"
const val ROUTE_SETTINGS = "settings"

And use these for the path. For example,
object CodeDetails : Screen(ROUTE_CODE_DETAILS) {
    private const val ROUTE_FOR_ARGS = "code_details"

    fun getRouteWithArgs(codeId: UUID): String {
        return "$ROUTE_FOR_ARGS/$codeId"
    }
}

This part should be changed to
object CodeDetails : Screen(ROUTE_CODE_DETAILS) {
    fun getRouteWithArgs(codeId: UUID): String {
        return "$ROUTE_CODE_DETAILS/$codeId"
    }
}

And for the passing data between graphs, you better keep that data in the global state data and reuse it.
Otherwise, you can check this source code
Here's the short snippet from the file.
navigation(startDestination = Routes.DESTINATION_PROFILE, route="${Routes.NAVIGATION_LOGGED_IN}/{${Routes.NAVIGATION_LOGGED_IN_ARG_USERNAME}}") {
                composable(route = Routes.DESTINATION_PROFILE) { navBackStackEntry ->
                    val profileViewModel: ProfileViewModel = hiltViewModel(viewModelStoreOwner = navBackStackEntry)

                    val username = navBackStackEntry.arguments!!.getString("username")!!

                    ProfileScreen(profileViewModel, username)
                }
            }

Comment: Thank you very much, but the question is not how to pass the data, but why can't I use the same route to go to a specific screen from different places. Perhaps you can explain how your answer can help me?


Mirror Failure - Default Redirect

Question: I an running into a common issue with trying to maintain and install packages for Ubuntu 20.04, with the following error being returned:

0% [Connecting to au.archive.ubuntu.com (2001:388:30bc:cafe::beef)]

So, first and foremost I just blamed IPv6 as the issue, so went to disable this with the following command:
sudo nano /etc/apt/apt.conf.d/99force-ipv4

Adding the value:
Acquire::ForceIPv4 "true";

Then I proceeded with the following to disable IPv6 on the system entirely:
sudo nano /etc/sysctl.d/99-sysctl.conf

Then added the following into the configuration file:
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1

Then I re-loaded:
sudo sysctl -p

Then, I ran an apt update -y to ensure my packages are updated. Here I an seeing that the repository IPv4 is now being shown, but I still cannot connect to it:
Get:1 http://security.ubuntu.com/ubuntu focal-security InRelease [107 kB]
Hit:2 https://apt.enpass.io stable InRelease
Hit:3 https://packages.cisofy.com/community/lynis/deb stable InRelease
Err:4 http://au.archive.ubuntu.com/ubuntu focal InRelease
  Could not connect to au.archive.ubuntu.com:80 (18.104.22.168), connection timed out
Err:5 http://au.archive.ubuntu.com/ubuntu focal-updates InRelease
  Unable to connect to au.archive.ubuntu.com:http:
Err:6 http://au.archive.ubuntu.com/ubuntu focal-backports InRelease
  Unable to connect to au.archive.ubuntu.com:http:

So as far as I understand, I am being redirected to my nearest mirror that's being best-sourced for my system. How/is there a method wherein I can test to see the availability of the mirror, or even default to another location based on a failure to connect?
Comment: I [did a little diagnostics](https://askubuntu.com/a/1241325/212930) on the mirrors for Proxies and Firewall.
Comment: I can't reach the au ones too, it could be down for some time; in the mean time you can replace them with `http://archive.ubuntu.com` or any `http://XX.archive.ubuntu.com` where XX=country code, in your `sources.list`
Answer: It weirdly looks like a "common" problem for Australian users going to the Australian mirrors: https://bugs.launchpad.net/ubuntu/+bug/162865  Per the bug ticket, contact email@example.com with your traceroutes and debugging.
In the meantime, you can swap out the mirrors in your /etc/apt/sources.list for a non-Australian mirror.
Comment: Thanks. This question was more on does the OS handle these issues automatically.

Mirror Failure - Default Redirect


How can I test whether or not a Chrome extension update will roll smoothly

Question: I have a few extension on the Chrome Web Store. The problem I have is that in another on of my extensions, I screwed up with an update, and it ruined the application unless it was reinstalled, unbeknownst to my user base. I want to test compatibility between versions, and my original idea went like so:

Package current version into .crx
Package new version into .crx using .pem from the current version
Install current version in Chrome
Install the new version over it as an update

This no longer works because Chrome disabled the updating extensions not installed from the Chrome web store. What way is there to test version compatibility before launch?
Comment: How could it require a reinstall instead of just pushing another update?
Comment: @DanielHerr because I could have made a mistake in the code, that messes up the extension upon an update. I need a way to test the update from the current version to the new one without actually distributing the update.
Answer: You can try out to mark the published extension as either unlisted or trusted testers. Its discussed on this StackOverflow question


Which of the following metric spaces are complete?

Question: [NBHM_2006_PhD Screening test_Topology]

Which of the following metric spaces are complete?

$X_1=(0,1), d(x,y)=|\tan x-\tan y|$
$X_2=[0,1], d(x,y)=\frac{|x-y|}{1+|x-y|}$
$X_3=\mathbb{Q}, d(x,y)=1\forall x\neq y$
$X_4=\mathbb{R}, d(x,y)=|e^x-e^y|$

$2$ is complete as closed subset of a complete metric space is complete and the metric is also equivalent to our usual metric.
$3$ is also complete as every Cauchy sequence is constant ultimately hence convergent.
$4$ is not complete I am sure but not able to find out a counter example, not sure about 1.thank you for help.
Answer: For (1), consider the sequence $\left\langle\frac1{2^n}:n\in\Bbb N\right\rangle$. Is it $d$-Cauchy? Does it converge to anything in $X_1$?
For (4), what about $\langle -n:n\in\Bbb N\rangle$?
Comment: for 1 $d(\frac{1}{2^n},0)=|\tan (\frac{1}{2^n})-0|\rightarrow \pi/2$ and for 4, $d(-n,0)=|1/e^n-1|\rightarrow 1$, both are cauchy seuence with respect to the specified metric.
Comment: @Patience: No: $\tan\frac1{2^n}\to 0$ as $n\to\infty$. But in both cases you're missing the point: in order to see whether the sequences are Cauchy, you have to consider $|x_n-x_m|$.
Comment: oops sorry, both are cauchy seuence but does not convergent in the space. as $0$ is missing.
Comment: Almost right: they're both Cauchy, and the first doesn't converge in the space because $0$ is missing; the latter doesn't converge in $\Bbb R$ because $\Bbb R$ has no left endpoint.
Comment: I do not understand your last line :(
Comment: @Patience: It was a non-rigorous explanation of why $\langle -n:n\in\Bbb Z^+\rangle$ doesn't converge in $\Bbb R$: as you move to the left in $\Bbb Z^+$, the points are getting closer and closer together with respect to $d$, but there's no $-\infty$ for them to approach. For a rigorous proof that $\langle -n:n\in\Bbb Z^+\rangle$ doesn't converge in $\Bbb R$, just let $x\in\Bbb R$, and show that for each $\epsilon>0$ there are infinitely many $n$ such that $d(-n,x)>\epsilon$, thereby showing that $x$ isn't the limit of the sequence.
Comment: @BrianM.Scott, is not the distance here $d(x,y)=|e^x-e^y|$ Since $|e^{-x}-e^{-y}|=|1/{e^x}-1/{e^y}| \rightarrow 0$ as $x,y\rightarrow \infty$ It seems like the sequence converges to 0.
Comment: @Freddy: What you've shown is that the sequence is Cauchy. But the sequence itself has no limit in $\Bbb R$, which is the point of the example.
Comment: Sorry for my confusion and thank you!
Comment: @Freddy: No problem: it's always best to get confusions cleared up. You're welcome!
Comment: @BrianM.Scott can somebody please explain 4 again? its very hard. please
Comment: @SighMath: The sequence $\langle -n:n\in\Bbb N\rangle$ has no limit in $\Bbb R$. For any $\epsilon>0$ there is certainly an $m_\epsilon\in\Bbb N$ such that $e^{-m_\epsilon}<\epsilon$. Suppose that $k,n\ge m_\epsilon$. Without loss of generality we may assume that $k\le n$. Then $$d(-k,-n)=|e^{-k}-e^{-n}|=e^{-k}-e^{-n}<e^{-k}\le e^{-m_\epsilon}<\epsilon\;,$$ and we've shown that the sequence is $d$-Cauchy. That is, it's a $d$-Cauchy sequence that does not converge, so $d$ is not complete.
Comment: @BrianM.Scott Sir, I followed your hint, $d(\frac{1}{2^n},\frac{1}{2^m})$ $=|tan(\frac{1}{2^n})-tan(\frac{1}{2^m})|$ $=|tan(\frac{1}{2^n}-\frac{1}{2^m})(1-tan(\frac{1}{2^n})tan( \frac{1}{2^m}))|$, which converges to $0$ as $m,n$  tends to $\infty$. hence it is cauchy Am I right? How to prove that it does not converges to a point in $X_1$? Please help me.
Comment: @ManeeshNarayanan I have tried to [respond in chat](https://chat.stackexchange.com/transcript/message/40676107#40676107).
Comment: @MartinSleziak Ok sir. i got the point. If any euclidean space with a function $d:X×X→\mathbb R$ is given. Isn't enough to show that given $d$ is metric and the subspace is complete? using the fact that all the norms are equivalent in finite vector spaces. Have I gone in wrong direction?
Comment: @MartinSleziak Sir Please help me.
Comment: I am not really sure how exactly I should help you. Why don't you join [the chatroom I suggested](https://chat.stackexchange.com/rooms/15201/general-topology) @ManeeshNarayanan and explain clearly what the problem is?
Comment: @MartinSleziak I tried several times. I am not able two type in the chat. I don't know why.


How can you split such complex strings

Question: INPUT :
A string in c that looks like this : "    12345      computer seince 101"
OUTPUT:
NUMBER OF COURSE = "12345"
NAME OF COURSE = "computer seince 101"
i need to ignore all spacebars before the number and the name, so strings like : "(spaces)12345(more spaces)computer sience 101" are allowded
i tried messing around with strtok, but i failed
Comment: Here the [`strtol`](https://en.cppreference.com/w/c/string/byte/strtol) function would work wonderfully. It not only convert the initial number in the string to an actual integer, it also tells you where the number in the string ends which means you could copy that part into a second string (or print out directly from that position (plus one to skip the space)).
Answer: Use strtol() function.
<code>#include <stdio.h>
#include <stdlib.h>

int main () {
   char str[30] = " 12345 computer science 101";
   char *ptr;
   long ret;

   ret = strtol(str, &ptr, 10);
   printf("NUMBER OF COURSE %ld\n", ret);
   printf("NAME OF COURSE %s", ptr);

   return(0);
}
</code>
The output is:
<code>NUMBER OF COURSE 12345
NAME OF COURSE  computer science 101
</code>

How can you split such complex strings


How to solve the ODE: $ \frac{dy}{dx}=\frac{\sqrt{1-x^2}}{x} $

Question: I am learning differential equations and have been stuck on :
$$ \dfrac{dy}{dx}=\frac{\sqrt{1-x^2}}{x} $$
I tried using $\cos{t}, \sin{t}$ but failed.. how to solve this? please help.
Comment: I found the first version with the integral more amusing...
Answer: Considering $$I=\int \dfrac{\sqrt{1-x^2}}{x}\,dx$$ let us try $x=\sin(t)$, $dx=\cos(t)dt$ which make $$I=\int \frac{\cos^2(t)}{\sin(t)}\,dt=\int \frac{1-\sin^2(t)}{\sin(t)}\,dt=\int \frac{dt}{\sin(t)}-\int \sin(t)\,dt=\int \frac{dt}{\sin(t)}+\cos(t)$$ So, now, considering $$J=\int \frac{dt}{\sin(t)}$$ using the tangent half-angle substitution $z=\tan(\frac t 2)$ makes $$J=\int\frac{dz}z=\log(z)=\log \left(\tan \left(\frac{t}{2}\right)\right)$$ Now, go back to $x$.
I am sure that you can take from here.


Create an array of items pulled from an array of dicts?

Question: I have some output data in this format:
[{'state': 'OK', 'sname': 'sig1', 'extra': None}, {'state': 'OFF', 'sname': 'sig2', 'extra': None}, {'state': 'OK', 'sname': 'sig3', 'extra': None}, {'state': 'UNKNOWN', 'sname': 'sig4', 'extra': None}]

This data can contain any number of entries. What I want to do is pull out all the sname values into a list like this:
snames = ['sig1','sig2','sig3','sig4']

How can I iterate over the output without knowing its length in advance?
Answer: You can use a list comprehension to do this:
In [1]: array_of_dicts = [{'state': 'OK', 'sname': 'sig1', 'extra': None}, {'state': 'OFF', 'sname': 'sig2', 'extra': None}, {'state': 'OK', 'sname': 'sig3', 'extra': None}, {'state': 'UNKNOWN', 'sname': 'sig4', 'extra': None}]

In [2]: snames = [d['sname'] for d in array_of_dicts]

In [3]: print snames
['sig1', 'sig2', 'sig3', 'sig4']

Answer: You can use list comprehension.
With
my_dict_list = [{'state': 'OK', 'sname': 'sig1', 'extra': None}, {'state': 'OFF', 'sname': 'sig2', 'extra': None}, {'state': 'OK', 'sname': 'sig3', 'extra': None}, {'state': 'UNKNOWN', 'sname': 'sig4', 'extra': None}]

You can get all 'sname' entries via:
my_list = [x['sname'] for x in my_dict_list]

and
print(my_list)

prints
['sig1', 'sig2', 'sig3', 'sig4']

Answer: The shortest and most pythonic is to use a list comprehension :
data =  [{'state': 'OK', 'sname': 'sig1', 'extra': None}, {'state': 'OFF', 'sname': 'sig2', 'extra': None}, {'state': 'OK', 'sname': 'sig3', 'extra': None}, {'state': 'UNKNOWN', 'sname': 'sig4', 'extra': None}]

snames = [i['sname'] for i in data if 'sname' in i]

print(snames)
>>> ['sig1', 'sig2', 'sig3', 'sig4']

It's better to verify that 'sname' is in your dict or you might get a KeyError unless you are sure about their consistency (you could get rid of if 'sname' in i in that case).
Comment: I would only start checking if I know that there are some dictionaries in the list that don't contain the Key. Otherwise potential unwanted errors in the nested data structure may not be detected. But I guess that heavily depends on the problem.
Comment: You're right, I had it "just in case" guessing that if we are not sure about the length, it could also be uncertain regarding the dicts. I added a precision in my answer.


Python Dataframe Single Row with Label

Question: import pandas as pd
data = ["X", "Y", "Z", "A", "B"]
label = ['a','b','c','d','e']
df = pd.DataFrame(data, columns=label)
print(df)

I want to get the dataframe to be:
a b c d e
X Y Z A B

I am getting
ValueError: Shape of passed values is (1, 5), indices imply (5, 5)

How to fix this to get the desired dataframe ?
Answer: Pass it as a list of list.
In [439]: pd.DataFrame([data], columns=label)
Out[439]:
   a  b  c  d  e
0  X  Y  Z  A  B

Answer: You can use a bit complicated, but very fast solution if large data - convert list to numpy array and then reshape:
df = pd.DataFrame(np.array(data).reshape(-1, len(data)), columns=label)
print(df)
   a  b  c  d  e
0  X  Y  Z  A  B

Timings:
N = 100
data = ["X", "Y", "Z", "A", "B"] * N
label = ['a','b','c','d','e'] * N

In [30]: %timeit pd.DataFrame([data], columns=label)
10 loops, best of 3: 178 ms per loop

In [31]: %timeit pd.DataFrame(np.array(data).reshape(-1, len(data)), columns=label)
1000 loops, best of 3: 1.06 ms per loop

N = 1000

In [35]: %timeit pd.DataFrame([data], columns=label)
1 loop, best of 3: 1.7 s per loop

In [36]: %timeit pd.DataFrame(np.array(data).reshape(-1, len(data)), columns=label)
100 loops, best of 3: 3.83 ms per loop

Python Dataframe Single Row with Label


Browser viewpoint position of a control

Question: I need to get java script code to find a HTML control position based on the browser screen.
Does anyone knows something about this or can point me in right direction please.
Answer: Try element.getBoundingClientRect().
MDN Document

Browser viewpoint position of a control


How to get Thymeleaf to parse boolean for SpringBootMVC? [ThymeLeaf-SpringBoot-Java17]

Question: So I have a hardcoded true/false value in HTML so I can use that to fill the E.bool value for one of my entities after the HTML form submits (POST).
HTML
<code>// I tried
<select id="isBool" name="isBool" class="form-select" aria-label="select">
  <option value="1">true option</option>
  <option value="0">false option</option>
</select>
// then I tried
<select id="isBool" name="isBool" class="form-select" aria-label="select">
  <option th:value="1">true option</option>
  <option th:value="0">false option</option>
</select>
// then I tried
<select id="isBool" name="isBool" class="form-select" aria-label="select">
  <option th:value="${true}">true option</option>
  <option th:value="${false}">false option</option>
</select>
</code>
Entity
<code>@Entity
@Table
public class E {
  ..
  @Column
  boolean bool
  ..
}
</code>
Controller
<code>public String addE(@Valid E e, BindingResult result, HttpServletRequest request, Model model) {
  ...
  // no matter what, E has bool = false here :(
  ...
}
</code>
What am I doing wrong? No matter what I try, it's always false.
The craziest thing is that I can literally go to my IntelliJ and see in the debugger, that the request.parameters has the correct value right there! What's going on? Why is ThymeLeaf/Spring being so difficult? Is there any easier way to get a boolean like this through the controller?
Answer: Amazingly, it was the getters fault for the boolean member field. My IDE generated it as "isBool" instead of "getBool" and apparently Thymeleaf only looks for literal getters and setters.


Need help in Understanding the Proof of Theorem 2.43 on Perfect Sets in Baby Rudin.

Question:
Theorem 2.43 Let $P$ be a nonempty perfect set in $\mathbb{R}^k$. Then $P$ is uncountable.
Proof:  Since $P$ has limit points, $P$ must be infinite. Suppose $P$ is countable, and denote the points of $P$ by $\mathbf{x_1}, \mathbf{x_2}, \mathbf{x_3}, \ldots$. We shall construct a sequence $\{V_{n}\}$ of neighborhoods as follows.
Let $V_1$ be any neighborhood of $\mathbf{x_1}$. If $V_1$ consists of all $y\in \mathbb{R}^k$ such that $|y−x_1|<r$, the closure $\overline{V_1}$ of $V_1$ is the set of all $y\in \mathbb{R}^k$ such that $|y−x_1|≤r$.
Suppose $V_n$ has been constructed, so that $V_n\cap P$ is not empty. Since every point of $P$ is a limit point of $P$, there is a neighborhood $V_{n+1}$ such that (i) $\overline{V_{n+1}} \subset V_n$, (ii) $x_n\notin \overline{V_{n+1}}$, (iii) $V_{n+1}\cap P$ is not empty. By (iii), $V_{n+1}$ satisfies our induction hypothesis, and the construction can proceed.
Put $K_n=\overline{V_n}\cap P$. Since $\overline{V_n}$ is closed and bounded, $\overline{V_n}$ is compact. Since $\mathbf{x_{n}}\notin K_{n+1}$, no point of $P$ lies in $\cap_1^\infty K_n$. Since $K_{n}\subset P$, this implies that $\cap_1^\infty K_n$ is empty. But each $K_n$ is nonempty, by (iii), and $K_n\supset K_{n+1}$, by (i); this contradicts the Corollary to Theorem 2.36.

I have difficulty in understanding the third paragraph. So I have been reading answers on the following related links on MSE (see [a] and [b]) to strengthen my understanding, but I am unable to get the motivation behind this construction. Also, I would be grateful if someone could explain this idea to me in English.
Comment: I am self-studying analysis, will be grateful if anyone could help.
Answer: To better understand the third paragraph of Rudin's proof, it may be useful to see some of the smaller induction cases worked out in detail.
To start off, pick $\mathbf{x'}\in V_1\cap P$ where $\mathbf{x'}\ne \mathbf{x_1}$.  Such a point exists because $P$ is perfect.
Let $r'=|\mathbf{ x'}−\mathbf{x_1}|$.  Pick $r_2$ such that $0<r_2<\min \left( {r',r - r'} \right)$ and set $V_2 = N_{r_2}(\mathbf{x'})$, where I'm using Rudin's notation for a neighborhood.  Then clearly $\overline{V_2}\subset V_1$, $\mathbf{x_1}\notin V_2$, and $V_2\cap P$ is not empty (the latter, since $V_2$ is a neighborhood of $\mathbf{x'}\in P$).
Next consider what to do for $V_3$.  If $\mathbf{x_2}\notin V_2$, then we can just shrink the neighborhood about $\mathbf{x'}$ to obtain $V_3$:  that is, pick any $r_3$ such that $0<r_3<r_2$.  If we then set $V_3=N_{r_3 } \left(\mathbf{x'} \right)$, we have that $\overline{V_3}\subset V_2$, $\mathbf{x_2}\notin V_3$, and $V_3\cap P$ is not empty.
If $\mathbf{x_2}\in V_2$ and $\mathbf{x_2}\ne \mathbf{x'}$, we can still have $V_3$ be a neighborhood of radius $r_3$ centered about $\mathbf{x'}$ if we simply ensure that $r_3$ is set to some positive value less than $\left| {\mathbf{x_2}-\mathbf{x'}} \right|$.
If, on the other hand, we actually have that $\mathbf{x_2}=\mathbf{x'}$, then we can construct $V_3$ similarly to how we constructed $V_2$.  That is, set $V_3 = N_{r_3} \left( \mathbf{x''} \right)$ where $\mathbf{x''}$ is some point in $V_2\cap P$ and  $r_3$ is chosen so that $V_3$ is strictly contained in $V_2$ but excludes $\mathbf{x_2}$.  For example, set $r'' =|\mathbf{ x''}−\mathbf{x_2}|$ and pick $r_3$ such that $0<r_3<\min(r'', r- r'')$.  Again, we have $\overline{V_3}\subset V_2$, $\mathbf{x_2}\notin V_3$, and $V_3\cap P$ is nonempty.
We can continue this construction indefinitely.
Answer: Paragraph 3 is what trips most people up. I try to show how you can construct such a $V_{n+1}$ here: Proof of Baby Rudin Theorem 2.43


How do I do these conditional bashes?

Question: I have a .txt file, it contains many names, each in its own separate line.
With conditional bashes I have to echo a "Yes" or "No" to the following:

Is there a repeating name?
Is the first name in the .txt file the name which would also be the first if the .txt was alphabetically ordered?
Does the .txt file contain a specific name? (as specified in the bash)

I tried my best but I can't even finish the first one;
if [ sort names.txt | uniq -c > 1]; then echo "Yes"; else echo "No"; fi

I'm not even truly sure what this did either.
How can do any of this?
Answer: There are a few issues with your attempt at Q1:

inside [  ] test brackets, > is the ordinary output redirection operator. (Inside a [[  ]] extended test, > is a comparison operator, but it compares arguments lexicographically rather than numerically.)

[ and [[ tests are picky about whitespace

Taken together, these mean that what your command does is create a file named 1] in the current directory, then throw an error because it can't find a matching ] for the [.

sort names.txt | uniq -c writes to standard output - if you want to test that against something, you need to capture standard output using a command substitution

uniq -c doesn't produce a simple count, instead it produces multiline output like
   1 bar
   2 foo

What you might consider instead is using sort | uniq -d, which will produce output only if there are duplicate lines, capturing its output, and testing whether the result is an empty string or not:
  -z STRING      True if string is empty.

  -n STRING
     STRING      True if string is not empty.

So for example:
if [ -n "$(sort Names.txt | uniq -d)" ]; then echo "duplicates"; else echo "no duplicates"; fi

or
if [ -z "$(sort Names.txt | uniq -d)" ]; then echo "unique"; else echo "non unique"; fi

Alternatively, you could replace uniq with sort -Cu to (quietly) check whether the sorted file is strictly ordered. In this case, you can test the pipeline's exit status rather than its standard output:
if sort Names.txt | sort -Cu; then echo "no duplicates"; else echo "duplicates"; fi

For Q2 and Q3 it will depend on the format of the file - but you might have success with cut and grep or with awk.
Comment: Thanks for the enlightenment! :D I need to learn more about these sorts of command structures than I thought.
Comment: Oops (1) is just plain wrong - deleting while I fix it
Comment: @JohnnyJohnson OK (1) should be correct now I think
Answer: [ sort file | uniq -d ] will always read the whole file.
If the file is big, this might be very slow even if the possible duplicate is in the very beginning.
You could use awk, which will be much faster. It will stop after first duplicate found and there is no need to sort it first.
awk 'seen[$0]++ {print "duplicates"}' file

or more enhanced:
awk '
    seen[$0]++ {dupes=1; exit}
    END {if (dupes) print "duplicates"; else print "no duplicates"}
' file

If you need to use it as part of a bash condition, you can assign a return value:
awk 'BEGIN{ret=1} seen[$0]++ {ret=0; exit} END{exit ret}' file

e.g.
if awk 'BEGIN{ret=1} seen[$0]++ {ret=0; exit} END{exit ret}' file; then
    echo "duplicates"
else
    echo "no duplicates"
fi

Regarding your other questions:
Compare first words:
if [ "$(sort file | head -n1)" =  "$(head -n1 file)" ]; then echo "First line is same as sorted"; fi

Check if a specific word is in the file:
if grep -q "specific_word" file; then echo "Found"; fi

How do I do these conditional bashes?


sqrt of uint64_t vs. int64_t

Question: I noticed that calculating the integer part of square root of uint64_t is much more complicated than of int64_t. Please, does anybody have an explanation for this? Why is it seemingly much more difficult to deal with one extra bit?
The following:
int64_t sqrt_int(int64_t a) {
    return sqrt(a);
}

compiles with clang 5.0 and -mfpmath=sse -msse3 -Wall -O3 to
sqrt_int(long):                           # @sqrt_int(long)
        cvtsi2sd        xmm0, rdi
        sqrtsd  xmm0, xmm0
        cvttsd2si       rax, xmm0
        ret

But the following:
uint64_t sqrt_int(uint64_t a) {
    return sqrt(a);
}

compiles to:
.LCPI0_0:
        .long   1127219200              # 0x43300000
        .long   1160773632              # 0x45300000
        .long   0                       # 0x0
        .long   0                       # 0x0
.LCPI0_1:
        .quad   4841369599423283200     # double 4503599627370496
        .quad   4985484787499139072     # double 1.9342813113834067E+25
.LCPI0_2:
        .quad   4890909195324358656     # double 9.2233720368547758E+18
sqrt_int(unsigned long):                           # @sqrt_int(unsigned long)
        movq    xmm0, rdi
        punpckldq       xmm0, xmmword ptr [rip + .LCPI0_0] # xmm0 = xmm0[0],mem[0],xmm0[1],mem[1]
        subpd   xmm0, xmmword ptr [rip + .LCPI0_1]
        haddpd  xmm0, xmm0
        sqrtsd  xmm0, xmm0
        movsd   xmm1, qword ptr [rip + .LCPI0_2] # xmm1 = mem[0],zero
        movapd  xmm2, xmm0
        subsd   xmm2, xmm1
        cvttsd2si       rax, xmm2
        movabs  rcx, -9223372036854775808
        xor     rcx, rax
        cvttsd2si       rax, xmm0
        ucomisd xmm0, xmm1
        cmovae  rax, rcx
        ret

Comment: As Zalman points out, it is converting the arg to `double` (because that's what your C source does), so it's not strictly the integer part of the sqrt.  Not all integers above 2^53 can be exactly represented as `double`, so this can involve rounding.  https://en.wikipedia.org/wiki/Double-precision_floating-point_format
Answer: First off, you need to be clear that this code is converting 64-bit integers (signed or unsigned) to double precision floating point, taking the square root, and then casting the result back to a signed or unsigned integer.
The answer to your question is because Intel provided 64-bit signed integer to double precision floating-point conversion (and the opposite) in the instruction set you are compiling for, but did not do so for the unsigned case. They added the unsigned conversion instruction in AVX-512, but it does not exist prior to that. So for the signed case, the conversion to double precision and the conversion back are one instruction each. For the unsigned case, the compiler has to synthesize the conversion operation from available instructions.
You can get information on which instructions are available in which versions of SSE2/AVX/AVX-512, etc. here:
    https://software.intel.com/sites/landingpage/IntrinsicsGuide/
You can see discussion of the method used to synthesize the conversion here:
    Are there unsigned equivalents of the x87 FILD and SSE CVTSI2SD instructions?
Answer: In addition to Zalman's excellent answer: The result of the sqrt is always less than INT64_MAX because the input of sqrt is in the uint64_t range. Therefore a single cvttsd2si is sufficient to convert the double back to uint64_t.
In other words: For all input values a the function
uint64_t sqrt_int(uint64_t a) {
    return sqrt(a);
}

has exactly the same behaviour as the modified code
uint64_t sqrt_int(uint64_t a) {
    return (int64_t)sqrt(a);
}

The latter function compiles to
.LCPI0_0:
  .long 1127219200 # 0x43300000
  .long 1160773632 # 0x45300000
  .long 0 # 0x0
  .long 0 # 0x0
.LCPI0_1:
  .quad 4841369599423283200 # double 4503599627370496
  .quad 4985484787499139072 # double 1.9342813113834067E+25
sqrt_int(unsigned long): # @sqrt_int(unsigned long)
  movq xmm0, rdi
  punpckldq xmm0, xmmword ptr [rip + .LCPI0_0] # xmm0 = xmm0[0],mem[0],xmm0[1],mem[1]
  subpd xmm0, xmmword ptr [rip + .LCPI0_1]
  haddpd xmm0, xmm0
  sqrtsd xmm0, xmm0
  cvttsd2si rax, xmm0
  ret

which is much less instruction than the original code.

sqrt of uint64_t vs. int64_t


Is using 15 amp components on a 20 amp breaker against code?

Question: I have noticed in a few different houses in Oklahoma that 20 amp breakers are used, but all of the outlets and switches only seem to be rated for 15 amps. This goes against everything I know to be proper and safe. The wire used is 12 gauge, so at least that is fine.
I have started to replace all of the switches and outlets with the decorative switches (the rectangular ones) and have found it very difficult to find switches that are rated for 20 amps. As for the outlets, I have can find them rated for 20 amps, but not in the 10 packs that I see for the 15 amp versions. To be clear I am not speaking about the shape of the plug, rather I am talking about the rating of the internal components of the outlet.
Is there something about electrical code that I am missing?
Comment: I think I've seen your exact question, but [this question and it's answers](http://diy.stackexchange.com/questions/5865/why-are-there-multiple-receptacles-by-amperage) should provide enough details.
Comment: @BMitch I am not referring to the shape of the plug, but rather the actual current rating. An outlet rated for 15 amps could have multiple devices on it pulling more than a total of 15 amp. Since the breaker is 20 amps, I could be constantly pulling more then the outlet is rated for. I have been able to find outlets that have the 15 amp shape, but are rated to handle 20 amps, but these are the ones that I am having a hard time finding (at least for a comparable price to the 15 amp ones).
Comment: However, if there is a question exactly as mine I would be fine with that. I did some search before I asked and didn't find anything.
Comment: And one more note, I did find it interesting that NEC says you can have 15amp circuits in living spaces and bedrooms and a minimum of two 20amp circuits in kitchens with home run. The smallest breaker in the houses here are 20 amps, and this includes in bedrooms and living areas.
Comment: When was the last time anyone here saw ANY device with a 120 volt 20 amp plug? I have been around a long time and I have seen them used ONCE on a series of fluorescent lit work stations where the lights could be daisy chained. 15 amp receptacles have a pass through rating of 20 amps so a 20 amp receptacle can be unstalled anywhere in the string on a 20 amp breaker circuit. When devices get near 20 amps at 120, device manufacturers tend to switch to 240 volts at half the current.
Answer: NEC 2008

210.21 Outlet Devices. Outlet devices shall have an ampere rating that is not less than the load to be served and shall comply with
  210.21(A) and (B).
(B) Receptacles
(1) Single Receptacle on an Individual Branch Circuit. A single receptacle installed on an individual branch circuit shall have an
  ampere rating not less than that of the branch circuit.
Exception No. 1: A receptacle installed in accordance with
  430.81(B).
Exception No. 2: A receptacle installed exclusively for the use of a cord-and-plug-connected arc welder shall be permitted to have an
  ampere rating not less than the minimum branch-circuit conductor
  ampacity determined by 630.11(A) for arc welders.
(2) Total Cord-and-Plug-Connected Load. Where connected to a branch circuit supplying two or more receptacles or outlets, a
  receptacle shall not supply a total cord and-plug-connected load in
  excess of the maximum specified in Table 210.21(B)(2).

(3) Receptacle Ratings. Where connected to a branch circuit supplying two or more receptacles or outlets, receptacle ratings shall
  conform to the values listed in Table 210.21(B)(3), or where larger
  than 50 amperes, the receptacle rating shall not be less than the
  branch-circuit rating.
Exception No. 1: Receptacles for one or more cord-andplug-connected arc welders shall be permitted to have ampere ratings not less than
  the minimum branch-circuit conductor ampacity permitted by 630.11(A)
  or (B) as applicable for arc welders.
Exception No. 2: The ampere rating of a receptacle installed for electric discharge lighting shall be permitted to be based on
  410.62(C)

(4) Range Receptacle Rating. The ampere rating of a range receptacle shall be permitted to be based on a single range demand
  load as specified in Table 220.55.

If it is a single receptacle on a 20 Amp circuit, it must be a 20 Amp receptacle (aside from the 2 exceptions).  If there are multiple receptacles on a 20 Amp circuit, the receptacles can be either 15 or 20 Amp (aside from the exceptions).
This is to allow You to have multiple devices plugged in drawing less than 15 Amps each, but the total draw on the circuit may be greater than 15 Amps.
NOTE:
Keep in mind that NEC defines a receptacle as follows.

Receptacle. A receptacle is a contact device installed at the outlet for the connection of an attachment plug. A single receptacle
  is a single contact device with no other contact device on the same
  yoke. A multiple receptacle is two or more contact devices on the same
  yoke.

So a duplex receptacle would be considered two receptacles, according to this definition. Which means you can install a single 15 Amp duplex receptacle on a 20 ampere circuit, without violating this code.
Comment: @MatthewPK Yes.  But don't forget, a duplex receptacle is **not** a single receptacle. So you can have a single 15A duplex receptacle on a 20A bathroom circuit.
Comment: @MikeB Table 210.21(B)(3) clearly says that on a 20 ampere circuit 15 or 20 ampere receptacles are allowed. Also remember that a duplex receptacle counts as two receptacles,  not one.
Comment: Also, you can't have a 30 ampere receptacle on a 20 ampere circuit, because that would allow you to plug in a 30 ampere device. If it's a single receptacle on a 20 ampere circuit, the receptacle must be rated 20 amperes.
Comment: Tester is 100% right, a single duplex 15 amp outlet is 2 places to plug in and this is clearly explained in 210.21 I did not need to look it up as the table has the code section and the explanation is close to that . If a single outlet 1 place to plug in it would need to be a 20 amp outlet, more than 1 they can be 15 amp if you read all the listing information on outlets you will find they are rated for 20 amp feed through. One exception to this is the outlets that only have backstab connections they are limited to 14 gauge wire thus 15 amp over current protection.
Comment: Does this mean that a 20A bathroom circuit, having only one receptacle, must use a 20A GFCI device?
Comment: I don't think you've got this right, Tester101. If a single receptacle is on a 20-amp circuit, it must have a rating "not less than that of the branch circuit". This means a 20-amp or greater device is fine, but you're saying it must be exactly 20-amp rated. Same for the case where the branch circuit is driving multiple outlets or multiple receptacles.
Answer: SteveR...
"Apparently a 15A receptacle is safe to use @ 20A"
Scott...
This is incorrect.  It is not safe.  You are allowed to use a 15 amp rated outlet on a 20 amp circuit simply because it is expected that the cord that's plugged into the outlet should not exceed 15 amps (by code).  The current conducted through the front of the outlet is added to the 20 amp branch total at the wire, not within the outlet itself.  In theory, if heat dissipation isn't an issue, you could install a 15 amp rated duplex outlet on a 30 amp circuit and be just as safe because the top could handle 15 amps and the bottom could handle 15 amps.  Yet nowhere within the receptical would it conduct 30 amps because the current is added at the conducting wire.
If you have an applicance with a 15 amp cord that's drawing > 15 amps, it is in violation of the code.  There should not be any such appliances on the market.  Appliances which draw > 15 amps should have a 20 amp or higher cord and plug.  Since power strips are supposed to have built in breakers, thier cords should not exceed 15 amps.  Unfortunately, sometime people exceed the 15 amp rating of a 15 amp receptical by using an extention cord with a triple input where the current sum of the individual cords > 15 amps.  It is recommended that you do not do this since it's a fire hazzard and it violates the code.  However, just because this is possible, doesn't mean it's the fault of the code.  You can't blame the code because people choose not to follow instructions.
I don't want the NEC to try to make the code idiot proof.  Such an effort would eliminate many many convienient electrical products which are safe when used as directed.
Kellenjb...
"But lets say I plug in a power strip and pull more than 15 amps, sounds plausible to me and not very safe."
Scott...
You are correct, it is not safe.
If you are able to do so, then you certainly do have a problem.  If your power strip has a standard 15 amp (14 awg) cord and plug, then it is supposed to have a built in 15 amp breaker.  In your example, your breaker isn't functioning properly and that is not the fault of the code.  If you don't have a built in 15 amp breaker, then your power strip is in violation of the code and by using it, you are violating the code.
Kellenjb...
"Thanks for the answer, but it didn't really get to the point of my question. I fully understand that if you add up the possible current that can be drawn from each outlet, you can go over the current rating of the breaker. I just don't understand why it is allowed to have the situation where one outlet can have more current pulled on it then what the outlet can handle. I would hope the breaker would trip before this point in time."
Scott...
Let me be frank.  I don't know exactly why the NEC chose to allow this.  I could speculate based on legitamate reasons but I won't now.  What I can say is what I stated above. it's possible to exceed the 15 amps when using an extention cord with more than one receptical on it whereby summing the current of multiple applicances totalling > 15 amps (violating the code).  Doing so is contrary to the instructions of the extention cord.  It is not safe and should not be done.  You should be able to discern when you reach the 15 amp limit by adding up the current of each appliance on such an extention cord and not exceed 15 amps (or use current = power/voltage).
Now I'll exclude such possibilities of improper practices from further discussion or I'll never get done.
An outlet rated for 15 amps should only have 15 amps conducted through the front of it via a 15 amp (14 awg) cord.
Let's say you have a duplex outlet and you draw 15 amps on the top and 5 on the bottom, totaling 20 amps.  There is no part of the outlet that's conducting 20 amps.  The 20 amps should be conducted through the attached 12 awg wire only.  If you have two different duplex outlets daisy chained (in parallel) whereas the first conducts 15 amps and the second condusts 5 amps, the current is added at the wire, not the outlet.
Comment: Keep in mind, in addition to a power strip and cord connecting a single device, you can get a power splitter from the hardware store without any breaker, and you can also plug in two 15 amp devices into a duplex receptacle. This is why they often rate a 15 amp receptacle at 20 amps. You can't plug in a 20 amp device with the side tang, but the receptacle is designed for it anyway, and likely assembled from the same parts, just with a different face.
Comment: Also, while devices which are *designed* to draw more than 15 amps should certainly have high-current-style plugs, what about devices which as a consequence of malfunction draw more current than designed, but not so outrageously much as to instantly trip a 20-amp breaker?
Comment: It seems a bit crazy to talk about how using an extension cord breaks code so should not be done. How many average people know this. I would imagine there isn't a single house in any of our towns where this isn't done regularly. People have no idea what code says and since we've all grown up with extension cords with multiple outlets in them, no one would have any idea not to use them as we always have. Something's gotta be missing here....
Comment: Many stores sell devices to convert a duplex outlet into six, and many such devices are rated for 15A but lack any sort of circuit protection.  If both the multi-tap device and the underlying outlet could handle 20 amps continuously without overheating, a 20 amp mains breaker would seem adequate protection, but if not I would think a 15-amp breaker should be required someplace for safety.
Answer: It appears to be permitted to use a 15A receptacle with 20A breaker and 12 AWG wire. The reasoning is that you can't plug a 20A appliance into the 15A receptacle because of the side tang.15A receptacle on 20A breaker.
Apparently a 15A receptacle is safe to use @ 20A. The thinking is that more appliances are drawing more power these days and 15A is to low. This seems to be especially true with kitchen appliances. If you think of a kitchen appliance that uses 1750W, that exceeds 12A (15A @ 80%) rating of a 15A circuit! It should hold if it's the only appliance, but will tax the breaker at a load of 14.6A. It would be safer on a 20A circuit, at 14.6A load (resistive).
Comment: You can't draw 20 amps through a **single** 15 amp outlet. You can draw 20 amps through 2 or more daisy chained 15 amp outlets. With daisy chained outlets the likelihood of drawing all 20 amps through one outlet is minimal. This is why it is allowed to use 15 amp outlets.
Comment: @BradGilbert - You can draw as much amperage though a 15 amp receptacle as you want, at lease til the circuit breaker trips or the receptacle or wire fails.  Their is nothing in a receptacle or switch which regulates how much ampacity that goes through it, other than physics.  I guess you can compare it to either speed limits or speedometers.  If a car's speedometer only shows 80 mph, can it not go faster?
Comment: @Kellenjb You can only protect people to a certain point, otherwise you would need an Electrician to plug in all your devices.  At some point, you just have to hand out a [Darwin Award](http://www.darwinawards.com/)
Comment: Most (all?) 15A receptacles you buy these day will say "20A feed through" on them. This means it can be used on a 20A circuit (although each individual plug is <=15A).
Comment: But lets say I plug in a power strip and pull more than 15 amps, sounds plausible to me and not very safe.
Comment: I agree, but that can also happen with a 20A receptacle. The circuit is still protected for 20A (with 12AWG wire), and they are saying a 15A receptacle can handle 20A okay. See my edit.
Comment: At least with a 20A receptacle on a 20 amp breaker, if you exceed 20 amps the breaker trips and prevents too much current flowing through the receptacle. If all 15A receptacles can actually handle 20 amps this would be good to know, but based off of what I have seen on the boxes, not all advertise that they can handle 20 amps.
Comment: @Kellenjb The power strip is likely rated at 15A, so you won't be able to pull more than that without blowing the internal fuse or damaging the power strip.
Comment: @Tester101 I kind of figured code was always written for the worst case with stupid people. Like if some kid decided to plug a big resistor into an outlet and caused it to pull more than 15 amps but less then 20.
Comment: @Tester101 Yeah, I understand that. But what about things like the compressor in [this answer](http://diy.stackexchange.com/a/5872/2260)?
Comment: @Kellenjb That sounds like a [UL](http://www.ul.com/global/eng/pages/solutions/standards/about/) problem, not NEC.
Comment: @BradGilbert Actually you can draw 20 amps through a NEMA 5-15R. They are basically the same as a 5-20R inside, whether duplex or simplex. I believe the 20 amp capacity is a listing requirement for 15 amp DESIGNATION devices.
Comment: @Skaperen I have taken apart quite a few outlets, and I know that they are the same internally. If I had thought about it I would have stated the argument to apply to both 15amp and 20amp outlets. The problem isn't the outlets, it is the plugs that usually can't handle the current. ( You still shouldn't pull all of the power through one outlet. )
Answer: I distinctly recall that years ago, 15-amp receptacles used to have "20-amp pass through" imprinted on the plastic back or below the ears. Apparently, this is no longer printed on most receptacles, but the UL requirements are the same.
Comment: Can you back this up with something like a link or a picture? Would be interesting to see
Comment: I've never seen this on a "standard" 15A receptacle, but it definitely is on most GFI receptacles.
Comment: This is in-line with what I have seen. Some specifically indicated 20-amp pass through and my concern was with the ones which did not have this stamp.
Answer: This is an old thread, but I think people have missed the point. 15 amp receptacles are designed for use on 20 amp circuits, but 20 amp receptacles are not designed for use on 15 amp circuits. In other words, the 15 amp rating ALLOWS the outlet to be used on a 15 amp circuit. The 20 amp rating PROHIBITS the outlet from being used on a 15 amp circuit.  Either one can be used on a 20 amp circuit.
Comment: I wasn't asking about the plug style being 15 vs 20, I was asking about the actual rating of the outlet. There are outlets that have a 15 amp style plug while being rated for 20 amps. I think the point in some of the other answers is that a device that has a 15 amp style plug should limit possible current draw to 15.
Comment: You can buy a device that converts your duplex 15A (or 20A) outlet in to 6 outlets. It plugs in to both the top and bottom receptacles. This allows it to pull 20A from the outlet without breaking the NEC rule about not drawing more than 12A through a single plug, or 15A when plugged in to a single receptacle circuit.
Answer: I totally understand what you are trying to say Kellenjb.
You are just wondering if an actual receptacles insides or "guts" are rated based on current as well. Right off the bat I will say I am not sure any electrician truly knows that. You would definitely need to call the receptacles company to see the specs. But if you take apart a 15 amp and 20 amp receptacle, do you see a difference? They look the exact same to me...
Lets create some scenarios that are applicable to your situation. Right now you have a 20 amp breaker, 20 amp wire, and a 20 amp receptacle. Now you want to plug your regular old 15 amp blender into your 20 amp receptacle.
But are the "guts" of the receptacle rated for this? Obviously they can take 15 amps but what about if the blender accidentally has something wrong with it and draws 17 amps? The breaker would not trip. The receptacle would have 2 extra amps on it. The blender has no internal breaker so isn't this a scary situation?
Not really. Yes thats two amps more than the blender cord can carry, but really that is not that much for the wire. I don't see any fires happening. And thats sort of the weird thing about all devices. The breaker is not designed to protect the device on it (unless short circuit or ground fault , but not a small extra draw within the breakers rating). Otherwise we would have to have a wide array of different breakers to protect all those random loads we have. The breaker is just to protect the wire. In which case, if the blender in question drew more than 20 amps it would trip the breaker.
Basically I am about to put a 20 amp breaker, with 20 amp wire on a 15 amp receptacle today. Why?
I have two stacked gas ovens that will draw 7.5 amps each. I just want to run one circuit. So 7.5 * 2 = 15 amps. Therefors I need the 20 amps at the receptacle to fit both plug cords on one circuit. If only one is on and drawing 18 amps... well i guess thats how it goes. The prongs should be able to take it. Till one day I think what the hell is wrong with my oven?
Answer: For the most part, ALL recepticals made nowadays have guts that are rated to handle 20A.  This is to ensure that you don't overload the outlet itself.  This is a safety precaution.  If you take apart a 20A and a 15A receptical, the internal parts are the same.  The only difference is the front cover, which limits you from plugging a 20A appliance into a circuit that is only rated for 15A.  This is where the different plug styles come in to play.  This makes it to where the circuit breaker trips before the receptical overheats, preventing a fire hazzard. I hope this helps.
Comment: Is this documented somewhere, or can you point to a specific example? Just wondering if there's a way for me to tell w/o taking it apart...
Answer: if memory serves they call this Diversity. The expectation is that not all outlets served by the breaker will be at full current draw 100% of the time, there is a limitation on the number of outlets per floor area too yet it's still possible to have enough 13A outlets on one 32A ring to exceed 32A. In practice it won't happen and if it did, well that's what the breaker is for. I should add this is in the United Kingdom but I expect there is a similar term for over the pond albeit lower voltage, higher current then here.
Comment: Thanks for the answer, but it didn't really get to the point of my question. I fully understand that if you add up the possible current that can be drawn from each outlet, you can go over the current rating of the breaker. I just don't understand why it is allowed to have the situation where one outlet can have more current pulled on it then what the outlet can handle. I would hope the breaker would trip before this point in time.
Comment: Well in the UK the plug that goes in the outlet is fused at the correct rating for the appliance so it is that that prevents the outlet being overloaded. The breaker prevents the supplying circuit to one but usually more outlets being overloaded, choosing the rating of that breaker is where Diversity has to be taken into account.
Answer: you are all over thinking this and the UK answers don't help as Europe has 240 volts.
USA answer: Each duplex receptacle on a 15Amp outlet can handle 15Amps, and in this scenario the wire plugged into it can handle 20Amps (12 guage)  therefore there's no chance that running even 20 amps is an issue in that outlet.
here's why: The only way to exceed 15amps per receptacle (there's 2 receptacles in a duplex "outlet") would be to connect a 20Amp device to it, which doesn't work as they have the protective side tangs to them. 20Amp devices are things like a 1.5HP pool pump. Most USA homeowners have never owned a 20Amp device, certainly not one that can bring around the house with them as thay always require a dedicated circuit and have fancy connections that cannot plug into regular outlets.
So since each receptacle on a duplex outlet is designed to handle 15Amps, there's no scenario where there could be an issue.
Comment: Here's a scenario: I buy a 5-20R to 5-15P adapter, like the one linked below, and plug it into that 5-15R, 15A-rated outlet... http://www.homedepot.com/p/RIDGID-20-Amp-T-Blade-Adapter-612-TADAPT20R/202070815
Comment: I think my comment to woody would apply to this answer as well. Essentially I am not concerned with plug type, I am concerned about the possibility of a device breaking and pulling too much. Sounds like it is up to the device to never allow that to happen.
Answer: A 20 amp receptacle and a 15 are the same aside from the face. It is the appliance itself which determines the draw.  20 amp plugs have the side slot to prevent attempting to power a 20amp device with a 15 amp service, under powering the device and overdrawing on the circuit.
Most new microwaves and MW/good fans combos require a 20 amp circuit but come with the standard 15amp plug. This is due to the possibility of the device drawing more than 12 amps.
The device will not overdraw on the available power and over heat the receptacle,  it will only draw to it's rating.
Comment: I'm not concerned about the plug type, and I understand it is the device that determines how much current it will pull. My major confusion is with what happens when you have a device that has a normal 15 amp plug, typically uses much less than 15 amp, but then breaks in a way that causes it to pull more than 15 but less than 20. I'd think this could cause a problem as the outlet is not rated to handle these higher currents, but the breaker won't trip. From the other answers it sounds like it is the devices responsibility to never pull more than 15 and to have an internal breaker if it could.
Answer: I see this is a real old thread but I'll chime in to see if it helps clear other people's minds as they Google search this question. I think people over think it. A 15 amp plug has two vertical blades, 20 amp plug has 1 vertical and 1 horizontal. The different configurations are so you don't accidentally plug a piece of equipment that draws 20 amps into a 15 amp circuit. Everyone is going to say duh... so how many people have 20 amp plugs that come with their appliances? I doubt anyone... so, everyone is plugging in 15 amp plugs with their appliances. If the appliances have 15 amp plugs, it probably means it's not supposed to draw over 15 amps so why would you need a receptacle with a 20 amp configuration?  The code requires you to install 2 circuits each capable of carrying 20 amps, not because you're plugging in 1 appliance that draws 20 amps, but because you're plugging in multiple appliances that may reach 20 amps. If I have 3-15 amp receptacles with a toaster, microwave, and fridge, they may each draw 6amps which is well below the 15 amps individually but as a sum is well over.
The reasoning behind the single receptacle being rated for the circuit breaker is... if I install a dedicated 20 amp circuit, why would I put a 15 amp receptacle on it? If I'm going through the trouble of installing a dedicated 20 amp circuit, it better be for a piece of equipment drawing 20 amps. Otherwise I'd install a dedicated 15 amp circuit for my 15 amp piece of equipment.
The reason I came across this thread is because I feel the code is a little unclear about the 80% rating of the breaker rule. I was always taught to never exceed 80% of the breaker on the entire circuit. But as I'm reading it tonight, 210.21 B2 says, where connected to a branch circuit supplying 2 or more receptacles, a receptacle shall not supply a total cord and plug connected load of table 210.21 B2 which is 80%. So the way it reads is, if I have 3 receptacles on 1 15a circuit, I can't have more than 12amps on 1 lone receptacle, but I could have 12amps on 1 and 1 amp on the other 2 receptacles and that'd be acceptable? That equals 14 amps on 15 amp breaker which I was always taught exceeds the 80% so it's wrong. But the code says I can't exceed 80% on just 1 of the 3 receptacles.
Comment: The old blanket 80% rule is an old wives tale. A 15A general receptacle circuit can have a load of 15A, not just 12A. There are certain loads and circuits that may not exceed 80%, but general use receptacles circuits do not fall under these.
Comment: I wasn't asking about the shape of the plug, rather the rating of the outlet itself. I believe the correct answer is that an outlet may be rated for 20 amp pass through with only a 15 amp shaped plug while other outlets may not be rated for the 20 amp pass through.
Answer: At least in Italy it's a violation, because circuit should be rated as the lowest rated component: you can have on a 4mm^2 circuit with both 15A and 10A outlets but breaker must be 10A.


Add gitignore for node_module failed

Question: I created a .gitignore file and within it I put "node_modules". But when I run git status it still shows my node_modules folder as untracked file. What's wrong?
Comment: Did you track the node_modules before adding it to .gitignore?
Comment: @NicholeA.Miler That doesn't answer the question: `git init` has nothing to do with *tracking* files.
Comment: @ThomasBormans I do git init before I do npm init of course.
Answer: If you want to ignore a folder, make sure to add a trailing slash in your .gitignore line:
node_modules/

(not "node_modules" with quotes)
If you still see untracked files, check also the rules with:
git check-ignore -v -- node_modules

Make sure the .gitignore is placed at the same level or above the folder which container node_modules.
Make sure the .gitignore name is correct (case, and no trailing space like '.gitgignore')
Comment: @NicholeA.Miler No problem, I have edited the answer to make that clear.
Comment: now I change it to `node_modules/`, and do git status, it's there still.

Add gitignore for node_module failed


Redirect Back Open Restrict page after Login

Question: When i open directly any restriction page/url "http://domain.com/xyz/" like user,dashboard,myphoto,messages etc..then page obliviously redirect to login page and when i login then how can come back open page/url?
I am not getting any referral url in login page so please let me know how can do it using PHP and cakePHP?
Comment: You should always mention the exact cakephp version you are using.
Comment: What I get is, you are on one of the pages of the website, but when you need to login and login you redirect to the page you were before the login?
Comment: @Lenap Basically if the authentication is successful, he's looking for another redirection from the login page back to the dashboard page... It's kind of redundant though, since he was redirected from the dashboard page to the login page in the first place, but I understand the need.
Answer: You can redirect user by using
$this->Auth->loginRedirect = array('controller'=>'your controller','action'=>'Your action')
in AppController.php
Comment: I am want to redirect previous page..Like if someone open direct url account,dashboard,message,etc then page redirect automatically on login page then how can redirect previous page from where he/she come...? Itz not about cakePHP itz about logic/concept...how can do it in programming...


Salvage droid mission keeps giving "already opened this cargo"

Question: I've been sending damage droids to kashyyyk in the second slot a bunch, after luckily unlocking Chiss HSP on bronze.
Now other than the usual VIP and credit rewards, sometimes I'm given the message that I've already opened this cargo and to please have these bux. It started out at 2 and it's up to 12 now, increment of 2 each time.
Has anybody else seen this yet? Maybe it's because I've unlocked a level already? I don't know if you can get other levels from different areas.
Answer: I also get a bux reward when opening a cargo container for cargo that I've already received.  I have not noticed your pattern of increasing bux rewards - my rewards have varied from 2 - 10 bux; but it could be that since I have several bitizens and 2 levels unlocked that the reward varies depending on what you see again?
One pattern I can confirm: When I unlock a bitizen, I first get the typical find bitizen quest to grant them access - this will give you 1 buck back; and then I will immediately get a new cargo delivery that gives me a 5 bux reward for having already received this cargo.  This means that you get a refund of 6 bux on the off-chance that you actually manage to unlock a new bitizen.


how to set the column value of one dataframe depending on whether the value in another column is included in the specific column of another dataframe

Question: How to set up the value of one column of a dataframe depending on whether the value in another column of the dataframe is included in a specific column of another dataframe. If it is included the number is 1, if not,0. For example: I have two dataframes:
a={'age':[22,38,26,62,198,27],'no':[1,2,3,4,5,6]}

TableB= {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen','Mary','Celina','Roger'],
'age': [22,38,26,35,41,22,38],
'fare': [7.25, 71.83, 0 , 8.05,7,6.05,6],
'survived?': [False, True, True, False, True, False, True]}

I would like to check if every number in the 'age' column of a is included in the 'age' column of TableB, if it is included, add a column 'Observer' in a and set the value to 1,if not,0.
I have tried this:

a['age'].isin(TableB['age'].set_value('Observer',1)

expected results are as follows, but my result is that all the values in the observer column of a is 1.
a={'age':[22,38,26,62,198,27],'no':[1,2,3,4,5,6],'observer':[1,1,1,0,0,0]}

Comment: `a={'age':[22,38,26,62,198,27],'no':[1,2,3]} ` how did you convert this to a dataframe?
Comment: Sorry  it was a mistake I have corrected it now
Answer: a={'age':[22,38,26,62,198,27],'no':[1,2,3,4,5,6]}
a = pd.DataFrame(a)
print (a)
   age  no
0   22   1
1   38   2
2   26   3
3   62   4
4  198   5
5   27   6

TableB= {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen','Mary','Celina','Roger'],
'age': [22,38,26,35,41,22,38],
'fare': [7.25, 71.83, 0 , 8.05,7,6.05,6],
'survived?': [False, True, True, False, True, False, True]}

TableB = pd.DataFrame(TableB)
print (TableB)
        name  age   fare  survived?
0     Braund   22   7.25      False
1   Cummings   38  71.83       True
2  Heikkinen   26   0.00       True
3      Allen   35   8.05      False
4       Mary   41   7.00       True
5     Celina   22   6.05      False
6      Roger   38   6.00       True

You can cast boolean mask to integer for True/False to 1/0 mapping:
a['observer'] = a['age'].isin(TableB['age']).astype(int)

Alternative solution is use numpy.where:
a['observer'] = np.where(a['age'].isin(TableB['age']), 1, 0)

print (a)
   age  no  observer
0   22   1         1
1   38   2         1
2   26   3         1
3   62   4         0
4  198   5         0
5   27   6         0

If working with dictionaries then use list comprehension with if-else and test membership by in:
a={'age':[22,38,26,62,198,27],'no':[1,2,3,4,5,6]}

TableB= {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen','Mary','Celina','Roger'],
'age': [22,38,26,35,41,22,38],
'fare': [7.25, 71.83, 0 , 8.05,7,6.05,6],
'survived?': [False, True, True, False, True, False, True]}

a['observer'] = [1 if x in TableB['age'] else 0 for x in a['age']]
print (a)
{'age': [22, 38, 26, 62, 198, 27], 'no': [1, 2, 3, 4, 5, 6], 'observer': [1, 1, 1, 0, 0, 0]}

Answer: a={'age':[22,38,26,62,198,27],'no':[1,2,3,4,5,6]}
TableB= {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'],
'age': [22,38,26,35,41,22,38],
'fare': [7.25, 71.83, 0 , 8.05,7,6.05,6],
'survived?': [False, True, True, False, True, False, True]}
 a['observer']=[];

for i in a['age']:
  if i in  TableB['age'] :
     a['observer'].append(1)
  else :
      a['observer'].append(0)


Unable to connect to Internet after wakeup from hibernate?

Question: It says Networking is Disabled. I have tried checking that box (which stays checked); but that does nothing.
Even tried: sudo ifconfig wlan0 up; which also did nothing. I'm running Ubuntu 13.10 x64.
Comment: Note that after a reboot it works fine again.
Comment: I have the same issue using 14.04 once it hibernates the only thing I have found to get my network operational is a reboot.
Comment: by the way I have enable networking checked and the other option ( "sudo ...")posted.  My machine is hibernating vs sleep mode if that makes a difference.
Answer: I have also had this problem. I have discovered that if you check the "Enable Networking" box, put it to sleep, and then wake it up again, it works. Eventually after doing it for a while the problem seemed to stop.