text
stringlengths
64
81.1k
meta
dict
Q: Complex Analysis Weierstrass Test Hi there. I am struggling to understand the line: $\frac{1}{2}(e^{-ny}+e^{ny}) \le e^{nr}$ Could someone please help me? A: Generally, for real $t$, we have $e^t \leqslant e^{\lvert t\rvert}$ (and $\lvert e^z\rvert \leqslant e^{\lvert z\rvert}$ for $z\in\mathbb{C}$). Hence for $-r \leqslant y \leqslant r$, we have $$\frac{1}{2}\left(e^{-ny} + e^{ny}\right) \leqslant \frac{1}{2}\left(e^{\lvert -ny\rvert} + e^{\lvert ny\rvert}\right) = \frac{1}{2}\left(e^{n\lvert y\rvert} + e^{n\lvert y\rvert}\right) = e^{n\lvert y\rvert} \leqslant e^{nr}.$$
{ "pile_set_name": "StackExchange" }
Q: Swift Firestore using an Array to get document fields I am using an array named PosterEmail to search for a document field name "First Name" in my Firestore Database. Here you can see my database set up. FirebaseSetup enter image description here As you can see my Database is Public then in the document I have the user's email as the document name and in that document I have their information such as their first name, last name, and profile photo url. I search for the document id using an Array The PosterEmail array is PosterEmail = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"] I am going through my PosterEmail index by setting a variable "profilecount" to 0 and adding 1 to it everytime to go through the PosterArray let docRef = db.collection("Public").document("\(self.PosterEmail[self.profilecount])") But it seems that the code above never searches for the Firebase document named after the second item in my Array The result is just ["Irving ", "Irving ", "Irving ", "Irving "] The result should end up as [Irving, Allmight, Allmight, Irving] Is there something I"m doing wrong? Below is where I call my getPosteInformation() in another method called getDatFromFirestore() (ehhh I know my method name has a typo but I can fix that later) if let postedBy = document.get("postedBy") as? String { print("Postby = document.get(postedby = \(postedBy)") self.PosterEmail.append(postedBy) if self.PosterEmail.count > 0 { self.getPosteInformation() } } } } } Below you can see my full code. func getDatFromFirestore() { let firestoreDatabase = Firestore.firestore() firestoreDatabase.collection("Posts").order(by: "Date" , descending : true).getDocuments { (snapshot, error) in if error != nil { print(error?.localizedDescription ?? "Connection Error") } else { self.userPostImageArray.removeAll(keepingCapacity: false) self.userCommentArray.removeAll(keepingCapacity: false) self.userCommentArray.removeAll(keepingCapacity: false) self.likeArray.removeAll(keepingCapacity: false) self.PosterEmail.removeAll(keepingCapacity: false) self.userProfilePhotoArray.removeAll(keepingCapacity: false) self.PosterFirstNameArray.removeAll(keepingCapacity: false) self.PosterLastNameArray.removeAll(keepingCapacity: false) for document in snapshot!.documents { let documentID = document.documentID self.documentIDArray.append(documentID) if let postDescription = document.get("PostDescription") as? String { self.userPostDescription.append(postDescription) } if let imageUrl = document.get("imageUrl") as? String { self.userPostImageArray.append(imageUrl) } if let PostLikes = document.get("Likes") as? Int { self.likeArray.append(PostLikes) } if let postTimeStamp = document.get("Date") as? Timestamp { let date = postTimeStamp.dateValue() let formatter = DateFormatter() formatter.dateFormat = "HH:mm MM/dd/yyyy" let dateString = formatter.string(from: date) let timeStampAsString = dateString self.postDate.append(timeStampAsString) } if let postedBy = document.get("postedBy") as? String { print("Postby = document.get(postedby = \(postedBy)") self.PosterEmail.append(postedBy) if self.PosterEmail.count > 0 { self.getPosteInformation() } } } } } self.VidaFeed.reloadData() } func getPosteInformation() { print("") print(PosterEmail[profilecount]) print(profilecount) print("") print(PosterEmail) let docRef = db.collection("Public").document("\(self.PosterEmail[self.profilecount])") docRef.getDocument { (document, error) in if let document = document, document.exists { let dataDescription = document.data().map(String.init(describing:)) ?? "nil" print("Document data: \(dataDescription)") if self.profilecount < self.PosterEmail.count { if let PosterFirstName = document.get("First Name") as? String { self.PosterFirstNameArray.append(PosterFirstName) print(self.PosterFirstNameArray) print("\(self.profilecount)") if self.PosterEmail.count > self.profilecount { self.profilecount = self.profilecount + 1 } } } } else { print("Document does not exist") } } } A: if let postedBy = document.get("postedBy") as? String { print("Postby = document.get(postedby = \(postedBy)") self.PosterEmail.append(postedBy) self.PosterFirstNameArray.append("") if self.PosterEmail.count > 0 { self.getPosteInformation(profCount: self.profileCount) } if self.PosterEmail.count > self.profilecount { self.profilecount = self.profilecount + 1 } } And now if you could modify this method like this: func getPosteInformation(profCount:Int) { //and inside the async call back instead of the following try /*if let PosterFirstName = document.get("First Name") as? String { self.PosterFirstNameArray.append(PosterFirstName) print(self.PosterFirstNameArray) print("\(self.profilecount)") if self.PosterEmail.count > self.profilecount { self.profilecount = self.profilecount + 1 } }*/ if let PosterFirstName = document.get("First Name") as? String { self.PosterFirstNameArray[profCount] = PosterFirstName print(self.PosterFirstNameArray) print("\(profCount)") } }
{ "pile_set_name": "StackExchange" }
Q: Include fileson python If I had two files on the same folder this is functions.py #!/usr/bin/python # -*- coding: utf-8 -*- def foo(): print "bar" and this is main.py #!/usr/bin/python # -*- coding: utf-8 -*- import functions functions.foo() If I want to use the foo() function I have yo call it functions.foo() ,there is a way yo call it only foo()? A: Try with from functions import foo But it may cause some problems if you're working with lots of files and you might come with two functions with the same name. I'd stick with the ugly way you had in the first time.
{ "pile_set_name": "StackExchange" }
Q: iOS: How to add different frameworks for device and simulator in the same code xcode swift? I have a third party framework with different versions for simulator and real device. What I am doing: Right now I maintain two different targets for simulator and device respectively. I need to add the framework to the target as well as to the embedded binaries section. I also have to import the header in the bridging header section as these are objc frameworks ( I have added swift compiler flags for each targets and import the necessary headers in bridging header section). If I add both frameworks in same target, it will give duplicate symbols error. NB: I Don't have the source code for these frameworks. So I cannot build a universal framework and use. Question: How can I use these frameworks such that , without changing any code or settings, I should be able to run the code on simulator as well as on a real device? A: I do this using an aggregate build target for the framework that runs a shell script. That script uses xcodebuild to create a framework for both the sim and the device, and then uses lipo to combine them into a single framework that can be included in any project, and work on both platforms. Here's a simplified version: #!/bin/sh BASE_BUILD_DIR=${BUILD_DIR} FRAMEWORK_NAME="FrameworkName" PROJECT_NAME="Framework" CONFIG=$CONFIGURATION UNIVERSAL_OUTPUTFOLDER="Build/${CONFIG}-universal" # make sure the output directory exists mkdir -p "${UNIVERSAL_OUTPUTFOLDER}" # Step 1. Build Device and Simulator versions xcodebuild -target "${PROJECT_NAME}" -configuration ${CONFIG} -sdk iphoneos ONLY_ACTIVE_ARCH=NO BUILD_DIR="${BASE_BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" clean build xcodebuild -target "${PROJECT_NAME}" -configuration ${CONFIG} -sdk iphonesimulator ONLY_ACTIVE_ARCH=NO BUILD_DIR="${BASE_BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" clean build # Step 2. Copy the framework structure (from iphoneos build) to the universal folder echo "copying device framework" cp -R "${BASE_BUILD_DIR}/${CONFIG}-iphoneos/${FRAMEWORK_NAME}.framework" "${UNIVERSAL_OUTPUTFOLDER}/" # Step 3. Copy Swift modules (from iphonesimulator build) to the copied framework directory echo "integrating sim framework" cp -R "${BASE_BUILD_DIR}/${CONFIG}-iphonesimulator/${FRAMEWORK_NAME}.framework/Modules/${FRAMEWORK_NAME}.swiftmodule/" "${UNIVERSAL_OUTPUTFOLDER}/${FRAMEWORK_NAME}.framework/Modules/${FRAMEWORK_NAME}.swiftmodule/" # Step 4. Create universal binary file using lipo and place the combined executable in the copied framework directory echo "lipo'ing files" lipo -create -output "${UNIVERSAL_OUTPUTFOLDER}/${FRAMEWORK_NAME}.framework/${FRAMEWORK_NAME}" "${BASE_BUILD_DIR}/${CONFIG}-iphonesimulator/${FRAMEWORK_NAME}.framework/${FRAMEWORK_NAME}" "${BASE_BUILD_DIR}/${CONFIG}-iphoneos/${FRAMEWORK_NAME}.framework/${FRAMEWORK_NAME}" # Step 5. Convenience step to copy the framework to the project's directory mkdir -p "${PROJECT_DIR}/iOS Framework/" rm -rf "${PROJECT_DIR}/iOS Framework/${FRAMEWORK_NAME}.framework" cp -R "${UNIVERSAL_OUTPUTFOLDER}/${FRAMEWORK_NAME}.framework" "${PROJECT_DIR}/iOS Framework"
{ "pile_set_name": "StackExchange" }
Q: Help with partitioning scheme for new Kubuntu dual boot I have a 256 GB SSD and a 1TB HDD in my laptop. I want to dual-boot Kubuntu 20.04 with Windows 10. Please explain what exactly do /var and /tmp do, because I need to do some web developing and want to know whether I should make separate partitions for them. Also, to save space on the SSD, can I mount /home, /var etc. on the HDD, without a significant increase in boot time? I heard that root partition will have to wait for mounting from HDD, which will increase boot time. Besides, should I make separate /opt and /usr, too. My current planning is: 11GB swap in SSD, 45GB root partition in SSD, 1GB /boot in SSD, and 50GB /home in HDD. I have also heard that separate /boot partition is not needed in SSD. So please guide me. Thank you!! A: It's better to have a boot partition for Linux on your SSD and 512MB will be enough. It's OK to have /home on your HDD (that won't slow down boot significantly). If you don't expect to have many gigabytes worth of MySQL (or any other DB) data there's no need to have a separate partition for /var. Likewise for /opt. It's not clear what you'll be running. Backup your EFI System partition before installing Linux just in case.
{ "pile_set_name": "StackExchange" }
Q: For " Follow active quads" method, do I need to make the entire object active or just the outside face? I have modeled this coffee cup. I used materials and different colors to make different faces. When completed I plan on exporting it to second life as a 3D object. I marked seams and unwrapped it. The "island" with the arrow is the brown outside face of the cup. I need some experienced advise on how to unwrap this cup so it will properly take a texture. If I use the "Follow active quads method", do I need to use it to unwrap the entire cup, all at once? Should I try to unwrap island by island? A: You can use Follow Active Quads on any selection you want. I doesn't have to be the whole mesh. Example of unwrapping a part of mesh using Follow Active Quads.
{ "pile_set_name": "StackExchange" }
Q: PDO MYSQL_ATTR_USE_BUFFERED_QUERY Not taking affect I have the following rough code (full code is 146 lines, 90 of which are string parsing, can add if needed): ini_set('memory_limit', '7G'); $db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true)); $db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); $db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true)); $db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); $stmt = $db->prepare('select columns from stats where timestamp between ? and ?'); $stmt->execute(array('2020-04-25', '2020-05-25')); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo memory_get_usage() .PHP_EOL; echo $row['id'] . PHP_EOL; $stmt2 = $db_ub->prepare('select somedata from users limit 1'); $stmt2->execute(); $row2 = $stmt2->fetch(PDO::FETCH_ASSOC); $type = !empty($row2['somedate']) ? 5 : 4; $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)'); $result->execute(array($row['id'], $type)); } during $stmt->execute(array('2020-04-25', '2020-05-25')); my memory consumption is as .34GB (using ps aux | grep 'php ' | awk '{$5=int(100 * $5/1024/1024)/100"GB";}{ print;}' to monitor consumption during select and show full processlist SQL side to verify). Once the script enters the while it jumps to +5 GB. Testing the setattribute var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)); seems like it has taken affect: bool(true) but the behavior doesn't change when I switch buffered or unbuffered. $db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false) and $db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true) Using echo $db->getAttribute(constant('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')); also shows the setting changes. Moving the setting to the statement rather than connection as https://www.php.net/manual/en/ref.pdo-mysql.php suggested also didn't work. $stmt = $db->prepare('select columns from stats where timestamp between ? and ?', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false)); I've also tried moving the buffer setting to the connection with no affect: $db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false)); Taking out the second connection seems to allow the unbuffered query to function as intended: ini_set('memory_limit', '1G'); $db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false)); $db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); //$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true)); //$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); $stmt = $db->prepare('select columns from stats where timestamp between ? and ?'); $stmt->execute(array('2019-01-25', '2019-11-25')); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo memory_get_usage() .PHP_EOL; echo $row['id'] . PHP_EOL; /* $stmt2 = $db_ub->prepare('select somedata from users limit 1'); $stmt2->execute(); $row2 = $stmt2->fetch(PDO::FETCH_ASSOC); $type = !empty($row2['somedate']) ? 5 : 4; $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)'); $result->execute(array($row['id'], $type)); */ } This usage the memory_get_usage doesn't exceed 379999. If I uncomment the second connection and make it unbuffered as well I receive: Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. The second connection buffered performs as initially described, large memory consumption on execution. If ini_set('memory_limit' is high it works if low it errors. Using a large memory_limit isn't a feasible solution. Was using (Red Hat Enterprise Linux Server release 7.3 (Maipo)): php71u-pdo.x86_64 7.1.19-1.ius.centos7 Moved script to a newer machine (Amazon Linux release 2 (Karoo)): php73-pdo.x86_64 7.3.17-1.el7.ius and have the same behavior. A: The PDO::ATTR_PERSISTENT value is not boolean. It identifies the connection being used, use unique values for multiple connections. In my case: $db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => 'unbuff', PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false)); $db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => 'buff', PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
{ "pile_set_name": "StackExchange" }
Q: nivo slider, is a way to always show the next and prev arrows? I am using nivo slider( default theme) and I positioned the prev and next arrows next to the image(not on top of the image) and I was wondering if there is a way to always show the next and prev arrows(right now the arrows only show when you hover over the image). Seems there should be a way to edit the code to do this but I can't seem to figure out where. Thanks! A: directionHideNav: false doesn't work as of 3.1. Changes now need to be made in CSS In the theme css file find the line .theme-default .nivo-directionNav a Change: opacity: 0; to opacity: 1; A: Right way is; just change or add directionNavHide value and set it to false in nivoSlider settings. $('#slider').nivoSlider({directionNavHide:false}); A: open the nivoslider js file and find {a(".nivo-directionNav",f).hide();f.hover(function(){a(".nivo-directionNav",f).show()},function(){a(".nivo-directionNav",f).hide()} change to {a(".nivo-directionNav",f).show();f.hover(function(){a(".nivo-directionNav",f).show()},function(){a(".nivo-directionNav",f).show()} Save an upload.
{ "pile_set_name": "StackExchange" }
Q: Update end time and duration in same time, using TIMESTAMPDIFF PHP MYSQL I want to update 'duration' and 'end_time' field in same query/action. 'end_time' field filled current time, 'duration' field filled from different minute between 'start' and 'end_time' field. when i execute this update, the result in 'duration' field is 0. How to get end_time and duration in same time. this is the php code : <?php include("koneksi.php"); $id = $_GET['id']; $start = gmdate("Y-m-d H:i:s", time()+60*60*7); $end_time = gmdate("Y-m-d H:i:s", time()+60*60*7); $duration = $_POST['duration']; $query = "update billing set end_time='$end_time', duration = TIMESTAMPDIFF(MINUTE, '$start', '$end_time') where id='$id'"; $result = mysql_query($query); if ($result){ echo '<script language="javascript">window.location = "../?p=los"</script>'; } ?> A: Duration is being set to 0 because $start and $end_time are the same. Consider your code: $start = gmdate("Y-m-d H:i:s", time()+60*60*7); $end_time = gmdate("Y-m-d H:i:s", time()+60*60*7); $query = "... TIMESTAMPDIFF(MINUTE, '$start', '$end_time') ..."; Because $start == $end_time, the difference will always be 0. You probably want to use the value of start_time already stored in the database, not the recently created php variable $start. Perhaps something like this: $query = " update billing set end_time='$end_time', duration = TIMESTAMPDIFF(MINUTE, start_time, '$end_time') where id='$id' "; where start_time is a column in the database. Note: mysql_* functions are deprecated, and you are susceptible to SQL injection. Consider using mysqli or pdo and utilize prepared statements.
{ "pile_set_name": "StackExchange" }
Q: C# code works but errors occur while packaging my UWP application in Visual Studio 2017 I have created a UWP application in Visual Studio. I plan on using it only for side loading(it is a LOB app). It doesn't have any errors. But when I try to package it, I get the following errors. Errors in Packaging 0X8007000b an attempt was made to load a program with an incorrect format Also, here is my output console. How do I fix this? A: From the solution explorer, double click and open Package.appxmanifest Click on Visual Assets tab on top. It is second from left, after Application tab. Select a source image (this is the image you want to use for logos, badges, splash screen, etc.) Under assets combo box, select all All Visual Assets Hit Generate Say ok that it will overwrite your existing files Now, if you want to use a different image for any of the specific areas, for example, App Icon, scroll down, and provide a different source for it. Now, build and make sure your app builds. Then attempt to create the app package again.
{ "pile_set_name": "StackExchange" }
Q: Node JS project returns '[object Object]' instead of displaying tweets from stream I'm creating a Node JS project that fetches and displays tweets on a server in the form of a list. However, when I go to view the webpage after running main.js, it returns a list of '[object Object]' instead of the tweets. I have tried using JSON.stringify but to no avail. Perhaps I'm using it incorrectly? I'm using Node.js, Express.js, and Pug. main.js 'use strict'; const express = require('express'), Twitter = require('twitter'), passport = require('passport'), TwitterStrategy = require('passport-twitter').Strategy, request = require('request'), app = express(), tweets = []; const T = new Twitter({ consumer_key: 'vLHfUa437ECQDnCqbikfpHnxh', consumer_secret: 'ygZ6HH19vMwm3hGQnSFGKimaBNClzPZUWKoq4TKXqNnOTZPkP4', access_token_key: '898531406703407108-qkmMO2wAyyXjo8XIG2B59dSlWY6OXZQ', access_token_secret: 'vBNdwsDeaI8WNQ1gWdtp70keg0EsutgpWNeliD56uj8v6' }); T.stream('statuses/filter', {track: 'love'}, function(stream){ stream.on('data', function(data){ if ('delete' in data === false){ tweets.push(data); } }); setTimeout(function(){ console.log(tweets.length); }, 1000); }); app.set('view engine', 'pug'); app.set('views', './views'); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(express.static('resources')); app.get('/', function(req, res) { res.setHeader("Content-Type", 'text/html'); res.render('index', {tweets: tweets}); }); app.listen(3000, function () { console.log('Listening on http://localhost:3000'); }); index.pug doctype html head meta(charset="UTF-8") meta(name="viewport", content="width=device-width, initial-scale=1") block title title This is the title! link(rel='stylesheet', href='/css/style.css', type='text/css') body ul each tweet in tweets li= tweet A: As Piyush pointed out, you are working with an object and need to dig further into that object before strings are pulled out. To display each tweet individually (which I assume you're looking to do), simply change the following: tweets.push(data); to this... tweets.push(data.text); Bam! Now you're displaying the actual text string for each tweet that matches your filter.
{ "pile_set_name": "StackExchange" }
Q: How to randomize website test using jmeter? I want to test multiple scenarios in a same website using JMeter. For example I have 2 thread users. I want.. >1st user performing 1st scenario: like login his account >2nd user performing 2nd scenario: browse some other page How this can be achieved in JMeter? A: If you need 50% of users to perform login and 50% of users to browse the website there are following options available: Use 2 separate Thread Groups: Thread Group 1: with virtual users who perform login Thread Group 2: with virtual users who perform browsing Use Throughput Controller like: Add Throughput Controller configured like: Percent Executions 50.0 Add the relevant sampler(s) under the Throughput Controller (as child) Do the same for 2nd, etc. scenarios See Running JMeter Samplers with Defined Percentage Probability article for more detailed explanation of above and more complex distribution scenarios.
{ "pile_set_name": "StackExchange" }
Q: How to divide a figure and convert it to decimal but the remainder I want to be able to divide 9245 by 1000 and get 9.245, and then push this number to my textview. my code gives me 9.0 and not the remainder. Hope do I keep the remainder? String playerScore1 = gameInfo.getGame_time() / 1000; playerscore1.setText(Double.toString(playerScore1)); A: If getGame_time() method does not return a double/float, you need to explicitly add .0 to dividend, or cast it to double/float type. gameInfo.getGame_time() / 1000.0; Java by default performs integer division, which truncates the decimal part of result. To force floating point division you can also use suffix notation: int/1000f int/1000d
{ "pile_set_name": "StackExchange" }
Q: JavaFX representing directories I am building an application in Java where I need to represent a predefined directory in any kind of view in my window. Imagine something like a backup application where the main window displays all of the files under a specific directory. Is there a way to do so using JavaFX? I do not care if files are going to be displayed as a tree or icons or anything really. Thanks edit: what I tried so far with no luck. This is my Controller class: import javafx.scene.control.*; import java.io.IOException; public class ViewController { public ListView listView; public ViewController() throws IOException { listView = new ListView(); listView.getItems().addAll("Iron Man", "Titanic", "Contact", "Surrogates"); } } and my fxml contains: <ListView fx:id="listView" prefHeight="200.0" prefWidth="200.0" /> A: I wrote up a brief program that displays a tree of files and directories chosen by the user. The result: How it works: When the user clicks the "Load Folder" button, getNodesForDirectory is called, and recursively walks through the file tree, making tree items along the way. Here is the code: import java.io.File; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.layout.BorderPane; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; public class DirectoryViewer extends Application { @Override public void start(Stage primaryStage) { TreeView<String> a = new TreeView<String>(); BorderPane b = new BorderPane(); Button c = new Button("Load Folder"); c.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { DirectoryChooser dc = new DirectoryChooser(); dc.setInitialDirectory(new File(System.getProperty("user.home"))); File choice = dc.showDialog(primaryStage); if(choice == null || ! choice.isDirectory()) { Alert alert = new Alert(AlertType.ERROR); alert.setHeaderText("Could not open directory"); alert.setContentText("The file is invalid."); alert.showAndWait(); } else { a.setRoot(getNodesForDirectory(choice)); } } }); b.setTop(c); b.setCenter(a); primaryStage.setScene(new Scene(b, 600, 400)); primaryStage.setTitle("Folder View"); primaryStage.show(); } public static void main(String[] args) { launch(args); } public TreeItem<String> getNodesForDirectory(File directory) { //Returns a TreeItem representation of the specified directory TreeItem<String> root = new TreeItem<String>(directory.getName()); for(File f : directory.listFiles()) { System.out.println("Loading " + f.getName()); if(f.isDirectory()) { //Then we call the function recursively root.getChildren().add(getNodesForDirectory(f)); } else { root.getChildren().add(new TreeItem<String>(f.getName())); } } return root; } } Good luck with your project!
{ "pile_set_name": "StackExchange" }
Q: Seemingly correct type signature refused in where block I have been messing around with continuation passing style in Haskell. Taking the Cont monad apart and removing the type wrappers helped me in understanding the implementation. Here is the code: {-# LANGUAGE ScopedTypeVariables #-} import Control.Monad (ap) newtype Cont r a = Cont {runCont :: (a -> r) -> r} instance Functor (Cont r) where fmap f ka = ka >>= pure . f instance Applicative (Cont r) where (<*>) = ap pure = return instance Monad (Cont r) where ka >>= kab = Cont kb' where -- kb' :: (b -> r) -> r kb' hb = ka' ha where -- ha :: (a -> r) ha a = (kab' a) hb -- ka' :: (a -> r) -> r ka' = runCont ka -- kab' :: a -> (b -> r) -> r kab' a = runCont (kab a) return a = Cont ka' where -- ka' :: (a -> r) -> r ka' ha = ha a This code compiles (using GHC 8.0.2) and everything seems fine. However, as soon as I uncomment any of the (now commented) type signatures in the where block I get an error. For exapmle, if I uncomment the line -- ka' :: (a -> r) -> r I get: β€’ Couldn't match type β€˜a’ with β€˜a1’ β€˜a’ is a rigid type variable bound by the type signature for: (>>=) :: forall a b. Cont r a -> (a -> Cont r b) -> Cont r b at cont.hs:19:6 β€˜a1’ is a rigid type variable bound by the type signature for: ka' :: forall a1. (a1 -> r) -> r at cont.hs:27:14 Expected type: (a1 -> r) -> r Actual type: (a -> r) -> r β€’ In the expression: runCont ka In an equation for β€˜ka'’: ka' = runCont ka In an equation for β€˜>>=’: ka >>= kab = Cont kb' where kb' hb = ka' ha where ha a = (kab' a) hb ka' :: (a -> r) -> r ka' = runCont ka kab' a = runCont (kab a) β€’ Relevant bindings include ka' :: (a1 -> r) -> r (bound at cont.hs:28:7) kab' :: a -> (b -> r) -> r (bound at cont.hs:31:7) kab :: a -> Cont r b (bound at cont.hs:19:10) ka :: Cont r a (bound at cont.hs:19:3) (>>=) :: Cont r a -> (a -> Cont r b) -> Cont r b (bound at cont.hs:19:3) Failed, modules loaded: none. So I tried using a type wildcard to let the compiler tell me what type signature I should put there. As such I tried the following signature: ka' :: _ Which gave the following error: β€’ Found type wildcard β€˜_’ standing for β€˜(a -> r) -> r’ Where: β€˜r’ is a rigid type variable bound by the instance declaration at cont.hs:15:10 β€˜a’ is a rigid type variable bound by the type signature for: (>>=) :: forall a b. Cont r a -> (a -> Cont r b) -> Cont r b at cont.hs:19:6 To use the inferred type, enable PartialTypeSignatures β€’ In the type signature: ka' :: _ In an equation for β€˜>>=’: ka >>= kab = Cont kb' where kb' hb = ka' ha where ha a = (kab' a) hb ka' :: _ ka' = runCont ka kab' a = runCont (kab a) In the instance declaration for β€˜Monad (Cont r)’ β€’ Relevant bindings include ka' :: (a -> r) -> r (bound at cont.hs:28:7) kab' :: a -> (b -> r) -> r (bound at cont.hs:31:7) kab :: a -> Cont r b (bound at cont.hs:19:10) ka :: Cont r a (bound at cont.hs:19:3) (>>=) :: Cont r a -> (a -> Cont r b) -> Cont r b (bound at cont.hs:19:3) Failed, modules loaded: none. Now I am really confused, the compiler tells me the type of ka' is (a -> r) -> r but as soon as I try to explicitely annotate ka' with this type, compiling fails. First I thought I was missing ScopedTypeVariables but it does not seem to make a difference. What is going on here? EDIT This is similar to the question " Why does this function that uses a scoped type variable in a where clause not typecheck? " in that it requires an explicit forall to bind type variables. However it is not a duplicate since the answer to this question also requires the InstanceSigs extension. A: Makes sense. After all, where did those as and bs come from? We have no way to know they're connected to the polymorphism of (>>=) and return. It's easy to fix, though, as mentioned in the comments: give (>>=) and return type signatures that mention a and b, toss in the requisite language extension, and hey presto: {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE InstanceSigs #-} import Control.Monad (ap) newtype Cont r a = Cont {runCont :: (a -> r) -> r} instance Functor (Cont r) where fmap f ka = ka >>= pure . f instance Applicative (Cont r) where (<*>) = ap pure = return instance Monad (Cont r) where (>>=) :: forall a b. Cont r a -> (a -> Cont r b) -> Cont r b ka >>= kab = Cont kb' where kb' :: (b -> r) -> r kb' hb = ka' ha where ha :: (a -> r) ha a = (kab' a) hb ka' :: (a -> r) -> r ka' = runCont ka kab' :: a -> (b -> r) -> r kab' a = runCont (kab a) return :: forall a. a -> Cont r a return a = Cont ka' where ka' :: (a -> r) -> r ka' ha = ha a I feel like there's a Dragonball joke in all these kas and has, but the joke escapes me.
{ "pile_set_name": "StackExchange" }
Q: Want to use three DatePicker and Display it on TextView I am tryin to set three DatePicker and want to display selected date in TextView. I tried alot but generating an error like:- ATAL EXCEPTION: main Process: com.example.sachin.datepicker, PID: 5708 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setInputType(int)' on a null object reference at com.example.sachin.datepicker.MainActivity.onCreateView(MainActivity.java:40) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758) Here I posted complete code of it.. just take a look on it, MainActivity2.java package com.example.sachin.datepicker; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Main2Activity extends AppCompatActivity { Button next; FragmentManager mFragmentManager; FragmentTransaction mFragmentTransaction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); next= (Button)findViewById(R.id.next); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mFragmentManager = getSupportFragmentManager(); mFragmentTransaction = mFragmentManager.beginTransaction(); mFragmentTransaction.replace(R.id.containerView,new MainActivity()).commit(); } }); } } Here, MainActivity.java package com.example.sachin.datepicker; import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.icu.text.SimpleDateFormat; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.InputType; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.DatePicker; import android.widget.EditText; import java.util.Calendar; import java.util.Locale; public class MainActivity extends Fragment implements View.OnClickListener { public MainActivity() {}; EditText openingdate,Birthdate,Anniversary; private DatePickerDialog fromDatePickerDialog; private DatePickerDialog toDatePickerDialog; private DatePickerDialog toDatePickerDialog1; private SimpleDateFormat dateFormatter; View view; @TargetApi(Build.VERSION_CODES.N) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.activity_add_wod, container, false); dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); openingdate = (EditText) view.findViewById(R.id.openingdate); openingdate.setInputType(InputType.TYPE_NULL); openingdate.requestFocus(); Birthdate = (EditText)view. findViewById(R.id.Birthdate); Birthdate.setInputType(InputType.TYPE_NULL); Birthdate.requestFocus(); Anniversary = (EditText)view. findViewById(R.id.Anniversary); Anniversary.setInputType(InputType.TYPE_NULL); setDateTimeField(); return view; } private void setDateTimeField() { openingdate.setOnClickListener(this); Birthdate.setOnClickListener(this); Anniversary.setOnClickListener(this); Calendar newCalendar = Calendar.getInstance(); fromDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @TargetApi(Build.VERSION_CODES.N) public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); openingdate.setText(dateFormatter.format(newDate.getTime())); } },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); toDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @TargetApi(Build.VERSION_CODES.N) public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); Birthdate.setText(dateFormatter.format(newDate.getTime())); } },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); toDatePickerDialog1 = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @TargetApi(Build.VERSION_CODES.N) public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); Anniversary.setText(dateFormatter.format(newDate.getTime())); } },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); } // @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getActivity().getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View view) { if(view == openingdate) { fromDatePickerDialog.show(); } else if(view == Birthdate) { toDatePickerDialog.show(); } else if(view == Anniversary) { toDatePickerDialog1.show(); } } } and lastly manifest file <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sachin.datepicker"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <Activity android:name=".MainActivity" /> <activity android:name=".Main2Activity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> I tried alot but always getting error... A: .setInputType(InputType.TYPE_CLASS_DATETIME); Change all in .setInputType, try below code also. @TargetApi(Build.VERSION_CODES.N) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.activity_add_wod, container, false); dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); openingdate = (EditText) view.findViewById(R.id.openingdate); openingdate.setInputType(InputType.TYPE_NULL); openingdate.requestFocus(); Birthdate = (EditText) view.findViewById(R.id.Birthdate); Birthdate.setInputType(InputType.TYPE_NULL); Birthdate.requestFocus(); Anniversary = (EditText) view.findViewById(R.id.Anniversary); Anniversary.setInputType(InputType.TYPE_NULL); setDateTimeField(); return view; } private void setDateTimeField() { openingdate.setOnClickListener(this); Birthdate.setOnClickListener(this); Anniversary.setOnClickListener(this); Calendar newCalendar = Calendar.getInstance(); fromDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @TargetApi(Build.VERSION_CODES.N) public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); openingdate.setText(dateFormatter.format(newDate.getTime())); } },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); toDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @TargetApi(Build.VERSION_CODES.N) public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); Birthdate.setText(dateFormatter.format(newDate.getTime())); } },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); toDatePickerDialog1 = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @TargetApi(Build.VERSION_CODES.N) public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); Anniversary.setText(dateFormatter.format(newDate.getTime())); } },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); } @Override public void onClick(View view) { if(view == openingdate) { fromDatePickerDialog.show(); } else if(view == Birthdate) { toDatePickerDialog.show(); } else if(view == Anniversary) { toDatePickerDialog1.show(); } }
{ "pile_set_name": "StackExchange" }
Q: How should I implement a "quiet period" when raising events? I'm using a subscriber/notifier pattern to raise and consume events from my .Net middle-tier in C#. Some of the events are raised in "bursts", for instance, when data is persisted from a batch program importing a file. This executes a potentially long-running task, and I'd like to avoid firing the event several times a second by implementing a "quiet period", whereby the event system waits until the event stream slows down to process the event. How should I do this when the Publisher takes an active role in notifying subscribers? I don't want to wait until an event comes in to check to see if there are others waiting out the quiet period... There is no host process to poll the subscription model at the moment. Should I abandon the publish/subscribe pattern or is there a better way? A: Here's a rough implementation that might point you in a direction. In my example, the task that involves notification is saving a data object. When an object is saved, the Saved event is raised. In addition to a simple Save method, I've implemented BeginSave and EndSave methods as well as an overload of Save that works with those two for batch saves. When EndSave is called, a single BatchSaved event is fired. Obviously, you can alter this to suit your needs. In my example, I kept track of a list of all objects that were saved during a batch operation, but this may not be something that you'd need to do...you may only care about how many objects were saved or even simply that a batch save operation was completed. If you anticipate a large number of objects being saved, then storing them in a list as in my example may become a memory issue. EDIT: I added a "threshold" concept to my example that attempts to prevent a large number of objects being held in memory. This causes the BatchSaved event to fire more frequently, though. I also added some locking to address potential thread safety, though I may have missed something there. class DataConcierge<T> { // ************************* // Simple save functionality // ************************* public void Save(T dataObject) { // perform save logic this.OnSaved(dataObject); } public event DataObjectSaved<T> Saved; protected void OnSaved(T dataObject) { var saved = this.Saved; if (saved != null) saved(this, new DataObjectEventArgs<T>(dataObject)); } // ************************ // Batch save functionality // ************************ Dictionary<BatchToken, List<T>> _BatchSavedDataObjects = new Dictionary<BatchToken, List<T>>(); System.Threading.ReaderWriterLockSlim _BatchSavedDataObjectsLock = new System.Threading.ReaderWriterLockSlim(); int _SavedObjectThreshold = 17; // if the number of objects being stored for a batch reaches this threshold, then those objects are to be cleared from the list. public BatchToken BeginSave() { // create a batch token to represent this batch BatchToken token = new BatchToken(); _BatchSavedDataObjectsLock.EnterWriteLock(); try { _BatchSavedDataObjects.Add(token, new List<T>()); } finally { _BatchSavedDataObjectsLock.ExitWriteLock(); } return token; } public void EndSave(BatchToken token) { List<T> batchSavedDataObjects; _BatchSavedDataObjectsLock.EnterWriteLock(); try { if (!_BatchSavedDataObjects.TryGetValue(token, out batchSavedDataObjects)) throw new ArgumentException("The BatchToken is expired or invalid.", "token"); this.OnBatchSaved(batchSavedDataObjects); // this causes a single BatchSaved event to be fired if (!_BatchSavedDataObjects.Remove(token)) throw new ArgumentException("The BatchToken is expired or invalid.", "token"); } finally { _BatchSavedDataObjectsLock.ExitWriteLock(); } } public void Save(BatchToken token, T dataObject) { List<T> batchSavedDataObjects; // the read lock prevents EndSave from executing before this Save method has a chance to finish executing _BatchSavedDataObjectsLock.EnterReadLock(); try { if (!_BatchSavedDataObjects.TryGetValue(token, out batchSavedDataObjects)) throw new ArgumentException("The BatchToken is expired or invalid.", "token"); // perform save logic this.OnBatchSaved(batchSavedDataObjects, dataObject); } finally { _BatchSavedDataObjectsLock.ExitReadLock(); } } public event BatchDataObjectSaved<T> BatchSaved; protected void OnBatchSaved(List<T> batchSavedDataObjects) { lock (batchSavedDataObjects) { var batchSaved = this.BatchSaved; if (batchSaved != null) batchSaved(this, new BatchDataObjectEventArgs<T>(batchSavedDataObjects)); } } protected void OnBatchSaved(List<T> batchSavedDataObjects, T savedDataObject) { // add the data object to the list storing the data objects that have been saved for this batch lock (batchSavedDataObjects) { batchSavedDataObjects.Add(savedDataObject); // if the threshold has been reached if (_SavedObjectThreshold > 0 && batchSavedDataObjects.Count >= _SavedObjectThreshold) { // then raise the BatchSaved event with the data objects that we currently have var batchSaved = this.BatchSaved; if (batchSaved != null) batchSaved(this, new BatchDataObjectEventArgs<T>(batchSavedDataObjects.ToArray())); // and clear the list to ensure that we are not holding on to the data objects unnecessarily batchSavedDataObjects.Clear(); } } } } class BatchToken { static int _LastId = 0; static object _IdLock = new object(); static int GetNextId() { lock (_IdLock) { return ++_LastId; } } public BatchToken() { this.Id = GetNextId(); } public int Id { get; private set; } } class DataObjectEventArgs<T> : EventArgs { public T DataObject { get; private set; } public DataObjectEventArgs(T dataObject) { this.DataObject = dataObject; } } delegate void DataObjectSaved<T>(object sender, DataObjectEventArgs<T> e); class BatchDataObjectEventArgs<T> : EventArgs { public IEnumerable<T> DataObjects { get; private set; } public BatchDataObjectEventArgs(IEnumerable<T> dataObjects) { this.DataObjects = dataObjects; } } delegate void BatchDataObjectSaved<T>(object sender, BatchDataObjectEventArgs<T> e); In my example, I choose to use a token concept in order to create separate batches. This allows smaller batch operations running on separate threads to complete and raise events without waiting for a larger batch operation to complete. I made separete events: Saved and BatchSaved. However, these could just as easily be consolidated into a single event. EDIT: fixed race conditions pointed out by Steven Sudit on accessing the event delegates. EDIT: revised locking code in my example to use ReaderWriterLockSlim rather than Monitor (i.e. the "lock" statement). I think there were a couple of race conditions, such as between the Save and EndSave methods. It was possible for EndSave to execute, causing the list of data objects to be removed from the dictionary. If the Save method was executing at the same time on another thread, it would be possible for a data object to be added to that list, even though it had already been removed from the dictionary. In my revised example, this situation can't happen and the Save method will throw an exception if it executes after EndSave. These race conditions were caused primarily by me trying to avoid what I thought was unnecessary locking. I realized that more code needed to be within a lock, but decided to use ReaderWriterLockSlim instead of Monitor because I only wanted to prevent Save and EndSave from executing at the same time; there wasn't a need to prevent multiple threads from executing Save at the same time. Note that Monitor is still used to synchronize access to the specific list of data objects retrieved from the dictionary. EDIT: added usage example Below is a usage example for the above sample code. static void DataConcierge_Saved(object sender, DataObjectEventArgs<Program.Customer> e) { Console.WriteLine("DataConcierge<Customer>.Saved"); } static void DataConcierge_BatchSaved(object sender, BatchDataObjectEventArgs<Program.Customer> e) { Console.WriteLine("DataConcierge<Customer>.BatchSaved: {0}", e.DataObjects.Count()); } static void Main(string[] args) { DataConcierge<Customer> dc = new DataConcierge<Customer>(); dc.Saved += new DataObjectSaved<Customer>(DataConcierge_Saved); dc.BatchSaved += new BatchDataObjectSaved<Customer>(DataConcierge_BatchSaved); var token = dc.BeginSave(); try { for (int i = 0; i < 100; i++) { var c = new Customer(); // ... dc.Save(token, c); } } finally { dc.EndSave(token); } } This resulted in the following output: DataConcierge<Customer>.BatchSaved: 17 DataConcierge<Customer>.BatchSaved: 17 DataConcierge<Customer>.BatchSaved: 17 DataConcierge<Customer>.BatchSaved: 17 DataConcierge<Customer>.BatchSaved: 17 DataConcierge<Customer>.BatchSaved: 15 The threshold in my example is set to 17, so a batch of 100 items causes the BatchSaved event to fire 6 times.
{ "pile_set_name": "StackExchange" }
Q: Css nΓ£o muda a cor para transparente Tenho um menu de um site onde especionando o elemento eu mudo para uma cor transparente mais ele nao muda, mesmo colocando como !important na frente da propriedade. Veja: Nesse menu ele esta assim no meu style.css .navigation{ height:50px; background:rgba(243, 241, 245, 0.04) !important; -webkit-box-shadow:0 0 3px rgba(0,0,0,.4); -moz-box-shadow:0 0 3px rgba(0,0,0,.4); box-shadow:0 0 3px rgba(0,0,0,.4); -webkit-border-radius:0 0 4px 4px; -moz-border-radius:0 0 4px 4px; border-radius:0 0 4px 4px; z-index:2; text-align:center; font-family: 'Roboto Condensed', sans-serif; position:absolute; top:0; } no background esta ja em transparente mais mesmo assim, quando eu recarrego a pagina ele volta para a cor : background: #f8f7f3; AlguΓ©m tem ideia o por que nΓ£o segura o valor rgb que ue coloco? A: Para resolver essa questΓ£o, na prΓ³pria pagina onde esta incorporada o menu, aplica a transparencia chamando a chasse referente ao menu. veja: <style> .navigation{ background:rgba(243, 241, 245, 0.04) !important; } </style> ForΓ§ando assim o css aplicar a ultima regra feita na pΓ‘gina onde esta o menu.
{ "pile_set_name": "StackExchange" }
Q: Strategy or Adapter pattern? I want to create some classes of each Virtual Server Provider, for example: Digital Ocean Linode Amazon AWS Each Provider has own PHP class (via composer) to use their API interface, I want to use their class library but I want to make sure I can use same method for each provider. For example of shutting down VPS: Linode API method: powerOff() Digital Ocean API method: haltServer() Rather than using powerOff() and haltServer() - I want to use shutdown() method for any providers classes I will create. Should I use Strategy design or Adaptor pattern? A: Should I use Strategy design or Adaptor pattern? This is the classic mistake everyone makes when designing an application (including myself). You should ideally not skim through the list of available design patterns and pick one that best matches your problem. Instead, you should come up with an initial class design and then try to identify the pattern that best describes your design. This safeguards you from over-designing i.e, creating unnecessary components which you don't otherwise require. With time, you soon have a vocabulary of design patterns that you have actually used rather than an application that tries to use a particular design pattern. Leaving design patterns aside, it looks like what you are searching for is a way to provide a common interface for performing the same functionality using different underlying libraries/approaches. This sounds a lot like Abstraction and Delegation. You can achieve Abstraction by defining a common interface called Provider with the standard operation methods such as shutdown, connect, retry, etc. You can then create one concrete provider class for each type of provider such as AWSProvider and LinodeProvider and implement the shutdown, connect and retry methods. You then use Delegation by calling the provider specific APIs within these methods. For example, call the powerOff method inside shutdown method of LinodeProvider class. If you now take a good look at your design, you will start to realize that it looks like the Strategy as well as the Aadpter pattern. What distinguishes the two patterns is the point of time where the Abstraction comes into play. If you decide the Provider implementation to be used via a Factory at runtime of the application, you are using the Strategy pattern; however, if this decision is made at compile time, you are using the Adapter pattern. Other than the name of the pattern, your classes will pretty much look the same. The advantage of this approach is that you have not only identified the right pattern, but you have also safeguarded yourself from over-designing the application by using patterns such as the Command pattern.
{ "pile_set_name": "StackExchange" }
Q: add defer / async in production bundle using angular cli 7 I’m getting some performance issues in new site using angular cli 7 production in special for mobile browsers, after check I discovered the main reason for the poor performance it was missing the pre / async in my javascript bundles generated for angular cli. I would like know if has any alternative to use angular cli 7 in order to add defer/async in the final bundles , I tried to search and I found out many alternatives for the old angular cli versions include one feature suggestion but not for the newlys versions because since the angular version 6 it not possible eject the webpack configuration and customize , add plugins , etc. A: There are no magic solution from angular cli part, however I found out about custom builders that works well for me. https://www.npmjs.com/package/@angular-builders/custom-webpack#custom-webpack-config-object angular-cli.json "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "outputPath": "dist/browser", "index": "src/index.html", "main": "src/main.ts", "tsConfig": "src/tsconfig.app.json", "polyfills": "src/polyfills.ts", "assets": [ "src/assets", "src/favicon.ico" ], "styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/photoswipe/dist/photoswipe.css", "node_modules/photoswipe/dist/default-skin/default-skin.css", "src/styles.scss" ], "scripts": [], "customWebpackConfig": { "path": "./webpack-extra.config.js", "mergeStrategies": {"plugins": "replace"} } }, webpack-extra.config const HtmlWebpackPlugin = require('html-webpack-plugin'); const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); const CompressionPlugin = require('compression-webpack-plugin'); module.exports = { plugins: [ new HtmlWebpackPlugin({ "template": "./src\\index.html", "filename": "./index.html", "hash": false, "inject": true, "compile": true, "favicon": false, "minify": { "caseSensitive": true, "collapseWhitespace": true, "keepClosingSlash": true, "removeComments": true, "removeRedundantAttributes": true }, "cache": true, "showErrors": true, "chunks": "all", "excludeChunks": [], "title": "Webpack App", "xhtml": true, "chunksSortMode": "none" }), new ScriptExtHtmlWebpackPlugin({ defaultAttribute: 'defer' }), new CompressionPlugin({ test: /\.js(\?.*)?$/i }) ] };
{ "pile_set_name": "StackExchange" }
Q: Are links without anchor text bad for seo? we are currently redesigning our website and certain elements have the following structure: <div class="Item"> <div class="Text"> <span class="Name">Name of Profile</span> <span class="City">City</span> </div> <div class="Link"> <a href="http://example.com/"></a> </div> </div> My question would be, if an empty anchor text is bad for SEO and Google. How do they handle this kind of links currently? I did a search on this issue but only found very old entries which said that Google even banned the website, but back in 2002. Any information or suggestion on this would be much appreciated. Thanks. A: By using empty anchor text you will not prevent from indexing your pages but you will loose a good opportunity to add relevance to your pages. Empty anchor text is not critical Google does not need an anchor text to follow a @href URL (bot will be able to find your pages) It's impossible to get a website banned from Google for this. But anchor text is really helpful for ranking Google uses anchor text in order to qualify the resources you create a reference to. In consequences if a page got links with "example" as anchor text pointing to itself, this page relevance on "example" request will increase. So better do not let empty anchor text and choose wisely the words (or keywords) you use in it.
{ "pile_set_name": "StackExchange" }
Q: HTML/JavaScript using JSP and JSTL - select dropdown only showing first option on iphone instead of selected option I have a <select> element in my html: <select id="mySelect"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> I am using JSP/JSTL for the back end, and when the page loads I want to dynamically select one of these options based on a page attribute I get from the back end. In other words, in JavaScript/jQuery: $(document).ready(function() { $("#mySelect").find("option[val=${Var}]").prop("selected", true); }); Ideally, when the page loads, the <select> element should show the option that is selected on screen (e.g if ${Var} is 4, it should display 4 by default, and allow the user to use the drop down to select any of the other options. This works fine in my browser and on Android devices, but when testing it on my iPhone 5S, the <select> displays the first option instead of the option that is selected when the page loads (the option with a value of ${Var}). Any tips on how to ensure that it displays the correct selected value? A: You can do it like this, when your page loads, it will execute this javascript: var test = '<%= request.getAttribute("var") %>'; Here the var "test" will contain the attribute you set in your servlet called "var". Then to make things easier, i am using jquery in this example, you can set your dropdown value to var. (but you must make sure that the dropdown select has a value with the variable var.) If var == 4 then it will set the dropdown select to value 4 on load. $("#mySelect").val(test);
{ "pile_set_name": "StackExchange" }
Q: WPF Custom/User Control for button with text and icon. Which one should I choose? I'd like to refactor the following code using a custom control for the button. Xaml file: LoginWindow.xaml <Button Grid.Column="0" Style="{DynamicResource BlackLoginButton}" Click="btnLogin_Click" IsDefault="True"> <DockPanel> <TextBlock Text="text1" VerticalAlignment="Center"/> <Image Source="../../../Assets/Images/apply.png" Style="{StaticResource ImageButton}" /> </DockPanel> </Button> Code behind: LoginWindow.xaml.cs private void btnLogin_Click(object sender, EventArgs e) { Login(); } I particular I'd like to have a structure like this: <local:CustomButton> Grid.Column="0" IsDefault="True" Style="{DynamicResource BlackLoginButton}" Click="btnLogin_Click" Text="ciao" Image="../../../Assets/Images/apply.png"> </local:CustomButton> I try to use both Custom Control and User Control. Here is my UserControl xaml <UserControl x:Class="foo.View.CustomUserControl.IconButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <Button Style="{DynamicResource BlackLoginButton}"> <DockPanel> <TextBlock VerticalAlignment="Center" Text="{Binding ElementName=Button, Path=Text}" /> <Image Source="{Binding ElementName=Button, Path=Image}" Style="{StaticResource ImageButton}" /> </DockPanel> </Button> </UserControl> And the code behind: using System.Windows; using System.Windows.Media; namespace Mhira3D.View.CustomUserControl { public partial class IconButton { public static DependencyProperty ClickProperty = DependencyProperty.Register("Click", typeof(RoutedEventHandler), typeof(IconButton)); public static DependencyProperty ImageProperty = DependencyProperty.Register("Image", typeof(ImageSource), typeof(IconButton)); public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(IconButton)); public IconButton() { InitializeComponent(); } public RoutedEventHandler Click { get { return (RoutedEventHandler) GetValue(ClickProperty); } set { SetValue(ClickProperty, value); } } public ImageSource Image { get { return (ImageSource) GetValue(ImageProperty); } set { SetValue(ImageProperty, value); } } public string Text { get { return this.GetValue(TextProperty) as string; } set { this.SetValue(TextProperty, value); } } } } The main problem of this structure is that I cannot use Button property (I did not inherit from button), for example I cannot use IsDefault. I think it could be an alternative use a CustomControl, to use the button property in a better way, like this (in thi example I put only the Image property): public class IconButtonCustom : Button { static IconButtonCustom() { DefaultStyleKeyProperty.OverrideMetadata(typeof(IconButtonCustom), new FrameworkPropertyMetadata(typeof(IconButtonCustom))); } public ImageSource Image { get { return GetValue(SourceProperty) as ImageSource; } set { SetValue(SourceProperty, value); } } public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Image", typeof(ImageSource), typeof(IconButtonCustom)); } And the style in Generic.xaml <Style TargetType="{x:Type customUserControl:IconButtonCustom}" BasedOn="{StaticResource BlackLoginButton}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type customUserControl:IconButtonCustom}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <DockPanel> <TextBlock VerticalAlignment="Center" Text="{Binding ElementName=Button, Path=Text}" /> <Image Source="{Binding ElementName=Button, Path=Image}" Style="{StaticResource ImageButton}" /> </DockPanel> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> Now I have some questions: Which of these methods is the more suitable to create my custom button? Using both methods, I have problem mapping the click function, in fact I got the System.Windows.Markup.XamlParseException because WPF cannot convert the string btnLogin_Click in the function Click. I've never used Generic.xaml, is my example correct or should be improved in some way? A: Alrighty, so most Framework elements have a handy-dandy property called Tag that exists for instances like these where we could use a way to piggy-back something into a template without having to go and declare additional dependency properties and such. So if we take a default Button style template (Right-Click the button->Edit Template->Edit a Copy) we see a ContentPresenter in there that will generally pass any CLR object. So we're good there for your text, or whatever else you want. We now have multiple options to accomplish your goal. One would be to simply pass in your two elements this way (in pseudo); <Button> <StackPanel Orientation="Horizontal"> <TextBlock/> <Image/> </StackPanel> </Button> Except that seems a bit tedious. So we move into the Style Template option and instead do something like this to it; <Style x:Key="SpecialButtonStyle" TargetType="{x:Type Button}"> <!-- We set a default icon/image path for the instance one isn't defined. --> <Setter Property="Tag" Value="../../../Assets/Images/apply.png"/> <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/> <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/> <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="HorizontalContentAlignment" Value="Center"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Padding" Value="1"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> <!-- This is where we've added an Image to our Button with it's source bound to Tag. PS - In everything else like Silverlight, WP, UWP, Embedded etc, it's just {TemplateBinding Tag} --> <Image Grid.Column="1" Source="{Binding Path=Tag, RelativeSource={RelativeSource TemplatedParent}}"/> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsDefaulted" Value="true"> <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> </Trigger> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/> <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/> </Trigger> <Trigger Property="IsPressed" Value="true"> <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/> <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/> <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/> <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> Notice the added Image element with it's Source set to {TemplateBinding Tag} along with a setter at the top specifying a string path to what could be a default image. So now at the instance we could just do; <Button Content="Blah Blah Blah" Click="Click_Handler" Style="{StaticResource SpecialButtonStyle}"/> ...and we would get a button, with the default icon, and your click handler. Except now we need to display different icons for each instance. So we could do something like; <Button Content="Blah Blah Blah" Click="Click_Handler" Tag="../../../Assets/Images/DIFFERENTIMAGE.png" Style="{StaticResource SpecialButtonStyle}"/> Except that still seems a little daunting. So we could take it a step further and make your asset strings into resources. Add the mscorlib namespace to you dictionary as something like `xmlns:sys" prefix and you could do this; <sys:String x:Key="imageONE">../../../Assets/Images/imageONE.png</sys:String> <sys:String x:Key="imageTWO">../../../Assets/Images/imageTWO.png</sys:String> <sys:String x:Key="imageTHREE">../../../Assets/Images/imageTHREE.png</sys:String> This does us a few benefits. One, much easier maintenance in case you need to change the file path/name for one of those icons. You can do it in just one spot and it will inherit to all instances. Instead of having to track down each instance it's hard set at. It also allows us to invoke these at the instance as a resource, so now our Button instance would look like this; <Button Content="Blah Blah Blah" Click="Click_Handler" Tag="{StaticResource imageTWO}" Style="{StaticResource SpecialButtonStyle}"/> Voila, you're done. However another observation you should consider, is your file paths. I would definitely use Pack Uri instead. As long as your path is correct and your build action on the image is also you should be set. Hope this helps, cheers.
{ "pile_set_name": "StackExchange" }
Q: Beyond calculating just as an exercise, are there any other reasons to calculate an indefinite integral? Calculus textbooks often have us calculate indefinite integrals as exercises. However, beyond calculating just as an exercise, are there any other reasons to calculate an indefinite integral? A: I am guessing you want to emphasize solving indefinite integrals vs. definite integrals. To state the obvious, if you don't know how to do the former, you won't be able to do the latter. So there's a good reason. Beyond that evaluating indefinite integrals is key to solving many important differential equations. ('Important' here means a few things, including many applications.)
{ "pile_set_name": "StackExchange" }
Q: Why does my custom class not recognize swift extensions? (i.e. String) I have a string extension in which I define a function that calculates the DamerauLevenshtein distance between two different strings. When adding the following code: var result = "Hello" result.damerauLevenshteinTo("Hellow") in any other class such as a UIViewController, UITableViewController, etc. the code compiles fine. As soon as I try adding it to my own class defined as class CustomClass: AnyObject I get the following error message. Value of type String has no member 'damerauLevenshteinTo' What am I missing? Thanks! Update Copy pasting the entire class with the extension to an empty project compiles great... Moving it to the old project still gives me the error no matter what I try. Update 2 It seems I can't use any custom classes or subclasses inside this class. Hm... Update 3 Deleting the file and pasting the class in a new one got rid of the error after about the third time... Hurray A: How did you add the class with the extension? I added some classes into my project which included extensions, and the rest of the code wouldn't recognize the extensions. It appears that this was because I had added the files using "Create folder references" option instead of "Create groups" option. I deleted what I had added, then added them again with "Create groups" option selected. This fixed it for me. I'm didn't pursue why using references might result in this behavior, because I had intended to add them with the "Create groups" option to begin with.
{ "pile_set_name": "StackExchange" }
Q: RSS subscription implementation on express server I'm setting up a node.js server that subscribes to an RSS feed. When a new item is published to the feed, I want the server to parse that information and pass it to an API which will alert end users. Can I use feedparser as my subscriber? I understand that this library creates an EventEmitter that fires actions. Is it possible to export this function and make it run in parallel with my Express application? Taken from the parser examples: const FeedParser = require('feedparser') const request = require('request') const subscriber = async () => { const req = request('https://www.reddit.com/.rss') const feedparser = new FeedParser() req.on('error', (error) => { console.log(error) }) req.on('response', (r) => { const stream = this if (r.statusCode !== 200) { this.emit('error', new Error('bad status code')) } else { stream.pipe(feedparser) } }) feedparser.on('readable', () => { // This is where the action is! const stream = this var item = '' while (item = stream.read()) { console.log(item) } }) return feedparser } module.exports = { subscriber } When I call this function, I am expecting the console to log new items but I am not getting any items. The reason why is unclear. Bonus Question: Can I validate the subscription is working without having to wait for new items to be published? Is there an RSS tool or website that can simulate the behavior? A: Couple of things I learned: RSS Feeds don't send information. If you want to subscribe to one, you need to make the requests on an interval and parse new information: Subscribe to an RSS Feed Any functionality that doesn't require handling incoming requests probably doesn't need to be used in your Express middleware, you can just start the RSS subscription interval immediately before/after starting your HTTP server: var app = require('../app'); var http = require('http'); var port = normalizePort(process.env.PORT || '3000'); app.set('port', port); /** * Create HTTP server. */ var server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Start the subscriber */ var feed = new RssFeed({your rss feed url}, 60000); // 60000 = 60 second refresh rate feed.start(); Also including an incomplete snippet of my implementation: const Parser = require('rss-parser') class RssSubscriber extends Parser { constructor (url, interval) { super() this.url = url this.interval = interval this.latestPublishTime = null } start () { // execute on an interval setInterval(async () => { try { console.log('Fetching feed...') const news = await this.parseFeed() await Promise.all(news.map(n => { return this.alert(n) })) } catch (err) { console.log('WARN: Error Encountered when fetching subscription items.') } }, this.interval) }
{ "pile_set_name": "StackExchange" }
Q: Interpreting a formula tattoo I saw on the Internet and I'm curious as to what compound is represented by it. A: The molecule seen in the tattoo is a protein-based mammalian hormone called oxytocin, commonly called "the love hormone" because it is involved in several aspects of sexual reproduction. Image Source
{ "pile_set_name": "StackExchange" }
Q: Hiding table body when all the rows are hidden in angularjs I'm trying to display a table with activities, with a row displaying the day and after that the list of activities for this day. I also want the user to be able to filter the activities. "myActivities" is a Map with the user's activities assigned to true, and the rest to false. my code looks like this: <table> <tbody ng-repeat="date in dates"> <tr><td>{{date.day}}</td></tr> <tr ng-repeat="activity in date.activities" ng-show="myActivities[activity.id] == true"> <td>{{activity.time}}</td><td>{{activity.name}}</td> </tr> </tbody> </table> The problem with that is when there is a day with no relevant activities for the user, the row displaying the date is still shown but all the activities under it are hidden. I successfully solved the problem with this function: $scope.checkDate = function(activities) { activities.forEach(function(activity){ if (myActivities[activity.id] == true) return true; }); return false; } //added the ng-show to the tbody in the html: <tbody ng-repeat="date in dates" ng-show="checkDate(date.activities)"> It works perfectly, but is this the best solution? I have a feeling that there is a nicer solution. any ideas ? Thanks! A: You can assign the filtered variables to the date object, and check the length of that property: <table> <tbody ng-repeat="date in dates" ng-show="date.filteredActivities.length"> <tr> <td>{{ date.day }}</td> </tr> <tr ng-repeat="activity in (date.filteredActivities = (date.activities | filter: { active: true }))"> <td>{{ activity.time }}</td> <td>{{ activity.name }}</td> </tr> </tbody> </table>
{ "pile_set_name": "StackExchange" }
Q: How can I code a loop that compares every element of an unordered_set with all the others, using iterators in C++? I have an unordered_set and I need to pick each element and compare it with all the others. Notes: If A and B are compared, I don't need to compare B and A. My unordered_set is the value of an unordered_map, for which the key is a pair. I tried the following: unordered_map <pair<int, int>, unordered_set <int>, boost::hash<std::pair<int,int>>> gridMap; unordered_map <int, rigidBody*> objectsMap; auto gridMapIt = gridMap.begin(); while (gridMapIt != gridMap.end()) // loop the whole gridMap { auto setItOut = gridMapIt->second.begin(); while (setItOut != gridMapIt->second.end()) // loop each element of the set { auto setItIn = gridMapIt->second.begin(); while (setItIn != gridMapIt->second.end()) // versus each other element { //compare and do stuff ++setItIn; } checked.insert({ objectsMap[*setItOut]->getID(), objectsMap[*setItIn]->getID() }); checked.insert({ objectsMap[*setItIn]->getID(), objectsMap[*setItOut]->getID() }); ++setItOut; } ++gridMapIt; } The error I am getting is "Expression: cannot dereference end list iterator". If I remove or comment the innermost while loop, it works fine. Thanks in advance. A: The use of *setItIn after the loop is invalid. At that point you have an iterator that points past the last element. That's what the error is telling you. If you change from while to for you can use the scoping rules to stop yourself from dereferencing invalid iterators. Rather than populate checked, you can start the inner loop from the next element, rather than the first. for (auto & gridElem : gridMap) { for (auto setItOut = gridElem.second.begin(), setEnd = gridElem.second.end(); setItOut != setEnd; ++setItOut) { for (auto setItIn = std::next(setItOut); setItIn != setEnd; ++setItIn) { //compare and do stuff } // setItIn not visible here } }
{ "pile_set_name": "StackExchange" }
Q: In what state is a person affected by Hypnotic Pattern? Can they make saving throws? I'm reading the Hypnotic Pattern description and it says "Charmed, Incapacitated, Speed (0)" and "Snaps out of it, if being shaken or takes damage." Then I read the various states you can be under: Charmed: can't attack the caster Incapacitated: can't take actions or reactions - is a save an action/reaction? Immobilized (Speed 0): Somewhere between Paralyzed, Restrained and Stunnedβ€‰β€”β€Šwhich all say you auto fail Strength and Dexterity saves and people have advantage on attacking you. If I were to Fireball an individual (or group) under the influence of Hypnotic Pattern, would they get a Dexterity save to duck out of harm's way? A: Hypnotic Pattern has no impact on a saving throw whatsoever. It imposes both the Charmed and Incapacitated conditions and having a speed of 0 does not automatically impose the immobilized, paralyzed, restrained, or stunned conditions, it just means you have a speed of 0. In fact, immobilized isn't even a condition in 5e. Rules for saving throws can be found on page 179 of the Player's Handbook and nowhere does it say that they use either an action or a reaction, it simply says they "represent an attempt to resist a spell, a trap, a poison, a disease, or a similar threat" so being Incapacitated has no effect on this. Being charmed means you can't attack or target the charmer with harmful effects but in no way affects your ability to "resist a spell, a trap, a poison, a disease, or a similar threat". Conditions and spells that do affect savings throws explicitly note this fact in their descriptions. A: A save is neither an action nor a reaction - if it were, you would need to use your action or reaction in order to make a save. Effects that influence saves should always be clearly noted, because the save mechanic is an important part of the game. Speed 0 is not the same as applying the Immobilized condition - except for sharing the effect on speed of course. Creatures under the influence of Hypnotic Pattern may take Dexterity saves as normal (no penalty or disadvantage).
{ "pile_set_name": "StackExchange" }
Q: Latest upto date Selenium guides I've been looking into setting up a Selenium test suite recently but all of the documentation on Selenium I find is quite fragmented. Does anyone had found any good books or blogs on using Selenium Grid with ruby that could be of use to me? Thanks A: Did you try below links : http://www.jroller.com/selenium/entry/selenium_overview_tutorial http://www.seleniumhq.org/docs/01_introducing_selenium.html
{ "pile_set_name": "StackExchange" }
Q: Set up a VPN inside my VPC. Why can I not connect to other hosts on the VPC? Note: there is a similar quiestion here, but I do not understand the answer. I have just set up a VPN server using OpenVPN on an EC2 host inside my VPC. I've configured the VPN to tunnel all of my internet traffic through the VPN. I've connected to the VPN successfully and it does appear to be working (my public IP has changed). The issue is that I cannot connect to any other hosts in the VPC. If I edit my security groups to explicitly whitelist my IP, then I can connect, but that was not the intention of setting up the VPN. What set am I missing? A: If I edit my security groups to explicitly whitelist my IP, then I can connect, I am more than absolutely sure that the reason for the issue is your security group configuration. If the problem was in your routes, changing security groups haven't made any difference. but that was not the intention of setting up the VPN. Security group is acting like a firewall. If you want to connect to an instance, you need to allow connection via a specified port from a specified resourse. Otherwise, everything that behind your firewall will not be available. So the only solution is to add your IP to the security group exlusion. Primary goal of a VPN in AWS is to access instances that are located in private subnets (in other words, not available via public internet) from your on-premises. An example is described here: http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Scenario4.html
{ "pile_set_name": "StackExchange" }
Q: Microsoft Azure Startup Task Not Executing I have a simple file in the root of my Web project (which is tied to a Web worker role). The file is named Startup.cmd. This file contains the following line: dir > directory.txt. It executes properly when I run it from the command line and outputs a list of the directory contents to file named directory.txt as you would expect. Similarly, the line ECHO Write this line to file > output.txt does not appear to work either. Inside ServiceDefinition.csdef for my Azure Cloud Service project, I have the following lines: <WebRole name="Website" vmsize="Small"> <Startup> <Task commandLine="Startup.cmd" executionContext="elevated" taskType="simple"></Task> </Startup> .... </WebRole> I believe it is finding the file, because I have tried changing the path and it will throw a build error that it cannot find it. The issue is that when I check my /bin/ directory after debugging to the Azure Debugging Environment, I see Startup.cmd (I have it set to Copy always) but I do not see directory.txt. I'm not sure of another way to confirm that it executed properly. A: I found the following MSDN article useful: http://msdn.microsoft.com/en-us/library/hh180155.aspx. As a result, I made some changes to my Startup.cmd file. I changed the command to: ECHO The current version is %MyVersionNumber% >> "%TEMP%\StartupLog.txt" 2>&1 EXIT /B 0 However, this did not appear to put the output in my temporary directory for my system: C:\Users\username\AppData\Local\Temp. I'm going to presume this is because the Azure Compute Emulator uses a different temp directory I am unaware of. I changed my Startup.cmd to: ECHO The current version is %MyVersionNumber% >> "c:\temp\StartupLog.txt" 2>&1 EXIT /B 0 And updated my configuration to: <WebRole name="Website" vmsize="Small"> <Startup> <Task commandLine="Startup.cmd" executionContext="elevated" taskType="simple"> <Environment> <Variable name="MyVersionNumber" value="1.0.0.0" /> <Variable name="ComputeEmulatorRunning"> <RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated" /> </Variable> </Environment> </Task> </Startup> ... </WebRole> And this did appear to write the file to C:\temp\ upon starting the debugger.
{ "pile_set_name": "StackExchange" }
Q: Π€Π°ΠΉΠ» Π½Π΅ докачиваСтся ΠΏΠΎΠ»Π½ΠΎΡΡ‚ΡŒΡŽ Когда ΠΏΡ‹Ρ‚Π°ΡŽΡΡŒ ΡΠΊΠ°Ρ‡Π°Ρ‚ΡŒ Ρ„Π°ΠΉΠ» с сСрвСра, Ρ„Π°ΠΉΠ» Π½Π°Ρ‡ΠΈΠ½Π°Π΅Ρ‚ ΠΊΠ°Ρ‡Π°Ρ‚ΡŒΡΡ Π² ΠΊΠΎΡ€Ρ€Π΅ΠΊΡ‚Π½ΠΎΠΉ ΠΏΠ°ΠΏΠΊΠ΅, Π½ΠΎ ΠΏΠΎΡ‡Π΅ΠΌΡƒ Ρ‚ΠΎ Π½Π΅ Ρ…ΠΎΡ‡Π΅Ρ‚ ΠΏΡ€ΠΎΠ΄ΠΎΠ»ΠΆΠ°Ρ‚ΡŒ ΠΊΠ°Ρ‡Π°Ρ‚ΡŒΡΡ. ΠŸΠΎΡ‡Π΅ΠΌΡƒ? Π’ΠΎΡ‚ ΠΊΠΎΠ΄: using (WebClient client = new WebClient()) { client.DownloadProgressChanged += delegate(object send, DownloadProgressChangedEventArgs a) { pb.Value = a.ProgressPercentage; }; client.DownloadFileCompleted += delegate(object send, AsyncCompletedEventArgs a) { MessageBox.Show("Π—Π°Π³Ρ€ΡƒΠ·ΠΊΠ° Π±ΠΈΠ»Π΄Π° Π·Π°Π²Π΅Ρ€ΡˆΠ΅Π½Π°"); pb.Visible = false; }; pb.Visible = true; if(File.Exists(FolderDialog.SelectedPath + "/" + version)) File.Delete(FolderDialog.SelectedPath + "/" + version); client.DownloadFile("http://хост.Π΄ΠΎΠΌΠ΅Π½/" + version, FolderDialog.SelectedPath + "/" + version); } A: ΠŸΡ€ΠΎΠ±Π»Π΅ΠΌΠ° Π±Ρ‹Π»Π° с ΠΏΠΎΡ‚ΠΎΠΊΠ°ΠΌΠΈ. Надо ΠΏΠΈΡΠ°Ρ‚ΡŒ Π±Π΅Π· using ΠΈ мСсто DownloadFile Π½Π°Π΄ΠΎ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ DownloadFileAsync. Π’Π°ΠΊ ΠΆΠ΅ Π² эвСнтах Π½Π΅ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ Π°Π½ΠΎΠ½ΠΈΠΌΠ½Ρ‹Π΅ ΠΌΠ΅Ρ‚ΠΎΠ΄Ρ‹. Всё прСкрасно Π·Π°Ρ€Π°Π±ΠΎΡ‚Π°Π»ΠΎ: string n = ((Button)sender).Name; versionD = n.Equals("LoadLastVersionbutton") ? "S1.noext" : n.Equals("LoadPreLastVersionButton") ? "S2.noext" : n.Equals("LoadLastTestVersionbutton") ? "T1.noext" : "T2.noext"; pbd = (ProgressBar)this.Controls.Find(versionD.Equals("S1.noext") ? "LastPB" : versionD.Equals("S2.noext") ? "PreLastPB" : versionD.Equals("T1.noext") ? "TestPB" : "PreTestPB", true)[0]; FolderDialog.ShowDialog(); WebClient client = new WebClient(); Uri url = new Uri("http://Π±Π»Π°Π±Π»Π°Π±Π»Π°.Π΄ΠΎΠΌΠ΅Π½" + versionD); client.DownloadProgressChanged += OnProgressDownloadChenged; client.DownloadFileCompleted += OnDownloadComplete; pbd.Visible = true; if (File.Exists(FolderDialog.SelectedPath + "/" + versionD)) File.Delete(FolderDialog.SelectedPath + "/" + versionD); client.DownloadFileAsync(url, FolderDialog.SelectedPath + "/" + versionD);
{ "pile_set_name": "StackExchange" }
Q: Calculate complexity of algorithm I wrote this algorithm which has to a O(logn) complexity. The first while loops into the arrayList until he find the element with the right value and complexity. I organized the arraylist like an heap. In the second while the elements of the arraylist are reordered according to their priority. Has the first loop complexity O(n) O(logn)? public void increasePriority(T value, int oldPriority, int newPriority) throws PriorityQueueException { if (c.compare(oldPriority, newPriority) > 0) throw new PriorityQueueException("The new priority is lower than the current one"); int i = getSize() - 1; while (i > 0 && !(queue.get(i).getPriority() == oldPriority && queue.get(i).getValue() == value)) { i = getParent(i); } if (i == 0) throw new PriorityQueueException("Element (" + value + "," + oldPriority +") doesn't exits in the queue"); queue.get(i).setPriority(newPriority); while (i > 0 && c.compare(queue.get(i).getPriority(), queue.get(getParent(i)).getPriority()) > 0) { swap(i, getParent(i)); i = getParent(i); } } A: If your arraylist is structured as a heap, then the first loop has complexity O(log n). It starts at the last node and then moves up the heap. Each change of level divides i by 2. As written, your increasePriority method will not work, because it won't necessarily find the node you're looking for. It doesn't look at every node in the heap. For example, given this heap: 1 2 3 4 5 6 7 It will start at node 7, then look at 3, and then look at 1. If you were looking for any other value, your algorithm wouldn't find it. You have to do a sequential search of the arraylist to find the item. Then you can use the second loop to change the priority. So finding the node to change is O(n). Changing the priority once you find it is O(log n). That makes the complexity O(n) + log(n), and because log(n) is very small when compared to n, especially as n becomes large, we call that O(n).
{ "pile_set_name": "StackExchange" }
Q: print hour & minutes in french style I'm using babel, datetime & siunitx but I don't see an automatic way to mark and to write time in the french style. It's possible with plain hour with datetime: SI{18}{\hour} -> 18 h. But for hours & minutes, I don't if exists something better than 14~h~27 -> 14 h 27. An idea ? A: I am not sure of the french style but you can make your own style with datetime: \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{datetime} \newtimeformat{frenchtime}{% \twodigit{\THEHOUR}\ h\ % \twodigit{\THEMINUTE}\ min} \settimeformat{frenchtime} \begin{document} Et maintenant il est exactement \formattime{13}{50}{45}. Ce document a Γ©tΓ© gΓ©nΓ©rΓ© Γ  \currenttime. \end{document} This MWE should produce a ouput like: Et maintenant il est exactement 13 h 50 min. Ce document a Γ©tΓ© gΓ©nΓ©rΓ© Γ  13 h 50 min.
{ "pile_set_name": "StackExchange" }
Q: FunctionInterpolation Errors / Question re Evaluation Order and Options I have using Mathematica functions that takes a Cartesian coordinate relative to the Earth (xyz) and converts it to a latitude, longitude, and altitude (lla). And here it is: xyz2lla = First@GeoPosition@GeoPositionXYZ[#, "WGS84"] & I'm using it to convert a satellite viewing line (line of sight or los) from xyz to lla. For instance, if I have a satellite at the following observation point (obs, meters) looking in the direction of look: obs = {2.560453600382259, 5.245110323032143, -3.819772142191310} 1*^6; look = {-0.233218833096895, -0.814561997858160, -0.531128729720249}; It has the line of sight: obs+d look The transformation xyz2lla is smooth, so I was hoping to use function interpolation: f = FunctionInterpolation[{xyz2lla[obs + # look]} &[d], {d, 2000000, 3700000} ] And while this works, and I get the following lat, lon, alt functions from it: : I also get the following errors that I'm wondering why I get: GeoPositionXYZ::invcoord: "\!\(\"{2.560453600382259*^6 - 0.233218833096895*d, 5.245110323032143*^6 - 0.81456199785816*d, -3.81977214219131*^6 - 0.531128729720249*d}\"\) is not a valid coordinate specification." Thread::tdlen: Objects of unequal length in {-212500.,-70833.3,70833.3,212500.}^{} cannot be combined. >> Thread::tdlen: "Objects of unequal length in {12.2667 +3.14159\ I,11.1681 +3.14159\ I,11.1681,12.2667}\ {}\\n cannot be combined." FunctionInterpolation::nreal: Near d = 2.2125`*^6, the function did not evaluate to a real number. Does anyone have any insight into these errors? Also, how can I adjust the quality of the interpolation / how many points are investigated? A: I don't think InterpolatingFunction is intended to work on vector functions. The doc page doesn't say anything about it. Try for instance f = FunctionInterpolation[{x, x}, {x, 0, 6}] And Table[f[x], {x, 0, 6, 1}] returns (* ==> {0., 0.9999652778, 1.998576389, 3., 4.004131944, \ 4.994409722, 6.} *) So, no two dimensional output. It's probably better to come up with three separate interpolating functions for each of the three components of the output. Having said that, it doesn't look like this is the end of the problems. xyz2llaPhi = GeoPosition[GeoPositionXYZ[obs + # look, "WGS84"]][[1, 1]] &; fPhi = FunctionInterpolation[xyz2llaPhi[d], {d, 2000000, 3700000}] yields Whereas xyz2llaPhi[200000] yields a nice numerical result: (* ==> -34.86629487 *) It looks like the combination of FunctionInterpolation and GeoPosition isn't a healthy one. Somehow, the index d is held unevaluated. A workaround would be to generate a table of values and then use ListInterpolation.
{ "pile_set_name": "StackExchange" }
Q: Aggregate over several variables which contain NA values I have the following data frame: x <- read.table(text = " id1 id2 var1 var2 1 a x 1 NA 2 a x 2 4 3 a y 2 5 4 a y 4 9 5 b x 1 7 6 b y 4 4 7 b x 3 9 8 b y 2 8", header = TRUE) which contains one NA value in the first row. I use the aggregate() function to apply several functions on several variables in one call: aggregate(cbind(var1, var2) ~ id1 + id2, data = x, FUN = function(x) c(mn = mean(x), n = length(x))) This leads to the following output: id1 id2 var1.mn var1.n var2.mn var2.n 1 a x 2 1 4 1 2 b x 2 2 8 2 3 a y 3 2 7 2 4 b y 3 2 6 2 Unfortunately, the complete row which contains an NA value in var2 is dropped for every variable (also var1). Any solution to use the aggregate() function on several variables in one call without losing all rows which contain an NA value? My preferred output should look like this: id1 id2 var1.mn var1.n var2.mn var2.n 1 a x 1.5 2 4 1 2 b x 2.0 2 8 2 3 a y 3.0 2 7 2 4 b y 3.0 2 6 2 A: aggregate(x[c("var1", "var2")], x[c("id1", "id2")], function(x) c(mn = mean(x, na.rm = TRUE), n = sum(!is.na(x)))) # id1 id2 var1.mn var1.n var2.mn var2.n #1 a x 1.5 2.0 4 1 #2 b x 2.0 2.0 8 2 #3 a y 3.0 2.0 7 2 #4 b y 3.0 2.0 6 2
{ "pile_set_name": "StackExchange" }
Q: Make ActiveX buttons not move with cells / Excel Have a couple if ActiveX Command Buttons in a worksheet. When I hide some rows, they move with the cells and end up on top of each other. Which property should I use to tell them to just stay put? A: Right-click the command button and select Format Control. Go to the Properties tab and tick Don't move or size with cells.
{ "pile_set_name": "StackExchange" }
Q: add an image inside a primeNG's DialogModal? I'm trying to display an image inside a primeNG's DialogModal. How can I do it? Html part : <p-dialog header="DΓ©tails de la page" [(visible)]="displayDialog" [responsive]="true" showEffect="fade" [modal]="true" width="1000" (onAfterHide)="onDialogHide()"> <div class="ui-grid ui-grid-responsive ui-fluid" *ngIf="selectedPage" style="font-size:16px;text-align:center;padding:20px"> <div class="ui-grid-row"> <div class="ui-grid-col-12" style="text-align:center"> {{selectedPage.pageId}} <img src={{selectedPage.url}} width="45%" height="85% /> </div> </div> </div> </p-dialog> The result is : A: You seem to forget quotation marks in your html. Also, use object binding [] instead of interpolation {{}} Change <img src={{selectedPage.url}} width="45%" height="85% /> to <img [src]="selectedPage.url" width="45%" height="85%" />
{ "pile_set_name": "StackExchange" }
Q: How To Get PPID I am working on a MS Windows C# Winform project and I cannot get the PPID (Parent Process ID). I've found many solutions but none that seem to work with said OS and language. How can I get PPID? A: If you can use System.Management, it's easy enough: private static int GetParentProcess(int Id) { int parentPid = 0; using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString() + "'")) { mo.Get(); parentPid = Convert.ToInt32(mo["ParentProcessId"]); } return parentPid; } Otherwise you may have to resort to P/Invoke calls via CreateToolhelp32Snapshot like this
{ "pile_set_name": "StackExchange" }
Q: Sort LinkedHashMap with LinkedList as key I want to sort LinkedHashMap that has LinkedList<Integer> as key and float[] as value. For example let's say I have such LinkedHashMap like this: LinkedHashMap<LinkedList<Integer>, float[]> hm = new LinkedHashMap<>(); LinkedList<Integer> linkedlist; linkedlist = new LinkedList<>(); linkedlist.add(10); linkedlist.add(7); hm.put(linkedlist, new float[]{0.14f, 1.2f, 85.01f}); linkedlist = new LinkedList<>(); linkedlist.add(0); linkedlist.add(41); hm.put(linkedlist, new float[]{10.3f, 50.05f, 9.9f}); linkedlist = new LinkedList<>(); linkedlist.add(210); linkedlist.add(3); hm.put(linkedlist, new float[]{17.0f, 4.0f, 2.1f}); Now what I want is the output to be: {0, 41}, {10.3f, 50.05f, 9.9f} {10, 7}, {0.14f, 1.2f, 85.01f} {210, 3}, {17.0f, 4.0f, 2.1f} But when I use suggested solution (suggested by some of you in the comments section saying it is duplicate of another post that already have the right answer - the one below, link to it here) where it created new LinkedHashMap (cos I do not know how to sort the original LinkedHashMap in place by this code, unfortunately) like this: LinkedHashMap<LinkedList<Integer>, float[]> sortedMap = new LinkedHashMap<>(); hm.entrySet() .stream() .sorted(Map.Entry.comparingByKey()) .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue())); hm = sortedMap; My NetBeans 8.0.2 show me error about the line .sorted(Map.Entry.comparingByKey()) saying: incompatible types: inference variable K has incompatible bounds equality constraints: LinkedList<Integer> upper bounds: Comparable <? super K> where K,V are type-variables: K extends Comparable<? super K> declared in method <K,V>comparingByKey() V extends Object declared in method <K,V>comparingByKey() I thought maybe for some reason the values in the LinkedList are wrong so I tested it like this and it shows those are all correct (I tested just first 50 entries as the list have hundreds of them): for (int i = 0; i < hm.size(); i++) { if (i < 50) { for (Map.Entry<LinkedList<Integer>, float[]> entry : hm.entrySet()) { LinkedList<Integer> k = entry.getKey(); System.out.println(k); } } } A: The simple fix: You said that you wanted sorting by the first (0th) element of the list. So specify that: hm.entrySet() .stream() .sorted(Comparator.comparing(me -> me.getKey().get(0))) .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue())); With this sorting let’s try writing out the sorted map afterwards, for example: sortedMap.forEach((k, v) -> System.out.println("" + k + " -> " + Arrays.toString(v))); [0, 41] -> [10.3, 50.05, 9.9] [10, 7] -> [0.14, 1.2, 85.01] [210, 3] -> [17.0, 4.0, 2.1] If you didn’t want to create a new map, you must remove each key before inserting it again for the order to be changed: hm.entrySet() .stream() .sorted(Comparator.comparing(me -> me.getKey().get(0))) .forEachOrdered(x -> { hm.remove(x.getKey()); hm.put(x.getKey(), x.getValue()); }); hm.forEach((k, v) -> System.out.println("" + k + " -> " + Arrays.toString(v))); Now the output is the same as above.
{ "pile_set_name": "StackExchange" }
Q: Missing axis ticks and labels when plotting world map with geom_sf() When plotting a basic world map I'm not getting the lat and long to show up on the axes. I have done an example provided by the geom_sf() on cran and that does show the lat long. This is my code below. library("ggplot2") library("sf") #> Linking to GEOS 3.7.2, GDAL 2.4.2, PROJ 5.2.0 library("rnaturalearth") library("rnaturalearthdata") world <- ne_countries(scale = "medium", returnclass = "sf") class(world) #> [1] "sf" "data.frame" ggplot(data = world) + geom_sf() + coord_sf() This is the example code which does generate the lat long on the axes. nc <- st_read(system.file("shape/nc.shp", package="sf")) #> Reading layer `nc' from data source `/Library/Frameworks/R.framework/Versions/3.6/Resources/library/sf/shape/nc.shp' using driver `ESRI Shapefile' #> Simple feature collection with 100 features and 14 fields #> geometry type: MULTIPOLYGON #> dimension: XY #> bbox: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965 #> epsg (SRID): 4267 #> proj4string: +proj=longlat +datum=NAD27 +no_defs ggplot(nc) + geom_sf() A: coord_sf() only draws axis ticks when the graticule lines actually reach all the way to the axis. In your map of the world, the plot panel is expanded beyond the size of the earth (you can see that the graticule lines end before the edge of the plot panel), and hence no axis ticks are drawn. One way to solve the issue is to turn off the expansion. library("ggplot2") library("sf") #> Linking to GEOS 3.7.2, GDAL 2.4.2, PROJ 5.2.0 library("rnaturalearth") library("rnaturalearthdata") world <- ne_countries(scale = "medium", returnclass = "sf") class(world) #> [1] "sf" "data.frame" ggplot(data = world) + geom_sf() + coord_sf(expand = FALSE) Created on 2019-11-02 by the reprex package (v0.3.0)
{ "pile_set_name": "StackExchange" }
Q: Remote accessing of elasticsearch5? I am working with elastic search 5 and I setup it on my local network. Now I need t access through remote, I had changed my configuration as follows but it not worked. network.host: 0.0.0.0 Any suggestion, please. A: Got the solution to my problem. I have added following configuration to yml file http.host: myIpAddress Reference available here Thank you.
{ "pile_set_name": "StackExchange" }
Q: How can I modify code of all files in folders I need to make some recurrent modification in a lot of files (C++). I need to replace all strcpy() and strcat() by sprintf(). I figured out that the conversion would be made like this : strcpy(out,in) would be sprintf(out,%d,in) and strcat(out,in) would be sprintf(out,out%d,in) What tool could I use to rapidly make all replacement, I can't do it manually there is over 9000 of these to modify. Thanks for your suggestions. I'm using windows xp/linux Ubuntu The reason why I do this is that we plan to implement a method that translate code. And because we are using strcat and all, we can't make a situational translating working well. Because the file where all will be written won have all the stuff in the right order A: I would use the compiler -- or, more accurately, the preprocessor. Specifically, I'd find a project-wide header, and in it add a couple lines like: #define strcpy(out, in) sprintf(out, "%s", in) #define strcat(out, in) sprintf(out+strlen(out), "%s", in) ...and leave the rest of the source code alone. Then when you come to your senses, it'll be easy to change back to being sensible and using strcpy/strcat where they should be.
{ "pile_set_name": "StackExchange" }
Q: Regular expression quoting in Python How should I declare a regular expression? mergedData = re.sub(r'\$(.*?)\$', readFile, allData) I'm kind of wondering why this worked. I thought that I need to use the r'' to pass a regular expression. mergedData = re.sub("\$(.*?)\$", readFile, allData) What does "\$" result in in this case? Why? I would have thought "$". A: I thought that I need to user the r'' to pass a regular expression. r before a string literal indicates raw string, which means the usual escape sequences such as \n or \r are no longer treated as new line character or carriage return, but simply \ followed by n or r. To specify a \, you only need \ in raw string literal, while you need to double it up \\ in normal string literal. This is why it is usually the case that raw string is used in specifying regular expression1. It reduces the confusion when reading the code. You would have to do escaping twice if you use normal string literal: once for the normal string literal escape and the second time for the escaping in regex. What does "\$" result in this case? Why? I would have thought "$" In Python normal string literal, if \ is not followed by an escape sequence, the \ is preserved. Therefore "\$" results in \ followed by $. This behavior is slightly different from the way C/C++ or JavaScript handle similar situation: the \ is considered escape for the next character, and only the next character remains. So "\$" in those languages will be interpreted as $. Footnote 1: There is a small defect with the design of raw string in Python, though: Why can't Python's raw string literals end with a single backslash? A: The r'...' escapes sequences like '\1' (reference to first group in a regular expression, but the same as '\x01' if not escaped). Generally speaking in r'...' the backslash won't behave as an escape character. Try re.split('(.).\1', '1x2x3') # ['1x2x3'] vs. re.split(r'(.).\1', '1x2x3') # ['1', 'x', '3'] As '\$' is not an escape sequence in python, it is literally the same as '\\$'.
{ "pile_set_name": "StackExchange" }
Q: C# LINQ to Entities does not recognize the method 'Boolean' I have the following linq expression in lambda syntax: var myValue = 6; var from = 2; var to = 8; var res = MyList.Where(m => m.person.Id == person.Id && IsBetween(myValue, from, to)) .Select(x => new Person { blah blah blah }) .ToList()); IsBetween is simple generic helper method to see whether I have something in between: public bool IsBetween<T>(T element, T start, T end) { return Comparer<T>.Default.Compare(element, start) >= 0 && Comparer<T>.Default.Compare(element, end) <= 0; } Now I get this error, and I don't know hot to get around it: LINQ to Entities does not recognize the method 'Boolean IsBetween[Decimal](System.Decimal, System.Decimal, System.Decimal)' method, and this method cannot be translated into a store expression. A: You cannot call arbitrary methods from within a LINQ to Entities query, as the query is executed within the SQL database engine. You can only call methods which the framework can translate into equivalent SQL. If you need to call an arbitrary method, the query operator calling the method call will need to be preceded by an AsEnumerable() operator such that the call happens client-side. Be aware that by doing this, all results to the left-hand side of AsEnumerable() will potentially be loaded into memory and processed. In cases where the method you are calling is short enough, I would simply inline the logic. In your case, you would also need to drop the Comparer calls, and IsBetween(myValue, from, to) would simply become myValue >= from && myValue <= to.
{ "pile_set_name": "StackExchange" }
Q: Can I measure my Chinese proficiency without taking an HSK test? Is it possible to measure my proficiency on Mandarin Chinese without taking an HSK exam? I recently took a brief exam on EasyMandarin website but it is only about a brief grammar and vocabulary test, where you are expected to fill in the blank in a sentence by picking one of the four words. This is more like a quick test to introduce the respondents to their own programs. The ESL test is the same in this respect. I can't take the HSK exam right now, so is there any reliable website to test my Mandarin proficiency online? A: This page on Emory University's website about HSK Sample Tests should be of use to you. There are 6 different sample tests, along with a relevant review of vocabulary and grammar. Unfortunately, I'm not fluent in Mandarin, so I can't check if the practice tests are in the form that you prefer. If they aren't, please let me know so I can find a better resource.
{ "pile_set_name": "StackExchange" }
Q: How to fix a java.lang.UnsatisfiedLinkError for JSSC? (Needs hard float?) I have a Java application in a JAR that needs to communicate via serial using JSSC (On Ubuntu in a SOPine board). It is throwing the following java.lang.UnsatisfiedLinkError exception: Exception in thread "CommThread" java.lang.UnsatisfiedLinkError: /root/.jssc/linux/libjSSC-2.7_armsf.so: /root/.jssc/linux/libjSSC-2.7_armsf.so: cannot open shared object file: No such file or directory at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method) at java.base/java.lang.ClassLoader$NativeLibrary.load(ClassLoader.java:2430) at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(ClassLoader.java:2487) at java.base/java.lang.ClassLoader.loadLibrary0(ClassLoader.java:2684) at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2617) at java.base/java.lang.Runtime.load0(Runtime.java:767) at java.base/java.lang.System.load(System.java:1831) at jssc.SerialNativeInterface.<clinit>(SerialNativeInterface.java:172) at jssc.SerialPort.<init>(SerialPort.java:118) at com.company.comm.transport.serial.CommSerial.initialize(CommSerial.java:51) at com.company.product.adapters.comm.Communicator.connect(Communicator.java:73) at com.company.product.services.comm.CommThread.run(CommThread.java:18) TL;DR: Skip to the answer if you don't want to read several day's worth of troubleshooting. I exported my JAR file in Eclipse with the jssc.jar added to the project's Java Build Path's Libraries in the Classpath and its included in the exported entries. I did confirm that the file libjSSC-2.7_armsf.so is there: sudo ls –la /root/.jssc/linux/ drwxr-xr-x 2 root root 4096 Sep 23 14:41 . drwxr-xr-x 3 root root 4096 Sep 20 15:39 .. -rw-r--r-- 1 root root 10539 Sep 20 15:39 libjSSC-2.7_armsf.so The closest answer to my issue that I can find is the Stack Overflow question unsatisfied link error runnable jar referencing jssc library. I confirmed that the SOPine board I'm using has a VFPv4 Floating Point Unit, contains the directory /lib/arm-linux-gnueablhf/, and I have the JDK bellsoft-java11:armhf (From dpkg -l) installed, so I am not clear on why it is using libjSSC-2.7_armsf.so instead of libjSSC-2.7_armhf.so, which is in the same jssc.jar. I tried adding libjSSC-2.7_armhf.so to the /root/.jssc/linux/ directory, installing libjssc-java to linux, and modifying LD_LIBRARY_PATH and -Djava.library.path to point to another directory, but it throwing the same exception that it cannot locate libjSSC-2.7_armsf.so. I'm using the following command to run the JAR file with the pine user: sudo java -jar product-0.1.0.jar &> output-0.1.0_1.txt Edit 10/2/2019: I tried to change the JSSC shared library it's using by deleting the libjSSC-2.7_armsf.so, installing jssc locally using sudo apt install libjssc-java, and using LD_LIBRARY_PATH and -Djava.library.path to focus my program at running the new library, but it is still asking for libjSSC-2.7_armsf.so. I'm going to configure the Eclipse project to not package the JSSC JAR file with my project's exported JAR file and try running it again. Edit 10/7/2019: Last week, I decided to create a simple HelloSerial.java program to reduce potential dependencies. The code is below: import jssc.SerialPortList; public class HelloSerial { static { System.out.println("HelloSerial: loading JSSC"); try { System.load("/root/.jssc/linux/libjSSC-2.7_armhf.so"); System.out.println("HelloSerial: loading JSSC"); } catch (UnsatisfiedLinkError e) { System.err.println("Native core library failed to load.\n" + e); System.exit(1);; } } public static void main(String[] args) { System.out.println("HelloSerial: start"); String[] portNames = SerialPortList.getPortNames(); System.out.println("HelloSerial: listing " + portNames.length + " port names"); for(int i = 0; i < portNames.length; i++){ System.out.println(portNames[i]); } System.out.println("HelloSerial: end"); } } Here is the output from compiling and running it within the Linux system: $ sudo javac -classpath .:jssc.jar HelloSerial.java $ sudo java -cp jssc.jar:. HelloSerial HelloSerial: loading JSSC HelloSerial: loading JSSC HelloSerial: start Exception in thread "main" java.lang.UnsatisfiedLinkError: /root/.jssc/linux/libjSSC-2.7_armsf.so: /root/.jssc/linux/libjSSC-2.7_armsf.so: cannot open shared object file: No such file or directory at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method) at java.base/java.lang.ClassLoader$NativeLibrary.load(ClassLoader.java:2430) at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(ClassLoader.java:2487) at java.base/java.lang.ClassLoader.loadLibrary0(ClassLoader.java:2684) at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2617) at java.base/java.lang.Runtime.load0(Runtime.java:767) at java.base/java.lang.System.load(System.java:1831) at jssc.SerialNativeInterface.<clinit>(SerialNativeInterface.java:172) at jssc.SerialPortList.<clinit>(SerialPortList.java:43) at HelloSerial.main(HelloSerial.java:20) Even though I'm explicitly using System.load to load the hard float version of the shared library, it is still defaulting to try using the soft float. What could be forcing it to use the soft float version? All of the libraries, including the JDK, are using either armhf, arm64, or all in dpkg -l. Edit 10/8/2019: I found that JSSC uses logic in its SerialNativeInterface class to determine which shared library to use (This is just showing the relevant lines of code): 79 static { 80 String libFolderPath; 81 String libName; 82 83 String osName = System.getProperty("os.name"); 84 String architecture = System.getProperty("os.arch"); 85 String userHome = System.getProperty("user.home"); 86 String fileSeparator = System.getProperty("file.separator"); 87 String tmpFolder = System.getProperty("java.io.tmpdir"); ... 118 else if(architecture.equals("arm")) {//since 2.1.0 119 String floatStr = "sf"; 120 >>>> if(javaLibPath.toLowerCase().contains("gnueabihf") || javaLibPath.toLowerCase().contains("armhf")){ 121 floatStr = "hf"; 122 } 123 else { ... 139 } 140 architecture = "arm" + floatStr; 141 } 142 143 libFolderPath = libRootFolder + fileSeparator + ".jssc" + fileSeparator + osName; 144 libName = "jSSC-" + libVersion + "_" + architecture; 145 libName = System.mapLibraryName(libName); The important part is on line 120, where the ARM's library is choosen be soft float or hard float based on whether the java.library.path includes a gnueabihf or armhf path. Including the following line of code shows those paths: System.out.println("HelloSerial: java.library.path " + System.getProperty("java.library.path")); This outputted: HelloSerial: java.library.path /usr/java/packages/lib:/lib:/usr/lib It looks like gnueabihf or armhf paths like /lib/gnueabihf aren't being used, so I need to add one as a placeholder. Using sudo java -D.java.library.path=".:/lib/gnueabihf" -jar HelloSerial-1.0.0.jar works. I'll see if I can permanently add /lib/gnueabihf to java.library.path in the future. A: JSSC uses logic in its SerialNativeInterface class to determine which shared library to use. For OS's with ARM architecture, it checks the java.library.path to see if it contains gnueabihf or armhf in the paths. If not, it will use the soft float shared library instead. My current java.library.path doesn't contain either, so I added the existing /lib/gnueabihf directory to the path using the following command: $ sudo java -D.java.library.path=".:/lib/gnueabihf" -jar HelloSerial-1.0.0.jar There are other ways to load a path that are listed in this article or you can search online for that info. You can use $ java -XshowSettings:properties to confirm that it is included in the java.library.path.
{ "pile_set_name": "StackExchange" }
Q: Can't inherit explicit template specialization of same class in clang and gcc I want an Iterable<T> class to allow iterating generically on Object also. (T is assumed to be a derived of Object) However when defining my generic Iterable<T> as inheriting the specialized version for Object Iterable<Object>, as soon as the class is instantiated, I get a compile error in both clang and gcc (but not in MSVC). The error is that Iterable<Object> is an incomplete type. First question is why, since I expected the compiler would use the explicit instantiation of Iterable there. Second question is what would be a possible solution achieving the same result, the desired result being that an Iterable<T> with any T that is not Object should satisfy the IS A relationship with Iterable<Object> #include <functional> class Object {}; class Foo : public Object {}; template <class T> class Iterable : public Iterable<Object> { public: virtual void iterate(const std::function<void(T&)>& callback) const = 0; }; template <> class Iterable<Object> { public: virtual void iterate(const std::function<void(Object&)>& callback) const = 0; }; A: You can easily solve this by declaring the primary template first, then specialising it, and then defining it: template <class T> class Iterable; template <> class Iterable<Object> { public: virtual void iterate(const std::function<void(Object&)>& callback) const = 0; }; template <class T> class Iterable : public Iterable<Object> { public: virtual void iterate(const std::function<void(T&)>& callback) const = 0; }; [Live example] However, heed the warnings produced by the live example: Iterable<T>::iterate does not override Iterable<Object>::iterate, because their parameters have different types. You'll have to implement both in all classes derived from Iterable<T> for T other than Object.
{ "pile_set_name": "StackExchange" }
Q: Show $\lim\limits_{n \to \infty} \frac{1}{n^2} \sum\limits_{k=1}^n \frac{k+1}{\log(k+1)} = 0$ Show that $$ \lim\limits_{n \to \infty} \frac{1}{n^2} \sum\limits_{k=1}^n \frac{k+1}{\log(k+1)} = 0 $$ I have no clue how to show this. I would presume there is a clever way to use one of the $n$'s inside the sum to cancel appropriately but I can't seem to get the right idea. A: By Stolz-Cesaro theorem, $$\lim_{n \to \infty} \frac{1}{n^2} \sum_{k=1}^n \frac{k+1}{\log(k+1)}= \lim_{n \to \infty} \frac{\frac{n+2}{\log(n+2)}}{(n+1)^2-n^2} =\lim_{n \to \infty} \frac{1+\frac{2}{n}}{(2+\frac{1}{n})\log(n+2)}=0.$$
{ "pile_set_name": "StackExchange" }
Q: I'm trying to build site navigation using django-mptt I've used django-mptt to model the sections and sub-sections etc of the headings I want to store my articles under. Some sections and sections will have children others won't. eg: [Home] [News] [Politics][Crime][Policing] etc then [News] > [Politics] [UKIP][Labour] etc I'm sure you get the idea. I've created the Section models class Section(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey('self',null=True, blank=True, related_name='sub_sections') tree = SectionTreeManager() and by passing Section.objects.all() into the template :- <ul class="headernav" > {% recursetree sections %} <li> <a href="/section/{{node.name}}" >{{ node.name }}</a> {% if node.is_leaf_node %} <ul class="headernav"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> I can display all nodes. What I want to do is , based on the current url ie /section/News get all siblings on current level all ancestors on previous level and all related descendants on the level below. so if I selected News I'd get [home][**News**][World][Sports][Culture] <- Level 0 [Politics][Crime][Education] <- Children on Level 1 How can I do this? Any help would be much appreciated. I'm learning Django so if it's obvious I apologise in advance. A: django-page-cms has solved this type of problem using django-mptt, so I suggest having a look at the way it's done there. Specifically, the template to render the tree menu is recursively included via a custom template tag called pages_dynamic_tree_menu. This sounds complicated (custom ta-whaaa!), so I'll break it down a bit more. We can consider a Page in django-page-cms to be roughly the same as your Section class. In the base template which is shared between 99% of your pages, django-page-cms gets you to insert the following snippet: <ul> {% for page in pages_navigation %} {% pages_dynamic_tree_menu page %} {% endfor %} </ul> pages_navigation is set by a context processor (a way to add items to a template context for all views in a django project) and contains the top level pages (i.e. those without parents). The pages_dynamic_tree_menu tag is defined and registered as follows: def pages_dynamic_tree_menu(context, page, url='/'): """ Render a "dynamic" tree menu, with all nodes expanded which are either ancestors or the current page itself. Override ``pages/dynamic_tree_menu.html`` if you want to change the design. :param page: the current page :param url: not used anymore """ lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) children = None if page and 'current_page' in context: current_page = context['current_page'] # if this node is expanded, we also have to render its children # a node is expanded if it is the current node or one of its ancestors if(page.tree_id == current_page.tree_id and page.lft <= current_page.lft and page.rght >= current_page.rght): children = page.get_children_for_frontend() context.update({'children': children, 'page': page}) return context pages_dynamic_tree_menu = register.inclusion_tag( 'pages/dynamic_tree_menu.html', takes_context=True )(pages_dynamic_tree_menu) The whole point of it is to set the page and the children variables. The magic is in the if statement, which ensures the children are only displayed if the page is the current one (the current_page template variable is set by the django-page-cms view which renders a Page), or if the page is an ancestor. The lft & rght attributes are provided by django-mptt, and two of the properties of this MPTT are that the left value of a parent tree node will be less than its child node's left value and the right value of a parent node will be more than the right value of its child node, which you can verify visually by looking at the image below from the article Trees in SQL: The get_children_for_frontend() method of Page calls MPTTModel.getChildren() with some filtering to hide unpublished Page objects, so nothing special there. The tag then does the tag equivalent of {% include %} with the pages/dynamic_tree_menu.html template, which in turn calls the pages_dynamic_tree_menu tag again, causing the whole thing to recurse: {% load pages_tags cache %} {% if page.calculated_status %} <li {% ifequal page current_page %}class="selected"{% endifequal %}> <a href="{% show_absolute_url page %}">{% show_content page "title" %}</a> {% if children %} <ul>{% for child in children %}{% pages_dynamic_tree_menu child url %}{% endfor %}</ul> {% endif %} </li> {% endif %} So if you define a similar setup (provide top level sections and the current section to your template, define an "inclusive" template tag and matching template for the tag) and apply some styling, then you should be able to use this approach to accomplish your goal.
{ "pile_set_name": "StackExchange" }
Q: GDB 'Addresses'. What are they? This should be a very simple,very quick qustion. These are the first 3 lines of a program in C I wrote: Dump of assembler code for function main: 0x0804844d <+0>: push ebp 0x0804844e <+1>: mov ebp,esp 0x08048450 <+3>: and esp,0xfffffff0 ... ... ... ... ... ... ... What is 0x0804844d and 0x0804844e and 0x08048450? It is not affected by ASLR. Is it still a memory address, or a relative point to the file? A: If you look at the Intel Developer Manual instruction-set reference you can see that 0x0804846d <+32>: eb 15 jmp 0x8048484 encodes a relative address. i.e. it's the jmp rel8 short encoding. This works even in position-independent code, i.e. code which can run when mapped / loaded at any address. ASLR means that the address of the stack (and optionally code+data) in the executable can change every time you load the file into memory. Obviously, once the program is loaded, the addresses won't change anymore, until it is loaded again. So if you know the address at runtime, you can target it, but you can't write an exploit assuming a fixed address. GDB is showing you addresses of code in the virtual-memory space of your process, after any ASLR. (BTW, GDB disables ASLR by default: set disable-randomization on|off to toggle.) For executables, it's common that only the stack pointer is ASLRed, while the code is position-dependent and loaded at a fixed address, so code and static data addresses are link-time constants, so code like push OFFSET .LC0 / call puts can work, hard-coding the address of the string constant into a push imm32. Libraries usually need to be position-independent anyway, so ASLR can load them at a randomized address. But ASLR for executables is possible and becoming more common, either by making position-independent executables (Linux), or by having the OS fix-up every hard-coded address when it loads the executable at a different address than it was compiled for (Windows). Addresses only have a 1:1 relation to the position within the file only in a relative sense within the same segment. i.e. the next byte of code is the next byte of the file. The headers of the executable describe which regions of the file are what (and where they should be mapped by the OS's program loader). A: The meaning of the addresses shown differs in three cases: For executable files For DLLs (Windows) or shared objects (.so, Linux and Un*x-like) For object files For executables: Executable files typically cannot be loaded to any address in memory. In Windows there is the possibility to add a "relocation table" to an executable file (required for very old Windows versions); if this is not present (typically the case when using GCC) then it is not possible to load the file to another memory location. In Linux it is never possible to load the executable to another location. You may try something like this: static int a; printf("%X\n", &a); When you execute the program 100 times you see that the address of a is always the same so no ASLR is done for the executable file itself. The addresses dumped by objdump are absolute addresses. For DLLs / .so files: The addresses are relative to the base address of the DLL (under Linux) or they are absolute addresses (under Windows) that will change when the DLL is loaded into another memory area. For object files: When dumping an object file the addresses are relative to the currently displayed section. If there are multiple ".text" sections in a file the addresses will start at 0 for each section.
{ "pile_set_name": "StackExchange" }
Q: How vanishing points can help in restoring proper camera perspective? I'm trying to insert 3D object into a photo, that was not taken by me. Meta info is erased, so I can only guess camera parameters and dimensions of the objects in the scene. How can I set proper campoints in such case, is there any methodology? I've seen that people are drawing helper lines, finding vanishing points, but while I understand the meaning of the vanishing point, I do not get how it can help in restoring the perspective. Any good writeup on the topic? A: To completely determine a scene 3D data from a given image, you need to know the perspective projection parameters that formed your image. They are: camera intrinsics: focal length (a must!), and distortion parameters (if you want high precision) camera extrinsic parameters (rotation/ translation on the three axes) Detailed: Focal length can be obtained from viewing angle, with this formula: fx = imageWidth/(2*tan(alphaX)), and similar for the other dimension. If you have neither fx, nor aperture, you cannot reconstruct your 3D image. Another way to extract them is to calibrate the camera. See http://opencv.itseez.com/modules/calib3d/doc/calib3d.html, but it seems you cannot use it (you said you don't have access to camera.) The vanishing point (VP) is used to determine the angles at which camera was orientated. So, a difference between the image center and the VP gives you the rotation info: yaw = ((camera.center.x (pixels) - VP.x)/image.x )* aperture. pitch = similar. The roll angle cannot be extracted from VP, but from the horizon line. The last parameters you need are the translations. Depending of the application, you can set them all 0, or consider only the height as being relevant. None of them can be usually recovered from the image. Now, having all this data, you can look here Opencv virtually camera rotating/translating for bird's eye view to see how all this measures influence your perspective correction.
{ "pile_set_name": "StackExchange" }
Q: Material-Table onRowClick waves animation; is this possible? I would like the Table Row on click to have a Material Waves animation across the entire row. At current it looks as though the closest thing I can get to is an On hover background change. Does anyone know of the best way to achieve this? A: From my understanding it looks like applying a Waves/Ripple animation will require an element to be added to the HTML DOM, which conflicts with how strict HTML5 is with table tags. Since table tags cannot have children or wrappers, the easiest solution would be to utilize a material-ui list instead. The downside of this approach of course is that I will have to implement searching and filtering columns, seeing as I can't leverage the material-table functionality. I personally think that having proper button-like feedback on clicking a row is important, but for now I suppose a list will have to do. If I'm incorrect in this prognosis, please let me know.
{ "pile_set_name": "StackExchange" }
Q: Posedge in Verilog I'm just beginning with FPGAs and I have decided to go with verilog as the HDL. I saw a line like this: always@(posedge clk) I wanna know when is posedge used and when is negedge used. Also, what's the difference between them? A: posedge triggers the block on the positive (rising) edge of a clock signal. negedge triggers on the negative (falling) edge. Unless you're interfacing with external logic that specifically requires negative edges, you should always use posedge. Designs that use both will generally have poor timing results, and may in some situations be impossible to synthesize at all.
{ "pile_set_name": "StackExchange" }
Q: Android Database add column is there any simple way how to add column or update column via SQlite in Android? Now I am using raw SQL: public void addColumn(String tableName, String ColumnName, String ColumnType, String AdditionalDetails){ SQLiteDatabase db=dtbhelper.getWritableDatabase(); db.execSQL("ALTER TABLE "+tableName+" ADD COLUMN "+ColumnName+" "+ColumnType+" "+AdditionalDetails+";"); Log.d("TAG","FINISHED"); } THanks A: Your query looks correct. In SQLite you only can ADD column and you cannot UPDATE it. Also refer to some restrictions when adding column.
{ "pile_set_name": "StackExchange" }
Q: How to get the method name that thrown the exception in Java I have an aspect that runs after an exception is thrown from my TestNG test method. I would like to get the Test method name into my aspectj method. Any thoughts on this? Please find my code sample below: Aspect: pointcut publicCall(): call(public * *(..)); after() throwing (AssertionError e): publicCall() { logger.debug("Assertion Error thrown"); System.out.println("Threw an exception: " + e); } Test: @Test public void testScenarioOne(){ logger.debug("From Scenario One Test"); Assert.assertEquals(true, false); } A: You need to change your pointcut type from call to execution: pointcut publicMethod(): execution(public * *(..)); after() throwing (AssertionError e): publicMethod() { System.out.println(thisJoinPointStaticPart.getSignature()); } Edit: Maybe it would be even cleaner to specifically intercept @Test annotated methods: import org.testng.annotations; public aspect TestExceptionInterceptor { pointcut testMethod(): execution(@Test * *(..)); after() throwing (AssertionError e): testMethod() { System.out.println(thisJoinPointStaticPart.getSignature()); } }
{ "pile_set_name": "StackExchange" }
Q: R - select column depending on available values I have x: x = structure(c(12, 24, NA, 25), .Dim = c(2L, 2L)) > x [,1] [,2] [1,] 12 NA [2,] 24 25 and would like to return y, where y equals the value in the second column of x if the value is available, and the value in the first column if not. so: > y [1] 12 25 I want to use the solution for a large array, so I am looking for a vectorized solution if that makes sense. A: ifelse does exactly what you want: > ifelse(is.na(x[,2]), x[,1], x[,2]) [1] 12 25 If speed is paramount (and you don't want to mess with C), you can try: y <- x[,2] y[is.na(y)] <- x[is.na(y), 1] This effectively shortcircuits some of the overhead of ifelse. Consider: set.seed(1) x <- cbind(sample(1:1e5), sample(c(1:95000, rep(NA, 5000)))) library(microbenchmark) microbenchmark( z <- ifelse(is.na(x[,2]), x[,1], x[,2]), {y <- x[,2]; y[is.na(y)] <- x[is.na(y), 1]}, times=10 ) # Unit: milliseconds # expr min median # z <- ifelse(is.na(x[, 2]), x[, 1], x[, 2]) 30.46 33.06 # y <- x[, 2]; y[is.na(y)] <- x[is.na(y), 1] 5.48 5.77 identical(y, z) # [1] TRUE
{ "pile_set_name": "StackExchange" }
Q: Maximum non-Canon paper weight for Canon PIXMA printers? In the specifications of the Canon printers, such as PIXMA MG7150, it is said that we should not use papers that are too thick (weighing more than 28lb or 105g/mΒ²), except for Canon genuine paper. How serious is this? what happens if we use heavier non-Canon media? for example 215g/mΒ² card stock? A: What can go wrong? Paper jam can occur and possibly damage the printer. The paper may not move properly when printing, ruining your printout. Canon paper probably doesn't have any unique or magical properties, it's just certified to work. That means that non-Canon paper may work, but you're trying it at your own responsibility.
{ "pile_set_name": "StackExchange" }
Q: how to create table from codeigniter-query? i want to create a table from the following query... background is, i made an extra form to search for detailed informations about each club, where you can search for either for single details of the club name or you can combine fields like parts of the club name and lets say part of the street name but some of the fields in the table can be NULL. so i implemented these IF ELSE and LIKE statements. this works fine, but how to put these $query into a table, like in CREATE TABLE SearchedClubs AS (SELECT * FROM Clubs WHERE...) $this->db->select('*'); $this->db->from('Clubs'); if ($clubname <> NULL) { $this->db->like('Clubname', $clubname, 'both'); } if ($street <> NULL) { $this->db->like('Street', $street, 'both'); } if ($postalcode <> NULL) { $this->db->like('Postalcode', $postalcode, 'both'); } if ($city <> NULL) { $this->db->like('City', $city, 'both'); } if ($homepage <> NULL) { $this->db->like('Homepage', $homepage, 'both'); } if ($email <> NULL) { $this->db->like('Email', $email, 'both'); } if ($telephone <> NULL) { $this->db->like('Telephone', $telephone, 'both'); } $query = $this->db->get(); A: The easy way would be $this->db->select('*'); $this->db->from('Clubs'); if ($clubname <> NULL) { $this->db->like('Clubname', $clubname, 'both'); } if ($street <> NULL) { $this->db->like('Street', $street, 'both'); } if ($postalcode <> NULL) { $this->db->like('Postalcode', $postalcode, 'both'); } if ($city <> NULL) { $this->db->like('City', $city, 'both'); } if ($homepage <> NULL) { $this->db->like('Homepage', $homepage, 'both'); } if ($email <> NULL) { $this->db->like('Email', $email, 'both'); } if ($telephone <> NULL) { $this->db->like('Telephone', $telephone, 'both'); } $query = "CREATE TABLE SearchedClubs AS (" . $this->db->get_compiled_select() . ")"; $this->db->query($query);
{ "pile_set_name": "StackExchange" }
Q: Questions about Internal Direct Product Decomposition in Group Theory I'm currently on the chapter of internal direct product in group theory, and became curious about the following questions: One definition of an internal direct product in my book is that for a group $G$ with $S_i$ being a subgroup of $G$ and $G=S_1\cdots S_n$, $\prod_{i=1}^nS_i \cong G$ canonically by $h(s_1,\cdots,s_n)=s_1\cdots s_n$. My question is, is it necessary to restrict to the canonical isomorphism? I tried to find an example where $\prod_{i=1}^nS_i \cong G$ only non-canonically, but I couldn't. I've learned that a finitely generated Abelian group can be decomposed into cyclic groups $G=C_1\oplus \cdots \oplus C_n$ such that $C_{i\leq k}$ is of order $m_i$ with $m_1|m_2|\cdots|m_k$ and $C_{i>k}$ is infinite. My question is, is this decomposition unique in any sense? In particular, (1) For a finite Abelian group, each $m_i$ is uniquely determined. But when the group is not cyclic, the converse of Lagrange's theorem doesn't hold in general, so I guess $G=D_1\oplus \cdots\oplus D_n$ is possible where $D_i\neq C_i$ for some $i$ (even though they are isomorphic since they are cyclic group of same order). (2) When $G$ is infinite, since my book proved that $m_i$s are uniquely determined only for a finite group, I think the same assertion wouldn't necessarily hold in $G$. The problem is, I'm just a beginner and haven't met with infinite group other than cyclic group so I can't come up with suitable example of such a group, i.e. $G=\bigoplus_{i=1}^l D_i$ with possibly $l\neq n$ and the finite part of some $D_i$ has different order than $m_i$. Sorry if this question was basic, but I was so curious about this. It would be grateful if there is an example I can understand; I started learning group theory this semester. A: http://groupprops.subwiki.org/wiki/Internal_direct_product Example: Show $\mathbb{Z}_6 \cong \mathbb{Z}_3 \oplus \mathbb{Z}_2$ http://www.millersville.edu/~bikenaga/abstract-algebra-1/fg-abelian-groups/fg-abelian-groups.html Example: Let $|G| = 2^3 \cdot 3^2 \cdot 5$. Write down all nonisomorphic abelian groups
{ "pile_set_name": "StackExchange" }
Q: Sanitize search string for Dynamic SQL Queries I know i can use stored procedures to eliminate sql injection attacks but it would bloat the code by more than I'm willing to accept and making it costly to maintain. In my dynamic sql query, I would like to search a string of text in 2 columns in one of my tables but before that happens, I would like my business layer, which is written in c#, to sanitize sanitize the input. I would like the input to have special characters (ie: #,!, $, etc.) What is the minimal character set that i have to strip out in my search string to sanitize it? I'm thinking that stripping out single and double quotes is sufficient. Is that correct? Thanks A: You don't need to use stored procedures to be safe. (As a matter a fact, stored procedures don't necessarily guarantee safety against injection attacks if the stored procedures themselves construct dynamic queries.) And manual escaping is difficult to do 100% safely, and not recommended. Instead, use parameterized queries, which nearly all databases support.
{ "pile_set_name": "StackExchange" }
Q: My search returns null "page 404" I have created search on MVC.Net C# and and I am using ADO.Net /SQL server 2008 technology in below I have copied and pasted my controller page & my View page... Will you be kind and look at my codes and give me feedback that why this doesn't return any result, but an error? This error happens when I submit the search button! Controller: public class FormController : Controller { Context db = new Context(); [HttpGet] public ActionResult Report(string sortOrder, string currentFilter, string searchString, int? page) //adds a page parameter, a current sort order parameter, and a current filter parameter to the method { ViewBag.CurrentSort = sortOrder; // the view with the current sort order to keep the sort order the same while paging ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name_desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "Date_desc" : "Date"; if (searchString != null) { page = 1; //maintain the filter settings during paging, and it must be restored to the text box when the page is redisplayed } else { searchString = currentFilter; } ViewBag.CurrentFilter = searchString; // provides the view with the current filter strin var reports = from s in db.DRs select s; if (!String.IsNullOrEmpty(searchString)) { reports = db.DRs.Where(s => s.DR_REPORT_NUM.ToString().Contains(searchString.ToUpper()) || ... } #region Sorting switch (sortOrder) { case "Name_desc": reports = reports.OrderByDescending(s => s.DR_INM_LAST_NAME); break; case "Date": reports = reports.OrderBy(s => s.DR_INCIDENT_DATE); break; case "Date_desc": reports = reports.OrderByDescending(s => s.DR_INCIDENT_DATE); break; default: //Name ascending reports = reports.OrderBy(s => s.DR_INM_LAST_NAME); break; } #endregion int pageSize = 10; // converts the inmate query to a single page of forms in a collection type that supports paging. int pageNumber = (page ?? 1); return View(reports.ToPagedList(pageNumber, pageSize)); } and my View : @using (Html.BeginForm("Report", "Form", new { ReturnUrl = Request.QueryString["ReturnUrl"] }, FormMethod.Post)) { <p> <div style="width: 800px; margin: 0 auto;"> <div style="width: 50%; float: left; margin-left: -5%" id="left"> <h3>Find Report: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)<input type="submit" value="Search" /></h3> Server Error in '/' Application. The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly A: You can try changing the action attribute from From [HttpGet] To [HttpPost]
{ "pile_set_name": "StackExchange" }
Q: How to create a font from an image for a game? I found a font in a free pack of sprite as an image: I'm wondering what would be the best way to use it in a game? Is there tools to create a font from this image? Do i have to code it myself? I think of using this only for area with few text (like menus) so maybe a simple system converting a string to a sequence of image representing letters would be enough and it's not worth trying to use a complex font system? What do you think? A: Do you know how to implement sprites? If yes, then drawing text from a character sheet is easy: just treat each character as a sprite and draw them one after the other. The details depend on the font you have and on how fancy you want your typography to be. Obviously, the simplest case would be a monospace font, where each character is a constant-size rectangle. The font shown in your question appears to have variable character widths, which just means that you need to have a table giving the width of each character. If you already know how to work with variable-size sprites, this shouldn't be any more complicated. Just keep track of the current coordinates of the end of the text, and add the width of each character to the x-coordinate as you draw it. One minor complication is that, if you want to draw that can wrap over multiple lines, you may want to make your drawing routine split the text into words and calculate the width of each word before drawing it, in order to check whether it fits in the remaining space. (Of course, there are even fancier microtypographical tricks you can do, like non-greedy line length optimization and dynamically adjusting word and character spacing to justify both margins, but those are probably overkill for your needs.) Also, for fonts with less "blocky" shapes than the one in your example, you may want to implement kerning to make letter combinations like AV look nicer. A basic way to do this is to just calculate the minimum distance between two non-transparent pixels in a letter pair, and then move the letters to set this distance to the desired value. In practice, to improve performance, you may want to do this using downscaled bitmaps, or even a simplified model where each letter is first cut into a small number of horizontal slices, and each slice is then mapped to a pair of numbers giving the position of the leftmost and rightmost non-transparent pixel in the slice. For even fancier effects, like emulation of hand-written calligraphic text, you could implement things like ligatures and context-dependent letter form variants (which are actually pretty simple to implement, basically just a lookup table mapping pairs of letters to the appropriate variants; the hard work is in drawing the ligatures to begin with), but you probably don't need any of that stuff. For most purposes, just drawing simple rectangular character blocks in a row is more than good enough.
{ "pile_set_name": "StackExchange" }
Q: Why does the binding update without implementing INotifyPropertyChanged? I created a ViewModel and bound its property to two textboxes on UI. The value of the other textbox changes when I change the value of first and focus out of the textbox but I'm not implementing INotifyPropertyChanged. How is this working? Following is XAML <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <local:ViewModel /> </Window.DataContext> <StackPanel> <TextBox Text="{Binding Name}" /> <TextBox Text="{Binding Name}" /> </StackPanel> </Window> And following is my ViewModel class ViewModel { public string Name { get; set; } } A: I tested it, you are right. Now i searched for it on the web, and found this. Sorry to take so long to reply, actually you are encountering a another hidden aspect of WPF, that's it WPF's data binding engine will data bind to PropertyDescriptor instance which wraps the source property if the source object is a plain CLR object and doesn't implement INotifyPropertyChanged interface. And the data binding engine will try to subscribe to the property changed event through PropertyDescriptor.AddValueChanged() method. And when the target data bound element change the property values, data binding engine will call PropertyDescriptor.SetValue() method to transfer the changed value back to the source property, and it will simultaneously raise ValueChanged event to notify other subscribers (in this instance, the other subscribers will be the TextBlocks within the ListBox. And if you are implementing INotifyPropertyChanged, you are fully responsible to implement the change notification in every setter of the properties which needs to be data bound to the UI. Otherwise, the change will be not synchronized as you'd expect. Hope this clears things up a little bit. So basically you can do this, as long as its a plain CLR object. Pretty neat but totally unexpected - and i have done a bit of WPF work the past years. You never stop learning new things, right? As suggested by Hasan Khan, here is another link to a pretty interesting article on this subject. Note this only works when using binding. If you update the values from code, the change won't be notified. [...] WPF uses the much lighter weight PropertyInfo class when binding. If you explicitly implement INotifyPropertyChanged, all WPF needs to do is call the PropertyInfo.GetValue method to get the latest value. That's quite a bit less work than getting all the descriptors. Descriptors end up costing in the order of 4x the memory of the property info classes. [...] Implementing INotifyPropertyChanged can be a fair bit of tedious development work. However, you'll need to weigh that work against the runtime footprint (memory and CPU) of your WPF application. Implementing INPC yourself will save runtime CPU and memory. Edit: Updating this, since i still get comments and upvotes now and then from here, so it clearly is still relevant, even thouh i myself have not worked with WPF for quite some time now. However, as mentioned in the comments, be aware that this may cause memory leaks. Its also supposedly heavy on the Reflection usage, which has been mentioned as well.
{ "pile_set_name": "StackExchange" }
Q: Can't Click On Controls After Adding Css I've added a new css element to my master page. But After that, I can't click on other controls in the page. I know some div is overlapping the other making click not working. But I couldn't figure it out with the css file. My css file is given below: here where I placed my div in html : /* XLSF 2007 */ body { background: #333 url(image/bg-strip-dark.png) 0px 0px; font-family: normal, "Century Gothic", "Helvetica Neue Light", "Helvetica Neue", georgia, "times new roman", "Arial Rounded MT Bold", helvetica, verdana, tahoma, arial, "sans serif"; font-size: 75%; color: #666; } h1, h1 a { color: #999; text-decoration: none; } h1 { color: #999; margin-bottom: 0; margin-left: -5px; margin-top: 0; padding-left: 5px; padding-right: 5px; } h1, h2, h3 { clear: both; float: left; font-family: normal, "Century Gothic", "Helvetica Neue Light", "Helvetica Neue", georgia, "times new roman", "Arial Rounded MT Bold", helvetica, verdana, tahoma, arial, "sans serif"; font-size: 3em; font-size-adjust: none; margin-bottom: 0.25em; padding-bottom: 1px; } h1, h2 { letter-spacing: -1px; margin-bottom: 0; margin-left: -5px; margin-top: 0; padding-left: 5px; padding-right: 5px; } a { color: #6699cc; padding: 0px 2px; text-decoration: none; } a:hover { background: #6699cc; color: #fff; } #lights { clear: both; position: relative; left: 0px; top: 0px; width: 100%; height: 96px; overflow: hidden; z-index: 1; } .xlsf-light { position: relative; } body.fast .xlsf-light { opacity: 0.9; } .xlsf-fragment { position: relative; background: transparent url(image/bulbs-50x50-fragments.png) no-repeat 0px 0px; width: 50px; height: 50px; } .xlsf-fragment-box { position: relative; left: 0px; top: 0px; width: 50px; height: 50px; *width: 100%; *height: 100%; display: none; } .xlsf-cover { position: relative; left: 0px; top: 0px; width: 100%; height: 100%; background: #fff; opacity: 1; z-index: 999; display: none; } /* .xlsf-light.bottom { height:49px; border-bottom:1px solid #006600; } .xlsf-light.top { height:49px; border-top:1px solid #009900; } */ <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <link rel="stylesheet" media="screen" href="christmaslights.css" /> <title>Untitled Page</title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> <style type="text/css"> .style1 { width: 135px; } </style> <script src="snowstorm.js"></script> <script> snowStorm.snowColor = '#99ccff'; // blue-ish snow!? snowStorm.flakesMaxActive = 96; // show more snow on screen at once snowStorm.useTwinkleEffect = true; // let the snow flicker in and out of view </script> <script src="lights/soundmanager2-nodebug-jsmin.js"></script> <script src="http://yui.yahooapis.com/combo?2.6.0/build/yahoo-dom-event/yahoo-dom-event.js&2.6.0/build/animation/animation-min.js"></script> <script src="lights/christmaslights.js"></script> </head> <body> <form id="form1" runat="server"> <div> <table style="width:100%;"> <tr> <td class="style1"> <asp:Image ID="Image1" runat="server" ImageUrl="~/images/remedyonline-logo.png" /> </td> <td> <span style="font-family: Tahoma; font-size: xx-large; font-weight: bold; color: #666666; padding-left: 10px;">Representatives Corner <marquee direction="right"><font color=#993300 size=5 ><strong>GDS Wishes A HAPPY X'MAS</strong></marquee></font> </span> </td> </tr> </table> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form> <div id="lights"> </div> </body> </html> At least please notify me where's the problem. I am new to html and css. A: It could be that one of the elements with a modified z-index property is rendered above the aforementioned controls. The solution, then, would be to isolate which one of them is problematic for you by removing the properties and observing the results. A better solution, however, might be to learn about the developer tools in your favorite browser - they can be incredibly helpful for situations like this: Chrome Dev Tools Firefox Dev Tools
{ "pile_set_name": "StackExchange" }
Q: Child Care Volunteering: Should I mention I was orphan? I have an interview for children patient support volunteer position in a hospital. I feel being an orphan at a young age - I was 5 when my mother died and I was 15 when my father died - made me have better sympathy with children. Should I mention the same in interview or try to avoid this topic? A: Yes, mention it. I think this is an interesting situation because when you interview with a potential employer, a requirement is to have experience within the job you're applying. Being able to relate with these children will give you an advantage.
{ "pile_set_name": "StackExchange" }
Q: QFT: Prove this relationship In my notes from QFT appears this relationship between exponential and sinh and cosh, my question is: How demonstrate this? $$\exp{(\pm\frac{1}{2} \eta \sigma^3)}=\cosh(\frac{1}{2}\eta) \mathbb{I}_{2x2}\pm \sinh(\frac{1}{2}\eta)\sigma^3,$$ where $\sigma^3$ is a Pauli matrix, $\eta$ is the "rapidity" and $\mathbb{I}_{2x2}$ is the 2x2 identity matix. Thank you for your attention. A: The first step is to expand the exponential as a Taylor series: $$ \exp \left( \pm \frac{1}{2} \eta \sigma \right) = I \pm \left( \eta \sigma/2 \right) + \frac{1}{2} \left( \eta \sigma / 2 \right)^2 \pm \frac{1}{3!} \left( \eta \sigma / 2 \right)^3 \dots$$ Noting that $\sigma^2 = I$, this series can now be split into even and odd terms: the even terms sum to $\cosh \left( \eta/2 \right) \ I$, and the odd terms to $\pm \sinh \left( \eta/2 \right) \ \sigma$, which gives the result you want.
{ "pile_set_name": "StackExchange" }
Q: PHP - Merge-down multidimensional arrays by named key I have the following array (which contains results of multiple database queries - in the example only 2 but can be more. The merging needs to be done by a specified column (in this case the date column). Let's call this merge_by column. Array ( [0] => Array ( [0] => Array ( [date] => 2011-01-17 [col-1] => 58 [col-2] => 54 ) [1] => Array ( [date] => 2011-01-19 [col-1] => 50 [col-2] => 61 ) [2] => Array ( [date] => 2011-01-20 [col-1] => 44 [col-2] => 22 ) [3] => Array ( [date] => [col-1] => 448 [col-2] => 196 ) [1] => Array ( [0] => Array ( [date] => 2011-01-17 [col-3] => 1489 ) [1] => Array ( [date] => 2011-01-18 [col-3] => 1534 ) [2] => Array ( [date] => [col-3] => 1534 ) ) ) And I'm trying to achieve Array ( [0] => Array ( [date] => 2011-01-17 [col-1] => 58 [col-2] => 54 [col-3] => 1489 ) [1] => Array ( [date] => 2011-01-18 [col-1] => [col-2] => [col-3] => 1534 ) [2] => Array ( [date] => 2011-01-19 [col-1] => 50 [col-2] => 61 [col-3] => ) [3] => Array ( [date] => 2011-01-20 [col-1] => 44 [col-2] => 22 [col-3] => ) [4] => Array ( [date] => [col-1] => 448 [col-2] => 196 [col-3] => 1534 ) Things to consider: merge_by can take null or empty string values merge_by will not have same values in the arrays to be merged the number of results in the 2 queries will differ and the merge_by values can differ, so one might encounter $arr[0][1][date] != $arr[1][1][date] LE: except the merge_by column, all the other columns will differ from each other, so you won't have $arr[0][0][col-2] and $arr[1][0][col-2] So the purpose of this is to merge the columns of some queries by a common column. Too much data from too many databases from too many columns to make it from SQL only. I know... pre-calculate the values :) ... not an option now. I have managed to make it work when the number of columns and the indexes of these match. Have since tried many options so right now I have a version unworthy of adding it as example. So does anyone any idea of a function that can achieve the above? Thanks A: First, I'm going to assume your data is sorted by date, since you can do it in SQL and it's sorted in your example. You need to walk through all of your sets at the same time, merging as you go. $merged = array(); $i_first = 0; $i_second = 0; $count_first = count($data[0]); $cound_second = count($data[1]); while ($i_first < $count_first || $i_second < $count_second) { // this comparison depends on what your merge_by is $diff = strtotime($data[$i_first]['date']) - strtotime($data[$i_second]['date']); if ($diff == 0) { $merged[] = array_merge($data[$i_first], $data[$i_second]); $i_first++; $i_second++; } elseif ($diff < 0) // first date is earlier { $i_first++; } else // second date earlier { $i_second++; } } Now your $merged array should have what you want. Note that this solution assumes you don't have duplicate date rows in one chunk, or it would overwrite the existing results. Also, you could expand to have more than two data sets if you want.
{ "pile_set_name": "StackExchange" }
Q: Image of countably compact space Let $X$ be a space that is countably compact, which means that every countable open cover has a finite subcover. Assume that $f$ is a continious function. Then $f(A)$ is contably compact. So, take a space that is countably compact. Denote $A := f(X)$. Take a countable open cover of A. I have to show now that it has finite subcover. But don't have any idea on how to proceed further. Does it follow from the fact that image of open sets are open if $f$ is continious. I mean since we know that $f$ is continious function then image of finite open subcover of X will be open as well in A. Or it is not enough? Could anyone please give some hints? A: This proof is just a straightforward proof-idea copy of the compact case: Let $\{U_n: n \in \omega\}$ be a countable open cover of $f[X]$ by open subsets of $Y$, assuming $f:X \to Y$ is our continuous function, for notation's sake. Then $\{f^{-1}[U_n]: n \in \omega\}$ is a countable open cover of $X$ (the sets are open by continuity of $f$; if $x \in X$ some $U_m$ must cover $f(x) \in f[X]$, and then by definition $x \in f^{-1}[U_m]$, so all $x$ are covered). Finitely many of these cover $X$, as $X$ is countably compact, say $f^{-1}[U_{n_1}],\ldots, f^{-1}[U_{n_m}]$ do. But then $f[X]$ is also covered by the $U_{n_1}, \ldots, U_{n_m}$ (any $y \in f[X]$ is of the form $y =f(x)$ for some $x \in X$, $x$ lies in some $f^{-1}[U_{n_j}]$ from the finite subcollection, and then $y = f(x) \in U_{n_j}$ by definition, so is covered). So every countable open cover of $f[X]$ has a finite subcover.
{ "pile_set_name": "StackExchange" }
Q: Air Pagination Issues I just completed an Adobe AIR app. I built it using html, css, javascript and jQuery. It installs fine, loads fine and everything works except pagination on a popup page. You can install it here: http://www.bendelcorp.com/tools/air-installer.html When you click on the Capacity tab and enter values in each of the three fields (enter double or triple digits to activate the pagination) and then click on the Show Capacity Chart it brings up another window with data. The problem - when you click on the Next Page button, nothing happens. The web based version (located here) works fine. I just need some help "unlocking" the power of the Next Page button. Thanks in advance for any help. A: Once again I am the only one reading my entries about Adobe Air. The fix was in the JavaScript: CapacityWindow = window.open(document.location, 'CapacityWindow', 'toolbar,scrollbars,menubar,width=800,height=950'); CapacityWindow.document.write(s); CapacityWindow.document.close(); The previous script was not allowing the existing window to close so the new one could open up.
{ "pile_set_name": "StackExchange" }
Q: Why does no-wrap width calculation change when it is nested inside of an element with a display of table? With our design we end up needing multiple columns to display titles with ellipsis which I don't expect to be a big deal but when they are nested inside of a display: table the calculations seem to be incorrect. The caveats are that we want a responsive layout so percentage widths are required (fixed widths would solve the problem). And our layouts do require a display: table much further up the tree and I can't removing it without a major refactor. If you remove the display everything works as I would expect: EXPECTED But having that display causes the parent to take into account the child elements total width pre-truncated (but with nowrap taken into account). It is as if the initial rendering happens without an overflow being defined and adds it after the fact (but by that point the width calculation is way too large). RESULT I can guess at why the rendering is breaking but I would like a more definitive answer about how the browser renders this... (Tested in Chrome/FF/Safari on Mac) A: The reason for this has got to do with the way tables layout cells when using the auto layout method. The details of how it works are explained in section 17 of the CSS spec, but the key point is that the auto layout depends on the contents of the cell (which is why it's so big when you force your content onto one line), whereas the fixed layout is only dependent on the table width (which is what you're expecting). If you just add table-layout:fixed to your .table selector, your problem should be solved.
{ "pile_set_name": "StackExchange" }
Q: What exactly is the "Oily Black Stone", and why is it everywhere? In The World of Ice and Fire (TWOIAF), a companion book to the A Song of Ice and Fire series, there are repeated references to mysterious "black stone" (often described as oily or greasy), which composes, among other things: The Seastone Chair Yeen The Toad on the Isle of Toads The Five Forts of Yi Ti Hightower's foundations Asshai What exactly is the significance of this black stone? Is it related to dragonglass? Why is it found in such diverse locations? Have Elio, Linda, or GRRM (the authors of TWOIAF) said anything regarding it? A: Well according the ASOIAF wiki entry on "black stone," it is used in many supernatural instances. For example, Maester Theron theorizes that the black stone was produced by the Deep Ones - "[a] queer, misshapen race of half men sired by creatures of the salt seas upon human women." Meanwhile, "The Bloodstone Emperor rejected the traditional gods of Yi Ti and instead encouraged the worship of a black stone said to have fallen from the sky." Based upon what I found, I would venture to guess that it does not have anything to do with "dragonglass." As to why it is found in such "diverse locations," it may just be a coincidence or it may have something to do with the aforementioned supernatural elements present in the series.
{ "pile_set_name": "StackExchange" }
Q: Django how to store forms data from several pages into one table I'm building a django project, and creating user profile app. But I want user to complete creating profile process in multiple pages. For example: first page fill in the address and phone number, and then user click "continue" to the second page, where user can fill in some other things like gender, date of birth. But I want to store all this information into one table. What I used to do is store the first page's data into some hidden field, and pass to the next page and submit them at the final page. Is that the correct and secure way? How django handle this condition? Thank you. A: Use Django's FormWizard
{ "pile_set_name": "StackExchange" }
Q: Convert a table column to a matrix in Matlab I have a Table (T) as shown below: >> Name = {'John';'Mary';'Martha'}; Age = [10.8;15.11;20.22]; T=table(Name,Age); >> T T = 3Γ—2 table Name Age ________ _____ 'John' 10.8 'Mary' 15.11 'Martha' 20.22 Converting the Age column to a matrix works fine, if I use: cell2mat(table2cell(T(:,2))) But doesn't work if I use: cell2mat(table2cell(T.Age)) and throws the following errror: >> cell2mat(table2cell(T.Age)) Undefined function 'getVars' for input arguments of type 'double'. Error in table2cell (line 15) t_vars = getVars(t); Is there any way I could use the column name T.Age instead using T(:,2) while converting this column into a matrix ? A: From the Access Data in a Table doc on the MathWorks site Parentheses allow you to select a subset of the data in a table and preserve the table container. while Dot indexing extracts data from one table variable. The result is an array of the same data type as extracted variable. You can follow the dot indexing with parentheses to specify a subset of rows to extract from a variable. So, if you use T.Age to access the data, the result should already be a matrix, i.e. you don't need to do any conversions using table2cell or cell2mat.
{ "pile_set_name": "StackExchange" }
Q: PostgreSQL output to JSON object/array I'm running PostgreSQL and are trying to convert this: SELECT car_id AS id, car_model AS model FROM cars into this: [{ "id" : 123, "model" : "Fiat" }, {"id": 124, "model": "BMW"}, ...] I've tried: SELECT json_agg( json_build_object(car_id AS id), json_build_object(car_model AS model) ) FROM cars and a lot other stuff, but seems to be stuck A: You can try to use only one json_build_object in json_agg function. json_build_object explain from the document. Builds a JSON object out of a variadic argument list. By convention, the argument list consists of alternating keys and values. using json_build_object function parameter will be like json_build_object([key1],[Key_Value1],[key2],[Key_Value2]..) TestDLL CREATE TABLE cars( car_id INT, Car_Model VARCHAR(50) ); INSERT INTO cars VALUES (1,'TEST1'); INSERT INTO cars VALUES (2,'TEST2'); Query SELECT json_agg(json_build_object('ID', car_id , 'Model', car_model )) from cars Result | result | |----------------------------------------------------------------| | [{"ID" : 1, "Model" : "TEST1"}, {"ID" : 2, "Model" : "TEST2"}] | sqlfiddle
{ "pile_set_name": "StackExchange" }
Q: What is the good strategy to backup mongodb's data without locking it (fsync & lock)? We have a mongodb running on only one AWS EC2 (no master-slave, no replica sets). The data files are stored in a separate EBS volume. So, what is the best way to backup and restore the data without locking it from writing (sync & lock)? Or we must have master-slave to achieve it? A: As long as you have journaling enabled (the default in MongoDB 2.0+), you can take advantage of EBS snapshots to get a consistent dump of the data files without the need for fSyncLock(). This is covered in more detail in the EC2 Backup & Restore documentation on the MongoDB site.
{ "pile_set_name": "StackExchange" }
Q: Dynamic Polymorphism's weird output I am unable to understand the output. I have following two classes, class A { public int i = 1; public virtual void Print() { Console.WriteLine("I am A"); } } class B:A { public int i =2 ; public override void Print() { i++; Console.WriteLine("I am B"); } } Now, when i run the following code, A a1 = new PolymorphismInDepth.B(); a1.Print(); Console.WriteLine(a1.i); I get the following output, I am B 1 why do I get 1? Why not 2? A: The base class object a1 is pointing to the Derived object in memory. Hence a1.Print() will call the methods reference, i.e., B().Print() but you cannot access B().i using this A().i. You need to cast it: Console.WriteLine(((B)a1).i); You are confused because you used same variable names. Try this out: class A { public int ai = 1; public virtual void Print() { Console.WriteLine("I am A"); } } class B : A { public int bi = 2; public override void Print() { bi++; Console.WriteLine("I am B"); } } static void Main(string[] args) { A a1 = new B(); a1.Print(); Console.WriteLine(a1.ai); Console.WriteLine(((B)a1).bi); Console.Read(); } Trying to access bi like this should give you a compile time error: Console.WriteLine(a1.bi); //ERROR: 'A' does not contain a definition for 'bi'... Update: To add on to the answer - an implementation like this where you override the base class member variable behavior can also be achieved: class A { private int i = 1; public virtual int I { get { return i; } } public virtual void Print() { Console.WriteLine("I am A"); } } class B : A { private int i = 2; public override int I { get { return i; } } public override void Print() { i++; Console.WriteLine("I am B"); } } A a1 = new B(); a1.Print(); Console.WriteLine(a1.I); Console.WriteLine(((B)a1).I); Output: I am B 3 3
{ "pile_set_name": "StackExchange" }
Q: Quantum death of stars This comes from a comment on this question, to quote: The death of (large mass) stars is also based on quantum events with probabilities technically not 1 (and is very fast), so it is technically possible for a star not to die in a way it really ought to by sheer chance. The question is what quantum events are involved in the death of a star (likely and unlikely)? If many of these very unlikely quantum events happened at the same time all over the star, how could the death of a star differ form the typical nova or simply cooling down? A: Stellar fusion and supernovae are governed by quantum particle interactions (on massive scales). In general there are many possible ways for particles to interact, decay, etc. at various probabilities. To understand the physics of a system correctly you must take account of all possibilities (up to an error tolerance in actual practice). One often sees phrases of the form "situation X favors reaction Y". This means the conditions (X) make the the probability of Y greater than any other possible reaction, but it doesn't equate to Y having probability 1. Some may prefer to use this phrasing for when Y's probability is, in some sense, much larger than any other event. The proton-proton chain that governs the main sequence stage of a star is a prime example of why you cannot discount the reactions which aren't favored. If you did, you would conclude that our own sun is incapable of fusion. The 'favored' reaction for two interacting protons in a star like our sun is to simply bounce off of each other thanks to Coulomb repulsion. The protons simply don't have enough energy to overcome this repulsion in order to undergo fusion. Technically this statement is also not probability 1, but rather very close to it. But an improbable quantum tunneling event is possible to bypass this potential barrier, allowing the interacting protons to fuse when they collide just right and the dice favor them. But a diproton is unstable. The heavily favored reaction in this state is for the diproton to immediately decay into two protons. But there is a small chance that one of the protons will undergo a beta decay into a neutron, instead, at which point you have a stable helium nucleus. That these things are so unlikely is a major factor in why our sun needs billions of years to exhaust enough of its hydrogen (aka protons) in order to initiate helium fusion and exit the main stage. Even very large stars still need millions of years because of this. So while the proton-proton reaction is rather unlikely, stars are simply so immense that it is not only a virtual certainty that some proton-proton reaction will yield helium, but in fact that it is a virtual certainty that the reactions will occur in large numbers and continuously until the available reactants dwindle. At the other extreme, we have supernovae. There are quite a lot of varieties of supernovae, but the commonly understood types--the outer layers collapse and then violently rebound off the core--feature a sudden loss of radiation pressure due to certain endothermic reactions becoming favorable. Iron production from fusion is the culprit here: it takes more energy to fuse it than is released. The final split second of this sort of star's life is when conditions favor the production of iron via fusion. Ridiculously favors it, as I really do mean it is the final split second. There is an inconceivably tiny chance that this iron production would fail to occur for some chosen period of time, and if it happens to stall long enough then the star would likely undergo some other event. See also David's answer for another wildly improbable, but technically possible, example of random chance altering a star's death. A: Suppose you collect 11.0114 grams of carbon-11, come back 27.11 hours (80 half lives) later, and see what your sample has become. The most likely outcome: You'll find that you have 11.0093 grams of boron-11 and absolutely no carbon 11. You might find an atom or two of carbon-11 amongst those 11.0093 grams of boron-11. What about other results, for example, what is the probability that not a single one of those Avogadro's number of carbon-11 atoms will decay into boron-11 over a 27.11 hour interval? It is "technically possible" that none of those Avogadro's number of carbon-11 atoms will decay in 27.11 hours. The probability that a single atom of carbon-11 won't have decayed in that time interval is $2^{-80}$. That's a tiny number. The probability that not a single one of those Avogadro's number of carbon-11 atom won't have decayed is $\left(2^{-80}\right)^{6\times 10^{23}}$, or less than one out of one in $10^{10^{25}}$. That's not just a tiny number. The difference between "technically possible" and "can't happen" is essentially zero. How is this applicable? This result is, for example, applicable to a white dwarf stealing mass from a binary pair and turning into a neutron star rather than becoming a type 1A supernova as the white dwarf's mass approaches the Chandrasekhar limit. All it takes is a tiny number (maybe just one) carbon-carbon fusion reactions. The odds this won't happen as the mass gets ever closer to the Chandrasekhar limit is not just small. It is smaller than smaller than small. But it is "technically possible."
{ "pile_set_name": "StackExchange" }
Q: How to make git changes while not overwriting previous author's name by current author I want to beautify the whole project and format the code properly, but it will rewrite the current code and make me the author of, like, 50% of code. Our team and me don't want that. So the question is: how do I make changes to repository, while all the authors stay the same? I understand this process as something that probably contains 2 steps: 1) making a commit in a separate branch with a lot of changes, and then 2) reverting me as an author of every line of this commit to previous authors. Is it even possible? I can't wrap my head around it. Maybe, there is another way? How can I do it better? We use Bitbucket repository, Qt Creator as IDE and Artistic Style as a beautifier. Any help and advice will be greatly appreciated. A: GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_AUTHOR_DATE GIT_COMMITTER_NAME GIT_COMMITTER_EMAIL GIT_COMMITTER_DATE These variables can be used to forge the name, the email, the date of author and committer on git commit. For example:GIT_AUTHOR_NAME="foo" GIT_AUTHOR_EMAIL="[email protected]" git commit -m 'blah' git cherry-pick or git rebase keeps the same author but changes the committer to the current user.name and user.email in git-config. If you will use cherry-pick and rewrite some code, here's the possible method. Let's say old-branch is A-B-C. git init newbranch cd newbranch git init git remote add origin /foo/bar/.git git fetch origin old-branch git checkout --orphan new-branch A #make some extra changes git add . GIT_AUTHOR_NAME=$(git log -1 --pretty=%an A) GIT_AUTHOR_EMAIL=$(git log -1 --pretty=%ae A) GIT_COMMITTER_NAME=$(git log -1 --pretty=%cn A) GIT_COMMITTER_EMAIL=$(git log -1 --pretty=%ce A) git commit -m $(git log -1 --pretty=%B A) git cherry-pick -n B #make some extra changes git add . GIT_AUTHOR_NAME=$(git log -1 --pretty=%an B) GIT_AUTHOR_EMAIL=$(git log -1 --pretty=%ae B) GIT_COMMITTER_NAME=$(git log -1 --pretty=%cn B) GIT_COMMITTER_EMAIL=$(git log -1 --pretty=%ce B) git commit -m $(git log -1 --pretty=%B B) #make some extra changes git add . git cherry-pick -n C GIT_AUTHOR_NAME=$(git log -1 --pretty=%an C) GIT_AUTHOR_EMAIL=$(git log -1 --pretty=%ae C) GIT_COMMITTER_NAME=$(git log -1 --pretty=%cn C) GIT_COMMITTER_EMAIL=$(git log -1 --pretty=%ce C) git commit -m $(git log -1 --pretty=%B C) Now we get the beautified new-branch.
{ "pile_set_name": "StackExchange" }
Q: Making full-size main content with semantic-UI Sidebar react components I'm trying to make a Webapp with react using Semantic Ui components. However, I'm really struggling to make the main content component take up the full-size of the screen (see image). I want the main content component to fill up the rest of the space but it seems like it's only taking up as much space as it needs to. Ultimately I want to be able to have the sidebar sticky and only scroll the main content render() { const { visible } = this.state return ( <div> <Button onClick={this.toggleVisibility}>Toggle Visibility</Button> <Sidebar.Pushable as={Segment}> <Sidebar as={Menu} animation='push' width='thin' visible={visible} icon='labeled' vertical inverted> <Menu.Item name='home'> <Icon name='home' /> Home </Menu.Item> <Menu.Item name='gamepad'> <Icon name='gamepad' /> Games </Menu.Item> <Menu.Item name='camera'> <Icon name='camera' /> Channels </Menu.Item> </Sidebar> <Sidebar.Pusher> <Segment basic> <Header as='h3'>Application Content</Header> <Image src='/assets/images/wireframe/paragraph.png' /> </Segment> </Sidebar.Pusher> </Sidebar.Pushable> </div> ) } I've tried to apply the style inline {height:100%} to everything from within the up the hierarchy to the root component but nothing seems to make it fill the rest of the page. I know that this seems like such a simple problem, but I'm stuck haha. Any ideas? Cheers desired outcome A: The sidebar will take the same height as its enclosing div. It looks like you want the content to stretch to exactly 100% of the viewport. If this is the case, you can set height on the enclosing div to '100vh'. <div style={{height: '100vh'}} /> If you want the height to possibly go beyond, you can set min-height to '100vh'. <div style={{minHeight: '100vh'}} /> If you want it to just take up the rest of the page before or after some other content, you can do the following: <div style={{minHeight: '100vh', display: 'flex', flexFlow: 'column nowrap'}}> <div>Content Before</div> <div style={{flex: 1}}> Main Content with Sidebar </div> <div>Content After</div> </div>
{ "pile_set_name": "StackExchange" }
Q: How to deal with administration tools such as ipscanners and PSTools? In my company (And many others around the world) there is a wide usage by tech teams of tools such as ipscanners, psexec, pskill and other tools. How do you deal or control the usage of such tools in your environment? It's common for threat actors after an intrusion to use internal administration tools that are already available within servers and workstations, I would like to prevent. A: If you're worried about malicious actors using standard user internal utilities (psexec, pskill) after gaining access to a system, you're worrying about a scenario where no matter what actions are taken in preparation for the intrusion, the attacker will be able to circumvent it, as they already have access to the machine. Making it more difficult to use some of the "power-user" oriented tools on the system will only make it more frustrating for your legitimate users to do their jobs, and won't do anything to prevent the attacker other then mildly inconveniencing them. However, if you're concerned about tools and utilities that require root/admin level access being used by the attacker after intrusion, you should look into securing your user system (e.g. only giving sudo/admin level access to users signing in with PGP (or if Windows, only from local logins), or only allowing local access to root (only applicable to Linux), etc) instead of trying to limit the tools available in your userspace.
{ "pile_set_name": "StackExchange" }
Q: Try and catch method, python, indentation error can't figure it out #setBirthday sets their Birthday to a date def setBirthday(self): while True: try: day = int(raw_input('Please enter the date of the month (1-31) you were born on here ->')) if day <= 0 or day >= 32: print "better try again..." except ValueError: continue else: break month = int(raw_input('Please enter the month of the year (1-12) you were born on here ->')) if month <= 0 or day >= 13: print "better try again..." except ValueError: continue else: break year = int(raw_input('Please enter the year you were born (19xx or 20xx) here ->')) self.birthday = datetime(year, month, day) print str(varPerson.getName()) + " you were born on " + str(month) + "/" + str(day) + "/" + str(year) The indentation error is just above varPerson the last 3 lines. I have tried and tried to get this scenario working with exceptions to be able to have a smooth running script that allows for additional tries if value is not appropriate. Suggestions? I have been using this link for help: Asking the user for input until they give a valid response A: Your outer try block does not have a corresponding except block. It doesn't make sense have a while or try block directly in a class definition. They must be inside a method definition. You cannot define methods inside a while block in a class. Instead of trying to fix the above as they stand, try taking a good look at your code and figuring out what it is that you want to do. Then, ask how to best implement that big-picture objective-focused question on StackOverflow or another StackExchange site, showing what you've tried so far. A: If you really want handle any exceptions, try below code: import datetime from datetime import datetime class Person(object): def __init__(self, name): self.name = name self.birthday = None #getName returns the name of the person def getName(self): return self.name #setBirthday sets their Birthday to a date while True: try: def setBirthday(self): while True: try: day = int(raw_input('Please enter the date of the month (1-31) you were born on here ->')) month = int(raw_input('Please enter the month of the year (1-12) you were born on here ->')) year = int(raw_input('Please enter the year you were born (19xx or 20xx) here ->')) self.birthday = datetime(year, month, day) print str(varPerson.getName()) + " you were born on " + str(month) + "/" + str(day) + "/" + str(year) except ValueError: print "better try again...return to the start of the loop" continue else: break #if day <= 0 or day >= 32: #print "Please enter a number between 1 and 31. Try again." #getAge returns how many days old the individual is def getAge(self): dateNow = datetime.now() dateBirth = self.birthday timedelta = dateNow - dateBirth print str(varPerson.getName()) + " you have been living on Earth for " + str(timedelta) #current date - birthdate to get specific days, timedelta except: pass varPerson = Person(raw_input('Please enter your name here ->')) varPerson.setBirthday() varPerson.getAge() Personally, While True is not good to use...
{ "pile_set_name": "StackExchange" }
Q: System.Io is not working properly I want to copy some text on textbox2 to a txt file.I want to create a kk.txt file after clicking the button and need to store textbox2 text to that kk file. Here is the code i tried but it only create kk.txt file and not storing textbox2 data. private void button6_Click(object sender, EventArgs e) { //textBox4.Text +=Clipboard.GetText()+Environment.NewLine; Clipboard.SetText(textBox2.Text); System.IO.File.Create(@"C:/Ebaycodes/kk.txt"); string path = @"C:/Ebaycodes/kk.txt"; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.Write(textBox2.Text); sw.Dispose(); } } } could somebody help me to fix this error. A: The problem is your if statement, it only runs if the file doesn't exist. You created it, so it does exist, and the if doesn't run. You can change your entire routine to this: private void button6_Click(object sender, EventArgs e) { Clipboard.SetText(textBox2.Text); File.WriteAllText(@"c:\Ebaycodes\kk.txt", textbox2.Text); }
{ "pile_set_name": "StackExchange" }
Q: Combobox and its item display problem wpf I am using the following code to display items in the combobox. but item is not getting displayed. Code: <ComboBox Width="100" ItemsSource="{Binding}" SelectedIndex="0" Name="cbProduct"/> List<ComboObject> combObjList = new List<ComboObject>(); combObjList.Add(new ComboObject { Text = "All", Value = "%" }); combObjList.Add(new ComboObject { Text = "Music", Value = "1" }); combObjList.Add(new ComboObject { Text = "Games", Value = "2" }); combObjList.Add(new ComboObject { Text = "Video", Value = "3" }); cbProduct.DataContext= combObjList; cbProduct.DisplayMemberPath = "Text"; cbProduct.SelectedValuePath = "Value"; A: Make sure that the properties you are binding to have a 'get' defined. public ObservableCollection<ComboObject> CombObjList { get { return combObjList; } } private ObservableCollection<ComboObject> combObjList = new ObservableCollection<ComboObject>(); class ComboObject { public string Text { get; set; } public string Value { get; set; } } Also, take a look at your 'Output' window do see if you are having any Binding errors. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Logon Script, detect network status I'm wondering if it it is possible to build a logon script, for Windows XP & Vista, that will detect where the user is connected to a particular network (Defined by IP schema). If they are connected to a specific network, then it will display a message such as, "Please note your will not be able to access the XYZ Network Drive, or your company email" A: Why do this with batch file gyrations when you can just link GPOs to site objects? The "bonus" being that if you add addt'l subnets or move subnets around you'll never have to edit your script. If you're looking at this being a user logon script that you want to apply only when users logon to specific computers then you'll need to look at using loopback group policy processing as well.
{ "pile_set_name": "StackExchange" }
Q: How can I get all annotations within a class using ICompilationUnit I have a class Book which has some annotations like @Override,@Before,@After. How can I get those annotations using ICompilationUnit? A: Javadoc for IAnnotation states that: "Annotations are obtained using IAnnotatable.getAnnotation(String). Note that annotations are not children of their declaring element. To get a list of the annotations use IAnnotatable.getAnnotations()." What's an IAnnotatable? IField, ILocalVariable, IMethod, IPackageDeclaration, IType. There are methods on ICompilationUnit for getting objects of those types.
{ "pile_set_name": "StackExchange" }
Q: Adding extra tag for C types This is my problem: I'm using NON standard ANSI C (a modified r-tems for ARM that compile with standard GCC) and I want add an extra tag in front of C types which maintain the type property and add some "stuff". The final result will be something like this: REL char *p; This is still a pointer to char and the compiler must treat like that, but now the REL tag will define that p is a RELiable pointer too. HP int a; the same but now the HP tag will define this int as an HighPerformance int. I have to change/modify the preprocessor? How? PS:that isn't very important however by the specific of my project I can't use a simple #define because REL and HP tag will attached to a special hardware routine bound directly to the preprocessor. (This is the previously mentioned "stuff"). A: Use the __attribute__((section("SECTION"))) attribute to tell GCC to place the variable in a specific section. Then, use a linker script to ensure that the the appropriate sections get mapped to the appropriate places in memory. For example: #define REL __attribute__((section("REL"))) #define HP __attribute__((section("HP"))) char *p REL; int a HP; I'm not super-familiar with linker scripts, so figuring out exactly how to do that is an exercise for the reader.
{ "pile_set_name": "StackExchange" }
Q: Call Macro on a specific sheet / Excel I want to run a macro on a specific sheet, in my case the sheet is called "Tablet". If a cell value in "Tabelle1" changes, I want to run this macro in the "Tablet" sheet. Code in my Tabelle1: Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = "$C$2" Then Call Delete_OptionB1 End If End Sub This part works. Macro Code: Sub Delete_OptionB1() ' ' Delete_OptionB1 Makro ' With Worksheets("Tablet") .Range("M2:AD2").Select Selection.ClearContents End With End Sub This wont do the job. Any suggestions how I get this working? A: In your code using a with block With Worksheets("Tablet") .Range("M2:AD2").Select Selection.ClearContents End With You are selecting .Range("M2:AD2").Select but then clearing the contents of the selection on whatever sheet may be active when you Delete_OptionB1. Change to include a . - .Selection.ClearContents. Even better, get rid or the With...End With and Select altogether. A single line will do it all: Sub Delete_OptionB2() ' ' Delete_OptionB1 Makro ' Worksheets("Tablet").Range("M2:AD2").ClearContents End Sub
{ "pile_set_name": "StackExchange" }
Q: Laravel with Confide - Custom validator not working? The documentation of the Zizaco/confide package for Laravel isn't very descriptive when explaining how to use custom validators. I'd like to be able to validate first name, last name, address, city, state etc. fields in my registration process however I haven't found anything that works besides modifying the vendor package. Per the documentation, I should be able to put this in app/models/AccountValidator.php <?php use Zizaco\Confide\UserValidatorInterface; use Zizaco\Confide\ConfideUserInterface; class AccountValidator implements UserValidatorInterface { public function validate(ConfideUserInterface $user) { unset($user->password_confirmation); // Because this column doesn't really exists. Log::info("Using a custom validator!"); return true; } } and in app/start/global.php App::bind('confide.user_validator', 'AccountValidator'); I've tried putting my rules in the validate function as well as outside of it with no luck, instead of validating anything it'll try to insert the empty values to the database. I've also tried composer dump-autoload as mentioned here. I found this StackOverflow question but the only answer doesn't appear to be an "official" solution, and Zizaco has not replied to this question on Github (yes I did try that code as well), so I'm not sure what else to try. Any suggestions? A: This is how I do it: <?php use Zizaco\Confide\UserValidator as ConfideUserValidator; use Zizaco\Confide\UserValidatorInterface; class UserValidator extends ConfideUserValidator implements UserValidatorInterface { public $rules = [ 'create' => [ 'username' => 'required', 'email' => 'required|email', 'password' => 'required|min:4', ], 'update' => [ 'username' => 'required', 'email' => 'required|email', 'password' => 'required|min:4', ] ]; }
{ "pile_set_name": "StackExchange" }
Q: css to link tag in rails I have a link tag of rails like below <%= link_to 'New Product', new_product_path %> I want to increase the font size of the New Product and apply some CSS property to it. Can I do that in the rails tag itself? A: <%= link_to 'New Product', new_product_path, {style: 'font-size: 2em; color: black' } %> But a nicer solution would be, to add a class to the link, and than style the class in a separate css-file. <%= link_to 'New Product', new_product_path, class: 'myclass' %> CSS-File: .myclass { font-size: 2em; color: black; }
{ "pile_set_name": "StackExchange" }
Q: Recreating the look of a lightroom preset in another software I have a number of Lightroom presets that I have developed or downloaded from the web and I am trying to recreate them in Luminar. Despite using the same values for the same/similar filters, my images turn out completely differently. Lightroom default luminar default Lightroom processed - exposure+0.36, contrast+20, highlights-70,shadows+70. whites+20, blacks-80, saturation-30,vibrance-20,split tone highlight hue+45 saturation+5 shadow hue+45 saturation+22,clarity+60, postcrop vignette highlight priority amount-15 luminar processed - exposure+0.36, contrast+20, highlights-70,shadows+70. whites+20, blacks-80, saturation-30,vibrance-20,split tone highlight hue+45 saturation+5 shadow hue+45 saturation+22,clarity+60, postcrop vignette highlight priority amount-15 (Original link: http://imgur.com/a/O2Ale) Is there anyway to recreate a style from one software to another without doing it manually and subjectively? A: This is something that I don't expect is possible. I worked 9 years writing image processing software and I can tell you there are so many ways to implement each algorithm that it would be difficult for any two to perfectly match. The first problem you have is one of units. Most numbers in the user interface are meaningless. Other than exposure which can be measured in EV which is a unit, all other values you changed such as the contrast, highlights, shadows, etc are not in any specified units, so moving sliders to the same value is pointless. Processing can be done in so many ways even when considering something that sounds simple like saturation or contrast. Most programs convert to some representation, apply the transform, and then convert back. The nature of that representation, being linear, gamma, log, etc can make the resulting change dramatically different. This is so subtle that you may notice that even Lightroom does not always render like Lightroom! In the options for processing, you will be offered the choice of Lightroom engine because they do not always produce the same results.
{ "pile_set_name": "StackExchange" }
Q: printing timestamp values in a csv file I have a numpy array of time which is in seconds. I use the following code to convert seconds in to timestamp m, s = divmod(seconds, 60) h, m = divmod(m, 60) for i in range(0, 24300): print h[i],":", m[i],":", s[i] I need to print this timestamp values either in a csv file like( 01:05:25,01:04:60, 05:04:2) or store in a numpy array. Thanks in advance A: Remembering that a CSV file is what it says, just comma separated values. You've basically already got your answer. You might want to delimit the times with quotation marks, some csv-parsers might assume that the values need to be text strings if they aren't just simple numbers. Here's an example python code fragment import time import datetime from datetime import datetime for i in range(10): d = datetime.now() print('"{0}:{1}:{2}",'.format(d.hour,d.minute,d.second)) time.sleep(1) And this outputs the following times: "12:30:40", "12:30:41", "12:30:42", "12:30:43",
{ "pile_set_name": "StackExchange" }
Q: Given $f(x,y)=sin(x^2y)$, Prove that $Df(0,0)=0$ Assume that $f(x,y)=sin(x^2y)$ is given. a) Show that $f_x(0,0)=0$ and $f_y(0,0)=0$. b) Then Prove that $f$ is differentiable on $(0,0)$ and $Df(0,0)=0$. Note: I wrote the formula for the first part and solved it. The problem is the second part. This is my try: I claim that $Df(0,0)=0$. So, $L(h,k)=(0,0)$. Then i should prove that: $\lim_{(h,k)\to(0,0)} \frac{f((0,0)+(h,k))-f((0,0))-(0,0)}{|| (h,k) ||}= \lim_{(h,k)\to(0,0)}\frac{sin(h^2k)-sin(0)}{||(h,k)||}=\lim_{(h,k)\to(0,0)}\frac{sin(h^2k)}{|| (h,k) ||}$ So, How can i prove that $\lim_{(h,k)\to(0,0)}\frac{sin(h^2k)}{|| (h,k) ||}=0$ ? A: $$\frac{|sin(h^2k)|}{|| (h,k) ||} \leq \frac{|sin(h^2k)|}{|h |} \leq \frac{|h^2k|}{|h |} = |h| |k| $$
{ "pile_set_name": "StackExchange" }
Q: Find the smallest value in an array excluding 0 I have an array like: val a = Array(0, 6, 15, 0, 20, 0) if I use the reduceLeft function for finding the smallest value in this array, something like: val f = (x: Int, y: Int) => x min y val rlf = a.reduceLeft(f) how I can find the smallest number in this array excluding the comparison with 0, because in my case I am using 0 as a default value not as something that I want to compare with?! A: Origin: scala> val a = Array(0, 6, 15, 0, 20, 0) a: Array[Int] = Array(0, 6, 15, 0, 20, 0) scala> a.filterNot(_==0).min res6: Int = 6 Update: I missed case with empty array after filter. So correct version is like a.filterNot(_==0) match { case Array() => -1 case arr => arr.min } or Try(a.filterNot(_==0).min).getOrElse(-1) Update: To get min with index: Try(a.zipWithIndex.filterNot(_._1 == 0).minBy(_._1)).getOrElse((-1,-1)) Or a.zipWithIndex.filterNot(_._1==0) match { case Array() => (-1,-1) case arr => arr.minBy(_._1) } or (@Ryan solution with one iteration over array) a.foldLeft((-1, -1, 0)) { case ((min, minInd, length), n) => if (n == 0) (min, minInd, length + 1) else if (min > -1) { val localMin = Math.min(min, n) (localMin, if (localMin == min) minInd else length, length + 1) } else (n, length, length + 1) } it's maybe much more pretty to use "classical" cycle for optimized solution. A: You can do it in one pass with a foldLeft, which will also handle the empty case: a.foldLeft(-1) { (min, n) => if (n == 0) min else if (min > -1) Math.min(min, n) else n } Start with -1. If n is 0, use the previous minimum. If the previous minimum is greater than -1, take the min of the previous minimum and n. Otherwise (and this is just the first non-zero n), n is the new minimum. foldLeft is safe to use on an empty collection because you are providing a default value. If you have an empty array, foldLeft will just return -1 in this case.
{ "pile_set_name": "StackExchange" }
Q: How can I access with JS nonstandard tags in a HTML page? I wish to develop some kind of external API which will include users putting some nonstandard tags on their pages (which I will then replace with the correct HTML). For example: <body> ... ... <LMS:comments></LMS:comments> ... ... ... </body> Hoe can I target and replace the <LMS:comments></LMS:comments> part? A: Just use getElementsByTagName as usual to get the element. You cannot change the tag name, you will have to replace the entire element. See http://jsfiddle.net/2vcjm/
{ "pile_set_name": "StackExchange" }
Q: Yii2 smtp error 500 5.5.1 command unrecognized In my Yii2 application i've a contact form that sends email with swift. I've configured my application in this way: those are the configurations in web.php: 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', // send all mails to a file by default. You have to set // 'useFileTransport' to false and configure a transport // for the mailer to send real emails 'useFileTransport' => false, 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => 'authsmtp.myhost.com', 'username' => 'username', 'password' => '************', 'port' => '25', 'encryption' => 'tls', ], ], and this is the part of my controller where i send the mail: if($contact->load($post) && $contact->validate()) { Yii::$app->mailer->compose('request',['contact' => $contact ]) ->setFrom('[email protected]') ->setTo('[email protected]') ->setSubject('This is a test email') ->send(); return $this->redirect(['login/index']); } I receive a Swift_TransportException with this error: Expected response code 220 but got code "500", with message "500 5.5.1 command unrecognized" Is there a way to retrieve more information about the error generated by swift? This message is too general. Thanks in advance for all the help A: For logging use yii\swiftmailer\Logger: Logger is a SwiftMailer plugin, which allows passing of the SwiftMailer internal logs to the Yii logging mechanism. Each native SwiftMailer log message will be converted into Yii 'info' log entry. SMTP ports are 465 or 587 with SSL/TLS, and 25 without. From the Wikipedia page on SMTP: SMTP by default uses TCP port 25. The protocol for mail submission is the same, but uses port 587. SMTP connections secured by SSL, known as SMTPS, default to port 465 (nonstandard, but sometimes used for legacy reasons). Unless your server has been explicitly set to use port 25 with SSL/TLS you shouldn't use encryption.
{ "pile_set_name": "StackExchange" }
Q: Windows phone 8.1 app connect with a database I'm totally new to the windows phone 8.1 app development. I'm trying to develop a simple app with a database using visual studio 2013. It is not a silverlight app. my app just have a text field and a button.And i have a MySQL database in a local server(WAMP). I need to get a input from the text field and store it in the database. First thing that I want to know is it possible to do? If it is possible I would be very grateful if you could provide a step by step guide or a link where i can learn about this. If it is not possible what are the other ways that I can try to store my input in a database? A: Local storage I'm guessing you're looking for a way to store structured data locally on the phone. AFAIK, MySQL is not supported on Windows Phone (MySQL is big, runs as a server, and it wouldn't be possible or practical to "install" it onto a phone). Instead what Microsoft endorses is to use SQLite. You'll first need to download the SQLite library as a Visual Studio extension. Then you'll need to install something like SQLitePCL (from NuGet) which essentially wraps the native SQLite library so that it is accessible from .NET languages. Make sure you add both references to your project. SQLite stores a database as a file that you can put in the local storage for your app. Remote storage I'm not sure if it's directly possible to connect to a remove MySQL server from a WP app. Usually you'd access a remote database through a webserver that exposes an API for you to use (e.g. a REST API). You can then send data to the webserver via a HTTP POST request, and then your webserver will store the data in the database. This is a big topic, and involves knowledge of server-side programming such as ASP.NET, Ruby on Rails, Django, PHP, etc. This topic is too broad for me to give you specifics on how to do this. See this answer.
{ "pile_set_name": "StackExchange" }
Q: Manifest gives error once Remove BlackBerry Nature From Project I added BlackBerry Nature to Android Project and remove the BlackBerry Nature From Project. After that Android project Manifest shows error and not build the project. I did not do any changes on Manifest and just show error mark. I closed the eclipse,clean and build the project but still same How to solve this ? A: After several hours I found a solution actually I don't know what happen but it worked.I change the java compiler version to 1.5 and build the project, again I changed the compiler to 1.6 and build the project Then and only it fixed. ;)
{ "pile_set_name": "StackExchange" }