text
stringlengths
64
81.1k
meta
dict
Q: 無茶 - "bad tea" = absurd; unreasonable I have the following in a Zelda guide book I am translating. It is talking about being faced with a problem and trying various ways to solve it (you know the Zelda games). I am interested in "むちゃな". There is no kanji but I believe it is 無茶な. This is a videogame guide book and the target audience is teenagers I believe, from looking at what kanji is used and not used. そう思える場合は、大抵そのとおりなのだ。 あまりむちゃなアクションを要求されることはない。 This looks to me like "bad tea" (which could mean "absurd" in a way). Is this the correct kanji, and is it common to use this kanji or is hiragana preferred? Does anybody know the origins of this? Does "bad tea" really mean "absurd"? if the next line helps: これまでに覚えたアクションと、ゲットしたアイテムを使えば、ほとんどの謎は苦労せずに解けるはずなのだ。 A: First, 無茶 wouldn't be interpreted as bad tea. 無 means "no" as in "nothingness," not bad. As such, one might be led to believe that this is something about not having any tea to give to guests or something, and that situation being where the term came from. This is not true. The kanji 無茶 are ateji. This means that the kanji were chosen arbitrarily based on the pronunciation of the word. This site suggests that the word itself is derived from an old Buddhist term, 無作{むさ}, though that appears to be ultimately speculative. Regardless, though, the word is not connected to tea.
{ "pile_set_name": "StackExchange" }
Q: Can the tongues spell decipher writing (directly or indirectly)? The description for tongues states, This spell grants the creature touched the ability to speak and understand the language of any intelligent creature It makes no special mention of understanding written languages--just that you can "understand the language". If it doesn't include this ability, though, could, for example, a Dwarf using the spell read aloud a message written by Orcs (since apparently Dwarvish and Orcish use the same writing system, but if that's not how the actual languages in the settings work then replace the example with languages that do work that way), and then listen to and understand their own Orcish? A: Directly—maybe So there is a conflict between two rules here. As Matheus’s fine answer covers, tongues itself refers solely to speaking and listening, and any mention of reading and writing is conspicuously absent, compared with, say, comprehend languages which explicitly covers reading. The conflict I mention, though, is with some much more basic rules: Literacy Any character except a barbarian can read and write all the languages he or she speaks. (Basics → Races → Races and Languages) A literate character (anyone but a barbarian who has not spent skill points to become literate) can read and write any language she speaks. (Skills → Speak Language) So one could argue that when tongues gives you the ability to speak some language, it also (per this rule) gives you the ability to read and write it—nothing in tongues says it doesn’t do that, which could arguably mean this default rule is still in play. Contrast that with comprehend languages, which explicitly says you understand and can read languages you wouldn’t otherwise know, but cannot speak or write them. Comprehend languages has an explicit exception to the connection between being able to speak, read, and write a language, while tongues just leaves any mention of reading and writing out. (Obviously, none of this applies if you are a barbarian who somehow cast tongues.) The counter-argument, of course, is that the first is in the “races and languages” section, and is “obviously” talking about the automatic and bonus languages you learn as part of character creation. The second, equally, is in the section on the Speak Language skill, and so only applies to languages learned that way (though the description—the first bullet—explicitly discusses the state of affairs prior to spending any skill points on the skill). One could even argue that the repetition here is important—that the rule written in one of these places wouldn’t apply to the other so they had to write it in both. The counter-counter-argument is that if they only meant for those rules to apply to automatic/bonus languages and Speak Language, respectively, why didn’t they just say that? They explicitly—twice—used very general language, and they don’t even make any mention of “knowing” the language—reading and writing explicitly hinges on “speaking” the language, and tongues definitely does that. All in all, I suspect that tongues probably wasn’t meant to cover written language, but because of how the basic rule was written, it’s impossible to be sure. It is best, then, to ask your DM to make a ruling here. I have played games where tongues covers written language and I have played games where it does not, and I have played in many, many games where it never came up and never would have mattered anyway. (Actually, even in the games where we discussed this up front and rulings were made, I can’t recall it ever actually mattering in game there, either.) Language is rarely an critical part of adventures, and it is a very difficult thing for a DM to add to an adventure in a way that remains fun. Indirectly—certainly not Puzzling out something written in an unknown language is a function of the Decipher Script skill, and that skill gets no bonus for knowing related languages, or for speaking but not reading the language in question, and the tongues spell doesn’t mention it. So if tongues doesn’t help you directly, it also won’t help indirectly.
{ "pile_set_name": "StackExchange" }
Q: Wrong Answer with Java I'm a student that is learning Java, and I have this code: lletres = lletres.replace(lletres.charAt(2), codi.charAt(codi.indexOf(lletres.charAt(2)) + 1)); lletres is a string, and it's like this lletres = "BBB" The result is "CCC" and I only want to change the last B, so the result can be like this: "BBC". A: Reading the documentation for String.replace should explain what happened here (I marked the relevant part in bold): Returns a string resulting from replacing all occurrences of oldChar in this string with newChar. One way to solve it is to break the string up to the parts you want and then put it back together again. E.g.: lletres = lletres.substring(0, 2) + (char)(lletres.charAt(2) + 1);
{ "pile_set_name": "StackExchange" }
Q: How to set initial interface orientation? My application always launches in landscape mode with the home button on the left side. If the home button on the right side it rotates. How do i make it opposite? I tried setting different values into info.plist file for initial interface orientation key but it didn't work. I tried switching order of values in this method: - (NSInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskLandscapeLeft; } but it didn't work neither. How do i do that? A: For IOS 5 and 5.1 : Try to set (BOOL)shouldAutorotateToInterfaceOrientation in your view controllers, it works for me. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { return toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight; } If you are using storyboards you can also set your initial and other viewcontrolers to landscape mode : For IOS 6: your (NSInteger)supportedInterfaceOrientations should be (NSUInteger) , I am not sure though I never use it. // Only used by iOS 6 and newer. - (BOOL)shouldAutorotate { //returns true if want to allow orientation change return TRUE; } - (NSUInteger)supportedInterfaceOrientations { //decide number of origination to supported by Viewcontroller. return return UIInterfaceOrientationMaskLandscape; }
{ "pile_set_name": "StackExchange" }
Q: What's the opposite of head? I want all but the first N lines of a file Given a text file of unknown length, how can I read, for example all but the first 2 lines of the file? I know tail will give me the last N lines, but I don't know what N is ahead of time. So for a file AAAA BBBB CCCC DDDD EEEE I want CCCC DDDD EEEE And for a file AAAA BBBB CCCC I'd get just CCCC A: tail --help gives the following: -n, --lines=K output the last K lines, instead of the last 10; or use -n +K to output lines starting with the Kth So to filter out the first 2 lines, -n +3 should give you the output you are looking for (start from 3rd). A: Assuming your version of tail supports it, you can specify starting the tail after X lines. In your case, you'd do 2+1. tail -n +3 [mdemaria@oblivion ~]$ tail -n +3 stack_overflow.txt CCCC DDDD EEEE A: A simple solution using awk: awk 'NR > 2 { print }' file.name
{ "pile_set_name": "StackExchange" }
Q: Build an EBCDIC converter using NAND logic gates In this question, a mapping is defined between EBCDIC and a superset of ISO-8859-1. Your task is to build a network of two-input NAND gates that will take eight inputs A1, A2, A4, ..., A128 representing an EBCDIC character and return eight outputs B1, B2, B4, ..., B128 that represent the corresponding "ISO-8859-1" character according to that mapping. To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores: NOT: 1 AND: 2 OR: 3 XOR: 4 Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate. The logic circuit that uses the fewest NAND gates to correctly implement all the above requirements wins. A: 727 Gates How I did it: turned the code page translation from wikipedia into an appropriately formatted truth table using Excel (15 minutes) minimized the truth table using Espresso (5 minutes, 30 minutes on 1st iteration getting back into the saddle) fed the minimized truth table into a schematic generator (1 minute) iterated on 2&3 until I got a reasonable answer (<1 hour) turned the schematic into an uploadable image (30 min, %$#@! Microsoft) Here's the 100% NAND gate result: If I was actually going to implement this, I'd drop the NAND-centric scoring. Building XOR gates out of NANDs is a big waste of transistors. Then I'd start worrying about UMC, fire up the FPGA design tools, maybe break out the HDL manuals, etc. Whew! I love software. NB, for hobbyists interested in FPGAs, I'll recommend FPGA4fun. A: 309 NANDs A really low solution in the number of NANDs, but I can go even lower. One just have to stop somewhere, some time, and 309 seems good for that. (I actually reached 308 NANDs later, but then hit some kind of barrier.) No pencil drawn image of the circuit this time. Perhaps later if I some day return to this problem and hit a lower edge, ledge, limit, in the increasingly dense thicket of wrong circuits. The circuit is presented in obvious Verilog code, ready for running with test included. Verilog code: // EBCDIC to ISO-latin-1 converter circuit // Made of just 309 NANDs // // By Kim Øyhus 2018 (c) into (CC BY-SA 3.0) // This work is licensed under the Creative Commons Attribution 3.0 // Unported License. To view a copy of this license, visit // https://creativecommons.org/licenses/by-sa/3.0/ // // This is my entry to win this Programming Puzzle & Code Golf // at Stack Exchange: // https://codegolf.stackexchange.com/questions/26252/build-an-ebcdic-converter-using-nand-logic-gates // // There are even simpler solutions to this puzzle, // but I just had to stop somewhere, and 309 NAND gates is // a very low number anyway. module EBCDIC_to_ISO_latin_1 ( in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007, out000, out001, out002, out003, out004, out005, out006, out007 ); input in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007; output out000, out001, out002, out003, out004, out005, out006, out007; wire wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017, wir018, wir019, wir020, wir021, wir022, wir023, wir024, wir025, wir026, wir027, wir028, wir029, wir030, wir031, wir032, wir033, wir034, wir035, wir036, wir037, wir038, wir039, wir040, wir041, wir042, wir043, wir044, wir045, wir046, wir047, wir048, wir049, wir050, wir051, wir052, wir053, wir054, wir055, wir056, wir057, wir058, wir059, wir060, wir061, wir062, wir063, wir064, wir065, wir066, wir067, wir068, wir069, wir070, wir071, wir072, wir073, wir074, wir075, wir076, wir077, wir078, wir079, wir080, wir081, wir082, wir083, wir084, wir085, wir086, wir087, wir088, wir089, wir090, wir091, wir092, wir093, wir094, wir095, wir096, wir097, wir098, wir099, wir100, wir101, wir102, wir103, wir104, wir105, wir106, wir107, wir108, wir109, wir110, wir111, wir112, wir113, wir114, wir115, wir116, wir117, wir118, wir119, wir120, wir121, wir122, wir123, wir124, wir125, wir126, wir127, wir128, wir129, wir130, wir131, wir132, wir133, wir134, wir135, wir136, wir137, wir138, wir139, wir140, wir141, wir142, wir143, wir144, wir145, wir146, wir147, wir148, wir149, wir150, wir151, wir152, wir153, wir154, wir155, wir156, wir157, wir158, wir159, wir160, wir161, wir162, wir163, wir164, wir165, wir166, wir167, wir168, wir169, wir170, wir171, wir172, wir173, wir174, wir175, wir176, wir177, wir178, wir179, wir180, wir181, wir182, wir183, wir184, wir185, wir186, wir187, wir188, wir189, wir190, wir191, wir192, wir193, wir194, wir195, wir196, wir197, wir198, wir199, wir200, wir201, wir202, wir203, wir204, wir205, wir206, wir207, wir208, wir209, wir210, wir211, wir212, wir213, wir214, wir215, wir216, wir217, wir218, wir219, wir220, wir221, wir222, wir223, wir224, wir225, wir226, wir227, wir228, wir229, wir230, wir231, wir232, wir233, wir234, wir235, wir236, wir237, wir238, wir239, wir240, wir241, wir242, wir243, wir244, wir245, wir246, wir247, wir248, wir249, wir250, wir251, wir252, wir253, wir254, wir255, wir256, wir257, wir258, wir259, wir260, wir261, wir262, wir263, wir264, wir265, wir266, wir267, wir268, wir269, wir270, wir271, wir272, wir273, wir274, wir275, wir276, wir277, wir278, wir279, wir280, wir281, wir282, wir283, wir284, wir285, wir286, wir287, wir288, wir289, wir290, wir291, wir292, wir293, wir294, wir295, wir296, wir297, wir298, wir299, wir300, wir301, wir302; nand gate000 ( wir000, in_003, in_000 ); nand gate001 ( wir001, in_002, in_002 ); nand gate002 ( wir002, in_000, in_000 ); nand gate003 ( wir003, in_000, in_004 ); nand gate004 ( wir004, wir003, in_001 ); nand gate005 ( wir005, in_006, in_003 ); nand gate006 ( wir006, wir003, wir005 ); nand gate007 ( wir007, in_007, in_007 ); nand gate008 ( wir008, wir003, wir004 ); nand gate009 ( wir009, wir003, wir006 ); nand gate010 ( wir010, in_005, wir009 ); nand gate011 ( wir011, wir008, wir009 ); nand gate012 ( wir012, wir009, wir011 ); nand gate013 ( wir013, in_004, wir002 ); nand gate014 ( wir014, wir013, wir009 ); nand gate015 ( wir015, in_006, wir007 ); nand gate016 ( wir016, wir001, wir015 ); nand gate017 ( wir017, wir015, wir015 ); nand gate018 ( wir018, in_003, wir015 ); nand gate019 ( wir019, wir018, wir018 ); nand gate020 ( wir020, wir000, wir007 ); nand gate021 ( wir021, wir005, wir017 ); nand gate022 ( wir022, wir018, wir011 ); nand gate023 ( wir023, in_002, wir018 ); nand gate024 ( wir024, in_001, in_003 ); nand gate025 ( wir025, wir010, in_004 ); nand gate026 ( wir026, wir017, wir024 ); nand gate027 ( wir027, wir001, wir007 ); nand gate028 ( wir028, in_004, wir024 ); nand gate029 ( wir029, wir024, wir024 ); nand gate030 ( wir030, in_004, wir023 ); nand gate031 ( wir031, wir022, wir030 ); nand gate032 ( wir032, wir026, wir030 ); nand gate033 ( wir033, wir030, wir020 ); nand gate034 ( wir034, wir001, wir026 ); nand gate035 ( wir035, wir022, in_007 ); nand gate036 ( wir036, wir020, wir034 ); nand gate037 ( wir037, wir007, wir023 ); nand gate038 ( wir038, wir034, wir023 ); nand gate039 ( wir039, wir031, wir033 ); nand gate040 ( wir040, wir028, wir019 ); nand gate041 ( wir041, wir036, wir040 ); nand gate042 ( wir042, in_001, wir025 ); nand gate043 ( wir043, wir041, wir010 ); nand gate044 ( wir044, wir038, wir000 ); nand gate045 ( wir045, wir033, wir004 ); nand gate046 ( wir046, wir039, wir045 ); nand gate047 ( wir047, in_002, wir046 ); nand gate048 ( wir048, wir011, wir037 ); nand gate049 ( wir049, wir012, in_006 ); nand gate050 ( wir050, wir048, wir007 ); nand gate051 ( wir051, wir048, wir049 ); nand gate052 ( wir052, in_006, in_004 ); nand gate053 ( wir053, wir043, wir001 ); nand gate054 ( wir054, wir042, wir053 ); nand gate055 ( wir055, wir019, wir007 ); nand gate056 ( wir056, wir016, wir039 ); nand gate057 ( wir057, in_003, wir026 ); nand gate058 ( wir058, wir029, in_007 ); nand gate059 ( wir059, in_005, wir055 ); nand gate060 ( wir060, wir035, wir054 ); nand gate061 ( wir061, wir055, wir060 ); nand gate062 ( wir062, wir032, in_003 ); nand gate063 ( wir063, wir002, wir059 ); nand gate064 ( wir064, wir062, wir025 ); nand gate065 ( wir065, wir063, wir036 ); nand gate066 ( wir066, wir060, wir065 ); nand gate067 ( wir067, wir037, wir065 ); nand gate068 ( wir068, wir029, in_006 ); nand gate069 ( wir069, wir067, wir043 ); nand gate070 ( wir070, wir061, wir069 ); nand gate071 ( wir071, wir047, wir070 ); nand gate072 ( wir072, wir071, wir071 ); nand gate073 ( wir073, wir071, wir038 ); nand gate074 ( wir074, wir010, wir073 ); nand gate075 ( wir075, wir021, wir038 ); nand gate076 ( wir076, wir028, wir066 ); nand gate077 ( wir077, wir076, wir056 ); nand gate078 ( wir078, wir077, wir077 ); nand gate079 ( wir079, wir072, wir013 ); nand gate080 ( wir080, wir079, wir026 ); nand gate081 ( wir081, wir080, wir080 ); nand gate082 ( wir082, wir078, wir025 ); nand gate083 ( wir083, wir022, wir082 ); nand gate084 ( wir084, in_001, wir083 ); nand gate085 ( wir085, wir044, wir083 ); nand gate086 ( wir086, wir085, wir081 ); nand gate087 ( wir087, wir027, wir086 ); nand gate088 ( wir088, wir087, wir007 ); nand gate089 ( wir089, wir074, wir087 ); nand gate090 ( wir090, wir051, wir075 ); nand gate091 ( wir091, wir068, wir089 ); nand gate092 ( wir092, wir091, wir091 ); nand gate093 ( wir093, wir084, wir002 ); nand gate094 ( wir094, wir051, wir091 ); nand gate095 ( wir095, wir094, wir042 ); nand gate096 ( wir096, wir021, wir094 ); nand gate097 ( wir097, wir093, wir096 ); nand gate098 ( wir098, wir096, wir044 ); nand gate099 ( wir099, wir063, wir096 ); nand gate100 ( wir100, wir088, wir026 ); nand gate101 ( wir101, wir090, wir099 ); nand gate102 ( wir102, wir101, wir101 ); nand gate103 ( wir103, wir100, wir066 ); nand gate104 ( wir104, wir057, wir102 ); nand gate105 ( wir105, wir102, wir092 ); nand gate106 ( wir106, wir102, wir059 ); nand gate107 ( wir107, wir038, wir103 ); nand gate108 ( wir108, wir072, wir102 ); nand gate109 ( wir109, wir108, wir052 ); nand gate110 ( wir110, wir052, wir021 ); nand gate111 ( wir111, wir100, wir110 ); nand gate112 ( wir112, wir110, wir106 ); nand gate113 ( wir113, wir109, wir112 ); nand gate114 ( wir114, wir104, wir038 ); nand gate115 ( wir115, in_007, wir113 ); nand gate116 ( wir116, wir060, wir115 ); nand gate117 ( wir117, wir115, wir058 ); nand gate118 ( wir118, wir117, wir038 ); nand gate119 ( wir119, wir117, wir117 ); nand gate120 ( wir120, wir116, in_006 ); nand gate121 ( wir121, wir093, wir081 ); nand gate122 ( wir122, wir119, wir120 ); nand gate123 ( wir123, wir120, wir002 ); nand gate124 ( wir124, wir119, in_007 ); nand gate125 ( wir125, wir052, wir120 ); nand gate126 ( wir126, wir120, wir020 ); nand gate127 ( wir127, wir020, wir126 ); nand gate128 ( wir128, wir126, wir124 ); nand gate129 ( wir129, wir128, wir106 ); nand gate130 ( wir130, wir100, wir104 ); nand gate131 ( wir131, in_007, wir128 ); nand gate132 ( wir132, wir061, wir128 ); nand gate133 ( wir133, wir064, wir050 ); nand gate134 ( wir134, wir068, wir093 ); nand gate135 ( wir135, wir134, wir044 ); nand gate136 ( wir136, wir127, wir121 ); nand gate137 ( wir137, wir095, wir136 ); nand gate138 ( wir138, wir105, wir137 ); nand gate139 ( wir139, wir058, wir138 ); nand gate140 ( wir140, wir138, wir118 ); nand gate141 ( wir141, wir078, wir131 ); nand gate142 ( wir142, wir140, wir140 ); nand gate143 ( wir143, wir129, wir140 ); nand gate144 ( wir144, wir129, wir109 ); nand gate145 ( wir145, wir090, in_005 ); nand gate146 ( wir146, wir145, wir145 ); nand gate147 ( wir147, wir133, wir059 ); nand gate148 ( wir148, wir093, wir147 ); nand gate149 ( wir149, wir148, wir148 ); nand gate150 ( wir150, wir131, wir131 ); nand gate151 ( wir151, wir143, wir116 ); nand gate152 ( wir152, wir021, wir132 ); nand gate153 ( wir153, wir144, wir051 ); nand gate154 ( wir154, wir122, wir149 ); nand gate155 ( wir155, wir149, wir142 ); nand gate156 ( wir156, in_001, wir149 ); nand gate157 ( wir157, wir123, wir098 ); nand gate158 ( wir158, wir058, wir133 ); nand gate159 ( wir159, in_007, wir158 ); nand gate160 ( wir160, wir133, wir157 ); nand gate161 ( wir161, wir129, wir159 ); nand gate162 ( wir162, wir059, wir100 ); nand gate163 ( wir163, wir130, wir159 ); nand gate164 ( wir164, wir152, wir146 ); nand gate165 ( wir165, wir164, wir155 ); nand gate166 ( wir166, wir121, wir164 ); nand gate167 ( wir167, wir166, wir157 ); nand gate168 ( wir168, wir167, wir058 ); nand gate169 ( wir169, wir059, wir104 ); nand gate170 ( wir170, wir139, wir169 ); nand gate171 ( wir171, wir135, wir168 ); nand gate172 ( wir172, wir171, wir156 ); nand gate173 ( wir173, wir025, in_004 ); nand gate174 ( wir174, wir172, wir143 ); nand gate175 ( wir175, wir000, wir172 ); nand gate176 ( wir176, wir154, wir172 ); nand gate177 ( wir177, wir176, wir162 ); nand gate178 ( wir178, wir111, in_005 ); nand gate179 ( wir179, in_004, wir144 ); nand gate180 ( wir180, wir162, wir178 ); nand gate181 ( wir181, wir173, wir141 ); nand gate182 ( wir182, wir180, wir131 ); nand gate183 ( wir183, wir154, wir182 ); nand gate184 ( wir184, wir090, wir183 ); nand gate185 ( wir185, wir184, wir179 ); nand gate186 ( wir186, wir107, wir058 ); nand gate187 ( wir187, wir097, wir184 ); nand gate188 ( wir188, wir016, wir177 ); nand gate189 ( wir189, wir114, wir188 ); nand gate190 ( wir190, wir189, wir143 ); nand gate191 ( wir191, wir109, wir190 ); nand gate192 ( wir192, wir185, wir190 ); nand gate193 ( wir193, wir190, in_004 ); nand gate194 ( wir194, wir193, wir135 ); nand gate195 ( wir195, wir192, wir165 ); nand gate196 ( wir196, wir194, wir161 ); nand gate197 ( wir197, wir161, wir196 ); nand gate198 ( wir198, wir196, wir185 ); nand gate199 ( wir199, wir198, wir198 ); nand gate200 ( wir200, wir155, wir181 ); nand gate201 ( wir201, wir200, wir119 ); nand gate202 ( wir202, in_006, wir090 ); nand gate203 ( wir203, in_001, wir052 ); nand gate204 ( wir204, wir185, wir202 ); nand gate205 ( wir205, wir175, wir198 ); nand gate206 ( wir206, wir205, wir150 ); nand gate207 ( wir207, wir205, wir200 ); nand gate208 ( wir208, wir207, wir168 ); nand gate209 ( wir209, wir208, wir185 ); nand gate210 ( wir210, wir144, wir199 ); nand gate211 ( wir211, wir210, wir187 ); nand gate212 ( wir212, wir210, wir135 ); nand gate213 ( wir213, wir187, wir144 ); nand gate214 ( wir214, wir151, wir210 ); nand gate215 ( wir215, wir143, wir105 ); nand gate216 ( wir216, wir021, wir215 ); nand gate217 ( wir217, wir160, wir160 ); nand gate218 ( wir218, wir186, wir061 ); nand gate219 ( wir219, wir216, wir025 ); nand gate220 ( wir220, wir219, wir122 ); nand gate221 ( wir221, wir212, wir219 ); nand gate222 ( wir222, wir209, wir105 ); nand gate223 ( wir223, wir191, wir213 ); nand gate224 ( wir224, wir168, wir221 ); nand gate225 ( wir225, wir224, wir224 ); nand gate226 ( wir226, wir144, wir209 ); nand gate227 ( wir227, wir020, wir222 ); nand gate228 ( wir228, wir129, wir226 ); nand gate229 ( wir229, wir228, wir160 ); nand gate230 ( wir230, wir229, wir229 ); nand gate231 ( wir231, wir197, wir230 ); nand gate232 ( wir232, wir230, wir214 ); nand gate233 ( wir233, wir173, wir230 ); nand gate234 ( wir234, wir056, wir174 ); nand gate235 ( wir235, wir146, wir181 ); nand gate236 ( wir236, wir235, wir225 ); nand gate237 ( wir237, wir236, wir014 ); nand gate238 ( wir238, wir236, wir174 ); nand gate239 ( wir239, wir155, wir203 ); nand gate240 ( wir240, wir209, wir236 ); nand gate241 ( wir241, wir146, wir225 ); nand gate242 ( wir242, wir191, wir241 ); nand gate243 ( wir243, wir241, wir209 ); nand gate244 ( wir244, wir206, wir111 ); nand gate245 ( wir245, wir243, wir233 ); nand gate246 ( wir246, wir223, wir234 ); nand gate247 ( wir247, wir191, wir186 ); nand gate248 ( wir248, wir056, wir238 ); nand gate249 ( wir249, wir248, wir218 ); nand gate250 ( wir250, wir243, wir249 ); nand gate251 ( wir251, wir239, wir174 ); nand gate252 ( wir252, wir251, wir231 ); nand gate253 ( wir253, wir249, wir244 ); nand gate254 ( wir254, wir240, wir150 ); nand gate255 ( wir255, wir253, wir139 ); nand gate256 ( wir256, wir242, wir253 ); nand gate257 ( wir257, wir244, wir195 ); nand gate258 ( wir258, wir204, wir201 ); nand gate259 ( out007, wir254, wir255 ); nand gate260 ( wir259, wir217, wir253 ); nand gate261 ( wir260, wir258, wir259 ); nand gate262 ( wir261, wir197, wir260 ); nand gate263 ( wir262, wir220, wir261 ); nand gate264 ( wir263, wir261, wir192 ); nand gate265 ( wir264, wir262, wir263 ); nand gate266 ( wir265, wir201, wir125 ); nand gate267 ( wir266, wir265, wir250 ); nand gate268 ( wir267, wir266, wir237 ); nand gate269 ( wir268, wir266, wir199 ); nand gate270 ( wir269, wir136, wir244 ); nand gate271 ( wir270, wir264, wir195 ); nand gate272 ( wir271, wir256, wir268 ); nand gate273 ( wir272, wir247, wir269 ); nand gate274 ( wir273, wir271, in_001 ); nand gate275 ( wir274, wir256, wir271 ); nand gate276 ( wir275, wir273, wir274 ); nand gate277 ( wir276, wir275, wir275 ); nand gate278 ( wir277, wir249, wir227 ); nand gate279 ( wir278, wir222, in_006 ); nand gate280 ( wir279, wir278, wir153 ); nand gate281 ( wir280, wir272, wir163 ); nand gate282 ( wir281, wir278, wir170 ); nand gate283 ( wir282, wir245, wir281 ); nand gate284 ( wir283, wir204, wir282 ); nand gate285 ( out005, wir283, wir254 ); nand gate286 ( wir284, wir232, wir201 ); nand gate287 ( wir285, wir284, wir197 ); nand gate288 ( wir286, wir257, wir285 ); nand gate289 ( wir287, out007, wir279 ); nand gate290 ( wir288, wir163, wir287 ); nand gate291 ( wir289, wir245, wir288 ); nand gate292 ( wir290, wir288, wir247 ); nand gate293 ( wir291, wir252, wir211 ); nand gate294 ( wir292, wir277, wir232 ); nand gate295 ( wir293, wir192, wir292 ); nand gate296 ( wir294, wir290, wir280 ); nand gate297 ( wir295, wir264, wir292 ); nand gate298 ( wir296, wir217, wir264 ); nand gate299 ( wir297, wir221, wir295 ); nand gate300 ( out003, wir294, wir295 ); nand gate301 ( wir298, wir273, wir297 ); nand gate302 ( out002, wir298, wir246 ); nand gate303 ( out006, wir240, wir289 ); nand gate304 ( wir299, wir293, wir250 ); nand gate305 ( out000, wir270, wir267 ); nand gate306 ( out001, wir276, wir291 ); nand gate307 ( wir300, wir299, wir296 ); nand gate308 ( out004, wir286, wir300 ); endmodule module test; reg [7:0] AB; // C=A*B wire [7:0] C; EBCDIC_to_ISO_latin_1 U1 ( .in_000 (AB[0]), .in_001 (AB[1]), .in_002 (AB[2]), .in_003 (AB[3]), .in_004 (AB[4]), .in_005 (AB[5]), .in_006 (AB[6]), .in_007 (AB[7]), .out000 (C[0]), .out001 (C[1]), .out002 (C[2]), .out003 (C[3]), .out004 (C[4]), .out005 (C[5]), .out006 (C[6]), .out007 (C[7]) ); initial AB=0; always #1 AB = AB+1; initial begin $display("\t\ttime,\tEBCDIC \tISO-latin-1"); $monitor("%d,\t%b %b\t%b %b\t%c",$time, AB[7:4], AB[3:0], C[7:4], C[3:0], C); end initial #255 $finish; endmodule // iverilog -o EBCDIC_309 EBCDIC_309.v // vvp EBCDIC_309 /* https://codegolf.stackexchange.com/questions/24925/ebcdic-code-golf-happy-birthday-system-360 EBCDIC037_to_Latin1 = [ 0x00,0x01,0x02,0x03,0x9c,0x09,0x86,0x7f,0x97,0x8d,0x8e,0x0b,0x0c,0x0d,0x0e,0x0f, 0x10,0x11,0x12,0x13,0x9d,0x85,0x08,0x87,0x18,0x19,0x92,0x8f,0x1c,0x1d,0x1e,0x1f, 0x80,0x81,0x82,0x83,0x84,0x0a,0x17,0x1b,0x88,0x89,0x8a,0x8b,0x8c,0x05,0x06,0x07, 0x90,0x91,0x16,0x93,0x94,0x95,0x96,0x04,0x98,0x99,0x9a,0x9b,0x14,0x15,0x9e,0x1a, 0x20,0xa0,0xe2,0xe4,0xe0,0xe1,0xe3,0xe5,0xe7,0xf1,0xa2,0x2e,0x3c,0x28,0x2b,0x7c, 0x26,0xe9,0xea,0xeb,0xe8,0xed,0xee,0xef,0xec,0xdf,0x21,0x24,0x2a,0x29,0x3b,0xac, 0x2d,0x2f,0xc2,0xc4,0xc0,0xc1,0xc3,0xc5,0xc7,0xd1,0xa6,0x2c,0x25,0x5f,0x3e,0x3f, 0xf8,0xc9,0xca,0xcb,0xc8,0xcd,0xce,0xcf,0xcc,0x60,0x3a,0x23,0x40,0x27,0x3d,0x22, 0xd8,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0xab,0xbb,0xf0,0xfd,0xfe,0xb1, 0xb0,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0xaa,0xba,0xe6,0xb8,0xc6,0xa4, 0xb5,0x7e,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0xa1,0xbf,0xd0,0xdd,0xde,0xae, 0x5e,0xa3,0xa5,0xb7,0xa9,0xa7,0xb6,0xbc,0xbd,0xbe,0x5b,0x5d,0xaf,0xa8,0xb4,0xd7, 0x7b,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0xad,0xf4,0xf6,0xf2,0xf3,0xf5, 0x7d,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0xb9,0xfb,0xfc,0xf9,0xfa,0xff, 0x5c,0xf7,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0xb2,0xd4,0xd6,0xd2,0xd3,0xd5, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0xb3,0xdb,0xdc,0xd9,0xda,0x9f]; */
{ "pile_set_name": "StackExchange" }
Q: Is it possible to develop early society without developing religion as a side effect? When intelligent beings are first evolving and starting to explore the world there are a lot of unexplained things. Scary things, strange things, wondrous things. In trying to explain those things a natural first step is religion. Why does thunder happen? Thor did it. Why do people get sick? Evil spirits are attacking them. What happens when we die? We go to a nice place. Those explanations are seized on by people to create and maintain power for themselves. Shamans, priests, religions, all building power for individuals out of those first fumbling movements towards understanding. But is there an alternative? We know of no human societies that have not created religion in their first attempts to explain the world, even if some have then moved on. What differences in the nature of humans or in human society would be needed to have those religions either not form or fade away rapidly as new explanations are discovered. A: Yes. I'm assuming you're looking for an early society that values the scientific approach. From your last sentence you say the people should let old explanations "fade away rapidly as new explanations are discovered". I see that as a not-religion approach mainly due to what I view as the primary difference between religion and science. Namely, science seeks new explanations to meet the facts, while religion seeks facts to explain its old explanations. However. What you're describing is not Religion, it's superstition. Religion is a set of superstitions that someone, or a group of people, has decided are the correct superstitions. Then people agree or submit to this invented authority and become a member of this religion. Preventing superstition is much more difficult to do. I think it actually arises from the same thing that made people discover and use science in the first place. It arises from that thing inside people that keeps them looking for patterns and connections between events. The filter that people put in front of that process makes it into either superstition or science. Preventing religion is easier to do. The change in human nature would be to value evidence over conviction of faith. Humans would need to value discussion and realize that questions are not an attack, they're a cooperative effort to determine the Truth. A stronger natural skepticism will allow humans to agree that there are some things we don't know yet, and we can have ideas about what the answers might be, but we need to be willing to let go of those ideas if they don't appear to fit new information. An early human society that values the ideas of others as much as their own will likely not develop a religion, though they may have varied superstitions from person to person. A: Religion is a hard word to define. It seems easy, until you actually try to do it. Consider the challenges faced in the US right now regarding what should be a "protected" religious belief, versus what is a "belief" from a sham religion. Dictionary.com provides a definition I like: a set of beliefs concerning the cause, nature, and purpose of the universe, especially when considered as the creation of a superhuman agency or agencies, usually involving devotional and ritual observances, and often containing a moral code governing the conduct of human affairs. Breaking this down: "A set of beliefs concerning the cause, nature, and purpose of the universe" Religions answer the tough questions about existence "especially when considered as the creation of a superhuman agency or agencies" Agency is a very particular word, implying entities which have "freewill" and can act on the universe around us "usually involving devotional and ritual observances" Doing things "because the religion says so" and "to demonstrate to others our beliefs" "and often containing a moral code governing the conduct of human affairs" Moral codes provide definition to "good" and "bad" The creation of moral codes seems to be one of the sticking points. In fact, expanding the topic even larger than morality, religion seems to be one of the single most effective tools humanity has invented and/or been given by a deity. Methods of teaching soft skills such as "kindness" are often handled through religious channels because they're good at it. However, I would like to focus on the first two points. It is human nature to wonder about the universe around them, and in fact, the more successful we are at building models of how nature works. Cultures that do not build models of the universe get overridden by those who do. Once you have a model of how the universe works, it is very difficult not to begin picking up the other traits of a religion. Consider science. Science is often considered to be the alternative to religion. It explains much of the cause, nature, and purpose of the universe (though not all!), just like a religion. However, unlike religion, science does not include any superhuman agency... at least at first glance. Listen in on the musings of two Quantum Physics professors bantering back and forth, and you start to pick up words of agency used to describe quantum scale particles (these words are a side effect of our inability to see nor change some quantum values in tandem). Likewise, you will hear science weigh in on "when life begins," which is heavily entwined with human agency, and it is very difficult to go too far down that road before you wonder about superhuman agencies, such as those of mob mentalities and nations. These issues rapidly produce a moral code of their own! The last step towards science meeting that definition would be the presence of devotional rituals. Consider the repetative practice at the scientific method in school or the act of blind faith of landing in a foreign city with nothing but a GPS and the internet (or perhaps even the blind faith of getting on an airplane in the first place). These may not qualify as rituals in your own lexicon, but you have to admit that they are on a slippery slope. And if society's alternative to religion looks this much like a religion, that suggests that it would be remarkably difficult to handle the development of an early society without accidentally treading on it. In fact, I think it would be tricky to accomplish, even if you started the society with the expressed intent of sidestepping this particular definition of religion. Things just happen, especially when they are beneficial.
{ "pile_set_name": "StackExchange" }
Q: Test cases to run in sequence instead of parallel I googled for this issue but could not find the answer. My test runs appear to run in parallel and cause each other to fail. They do all pass when run individually. I tried to add thread in the test and put them to sleep but no luck. Is there a way to run these tests in sequence one after another? My environment: Visual Studio 2010 Resharper Jet brains 6.1 A: I would suggest you have unit tests that are deterministic. That is they don't depend on the order they are run or that other tests be run before or after. Not doing this is a recipe for failure. Most test runners are based on the fact that test methods are completely independent. This fact is inherently obvious in the way the methods of a test class are invoked. e.g. with MS Test you can have Assembly, Class and Test initialize methods. All of these are invoked for each TestMethod being invoked. For example, with the following class: [TestClass()] public class DivideClassTest { [AssemblyInitialize()] public static void AssemblyInit(TestContext context) { Console.WriteLine("Assembly Init"); } [ClassInitialize()] public static void ClassInit(TestContext context) { Console.WriteLine("ClassInit"); } [TestInitialize()] public void Initialize() { Console.WriteLine("TestMethodInit"); } [TestCleanup()] public void Cleanup() { Console.WriteLine("TestMethodCleanup"); } [ClassCleanup()] public static void ClassCleanup() { Console.WriteLine("ClassCleanup"); } [AssemblyCleanup()] public static void AssemblyCleanup() { Console.WriteLine("AssemblyCleanup"); } [TestMethod()] public void Test1() { Console.WriteLine("Test1"); } [TestMethod()] public void Test2() { Console.WriteLine("Test2"); } } You'll see output like Assembly Init ClassInit TestMethodInit Test1 TestMethodCleanup TestMethodInit Test2 TestMethodCleanup ClassCleanup AssemblyCleanup Although there is a "Test" class, the TestMethod itself is considered the test. A "test" class can effectively have many tests.
{ "pile_set_name": "StackExchange" }
Q: Accessing legacy BIOS following Windows 10 install So I have just recently installed Windows 10 and I'm needing to get into my BIOS (legacy, not UEFI BIOS). I have turned off Fast Startup and Hybernation and I have tried the Advanced Startup. The only problem with Advanced Startup is that it only gives the option for UEFI access, not BIOS. I've also tried removing the hard drive with the OS to just boot to it; that didn't work. I also tried putting in the install disk (USB) to see if I could get to it. That didn't work either. Thanks for any help. Specs: Windows 10 Enterprise (10240) 64Bit Processor: Intel Core i7-3770 RAM: 12GB Motherboard: Pegatron Corp. 2AD5 (v.1.03) A: Okay Gents...this is the whole story and solution. Like I've stated in my comment to the original post, I have an HP ENVY h8-1520t. Problem: I wanted two things that could only be changed in BIOS. The first was to enable Virtualization for laravel production with vagrant. The second was to have BIOS turn on my machine on Monday morning so that it was ready to go when I got into work. The first step had my priority while the second is more of a convenience thing. Before I installed Windows 10, I was on Windows 8.1 and I could very easily access BIOS by pressing F9 or ESC to access the startup menu. However, as soon as I performed a clean install of Windows 10, I could no longer access BIOS. The POST screen would flash so quickly that it is nearly impossible for a human to press the F-key at the right moment. I tried turning off Hibernation and Fast Boot in hopes that I could have enough time to access BIOS. It did not work. Also since I have legacy BIOS and not UEFI, I was not able to access BIOS with the restore settings found here. Solution: Last night before I went home from work I tried installing HP's Driver installer found here. The installation process went smooth and there were no errors. As soon as I restarted my computer, My computer just kept beeping at me and wouldn't power on. So in my frustration I left for the day. When I came in this morning I counted the beeps and there were 6, HP told me that the issue is with the 3rd party graphics card. So I removed the card I received no beeps, and alas, I was able to access my BIOS. However, I was no longer able to boot to any disk. BIOS could see my drives but it wouldn't give me the option to boot to disk, only network. Come to find out, HP in their infinite wisdom, decide to only trust certain hardware, including hard drives. Since my hard drive and graphics cards are after market, it didn't like them. So I had to disable secure boot. After I disabled secure boot, and enabled a 5 second POST screen delay, as well as enabling Virtualization everything was back to normal. I could plug in my video card and BAM...everything worked well. I hope this helps those in need. I was pulling my hair out and didn't get much sleep last night thinking that I had killed my motherboard by flashing the BIOS. Thanks Moab and Jamal for you answers.
{ "pile_set_name": "StackExchange" }
Q: Proof: $A\subseteq (B\cup C)$ and $B\subseteq (A\cup C)$ then $(A - B) \subseteq C$ How do I prove this: Let $A, B$ and $C$ be sets, $A \subseteq (B \cup C)$ and $B \subseteq (A \cup C)$ then $(A - B) \subseteq C$ How about this: Let $x \in A$ and $y \in B.$ Since $A \subseteq (B \cup C)$ then $x \in (B \cup C).$ Since $B \subseteq (A \cup C)$ then $y \in (A \cup C)$ $x \in B \cup C$, so if $x \in B$, then $x \notin A - B.$ if $x \notin B$, then $x \in C.$ $y \in A \cup C$, so if $y \in A$, then $y \notin A - B.$ if $y \notin B$, then $y \in C.$ So in both cases, $A - B \subseteq C$ Is it correct? if yes, the converse is false right? A: The question only asks you to prove that $A-B$ is a subset of $C$. This means that we need to take $x\in A-B$ and show that $x\in C$. Let $x$ be such element, then $x\in A$ and therefore $x\in B\cup C$. However, $x\notin B$ and therefore $x\in C$. In the other direction, it is true that if $A-B\subseteq C$ then $A\subseteq B\cup C$. See if you can prove it. (Hint: $x\in A$ then either $x\in B$ or $x\notin B$.)
{ "pile_set_name": "StackExchange" }
Q: Change address where Prometheus node exporter listens in systemd drop-in unit I have a this drop-in unit: # /etc/systemd/system/prometheus-node-exporter.service.d/override.conf [Service] Environment=ARGS=--web.listen-address=localhost:9101 It is relative to this unit from Debian package prometheus-node-exporter (stretch-backports version): # /lib/systemd/system/prometheus-node-exporter.service [Unit] Description=Prometheus exporter for machine metrics Documentation=https://github.com/prometheus/node_exporter [Service] Restart=always User=prometheus EnvironmentFile=/etc/default/prometheus-node-exporter ExecStart=/usr/bin/prometheus-node-exporter $ARGS ExecReload=/bin/kill -HUP $MAINPID TimeoutStopSec=20s SendSIGKILL=no [Install] WantedBy=multi-user.target /etc/default/prometheus-node-exporter sets ARGS="", i.e. the node exporter's default port 9100 applies. The drop-in is meant to change this to 9101 and let the service listen only on localhost. After systemctl start prometheus-node-exporter the service listens on :::9100 (tcp6). However, if I comment-out EnvironmentFile in the unit file it listens on 127.0.0.1:9101 (tcp), as I want it to. So it seems as if EnvironmentFile from the unit keeps precedence over Environment in the drop-in unit. Why does the drop-in not override the unit in choosing the value of ARGS? What am I missing and can I change the default listening address with a custom drop-in unit? A: From man systemd.exec: EnvironmentFile= ... Settings from these files override settings made with Environment=. If the same variable is set twice from these files, the files will be read in the order they are specified and the later setting will override the earlier setting. So you need to specify an EnvironmentFile to override the setting in the unit file: # /etc/systemd/system/prometheus-node-exporter.service.d/override.conf [Service] EnvironmentFile=/etc/prometheus.conf and actual config: # cat /etc/prometheus.conf ARGS=--web.listen-address=localhost:9101
{ "pile_set_name": "StackExchange" }
Q: "does not take parameters" when chaining method calls without periods I have a class: class Greeter { def hi = { print ("hi"); this } def hello = { print ("hello"); this } def and = this } I would like to call the new Greeter().hi.and.hello as new Greeter() hi and hello but this results in: error: Greeter does not take parameters g hi and hello ^ (note: the caret is under "hi") I believe this means that Scala is takes the hi as this and tries to pass the and. But and is not an object. What can I pass to apply to chain the call to the and method? A: You can't chain parameterless method calls like that. The general syntax that works without dots and parentheses is (informally): object method parameter method parameter method parameter ... When you write new Greeter() hi and hello, and is interpreted as a parameter to the method hi. Using postfix syntax you could do: ((new Greeter hi) and) hello But that's not really recommended except for specialized DSLs where you absolutely want that syntax. Here's something you could play around with to get sort of what you want: object and class Greeter { def hi(a: and.type) = { print("hi"); this } def hello = { print("hello"); this } } new Greeter hi and hello
{ "pile_set_name": "StackExchange" }
Q: Can't add multiple Foreign Keys to a table - EF - Code First I decided to play around with the code first option with the EF, however, i've run into a problem regarding multiple foreign keys in a single table. The error I get is: The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = FK_dbo.Comments_dbo.Users_UserId ] I have three tables, User, Post and Comments. Using my limited knowledge in this field, I have created three classes. User public class User { [Key] public int UserId { get; set; } public string Username { get; set; } public string Email { get; set; } public string FName { get; set; } public string LName { get; set; } public DateTime JoinDate { get; set; } public string Password { get; set; } public virtual ICollection<Post> Posts { get; set; } public virtual ICollection<Comment> Comments { get; set; } public User() { Posts = new List<Post>(); } } Post public class Post { [Key] public int PostId { get; set; } public string Title { get; set; } public string Body { get; set; } public DateTime PublishDate { get; set; } public int UserId { get; set; } public virtual ICollection<Comment> Comments { get; set; } public Post() { Comments = new List<Comment>(); } } Comment public class Comment { [Key] public int CommentId { get; set; } public string Title { get; set; } public string Body { get; set; } public DateTime CommentDate { get; set; } public int UserId { get; set; } public int PostId { get; set; } } The relationship between the UserId in the 'User' table, and the UserId in the 'Post' table is fine. However, I run into problems when I wish to create a relationship from the 'Comment' table to the 'Post' and 'User' tables. I'm not sure what i'm doing wrong, as each table is connected to their respective Id. Any help would be appreciated. A: You will probably have to disable cascading delete on one or two of the relationships, for example for the relationships of User.Posts and User.Comments. You must do it with Fluent API in an overridden OnModelCreating of your derived DbContext: modelBuilder.Entity<User>() .HasMany(u => u.Posts) .WithRequired() .HasForeignKey(p => p.UserId) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(u => u.Comments) .WithRequired() .HasForeignKey(c => c.UserId) .WillCascadeOnDelete(false); Alternatively you could make the relationships to User optional instead of required. It would be as simple as making the UserId foreign key properties in Post and Comment nullable: public int? UserId { get; set; } It might even make sense from a business perspective to allow keeping posts and comments in the system as anonymous even after the user has been deleted, represented by a null value of UserId in Post and Comment.
{ "pile_set_name": "StackExchange" }
Q: Broken C pointer in Objective-C Header I have a CGFloat pointer in my header that is used to point at a CGFloat array. I declare it like that: CGFloat* pointer;. In the initialization I try to set the pointer using this code: CGFloat newArray[2] = { 0.0f, 1.0f, }; pointer = newArray; This "actually" works. I don't get any compiler errors and stuff. When i print the second value of the array right after setting the pointer with this code: printf("%f", pointer[1]); I get the right result (1.000000). However, when I print the second value of the array in the method called next i get 0.000000 which means that the pointer doesn't point at the array anymore. I've got two questions. How do I fix this problem and why does the pointer work right after setting it but "forgets" its value again? A: CGFloat newArray[2] = { 0.0f, 1.0f, }; Array indices start at 0. pointer[1] prints the second element in the array, not the first. pointer[2] is off the end of the array. CGFloat newArray[2] = {0,0}; newArray[0]; // this is the 1st item newArray[1]; // this is the 2nd item newArray[2]; // this is nonsense. Note that if you try to pass newArray somewhere with the intention of using it later, it'll be badness. newArray is on the stack and will be destroyed when the scope is destroyed. If you want a function that returns an array of two floats, you'd do: CGFloat *two_of_these() { CGFloat *newArray = malloc(2 * sizeof(CGFLoat)); newArray[0] = 42.0; newArray[1] = 59.4; return newArray; } Just make sure and call free on that return value later. Note that it is exceedingly rare to allocate something so small. Typically, it'll be a structure that is returned directly. See CGPoint, CGRect, NSRange, etc....
{ "pile_set_name": "StackExchange" }
Q: CakePHP Auth Component Not logging in when using $this->Auth->login(); I'm new to cakePHP and I have read their documentation and I'm following their simple authentication example. I've also searched far and wide (including answers on this site) for an answer to my problem. I'm using cakePHP 2.0 and my UsersController's login function looks like this: function login() { if ($this->request->is('post')) { if ($this->Auth->login(/*$this->request->data*/)) { $this->redirect($this->Auth->redirect()); }else { $this->Session->setFlash(__('Invalid username or password, try again')); } } } My AppController looks like this: public $components = array( 'Session', 'Auth' => array( 'loginRedirect' => array('controller' => 'pages', 'action' => 'display'), 'logoutRedirect' => array('controller' => 'pages', 'action' => 'display') ) ); public function beforeFilter() { $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login'); } My User Model: class User extends AppModel { public $name = "User"; } And the login form: echo $this->Session->flash('auth'); echo $this->Form->create('User', array('action' => 'login')); echo $this->Form->input('username'); echo $this->Form->input('password'); echo $this->Form->end('Login'); The problem is it doesn't log a user in. When $this->Auth->login() is called without $this->request->data as a parameter nothing is written in the session and the page just refreshes.However when you supply the $this->request->data it works, credentials are written to the session and I'm redirected correctly. However I've noticed that you can 'log in' anyone with $this->Auth->login($this->request->data) even if they are not present in the database. In addition to this, if I enter wrong credentials nothing happens, no flash messages are displayed. I'm not trying to do anything special, all I want is the ability to log a user in. I have a simple users table with username and password fields and I have followed their example and read their documentation, but still nothing I have tried has worked. I apologise if I have not supplied all the information needed to provide a response. Any help is greatly appreciated. A: I had the exact same experience. What happened to me was, at one point, I was able to log in successfully using some username and password, but I never had any code in the view that showed me I was logged in. I was also really confused that when I subsequently logged in with random usernames and passwords, it still gave me a successful login notification. I think what happened was, if you are in a logged-in state, then $this->Auth->login() will return true no matter what username and password you enter. The solution would probably be to somehow call $this->Auth->logout() in your program, or empty your cookies so that the program doesn't specify you as being logged in anymore. Then $this->Auth->login() will work as normal again.
{ "pile_set_name": "StackExchange" }
Q: Simplifying an Expression further I have trouble doing this and I'm not sure why are they the same and what are the steps I need to do to reach the simplified answer. For example ... $\frac{-8}{\sqrt{128}}$ This is the same as $\frac{-1}{\sqrt{2}} $ I'm not sure how to reach the simplified expression from the earlier expression .. Can anyone help me ? Thanks ! A: $\frac{-8}{\sqrt {128}} = $$\frac{-8}{\sqrt 2 \sqrt {64}} = \frac{(-1)(8)}{\sqrt2(8)} = \frac{-1}{\sqrt2}$ A: Here are the steps: $$\frac {-8}{\sqrt{128}}=$$Simplify the bottom fraction $$ \frac {-8}{8\sqrt{2}}$$ cancel out the 8's $$ \frac {-1}{\sqrt{2}}$$ A: $\frac{-8}{\sqrt{128}}=-(\frac{8}{\sqrt{128}})=-(\sqrt{\frac{8^2}{(\sqrt{128})^2}})=-(\sqrt{\frac{64}{128}})=-(\sqrt{\frac{1}{2}})=-(\frac{1}{\sqrt{2}})=\frac{-1}{\sqrt{2}}$ In general, put the minus symbol outside, then try to simplify the content of the square root of the perfect square of numerator and denominator (the will be $a^2$ and $b$): $$\frac{-a}{\sqrt{b}}=-(\frac{a}{\sqrt{b}})=-(\sqrt{(\frac{a}{\sqrt{b}})^2})=-(\sqrt{\frac{a^2}{(\sqrt{b})^2}})=-(\sqrt{\frac{a^2}{b}})$$
{ "pile_set_name": "StackExchange" }
Q: how to get the notification when UITableview 's section scroll to top? I have a UITableView that contains many sections and each section has only one cell. I want to get the notification when a section scroll to top (a section will disappear) and do something. How to get the notification ? A: You should try something like the following in your delegate method: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CGRect rect = [tableView rectForRowAtIndexPath:indexPath]; float ypos = rect.origin.y; if(y==<your identifier for top>) { NSLog(@"I am on top"); } // rest of your code... } If I understood correctly this should be what you need.
{ "pile_set_name": "StackExchange" }
Q: How to let react only render part of the component? I am writing a react app with css grids. I'm not going to include the css here but it is a 2x2 grid. import { useState } from 'react'; function Container() { const [count, setCount] = useState(0); return ( <div className = "gridwrapper"> <div className = "top_left"> <SomeCustomComponent></div> <div className = "bottom_left"> <CustomCounter counter = {count}></div> <div className = "bottom_right"> <CustomCounter counter = {count+2}></div> <div className = "top_right"><button onClick={() => setCount(count + 1)}>Click me</button><div> </div> ); } function CustomCounter({count}){ return(<p>The count is {count}</p>) } I have two issues right now Since setState would cause re-render, now it would re-render the whole thing. But I only need the bottom two cells to re-render since other parts of my Container component do not even depend on props. In order for my grid structure to work properly, I need to wrap them in divs, why is that? I tried to assign classnames directly before but it didn't work A: Regarding unnecessary re-renders - don't worry about it. The React diffing engine is smart enough to know which elements have actually changed and which ones haven't, and it will only update what is necessary.
{ "pile_set_name": "StackExchange" }
Q: Can't render line breaks in Rails with simple_format I'm aware that in order to render \r\n I need to use simple_format, however it doesn't work on my posts that I migrated from WordPress. I tried many solutions including regex to replace \r\n with break tags, but it didn't help either. I still see on the screen all the line breaks printed out as text and not rendered. Here is what I tried: <%= simple_format(@post.body) %> <%= simple_format(@post.body.gsub(/(?:\n\r?|\r\n?)/, '<br>')) %> If I just do something like below it will work. <%= simple_format "<h1>Briefed while smartwatch firm Pebble lays off 25% of its staff</h1> -\r\n\r\n \r\n <p>hello</p>" %> I have no idea what am I doing wrong. A: I finally solved it using an SQL query: UPDATE posts SET body = REPLACE(body, '\r\n', '<br>'); Don't know why Rails gsub didn't work. Edit: Looks like my regex was wrong. This solves it too: <%= simple_format(@post.body.gsub(/\\r\\n/, "\n")) %>
{ "pile_set_name": "StackExchange" }
Q: Are there UN norms for a government change? In another question a comment mentioned that the change in government in the Ukraine conformed to UN norms. Do such UN norms for government changes (e.g. impeachment of the president) exist? If so, what are they? A: There are not any specific norm or norms for “change of government” which may mean whether a change of government can be assumed internationally legal or illegal. This is a political subject-matter, and therefore, there are certain related issues that can be raised here. These issues will clarify the answer and therefore it is necessary to pay attention to them: Change of Government and recognition of a new State or Government (a government has changed and a new government is in power) - The recognition of a new State or Government is an act that only other states and governments may grant or withhold. It generally implies readiness to assume diplomatic relations. The United Nations is neither a State nor a Government, and therefore does not possess any authority to recognize either a State or a Government. As an organization of independent States, it may admit a new State to its membership or accept the credentials of the representatives of a new Government. This is very important, since these are the member states that have to recognize the changed government. If so, then the acceptance of the credentials may seem to happen easier. If not, there might be problems. This is a political process. Let’s imagine that a president is changed illegally (through coup d’état for instance). Even if initially successful in seizing the main centres of state power, the coup may be actively opposed by certain segments of society or by the international community. Opposition can take many different forms, including an attempted counter-coup by sections of the armed forces, international isolation of the new regime, and military intervention. The UN monitoring bodies will look into the whole process (coup, counter-coup, oppositions and political or military action and reactions), and by the time there is no threat to the international peace and security, there might be no political motion. Also, if the rights of the people are extensively violated then reactions may start. However, political relationships matter. It is important to consider the fact that how those in power (new-comers or the previous regime) connect politically with the UN member states and how they gain the political support. Meanwhile, Threat to peace and security and massive human rights violations are much worth in the context of the United Nations. United Nations bodies have produced (through cooperation of its members) a series of human rights principles. Most of these principles are about the governments’ behaviours. The governments have to observe these principles by the time they formally approve the principles. For instance, the Convention of the Rights of the Child (CRC) contains the rights that children should have in a country. When one state join the convention, then the state has to observe these regulations. Now, suppose that there is a government that has been criticized by the International community for its behaviours towards children because the government is a member to CRC. When the government changes, if it shows that it would like to observe the principles regarding the children, it may be said that the government is acting based on UN norms. However, these norms are not about every issues; for instance, there is not any convention on the behaviour of a president or about the impeachment of a president (of course impeachment has been used in the question in its informal meaning). Change of Government and membership in UN (the previous government has not been a member and the new government expresses its intention to be a member of the United Nations). Membership in the Organization, in accordance with the Charter of the United Nations, “is open to all peace-loving States which accept the obligations contained in the [United Nations Charter] and, in the judgment of the Organization, are able to carry out these obligations”. States are admitted to membership in the United Nations by decision of the General Assembly upon the recommendation of the Security Council. The previous government has resorted an act that has been determined by the Security Council as a threat to the peace, breach of the peace, or act of aggression (Article 39 of the UN Charter) and the Security Council decides to take actions – but the new government has changed its behaviour and therefore, the Security Council may remove the actions (such as bans or …). In certain cases, the Security Council even is involved in changing a government. What happened in Libya, can be a good case to raise here. The Security Council in that time felt an imminent threat of mass atrocities and the international community and regional and sub-regional bodies acted to protect the populations through a range of economic, political, and military measures. In fact, UN bodies quickly became seized of the crisis and condemned the attacks against civilians by Gaddafi’s forces. I am not going to write the whole story here, but it is important to mention that United Nations played a major role in changing the regime in Libya. If we try to summary the whole answer, then we may say that the norms are not there, but two important aspects have to be considered: Threat to peace and security and massive human rights violations; meanwhile, if there are not such cases, and the change has gone through the due process of law and the new government has been able to gain the most support of the member states, then the new government is recognized. In this case, one may say that the government has changed (or has been changed) based on UN norms.
{ "pile_set_name": "StackExchange" }
Q: MasterPage error in different directory I have asp.net project which have a masterpage file, when using this in any newpage in same directory its working, but if I make a different directory page then the style is not working good! A: You've probably got a relative reference to your CSS files that works from the master page folder, but not from other folders. That reference will always be resolved relative to the content page and not the master page. For example, if your CSS is linked thus: <link href="css/Style.css" type="text/css"/> This will only work from content pages (note that the master page location is irrelevant in the resolution of a relative URL) in the parent folder. You should replace references like that with an absolute reference, e.g. <link href="/css/Style.css" type="text/css"/>
{ "pile_set_name": "StackExchange" }
Q: Accesing a class with properties from another class returns null values I am making an application that reads values from a meter that is connected to my computer via a serial cable. When i press a button i send a command to the meter and after a few miliseconds i get a response back from the meter with the answer. I am saving these values to a class that has properties init, so that i can access these values from anywhere. So my problem is that when i try to get the values back it returns a 'nothing value', and its probably from the initialization i have that has a 'New' like this'Dim clsSavedValues As New clsSavedValues', so when i try to get the values from that property class i create a new instanse and that instanse is empty if am not mistaken. Ill post the code below but here is how the code flows: I have 3 classes. MainClass, ProtocolClass, PropertiesClass. From main i call a method inside ProtocolClass, and that method sends a command to the meter. after a few miliseconds i get a call back inside ProtocolClass anf this method is called 'Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived' and it saves that return value to the PropertiesClass. And after the DataReceived method is finished i go back to the MainClass and call another method to get the values from the PropertiesClass that i just saved but they return null. I know they are saved correctly because i can access them if i call them from within the ProtocolClass. But they are null from MainClass. Here is my code: MainClass 'Here i call the ProtocolClass Private Sub btnGetLastTransaction_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetLastTransaction.Click clsProtocol.GetLastTransaction(1, Integer.Parse(tbxTransactionPosition.Text)) End Sub 'Here i try to read the valies from PropertiesClass Public Sub RetrieveMeterSerialNumber() Dim clsSavedValues As New clsSavedValues lblMeterSerialNumber.Text = clsSavedValues.SaveMeterSerialNumber End Sub ProtocolClass Public Sub GetLastTransaction(ByVal destinationAddress As String, ByVal transactionNum As Integer) clsSavedValues = New clsSavedValues 'Creating Instance of the properties class Try Dim v_bodyOfMessage As [Byte]() = {ASCIItoHEX("G"), _ ASCIItoHEX("r")} Dim v_bytearray As [Byte]() = ConstructCommand(v_bodyOfMessage) SendCommand(v_bytearray) Catch ex As Exception Console.WriteLine("Meter serial number button click exception: {0}", ex) End Try End Sub Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived If comOpen Then Try ReDim rx(rxPacketSize) Console.WriteLine("RESPONSE") For i = 0 To rxPacketSize - 1 readByte = SerialPort.ReadByte.ToString Console.WriteLine(i.ToString & ": " & Conversion.Int(readByte).ToString) rx(i) = Conversion.Int(readByte).ToString If i <> 0 Then If Convert.ToByte(rx(i)) = vDelimeterFlag(0) Then Exit For End If Next DecodeResponse() Catch ex As Exception MsgBox("SerialPort_DataReceived Exception: " & ex.Message) End Try End If End Sub Private Sub GetMeterSerialNumber() Dim i_startPosition As Integer = 5 Dim meterSerialNumber As String = GetRemainingPortionOfString(i_startPosition) clsSavedValues.SaveMeterSerialNumber = meterSerialNumber frmExplorer.RetrieveMeterSerialNumber() 'This is the call to the main class End Sub PropertiesClass Public Property SaveMeterSerialNumber() As String Get Return _MeterSerialNumber End Get Set(ByVal meterSerialNumber As String) _MeterSerialNumber = meterSerialNumber End Set End Property I want to get the values from the PropertiesClass because ill get more than wan response from the meter and that causes thread issues and i cannot keep track with them. So i save the values in one class and then i want to access them all from that class. Sorry for the long post, ask me anything you want for clarification A: clsSavedValues in SerialPort_DataReceived() and in your Main Class RetrieveMeterSerialNumber() are two different objects (with same variable names but each 'new' create a new instance of clsSavedValues ) maybe you should pass the clsSavedValues var from protocol to Main as parameter. Main : Public Sub RetrieveMeterSerialNumber(clsSavedValues As clsSavedValues ) lblMeterSerialNumber.Text = clsSavedValues.SaveMeterSerialNumber End Sub Protocol : Private Sub GetMeterSerialNumber() Dim i_startPosition As Integer = 5 Dim meterSerialNumber As String = GetRemainingPortionOfString(i_startPosition) clsSavedValues.SaveMeterSerialNumber = meterSerialNumber frmExplorer.RetrieveMeterSerialNumber(clsSavedValues) 'This is the call to the main class End Sub or use a static property in your PropertiesClass
{ "pile_set_name": "StackExchange" }
Q: SQL order by string order In my table i have two file one is id another is strNum. I want to order the strNum like as One Two Three My table data id strNum ------ ------------ 1 Two 2 One 3 Five 4 Nine I want to get output without any extra field add. How can i will order like as One Two Three Four Five A: You can use this query : SELECT strNum FROM your_table ORDER BY FIELD(strNum,'One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten') ASC
{ "pile_set_name": "StackExchange" }
Q: Hi I am trying to set error messages for my android app but it keeps crashing and im not sure why Hi I have a problem with my error message. I am trying to set when my add button is clicked a message will appear if the user has left one of my edit texts empty. The problem is how can i do this as well as add my contacts at the same time? This is the part that is giving me difficulty: while (!name.matches("") && !phone.matches("") && !email.matches("") && !address.matches("") ){ Boolean added = handler.addContactDetails(contact); if(added){ Intent intent = new Intent(NewContact.this, Main.class); startActivity(intent); }else{ Toast.makeText(getApplicationContext(), "Contact data not added. Please try again", Toast.LENGTH_LONG).show(); And this is the class in its entirety: import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class NewContact extends Activity { private static int RESULT_LOAD_IMAGE = 1; private ContactHandler handler; private String picturePath = ""; private String name; private String phone; private String email; private String address; private String photograph; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_contact); handler = new ContactHandler(getApplicationContext()); ImageView iv_user_photo = (ImageView) findViewById(R.id.iv_user_photo); iv_user_photo.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, RESULT_LOAD_IMAGE); } }); Button btn_add = (Button) findViewById(R.id.btn_add); btn_add.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { EditText et_name = (EditText) findViewById(R.id.et_name); phone = et_name.getText().toString(); // if ( ( !et_name.getText().toString().equals(""))) //{ //return; } //else if (( et_name.getText().toString().equals(""))) // Toast.makeText(getApplicationContext(), // "Password field empty", Toast.LENGTH_SHORT).show(); { //else //return; EditText et_phone = (EditText) findViewById(R.id.et_phone); phone = et_phone.getText().toString(); { EditText et_email = (EditText) findViewById(R.id.et_email); email = et_email.getText().toString(); { EditText et_address = (EditText) findViewById(R.id.et_address); address = et_address.getText().toString(); { ImageView iv_photograph = (ImageView) findViewById(R.id.iv_user_photo); photograph = picturePath; Contact contact = new Contact(); contact.setName(name); contact.setPhoneNumber(phone); contact.setEmail(email); contact.setPostalAddress(address); contact.setPhotograph(photograph); while (!name.matches("") && !phone.matches("") && !email.matches("") && !address.matches("") ){ Boolean added = handler.addContactDetails(contact); if(added){ Intent intent = new Intent(NewContact.this, Main.class); startActivity(intent); }else{ Toast.makeText(getApplicationContext(), "Contact data not added. Please try again", Toast.LENGTH_LONG).show(); } } } }}}}}); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri imageUri = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); picturePath = cursor.getString(columnIndex); cursor.close(); ImageView imageView = (ImageView) findViewById(R.id.iv_user_photo); imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); } } } A: I don't really understand why you are using a while statement it should be if statement, you can use the isEmpty method to check strings whether they are empty and carry out actions otherwise...try this if(name.isEmpty() || phone.isEmpty() || email.isEmpty() || address.isEmpty()){ String error = "Contact data not added please try again"; Toast.makeText(NewContact.this, error, Toast.LENGTH_SHORT).show(); } else { Boolean added = handler.addContactDetails(contact); if(added){ Intent intent = new Intent(NewContact.this, Main.class); startActivity(intent); }
{ "pile_set_name": "StackExchange" }
Q: Play full music to Unlogged Users using Deezer API I have a website and it includes the option for users to search and listen to music using the Deezer API. It works fine, however, when the user is not logged in, the songs have a limit of 30 seconds. I've found this section in Deezer documentation that explains the music access to unlogged users: 30s clips listening restrictions. But, I would like to make the full songs available to all users of my website to listen to, so is there any paid way or partnership with Deezer to get this? A: The only way for your users to stream full tracks on Deezer is that they are users from our service and logged in.
{ "pile_set_name": "StackExchange" }
Q: Fastest way showing the limit exists without finding the limit? Let $\{a_n\}$ and $\{b_n\}$ be two integer sequences such that $a_1=b_1=1,$ \begin{align*} a_n=a_{n-1}+b_{n-1},\qquad\qquad b_n =r\,a_{n-1}+b_{n-1}. \end{align*} Where $r$ is a natural number $>1$. ($r$ is a fixed value) Write $c_n={b_n}/{a_n}$, how to prove the following limit exist without finding it? \begin{align*} \lim_{n\to\infty} c_n. \end{align*} Attempt I used mathematical induction to prove $\{c_{2n}\}$ is monotonically decreasing and $\{c_{2n+1}\}$ is monotonically increasing. Then, note that \begin{align*} c_{n+1}=\frac{b_{n+1}}{a_{n+1}}&=\frac{r\,a_n+b_n}{a_n+b_n}\\ &=r-\frac{r-1}{\frac 1{b_n/a_n}+1}<r \end{align*} Therefore, $0<c_n<r$. $\vdots$ Instead of continuing using this method (too complicated), any other faster ways to prove "exist"? I tried to use the definition of Cauchy sequence and contraction mapping (they are 2 methods), but I don't think they work here. Any hints or tips are appreciated:) A: Write your formulas in a matrix form: $$\begin{bmatrix}a_n\\b_n\end{bmatrix} = \begin{bmatrix}1&1\\r&1\end{bmatrix}\begin{bmatrix}a_{n-1}\\b_{n-1}\end{bmatrix}$$ i.e. $$w_n=Aw_{n-1}$$ Notice that if you normalize every vector after applying $A$, that is if you consider $$v_n=\frac{Av_{n-1}}{||Av_{n-1}||}$$ instead $w_n$, then it will generate the same $\{c_n\}$. This is because normalization changes magnitude of the given vector, not its direction $A$ is a linear transformation; changing the magnitude of its input doesn't change the direction of its output and finally $c_n$ depends on the n-th direction only. This formula for $v_n$ above is exactly what power iteration does. The following citation is useful (it has been translated to match our chosen names and starting index): If $A$ has an eigenvalue that is strictly greater in magnitude than its other eigenvalues and the starting vector $v_{1}$ has a nonzero component in the direction of an eigenvector associated with the dominant eigenvalue, then a subsequence $\{v_n\}$ converges to an eigenvector associated with the dominant eigenvalue. Think about eigenvalues (say: $\lambda$) and how they depend on $r$. You will have to consider a quadratic equation w.r.t. $\lambda$ and its discriminant, which will be of first degree w.r.t. $r$. By analyzing the two you will find that for $r>1$ there are always two distinct real eigenvalues (and none of them is $0$, this will be important in a moment). Apply proper Vieta's formula to show they cannot sum to $0$. They cannot be equal, they cannot be opposite, so one eigenvalue is strictly greater in magnitude for sure. If the starting non-zero vector had zero component in the direction of one of the two eigenvectors, then it would be the other eigenvector. Applying $A$ to it would act as multiplying by eigenvalue (which is nonzero). This means $w_1, w_2, w_3, …$ would have the same direction, so $c_1, c_2, c_3, …$ would be equal and $\{c_n\}$ would trivially converge. In our case however $c_1=1$ and $c_2\neq1$. This means $v_1$ has non-zero component in the direction of any of the two eigenvectors; in particular in the direction associated with the dominant eigenvalue. So the conditions are met, $\{v_n\}$ converges to some eigenvector. It has some direction which corresponds to the limit of $\{c_n\}$. Q: But wait! If $\begin{bmatrix}0\\1\end{bmatrix}$ was this eigenvector associated with the dominant eigenvalue, wouldn't the limit be $\infty$ or $-\infty$? A: I think it would, it doesn't matter though. Calculate $A\begin{bmatrix}0\\1\end{bmatrix}$ and you will see it's not an eigenvector. A: Not sure if the following fits the requirement to avoid finding the limit, but anyway... Consider the change of variable $$x_n=c_n-\frac{r}{c_n}$$ then $$x_{n+1}=-f(c_n)x_n$$ with $$f(c)=\frac{(r-1)c}{(c+1)(c+r)}$$ Now, for every $c>0$, $$(c+1)(c+r)\geqslant(r+1)c$$ hence $$f(c)\leqslant s$$ with $$s=\frac{r-1}{r+1}<1$$ Thus, $$|x_n|\leqslant s^{n-1}\cdot|x_1|$$ which implies that $$x_n\to0$$ hence $$c_n\to\text{____}$$ A: Again, not sure if this satisfies your criteria, but if we let $f : [0,\infty) \to \mathbb{R}$ by $$ f(z) = \frac{r+z}{1+z} $$ then $f$ is decreasing, $0\leq f \leq r$, and $c_{n+1} = f(c_n)$. So if we let $$ \beta = \limsup_{n\to\infty} c_n, \qquad \alpha = \liminf_{n\to\infty} c_n $$ then we have $ \beta = f(\alpha)$ and $\alpha = f(\beta)$, i.e., both $\alpha$ and $\beta$ are non-negative fixed points of $g = f\circ f$. Since this function has a unique non-negative fixed point, this proves that $\alpha = \beta$.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between aula and atrium? When researching for the living room question and the question that inspired it, I came across some dictionary definitions of aula and atrium. Aula is a Greek thing and atrium is Roman, but otherwise they seem very similar to me. I know there are architectural differences between Greece and Rome. What is the difference between aula and atrium? I have found no comparison of the two anywhere. Would the Romans use the word atrium for something the Greeks would call aula and vice versa? I get the impression that atrium is the Roman-style word for an inner court or a hall, and aula is a Greek-style word for the same purpose. A: General description of a Greek αυλη: An αυλη could refer to a courtyard in front of the house or a courtyard, open to the sky, within the house, around which rooms were located. This courtyard was surrounded on all four sides with colonnades, creating a peristyle. These were used for exercise mainly but occasionally meals were eaten here. The household altar of Zeus was also located in the αυλη. General description of a Roman atrium: The Roman atrium was the first main room into which guests entered from the front door. In early Roman houses, the atrium was the only room. As wealth increased, so did the number of rooms, all of which led off the atrium but the atrium remained the most important room. It was open to the sky, allowing rainwater to collect in the impluvium. The household gods, the Lares, were kept here, as were the wax portraits of family ancestors, and the lectus genialis. Its main and most important function was to receive clients and guests. As such, atria could be very elaborate and were an important part of displaying and maintaining status. Similarities between a Greek αυλη and a Roman atrium: Open to the sky. Rooms were located off this centralised space. Religious icons were kept here. Differences between a Greek αυλη and a Roman atrium: The αυλη seems to have always been a courtyard at heart, that is to say, an outdoor area. In contrast, the atrium was always a room (in early houses, the only room). The αυλη was surrounded on four sides with colonnades creating a peristyle or cloister which was used for exercise. Indeed, Vitruvius appears to use aula and peristylium synonymously (6.7.4). The Dictionary of Greek and Roman Antiquities similarly notes that αυλη was “also used by later writers as equivalent to περιστύλιον”, citing Pollux (who wrote in 2nd cent. AD). In contrast, Vitruvius distinguishes between peristylium and atrium in the Roman house (6.5.2 – see below). For Vitruvius, therefore, neither αυλη nor aula are the same as atrium. The atrium had columns, no doubt to support the roof, but I have found no evidence that they were employed to create a colonnade nor that the atrium was used for exercise. Rather, the atrium appears to be a much more enclosed space than the αυλη. I’m not sure just how open to the sky each space was. It seems that the αυλη was entirely open while the atrium had an opening, the compluvium, to allow rainwater to run into the impluvium. The atrium was first and foremost a room for receiving clients/guests. A crowded atrium signified great social and political success (frequens atrium – Seneca, Epistles, 76.12); an empty one, failure (atrium vacuum – Seneca, Epistles, 22.9). I have not come across aula (in Latin) being used in this way, to denote a room in which one’s social status hangs in the balance. Vitruvius goes so far as to say that those in the lower classes do not need an atrium since they don’t receive clients (but rather are clients) (6.5.1). On the other hand, those of the highest rank have need of lofty atria: faciunda sunt vestibula regalia, alta atria et peristylia amplissima (6.5.2) Note again Vitruvius’ distinction between atrium and peristylium, the latter of which he sees as synonymous with aula. Later, he clarifies that in the Greek house: hospites advenientes non in peristylia sed in ea hospitalia recipiantur / arriving guests are not received in the peristylia but in the guest accommodation (6.7.4) Thus, the function of the aula and the atrium are not at all the same. In very early Greek houses, the αυλη was a courtyard you would pass through on your way to the δωμα or μεγαρον, the great hall. This reinforces the idea that the αυλη was not the main reception room in the Greek house (see this diagram of Odysseus' palace). As Vitruvius wrote: atriis graeci quia non utuntur, neque aedificiant … / not using atria, the Greeks do not build like us … (6.7.1) But how did the Romans use the (Latin) terms aula and atrium? By far the most common use of aula in Latin is to mean court, as in the sense of a ruler’s entourage and household, or simply a palace. Nevertheless, the Romans did sometimes use aula to mean a forecourt, usually where animals were kept, for instance a barking dog in Horace (Epistles, 1.2.66) and sheep in Propertius (3.13.39). Thus, this use equates with one Greek sense of the word. Otherwise, it is hard to be 100% certain that aula was used synonymously with atrium. As noted above, Vitruvius doesn’t use aula and atrium interchangeably as he clearly sees the two terms as describing two quite different spaces, different in form and function. However, Horace’s use of aula (in Epistles, 1.1.87) is clearly being used as a synonym with atrium. I say this because of the reference to the lectus genialis, the marriage bed which was kept in the atrium (unoccupied!), opposite the front door (lectus). Another possible synonymous use of aula with atrium is in Juvenal (Satires, 1.5) where he advises someone not to have children lest they divert his attentions from his patron: nullus tibi parvulus aula luserit Aeneas / don’t have a little Aeneas playing in the aula [which is actually a reference to Dido’s lament: si quis mihi parvulus aula luderet Aeneas / if in my aula a baby Aeneas were playing (Aeneid, 4:328)] Juvenal (and Dido) may mean the atrium or the aula proper, a peristyle or they could just as easily mean the forecourt. The problem is that, when translating, you could equally insert hall/atrium/courtyard and still make perfect sense without ever knowing for sure what the original intention was. Having said that, it seems to me that when it is important to the understanding of the sentence, atrium is used. For example, the biting remarks of Seneca about the gap between appearances and reality relies on the reader understanding that he is talking about the atrium and its function as a marker of status: non facit nobilem atrium plenum fumosis imaginibus / an atrium full of busts grimy with smoke do not make a nobleman (Epistles 44.5) Or again in Juvenal: tota licet veteres exornent undique cerae atria, nobilitas sola est atque unica virtus / you may decorate your entire atrium everywhere with ancient wax portraits but the one and only nobility is excellence of character (Satires, 8.19). And in Horace: cur invidendis postibus et novo sublime ritu moliar atrium? / why should I go to all the effort to build envy-inducing doorposts and a towering atrium? (Odes, 3.1.45-46) I don’t think that in any of these examples the full force of the author’s point would be felt if they had used aula. This is, in my opinion, because the perceived functions of the aula/αυλη and the atrium were different even if over time all three terms came to suggest the form of a central hall-like space. Only the distinctly Roman atrium and its peculiarly Roman function as reception room could be used here. A: The atrium was a central, and most important part of the Roman domus, built as a kind of courtyard. It had an inwardly-sloping roof with a central gap — the impluvium, into which rainwater drained before falling into a cistern (which, confusingly, was also called impluvium). Vitruvius (vi, 3) is a major source for the various designs, etc., of atrium, which he also refers to as cavum aedium. The word aula is less easily defined. Though in origin it was a court in the front of a Greek house, it doesn't seem to have been anything at Rome as important to a house as the atrium itself, but was possibly some part of it (Horace Ep. I, 1, 87). The word seems just as likely to have been used for 'court' in all the English senses of the noun, (e.g. Tacitus Hist. I, 13, end)
{ "pile_set_name": "StackExchange" }
Q: Base Class library for NTP client in .NET? Is there any .NET BCL for NTPClient? I have seen a few implementations of NTPClient here and here. But does .net provide any library for doing this? A: There appears to be no BCL for .NET; We have to write our own libraries, examples of which are documented in the question.
{ "pile_set_name": "StackExchange" }
Q: How to handle attributes of type "Set" in Lightning? I am trying to collect record Ids of changed records. Therefor I'm using aura:attribute type="Set". But whenever I add the same id twice, it will be twice in my set. As described in the documentation, there should be no duplicates. (Current Worakround is using type="Map"). <aura:attribute name="mySet" type="Set" default="[]" access="private" /> Controller: var recordId = "a0246000005mfR0AAI"; var mySet = cmp.get("v.mySet"); mySet.push(recordId); mySet.push(recordId); cmp.set("v.mySet", mySet); var doublecheck = cmp.get("v.mySet"); Debug result: doublecheck = Proxy {0: "a0246000005mfR0AAI", 1: "a0246000005mfR0AAI", length: 2} Am I handling the set wrong, or does it just not work yet? A: I think that the problem is in javascript when you are declaring mySet. Try this: var mySet = new Set(component.get("v.mySet")); Edit: the best solution is var changes = cmp.get("v.changes") || new Set();
{ "pile_set_name": "StackExchange" }
Q: C++ - Error - No operator "[]" matches these operands I'm working on code for a container that stores strings and sorts them in alphabetical order (thought that it'd be a fun idea). I've been attempting to put a "[]" operator and assign it to the private member words so I can access any data or strings inside of said member. However, I've been struggling with this continuous error that I'm having trouble fixing. It says: No operator "[]" matches these operands. Operand types are std::shared_ptr<std::vector<std::string, std::allocator<std::string>>>[size_t] Here's some of the code regarding the error (Error is present at class.cpp): class.h #pragma once #include <memory> #include <vector> #include <string> #include <iostream> class sort { public: //... sort(int i): words(std::make_shared<std::vector<std::string>>(i)) { } std::shared_ptr<std::vector<std::string>> & operator [](size_t st); //... private: std::shared_ptr<std::vector<std::string>> words; std::string alpha = "abcdefghijklmnopqrstuvwxyz"; }; class.cpp #include "sort.h" #include <memory> #include <vector> #include <iostream> //... std::shared_ptr<std::vector<std::string>> & sort::operator[](size_t st) { return words[st]; //Error is defined at the brackets } //... Another thing to note is that if I remove the brackets with st, the error is gone (Obviously not what I'm trying to achieve). Any help or a fix to this code would be greatly appreciated. A: Your words member is not an array or container. It is a std::shared_ptr, which does not have an operator[] defined prior to C++17 (and even then, your code would still be using it wrong). That is why your operator[] fails to compile. You have a std::shared_ptr pointing to a std::vector<std::string> object stored somewhere else in memory 1. If you want your operator[] to access the std::string values in that std::vector, you need to deference the pointer first in order to access the std::vector, and then you can call its operator[]. You need to fix the return value of your operator[] to be a single std::string, not a std::shared_ptr. 1: why are you using a pointer at all? Why not declare words to be an actual std::vector object directly in your class? std::vector<std::string> words; Try this instead: class.h #pragma once #include <memory> #include <vector> #include <string> #include <iostream> class sort { public: //... std::string& operator [](size_t st); //... private: std::shared_ptr<std::vector<std::string>> words; std::string alpha = "abcdefghijklmnopqrstuvwxyz"; }; class.cpp #include "sort.h" #include <memory> #include <vector> #include <iostream> //... std::string& sort::operator[](size_t st) { return (*words)[st]; } //...
{ "pile_set_name": "StackExchange" }
Q: Excluding specific files from Visual Studio search Is it possible to exclude certain files from search in Visual Studio. For example jquery.js is almost always polluting my search results with half result coming from that file. I know you can white-list specific types, but when I want to search in .js extension is there solution for that? Vote here for feature: https://developercommunity.visualstudio.com/idea/405990/code-search-exclude-files-from-search.html?inRegister=true A: Altough it does not solve your problem it may help out a bit Ctrl + Shift + F should trigger the Find and Replace window. From there, click Result Options and select "Display file names only". It won't have all the info you need but might make it easier to recognize the files. A: In Visual Studio 2017 there is a workaround: you can right-click a search result and then click Delete. I use it to eliminate the big minified files from the Find Results window. A: I've got the same problem with unwanted .js files polluting the search result. Especially the minified versions (e.g. jquery.min.js) are really annoying since they consist of only one (1) single very very long line. All of that line is displayed line-wrapped in search result. Not ideal! Possible solutions: Since .js files are (normally) just static content, you should be able to name them as you like. Rename it to jquery.min.js.nosearch and include the file with <script type="text/javascript" src="jquery.min.js.nosearch"></script> in HTML. Get these files from an CDN and delete your local files. Exclude these files from the VS project, provided that you can handle the inclusion of them in an other way when needed, e.g. when deploying (and provided that you scope your search to solution/project, not folder).
{ "pile_set_name": "StackExchange" }
Q: How does OBS captures OpenGL based games video on Windows? I am trying to capture screenshots for OpenGL based games on Windows. Most answers on the internet are to make the window visible and take screenshots. But when I use OBS(Open Broadcaster Software) to broadcast my game play, it is able to streaming the game content even the game window is minimized. Can anyone help me understand how they do that? Thanks! A: The OpenGL API provides a way to draw to an internal "Frame buffer object" (FBO) which can be blitted to the window. If OBS doesn't provide a way to access that FBO, then your only solution is to make the window visible. Well, you could also hack the broadcast and try to figure out about those bytes... EDIT: When the OP clarified his question I was curious. So I dug into OBS code and found that for Windows it uses .dll injection and process hook. I also found that it hooks "swap buffers" and get the current Frame Buffer with glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING...), copies it and then let Windows continues its job. Please, notice that I can be wrong. But what I found looks good to me.
{ "pile_set_name": "StackExchange" }
Q: C# - Very slow string variable calculation I have over 27,000,000 string variable in the array. When I add a string to another one speed is greatly reduced. my code is: //public string[] part2 = { ..... string Str1; string Str0; Parallel.ForEach(index_choose, x => { Str1 += part1[x]; Str0 += part2[x]; //progressBar1.PerformStep(); //label1.Text = progressBar1.Value.ToString(); //Application.DoEvents(); }); string total = Str1 + Str0; Run this code on a powerful CPU takes More than 20 hours! A: I will recommend to use StringBuilder - like in the following example StringBuilder str0 = new StringBuilder(); StringBuilder str1 = new StringBuilder(); Parallel.ForEach(index_choose, x => { Str1.Append(part1[x]); Str0.Append(part2[x]); //progressBar1.PerformStep(); //label1.Text = progressBar1.Value.ToString(); //Application.DoEvents(); }); string total = Str1.Append(Str0).ToString();
{ "pile_set_name": "StackExchange" }
Q: "Selection cannot be launched and there are no recent launches” when Eclipse for Android Project Dev I am trying to open an unzipped Android Project using Eclipse but every time I try to run or debug it show this error: "selection cannot be launched and there are no recent launches". So I looked it up and tried creating a new project from an existing source but opens with errors and I open the src etc folders. I also tried importing the project which didn't work either. There are no run as options and changing the run configuration didn't really help. I couldn't find any option to open it as an Android project. Could you please help me to run this project. (Since I unzipped this project there is a _MACOSX folder when I import and I am not sure if that matters or should I remove that folder.) A: I am running Eclipse Juno SR 2 I had a similar problem. To fix the issue go to Run-> Run Configurations... If there isn't create a new run configuration (top left) Under Android tab: browse and select the project you want to run Under Target tab: select Always prompt to pick device (or) you can pick automatic launch. Similar solution can be applied to the Debug by going to Run-> Debug Configurations... Update: I realize this is beyond the scope of the question but if any new developers are coming to answer then I would suggest switching to Android Studio from Eclipse. AS is the official Google supported IDE for Android development and much nicer to use. A: In the Package Explorer (the left column), right-click on the name of the project (the top item). In the menu that appears, select "Run as"; then choose "Android Application".
{ "pile_set_name": "StackExchange" }
Q: Missing fonts when building/running Appcelerator app from XCode I've recently updated from Titanium w/3.5.0.GA SDK to Appcelerator Studio w/5.2.0SDK and can no longer build and run the appc (5.1.0 CLI) generated projects in XCode (7.2.1) without losing the ability to display my custom font resources (app/assets/fonts). When building a project for iOS in studio (latest 4.4.0) and deploying to connected iPhone 6 (running 9.2) all fonts appear correctly in app. However when building and running the <projectname>.xcodeproject that is generated by appc during this process the same fonts do not show? Is this related to https://jira.appcelerator.org/browse/TIMOB-19818 ? Is there any fix on the horizon if so? I have always relied on modifying the generated projects to include other asset catalogs and manually alter the build and version numbers prior to appstore submission so am very curious to find a solution to this issue - all help much appreciated! FYI - for reference, I've tried to build the same project generated in Titanium studio w/3.5.0.GA within the Latest XCode (7.2.1) as above and the fonts still work correctly so this issue seems to be with Appcelerator Studio with CLI 5.1.0 and SDK 5.2.0 combination. A: You can follow this below two steps. This is a workaround, might work for you. Step 1: Grab resource files from debug ipa: a. Build a debug version for your iPhone device. b. After the app has successfully launched on your iPhone, navigate to the ipa file in the debug build folder. Click right on the file (or cmd-click) and choose to uncompress the file c. In the extracted archive find the payload file. Also right click on the file (or cmd-click) and choose to show its contents. d. You should now see your resource files and folders. Select all the required files and folders and copy them in some new folder. Step 2: Add files to XCode project a. Open the build XCode project with XCode b. In the left column right click (or cmd-click) on your project c. Choose "Add Files to [project name]" d. In the file dialog multiselect your files and folders you copied from the debug ipa in step 1 e. That's it. Now archive your product and submit it.
{ "pile_set_name": "StackExchange" }
Q: db2 database couldn't check if username already exists I am creating a simple registration page using IBM Db2 and PHP and all my data is saved in the Db2 database. However, I can't keep the constraint of already existing username. It is registering the user even if the username is already there in Db2. Also, it is logging in with any password entered! I couldn't understand when the entries are shown in the database it means the data has found the right connection to the database. Then why it is not catching the constraints logic. I just changed the MySQL functions in Db2 for PHP and there are some functions which are giving me error vibes like db2_exec() and db2_fetch_assoc. A: $user_check_query= "SELECT * FROM users WHERE username ='$username'" $result = db2_exec($db,$user_check_query); $user = db2_fetch_assoc($result); if(!empty($user)){ // Not empty mean database already exist this username array_push($errors,"Username exists"); }
{ "pile_set_name": "StackExchange" }
Q: Finding the number of ways to pick ${n}$ marbles from a jar Problem: А jar contains 8 blue marbles, 6 green marbles, and 4 red marbles. Five marbles are selected at random, all at once. In how many ways can: A.) two red and three blue marbles be obtained? B.) two green and two blue marbles be obtained? C.) two red marbles be obtained? D.) two or more green marbles be obtained? Work: A.) $4\cdot3\cdot8\cdot7\cdot6 $ $\cdot$ $_{5}C_{2}$ = $40,320$ B.) $6\cdot5\cdot8\cdot7\cdot6 $ $\cdot$ $_{5}C_{2}$ = $100,800$ C.) $4\cdot3\cdot12\cdot11\cdot10 $ $\cdot$ $_{5}C_{2}$ = $158,400$ D.) ($6\cdot5\cdot12\cdot11\cdot10 $ $\cdot$ $_{5}C_{2}$) + ($6\cdot5\cdot4\cdot12\cdot11 $ $\cdot$ $_{5}C_{3}$) + ($6\cdot5\cdot4\cdot3\cdot12 $ $\cdot$ $_{5}C_{4}$) + ($6\cdot5\cdot4\cdot3\cdot2 $ $\cdot$ $_{5}C_{5}$) = $576,720$ Is all of work correct? A: We assume (as we are expected to) that the marbles are distinguishable. A.) There are $\binom{4}{2}$ ways to choose the reds. For each of these ways, there are $\binom{8}{3}$ ways to choose the blues, for a total of $\binom{4}{2}\binom{8}{3}$. B.) We interpret the question as asking for exactly $2$ green and exactly $2$ blue, so $1$ red. The same reasoning as above gives $\binom{6}{2}\binom{8}{2}\binom{4}{1}$. C.) The $2$ red can be chosen in $\binom{4}{2}$ ways. Now we must choose $3$ non-red from the $14$ non-red. D.) It's your turn.
{ "pile_set_name": "StackExchange" }
Q: IOS Swift How can fatal error unwrapping optional value I have a ViewController called BookViewC all it does is display 1 video. The story board contains a IBOutlet called FullName and a UIView which I use to show the video . I have functionality that when you tap the video it is supposed to get the next video. I always get the nil value for FullName when I get the next video, it always gets the first video correctly . Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on the IBOutLet for fullname which I understand why, is there a way around that ? Here is my code to clear things up class BookViewC: UIViewController, VideoViewDelegate{ @IBOutlet weak var VideoView: UIView! @IBOutlet weak var FullName: UIButton! override func viewDidLoad() { super.viewDidLoad() // This method queries the database for the latest video ReloadTable(Offset: 0) } func reloadTable(Offset: Int) { // Queries the database for video name // Returns data in Json DispatchQueue.main.async { for Stream in Streams! { if let fullname = Stream["fullname"] as? String { // This below throws the nil error when getting the 2nd video self.FullName.setTitle(fullname, for: .normal) } } // Method below simply shows the video self.PlayVideo(MediaHeight: Float(pic_height), MediaURL: s_image) } func PlayVideo(MediaHeight: Float, MediaURL: String) { let movieURL = URL(string: MediaURL) videoCapHeight.constant = CGFloat(MediaHeight) streamsModel.playerView = AVPlayer(url: movieURL!) streamsModel.MyAVPlayer.player = streamsModel.playerView streamsModel.MyAVPlayer.videoGravity = AVLayerVideoGravity.resizeAspectFill.rawValue streamsModel.MyAVPlayer.showsPlaybackControls = false streamsModel.MyAVPlayer.view.frame = VideoView.bounds VideoView.addSubview(streamsModel.MyAVPlayer.view) self.addChildViewController(streamsModel.MyAVPlayer) streamsModel.playerView?.isMuted = false streamsModel.MyAVPlayer.player?.play() } } When you tap on a Video it goes to this class class CustomAVPLayerC: AVPlayerViewController { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // I try to return to my original Class now let BookC = BookViewC() for touch in touches { let location = touch.location(in: self.view) if location.x < self.view.layer.frame.size.width / 2 { print("Tapped Left") } else { print("Tapped Right get next video") // Offset is now 1 which gets the 2nd video BookC.ReloadTable(offset: 1) } } } } What is happening is that Once I go to CustomAVPLayerC Controller all the IBOutlets from BookViewC become nil and then once I try to go back it gives me the error. Is there anything I can do to fix that or work around it ? The videos I display use the AVPlayer so on tap I must go to the CustomAVPLayerC Controller . Any suggestions would be great . A: IBOutlets are nil because your BookVC is not initialized from .xib/storyboard. Using delegation pattern should solve the issue. Following is an example that can help achieving this, Create a protocol like below, protocol CustomAVPLayerProtocol: class { func reloadTable(at index: Int) } Update BookViewC to conform to CustomAVPLayerProtocol like below, extension BookViewC: CustomAVPLayerProtocol { func reloadTable(at index: Int) { self.reloadTable(Offset: index) } } then update CustomAVPLayerC class CustomAVPLayerC: AVPlayerViewController { weak var delegate: CustomAVPLayerProtocol? func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self.view) if location.x < self.view.layer.frame.size.width / 2 { print("Tapped Left") } else { let index = 1 self.delegate?.reloadTable(at: index) } } } } and lastly in BookViewC set CustomAVPLayerC(when you are initializing) delegate like below, let customAVPLayerVC = CustomAVPLayerC() customAVPLayerVC.delegate = self
{ "pile_set_name": "StackExchange" }
Q: Implement pull to refresh FlatList please help me out to implement pull to refresh on my app, I'm kinda new to react native, thanks. I don't know how to handle onRefresh and refreshing. class HomeScreen extends Component { state = { refreshing: false } _renderItem = ({ item }) => <ImageGrid item={item} /> _handleRefresh = () => { }; render() { const { data } = this.props; if (data.loading) { return ( <Root> <Loading size="large" /> </Root> ) } return ( <Root> <HomeHeader /> <FlatList contentContainerStyle={{ alignSelf: 'stretch' }} data={data.getPosts} keyExtractor={item => item._id} renderItem={this._renderItem} numColumns={3} refreshing={this.state.refreshing} onRefresh={this._handleRefresh} /> </Root> ); } } export default graphql(GET_POSTS_QUERY)(HomeScreen); A: Set variable this.state = { isFetching: false, } Create Refresh function onRefresh() { this.setState({isFetching: true,},() => {this.getApiData();}); } And in last set onRefresh and refreshing in FlatList. <FlatList data={ this.state.FlatListItems } onRefresh={() => this.onRefresh()} refreshing={this.state.isFetching} After fetching Data in function getApiData Make sure to set false isFetching. this.setState({ isFetching: false }) A: you can also use refreshControl in Flatlist ScrollView and any other list component <FlatList contentContainerStyle={{ alignSelf: 'stretch' }} data={data.getPosts} keyExtractor={item => item._id} renderItem={this._renderItem} numColumns={3} refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._handleRefresh} /> } /> A: // Sample code representing pull to refresh in flatlist. Modify accordingly. import React, { Component } from 'react' import { Text, View,StyleSheet,FlatList,Dimensions,Image,TouchableHighlight } from 'react-native' export default class Home extends Component { constructor(props) { super(props); this.state = { data : [], gender : "", isFetching: false, } } componentWillMount() { this.searchRandomUser() } onRefresh() { this.setState({ isFetching: true }, function() { this.searchRandomUser() }); } searchRandomUser = async () => { const RandomAPI = await fetch('https://randomuser.me/api/?results=20') const APIValue = await RandomAPI.json(); const APIResults = APIValue.results console.log(APIResults[0].email); this.setState({ data:APIResults, isFetching: false }) } render() { return ( <View style = {styles.container}> <TouchableHighlight onPressOut = {this.searchRandomUser} style = {{width:deviceWidth - 32, height:45,backgroundColor: 'green',justifyContent:"center",alignContent:"center"}}> <Text style = {{fontSize:22,color: 'white',fontWeight: 'bold',textAlign:"center"}}>Reload Data</Text> </TouchableHighlight> <FlatList data={this.state.data} onRefresh={() => this.onRefresh()} refreshing={this.state.isFetching} keyExtractor = { (item, index) => index.toString() } renderItem={({item}) => <View style = {styles.ContainerView}> <View> <Image source={{uri : item.picture.large}} style = {{height:100,width:100,borderRadius: 50,marginLeft: 4}} resizeMode='contain' /> </View> <View style = {{flexDirection: 'column',marginLeft:16,marginRight: 16,flexWrap:'wrap',alignSelf:"center",width: deviceWidth-160}}> <Text>Email Id : {item.email}</Text> <Text>Full Name : {this.state.gender} {item.name.first} {item.name.last}</Text> <Text>Date of birth : {item.dob.age}</Text> <Text>Phone number : {item.phone}</Text> </View> </View> } /> </View> ) } } const deviceWidth = Dimensions.get('window').width const deviceHeight = Dimensions.get('window').height const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', marginTop:22 }, ContainerView: { // backgroundColor:'grey', marginBottom:20, paddingVertical:10, backgroundColor: '#F5F5F5', borderBottomWidth:0.5, borderBottomColor:'grey', width: deviceWidth-40, marginLeft:20, marginRight:20, marginTop:20, flexDirection:'row' } });
{ "pile_set_name": "StackExchange" }
Q: How to overcome 'DataFrame' object has no attribute 'excelwriter' in pandas for Python I have refined an existing xlsx file and want to create three new files based on the content. Successful in getting three new outputs, but not able to write it to new xlsx files. I tried installing excelwriter but that didn't fixed my problem. import pandas as pd import xlsxwriter xl_file = pd.ExcelFile('C:\\Users\\python_codes\\myfile.xlsx') dfs = pd.read_excel('myfile.xlsx', sheetname="Sheet1") test = dfs.drop_duplicates(subset='DetectionId', keep='first', inplace=False) dfs2 = test[test['list_set_id'] == 1] print(dfs2) writer = dfs2.ExcelWriter('newfile.xlxs', engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() I want to write new xlsx file with the filtered content from the existing file. A: ExcelWriter belongs to the pandas module, not to a DataFrame instance. writer = dfs2.ExcelWriter should be writer = pd.ExcelWriter
{ "pile_set_name": "StackExchange" }
Q: Boost asio-acceptor unblocks without a new connection? I am using the C++ boost asio library, where I listen to new connections on the socket. On getting a connection I process the request and then listen for a new connection on another socket in a loop. while (true) { tcp::socket soc(this->blitzIOService); this->blitzAcceptor.listen(); boost::system::error_code ec; this->blitzAcceptor.accept(soc,ec); if (ec) { // Some error occured cerr << "Error Value: " << ec.value() << endl; cerr << "Error Message: " << ec.message() << endl; soc.close(); break; } else { this->HandleRequest(soc); soc.shutdown(tcp::socket::shutdown_both); soc.close(); } } According to my understanding it should always block at this->blitzAcceptor.accept(soc,ec); and everytime a new connection is made it should handle it in this->HandleRequest(soc); and again block at this->blitzAcceptor.accept(soc,ec); But what I see is this that for the first time it will block at this->blitzAcceptor.accept(soc,ec) and when a new connection is made it will handle the request, but instead of blocking again at this->blitzAcceptor.accept(soc,ec) it will go ahead into this->HandleRequest(soc); and block at soc.receive(); inside. This doesn't happen always, but happens most of the time. What could be the reason to this behavior, and how can I ensure that it always block at this->blitzAcceptor.accept(soc,ec) until a new request is made? A: What could be the reason to this behavior? This behavior is entirely dependent on the client code. If it connects, but does not send a request, the server with block when receiving data. how can I ensure that it always block at this->blitzAcceptor.accept(soc,ec) until a new request is made? You can't. But your server can initiate a timeout that starts immediately after accepting the connection. If the client does not send a request within that duration, close the socket. To do that, you should switch to using asynchronous methods rather than synchronous methods.
{ "pile_set_name": "StackExchange" }
Q: Java: How to drag and drop on a TrayIcon? How can I catch a drop event of a text / file / any other DataFlavor onto a java.awt.TrayIcon (placed in a java.awt.SystemTray)? A: Apparently this is not supported yet (Java 1.7). If anyone is interested, I have created a feature request Sun Feature Request 7119272 - you can monitor progress and vote for it if you'd like.
{ "pile_set_name": "StackExchange" }
Q: What to do about failed native extension builds in gem on Windows? A couple of Rails applications I downloaded have dependencies on bson_ext which appears to be a native code library. When I run rake gems:install for the app I get the following error message: ERROR: Error installing bson_ext: ERROR: Failed to build gem native extension. d:/Ruby187/bin/ruby.exe extconf.rb checking for asprintf()... no checking for ruby/st.h... no checking for st.h... no checking for ruby/regex.h... no checking for regex.h... no checking for ruby/encoding.h... no creating Makefile make 'make' is not recognized as an internal or external command, operable program or batch file. Gem files will remain installed in d:/Ruby187/lib/ruby/gems/1.8/gems/bson_ext-1.0.1 for inspection. Results logged to d:/Ruby187/lib/ruby/gems/1.8/gems/bson_ext-1.0.1/ext/cbson/gem_make.out My questions are: Will my rails application fail because of this, I think I know the answer to this? If I need to build this gem can I do it on windows? If it can be built on Windows what toolchain do I need? GCC? Should I just abandon Windows for Rails development and use my Mac or a Linux VM instead? A: Try using RubyInstaller and the optional DevKit. With the DevKit installed you should be able to build (compile) most native extensions on windows.
{ "pile_set_name": "StackExchange" }
Q: SRA Toolkit and lebanese data I am trying to extract data from this: https://trace.ncbi.nlm.nih.gov/Traces/sra/?run=SRR6245218 I installed SRA Toolkit, downloaded the SRR6245218 file and executed this: fastq-dump -X 5 SRR6245218 --fasta -O ./ The result is a fasta file 900 bytes long, which does not contain the mitochondrial data that I need. What am I doing wrong? A: Your command is fine. It is working as expected. Did you intend to include -X 5 in your command? That restricts the number of spots to 5. If you drop it, you will download the entire set of 2563898 spots.
{ "pile_set_name": "StackExchange" }
Q: Javascript - Adding Full Screen Video to Image Slideshow I need assistance as to how I would add a short video clip to display along with my image slideshow. Below is the JavaScript slideshow which works fine with images, I would like to add videos alongside with the images as part of the slideshow. Any assistance would be greatly appreciated. Thanks. <script type="text/javascript"> var img1 = new Image(); img1.src = "path/image1.jpg"; var img2 = new Image(); img2.src = "path/image2.jpg"; var img3 = new Image(); img3.src = "path/image3.jpg"; var img4 = new Image(); img4.src = "path/video.mp4"; var galleryarray = [img1, img2, img3, img4]; var curimg = 1; function rotateimages(){ $( "#slideshow" ).fadeOut( "slow", function() { document.getElementById("slideshow").setAttribute("src", galleryarray[curimg].src) curimg=(curimg<galleryarray.length-1)? curimg+1 : 0 }); $( "#slideshow" ).fadeIn( "slow" ); } window.onload=function(){ setInterval("rotateimages()", 5000) } HTML: <img id="slideshow" src="images/image1.jpg" class="img-responsive"/> A: You will have to create a video element instead of a img one. function img(src) { var el = document.createElement('img'); el.src = src; return el; } function vid() { //Accepts any number of ‘src‘ to a same video ('.mp4', '.ogg' or '.webm') var el = document.createElement('video'); el.onplay = function () { clearInterval(sliding); }; el.onended = function () { sliding = setInterval(rotateimages, 5000); rotateimages(); }; var source = document.createElement('source'); for (var i = 0; i < arguments.length; i++) { source.src = arguments[i]; source.type = "video/" + arguments[i].split('.')[arguments[i].split('.').length - 1]; el.appendChild(source); } return el; } var galleryarray = [img('path/image1.jpg'), img('path/image2.jpg'), img('path/image3.jpg'), vid('path/video.mp4', 'path/video.ogg')]; var curimg = 1; function rotateimages() { $("#slideshow").fadeOut("slow"); setTimeout(function () { curimg = (curimg < galleryarray.length - 1) ? curimg + 1 : 0 document.getElementById('slideshow').innerHTML = ''; galleryarray[curimg].style.width = "100%"; galleryarray[curimg].style.height = "100%"; document.getElementById('slideshow').appendChild(galleryarray[curimg]); if (galleryarray[curimg].tagName === "VIDEO") { galleryarray[curimg].play(); } $("#slideshow").fadeIn("slow"); }, 1000); } var sliding; window.onload = function () { sliding = setInterval(rotateimages, 5000); rotateimages(); //FullScreen won't work in jsFiddle's iframe document.getElementById('slideshow').onclick = function () { if (this.requestFullscreen) { this.requestFullscreen(); } else if (this.msRequestFullscreen) { this.msRequestFullscreen(); } else if (this.mozRequestFullScreen) { this.mozRequestFullScreen(); } else if (this.webkitRequestFullscreen) { this.webkitRequestFullscreen(); } } } Working Fiddle
{ "pile_set_name": "StackExchange" }
Q: count and group the column by sequence I have a dataset that has to be grouped by number as follows. ID dept count 1 10 2 2 10 2 3 20 4 4 20 4 5 20 4 6 20 4 7 30 4 8 30 4 9 30 4 10 30 4 so for every 3rd row I need a new level the output should be as follows. ID dept count Level 1 10 2 1 2 10 2 1 3 20 4 1 4 20 4 1 5 20 4 2 6 20 4 2 7 30 4 1 8 30 4 1 9 30 4 2 10 30 4 2 I have tried counting the number of rows based on the dept and count. data want; set have; by dept count; if first.count then level=1; else level+1; run; this generates a count but not what exactly I am looking for ID dept count Level 1 10 2 1 2 10 2 1 3 20 4 1 4 20 4 1 5 20 4 2 6 20 4 2 7 30 4 1 8 30 4 1 9 30 4 2 10 30 4 2 A: It isn't quite clear what output you want. I've extended your input data a bit - please could you clarify what output you'd expect for this input and what the logic is for generating it? I've made a best guess at roughly what you might be aiming for - incrementing every 3 rows with the same dept and count - perhaps this will be enough for you to get to the answer you want? data have; input ID dept count; cards; 1 10 2 2 10 2 3 20 4 4 20 4 5 20 4 6 20 4 7 30 4 8 30 4 9 30 4 10 30 4 11 30 4 12 30 4 13 30 4 14 30 4 ; run; data want; set have; by dept count; if first.count then do; level = 0; dummy = 0; end; if mod(dummy,3) = 0 then level + 1; dummy + 1; drop dummy; run; Output: ID dept count level 1 10 2 1 2 10 2 1 3 20 4 1 4 20 4 1 5 20 4 1 6 20 4 2 7 30 4 1 8 30 4 1 9 30 4 1 10 30 4 2 11 30 4 2 12 30 4 2 13 30 4 3 14 30 4 3
{ "pile_set_name": "StackExchange" }
Q: decoding captured HID over GATT traffic with usbpcap/wireshark I'm trying to reverse-engineer a BLE device that uses USB HID over GATT to communicate with the host. I can capture the traffic using usbpcap, but when loading the results into wireshark, the packets seem to contain the bytes representing the data that is going over the air (i.e. device descriptor), but the packets are not decoded according to USBHID protocol. Everything is decoded as USB, and only contain URB_INTERRUPT_IN, URB_BULK in/out and URB_CONTROL_OUT, while I'm looking for things like GET DESCRIPTOR Request/Response DEVICE. Is there an extra step I can take to get the packets formatted and parsed correctly? A: There are a few characteristics in use. You have one characteristic which contains the Report Map. This is usually only read once when the device is paired. This map contains the layout/specification of the data which is later sent through the Report notifications. This is mostly "copy-paste" the specification from the USB spec into BLE. Now, when you run HID-over-GATT and your Bluetooth controller talks to the Host over USB, what you will see in usbpcap is the ACL data which contains L2CAP data, which contains GATT data, which in turn contains the Report data for HID. Then the Bluetooth stack on the host will decode this and feed it into the kernel's HID parser. I would suggest you to instead connect your HID-over-GATT device to an Android phone and then take a look at the HCI snoop log what happens, which is decodable in Wireshark (but it won't parse your HID data).
{ "pile_set_name": "StackExchange" }
Q: What can we say if the inner products of two vectors ($u$ and $v$) with another vector ($x$) are equal? ($x$ is an eigenvector) We know that $x$ is an eigenvector and the inner products of $x$ with $u$ and $v$ are equal, I mean: $\langle u,x\rangle \;= \; \langle v,x \rangle$ On the other hand, we know that $v = [1,1,...,1]$. $u$ and $v$ and $x$ are defined on $\mathbb{R}^d$. And by the inner-product, I mean the sum of elements of the output of the element-wise multiplication. What can we say about the relation between $u$ and $v$? A: $\langle w, x \rangle$ is a scalar multiple of the length projection of $w$ onto $x$. So your two inner products are equal if and only if $u$ and $v$ have the same projection onto $x$, or equivalently, $u-v$ is orthogonal to $x$ (which can be easily seen by $\langle u-v, x\rangle = \langle u, x \rangle - \langle v, x \rangle = 0$).
{ "pile_set_name": "StackExchange" }
Q: Project Web Access, Resources from Databases Is there a way to retrieve the resources (names) of a current project? Here at my work we work with the Scrum methodology, so in each sprint we create a new project file. Each project file is synced with PWA (Project Server Web Access). I have permission on the database to retrieve information. Is there a way to pull resources names from the database? A: Yes you can, but it depends on the version of Project Server you are using. Project Server 2007 This version introduced the reporting database. It is populated whenever a project is published. (You can query unpublished data by using the drafts database.) Microsoft have provided a report pack which may already contain the report you need. It also contains many examples on how to use the reporting database. The complete database schema is available for download in the Project 2007 SDK (look for pj12ReportingDB.chm). Project Server 2003 As this is an older version there is less information available, however there are example queries from EPM Central that show how to query resources. The complete database schema is also available from Microsoft.
{ "pile_set_name": "StackExchange" }
Q: Get all time value according to its primary key I have a mysql table like this: I want to extract all time value from the table by ID and date using php. Thanks in advance. I want the output to be like this: 01403003 2015-09-01 07:54 11:00 11:42 17:02 17:03 A: What you looking for is group_concat. This function returns a string result with the concatenated non-NULL values from a group. So for your need you can do something like: SELECT id, date, group_concat(valid_time) from TABLE_NAME group by id, date; it will return result like: 01403003 2015-09-01 07:54, 11:00, 11:42, 17:02, 17:03
{ "pile_set_name": "StackExchange" }
Q: MSBuild.SonarQube.Runner.exe can't access https://sonarqube.com I am trying to run a SonarQube Analysis locally using the msbuild scanner. I can call MSBuild.SonarQube.Runner.exe begin /key:"CanoePoloLeagueOrganiser" /name:"CanoePoloLeagueOrganiser" /version:"1.0.0" without any problems. I can also run the msbuild step ("C:/Program Files (x86)/MSBuild/14.0/Bin/MSBuild.exe" "C:\Users\ceddl\Documen ts\GITHub\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiser.sln") without problems. But when I call MSBuild.SonarQube.Runner.exe end, it fails. I have enabled the full debug log output and done a lot of googling and looking at the generated files, but it looks like it should work to me. I have generated a token which is in the xml file and I can curl to https://sonarqube.com no problem, so I don't think its a firewall issue. This is the output that I get SonarQube Scanner for MSBuild 2.1 Default properties file was found at C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\tools\sonar\SonarQube.Analysis.xml Loading analysis properties from C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\tools\sonar\SonarQube.Analysis.xml sonar.verbose=true was specified - setting the log verbosity to 'Debug' Post-processing started. Using environment variables to determine the download directory... Executing file C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\bin\MSBuild.SonarQube.Internal.PostProcess.exe Args: Working directory: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube Timeout (ms):-1 Process id: 8236 SonarQube Scanner for MSBuild End Step 2.1 22:01:54.73 sonar.verbose=true was specified - setting the log verbosity to 'Debug' 22:01:54.734 Loading the SonarQube analysis config from C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\conf\SonarQubeAnalysisConfig.xml 22:01:54.734 Not running under TeamBuild 22:01:54.734 Analysis base directory: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube Build directory: Bin directory: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\bin Config directory: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\conf Output directory: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\out Config file: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\out Generating SonarQube project properties file to C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\out\sonar-project.properties The supplied Code Analysis ErrorLog file is a valid json file and does not need to be fixed: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiserXamarin\bin\Debug\CanoePoloLeagueOrganiserXamarin.dll.RoslynCA.json The supplied Code Analysis ErrorLog file is a valid json file and does not need to be fixed: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiser\bin\Debug\CanoePoloLeagueOrganiser.dll.RoslynCA.json The supplied Code Analysis ErrorLog file is a valid json file and does not need to be fixed: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\XamarinFormsPortable\XamarinFormsPortable.Droid\bin\Debug\XamarinFormsPortable.Droid.dll.RoslynCA.json The supplied Code Analysis ErrorLog file is a valid json file and does not need to be fixed: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\XamarinFormsPortable\XamarinFormsPortable\bin\Debug\XamarinFormsPortable.dll.RoslynCA.json WARNING: File is not under the project directory and cannot currently be analysed by SonarQube. File: C:\Users\ceddl\AppData\Local\Temp\.NETFramework,Version=v4.6.1.AssemblyAttributes.cs, project: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiserTests\CanoePoloLeagueOrganiserTests.csproj WARNING: File is not under the project directory and cannot currently be analysed by SonarQube. File: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\packages\xunit.runner.visualstudio.2.1.0\build\_common\xunit.runner.visualstudio.testadapter.dll, project: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiserTests\CanoePoloLeagueOrganiserTests.csproj WARNING: File is not under the project directory and cannot currently be analysed by SonarQube. File: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\packages\xunit.runner.visualstudio.2.1.0\build\_common\xunit.runner.utility.desktop.dll, project: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiserTests\CanoePoloLeagueOrganiserTests.csproj WARNING: File is not under the project directory and cannot currently be analysed by SonarQube. File: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\packages\xunit.runner.visualstudio.2.1.0\build\_common\xunit.abstractions.dll, project: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiserTests\CanoePoloLeagueOrganiserTests.csproj WARNING: File is not under the project directory and cannot currently be analysed by SonarQube. File: C:\Users\ceddl\AppData\Local\Temp\MonoAndroid,Version=v6.0.AssemblyAttributes.cs, project: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiserXamarin\CanoePoloLeagueOrganiserXamarin.csproj WARNING: File is not under the project directory and cannot currently be analysed by SonarQube. File: C:\Users\ceddl\AppData\Local\Temp\.NETPortable,Version=v4.5,Profile=Profile111.AssemblyAttributes.cs, project: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiser\CanoePoloLeagueOrganiser.csproj WARNING: File is not under the project directory and cannot currently be analysed by SonarQube. File: C:\Users\ceddl\AppData\Local\Temp\MonoAndroid,Version=v6.0.AssemblyAttributes.cs, project: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\XamarinFormsPortable\XamarinFormsPortable.Droid\XamarinFormsPortable.Droid.csproj WARNING: File is not under the project directory and cannot currently be analysed by SonarQube. File: C:\Users\ceddl\AppData\Local\Temp\.NETPortable,Version=v4.5,Profile=Profile111.AssemblyAttributes.cs, project: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\XamarinFormsPortable\XamarinFormsPortable\XamarinFormsPortable.csproj Setting analysis property: sonar.visualstudio.enable=false Writing processing summary to C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\out\ProjectInfo.log Removing the existing directory: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\bin\sonar-scanner Creating directory: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\bin\sonar-scanner SONAR_SCANNER_OPTS is not configured. Setting it to the default value of -Xmx1024m Calling the SonarQube Scanner... Setting environment variable 'SONAR_SCANNER_OPTS'. Value: -Xmx1024m Executing file C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\bin\sonar-scanner\bin\sonar-scanner.bat Args: -Dproject.settings=C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\out\sonar-project.properties -e <sensitive data removed> Working directory: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser Timeout (ms):-1 Process id: 3228 C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\bin\sonar-scanner\bin\.. INFO: Scanner configuration file: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\bin\sonar-scanner\bin\..\conf\sonar-scanner.properties INFO: Project root configuration file: C:\Users\ceddl\Documents\GITHub\CanoePoloLeagueOrganiser\.sonarqube\out\sonar-project.properties INFO: SonarQube Scanner 2.6 INFO: Java 1.7.0_71 Oracle Corporation (32-bit) INFO: Windows 8.1 6.3 x86 INFO: SONAR_SCANNER_OPTS=-Xmx1024m INFO: Error stacktraces are turned on. INFO: User cache: C:\Users\ceddl\.sonar\cache DEBUG: Extract sonar-scanner-api-batch in temp... DEBUG: Get bootstrap index... DEBUG: Download: https://sonarqube.com/batch_bootstrap/index INFO: ------------------------------------------------------------------------ ERROR: SonarQube server [https://sonarqube.com] can not be reached INFO: EXECUTION FAILURE INFO: ------------------------------------------------------------------------ INFO: Total time: 0.797s INFO: Final Memory: 3M/15M ERROR: Error during SonarQube Scanner execution INFO: ------------------------------------------------------------------------ org.sonarsource.scanner.api.internal.ScannerException: Unable to execute SonarQube at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory$1.run(IsolatedLauncherFactory.java:84) at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory$1.run(IsolatedLauncherFactory.java:71) at java.security.AccessController.doPrivileged(Native Method) at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory.createLauncher(IsolatedLauncherFactory.java:71) at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory.createLauncher(IsolatedLauncherFactory.java:67) at org.sonarsource.scanner.api.EmbeddedScanner.doStart(EmbeddedScanner.java:218) at org.sonarsource.scanner.api.EmbeddedScanner.start(EmbeddedScanner.java:156) at org.sonarsource.scanner.cli.Main.execute(Main.java:70) at org.sonarsource.scanner.cli.Main.main(Main.java:60) Caused by: java.lang.IllegalStateException: Fail to download libraries from server at org.sonarsource.scanner.api.internal.Jars.downloadFiles(Jars.java:93) at org.sonarsource.scanner.api.internal.Jars.download(Jars.java:70) at org.sonarsource.scanner.api.internal.JarDownloader.download(JarDownloader.java:39) at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory$1.run(IsolatedLauncherFactory.java:75) ... 8 more Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure at sun.security.ssl.Alerts.getSSLException(Unknown Source) at sun.security.ssl.Alerts.getSSLException(Unknown Source) at sun.security.ssl.SSLSocketImpl.recvAlert(Unknown Source) at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at org.sonarsource.scanner.api.internal.shaded.okhttp.Connection.connectTls(Connection.java:239) at org.sonarsource.scanner.api.internal.shaded.okhttp.Connection.connectSocket(Connection.java:201) at org.sonarsource.scanner.api.internal.shaded.okhttp.Connection.connect(Connection.java:172) at org.sonarsource.scanner.api.internal.shaded.okhttp.Connection.connectAndSetOwner(Connection.java:358) at org.sonarsource.scanner.api.internal.shaded.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:117) at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329) at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246) at org.sonarsource.scanner.api.internal.shaded.okhttp.Call.getResponse(Call.java:276) at org.sonarsource.scanner.api.internal.shaded.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:234) at org.sonarsource.scanner.api.internal.shaded.okhttp.Call.getResponseWithInterceptorChain(Call.java:196) at org.sonarsource.scanner.api.internal.shaded.okhttp.Call.execute(Call.java:79) at org.sonarsource.scanner.api.internal.ServerConnection.callUrl(ServerConnection.java:114) at org.sonarsource.scanner.api.internal.ServerConnection.downloadString(ServerConnection.java:99) at org.sonarsource.scanner.api.internal.Jars.downloadFiles(Jars.java:78) ... 11 more ERROR: ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging. Process returned exit code 1 The SonarQube Scanner did not complete successfully 22:01:55.932 Creating a summary markdown file... Process returned exit code 1 Post-processing failed. Exit code: 1 Thanks Cedd A: It's an SSL issue: javax.net.ssl.SSLHandshakeException . Most probable cause: your (old) Java 7 JVM doesn't speak TLS v1.2 . No need to fix your Java 7 JVM settings though: Java 7 is anyhow not supported by SonarQube (see requirements). Bottom line: make sure to use Java 8 if you still get SSL-related exception then enable Java-SSL debug logs with -Djavax.net.debug=all (in SONAR_SCANNER_OPTS environment variable) to understand the root-cause
{ "pile_set_name": "StackExchange" }
Q: sorting colors in matlab I have different RGB values in a 260000 * 3 dimension array. I wan to sort these colors in ascending or descending order (it does not matter which) so that similar colors are closer. What's the most efficient way to do this? A: Example: First we start with the regular Jet colormap: %# sample image mapped to Jet colormap I = repmat(1:100, 100, 1); C = jet(100); figure subplot(211), imagesc(I), colormap(C) subplot(212), rgbplot(C) First we shuffle the colors. Then we try to recover the original grouping of colors (we do this by sorting in the HSV colorspace according to the hue and value): %# shuffle colors C = C(randperm(100), :); %# rearrage according to HSV colorspace C = rgb2hsv(C); C = sortrows(C, [-1 -3 2]); %# sort first by Hue, then by value C = hsv2rgb(C); figure subplot(211), imagesc(I), colormap(C) subplot(212), rgbplot(C)
{ "pile_set_name": "StackExchange" }
Q: pyaudio installation on mac (python 3) I first tried: pip install pyaudio but I was told that -bash: pip: command not found Then I tried: pip3 install pyaudio then i got: src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found #include "portaudio.h" ^ 1 error generated. error: command '/usr/bin/clang' failed with exit status 1 ---------------------------------------- Command "/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 -c "import setuptools, tokenize;__file__='/private/var/folders/77/gz1txkwj2z925vk6jrkx3wp80000gn/T/pip-build-43z_qk7o/pyaudio/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/77/gz1txkwj2z925vk6jrkx3wp80000gn/T/pip-tkf78ih4-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/77/gz1txkwj2z925vk6jrkx3wp80000gn/T/pip-build-43z_qk7o/pyaudio but I had installed portaudio brew install portaudio Warning: portaudio-19.20140130 already installed So what can I do. Thanks a lot, it's my first time using pyaudio, so....... :) A: I'm assuming you are on a Mac. This is a simple issue to fix. First install Xcode. Then restart your computer. Afterwards run the commands in sequence, xcode-select --install brew remove portaudio brew install portaudio pip3 install pyaudio So to clarify, Xcode is installed through the App Store. Xcode command line tools are required for some installations, for others they are not. I'm including it here just to be on the safe side. You also probably do not need to uninstall and reinstall the formula via Homebrew, I did that to ensure that there would be absolutely no problems. Edit: I have been told Homebrew requires Xcode. So just run the xcode-select --install command to be able to use Clang. Also what version of Mac are you on? A: Steps: I assume you are using a mac osx download homebrew by pasting this code at any terminal point /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" After installing homebrew, install portaudio: brew install portaudio Finally install pyaudio using pip pip install pyaudio Note: Ensure you install homebrew if its not already installed
{ "pile_set_name": "StackExchange" }
Q: Problem with binding and unbinding mouse events to custom element I am trying to add "move by mouse" functionality to my CustomElement to enable it to move by mouse drag, by this simple function as below. But it has a lot of lag and the event does not attach and detach correctly on "mouseup" or "mousedown" events. I couldn't found why this happens because it works normally on simple "div" elements. drag functionality: //drag-element.js export default function dragElement(elm) { const header = elm.Cardheader; header.style.cursor = "all-scroll"; let [initX, initY] = [0, 0]; let mousedown = false; let mousemoveEventHandler = function(e) { if (mousedown) { elm.style.top = `${e.clientY - initY}px`; elm.style.left = `${e.clientX - initX}px`; } }; let mousedownEventHandler = function(e) { mousedown = true; header.onmousemove = mousemoveEventHandler; initX = e.clientX - elm.offsetLeft; initY = e.clientY - elm.offsetTop; }; let mouseupEventHandler = function(e) { mousedown = false; header.onmousemove = null; }; document.addEventListener("mouseup", mouseupEventHandler); header.onmousedown = mousedownEventHandler; } Custom Element: //content-card.js export default class ContentCard extends HTMLElement { constructor() { super(); let shadow = this.attachShadow({ mode: "open" }); let style = document.createElement("style"); style.textContent = ` :host { position: absolute; background-color: #fff; width: 50%; margin: 20px auto; display: block; border: 1px solid #eee; box-shadow: 1px 1px 4px 1px #444; box-sizing: border-box; } .header { background-color: #eee; min-height: 20px; display: block; padding: 15px; } .body { min-height: 150px; display: block; padding: 15px; } `; this.Cardheader = document.createElement("div"); this.Cardheader.setAttribute("class", "header"); this.Cardbody = document.createElement("div"); this.Cardbody.setAttribute("class", "body"); this.Cardheader.textContent = this.getAttribute("subject"); this.Cardbody.innerHTML = this.getAttribute("content"); shadow.appendChild(this.Cardheader); shadow.appendChild(this.Cardbody); shadow.appendChild(style); } static get observedAttributes() { return ["subject", "content"]; } get subject() { return this.Cardheader.textContent; } set subject(val) { this.Cardheader.textContent = val; } get content() { return this.Cardbody.innerHTML; } set content(val) { this.Cardbody.innerHTML = val; } connectedCallback() {} disconnectedCallback() {} attributeChangedCallback(name, oldValue, newValue) { if (newValue === oldValue) return; switch (name) { case "subject": this.subjetct = newValue; break; case "content": this.content = newValue; break; default: break; } } adoptedCallback() {} } main Javascript: //index.js import ContentCard from "./content-card.js"; import ContentCard from "./drag-element.js"; customElements.define("content-card", ContentCard); let cCard = new ContentCard(); document.body.appendChild(cCard); dragElement(cCard); <html> <head> <script defer type="module" src="./index.js"></script> </head> <body> <content-card subject="subject" content="Content"></content-card> </body> </html> A: With thanks of @fubar and @Zydnar I change Style of host and removed the margin: 20 auto and also add event.preventDefault() to mousedown event and lag decreased a lot and also unbinding problem fixed in the separate browser. (But it has still, the problem with code snippets) but it does not occur in the real page. I add some improvement to drag methods: 1- instead of setting elm.style.top and elm.style.left I used elm.style.transform =translate(${left}px,${top}px); 2- instead of using element.offsetLeft and element.offsetTop I used let rect = elm.getBoundingClientRect(); and rect,left and rect.top //drag-element.js function dragElement(elm) { const header = elm.Cardheader; header.style.cursor = "all-scroll"; let [initX, initY] = [0, 0]; let mousedown = false; let mousemoveEventHandler = function(e) { if (mousedown) { let top = e.clientY - initY || elm.top; let left = e.clientX - initX || elm.left; elm.style.transform = `translate(${left}px,${top}px)`; } }; let mousedownEventHandler = function(e) { e.preventDefault(); mousedown = true; header.onmousemove = mousemoveEventHandler; let rect = elm.getBoundingClientRect(); initX = e.clientX - rect.left; initY = e.clientY - rect.top; }; let mouseupEventHandler = function(e) { mousedown = false; header.onmousemove = null; }; document.addEventListener("mouseup", mouseupEventHandler); header.onmousedown = mousedownEventHandler; } //content-card.js class ContentCard extends HTMLElement { constructor() { super(); let shadow = this.attachShadow({ mode: "open" }); let style = document.createElement("style"); style.textContent = ` :host { position: absolute; background-color: #fff; backface-visibility: hidden; width: 50%; display: block; border: 1px solid #eee; box-shadow: 1px 1px 4px 1px #444; box-sizing: border-box; } .header { background-color: #eee; min-height: 20px; display: block; padding: 15px; } .body { min-height: 150px; display: block; padding: 15px; } `; this.Cardheader = document.createElement("div"); this.Cardheader.setAttribute("class", "header"); this.Cardbody = document.createElement("div"); this.Cardbody.setAttribute("class", "body"); this.Cardheader.textContent = this.getAttribute("subject"); this.Cardbody.innerHTML = this.getAttribute("content"); shadow.appendChild(this.Cardheader); shadow.appendChild(this.Cardbody); shadow.appendChild(style); } static get observedAttributes() { return ["subject", "content"]; } get subject() { return this.Cardheader.textContent; } set subject(val) { this.Cardheader.textContent = val; } get content() { return this.Cardbody.innerHTML; } set content(val) { this.Cardbody.innerHTML = val; } connectedCallback() {} disconnectedCallback() {} attributeChangedCallback(name, oldValue, newValue) { if (newValue === oldValue) return; switch (name) { case "subject": this.subjetct = newValue; break; case "content": this.content = newValue; break; default: break; } } adoptedCallback() {} } customElements.define("content-card", ContentCard); let cCard = new ContentCard(); document.body.appendChild(cCard); dragElement(cCard);
{ "pile_set_name": "StackExchange" }
Q: how to search about text between brackets using regular expression using java? Using Java How to search about text between bracket in an expression like that "Request ECUReset for [*11 01]" I want to extract "11 01" but I don't know exactly the length of the text between brackets. may be :"Request ECUReset for [*11 01]" or : "Request ECUReset for [*11]" or : "Request ECUReset for [*11 01 10]" or any length any help please ?? A: If the strings have a fixed format, String#substring() will suffice: Online demo here. public static void main(String[] args) { String input1 = "Request ECUReset for [*11 01]"; String output1 = input1.substring(input1.indexOf("[*")+"[*".length(), input1.indexOf("]", input1.indexOf("[*"))); System.out.println(input1 + " --> " + output1); String input2 = "Request ECUReset for [*11]"; String output2 = input2.substring(input2.indexOf("[*")+"[*".length(), input2.indexOf("]", input2.indexOf("[*"))); System.out.println(input2 + " --> " + output2); String input3 = "Request ECUReset for [*11 01 10]"; String output3 = input3.substring(input3.indexOf("[*")+"[*".length(), input3.indexOf("]", input3.indexOf("[*"))); System.out.println(input3 + " --> " + output3); } Output: Request ECUReset for [*11 01] --> 11 01 Request ECUReset for [*11] --> 11 Request ECUReset for [*11 01 10] --> 11 01 10 Or, if the input is less stable, you can use a Regex (through the utility Pattern class) to match the number between the brackets: Online demo here. import java.util.regex.*; public class PatternBracket { public static void main(String[] args) { String input1 = "Request ECUReset for [*11 01]"; String output1 = getBracketValue(input1); System.out.println(input1 + " --> " + output1); String input2 = "Request ECUReset for [*11]"; String output2 = getBracketValue(input2); System.out.println(input2 + " --> " + output2); String input3 = "Request ECUReset for [*11 01 10]"; String output3 = getBracketValue(input3); System.out.println(input3 + " --> " + output3); } private static String getBracketValue(String input) { Matcher m = Pattern.compile("(?<=\\[\\*)[^\\]]*(?=\\])").matcher(input); if (m.find()) { return m.group(); } return null; } } (same output as above)
{ "pile_set_name": "StackExchange" }
Q: divisibility of number of solutions of $x_1+\cdots+x_k=n$ I observed that the number of solutions in positive integers $x_1,\ldots,x_k$ of $$x_1+\cdots+x_k=n$$ for fixed $k$ and $n$ is always a multiple of $k$ as long as $\gcd(k,n)=1$. For example, $$6=2+1+1+1+1,$$ $$6=1+2+1+1+1,$$ $$6=1+1+2+1+1,$$ $$6=1+1+1+2+1,$$ $$6=1+1+1+1+2,$$ i.e. there are $5$ solutions. Is there any combinatorial rationale behind this? (i.e. combinatorial argument, e.g., via bars and stars?) A: Let $S$ be the set of all positive solutions of the equation $x_0+x_1+\cdots+x_{k-1}=n$. We show by a combinatorial argument, without even counting $S$, that if $k$ and $n$ are relatively prime, then $k$ divides the number of elements of $S$. We will say that two elements of $S$ belong to the same family if one is a cyclic permutation of the other. We show that if $k$ and $n$ are relatively prime, then each family has $k$ distinct members. From this it follows that $k$ divides the number of solutions. So we need to show that a non-trivial cyclic permutation of a solution yields a different solution. Let $A=(a_0,a_1,\dots,a_{k-1})$ be a solution, and consider the solution $A_t=(a_t,a_{t+1}, \dots, a_{t+k-1})$, where the indices are reduced modulo $k$. Suppose that for some $t$, with $1\le t\le k-1$, we have $A_t=A$. Then there is a smallest such $t$, and this $t$ divides $k$. Let $k=dt$. If $k\ne 1$, we have $d\gt 1$. Since $A_t=A$, we have $n=d(a_0+\cdots+a_{t-1})$. It follows that $d$ divides $n$, contradicting the fact that $k$ and $n$ are relatively prime. Remark: To visualize, imagine the numbers $a_0,a_1,\dots,a_{k-1}$ written around a circle. Two solutions belong to the same family if one can be obtained from the other by a rotation.
{ "pile_set_name": "StackExchange" }
Q: reduced image quality / sharpness when texture has opacity / alpha / transparency The output of Graphics3D looks blunt (polygon borders, arrow) when a polygon primitive is present in the scene with texture that has opacity channel. Also it seems that different kind of texture filtering is applied. I'm on Win10 and tested the code on 2 different PCs with GPUs from different vendors. I'm also interested in boosting the overall image quality like aliasing and texture filtering. Thank you! SeedRandom[0] imgData = RandomReal[1, {4, 5, 3}]; Image[imgData] Graphics3D[{{Texture[Image[imgData]], Polygon[{{-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}}, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}, {GraphicsComplex[{{1, 0, 2}, {0, 1, 2}, {-1, 0, 2}, {0, -1, 2}}, Polygon[{{1, 2, 3}, {3, 4, 1}}]]}, {Arrow[{{0, 0, 0}, {1, 1, 1}}]}}, Boxed -> False, Lighting -> "Neutral", ViewPoint -> {1/2, -2, 1}] Graphics3D[{{Texture[Image[Map[Append[#, 0.5] &, imgData, {2}]]], Polygon[{{-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}}, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}, {GraphicsComplex[{{1, 0, 2}, {0, 1, 2}, {-1, 0, 2}, {0, -1, 2}}, Polygon[{{1, 2, 3}, {3, 4, 1}}]]}, {Arrow[{{0, 0, 0}, {1, 1, 1}}]}}, Boxed -> False, Lighting -> "Neutral", ViewPoint -> {1/2, -2, 1}] A: Consider upgrading to version 12.1 which uses Direct3D 11 for 3D graphics rendering on Windows (version 12.0 used Direct3D 9): Windows 3D graphics rendering updated from Direct3D 9 to Direct3D 11 Here your scene is rendered in both versions on the same machine with Windows 10 (clickable!): As one can see, there is significant difference for the scene with opacity. For further improving try changing RenderingOptions. For example (output is rendered by version 12.1): g = Graphics3D[{{Texture[Image[Map[Append[#, 0.09] &, imgData, {2}]]], Polygon[{{-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}}, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}, {GraphicsComplex[{{1, 0, 2}, {0, 1, 2}, {-1, 0, 2}, {0, -1, 2}}, Polygon[{{1, 2, 3}, {3, 4, 1}}]]}, {Arrow[{{0, 0, 0}, {1, 1, 1}}]}}, Boxed -> False, Lighting -> "Neutral", ViewPoint -> {1/2, -2, 1}, ImageSize -> Medium]; {g, Style[#, RenderingOptions -> {"3DRenderingMethod" -> "BSPTree"}] &@g}
{ "pile_set_name": "StackExchange" }
Q: Relay Command not firing on menu item click My View <Button.ContextMenu> <ContextMenu x:Name="Conn_Context_button" Style="{StaticResource LeftContextMenuStyle}"> <MenuItem Style="{StaticResource LeftContextMenuItemStyle}" Header="{x:Static properties:ResourceWrapper.Dashboard_Connection_Delete}" Click="MenuItem_DeleteConnection_Click" /> <MenuItem Style="{StaticResource LeftContextMenuItemStyle}" Header="{x:Static properties:ResourceWrapper.Dashboard_Connection_Refresh}" Command="{Binding MyViewModel.RefreshCommand}" /> </ContextMenu> MyViewModel.cs public RelayCommand RefreshCommand { get; set; } RefreshCommand = new RelayCommand(RefreshConnection); private void RefreshConnection(object sender) { //My Logic } Here RefreshCommand is not firing when i click the refresh menu item A: As a good example, take a look to this situation. Here's a simple piece of code taken from one of my current projets: private void PrepareCommands() { RefreshCommand = new RelayCommand(RefreshCommandMethod); AddConfigurationCommand = new RelayCommand(AddConfigurationCommandMethod, param => CanAddConfiguration); EditConfigurationCommand = new RelayCommand(EditConfigurationCommandMethod, param => CanEditConfiguration); RemoveConfigurationCommand = new RelayCommand(RemoveConfigurationCommandMethod, param => CanRemoveConfiguration); } where the commands are #region Commands public ICommand AddConfigurationCommand { get; set; } public ICommand EditConfigurationCommand { get; set; } public ICommand RemoveConfigurationCommand { get; set; } public ICommand RefreshCommand { get; set; } #endregion Bindings are <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" DockPanel.Dock="Right"> <Button Template="{StaticResource AddButton}" Command="{Binding AddConfigurationCommand}" Margin="3,0" /> <Button Template="{StaticResource EditButton}" Command="{Binding EditConfigurationCommand}" Margin="3,0" /> <Button Template="{StaticResource DeleteButton}" Command="{Binding RemoveConfigurationCommand}" Margin="3,0" /> </StackPanel> As Jan Walczak said above, try to use ICommand instead of RelayCommand. If you have created your own RelayCommand, don't forget to inherit from ICommand.
{ "pile_set_name": "StackExchange" }
Q: Delphi 2010 - Verify if exist process and kill it whenever run How to verify if a process name (partial name e.g: notep* for notepad.exe) exist and create a loop to kill this process whenever run? In batch it's simple: :a taskkill -f -im notep* goto a Any help? A: You can use a asynchronous WMI event (like __InstanceCreationEvent) to detect when the a process is launched and the using the Win32_Process WMI Class and the Terminate method to kill the process. You can wrote a WQL sentence like this to detect the launch of any process strating with the "notep" string. Select * From __InstanceCreationEvent Within 1 Where TargetInstance ISA "Win32_Process" And TargetInstance.Name like "notep%" Try this sample {$APPTYPE CONSOLE} uses Windows, {$IF CompilerVersion > 18.5} Forms, {$IFEND} OleServer, SysUtils, ActiveX, ComObj, Variants; type TSWbemSinkOnObjectReady = procedure(ASender: TObject; const objWbemObject: OleVariant; const objWbemAsyncContext: OleVariant) of object; TSWbemSinkOnCompleted = procedure(ASender: TObject; iHResult: TOleEnum; const objWbemErrorObject: OleVariant; const objWbemAsyncContext: OleVariant) of object; TSWbemSinkOnProgress = procedure(ASender: TObject; iUpperBound: Integer; iCurrent: Integer; const strMessage: WideString; const objWbemAsyncContext: OleVariant) of object; TSWbemSinkOnObjectPut = procedure(ASender: TObject; const objWbemObjectPath: OleVariant; const objWbemAsyncContext: OleVariant) of object; ISWbemSink = interface(IDispatch) ['{75718C9F-F029-11D1-A1AC-00C04FB6C223}'] procedure Cancel; safecall; end; TSWbemSink = class(TOleServer) private FOnObjectReady: TSWbemSinkOnObjectReady; FOnCompleted: TSWbemSinkOnCompleted; FOnProgress: TSWbemSinkOnProgress; FOnObjectPut: TSWbemSinkOnObjectPut; FIntf: ISWbemSink; function GetDefaultInterface: ISWbemSink; protected procedure InitServerData; override; procedure InvokeEvent(DispID: TDispID; var Params: TVariantArray); override; public procedure Connect; override; procedure ConnectTo(svrIntf: ISWbemSink); procedure Disconnect; override; procedure Cancel; property DefaultInterface: ISWbemSink read GetDefaultInterface; published property OnObjectReady: TSWbemSinkOnObjectReady read FOnObjectReady write FOnObjectReady; property OnCompleted: TSWbemSinkOnCompleted read FOnCompleted write FOnCompleted; property OnProgress: TSWbemSinkOnProgress read FOnProgress write FOnProgress; property OnObjectPut: TSWbemSinkOnObjectPut read FOnObjectPut write FOnObjectPut; end; TWmiAsyncEvent = class private FWQL : string; FSink : TSWbemSink; FLocator : OleVariant; FServices : OleVariant; procedure EventReceived(ASender: TObject; const objWbemObject: OleVariant; const objWbemAsyncContext: OleVariant); public procedure Start; constructor Create; Destructor Destroy;override; end; { TSWbemSink } procedure TSWbemSink.Cancel; begin DefaultInterface.Cancel; end; procedure TSWbemSink.Connect; var punk: IUnknown; begin if FIntf = nil then begin punk := GetServer; ConnectEvents(punk); Fintf:= punk as ISWbemSink; end; end; procedure TSWbemSink.ConnectTo(svrIntf: ISWbemSink); begin Disconnect; FIntf := svrIntf; ConnectEvents(FIntf); end; procedure TSWbemSink.Disconnect; begin if Fintf <> nil then begin DisconnectEvents(FIntf); FIntf := nil; end; end; function TSWbemSink.GetDefaultInterface: ISWbemSink; begin if FIntf = nil then Connect; Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call "Connect" or "ConnectTo" before this operation'); Result := FIntf; end; procedure TSWbemSink.InitServerData; const CServerData: TServerData = ( ClassID: '{75718C9A-F029-11D1-A1AC-00C04FB6C223}'; IntfIID: '{75718C9F-F029-11D1-A1AC-00C04FB6C223}'; EventIID: '{75718CA0-F029-11D1-A1AC-00C04FB6C223}'; LicenseKey: nil; Version: 500); begin ServerData := @CServerData; end; procedure TSWbemSink.InvokeEvent(DispID: TDispID; var Params: TVariantArray); begin case DispID of -1: Exit; // DISPID_UNKNOWN 1: if Assigned(FOnObjectReady) then FOnObjectReady(Self, Params[0] {const ISWbemObject}, Params[1] {const ISWbemNamedValueSet}); 2: if Assigned(FOnCompleted) then FOnCompleted(Self, Params[0] {WbemErrorEnum}, Params[1] {const ISWbemObject}, Params[2] {const ISWbemNamedValueSet}); 3: if Assigned(FOnProgress) then FOnProgress(Self, Params[0] {Integer}, Params[1] {Integer}, Params[2] {const WideString}, Params[3] {const ISWbemNamedValueSet}); 4: if Assigned(FOnObjectPut) then FOnObjectPut(Self, Params[0] {const ISWbemObjectPath}, Params[1] {const ISWbemNamedValueSet}); end; {case DispID} end; //Detect when a key was pressed in the console window function KeyPressed:Boolean; var lpNumberOfEvents : DWORD; lpBuffer : TInputRecord; lpNumberOfEventsRead : DWORD; nStdHandle : THandle; begin Result:=false; nStdHandle := GetStdHandle(STD_INPUT_HANDLE); lpNumberOfEvents:=0; GetNumberOfConsoleInputEvents(nStdHandle,lpNumberOfEvents); if lpNumberOfEvents<> 0 then begin PeekConsoleInput(nStdHandle,lpBuffer,1,lpNumberOfEventsRead); if lpNumberOfEventsRead <> 0 then begin if lpBuffer.EventType = KEY_EVENT then begin if lpBuffer.Event.KeyEvent.bKeyDown then Result:=true else FlushConsoleInputBuffer(nStdHandle); end else FlushConsoleInputBuffer(nStdHandle); end; end; end; { TWmiAsyncEvent } constructor TWmiAsyncEvent.Create; const strServer ='localhost'; strNamespace ='root\CIMV2'; strUser =''; strPassword =''; begin inherited Create; CoInitializeEx(nil, COINIT_MULTITHREADED); FLocator := CreateOleObject('WbemScripting.SWbemLocator'); FServices := FLocator.ConnectServer(strServer, strNamespace, strUser, strPassword); FSink := TSWbemSink.Create(nil); FSink.OnObjectReady := EventReceived; FWQL:='Select * From __InstanceCreationEvent Within 1 '+ 'Where TargetInstance ISA "Win32_Process" And TargetInstance.Name like "notep%"'; end; destructor TWmiAsyncEvent.Destroy; begin if FSink<>nil then FSink.Cancel; FLocator :=Unassigned; FServices :=Unassigned; FSink.Free; CoUninitialize; inherited; end; procedure TWmiAsyncEvent.EventReceived(ASender: TObject; const objWbemObject: OleVariant; const objWbemAsyncContext: OleVariant); var PropVal: OLEVariant; FOutParams : OLEVariant; begin PropVal := objWbemObject; Writeln(Format('Detected Process %s Pid %d',[String(PropVal.TargetInstance.Name), Integer(PropVal.TargetInstance.ProcessId)])); Writeln('Killing'); FOutParams:=PropVal.TargetInstance.Terminate(VarEmpty); Writeln(Format('ReturnValue %s',[FOutParams])); end; procedure TWmiAsyncEvent.Start; begin Writeln('Listening events...Press Any key to exit'); FServices.ExecNotificationQueryAsync(FSink.DefaultInterface,FWQL,'WQL', 0); end; var AsyncEvent : TWmiAsyncEvent; begin try AsyncEvent:=TWmiAsyncEvent.Create; try AsyncEvent.Start; //The next loop is only necessary in this sample console sample app //In VCL forms Apps you don't need use a loop while not KeyPressed do begin {$IF CompilerVersion > 18.5} Sleep(100); Application.ProcessMessages; {$IFEND} end; finally AsyncEvent.Free; end; except on E:EOleException do Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode])); on E:Exception do Writeln(E.Classname, ':', E.Message); end; end. A: Enumerating running processes in Delphi will help with enumerating processes. When you find the one you're looking for, post a WM_QUIT message using SendMessageTimeout to give it a chance to close nicely, and if it doesn't use TerminateProcess to close it forcefully. If I was going to do something like this, I'd put the whole thing in a TThread so that it could do the scanning for processes in the background without interfering with the user interface of my application.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to set multiple column values on a single spatial query? I am associating attributes with points using PostGIS's ST_DWIthin(). UPDATE scratch.intersections AS i SET legs = ( SELECT COUNT(r.geom) FROM received.streets r WHERE ST_DWithin(i.geom, r.geom, 2)); UPDATE scratch.intersections AS i SET streets = ( SELECT ARRAY_AGG(DISTINCT r.NAME ORDER BY r.NAME) filter (WHERE r.NAME IS NOT NULL) FROM received.streets r WHERE ST_DWithin(i.geom, r.geom, 2)); Seems like it should be possible to update multiple columns with a single spatial query, but I can't think of a way to structure it since I can only update a single column at a time. Is there a way to turn these two queries into a single query, requiring only one spatial calculation? Would it be more efficient to do an INNER JOIN creating a new temp table with a record for each line within 2 of a point, and then set values off of that table? Describing it, it sounds less efficient since performance of ST_DWithin() isn't terrible using indexes. A: You can update multiple columns in one statement by enclosing them in parentheses UPDATE myTable SET (a,b) = ( select c,d from anotherTable WHERE st_dwithin(mytable.geom, anotherTable.geom,2) );
{ "pile_set_name": "StackExchange" }
Q: Not possible to update to Buildship v. 2.1.2.v20170807-1324 from v. 2.0.2.v20170420-0909 in Eclipse Oxygen 4.7.0 build 20170620-1800 I've a new installation of Eclipse Oxygen v. 4.7.0 build 20170620-1800 with the Spring Tool plugin v. 3.9.0.201707061730-RELEASE. I'm trying to update the Buildship from v. 2.0.2.v20170420-0909 to v. 2.1.2.v20170807-1324 (as noticed from the Eclipse update popup), but I've the error below: An error occurred while collecting items to be installed session context was:(profile=C__Users_Andrea_eclipse_jee-oxygen_eclipse, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=). No repository found containing: osgi.bundle,com.gradleware.tooling.client,0.19.3.v20170801075239 No repository found containing: osgi.bundle,com.gradleware.tooling.model,0.19.3.v20170801075239 No repository found containing: osgi.bundle,com.gradleware.tooling.utils,0.19.3.v20170801075239 No repository found containing: osgi.bundle,org.eclipse.buildship.branding,2.1.2.v20170807-1324 No repository found containing: osgi.bundle,org.eclipse.buildship.core,2.1.2.v20170807-1324 No repository found containing: osgi.bundle,org.eclipse.buildship.stsmigration,2.1.2.v20170807-1324 No repository found containing: osgi.bundle,org.eclipse.buildship.ui,2.1.2.v20170807-1324 No repository found containing: osgi.bundle,org.gradle.toolingapi,3.5.0.v20170801075239 No repository found containing: org.eclipse.update.feature,org.eclipse.buildship,2.1.2.v20170807-1324 Thanks a lot, Regards, Andrea A: Looks like it isn't buildship, but an Eclipse bug. FWIW, I followed the instructions to: Go into Preferences > Install/Update -> Available Software sites Uncheck Buildship Open Marketplace and find Buildship 2.0 Click on greyed-out Install button Click on enabled Update button Not sure what the last two steps were all about, but after the update and a restart Buildship is re-enabled in Prefs and it appears to be updated successfully.
{ "pile_set_name": "StackExchange" }
Q: Scraping with casperjs -- Not sure how to handle empty div I'm using casperjs to scrape a site. I setup a function which stores a string into a variable named images (shown below) and it works great. images = casper.getElementsAttribute('.search-product-image','src'); I then call that variable in fs so I can export it to a CSV, which also works fine. casper.then(function() { var f = fs.open('e36v10.csv', 'w'); f.write(imagessplit + String.fromCharCode(13)); f.close(); }); The issue I just noticed is that not all products have images, so when the scraper hits a product without an image it passes by it obviously. I need it to at least alert me somehow (something as simple as filler text thats says, "no image here") when it passes by a product without an image because what I do is I copy that string (along with may other strings) and organize them into columns within the CSV and it messes up the order of everything without having some sort of filler text ("no image here"). Thanks Edit Below is the exact source from the website I am trying to pull from. A product I can get the image from and my code works fine: <div class="search-v4-product-image"> <img alt="238692" class="search-product-image" src="http://d5otzd52uv6zz.cloudfront.net/group.jpg"> <p class="image-overlay">Generic</p> </div> A product with no image and my scraper passes right by it without alerting me. <div class="search-v4-product-image">&nbsp;</div> A: You can write this functionality for the page context this way: casper.then(function(){ var imgList = this.evaluate(function(){ var productImages = document.querySelectorAll("div.search-v4-product-image"), imageList = []; Array.prototype.forEach.call(productImages, function(div){ if (div.children.length == 0) { imageList.push({empty: true}); } else { var img = div.children[0]; // assumes that the image is the first child imageList.push({empty: false, src: img.src}); } }); return imageList; }); var csv = ""; imgList.forEach(function(img){ if (img.empty) { csv += ";empty"; } else { csv += img.src+";"; } }); fs.write('e36v10.csv', csv, 'w'); }); This iterates over all divs and pushes the src to an array. You can check the empty property for every element. I suspect that the output would be more meaningful if you iterate over all product divs and check it this way. Because then you can also write the product name to the csv. You could use CSS selectors but then you would need make the :nth-child selection much higher in the hierarchy (product div list). This is because :nth-child only works based on its parent and not over the whole tree.
{ "pile_set_name": "StackExchange" }
Q: @Transactional not working with readOnly = true I have following code, where I am setting @Transactional(readOnly = true). Code in main method. ApplicationContext context = Utils.getContext(); AnnotatedCrudDao service = new AnnotatedCrudDao(); DataSource dataSource = (DataSource) context.getBean("mySqlDataSource"); service.setDataSource(dataSource); service.insert(account, user, movie); @Transactional public class AnnotatedCrudDao extends JdbcDaoSupport { private static Logger logger; static { logger = Logger.getLogger(AnnotatedCrudDao.class); } @Transactional(readOnly = true) public void insert(Account account, User user, MovieTicket movie) { TicketUtils.insertAccount(getJdbcTemplate(), account); TicketUtils.insertUser(getJdbcTemplate(), user); TicketUtils.insertMovie(getJdbcTemplate(), movie); } } class TicketUtils{ public static void insertUser(JdbcTemplate template, User user) { String queryUser = "INSERT INTO t_user_txn (ID, NAME, ACCOUNT_ID, TICKETID) VALUES (?,?,?,?)"; logger.debug("queryUser" + queryUser); template.update(queryUser, new Object[] { user.getId(), user.getName(), user.getAccount().getId(), user.getTicketId() }); } public static void insertMovie(JdbcTemplate template, MovieTicket movie) { String queryMovie = "INSERT INTO t_movieticket_txn (ID, MOVIENAME, TOTALTICKETSCOUNT, PRICE) VALUES (?,?,?,?)"; logger.debug("queryMovie:" + queryMovie); template.update(queryMovie, new Object[] { movie.getId(), movie.getMovieName(), movie.getTotalTicketsCount(), movie.getPrice() }); } public static void insertAccount(JdbcTemplate template, Account account) { String queryAccount = "INSERT INTO t_account_txn (ID, AMOUNT) VALUES (?,?)"; logger.debug("queryAccount:" + queryAccount); template.update(queryAccount, new Object[] { account.getId(), account.getAmount() }); } } context <bean id="mySqlDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@localhost:1521:qadb7"/> <property name="username" value="tp2"/> <property name="password" value="tp2"/> </bean> <bean id="dsTxnMgr" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="mySqlDataSource" /> </bean> <!-- Add this tag to enable annotations transactions --> <tx:annotation-driven transaction-manager="dsTxnMgr" /> Even thought I have set @Transactional(readOnly = true) for insert method, still the insert operation is being performed. Should not the attribute readOnly, which is set to true should take care that insert cannot be performed on this method. A: A couple of things You are creating your own instance of the dao, this isn't spring managed and therefor nothing is being done with the @Transactional annotation. readonly="true" enforces nothing don't expect an exception to be thrown or inserts not to happen, very few jdbc providers actually do something with the readOnly flag. It is merely a hint to the underlying system nothing more nothing less. In general it is used and understood by ORM tools like Hibernate and the like. But for plain JDBC access in the majority of cases it is simply ignored.
{ "pile_set_name": "StackExchange" }
Q: Using Website Information Without WebView I am very new to this, and I more looking for what information I need to study to be able to accomplish this. What I want to do is use my GUI I have built for my app, but pull the information from a website. If I have a website that looks like this: (full website can be seen at http://www.atmequipment.com/Error-Codes) What would I need from the website so that if a user entered an error code here: It would use the search from the website, and populate the error description in my app? I know this is a huge question, I'm just looking for what is actually needed to accomplish this, and then I can start researching from there. -- Or is it even possible? A: What you're going to need is some kind of a web services api on the server you want to search. Then you can post http requests to send and receive information from the server.
{ "pile_set_name": "StackExchange" }
Q: Defining 2D array inside class of Perl I am new to Perl and I am trying to define a 2D array as an attribute of my class in Perl. I define my class as follows, sub new{ my $class = shift; my $self = {}; my @board = []; for (my $i = 0; $i < 8; $i++){ for(my $j = 0; $j < 8; $j++){ $board[$i][$j] = '.'; } } $self->{board} = @board; bless($self, $class); return $self; } But later on when I try to access the board field like this $self->{board}[$i][$j] = ' '; I got an error saying Can't use string ("8") as an ARRAY ref while "strict refs" in use Can anyone tell me what is the correct way of doing this? I do not want to just delete use strict. A: I changed your code to what I'm sure was your intention, see the lines changed and comment # not sub new{ my $class = shift; my $self = {}; my @board = (); # not [] for (my $i = 0; $i < 8; $i++){ for(my $j = 0; $j < 8; $j++){ $board[$i][$j] = '.'; } } $self->{board} = \@board; # not @board bless($self, $class); return $self; } or sub new{ my $class = shift; my $self = {}; my $board = []; # not @board for (my $i = 0; $i < 8; $i++){ for(my $j = 0; $j < 8; $j++){ $board->[$i][$j] = '.'; } } $self->{board} = $board; # not @board bless($self, $class); return $self; } about your my @board=[]; is the same as =([],); assign a list (that perl calls ARRAY) whose first element is a reference to an ARRAY to @board, but this is neither what make your code fail because you overwrite this empty array reference allocation and assignment to position zero. The @board is a list not a reference to it as $self->{board} expect
{ "pile_set_name": "StackExchange" }
Q: Kendo ui datepicker in inline editing grid Since Our database is using AUS format date not US Format. I have added this in my cshtml page, but it is not working since when it pass to the controller it still get the US Date format. Please advise <script type="text/javascript" src="@Url.Content("~/Scripts/kendo/cultures/kendo.culture.en-AU.min.js")" ></script> <script> kendo.culture("en-AU"); </script> A: I think this is working correct. You don't need to use same format as in client side to server side. If it is converting correctly to the server side culture then you are ok. And when you are going to display the date in the ui kendo will format that value to correct culture again.
{ "pile_set_name": "StackExchange" }
Q: Listbox Help wanted (simple script) I am not an expert but try to figure it out about ~6 hours now, I have a selection window with 2 items, and whatever what i choose it say i choose No1 item. Later on i replace nr1, nr2, with actions if the selections could working. Please help! I assume i use wrong code at MyListbox1. Gui, Add, ListBox, vMyListBox1 gMyListBox1 w100 r10 { GuiControl,, MyListBox1, Item1|Item2 } Gui, Show return MyListBox1: if A_GuiEvent <> DoubleClick return GuiControlGet, MyListBox1, %Item1% GuiControlGet, MyListBox1, %Item2% IfMsgBox, %Item1% MsgBox, MsgBox You entered 1 return IfMsgBox, %Item2% MsgBox, MsgBox You entered 2 Return GuiClose: GuiEscape: ExitApp A: Like this? Gui, Add, ListBox, vMyListBox1 gMyListBox1 w100 r10, NotePad|x Gui, Show return MyListBox1: if A_GuiEvent <> DoubleClick ; If not double click stop Return GuiControlGet, MyListBox1 ; Get current value of MyListBox1 variable If (MyListBox1 = "NotePad") ; If MyListBox1 contains NotePad Run, NotePad.exe Else If (MyListBox1 = "x") ; If MyListBox1 contains x { Send, !{Esc} ; Need to switch back to previous application since GUI is in focus and you would send the data to your own GUI Sleep, 100 ; Wait a little while, so that the other application can be in focus Send, x ; You could have used Send, %MyListBox1%, since MyListBox1 contains x } Return GuiClose: GuiEscape: ExitApp
{ "pile_set_name": "StackExchange" }
Q: Is it possible to have "Perfect Tempo" Perfect pitch is an acknowledged musical skill - the ability to hear a note and name it. Is there a corresponding skill that applies to tempo, to be able to hear music playing and say precisely what the bpm is? For people claiming this skill, what level of accuracy is possible? A: I know a professional conductor who can pretty much nail it right on. It's just like perfect pitch, in that it's something you learn to do by being exposed to a ton of music and having reference points ingrained in your memory through sheer repetition. They're not magical skills that you're born with and either have or don't have. You can probably find 120 pretty accurately, since it's march tempo. Just sing Stars and Stripes Forever or Washington Post. You can probably sing your favorite songs extremely close to their original tempo, so now it's just a matter of looking up what that tempo is to develop another reference point. Then you just keep going. A: I've worked with quite a few dance band drummers who hit the correct tempo for particular dances - and believe me, serious dancers can tell if it's not right! It's sort of the opposite of what the OP is asking, but could very easily work the other way round. Basically, it's experience, the more you do it, the more consistently right it gets. Having said that, most people seem to be capable of singing/playing well-known songs at the recorded tempo, so if one knew a song at, say, 100b.p.m., it should be possible to judge another tempo from this reference point. More like relative pitch. A: By coincidence, in last week's Boston Symphony program book (for Thursday November 12 through Saturday November 14) it says of Bela Bartok that "He was equipped with an uncannily accurate inner clock and he could tell when music marked to be played at metronome 112 was in fact going at 111 or 113." I don't know if that is true or not. His piano pieces have a metronome marking at the top and a timing in minutes and seconds at the end and they never match up.
{ "pile_set_name": "StackExchange" }
Q: Is there minimum clearance from gas stove to door? I know there is a minimum clearance to hood and cabinets above, but I can't find a side-clearance to a doorway. My concern is someone coming through the door and not seeing the hot stove around the corner. Edit: it's an interior door. I'm not concerned with drafts, I'm concerned with safety. A: There is no code requirement in the IRC specifying minimum distance between stove and doorway. Doesn’t make it a good idea, but it’s not banned. http://www.inspectionnews.net/home_inspection/built-in-appliances-and-systems-home-inspection-and-commercial-inspection/21577-range-distance-door.html
{ "pile_set_name": "StackExchange" }
Q: Most efficient method to detect color using OpenCV? I setup an area of interest somewhere near the center of my image using: Mat frame; //frame has been initialized as a frame from a camera input Rect roi= cvRect(frame.cols*.45, frame.rows*.45, 10, 8); image_roi= frame(roi); //I stoped here not knowing what to do next I'm using a camera and at any time when I grab a frame, the ROI will be anywhere between 30% to 100% filled with my desired color, which is Red in this case. What is the most efficient method to know if Red is present in my current frame? Solution: image_roi= frame(roi);// a frame from my camera as a cv::Mat cvtColor(image_roi, image_roi, CV_BGR2HSV); thrs= new Mat(image_roi.rows, image_roi.cols, CV_8UC1);//allocate space for new img inRange(image_roi, Scalar(0,100,100), Scalar(12,255,255), *thrs);//do hsv thresholding for red for(int i= 0; i < thrs->rows; i++)//sum up { for(int j=0; j < thrs->cols; j++) { sum= sum+ thrs->data[(thrs->rows)* i + j]; } } if(sum> 100)//my application only cares about red cout<<"Red"<<endl; else cout<<"White"<<endl; sum=0; A: This solution should address not only red but any color distribution: Get a color histogram for your ROI, a bidimensional hue and saturation histogram (follow the example here). Use calcBackProject to project the histogram back in the full image. You will get larger values in pixels presenting a color near the modes of the histogram (in this case, reds). Threshold the result to get the pixels that better match the distribution (in this case, the "best reds"). This solution can be used, for example, to get a simple but very functional skin detector. A: I'm assuming you just want to know the percentage of red in the ROI. If that's not correct, please clarify. I'd scan the ROI and convert each pixel into a better color space for color comparison, such as YCbCr, or HSV. I'd then count the number of pixels where the hue is within some delta of red's hue (usually 0 degrees on the color wheel). You might need to deal with some edge cases where the brightness or saturation are too low for a human to think they're red, even though technically they are, depending on what you're trying to achieve.
{ "pile_set_name": "StackExchange" }
Q: Delete ClearCase Views Script (This is a repost of a deleted question) (on request) What is the best ClearCase View deletion Script? I found the following on http://www.cmcrossroads.com/forums?func=view&id=44045&catid=31 written by Yossi Sidi below The 2 things this script misses are the deletion of the entries in the session.dat file for CCRC views and the cleaning of server view storage and cached file directories. The manual steps can be found here: http://www-01.ibm.com/support/docview.wss?uid=swg21172246 rmview.pl ============== # # rmview.pl # # This script is used to delete a view.. # --------------------------------------------------- # Fetching the UUID of the view : # Cleartool describe -long vob:vob_name (lists all views) # -or- # cleartool lsview -long <View_name> # ------------------------------------------------------------------------ # Remove sequence:- # Cleartool rmview -force -uuid <uuid> (from a VIEW contents directory) # Cleartool unreg -view -uuid <uuid> # Cleartool rmtag -view VIEW_NAME # # Arguments: # view tag name : # # ASSUMED: You must be in a VOB with a view set when this tool # is used. # # Author: Yossi Sidi # email: [email protected] # URL: [url=http://www.corrigent.com" target="_blank]http://www.corrigent.com[/url] # Date: Sep. 14, 2003 ############################################################ # History: 14/10/03 : Created for Corrigent ############################################################ ######################## ######## MAIN ########---------------------------------------------------------------- ######################## $DIV1="*************************************************************n"; $USAGE=""USAGE ccperl.exe $0 view tag name \n EXAMPLE: ccperl.exe $0 ""My_view"" ""; if ($#ARGV == 0) { $view_name = $ARGV[0]; } else { `clearprompt yes_no -mask abort -default abort -pre -prompt $USAGE`; exit 1; } select STDOUT; $| = 1; # Do not buffer the STDOUT file so ccperl prog.pl >out.txt # will have the correct sequence of report lines printf ($DIV1); printf ("View Propertiesn"); printf (" View Tag: $view_namen"); printf ($DIV1); printf ("n"); $COMMAND = "cleartool lsview -l $view_name"; @dl = `"$COMMAND"`; $view_uuid = ""; foreach $dl (@dl) { chomp ($dl); printf ("$dln"); if ( $dl =~ /^View uuid: / ) { $view_uuid = $'; #' reset syntax highlighter } } if ( $#dl > 0 ) { # Cleartool rmview -force -all -uuid <uuid> (from a VIEW contents directory) # Cleartool unreg -view -uuid <uuid> # Cleartool rmtag -view VIEW_NAME $rmview = "cleartool rmview -force -all -uuid $view_uuid"; $unreg = "cleartool unreg -view -uuid $view_uuid"; $rmtag = "cleartool rmtag -view $view_name"; printf ($DIV1); printf ("Removing commandsn"); printf ($DIV1); printf ("n"); printf ("n$rmview n"); @dl = `"$rmview"`; printf ("n$unreg n"); @dl = `"$unreg"`; printf ("n$rmtag n"); @dl = `"$rmtag"`; } exit 0; (hmmm... interesting here is that the stackoverflow colorcoding goes wild after Perl's $' .... mini bug) A: I mentioned a script a little bit verbose, but which won't remove any local storage and won't either clean the CCRC session.dat: nuke_view.pl: you can use it to remove all views from a workstation (which may not be available anymore) cleartool lsview -host myHostname -quick | xargs ccperl nuke_view.pl The -quick option is very important to quickly get the list of views for a given workstation. ## This script should be used to cleanup a view when 'ct rmview' will not ## work (such as when the viewstore directory has been deleted. ## ## Note: The view storage directory will have to manually deleted if it still exists. use strict; #sub NukeView(); #sub DoIt(); foreach(@ARGV) { NukeView($_); } ############################################################## sub NukeView { my $view2del = $_[0]; print "Processing $view2del...\n"; my @lines = `cleartool lsview -l $view2del`; my $tag; my $uuid; foreach(@lines) { chomp; $tag = $1 if /^Tag: (\S+)/; $uuid = $1 if /^View uuid: (\S+)/; s/^/\t/; print "$_\n"; } if ( $tag eq '' or $uuid eq '' ) { print "Error! $view2del: unable to get tag and/or uuid\n"; return 0; } my $err_count = 0; print "\tremoving tag...\n"; my $cmd = "cleartool rmtag -view $tag"; $err_count += 1 if DoIt($cmd); print "\tunregistering view storage...\n"; $cmd = "cleartool unreg -view -uuid $uuid"; $err_count += 1 if DoIt($cmd); print "\tremoving view references...\n"; $cmd = "cleartool rmview -force -avobs -uuid $uuid"; $err_count += 1 if DoIt($cmd); if ( $err_count == 0 ) { print "Success! removed view $view2del\n"; } else { print "Error! errors occured while removing $view2del\n"; } } ############################################# sub DoIt { my $ret = system($_[0]) / 256; print "Error! cmd failed: $_[0]\n" if $ret != 0; return $ret; } The extra steps needed for removing CCWeb Views are described in this IBM technote: Note: For ClearCase 7.1.1.1 or 7.1.1.2 the session.dat file is no longer generated from ClearCase 7.1.1.1 as a result of APAR PM03334: session.dat no longer need to be cleaned. Remove the view storage and cached files stored on CCWeb server. By default, view.stg (CCRC / CCWeb view storage), view.dat and VOB's cached files are stored in the following location: Windows®: C:\Program Files\Rational\ClearCase\var\ccweb\<user>\<view_tag> UNIX® / Linux®: /var/adm/rational/clearcase/ccweb/<user>/<view_tag> Remove the <view_tag> folder located in the location above. This will remove view's storage files, view.dat and VOB's cached files and will let the user create a new view using the same / original view's name. Note: It may also be necessary to manually remove the view workspace if the view is still present on the CCRC client. This can done by navigating to the defined workspace on the client system (by default C:\Documents and Settings\<user-name>\view_tag) and removing the view workspace. This path to the workspace is listed in the session .dat file. The entry looks like this: -workroot "c:/web_dev2". This may become useful in a case where the user did not use the default location. CCRC view roots are also cached in a file on the client in the User Profile. Check the following file and remove the already removed view from that list as well. C:\Documents and Settings\<user-name>\.ccase_wvreg
{ "pile_set_name": "StackExchange" }
Q: MySQL LIKE Statement and PHP Variable I need my following code to work. I am trying to use a PHP Variable and also add a [charlist] Wildcard statement to it Could some one please help figure out why it wont work. Basically it works if i remove the [charlist] Wildcard but I need it to find all the letters which are in the PHP Variable my code is as followed LIKE ''[' $searchWord ']%'' A: To use a character class, you need to use the REGEXP operator. Additionally, after a character class, you need to indicate a repetition operator. % matches any string (and is only for LIKE), but if you want to apply it so that it will match any series of letters contained within your character class, you need to do: $query = '`column` REGEXP "[' . $searchWord . ']+"'; Alternatively, use a * to match 0 or more. (+ is 1 or more)
{ "pile_set_name": "StackExchange" }
Q: How to describe a way of something? I know that when you attach ~方 (kata) to something (like a verb or noun), it means the way of... But how would you describe the way of something? For example, if I wanted to say that "there are many easy ways to cook onigiri", would たくさん簡単なおにぎりを料理する方があった work? I'm not really sure about this sentence because it seems kinda off, but I can't tell what. A: There are several ways to express that. The two most basic ones: 方 which you already pointed out, but it should be attached to the -masu stem of the verb, so formally し方 not する方 (which would mean "a person who does something"). But again, し方 is rarely used, it's more common to use やり方 or a more specific verb. For your example sentence, the most natural would be probably 作り方. a more formal noun 方法{ほうほう} which attaches to the infinitive form of the verb ~する方法 or the noun ~の方法 But there are more problems with the example sentence than just this expression (including the English "to cook onigiri" which sounds odd, because in whatever form, you don't really cook it): you should attach たくさん and 簡単な to the "way" not to the "onigiri" を料理する doesn't fit here, as stands more for "make foot out of something" for a general statement (without stressing or comparison) you would use は instead of が あった is a past tense, but you are describing a general, present situation おにぎりの簡単な作り{つくり}方{かた}はたくさんある
{ "pile_set_name": "StackExchange" }
Q: Would UK visa/entry problems affect getting a visa for other countries? Long story short. Unfortunately, I was removed from the UK by the authorities. I understand that there is definitely going to be a ban on me to the UK. Am I liable to get visa from other countries denied on the basis of that ban (such as New Zealand, Canada or the USA)? My main concern is to find out whether New Zealand would ban me since my fiance is from New Zealand. Is there going to be an issue in getting a NZ visa because of a possible ban from the UK? A: All of the countries you've listed require that you disclose your immigration history, including removals, refusals, and bans. Not doing so is a bad idea, and can result in visa denials, refusals, bans. New Zealand is the same: you have to reveal your UK history and removal or risk not being issued a visa. You noted on SETravel that you do not have a fiance in New Zealand but, rather, there is an individual who may be willing to marry. Culturally arranged marriage visas are issued by New Zealand. New Zealand Immigration requires that you submit your passport (which may show the UK removal) and demonstrate your character (provide a Police Certificate from your home country, as well as from any country in which you lived for a year or more; that would include the UK). You also have to prove that you've met (as well as her immigration status, among other things). Is she planning to meet you outside of New Zealand? For your broad question, whether information is shared among countries such as the UK, Canada, the US, New Zealand, Australia, the answer is yes: all of these countries share intelligence information. No one knows what, or how much. Is immigration information shared? Who knows? Could be, but the bottom line is don't let that affect where you apply for a visa, or what you do or don't include in an application. Failing to disclose the facts, lying may result in visa refusals and can mean that you're not going anywhere for a long time.
{ "pile_set_name": "StackExchange" }
Q: Equilibrium point differential equation I am looking at the equilibrium points of the following system: $$ X' = a_1 X - a_2 X^2 -a_3 XY \\ Y' = \beta a_3YX-a_4Y-a_5Y^2 $$ I found the following $(X,Y)$ equilibrium points $(0,0); \ (\frac {a_1}{a_2},0 ); \ (0,-\frac{a_4}{a_5})$ but I can not find the 4th equilibrium point when both $X\ne 0$ and $Y \ne 0$. I get lost in computation and cant find the solution. A: From $0 = a_1 X - a_2 X^2 -a_3 XY \\ 0 = \beta a_3XY-a_4Y-a_5Y^2$ we get $a_3XY=a_1X-a_2X^2$. Use the second equation to derive $0=X(\beta a_1- \beta a_2 X)-Y(a_4+a_5Y)$ Now it is easy to see that $(\frac {a_1}{a_2},- \frac {a_4}{a_5})$ is an equilibrium point.
{ "pile_set_name": "StackExchange" }
Q: Force use WAN for internet even if LAN is connected? I have two CPEs. One fast 4G CPE (High Speed, 150 GB/m and one slow 3G CPE (2 MBPS,U/L) Primary 4G CPE which is basically my primary high-speed internet access is shared through a router and switch for LAN connections. Pi's ethernet is connected to this network. I access Plex, Sonarr, Deluge installed on Pi through the wired network backed by high-speed 4G CPE. I have another secondary 3G CPE (wireless only, no ethernet port) which is slow but has unlimited download. Pi's WiFi is connected to this other slow 3G CPE. My use case is I have to download using Secondary Wireless only 3G CPE and use Pi's LAN(backed by 4G CPE) only to access home network and Plex etc. Scenario 1 - When I connect both WAN and LAN, Pi connects to internet through LAN only. Scenario 2 - When I connect to LAN and WAN but disable internet using LAN from Router, the internet doesn't work. Pi doesn't use WAN internet when LAN is connected even if it doesn't have internet access Scenario 3 - I download stuff by running sudo ifconfig eth0 down so Pi has only WiFI and it downloads from slow 3G Network Scenario I want - Connected to LAN with internet access disabled from Router and only have home network access. Connected to WAN and used to access internet through 3G CPE. How Do I achieve this? A: This is a simple routing problem. You can route local traffic through eth0 and route all other traffic to the internet through wlan0 by setting the default route to this interface. For example I use these ip addresses on the RasPi: rpi ~$ ip -4 -brief addr lo UNKNOWN 127.0.0.1/8 eth0 UP 192.168.50.246/24 wlan0 UP 192.168.30.117/24 The unmodified routing table for this looks: rpi ~$ ip route default via 192.168.50.1 dev eth0 proto dhcp src 192.168.50.246 metric 202 default via 192.168.30.1 dev wlan0 proto dhcp src 192.168.30.117 metric 303 192.168.30.0/24 dev wlan0 proto dhcp scope link src 192.168.30.117 metric 303 192.168.50.0/24 dev eth0 proto dhcp scope link src 192.168.50.246 metric 202 You have two default routes. This is what you makes your problems. The kernel can only use one, of course. It uses the one with the lowest metric and that is the route through eth0 with metric 202. All traffic to the internet (destination ip addresses not belonging to local networks -> default route) goes through eth0 but there is no internet. If you shutdown interface eth0 then also its default route is deleted and the route with lower metric is used. That's the connection through wlan0 and there you find the internet. To fix this just delete the wrong default route: rpi ~$ sudo ip route del default via 192.168.50.1 dev eth0 If you use Raspbian default dhcpcd networking you can make it persistent by adding this to /etc/dhcpcd.conf: interface eth0 nogateway If using systemd-networkd you have to modify the .network file in /etc/systemd/network/ that matches the interface eth0 (section [Match]). There you have to add this if you use DHCP on this interface: [DHCP] UseRoutes=no If you defined a static ip address there then just omit the Gateway= option in section [Network].
{ "pile_set_name": "StackExchange" }
Q: Modify a line in a file located in the AppData folder of all users on a computer I would like to modify a line in a file located in the AppData folder of all users on a computer. The line to be changed in the prefs.js file begins with: user_pref("mail.server.server1.directory", "C:\\Users\ I would replace the entire line: user_pref("mail.server.server1.directory", "C:\\ Thunderbird Mail\\Local Folders") I am doing this in each user profile. I started a script, but it does not work: $configFiles = Get-ChildItem C:\users\*\appdata prefs.js -rec $ligne1 = 'user_pref("mail.server.server1.directory", "C:\\Users\' $ligne2 = 'user_pref("mail.server.server1.directory", "C:\\Thunderbird\\Mail\\Local Folders");' foreach ($file in $configFiles) { (Get-Content $file.PSPath) | ForEach-Object { $_ -replace $ligne1.+, $ligne2 } | Set-Content $file.PSPath } A: The -replace operator does regular expression replacements, so you need to escape special characters in your match string ($ligne1), particularly the backslashes and parentheses. Replace this: (Get-Content $file.PSPath) | ForEach-Object { $_ -replace $ligne1.+, $ligne2 } | Set-Content $file.PSPath with this: (Get-Content $file.FullName) -replace ([regex]::Escape($ligne1) + '.+'), $ligne2 | Set-Content $file.FullName and the problem will disappear.
{ "pile_set_name": "StackExchange" }
Q: ¿Por qué no está funcionando el método stopListening()? Android Java Veréis, tengo en mi aplicación un botón para que se pueda transcribir de voz lo que queramos decir. El problema es que he creado un contador en el botón para que cuando pulse el botón nuevamente, pare de escuchar, pero no funciona: public class MainActivity extends AppCompatActivity { private static final int MY_PERMISSIONS_RECORD_AUDIO = 1; int count = 0; SpeechRecognizer mSpeechRecognizer; Intent mSpeechRecognizerIntent; @BindView(R.id.etBeforeTranslate) EditText etBeforeTranslate; @BindView(R.id.ivLogo) ImageView ivLogo; @BindView(R.id.btnTranslate) Button btnTranslate; @BindView(R.id.btnVoice) ImageButton btnVoice; private DatabaseReference Translates; public String removeAccents() {...} public String textTranslate() {...} public void registerTranslates() {...} private void checkPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { //When permission is not granted by user, show them message why this permission is needed. if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) { //Give user option to still opt-in the permissions ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_RECORD_AUDIO); } else { // Show user dialog to grant permission to record audio ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_RECORD_AUDIO); } } //If permission is granted, then go ahead recording audio else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) { //Go ahead with recording audio now speechToText(); } } private void speechToText() { mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this); mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); mSpeechRecognizer.setRecognitionListener(new RecognitionListener() { @Override public void onReadyForSpeech(Bundle params) { } @Override public void onBeginningOfSpeech() { } @Override public void onRmsChanged(float rmsdB) { } @Override public void onBufferReceived(byte[] buffer) { } @Override public void onEndOfSpeech() { } @Override public void onError(int error) { } @Override public void onResults(Bundle results) { ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); if (matches != null) { etBeforeTranslate.setText(matches.get(0)); } } @Override public void onPartialResults(Bundle partialResults) { } @Override public void onEvent(int eventType, Bundle params) { } }); mSpeechRecognizer.startListening(mSpeechRecognizerIntent); count = 1; } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_RECORD_AUDIO: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! speechToText(); } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(this, "Vaya, pues te quedas sin hablarme", Toast.LENGTH_LONG).show(); } return; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); btnVoice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (count == 0) { checkPermission(); speechToText(); } else if (count == 1) { mSpeechRecognizer.stopListening(); etBeforeTranslate.setText("holi"); } } }); btnTranslate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String texto = textTranslate(); if (etBeforeTranslate.getText().toString().trim().isEmpty()) { ivLogo.setImageResource(R.drawable.logotipoangry); Toast.makeText(MainActivity.this, "¡Ay que agobio! Intridici il tixti, anda", Toast.LENGTH_SHORT).show(); } else { Translates = FirebaseDatabase.getInstance().getReference("Translates"); registerTranslates(); ivLogo.setImageResource(R.drawable.logotipo); Intent intent = new Intent(MainActivity.this, TranslateActivity.class); intent.putExtra("texto", texto); startActivity(intent); } } }); } } El texto que metí era para comprobar que me lo mostrara para ver que se estaba realizando y efectivamente cambia, me lo muestra, es decir que entra, pero que va, no me salta el sonido como que ha parado de escuchar y ya no se si es problema de mi aplicación o de terceros, ya que leí en respuestas de hace años que no iba bien ese servicio, pero supongo que con el paso de los años se solucionó. A ver si me podéis echar una mano, muchas gracias :) A: Como lo mencionas, hace tiempo se tenía un "bug" en SpeechRecognizer.stopListening() el cual fue "solucionado", a mi parecer fue en realidad el uso incorrecto de este método. Si en realidad si deseas terminar el servicio de reconocimiento de voz, realizalo mediante: mSpeechRecognizer.cancel(); mSpeechRecognizer.destroy(); Por cierto es buena práctica liberar recursos, realizando el mismo llamado en el método onDestroy() de tu Activity: @Override protected void onDestroy() { super.onDestroy(); //libera recursos. if(mSpeechRecognizer != null){ mSpeechRecognizer.cancel(); mSpeechRecognizer.destroy(); } } .cancel() Termina el servicio de reconocimiento de voz. .destroy() Destruye el objeto SpeechRecognizer.
{ "pile_set_name": "StackExchange" }
Q: How to load related entity of external data source in Lightswitch (Visual Studio 2013) I have 2 tables which are both in an Azure SQL Database which is connected to my Lightswitch Sharepoint app. I am doing some manipulation of the data in code, and it appears to be working, except that when I load the entities from one table, I am not able to see the related entities in the other. Basically, I have a products table and an invoice lines table. Each invoice line record contains a product code, which relates to the products table PK. I have defined the relationship in Lightswitch, but when I load the invoice line record, I can't see the product information. My code is as follows: // Select invoice and get products myapp.AddEditServiceRecord.InvoicesByCustomer_ItemTap_execute = function (screen) { screen.ServiceRecord.InvoiceNumber = screen.InvoicesByCustomer.selectedItem.INVO_NO; // Delete existing lines (if any) screen.ServiceDetails.data.forEach(function (line) { line.deleteEntity(); }); // Add products for selected invoice screen.getInvoiceLinesByNumber().then(function (invLines) { invLines.data.forEach(function (invLine) { invLine.getProduct().then(function (invProduct) { var newLine = new myapp.ServiceDetail(); newLine.ServiceRecord = screen.ServiceRecord; newLine.ProductCode = invLine.ProductCode; newLine.ProductDescription = invProduct.Description; newLine.CasesOrdered = invLine.Cases; }); }); }); }; The idea is that a list of invoices are on the screen 'InvoicesByCustomer', and the user clicks one to add the details of that invoice to the 'ServiceRecord' table. If I comment out the newLine.ProductDescription = invProduct.Description line it works perfectly in adding the correct product codes and cases values. I have also tried a few other combinations of the below code, but in each case the related product entity appears as undefined in the Javascript debugger. EDIT: I also read this article on including related data (http://blogs.msdn.com/b/bethmassi/archive/2012/05/29/lightswitch-tips-amp-tricks-on-query-performance.aspx) and noticed the section on 'Static Spans'. I checked and this was set to 'Auto (Excluded)' so I changed it to 'Included', but unfortunately this made no difference. I'm still getting the invProduct is undefined message. I also tried simply invLine.Product.Description but it gives the same error. A: The solution in this case was a simple one. My data was wrong, and therefore Lightswitch was doing it's job correctly! In my Invoices table, the product code was something like 'A123' whereas in my Products table, the product code was 'A123 ' (padded with spaces on the right). When doing SQL queries against the data, it was able to match the records but Lightswitch (correctly) saw the 2 fields as different and so could not relate them. I may have wasted several hours on this, but it's not wasted when something has been learnt...or so I'll tell myself!
{ "pile_set_name": "StackExchange" }
Q: change text on website based if user is logged in or not i want to show a logout button when the user is logged in and if the user isn't logged i want to show an login button. I work wit json token, so i ask if the token isn't null, because then I know that the user is logged in. But it doesn`t work. Please Help! home.page.ts admin = false; constructor(private userService: UserService, private storage: Storage, private router: Router) {} ngOnInit() { this.router.navigateByUrl('home'); if (this.storage.get('token') != null) { this.admin = true; } } home.page.html <ion-button *ngIf="admin==true">Logout</ion-button> <ion-button *ngIf="admin==false">Login</ion-button> A: You have to change your Code like this. admin = false; constructor(private userService: UserService, private storage: Storage, private router: Router) {} async ngOnInit() { this.router.navigateByUrl('home'); let token = await this.storage.get('token'); if (!token) { this.admin = false; //User is not logged in } else{ this.admin=true; //user is logged in } }
{ "pile_set_name": "StackExchange" }
Q: Why do processes I fork get systemd as their parent? I am learning fork() in Linux, and here is my program: 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 int main(void){ 5 int pid; 6 pid = fork(); 7 if(pid < 0){ 8 exit(1); 9 } 10 if(pid == 0){ 11 fork(); 12 fork(); 13 printf("pid:%d ppid:%d\n",getpid(),getppid()); 14 exit(0); 15 } 16 else{ 17 printf("parent pid:%d ppid:%d\n",getpid(),getppid()); 18 exit(0); 19 } 20 21 } Sometimes it worked fine, with result like this: ./test1.out parent pid:27596 ppid:21425 pid:27599 ppid:27597 pid:27597 ppid:27596 pid:27598 ppid:27597 pid:27600 ppid:27598 But the result was not consistent, more often than not it worked like this: parent pid:27566 ppid:21425 pid:27567 ppid:27566 pid:27568 ppid:27567 pid:27569 ppid:1599 pid:27570 ppid:1599 Which makes no sense to me, so I typed $ps aux to find out what process 1599 is:(with some columns deleted) USER PID VSZ RSS STAT START COMMAND linux 1599 63236 6316 Ss 09:03 /lib/systemd/systemd --user Can anybody help me straighted things up? A: The "inconsistency" you observed is because sometimes, the parent process(es) exited before their child process(es) terminated. So, these child processes become "orphans" as their parent processes are not waiting for them. As a result, they are "re-parented" to the init process. While traditionally the process id of the "init" process is 1, it's not always true. POSIX leaves it as implementation-defined: The parent process ID of all of the existing child processes and zombie processes of the calling process shall be set to the process ID of an implementation-defined system process. That is, these processes shall be inherited by a special system process. Thus you see a particular PID as the parent (1599 in your example), which happens to be "init" process equivalent on your Linux. The systemd is an init variant used in Debian Linux distributions - which follows a slightly more complicated implementation. In essense, what you observed is pretty normal. Ideally, you should reap all the processes in order to avoid zombie processes. A: I suppose that, sometimes, a race condition happens, and the parent dies before the child. Hence, the child becomes children from init process. In your case, that must be systemd. Anyway, be advised that running fork(); fork(); will produce 4 processes, which is (probably) not what you intend. Use control structure as you did with the first one to have fine control on the behaviour of your program.
{ "pile_set_name": "StackExchange" }
Q: Uploading files to S3 via SSL/HTTPS using Fineuploader I've set up Fineuploader to upload files to an S3 bucket for a project I'm working on and everything was running smoothly...until I set up SSL. (Application runs within Docker, and added Nginx + LetsEncrypt around that to achieve this) While the rest of the application works fine, uploads via Fineuploader are failing with error message: Mixed Content: The page at 'https://example.com/upload' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://MYBUCKETNAME.amazonaws.com/'. This request has been blocked; the content must be served over HTTPS. I've looked through Fineuploader's documentation but see no options covering requests over HTTPS other than the mention that "SSL is also supported" under request>endpoint [https://docs.fineuploader.com/api/options-s3.html#request]. (There was also a feature suggestion which seems to tackle this that went through but was then reverted for some reason - https://github.com/FineUploader/fine-uploader/issues/1119) I've tried adding "https://" in front of my endpoint within the client-side uploader but that hasn't worked either. var uploader = new qq.s3.FineUploader({ request: { endpoint: 'https://MYBUCKETNAME.amazonaws.com', accessKey: 'TRALALALALALA', }, ... Are there any options I'm missing here? Does the signature functionality need to change for this to work? As this is an upload to an S3 bucket, does the endpoint policy depend on the bucket's permissions (in which case, how do you go about enabling uploads over https?) A: I've just resolved this and turns out it was a Docker issue... For some reason the image wasn't being updated despite having the right tag. I've tried changing the endpoint by tacking 'https://" to the front of it and it's now working. (Similar to the recommendation in Using FineUploader with optional https? ) Hope this helps others as the Fineuploader doesn't make this clear.
{ "pile_set_name": "StackExchange" }
Q: Combine two key-value collections with Spark efficiently I have the following key-value pairs lists (like a hashmap, but not exactly inside the spark context): val m1 = sc.parallelize(List(1 -> "a", 2 -> "b", 3 -> "c", 4 -> "d")) val m2 = sc.parallelize(List(1 -> "A", 2 -> "B", 3 -> "C", 5 -> "E")) I want to get something like this and do if efficiently in parallel (don't even know if it's possible List(1 -> (Some("a"), Some("A")), 2 -> (Some("b"), Some("B")), 3 -> (Some("c"), Some("C")), 4 -> (Some("d"), None), 5 -> (None, Some("E"))) Or at least List(1 -> ("a","A"), 2 -> ("b","B"), 3 -> ("c","C")) How to achieve this? As I understand - I don't have efficient way to get values from the "maps" by key - these are not hashmaps really. A: You can use the fullOuterJoin function: val m1: RDD[(Int, String)] = //... val m2: RDD[(Int, String)] = //... val j: RDD[(Int, (Option[String], Option[String]))] = m1.fullOuterJoin(m2) Depending on your use, you can use any variation of joins: val full: RDD[(Int, (Option[String], Option[String]))] = m1.fullOuterJoin(m2) val left: RDD[(Int, (String, Option[String]))] = m1.leftOuterJoin(m2) val right: RDD[(Int, (Option[String], String))] = m1.rightOuterJoin(m2) val join: RDD[(Int, (String, String))] = m1.join(m2)
{ "pile_set_name": "StackExchange" }
Q: Did the Catholic Church forbid the use of forks in Medieval times? A very popular "demotivational" website in Poland has an image that claim that in Medieval times, the Roman Church forbade the use of forks, calling then "tools of the Devil" and threatening to excommunicate people who use forks to eat. It quotes Hildegard of Bingen, who allegedly said that to use forks was to insult God. The page cites this 2012 Polish blog post as its source. The blog post makes the same claim, while elaborating that the similarity of the word "widelec" ("fork") and "widły" ("pitchfork") in Polish is a consequence of the aforementioned polices of the Church. It also elaborates that when a woman who owned a fork fell ill and died, St. Bonaventure said that the illness was a divine punishment. The blog post also claims that forks were widely used in the Byzantine Empire and that, in spite of the efforts of the Church to ban them, they started appearing in the West as well, even in monasteries. However, the blog post doesn't provide sources for any of this. Did the Roman Church attempt to ban the use of forks for eating in Medieval times, linking these tools to the Devil? A: Absence of evidence for a church ban, but some individual Roman Catholics expressed dislike of it From the Wikipedia page on the fork The fork's adoption in northern Europe was slower. Its use was first described in English by Thomas Coryat in a volume of writings on his Italian travels (1611), but for many years it was viewed as an unmanly Italian affectation.[15] Some writers of the Roman Catholic Church expressly disapproved of its use, St. Peter Damian seeing it as "excessive delicacy":[11] It was not until the 18th century that the fork became commonly used in Great Britain[16] [.] There is no mention that the church as a whole banned it. A Google search on "catholic church fork" provides this passage: What’s more even the church was against the use of forks (despite them being in the Bible)! Some writers for the Roman Catholic Church declared it an excessive delicacy, God in his wisdom had provided us with natural forks, in our fingers, and it would be an insult to him to substitute them for these metallic devices. ...but there is no source for that claim so it is hard to tell if the writer is conflating the individuals with the church or not. Another similar passage is this: So it's not surprising that the first appearance of forks in the West was in Venice, the European bridge to the East and terminus of the Silk Road. The "patient zero" of forks was apparently an 11th-century Byzantine princess who married a Venetian doge and brought golden forks as part of her dowry. The Venetians were appalled when they saw her using her fork, seeing it as spiting God: one clergyman said, "God in his wisdom has provided man with natural forks — his fingers. Therefore it is an insult to him to substitute artificial metallic forks for them when eating." When the princess died two years later, the Venetian church saw it as God's punishment for the pride and vanity and "excessive delicacy" she displayed in her use of forks. Again, this is not sourced. There is a link about that supposed statement by the clergyman but it does not lead to anything supporting that such a statement was ever made. Apart from that I find no mention of anything like a ban issued by the church on the first 10 pages of search results. I cannot prove a negative, but I would expect a Roman Catholic church ban on something as common as cutlery would have left a larger imprint. In conclusion: There is lack of evidence for a ban, and although lack of evidence for a ban is not evidence for a lack of a ban, that I think is as far as we will get. [11]: Wilson, Bee. Consider the Fork: A History of How We Cook and Eat. New York: Basic, 2012. Print. [15]: Petroski, Henry (1992), The evolution of useful things, New York: Alfred A. Knopf, ISBN 978-0-6797-4039-1 [16]: Charing Worh (2014), Types of Cutlery in the UK, Charing Worth, retrieved March 24, 2014 A: As far as I know the Catholic Church didn't forbid the use of forks, but many senior churchmen who had a foul and unholy lust for power and control over people opposed the use of forks. Several Byzantine princesses who married into the families of Doges of Venice were accused of ultra luxurious practices like using forks. Theodora was married to Domenico Selvo in Constantinople (1075) with full Imperial pageantry, and crowned with the Imperial diadem by her brother, Michael VII Doukas. Theodora brought a large Greek retinue to Venice, and rendered herself extremely unpopular because of her aristocratic bearing and haughty manner. What was then perceived as her Byzantine extravagance included the use of a fork, finger bowls, napkins, and sconce candles. The Dogaressa died of a degenerative illness, which was seen by the Venetians as a divine judgment for her "immoderate" lifestyle. There is an account of her lavish manners written by Peter Damian, the Cardinal Bishop of Ostia, entitled "Of the Venetian Doge's wife, whose body, after her excessive delicacy, entirely rotted away."1 It is not possible however for Peter Damian to have written anything about the marriage of Theodora and Domenico: their marriage took place in 1075 and Peter died in 1072. The same stories of Peter Damian have been equally attributed to Maria Argyropoulaina and Giovanni Orseolo: she the niece of the Byzantine Emperors Basil II and Constantine VIII and he the son of Doge Pietro II. Maria and Giovanni were married in Constantinople in 1005 or 1006. Both died in 1007 when a plague swept through the city-state. Peter Damian was born between 995 and 1007: he would have been, at most, 11 years old when Maria, Giovanni and their son arrived in Venice. https://en.wikipedia.org/wiki/Theodora_Anna_Doukaina_Selvo1 Maria Argyra or Maria Argyropoulina (Greek: Μαρία Αργυρή or Αργυροπουλίνα ; died 1007) was the granddaughter of the Byzantine emperor Romanos II and niece of the emperors Basil II and Constantine VIII. In the Venetian Chronicle by John the Deacon, it is mentioned that Maria was the daughter of a noble patrician, called Argyropoulos, who was a descendant of the imperial family. This information is confirmed by the chronicle of Andrea Dandolo, who says that she was the niece of the emperor Basil II. As a member of the Argyros family Maria was also relative to the future Byzantine emperor Romanos III Argyros. In 1004 Maria was married to Giovanni Orseolo, the son of the Doge of Venice Pietro II Orseolo, in the Iconomium palace in Constantinople with full imperial pageantry - the couple was crowned with golden diadems by Basil II. Maria brought to her husband great dowry, including a palace in the imperial capital, where they lived after the wedding. Basil also honored Maria's husband with the title of patrician. At her wedding she used cutting edge, fashionable gold forks. But in the 11th century the fork was a controversial item. “She was roundly condemned by the local clergy for her decadence, with one going so far as to say, ‘God in his wisdom has provided man with natural forks—his fingers. Therefore it is an insult to him to substitute artificial metal forks for them when eating.’” Before they left Constantinople, Maria Argyra begged the emperor for pieces of the holy relics of Saint Barbara, which were brought to Venice by her. Maria Argyre and Giovanni Orseolo had a son, who was named after emperor Basil II. In 1007 Maria along her husband and son died when plague swept through the city-state. So some clergymen believed that: ‘God in his wisdom has provided man with natural forks—his fingers. Therefore it is an insult to him to substitute artificial metal forks for them when eating.’ I suppose that those same clergymen would forbid the peasants on properties owned by the church from using plows, and hoes, and other tools, and demand that the peasants do everything barehanded while working the land to support those clergymen. The "byzantine" Theophanu (c. 955-990) Empress consort of Otto II from 973 to 983 and regent for Otto III from 983 to 990, was also criticized by some for her luxurious habits. https://en.wikipedia.org/wiki/Theophanu2 I believe that the "decadent eastern habits" of Theophanu and her son Otto III may have included - Gasp! Shudder! - using forks.
{ "pile_set_name": "StackExchange" }
Q: How do the different compression levels of gzip differ? I am trying to better understand how different compression levels (1-9) of gzip differ in the way that encoding is implemented. I've looked the zlib C source code and it seems that it has to do with how exhaustive the search for the longest matching string is, but looking for more specific information. For example, do the levels yield any differences in the assignment of Huffman codes? A: The levels differ only in how hard deflate looks for matching strings, as you observed. The Huffman coding is done on a chosen fixed number of symbols (literals and length/distance pairs), producing a "block", where that number is defined by the memory level, not the compression level. The Huffman codes generated will necessarily differ, since the symbols being coded will differ. The choice of memory level also has some effect on compression, as a larger number of symbols spreads the cost of the code description for a block over more symbols, but too many symbols may prevent adaptation of the Huffman codes to local changes in the statistics of the symbols. The default memory level is 8 (resulting in 16,383 symbols per block), since testing indicated that that gave better compression than level 9 (32,767 symbols per block). However your mileage may vary.
{ "pile_set_name": "StackExchange" }
Q: Trying to Scanner from delimited txt file into a String Array I am trying to read a tab delimited txt file and put the data into two columns of a String array. package mailsender; import java.io.*; import java.util.Scanner; public class MailSenderList { static String address=null; static String name=null; static String[][] mailer; // @SuppressWarnings("empty-statement") public static void main(String[] args) throws IOException { try { Scanner s = new Scanner(new BufferedReader(new FileReader("/home/fotis/Documents/MailRecipients.txt"),'\t')); //This is the path and the name of my file for(int i=0;i>=30;i++){ for(int j=0;j>=2;j++){ if (s.hasNext());{ mailer[i][j]=s.next(); //here i am trying to put 1st+2 word into first column and 2nd+2 into second column. } } } for(int ii=0;ii>=30;ii++){ System.out.println("Line : "); for(int ji=0;ji>=2;ji++){ System.out.print(" " + mailer[ii][ji]); //trying to print and check the array } } } catch (java.io.FileNotFoundException e) { System.out.println("Error opening file, ending program"); //System.exit(1);} } } class mail{ mail(){ } } } The file builds successfully but no result in System.out.In debugger, it seems as it never passes from the first for loop. A: Indeed.For was so wrong.But I was dizzy. Nevertheless , confusing "<>" was not the real problem. The code worked with while. Here is the whole class. import java.io.File; import java.util.Scanner; public class ReadFile { public static void main(String[] args) { try { File file = new File("/home/fotis/Documents/Mailers.txt"); //this a the path there try (Scanner input = new Scanner(file).useDelimiter("\\t")) { String line[] = new String[150000]; int i=0; while (input.hasNextLine()) { line[i] = input.next(); System.out.println(line[i]); i++; } } } catch (Exception ex) { ex.printStackTrace(); }
{ "pile_set_name": "StackExchange" }
Q: Why the values of the global object are changing and not just local object values? First I will like to say that probably some of the code will be a little complicated and probably had to be reviewed, so I filling shamed in advanced :-< Anyway enough with my apologies here is my code, I also added jsfiddle so you can view live example. jsfiddle In case you wish to download the code: https://github.com/printmypic/js-form-generator The problem I have is with edit once I edit and afterwards I click on new form, it takes the form values of the previews edit form. I am not understand why the values of userForm are being set instead of the local var of formGenerator.form? Thank you in advance. HTML: <button class="btn btn-success" id="newUser">New User</button> <table id="data" class="table table-striped table-hover table-bordered dt-responsive nowrap dataTable no-footer" cellspacing="0" width="100%" role="grid" aria-describedby="data_info" style="width: 100%;"> <thead> <tr role="row"><th class="sorting_asc" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-sort="ascending" aria-label="id: activate to sort column descending" style="width: 50px;">id</th><th class="sorting" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-label="user: activate to sort column ascending" style="width: 122px;">user</th><th class="sorting" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-label="password: activate to sort column ascending" style="width: 214px;">password</th><th class="sorting" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-label="email: activate to sort column ascending" style="width: 201px;">email</th><th class="sorting" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-label="phone: activate to sort column ascending" style="width: 42px;">phone</th><th class="sorting" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-label="full name: activate to sort column ascending" style="width: 92px;">full name</th><th class="sorting" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-label="country: activate to sort column ascending" style="width: 51px;">country</th><th class="sorting" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-label="pids: activate to sort column ascending" style="width: 221px;">pids</th><th class="sorting" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-label="type: activate to sort column ascending" style="width: 29px;">type</th><th class="sorting" tabindex="0" aria-controls="data" rowspan="1" colspan="1" aria-label="bid: activate to sort column ascending" style="width: 21px;">bid</th></tr></thead> <tbody> <tr role="row" class="odd"><td class="sorting_1"><div class="btn-group"> <button class="btn dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button> <ul class="dropdown-menu"> <li class=""><a class="action editUser" data-id="1">Edit</a></li><li class=""><a class="action deleteUser" data-id="">Delete</a></li></ul></div></td><td>tal</td><td>222a3962a50d89a</td><td>[email protected]</td><td>34214324</td><td>frw</td><td>dsad</td><td>dsad</td><td>Admin</td><td></td></tr></tbody> </table> <div id="myModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="modaltitle">Modal title</h4> </div> <div class="modal-body clearfix" id="modalbody"> </div> <div class="modal-footer"> <button id="modalcancel" type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button id="modalsave" type="button" class="btn btn-primary">Save changes</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> JS function showModal(modalContent,callback) { for (i in modalContent) { if (i === 'modalcancel' || i === 'modalsave') { $('#' + i).attr('onclick', modalContent[i]); if (modalContent[i] === '') { $('#' + i).text('close').hide(); } else { $('#' + i).text('save').show(); } } else if ($.isFunction(modalContent[i])) { $('#' + i).html(modalContent[i]()); } else { $('#' + i).html(modalContent[i]); } } $('#myModal').modal(); if($.isFunction(callback)){ callback(); } } var formGenerator = { tableSelector: '#data', tableHeaders: '#data th', formId: 'newUserForm', form: {}, skipVars: ['id'], init: function (config, callback) { if (config.formId) { this.formId = config.formId; } if (config.tableHeaders) { this.tableHeaders = config.tableHeaders; } if (config.editElement) { this.form = this.setValuesByTableRow(config.editElement, config.form); } else { this.form = config.form; } if($('#'+this.formId).size()){ $('#'+this.formId).remove(); } var $form = $('<form id="'+this.formId+'" autocomplete="off" class="form-horizontal"></form>'); var that = this; $(this.tableHeaders).each(function () { var name = $(this).text().toLowerCase().replace(/ /g, '_'); if ($.inArray(name, that.skipVars) !== -1 || typeof (that.form[name]) === 'undefined') { return; } $formElement = that.createFormElement(that.form[name].name, that.form[name].type, that.form[name].value); $formElement.appendTo($form); }); if(callback && $.isFunction(callback)){ setTimeout(function () { callback() }, '200'); } return this.htmlForm = $form[0].outerHTML; }, createFormElement: function (name, type, value) { var $inputContainer = $('<div class="form-group col-md-6"></div>'); var $container = $('<div class="form-group col-md-12"></div>'); switch (type) { case 'password': case 'text': case 'email': case 'hidden': case 'number': value = value ? value : ''; $element = $('<input autocomplete="off" type="' + type + '" class="form-control" id="' + name + '" placeholder="' + name.replace(/_/g, ' ') + '" name="' + name + '" value="' + value + '" />'); break; case 'select': var options = this.getOptions(this.form[name].selectData,value); $element = $('<select class="form-control" id="' + name + '" placeholder="' + name + '" name="' + name + '">' + options + '</select>'); break; } $inputContainer.append($element); $labelContainer = $('<div class="form-group col-md-6"><label for="' + name + '">' + name.replace(/_/g, ' ') + '</label></div>'); $container.append($labelContainer); return $container.append($inputContainer); }, getColByThTr: function (thText, $element, tableSelector) { var landingIndex = $(tableSelector + ' th:contains(' + thText + ')').index() + 1; return $element.closest('tr').find('td:nth-child(' + landingIndex + ')'); }, setValuesByTableRow: function ($element, form) { var editForm = form; for (i in editForm) { var th = i.replace(/_/g, ' '); if (editForm[i].type === 'select') { editForm[i].selectData.selected = this.getColByThTr(th, $element, this.tableSelector).text(); } else if (editForm[i].type === 'password') { editForm[i].value = ''; } else { editForm[i].value = this.getColByThTr(th, $element, this.tableSelector).text().trim(); } } return editForm; }, formatSelectArr: function (arr, nasted, selectedItem) { var formattedSelectArr = []; if (!selectedItem) { formattedSelectArr.push({'title': 'Select', 'selected': true, 'value': ''}); } var value, title = ''; for (i in arr) { title = arr[i]; if (nasted) { value = i; } else { value = arr[i]; } if (selectedItem === arr[i]) { selected = true; } else { selected = false; } formattedSelectArr.push({'title': title, 'selected': selected, 'value': value}); } return formattedSelectArr; }, getOptions: function (arr) { var data = this.formatSelectArr(arr.data, arr.nasted, arr.selected); var html = ''; for (i in data) { selected = (data[i].selected) ? 'selected' : ''; html += '<option value="' + data[i].value + '" ' + selected + '>' + data[i].title + '</option>'; } return html; } }; var userTypes = {"1":"Admin","2":"API"}; var bids = ["bid1","bid2"]; var countriesArr = ["Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antarctica","Antigua and Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Bouvet Island","Brazil","British Indian Ocean Territory","Brunei Darussalam","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central African Republic","Chad","Chile","China","Christmas Island","Cocos (Keeling) Islands","Colombia","Comoros","Congo","Congo, the Democratic Republic of the","Cook Islands","Costa Rica","Cote DIvoire","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands (Malvinas)","Faroe Islands","Fiji","Finland","France","French Guiana","French Polynesia","French Southern Territories","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guadeloupe","Guam","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Heard Island and Mcdonald Islands","Holy See (Vatican City State)","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran, Islamic Republic of","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Korea, Democratic Peoples Republic of","Korea, Republic of","Kuwait","Kyrgyzstan","Lao Peoples Democratic Republic","Latvia","Lebanon","Lesotho","Liberia","Libyan Arab Jamahiriya","Liechtenstein","Lithuania","Luxembourg","Macao","Macedonia, the Former Yugoslav Republic ","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Martinique","Mauritania","Mauritius","Mayotte","Mexico","Micronesia, Federated States of","Moldova, Republic of","Monaco","Mongolia","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Niue","Norfolk Island","Northern Mariana Islands","Norway","Oman","Pakistan","Palau","Palestinian Territory","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Pitcairn","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Helena","Saint Kitts and Nevis","Saint Lucia","Saint Pierre and Miquelon","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Georgia and the South Sandwich Isl","Spain","Sri Lanka","Sudan","Suriname","Svalbard and Jan Mayen","Swaziland","Sweden","Switzerland","Syrian Arab Republic","Taiwan, Province of China","Tajikistan","Tanzania, United Republic of","Thailand","Timor-Leste","Togo","Tokelau","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Turks and Caicos Islands","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","United States Minor Outlying Islands","Uruguay","Uzbekistan","Vanuatu","Venezuela","Viet Nam","Virgin Islands, British","Virgin Islands, U.s.","Wallis and Futuna","Western Sahara","Yemen","Zambia","Zimbabwe","Montenegro"]; var userForm = { 'full_name': {type: 'text', name: 'full_name',value:''}, 'user': {type: 'text', name: 'user',value:''}, 'password': {type: 'password', name: 'password',value:''}, 'bid': {type: 'select', name: 'bid', selectData: {'data':bids, 'nasted':false, 'selected':''},value:''}, 'pids': {type: 'text', name: 'pids',value:''}, 'phone': {type: 'number', name: 'phone',value:''}, 'type': {type: 'select', name: 'type', selectData: {'data':userTypes, 'nasted':true, 'selected':'Affiliate'},value:''}, 'country': {type: 'select', name: 'country', selectData: {'data':countriesArr, 'nasted':false, 'selected':'Israel'},value:''}, 'email': {type: 'email', name: 'email',value:''}, }; myForm = formGenerator; function editUser(element, id) { $element = $(element).closest('tr'); showModal({ 'modalsave': '', 'modalcancel': '', 'modaltitle': 'Info', 'modalbody': '' + myForm.init( { 'tableHeaders': '#data th', 'form': userForm, 'editElement':$element } ) + '' }); } function newUserForm(){ showModal({ 'modalsave': 'alert(\'save\')', 'modalcancel': '', 'modaltitle': 'Info', 'modalbody': '' + myForm.init( { 'tableHeaders': '#data th', 'form': userForm, 'editElement':false } ) + '' }); } $(function(){ $('#newUser').on('click',function(){newUserForm();}); $('.editUser').on('click',function(){editUser(this,$(this).data('id'));}); }); A: From this formId: 'newUserForm' to this this.formId = config.formId; is passed by reference. So what you have as formId inside formGenerator is in fact a reference of newUserForm. Does that make sense? Javascript by default passes objects by reference. If you do not want that, you might want to write a clone function or perform a shallow/deep copy. jQuery makes this easy where you can simply do this. var newUserForm2 = jQuery.extend({}, newUserForm) This will make changes to newUserForm2 not affect newUserForm. Please read this thread for more info
{ "pile_set_name": "StackExchange" }
Q: How to make a div that covers the all area of the screen except the area covered by a fixed div? I am facing problem while making two divs side by side in a way that second div starts after the width of the first div. I don't want to use overflow: hidden, as i want to start the second after the first paragraph. This is what i want to achieve. A: I don't think you make <div> like you shown in the image. But I have a suggestion. Both the elements in the below div are rectangle. but the content behaves like you drawn. You can look up CSS Basics here div{ margin: 0; background: green; } .small{ float:left; width:20%; height: 100px; background: yellow; } <div class="small">Lorem ipsum dolor sit amet, consectetur adipiscing elit. .</div> <div class="big">Aenean euismod eros et erat pharetra, at elementum odio suscipit. Cras a enim quis diam molestie sollicitudin eget ac est. Proin porta turpis a massa porta laoreet. Fusce semper facilisis erat nec suscipit. Aliquam gravida quis dui sed aliquet. Ut consequat ullamcorper volutpat. Cras neque tortor, pharetra id condimentum nec, accumsan ac ipsum. Etiam sit amet convallis ante. In pulvinar eu erat eu fringilla. Nam scelerisque eget ligula a blandit. Nullam eu tortor augue. Nulla at eros arcu. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque eget tincidunt massa. Sed dictum faucibus risus ac varius. Praesent aliquet erat tortor, sed lacinia metus fermentum non. Nulla vitae sapien dui. Vestibulum sed urna quis ex dictum scelerisque id ut erat. Cras efficitur ligula eu neque pellentesque, eget posuere lacus aliquet. Pellentesque interdum at sem vitae aliquet. Donec cursus, elit et varius viverra, urna erat commodo sem, ac congue erat augue eget ex. Suspendisse posuere sem at tempor faucibus. Aliquam erat volutpat. Curabitur aliquam feugiat tortor vitae blandit. Quisque faucibus urna arcu, sed rhoncus quam rutrum scelerisque. Aliquam pulvinar condimentum accumsan. Etiam lorem nibh, porta vitae mauris sit amet, egestas interdum lectus. Proin sit amet dolor purus. Nunc sed sem sed purus sagittis congue iaculis sed mauris. Donec pellentesque ut dolor rhoncus iaculis. Donec quis magna accumsan turpis convallis dignissim. Integer vel nisl accumsan, ultrices augue ut, placerat eros. Phasellus eu lacinia elit, nec maximus dui. </div>
{ "pile_set_name": "StackExchange" }
Q: How do I calculate weighted degree distributions with igraph in R? Consider a dataframe df where the first two columns are node pairs and successive columns V1, V2, ..., Vn represent flows between the nodes (potentially 0, implying no edge for that column's network). I would like to conduct analysis on degree, community detection, and other network measures using the flows as weights. Then to analyze the graph with respect to the weights in V1 I do: # create graph and explore unweighted degrees with respect to V1 g <- graph.data.frame( df[df$V1!=0,] ) qplot(degree(g)) x <- 0:max(degree(g)) qplot(x,degree.distribution(g)) # set weights and explore weighted degrees using V1 E(g)$weights <- E(g)$V1 qplot(degree(g)) The output from the third qplot is no different than the first. What am I doing wrong? Update: So graph.strength is what I am looking for, but graph.strength(g) in my case gives standard degree output followed by: Warning message: In graph.strength(g) : At structural_properties.c:4928 :No edge weights for strength calculation, normal degree I must be setting the weights incorrectly, is it not sufficient to do E(g)$weights <- E(g)$V1 and why can g$weights differ from E(g)$weights? A: The function graph.strength can be given a weights vector with the weights argument. I think what is going wrong in your code is that you should call the weights attribute E(g)$weight not E(g)$weights. A: I created an equivalent degree.distribution function for weighted graphs for my own code by taking the degree.distribution code and making one change: graph.strength.distribution <- function (graph, cumulative = FALSE, ...) { if (!is.igraph(graph)) { stop("Not a graph object") } # graph.strength() instead of degree() cs <- graph.strength(graph, ...) hi <- hist(cs, -1:max(cs), plot = FALSE)$density if (!cumulative) { res <- hi } else { res <- rev(cumsum(rev(hi))) } res }
{ "pile_set_name": "StackExchange" }
Q: Safe temperature for desoldering SMD components w/ hot-air rework gun? What is a reasonably safe temperature to use for desoldering SMD components using a hot-air rework gun? I have a new-to-me rework station from Xytronic and the documentation clearly assumes you know what you're doing… It tells you what temperature range the gun is capable of, but has nothing to say about where you should be setting it. Also, I was surprised by how little air pressure the unit generates even when the AIR setting is set to max (99). Is this normal? My one test so far was to desolder a random surface-mount IC package from a piece of electronic salvage I had lying around (kept for exactly this purpose). I tried to step up the temperature slowly, but I got all the way to 400 degrees Celsius before the chip seemed to suddenly be floating free. I never did see any visible change in the solder… (But perhaps that's just my eyesight.) I am concerned that at that temperature any component that I can get off a board might be damaged by the heat. A: Very good idea to practice, practice, and practice some more on salvaged boards until you get competent with new tools. You didn't notice the solder had reached the molten state because there's so little of it used to solder components. The typical lead-free solder has a melting point around 217 degrees C, so you'll have to get the leads and pads up to that temperature before trying to remove the component. The reason why you need a much higher temperature is because you want to get the solder joints to the melting point as fast as possible. If the hot-air gun is set to a much lower temperature, it'll take a longer time to reach the melting point. The longer the time to raise the temperature of the leads/pads will increase the overall temperature of the component, possibly past the point of destruction. So the technique is to heat it up fast, remove the part and hot-air gun, then put the part where it can cool off. Now, if you're removing a part that's already fried due to some other reason, no worries then. Just don't damage the board by overheating the pads and causing them to lift off. If that happens, your headaches are just beginning on this repair. A: I am working with SMD for a while and I suggest you use leaded solder to treat the oxidized solder joints with flux before you get to the hot air stage. After solder mixture process, preheat the board close to 200C and continue with hot air station. I use analog hot air stations because I don't want to turn around and look at the temperature. I know where I have to set the hand dial without looking and I think that is between 7-8 on Hakko 852 station (around 420C). Preheat the chip from distance and can feel when it is enough to start. I count to 5 and viola pull the chip out without any problem. The hard ones are BGA chips and need precision timing and good BGA preheater. Average ICs are rated to 380C/10Sec I think but I am not sure.
{ "pile_set_name": "StackExchange" }
Q: c#: Isn't Where(), OrderBy() and Select() from Enumerable Class supposed to take a delegate type, lambda expression or anonymous type as a parameter I have got a question. See the two blocks of code. Isn't Where(), OrderBy() and Select() from IEnumerable Class supposed to take a delegate type, lambda expression or anonymous type as a parameter. If so, how did the QueryOverStringWithRawDelegate() produce the same results as QueryOverStringsWithExtensionMethods()? void QueryOverStringsWithExtensionMethods() { // Assume we have an array of strings string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Bio Shock 4" }; IEnumerable<string> subset = currentVideoGames.Where(game => game.Contains(" ")).OrderBy(game => game).Select(delegate (string game) { return game; }); Console.WriteLine("Query Over Strings With Extension Method"); foreach (var s in subset) { Console.WriteLine("Items: {0}", s); } } and void QueryStringsWithRawDelegates() { // Assume we have an array of strings string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Bio Shock 4" }; var subset = currentVideoGames.Where(Filter).OrderBy(ProcessItems).Select(ProcessItems); foreach (var s in subset) { Console.WriteLine("Items: {0}", s); } string ProcessItems(string game) { return game; } bool Filter(string game) { return game.Contains(" "); } } Thank you for your help ! A: currentVideoGames.Where(Filter) is simply shorthand for: currentVideoGames.Where(new Func<string, bool>(Filter)) That is, the compiler sees that you've got a method which takes a delegate type Func<string, bool>, it sees that you're giving it a method which has the signature bool Filter(string) (strictly, a method group of one or more overloads, one of which has a signature that's close enough), and it automatically inserts the code to instantiate a new delegate instance. This same language feature lets you write things like: SomeEvent += Handler; rather than: SomeEvent += new EventHandler(Handler); See this on SharpLab. Similarly: currentVideoGames.Where(game => game.Contains(" ")) is shorthand for: currentVideoGames.Where(new Func<string, bool>(CompilerGeneratedFunction)) where CompilerGeneratedFunction will look something like: bool CompilerGeneratedFunction(string x) { return x.Contains(" "); } See this on SharpLab. It so happens that the compiler's put CompilerGeneratedFunction (which it called <M>b__0_0) in a new inner class, and it caches the Func<string, bool> that it instantiates for performance reasons.
{ "pile_set_name": "StackExchange" }
Q: Java Swing GUIs on Mac OS X Have you ever attempted using Swing only to end up changing courses because it just couldn't do what you wanted? I'm pretty new to Swing, having only used it for school projects over 5 years ago, but it seems Swing has come a long way in providing a more native look and feel, so much so that I'm considering using it to develop the GUI for an app on Mac OS X. Before I do, though, I wanted to see if anyone has run into any showstopper issues that prevented them from using Swing. Just off the top of my head, some possibilities: Problems developing custom components that looked "right" Bad interactions with native applications and widgets Performance issues (unresponsiveness, repaint problems) Inability to mimic native behaviors (like Dock interaction) A: Swing isn't going to give you perfect fidelity with the hosting OS. Sun simply can't devote the considerable resources necessary to do so. My impression is that Swing has gotten much better, but is still going to look out of place by default. The minimum required to even hope to pass as a Mac app: package your .jar in a .app set the L&F to system default set apple.laf.useScreenMenuBar property to true must do this before any UI code Dock interaction is non-existent in standard Java. You'll have to use Apple's Cocoa-Java bridge, which is no longer supported. I have no idea how tractable JNI is on OS X, which is the only real alternative. Performance shouldn't be a problem. Drag & Drop is probably as hairy on OS X as it is everywhere else. Basically, if you're explicitly targeting OS X you're best off using Objective-C. Its far from impossible to build an app on OS X using Java & Swing, but its a lot of work to make it look "native". A: As Kevin and John said you should try Objective-C, Cocoa and XCode if you are only targeting Mac users. The developer tools for Mac is freely available. If you want to (or have to) use Java and Swing you can use some libraries to create a GUI that looks well on Macs: Quaqua look and feel MacWidgets For deploying your application you should read the JarBundler docs. However, in this case interaction with dock and native applications is very limited. Some other good links are: Making Java/Swing Applications Look (More) Like Native Mac OS X Applications Java: How to handle drop events to the Mac OS X Dock icon A: @Kevin++ Using Cocoa is probably better If you want it to look exactly like native applications If you are targeting only the Mac If you intend to distribute your applications for Windows, Linux, etc. Swing is a decent choice. It's better but like in any toolkit there are still issues. You'll never get a truly native look and feel with it, same goes for similar UI toolkits which claim to be "cross-platform". The Apple Guidelines for Java development can be found here.
{ "pile_set_name": "StackExchange" }
Q: While reading multiple files with Python, how can I search for the recurrence of an error string? I've just started to play with Python and I'm trying to do some tests on my environment ... the idea is trying to create a simple script to find the recurrence of errors in a given period of time. Basically I want to count the number of times a server fails on my daily logs, if the failure happens more than a given number of times (let's say 10 times) over a given period of time (let's say 30 days) I should be able to raise an alert on a log, but, I´m not trying to just count the repetition of errors on a 30 day interval... What I would actually want to do is to count the number of times the error happened, recovered and them happened again, this way I would avoid reporting more than once if the problem persists for several days. For instance, let's say : file_2016_Oct_01.txt@hostname@YES file_2016_Oct_02.txt@hostname@YES file_2016_Oct_03.txt@hostname@NO file_2016_Oct_04.txt@hostname@NO file_2016_Oct_05.txt@hostname@YES file_2016_Oct_06.txt@hostname@NO file_2016_Oct_07.txt@hostname@NO Giving the scenario above I want the script to interpret it as 2 failures instead of 4, cause sometimes a server may present the same status for days before recovering, and I want to be able to identify the recurrence of the problem instead of just counting the total of failures. For the record, this is how I'm going through the files: # Creates an empty list history_list = [] # Function to find the files from the last 30 days def f_findfiles(): # First define the cut-off day, which means the last number # of days which the scritp will consider for the analysis cut_off_day = datetime.datetime.now() - datetime.timedelta(days=30) # We'll now loop through all history files from the last 30 days for file in glob.iglob("/opt/hc/*.txt"): filetime = datetime.datetime.fromtimestamp(os.path.getmtime(file)) if filetime > cut_off_day: history_list.append(file) # Just included the function below to show how I'm going # through the files, this is where I got stuck... def f_openfiles(arg): for file in arg: with open(file, "r") as file: for line in file: clean_line = line.strip().split("@") # Main function def main(): f_findfiles() f_openfiles(history_list) I'm opening the files using 'with' and reading all the lines from all the files in a 'for', but I'm not sure how I can navigate through the data to compare the value related to one file with the older files. I've tried putting all the data in a dictionary, on a list, or just enumerating and comparing, but I've failed on all these methods :-( Any tips on what would be the best approach here? Thank you! A: I'd better handle such with shell utilities (i.e uniq), but, as long as you prefer to use python: With minimal effor, you can handle it creating appropriate dict object with stings (like 'file_2016_Oct_01.txt@hostname@YES') being the keys. Iterating over log, you'd check corresponding key exists in dictionary (with if 'file_2016_Oct_01.txt@hostname@YES' in my_log_dict), then assign or increment dict value appropriately. A short sample: data_log = {} lookup_string = 'foobar' if lookup_string in data_log: data_log[lookup_string] += 1 else: data_log[lookup_string] = 1 Alternatively (one-liner, yet it looks ugly in python most of time, I have had edited it to use line breaks to be visible): data_log[lookup_string] = data_log[lookup_string] + 1 \ if lookup_string in data_log \ else 1
{ "pile_set_name": "StackExchange" }
Q: Printing perl struct members I have a struct and would like to print out the contents within quotes #!/usr/bin/perl use Class::Struct; struct( astruct => [ test => '$']); my $blah = new astruct; $blah->test("asdf"); print "prints array reference: '$blah->test'\n"; print "prints content: '", $blah->test, "'\n"; The output is prints array reference: 'astruct=ARRAY(0x20033af0)->test' prints content: 'asdf' Is there a way to print the contents within the quotes? Its making my code a bit scruffy having to open and close quotes all the time. It's also problematic when using `` to run commands which use the contents of structs. A: The variable $blah holds an array reference and is interpolated into the string before it can be dereferenced. To change that, we put the dereferencing either outside the String: print "prints no array reference any more: '".($blah->test)."'\n"; # parenthesis was optional or pull a little trick with an anonymous array: print "prints no array reference any more: '@{[$blah->test]}'\n"; We dereference (@{...}) an anonymous array ([...]) which we construct from the return value of the test method. (Our your struct field, whatever.) While both these methods work when constructing a string, the second form can easily be used in a qx or backticks environment. You could also build a string $command and then execute that with qx($command). If you don't need the additional functionality of the Class::Struct, you can always use hashes and spare yourself the hassle: %blah = (test => 'asdf'); print "prints my value: '$blah{test}'\n"; or $blah = {test => 'asdf'}; print "prints my value: '$blah->{test}'\n";
{ "pile_set_name": "StackExchange" }
Q: « à minuit trente précises » ou bien « à minuit trente précis » {j’ai dit} : Je suis rentré chez moi à minuit trente précises cette nuit. ... Puis ma collègue m’a fait remarquer qu’il fallait plutôt dire « à minuit trente précis ». Pour moi, « à minuit trente précises » est assorti d’un invisible mot « minutes ». C’est ce pourquoi je penche pour « précises ». Notre discussion tourne en rond là-dessus... A: On doit dire normalement je pense: à minuit trente précis. Bien qu'on fasse la faute, par similarité avec: à deux heures trente précises http://www.cnrtl.fr/definition/pr%C3%A9cis Citation: Il n'est pas question de modifier le programme qui invariablement et quoi qu'il arrive commence à deux heures précises http://bdl.oqlf.gouv.qc.ca/bdl/gabarit_bdl.asp?id=2892 Citation: Précis est un adjectif qui s’accorde avec le mot heure(s) qu’il qualifie. On écrira minuit précis et midi précis puisque ces noms sont au masculin singulier. Le 31 décembre à minuit précis, c’est le début d’une nouvelle année. Donc je pense qu'il en est de même pour minuit trente précis.
{ "pile_set_name": "StackExchange" }
Q: xaxis/yaxis lines in matlab plot couldn't find this: I would like to plot a line on X and Y axis that always fits to 100% to the width or height of the figure. figure; hold on; plot(rand(1,100)); line(xlim,[.5 .5],'Color','red'); line([50 50],ylim,'Color','red'); pause(.5) xlim([1 200]);% lines should now automatically extend with grid on it's possible to get a grid that scales automatically, however it seems impossible to only limit the grid to the X/Y axes. Ideas? after scaling: what I would prefer: A: The functions xline and yline were introduced in MATLAB R2018b, and do exactly as you need. Furthermore, it is possible to add a (text) label to the line.
{ "pile_set_name": "StackExchange" }
Q: there exist an extension such that this element is a zerodivisor? Everyone knows that if in a ring A a unit a $\in$ A can´t be a zerodivisor. But could also be possible that "a" not be a zero divisor ( i.e does not exist a nonzero x $\in$ A , such that $ax=0$) but neither a unit ( in A ) in this case My question is so simple in this case, considering the ring of fractions, we know that there exist an extension such that "a" is a unit . My question is, in this case, there exist other extension $J$ of $A$ , such that $a$ is a zero divisor in J ( i.e there exist a nonzero x $\in$ $J$ , such that $ax=0$) . So the question is obviously false if we consider "a" as a unit, but I think that here could be true. Remark : I think that we may assume that A is commutative, but I´m not completely sure ( because we use the ring of fractions the commutative property is needed otherwise the sum in the fraction won´t be commutative). If you note that other properties are also needed please let me know ( like identity , etc). A: I believe you are asking if a is not a unit in the (unital, commutative, associative) ring A, then is there a ring B with A ≤ B a (unital) subring of B such that a is a zero divisor in B, that is, such that there is some nonzero b in B with ab = 0. The answer is yes, there is always such a ring B when a is not a unit of A (and of course no when a is a unit of A). Consider the ring $R=A[x]/(ax)$ and define a homomorphism $f:R\to B$ that is the identity on A and takes x to b. This is well-defined since ab = 0. In R we also have that ax = 0, and since $f(x) = b \neq 0$, we must also have $x \neq 0$. Hence we might as well assume $B=R$ in the first place, but then we'll still need to prove $x \neq 0$ in R. Saying that $x = 0 $ in $R$ is the same as saying $x+(ax) = 0+(ax)$, which simply means $x \in (ax)$, where these ideals are all in $A[x]$. If $x \in (ax)$, then $x = rax$ for some $r \in A[x]$, but obviously by degree arguments, $r \in A$. Hence $ra=1$ and $a$ is a unit. The background material is just ideals, quotient rings, and polynomial rings. Switching from B to R is called considering a "universal example". As far as the non-commutative case goes, most everything already goes wrong and you can no longer invert some non-zero divisor elements.
{ "pile_set_name": "StackExchange" }
Q: A list of data from a DB showed in the form of LinkButtons list- How to achieve this in ASP.net? I'm making a photographer website. It retrieves the categories of the images and show it as a list of link buttons. The user can click on a certain link buttons to show that categories images. I thought of adding a BulletedList and then dynamically adding those link buttons to it, but it produces and error that I can't nest controls inside the list item. This was what I attempted to do: <div id="gallery_wrapper"> <div id="cat_wrapper" runat="server"> <asp:BulletedList ID="BulletedList1" runat="server"> <asp:ListItem Text=""><asp:LinkButton runat="server">LinkButton</asp:LinkButton></asp:ListItem> </asp:BulletedList> </div> <div id="img_wrapper" runat="server">test_img</div> </div> But it produces this parse error: Parser Error Message: The 'Text' property of 'asp:ListItem' does not allow child objects. My question is how can I show category names that are retrieved from a DB in the form of a list of link buttons? A: Since you stated that you're really a beginner at this, I think the most helpful thing would be to point you in the right direction for documentation. That said, I'd start with the MSDN introduction to ASP.NET Data Bound Controls There are more than enough approaches in this one page to choose from. Personally, I'd use a Repeater control, or a DataList control. (Code samples for both in the linked article.)
{ "pile_set_name": "StackExchange" }
Q: Representative matrix of an operator I've got this course assignment which instructs me to find a representative matrix of an operator T with regard to the standard basis. The vector space is the set of $2\times2$ matrices over the field of real numbers. T is given as: $$T(A) = MA \qquad \text{in which} \qquad M=\begin{bmatrix} a & b \\ c & d \end{bmatrix}$$ What is the meaning of the term representative matrix in this context? Isn't it M? IDK if that helps, but there is actually a posted answer which is a $4\times4$ matrix, which is a block matrix constructed from the products of M with each of the standard basis vectors. It makes zero sense to me. Thanks A: Do you agree that a 2x2-matrix is the representative matrix of an operator on a vector space of dimention 2 (say, $\mathbb{R}^2$) ? You operator T acts on the vector space of all 2x2-matrix. Do you agree this space is of dimension 4 ? Hence, your task is to write the 4x4-matrix representing T in a base of the 4-dimension space of 2x2-matrix. The canonical base is $\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}$ , $\begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}$ , $\begin{pmatrix} 0 & 0 \\ 1 & 0 \end{pmatrix}$ , $\begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}$ ...
{ "pile_set_name": "StackExchange" }
Q: Matching a regex pattern into an URL when it have a specific number of segments I have urls like these: example.com/test/testurl example.com/test/test-url example.com/test/testurl/content example.com/test/test-url/content I'm working on a redirect in here so, I need a regex to match the url when it has only 2 segments (like the 2 first ones) getting the second segment in a group, but to fail in all the others. Here's the pattern I accomplished so far: test\/(\w+)(?!\/)\b This one matches the first url and fails on the third, great. But it ends up matching the second and fourth url, capturing the word up to the dash. I'm pulling my hair out on this one, any pointers are appreciated. Thanks in advance ! :) A: First throw out \b. That's to match word boundaries and URLs can contain non-word characters. I'm going to make the assumption that you're getting the url in its own string without any other accompanying text. That being the case the following regex will: match the start of a string match one or more characters up to the first forward slash match /test/ match one or more characters up to another slash optionally match a slash match the end of a string REGEX ^[^/]+/test/[^/]+/?$ REY NO MATCH: example.com/test/ MATCH: example.com/test/testurl MATCH: example.com/test/test-url MATCH: example.com/test/test-url/ NO MATCH: example.com/test/testurl/content NO MATCH: example.com/test/test-url/content Also if you need to add the protocol, you can rewrite the regex thusly: ^[^:]+://[^/]+/test/[^/]+/?$
{ "pile_set_name": "StackExchange" }