text
stringlengths
64
89.7k
meta
dict
Q: How to remove code redundancy in repositories Currently I have 2 tables in my database. Meals and Tables (it's restaurant managing application). I have created repositories interfaces and their implementation for both tables (Authorized user should be able to add/remove/update meals and tables data when for example new meal appears in menu). The problem is that both of my interfaces have basically the same method which causes code redundancy I believe. These are my interfaces: public interface IMealsRepository { IEnumerable<Meal> FindAll(); Meal FindById(int id); Meal FindByName(string mealName); Meal AddMeal(MealDTO newMeal); void RemoveMeal(int id); Meal UpdateMeal(Meal meal); } public interface ITablesRepository { IEnumerable<Table> FindAll(); Table FindById(int id); Table AddTable(Table newTable); void RemoveTable(int id); Table UpdateTable(Table table); } I tried to make a base repository interface with common methods of FindAll, FindById, Add, Remove, Update but I ran into problem that I'm taking and returning different types e.g. for Add method I either return Table object or Meal object depending on the interface. I tried to go with object approach: public interface IRepository { IEnumerable<object> FindAll(); object FindById(int id); object Add(object newObject); void Remove(int id); object Update(object updatedObject); } Then I would just IMealsRepository : IRepository and ITablesRepository : IRepository and add additional methods unique for those repositories which is for example searching Meal by name. My meals interface would look like this: public interface IMealsRepository : IRepository { Meal FindByName(string mealName); } I also have Services for those Repositories that are the only one able to access repositories and return those particular types of objects using repositories methods. Is that a good approach or I'm going way too deep in this project regarding interfaces of my repositories? A: You can follow this link to implement Generic/Base Repository (If you are not using Entity Framework/SQL, still this is valid). Other than Base/Generic repository pattern you need to consider a few things Use UnitOfWork pattern when you are doing the operation in multiple repositories to maintain transaction. Don't create repository for each table/domain object. Create a repository only for Aggregate object (example in E-Commerce context is Order not for OrderDetail). Don't create table/domain-specific repository, If you don't need. If you're doing simple CRUD operation and all type of operation already available in my base repository then you don't need a table-specific repository public class AdvertisementService : IAdvertisementService { private readonly IBaseRepository imageRepository; public AdvertisementService( IBaseRepository<AdvertisementImage> imageRepository) { this.imageRepository = imageRepository; } Startup.cs builder.Services.AddScoped<IBaseRepository<AdvertisementImage>, BaseRepository<AdvertisementImage>>(); In the above example, I didn't create any `AdvertisementImage' repository.
{ "pile_set_name": "StackExchange" }
Q: Unix shell script: exit with returning value I have the following unix shell script, in which i have two integer variables namely a and b. If a is greater then or equal to b then shell script should exit with returning 0. Else it should exit with returning 1. My try: Script: ConditionTest.sh #!/bin/sh a=10 b=20 if [ $a -ge $b ] then exit 0 else exit 1 fi .... .... .... Running Script: $ ./ConditionTest.sh $ Note: I am not getting any return value after executing the file. A: The shell puts the exit status of the last command in the variable ?. You could simply inspect it: mycommand echo $? ... or you could use it to do something else depending on its value: mycommand && echo "ok" || echo "failed" or alternatively, and slightly more readable: if mycommand; then # exit with 0 echo "ok" else # exit with non-zero echo "failed" if A: Your script looks fine; you did everything right. #!/bin/sh a=10 b=20 if [ $a -ge $b ] then exit 0 else exit 1 fi So here's where we run it and check the return value: $ sh test.sh $ echo $? 1 $ 10 is not greater than or equal to 20. Another way to test it would be like this: $ sh test.sh && echo "succeeded" || echo "failed" failed As noted in the comments, you should also quote your variables, always: if [ $a -ge $b ] Should be: if [ "$a" -ge "$b" ]
{ "pile_set_name": "StackExchange" }
Q: Add border around Div HTML component in Dash (Python) I am simply trying to add a border around a html.Div component in Dash using Python. I have tried something like: html.Div(children=[...], style={"border":"2px") or html.Div(children=[...], style={"border":{"width":"2px", "color":"black"}) But it doesn't seem to be working. Can someone help on this? Thanks A: html.Div(children=[...], style={"border":"2px black solid"}) The border property is a shorthand property for the following individual border properties: border-width border-style (required) border-color Better way is to use css classes html.Div(children=[...], className='divBorder') then add a css class .divBorder{ border: 2px solid black; }
{ "pile_set_name": "StackExchange" }
Q: Weird $ behavior: ${\string} While I was experimenting, I found out that print ${\string} would print string to the screen. Is this normal? Does this have a name? A: The bareword "string" is being understood as a string you simply didn't quote. use strict would prohibit this, and use warnings would have complained about it. You are then taking a reference to the string (effectively, my $ref = \"string";), and dereferencing it (effectively, ${$ref}). It is "normal" in the sense that life without strict is sometimes both slippery and sharp-edged. A: It's a reference to string being dereferenced with ${} perl -MO=Deparse -e "print ${\string}" print ${\'string';};
{ "pile_set_name": "StackExchange" }
Q: IE width 100% doesn't work. How to fix it? This code won't work in any IE browser: main { position: relative; } div { position: absolute; height: 300px; background-color: red; width: 100%; } <main> <div></div> </main> I tried using width 100vw but horizontal scroll appears if page doesn't fit the viewport. A tried something like width calc(100vw - vertical_scroll_width) but it is not okay if there is no vertical scroll on the page. A: "Partial support refers to only the element (added later to the spec) being "unknown", though it can still be used and styled." As shown here : https://caniuse.com/#search=main Main is not fully supported. You can still style it through. As explained before, simply do : main { display: block; }
{ "pile_set_name": "StackExchange" }
Q: What makes the searchbar option selectedScopeButtonIndexDidChange execute? I'm trying to learn the new UISearchController in swift. Not too many examples out there yet. I have been looking at adding a scope option such that when a user selects the scope in the search the list is filtered by the scope. I've been looking at the programming iOS 8 O'Reilly book, examples. They have an example where the filtering is done in one screen. I realize that the actual search will not work with the current scope values I have. All I'm after at the moment is to get that function working. I'm using this code to test ideas and then porting those ideas to my application. If I enter a text search it all works, but when I try the scope, it doesn't. Here is the code. Any hints as to why the following code is never called: func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { println("In selectedScopeButtonIndexDidChange") updateSearchResultsForSearchController(searcher) } Here is the complete code. import UIKit class ViewController: UITableViewController, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating { var sectionNames = [String]() var sectionData = [[String]]() var originalSectionNames = [String]() var originalSectionData = [[String]]() var searcher = UISearchController() var searching = false override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { //super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let s = NSString(contentsOfFile: NSBundle.mainBundle().pathForResource("states", ofType: "txt")!, encoding: NSUTF8StringEncoding, error: nil)! let states = s.componentsSeparatedByString("\n") as [String] var previous = "" for aState in states { // get the first letter let c = (aState as NSString).substringWithRange(NSMakeRange(0,1)) // only add a letter to sectionNames when it's a different letter if c != previous { previous = c self.sectionNames.append( c.uppercaseString ) // and in that case also add new subarray to our array of subarrays self.sectionData.append( [String]() ) } sectionData[sectionData.count-1].append( aState ) } self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.tableView.registerClass(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "Header") self.tableView.sectionIndexColor = UIColor.whiteColor() self.tableView.sectionIndexBackgroundColor = UIColor.redColor() // self.tableView.sectionIndexTrackingBackgroundColor = UIColor.blueColor() // self.tableView.backgroundColor = UIColor.yellowColor() self.tableView.backgroundView = { // this will fix it let v = UIView() v.backgroundColor = UIColor.yellowColor() return v }() // in this version, we take the total opposite approach: // we don't present any extra view at all! // we already have a table, so why not just filter the very same table? // to do so, pass nil as the search results controller, // and tell the search controller not to insert a dimming view // keep copies of the original data self.originalSectionData = self.sectionData self.originalSectionNames = self.sectionNames let searcher = UISearchController(searchResultsController:nil) self.searcher = searcher searcher.dimsBackgroundDuringPresentation = false searcher.searchResultsUpdater = self searcher.delegate = self // put the search controller's search bar into the interface let b = searcher.searchBar b.sizeToFit() // crucial, trust me on this one b.autocapitalizationType = .None b.scopeButtonTitles = ["All", "S", "X"] // won't show in the table **b.delegate = self** self.tableView.tableHeaderView = b self.tableView.reloadData() //self.tableView.scrollToRowAtIndexPath( // NSIndexPath(forRow: 0, inSection: 0), // atScrollPosition:.Top, animated:false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.sectionNames.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.sectionData[section].count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let s = self.sectionData[indexPath.section][indexPath.row] cell.textLabel!.text = s // this part is not in the book, it's just for fun var stateName = s stateName = stateName.lowercaseString stateName = stateName.stringByReplacingOccurrencesOfString(" ", withString:"") stateName = "flag_\(stateName).gif" let im = UIImage(named: stateName) cell.imageView!.image = im return cell } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let h = tableView.dequeueReusableHeaderFooterViewWithIdentifier("Header") as UITableViewHeaderFooterView if h.tintColor != UIColor.redColor() { h.tintColor = UIColor.redColor() // invisible marker, tee-hee h.backgroundView = UIView() h.backgroundView!.backgroundColor = UIColor.blackColor() let lab = UILabel() lab.tag = 1 lab.font = UIFont(name:"Georgia-Bold", size:22) lab.textColor = UIColor.greenColor() lab.backgroundColor = UIColor.clearColor() h.contentView.addSubview(lab) let v = UIImageView() v.tag = 2 v.backgroundColor = UIColor.blackColor() v.image = UIImage(named:"us_flag_small.gif") h.contentView.addSubview(v) lab.setTranslatesAutoresizingMaskIntoConstraints(false) v.setTranslatesAutoresizingMaskIntoConstraints(false) h.contentView.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("H:|-5-[lab(25)]-10-[v(40)]", options:nil, metrics:nil, views:["v":v, "lab":lab])) h.contentView.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("V:|[v]|", options:nil, metrics:nil, views:["v":v])) h.contentView.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("V:|[lab]|", options:nil, metrics:nil, views:["lab":lab])) } let lab = h.contentView.viewWithTag(1) as UILabel lab.text = self.sectionNames[section] return h } // much nicer without section index during search override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { return self.searching ? nil : self.sectionNames } func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { println("In selectedScopeButtonIndexDidChange") updateSearchResultsForSearchController(searcher) } func updateSearchResultsForSearchController(searchController: UISearchController) { let sb = searchController.searchBar let target = sb.text println("target is: \(target)") if target == "" { self.sectionNames = self.originalSectionNames self.sectionData = self.originalSectionData self.tableView.reloadData() return } // we have a target string self.sectionData = self.originalSectionData.map { $0.filter { let options = NSStringCompareOptions.CaseInsensitiveSearch let found = $0.rangeOfString(target, options: options) return (found != nil) } }.filter {$0.count > 0} // is Swift cool or what? self.sectionNames = self.sectionData.map {prefix($0[0],1)} self.tableView.reloadData() } } A: The answer to this problem was to add: b.delegate = self into the viewDidLoad() section. I've updated the code above with the new line added.
{ "pile_set_name": "StackExchange" }
Q: Replace current process with invocation of subprocess? In python, is there a way to invoke a new process in, hand it the same context, such as standard IO streams, close the current process, and give control to the invoked process? This would effectively 'replace' the process. I have a program whose behavior I want to repeat. However, it uses a third-party library, and it seems that the only way that I can truly kill threads invoked by that library is to exit() my python process. Plus, it seems like it could help manage memory. A: You may be interested in os.execv() and friends: These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions.
{ "pile_set_name": "StackExchange" }
Q: Strange characters in two arduinos trying to connect with nRF24L01+ am trying to connect 2 nRF24L01+ modules that just arrived in my inbox with 2 arduinos. I am using the RF24 library with client in one and server on the other, pingpair, scanners. On ALL of them I am getting strange characters in Serial terminal display: Unfortunately, I am unable to proceed any further. A: That looks like the kind of garbage one gets when the serial settings are wrong (wrong baud rate, parity, stop bits, etc...). Do you have any reason to believe this is a problem with the nRF24L01+, and not the serial communications you are using to read the output?
{ "pile_set_name": "StackExchange" }
Q: keep getting error 'value of type ' ' has no member ' ' I've been stuck in this project for 2 days and I think I really need help. The program is only half-completed as I can't even get the layout to work. I have a var settings = setting() to link to the class setting(). Within class setting, I have varies vars and func. originally, I had the class put in a different swift file in the project, but because Swift keeps giving me the 'type has no member' error, I decided to put the class in the ContentView.swift. but even then, Swift seems to selectively dis-recognise my vars in the class instance and I can't exactly pinpoint why. e.g. the first line with error 'value of type 'setting' ha no member '$playerChoice'' says it cant find settings.playerChoice, whilst not listing the same error on the line underneath to look for settings.playerChoice in the String interpolation. I tried turning the program off and on, shift cmd K to re-compile preview a few times, it didn't work. Can someone please have a look for me what exactly went wrong? Thank you. my codes are as follow: import SwiftUI import Foundation class setting { var playerChoice : Int = 0 var questionCount : Int = 0 var pcRandom : Int = 0 var correctAnswer = 0 var question : String = "" var buttonArray = [Int]() var enteredAnswer = "" var gameRound : Int = 0 var scoreCount : Int = 0 var title2 = "" var alertTitle = "" var alertMessage = "" var alertEndGame = false func refreshGame() { pcRandom = Int.random(in: 1 ... 12) correctAnswer = playerChoice * pcRandom question = "\(playerChoice) times \(pcRandom) is??" } func compareAnswer() { let answerModified = enteredAnswer let answerModified2 = answerModified.trimmingCharacters(in: .whitespacesAndNewlines) if Int(answerModified2) == correctAnswer { scoreCount += 1 title2 = "RIGHT" } else { title2 = "WRONG" } if gameRound > questionCount { alertTitle = "Game Ended" alertMessage = "You got \(scoreCount) over \(questionCount)" alertEndGame = true } else { refreshGame() } gameRound += 1 gameRound += 1 } } var settings = setting() struct ContentView: View { var body: some View { VStack { Section (header: Text("Getting Your Settings Righttt").font(.title)) { Form { Stepper(value: settings.$playerChoice, in: 1...13, step: 1) { //value of type 'setting' ha no member '$playerChoice' if settings.playerChoice == 13 {Text("All")} else { Text("Multiplication table \(settings.playerChoice)") } } } Form { Text("Number of Questions?") Picker(selection: settings.$questionCount, label: Text("Number of Questions?")) { //value of type 'setting' has no member '$questionCount' ForEach (settings.questionCountArray, id: \.self) {Text("\($0)")} } ////value of type 'setting' ha no member '$questionCountArray' .pickerStyle(SegmentedPickerStyle()) } Spacer() Button("Tap to start") { settings.refreshGame } } Section (header: Text("Game Play").font(.title)){ Text(settings.question) TextField("Enter your answer", text: settings.$enteredAnswer, onCommit: settings.compareAnswer) //value of type 'setting' ha no member '$enteredAnswer' Text("Your score is currently \(settings.scoreCount)") Text("This is game round \(settings.gameRound) out of \(settings.questionCount)") } Spacer() } .alert(isPresented: settings.$alertEndGame) { Alert(title: Text("Game Ended"), message: Text("You reached score \(settings.scoreCount) out of \(settings.questionCount)"), dismissButton: .default(Text("Play Again"))) //game doesnt restart and refresh } } } A: Well I did not check logic, but below fixed code at least compilable, so hope it will be helpful import SwiftUI import Combine class Setting: ObservableObject { @Published var playerChoice : Int = 0 var questionCount : Int = 0 @Published var questionCountArray = [String]() var pcRandom : Int = 0 var correctAnswer = 0 var question : String = "" var buttonArray = [Int]() @Published var enteredAnswer = "" var gameRound : Int = 0 var scoreCount : Int = 0 var title2 = "" var alertTitle = "" var alertMessage = "" @Published var alertEndGame = false func refreshGame() { pcRandom = Int.random(in: 1 ... 12) correctAnswer = playerChoice * pcRandom question = "\(playerChoice) times \(pcRandom) is??" } func compareAnswer() { let answerModified = enteredAnswer let answerModified2 = answerModified.trimmingCharacters(in: .whitespacesAndNewlines) if Int(answerModified2) == correctAnswer { scoreCount += 1 title2 = "RIGHT" } else { title2 = "WRONG" } if gameRound > questionCount { alertTitle = "Game Ended" alertMessage = "You got \(scoreCount) over \(questionCount)" alertEndGame = true } else { refreshGame() } gameRound += 1 gameRound += 1 } } struct ASFContentView: View { @ObservedObject var settings = Setting() var body: some View { VStack { Section (header: Text("Getting Your Settings Righttt").font(.title)) { Form { Stepper(value: $settings.playerChoice, in: 1...13, step: 1) { //value of type 'setting' ha no member '$playerChoice' if settings.playerChoice == 13 {Text("All")} else { Text("Multiplication table \(settings.playerChoice)") } } } Form { Text("Number of Questions?") Picker(selection: $settings.questionCount, label: Text("Number of Questions?")) { //value of type 'setting' has no member '$questionCount' ForEach (settings.questionCountArray, id: \.self) {Text("\($0)")} } ////value of type 'setting' ha no member '$questionCountArray' .pickerStyle(SegmentedPickerStyle()) } Spacer() Button("Tap to start") { self.settings.refreshGame() } } Section (header: Text("Game Play").font(.title)){ Text(settings.question) TextField("Enter your answer", text: $settings.enteredAnswer, onCommit: settings.compareAnswer) //value of type 'setting' ha no member '$enteredAnswer' Text("Your score is currently \(settings.scoreCount)") Text("This is game round \(settings.gameRound) out of \(settings.questionCount)") } Spacer() } .alert(isPresented: $settings.alertEndGame) { Alert(title: Text("Game Ended"), message: Text("You reached score \(settings.scoreCount) out of \(settings.questionCount)"), dismissButton: .default(Text("Play Again"))) //game doesnt restart and refresh } } }
{ "pile_set_name": "StackExchange" }
Q: Create an instance of app for each screen I want my WinForms application to create an instance of itself for each screen and display on that screen. I have the following code: Main form: class MainForm { public MainForm() { string[] args = Environment.GetCommandLineArgs(); foreach (string arg in args) { if (arg == "TakeOverAllScreens") { TakeOverAllScreens(); } if (arg.StartsWith("Screen|")) { string[] s; s = arg.Split('|'); int xPos , yPos, screenNum ; int.TryParse(s[1], out xPos); int.TryParse(s[2], out yPos); int.TryParse(s[3], out screenNum); Screen[] sc; sc = Screen.AllScreens; this.Left = sc[screenNum].Bounds.Width; this.Top = sc[screenNum].Bounds.Height; this.StartPosition = FormStartPosition.Manual; } } InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { this.TopMost = true; this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; } } TakeOverAllScreens form: private void TakeOverAllScreens() { int i = 0; foreach (Screen s in Screen.AllScreens) { if (s != Screen.PrimaryScreen) { i++; Process.Start(Application.ExecutablePath, "Screen|" + s.Bounds.X + "|" + s.Bounds.Y+"|" + i); } } } My application does create a new instance for every screen, however it only displays on my main screen and does not display on the other screens. A: This looks suspect: int.TryParse(s[1], out xPos); int.TryParse(s[2], out yPos); int.TryParse(s[3], out screenNum); Screen[] sc; sc = Screen.AllScreens; this.Left = sc[screenNum].Bounds.Width; this.Top = sc[screenNum].Bounds.Height; You pass x and y values across on the command line, and then ignore them and use the width and height of the screen to set your x/y values. If all of the screens are the same resolution, and arranged horizontally or vertically, it's likely that all of these windows are positioned below (or to the right of) any visible portions of the screen. I also can't find any guarantee that Screen.AllScreens will always return the screens in the same order, so the screenNum value may be referencing a different screen. I'd also prefer to see this code appearing after the call to InitializeComponents rather than before, so you know that any designer set properties will be overridden by your code, rather than vice versa. So, my code is: public MainForm() { InitializeComponent(); string[] args = Environment.GetCommandLineArgs(); foreach (string arg in args) { if (arg == "TakeOverAllScreens") { TakeOverAllScreens(); } if (arg.StartsWith("Screen|")) { string[] s; s = arg.Split('|'); int xPos, yPos, screenNum; int.TryParse(s[1], out xPos); int.TryParse(s[2], out yPos); this.Left = xPos; this.Top = yPos; this.StartPosition = FormStartPosition.Manual; } } } And: private void TakeOverAllScreens() { foreach (Screen s in Screen.AllScreens) { if (s != Screen.PrimaryScreen) { Process.Start(Application.ExecutablePath, "Screen|" + s.Bounds.X + "|" + s.Bounds.Y); } } } Of course, the TryParse calls are pointless and can be replaced by Parse, if you're just going to ignore the return value.
{ "pile_set_name": "StackExchange" }
Q: fetch data in rows/column using php I want to make 4 columns in table. In code all the images are comes in single row and single column. But I want a single row containing 4 columns with 4 images (images fetching from database), then create another row and automatically add next 4 images & so on. I don't know how I do this can anyone please suggest me how I do this. <form name="form"> <select id="sorting" style="width:140px" onChange="optionCheck()"> <option id="s">---Sort By----</option> <option value="bydate">Sort By Date</option> <option value="bytopic">Sort By Topic</option> </select> </form> <br /> </div> <?php include 'connection.php'; ?> <div id="showByDefault"> <table style="width:60%"> <tr> <?php include 'connection.php'; ?> <div id="showByDefault"> <!--<table style="width:60%"><tr>--> <?php $sql1=mysqli_query($con,"select * from `insert-n-retrive-pdf` ORDER BY date DESC") or die(mysqli_error($con)); $i=0; echo "<table><tr>"; while($row=mysqli_fetch_array($sql1)) { if($i != 0 && $i%4 == 0) { echo '<tr></tr>'; } ?> <td style="padding:20px;"> <a href="<?php echo $row["path"]; ?>" target="_blank"><img src="<?php echo $row["thumbnails"]; ?>" /></a></td><?php echo '</tr>'; $i++; } ?></tr></table> </div> <div id="hideall"> <div id="topic1"> <?php include 'pdf-sort-by-topic.php'; ?> </div> <div id="topic"> <?php include 'pdf-sort-by-date.php'; ?> </div> </div> A: Try this one 100% working: Nice and easy. <?php $sql1=mysqli_query($con,"select * from `insert-n-retrive-pdf` ORDER BY date DESC") or die(mysqli_error($con)); $i = 0; echo "<tr>"; while($row=mysqli_fetch_array($sql1)) { if($i != 0 && $i%4 == 0) { echo "</tr><tr>"; } ?> <td style="padding:20px;"><a href="<?php echo $row["path"]; ?>" target="_blank"><img src="<?php echo $row["thumbnails"]; ?>" /></a></td> <?php $i++; } ?> Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Autobahn 0.7.3 - Proxied Websocket fails when a client is behind a http Proxy I'm proxying my test websocket using nginx from 9000 to 80 port and all my tests are ok until the client is behind a web proxy, then the handshake process fails, where can be the problem? Thanks in advance for your time. I'm getting these errors: Client: WebSocket connection to 'ws://myserver/ws/' failed: Error during WebSocket handshake: Unexpected response code: 502 autobahn.min.js:62 Server: 2014-01-10 19:51:22-0300 [PubSubServer1,19,127.0.0.1] Unhandled Error Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 84, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 69, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext return func(*args,**kw) --- <exception caught here> --- File "/usr/lib/python2.7/dist-packages/twisted/internet/posixbase.py", line 586, in _doReadOrWrite why = selectable.doRead() File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 199, in doRead rval = self.protocol.dataReceived(data) File "/usr/local/lib/python2.7/dist-packages/autobahn-0.7.3-py2.7.egg/autobahn/twisted/websocket.py", line 77, in dataReceived self._dataReceived(data) File "/usr/local/lib/python2.7/dist-packages/autobahn-0.7.3-py2.7.egg/autobahn/websocket/protocol.py", line 1270, in _dataReceived self.consumeData() File "/usr/local/lib/python2.7/dist-packages/autobahn-0.7.3-py2.7.egg/autobahn/websocket/protocol.py", line 1303, in consumeData self.processHandshake() File "/usr/local/lib/python2.7/dist-packages/autobahn-0.7.3-py2.7.egg/autobahn/websocket/protocol.py", line 2819, in processHandshake self.sendServerStatus() File "/usr/local/lib/python2.7/dist-packages/autobahn-0.7.3-py2.7.egg/autobahn/websocket/protocol.py", line 3276, in sendServerStatus self.sendHtml(html) File "/usr/local/lib/python2.7/dist-packages/autobahn-0.7.3-py2.7.egg/autobahn/websocket/protocol.py", line 3219, in sendHtml response += "Content-Length: %d\x0d\x0a" % len(raw) exceptions.NameError: global name 'raw' is not defined My Test server: import sys from twisted.python import log from twisted.internet import reactor from autobahn.twisted.websocket import listenWS from autobahn.wamp import WampServerFactory, \ WampServerProtocol class PubSubServer1(WampServerProtocol): def onSessionOpen(self): self.registerForPubSub("http://test.com/test") if __name__ == '__main__': log.startLogging(sys.stdout) factory = WampServerFactory("ws://localhost:9000", debugWamp = 'debug',externalPort=80) factory.protocol = PubSubServer1 factory.setProtocolOptions(allowHixie76 = True) listenWS(factory) #reactor.listenTCP(9000, factory) reactor.run() Command: ~$ python /home/my/wsbroker.py /usr/local/lib/python2.7/dist-packages/zope.interface-4.0.5-py2.7-linux-x86_64.egg/zope/__init__.py:3: UserWarning: Module twisted was already imported from /usr/lib/python2.7/dist-packages/twisted/__init__.pyc, but /usr/local/lib/python2.7/dist-packages/autobahn-0.7.3-py2.7.egg is being added to sys.path Edited: Debug info for a failed handshake (Client using a web proxy):http://pastebin.com/aN4ppA2e Debug info for a done handshake (Client without proxy):http://pastebin.com/5rXREY2q A: The traceback you see above is due to a bug introduced with Autobahn 0.7.0 and fixed in 0.7.4. However, the bug is likely not the cause of your actual problem: the traceback shows that Autobahn was trying to render a plain HTML server status page - and it does so, when the HTTP request it receives does not contain Upgrade to Websocket headers. You proxy might not (yet) be configured to properly forward WebSocket. Another thing you might run into: WebSocketServerFactory of Autobahn provides an option to set the externalPort. This should be set to the TCP/IP port of your proxy under which it accepts WebSocket connections. This is needed since Autobahn will (in compliance with the WebSocket specification) check if the WebSocket opening HTTP request host and port matches the one it runs on (and if it's different, bail out). The mentioned option allows you to override that behavior.
{ "pile_set_name": "StackExchange" }
Q: What do I need to do to get a JS3 environment (or at least couchdb) up and running? I'm primarily a front-end coder but I'm not a stranger to server-side programming or the command line. Regardless I've still got a lot to learn about setting up servers and whatnot so I was wondering if anyone could help me put together some steps for setting up CouchDB on (preferably) ubuntu. That's my main goal but I'd also like to get the 'JS3' environment going if possible. See this post for more info. The things I struggle with most are knowing what packages I need to install and how to get it so I can work in my browser on localhost. Thanks for any pointers you can give me. A: Packages are very dependant on the Operating System Flavor you use. On Freebsd you could go with cd /usr/ports/www/helma ; make install clean cd /usr/ports/databases/couchdb ; make install clean and you have all the relevant software on your server. Then you need jQuery beeing hosted somewhere. Helma's Jetty Webserver can handle that for you. For Ubuntu I read it now comes with a couchdb package sou you can just do sudo apt-get install couchdb
{ "pile_set_name": "StackExchange" }
Q: OpenCV Video capture using keyboard to start/stop I have a running script capable of starting/stopping a video stream using 2 different keys; Program runs and shows the live stream. When ESC is hit, the program exits. When SPACE is hit, the video stream is captured. However, when a video is captured it stores all the stream from the beginning of script execution. import cv2 import numpy as np capture = cv2.VideoCapture(1) codec = cv2.VideoWriter_fourcc(*'XVID') output = cv2.VideoWriter('CAPTURE.avi', codec, 30, (640, 480)) while True: ret, frame_temp = capture.read() cv2.imshow('FRAME', frame_temp) key=cv2.waitKey(1) if key%256 == 27: break elif key%256 == 32: output.write(frame_temp) capture.release() output.release() cv2.destroyAllWindows() So, instead when the program runs I would like; Program runs and shows the live stream. Begin recording the stream when SPACE is hit and stop the recording when SPACE is hit once more. Any suggestions would be much appreciated. A: You need an extra variable to figure out if you are recording. I made a variable called recording_flag import cv2 import numpy as np capture = cv2.VideoCapture(1) codec = cv2.VideoWriter_fourcc(*'XVID') recording_flag = False while True: ret, frame_temp = capture.read() cv2.imshow('FRAME', frame_temp) key=cv2.waitKey(1) if key%256 == 27: break elif key%256 == 32: if recording_flag == False: # we are transitioning from not recording to recording output = cv2.VideoWriter('CAPTURE.avi', codec, 30, (640, 480)) recording_flag = True else: # transitioning from recording to not recording recording_flag = False if recording_flag: output.write(frame_temp) capture.release() output.release() cv2.destroyAllWindows()
{ "pile_set_name": "StackExchange" }
Q: How do I structure my project in a Views folder I want to structure my project in the following way: I want to put all my HTML files in a folder called views. partials hold the files head.html, footer.html and header.html. Those are three short HTML snippets that gets included in my Views; So that when I change something in the header, I won't have to change it in individually in each view. But just once in the partial. media holds my images. css and js respectively my styling and Javascript. This is the structure I want to have, but I encounter the following problems: How to avoid having http://example.com/views/index.php? I just want http://example.com/index.php. I tried this by using htaccess MOD_REWRITE; but this also messed up my includes. How do I include my CSS and Javascript from the head partial? So, I have a head-partial that looks like this: <link rel="stylesheet" type="text/css" href="css/general.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="js/general.js" defer></script> This gets put into all views by using PHP's file_get_contents(). However, I need to statically link these two files somehow. How would I do that? My partials get loaded like this: <?php echo file_get_contents("partials/head.html"); ?> Also, how would I do that statically? I tried it by using $_SERVER['DOCUMENT_ROOT'] but this returns /Users/myName/... which results in my includes failing. The ideal solution would be if I could just link everything by starting from my folder called vereniging like href="/css/..." src="/media/.... Edit: This is my current htaccess content: RewriteEngine On # browser requests PHP RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php RewriteRule ^/?(.*)\.php$ /$1 [L,R=301] # check to see if the request is for a PHP file: RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^/?(.*)$ /$1.php A: The first problem is solved with the following .htaccess: RewriteCond %{REQUEST_URI} !^/(views|css|js|media|partials|php) RewriteRule (.*) /views/$1 The second and third problem is solved the following way: <base href="http://example.com/" target="_self">
{ "pile_set_name": "StackExchange" }
Q: Why does this query return no results? Given these definitions of a datascript db, (def schema {:tag/name { :db/unique :db.unique/identity } :item/tag {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many} :outfit/item {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many}} ) (defonce conn (d/create-conn schema)) (defn new-entity! [conn attrs] (let [entity (merge attrs {:db/id -1}) txn-result (d/transact! conn [entity]) temp-ids (:tempids txn-result)] (temp-ids -1))) (defonce init (let [tag1 (new-entity! conn {:tag/name "tag1"}) item1 (new-entity! conn {:item/tag tag1}) outfit1 (new-entity! conn {:outfit/item item1})] :ok)) If I run this devcard, I don't get any results: (defcard find-by-tag-param "find items by tag" (d/q '[ :find ?item :in ? ?tagname :where [ ?tag :tag/name ?tagname ] [ ?item :item/tag ?tag ]] @conn "tag1")) Why does this query return no results? A: For starters, your in clause should be :in $ ?tagname; The binding you have in there leaves you with no default database, meaning that nothing will match your query clauses. The $ symbol is a special symbol which gets used as the default database in the :where forms. You can use non-default databases by prefixing your :where clauses with the name-symbol of the alternate db (e.g. :in ?alt-db :where [?alt-db ?tag :tag/name ?tagname] ...). I haven't worked with dev cards, so it's possible there is something else needed to get this working, but fixing your query is the first step.
{ "pile_set_name": "StackExchange" }
Q: How do I invoke the default complexity function? Documentation on ComplexityFunction says: With the default setting ComplexityFunction->Automatic, forms are ranked primarily according to their LeafCount, with corrections to treat integers with more digits as more complex. I need to use this default function on its own, not in Simplify or FullSimplify. Can I invoke it from my code? If no, could you give me a custom function that behaves as close to the default function as possible? Thanks! A: The code for the default ComplexityFunction was posted on MathSource a number of years ago by Adam Strzebonski (of Wolfram Research). You will see reference to the original reply from Adam referenced in a MathGroup reply from Andrzej Kozlowski dated 12 Jan 2010 with the subject: "[mg106386] Re : Radicals simplify". I mention all that because I can't get the hyperlink to work (: The code Adam provided is there as well. The implementation from Adam used nested If statements. I can't resist the urge to use Which instead. I give my version below. I don't know for sure that the same function is used, but I have seen no reports indicating that it has changed. SimplifyCount[p_]:=With[{hd=Head[p]}, Which[ hd===Symbol,1, hd===Integer,If[p===0,1,Floor[N[Log[2,Abs[p]]/Log[2,10]]]+If[Positive[p],1,2]], hd===Rational,SimplifyCount[Numerator[p]]+SimplifyCount[Denominator[p]]+1, hd===Complex,SimplifyCount[Re[p]]+SimplifyCount[Im[p]]+1, NumberQ[p],2, True,SimplifyCount[Head[p]]+If[Length[p]==0,0,Plus@@(SimplifyCount/@(List@@p))] ] ] A: This function lives in the system as Simplify`SimplifyCount. A: Based on Vladimirs solution I wanted to post a faster alternative to SimplifyCount which produces the same results as SimplifyCount, but is a factor 3 faster. This can be very significant in case of complicated functions, it is however still significantly slower then Automatic. myNumberComplexity[x_Integer] := If[Positive[x], IntegerLength[x] - 1, IntegerLength[x]] myNumberComplexity[x_Real] := 1; myNumberComplexity[x_Rational] := myNumberComplexity[Numerator[x]] + myNumberComplexity[Denominator[x]] myNumberComplexity[x_Complex] := myNumberComplexity[Re[x]] + myNumberComplexity[Im[x]] myNumberComplexity[x_] := 0; myComplexityFunctionNC[x_] := LeafCount[x] + Plus @@ myNumberComplexity /@ Level[x, {-1}] It is also possible to increase the speed of SimplifyCount by a factor of two by replacing the sum of the two Ifs after hd===Integer with just this If[Positive[p], IntegerLength[p], IntegerLength[p] + 1]. I must however say that I have my doubts that SimplifyCount is still exactly what is being done in (Full-)Simplify. I have an example were SimplifyCount (or my alternateive) does not produce the same as Automatic. Here the example (which might take a full day (!) with SimplifyCount): $Assumptions = {{a, b, m, s, q, k, x, y, x0, x1, x2, x3, X} \[Element] Reals , s > 0, b > 0, a > 0}; kuskgaus0b[a_, b_, m_, s_] := ProbabilityDistribution[(b*Sqrt[Gamma[3/b]/Gamma[b^(-1)]]* Piecewise[{{Gamma[ b^(-1), ((a*(-\[FormalX] + m)* Sqrt[Gamma[3/b]/Gamma[b^(-1)]])/s)^b]/(2* Gamma[b^(-1)]), a*(\[FormalX] - m) <= 0}}, 1 - Gamma[ b^(-1), ((a*(\[FormalX] - m)*Sqrt[Gamma[3/b]/Gamma[b^(-1)]])/ s)^b]/(2* Gamma[b^(-1)])])/(E^(((\[FormalX] - m)^2*Gamma[3/b])/(s^2* Gamma[b^(-1)]))^(b/2)*s* Gamma[b^(-1)]), {\[FormalX], -Infinity, Infinity}] D[PDF[kuskgaus0b[a, b, 0, 1], x]*x, b] /. b -> 2; FullSimplify[%, ComplexityFunction -> Automatic] // AbsoluteTiming And here the result with Automatic: Piecewise[ {{(x*(Sqrt[2]*a*x*(-3 + EulerGamma + Log[2] + 2*Log[a*x]) + E^((a^2*x^2)/2)*(Sqrt[Pi]*(-2*(1 + x^2*(-3 + EulerGamma + Log[2]) + 2*x^2*Log[x]) + Erfc[(a*x)/Sqrt[2]]*(1 + EulerGamma*(1 + x^2) + x^2*(-3 + Log[2]) + Log[2] + 2*x^2*Log[x] + 2*Log[a*x])) + MeijerG[{{}, {1, 1}}, {{0, 0, 1/2}, {}}, (a^2*x^2)/2])))/(4*Sqrt[2]*E^(((1 + a^2)*x^2)/2)*Pi), x > 0}}, (x*(a*x*(-6 + 2*EulerGamma + Log[4*a^4*x^4]) - Sqrt[2]*E^((a^2*x^2)/2)*(Sqrt[Pi]*(1 + Erf[(a*x)/Sqrt[2]])*(1 + EulerGamma + (-3 + EulerGamma)*x^2 + x^2*Log[2*x^2] + Log[2*a^2*x^2]) + MeijerG[{{}, {1, 1}}, {{0, 0, 1/2}, {}}, (a^2*x^2)/2])))/(8*E^(((1 + a^2)*x^2)/2)*Pi)] And now with SimplifyCount: Piecewise[{{ComplexInfinity, x == 0}, {(x*(Sqrt[2]*a*x*(-3 + EulerGamma + Log[2] + 2*Log[a*x]) - E^((a^2*x^2)/2)*(-2*Sqrt[2]*a*x*HypergeometricPFQ[{1/2, 1/2}, {3/2, 3/2}, -(a^2*x^2)/2] + Sqrt[Pi]*x^2*(1 + Erf[(a*x)/Sqrt[2]])*(-3 + EulerGamma + Log[2] + 2*Log[x]) + Sqrt[Pi]*(1 + Erf[(a*x)/Sqrt[2]]*(1 + EulerGamma + Log[2] + 2*Log[a*x])))))/ (4*Sqrt[2]*E^(((1 + a^2)*x^2)/2)*Pi), x > 0}}, (x*(E^((a^2*x^2)/2)*(4*a*x*HypergeometricPFQ[{1/2, 1/2}, {3/2, 3/2}, -(a^2*x^2)/2] - Sqrt[2*Pi]*(1 + (-3 + EulerGamma)*x^2 + x^2*Log[2*x^2] + Erf[(a*x)/Sqrt[2]]*(1 + EulerGamma + (-3 + EulerGamma)*x^2 + x^2*Log[2*x^2] + Log[2*a^2*x^2]))) + a*x*(-6 + 2*EulerGamma + Log[4*a^4*x^4])))/ (8*E^(((1 + a^2)*x^2)/2)*Pi)] The differences are the additional Infinity at 0, and the change from MeijerG to HypergeometricPFQ.
{ "pile_set_name": "StackExchange" }
Q: The physics of sound boards As a kid I was bemused at why soundboards worked. A small sound could be demonstrably amplified simply by attaching the source to a surface that is rigid and not too thick. How could the volume increase so much given that there was no extra energy added? As an adult I kind-of-think I know, but there are still many nagging questions. I assume it has to do with the waves propogating from a vibrating object actually being a compression on one side of the object just as they are a decompression on the other side, and something about that lack of coherence limits the volume. Exactly why remains a mystery to me. Is separating the pocket of compression and decompression so that the boundary along which they meet is quite small part of the issue? My question is what are the physics that make a soundboard work? Interesting specifics that would be nice-to-knows would be why does a hollow one (like a violin) work better than a solid one (imagine a filled in violin)? How important are the harmonics of the solid? But the real question is what are the physics that make a soundboard work? P.S. I am a mathematician, so feel free to wax very mathematical if it is necessary to give a good explanation. A: You are right that a soundboard adds no energy to the system. However, it does allow the existing energy to be converted to sound better. The greater area of the soundboard causes more air to be pushed than the string alone can, even though the displacement amplitude of the soundboard is less than the string. This exactly the same reason speakers have cones. Only a small ring at the center of the speaker is actually driven. That by itself makes little sound because it is so small and therefore doesn't move much air. By causing it to move the speaker cone, which in turn moves much more air, you get a much louder sound. Another way to think of this is as a impedance match. The string vibrates at high amplitude, but the air presents a very high impedance to it, so little energy is transferred. The soundboard puts a little more drag on the string, but this lower impedance allows more of the energy from the vibrating string to be transferred to the air. Yes, the thickness of the soundboard definitely matters. Ideally you want something with low stiffness and mass so that energy isn't dissipated in the soundboard itself, but rather more of it is tranferred to the air. This is why speaker cones are made of paper or other light and thin material. The wood of a violin has other functions it must perform, and was also something that needed to be manufacturable by hand 100s of years ago. The shape, type of wood, thickness, and even the glue used in violins are all part of a black art with much accumulated lore about how to get the "best" sound. In this case "best" isn't the loudest or most efficient coupling to the air, but what has become expected of a violin over the centuries. Air cavities that resonate as sub-harmonics also have a lot to do with it.
{ "pile_set_name": "StackExchange" }
Q: Show selected element in Telerik MVC TreeView this is the code where i create tree in telerik mvc. Now i want to create popup which shows the slected node name. Html.Telerik().TreeView() .Name("ZebTree") .ExpandAll(true) .ClientEvents(events => events.OnSelect("TreeView_onSelect")) .BindTo(Model , map => { map.For<TreeViewBind.Models.Category>(bind => bind.ItemDataBound((item, category) => { item.Text = category.CategoryName; }).Children(category => category.Products)); map.For<TreeViewBind.Models.Product>(bind => bind.ItemDataBound((item, product) => { item.Text = product.ProductName;})); } ) Here is the javascript code. function TreeView_onSelect(e) { var treeview = $(this).data('tTreeView'); alert("You select the node " + ...); } A: to get a node's text: function TreeView_onSelect(e) { var treeview = $(this).data('tTreeView'); var nodeText = treeview.getItemText(e.item); alert("You select the node: " + nodeText); } Regards
{ "pile_set_name": "StackExchange" }
Q: How to hide an element by Id with mutation observer I've read https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/ but still not sure how to configure to achieve my objective. There's an element on a page being generated by a code generator (so I cannot prevent the bevahiour). The element has an id "myid" and I just need to hide it once it displays in the browser. My challenge is how to configure the observer such that the code fires when the element is displayed. I've inserted my questions as comments where I think I need the help here but kindly guide me if I've got it all wrong: var target = document.querySelector('#myid'); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { // how do I detect when the element is now on the page so that the next statement makes sense? document.getElementById("myid").style.visibility = "hidden"; }); }); // what change do I need to make here? var config = { attributes: true, childList: true, characterData: true }; observer.observe(target, config); observer.disconnect(); A: Why don't you simply use CSS? That way you don't have to worry about when the item is created at all, you won't need a script do begin with. #myid { visibility: hidden; /*!important; if necessary*/ }
{ "pile_set_name": "StackExchange" }
Q: How to Change input language of textbox in html? I want to change language of textbox to marathi in html file My code is as follows but it not working <html lang="mr" xml:lang="en"> <head></head> <body> <textarea style="height:200px;width:200px;font-family:Mangal"> </textarea> </body> </html> A: I hope you meant Font and not language... first of all, give that textarea an id and a class, for example <textarea id="txtArea" class="textarea" style="height:200px;width:200px;font-family:Mangal"> </textarea> then let's get ride of that bad inline style coding and have either an external stylesheet or inside the <head> this: <style> .textarea { height:200px; width:200px; font-family:Mangal } </style> so now it would be clean as <textarea id="txtArea" class="textarea"> </textarea> to change the font, just do: from javascript txtArea.style.fontFamily = "Arial"; from stylesheet .textarea { height:200px; width:200px; font-family:'Arial' } or, if you can't ride the inline styles, add the id and call the javascript. I don't recall if the font-family:'Arial' !important gets prioritize from an inline style, but you can also try that.
{ "pile_set_name": "StackExchange" }
Q: Is there no way available for retrieving posts using a search query/keyword from facebook? I'm trying to use GraphAPI for retrieving various posts using a search query/keyword from Facebook. This is what I tried: new GraphRequest( AccessToken.getCurrentAccessToken(), "/search?q=solareclipse&type=post", null, HttpMethod.GET, new GraphRequest.Callback() { public void onCompleted(GraphResponse response) { /* handle the result */ } } ).executeAsync(); but I got this error: { "error": { "message": "(#11) This method is deprecated", "type": "OAuthException", "code": 11, "fbtrace_id": "AZD1YH0em2M" } } Has Facebook completely taken back the privilege of searching through it's public posts or is there some other way available? A: Since Graph API v2.0 it is no longer possible to search through public posts. There is a public feed API (https://developers.facebook.com/docs/public_feed), however the access is limited to certain media companies only.
{ "pile_set_name": "StackExchange" }
Q: Prime Spectrum of A Ring I was given the definition that the spectrum of a ring R, denoted Spec R, is the set of the prime ideals of R. Then for an arbitrary subset $S \subseteq R$, then $V(S) = \{P \in SpecR | S \subseteq R \}$. I am confused by what a set of ideal would mean. Here it seems that this is a variety--but that does not make sense to me. Could someone please explain? Thank you! A: The spectrum originated in algebraic geometry. Suppose $f(X_1,X_2,\dots,X_n)$ is an irreducible polynomial in $n$ variables over the field $k$ and let $I$ be the principal ideal generated by $f$. Then the ring $R=k[X_1,X_2,\dots,X_n]/I$ “encodes” the hypersurface defined by the polynomial. A point $(a_1,a_2,\dots,a_n)\in k^n$ belonging to this hypersurface corresponds to the maximal ideal $$ \frac{(X_1-a_1,X_2-a_2,\dots,X_n-a_n)}{I} $$ whereas a prime ideal in $R$ corresponds to an irreducible subvariety of the hypersurface. So the spectrum not only encodes points of the variety, but also its irreducible subvarieties. The arbitrary subset $S\subseteq R$ can be substituted by the ideal $(S)$ generated by $S$ and $V(S)=V((S))$. By Hilbert's basis theorem $(S)$ is generated by a finite number of polynomials, so it corresponds to a non necessarily irreducible subvariety and so $V((S))$ is the set of irreducible subvarieties contained in this subvariety. Of course this can be generalized starting from any irreducible variety, not only a hypersurface, in exactly the same fashion. It was Grothendieck's intuition, surely influenced by earlier studies by Zariski, that this encoding could be fruitful, connecting algebraic geometry to topology (because the space of irreducible subvarieties or, equivalently, of prime ideals can be given a topology using the sets $V(S)$ as closed sets) and indeed it has been, leading to the theory of schemes.
{ "pile_set_name": "StackExchange" }
Q: Cannot run heroku pg:info from rake task I am writing a rake task to deploy on heroku. The task has only one step: sh %{ heroku pg:info --app myapp} and it fails with heroku pg:info Unknown command. Run 'heroku help' for usage information. rake aborted! Command failed with status (1): [heroku pg:info --app...] The funny thing is that any other heroku command seems to work. It is just the "heroku pg" ones that do not work. Ideas? Thanks in advance for any help A: The problem was due to rack using heroku gem version 1.6.3 which does not support the pg commands. After I have updated my Gemfile to update heroku to 1.18.3 everything started to work.
{ "pile_set_name": "StackExchange" }
Q: PieChart using Charts on swift. Need to remove the values of the elements In the black circles data that i wont to hide. I wonna to get simple green and red chat w\o text in elements. I checked all the methods of PieChartView and wont find method to hide this data. Sims it integrated to elements... Inplementation code: import Charts class ViewController: UIViewController { @IBOutlet weak var pieChart: PieChartView! override func viewDidLoad() { super.viewDidLoad() // pieChart.chartAnimator // pieChart.drawCenterTextEnabled = false // pieChart.drawHoleEnabled = false let months = ["", ""] let unitsSold = [60.0, 40.0] setChart(dataPoints: months, values: unitsSold) } func setChart(dataPoints: [String], values: [Double]) { var dataEntries: [ChartDataEntry] = [] // let da = ChartDataEntry( let dataEntry1 = ChartDataEntry(x: Double(0.0), y: 60.0) let dataEntry2 = ChartDataEntry(x: Double(0.0), y: 40.0) dataEntries.append(dataEntry1) dataEntries.append(dataEntry2) print(dataEntries[0].data as Any) let pieChartDataSet = PieChartDataSet(entries: dataEntries, label: nil) let pieChartData = PieChartData(dataSet: pieChartDataSet) pieChart.data = pieChartData let colors: [UIColor] = [UIColor(cgColor: UIColor.red.cgColor), UIColor(cgColor: UIColor.green.cgColor)] pieChartDataSet.colors = colors } A: You need to set the text color as clear, it will work fine. Check out following change in your current code let pieChartData = PieChartData(dataSet: pieChartDataSet) pieChartData.setValueTextColor(NSUIColor.clear) pieChart.data = pieChartData
{ "pile_set_name": "StackExchange" }
Q: Collision detection via overlap() not working in phaser.io Please note that I've created the following code entirely using Phaser.io. So I've created an enemy group and also a weapon group (using the inbuilt game.add.weapon()). I check for overlap between these two groups but for some reason the hitEnemy() function is never fired. I believe this has something to do with using the inbuilt weapon group, but I can't figure out what exactly it is. var playState = { preload: function () { game.load.image('player', 'assets/player.png'); game.load.image('enemy', 'assets/enemy.png'); game.load.image('floor', 'assets/floor.png'); game.load.image('bullet', 'assets/bullet.png'); }, create: function () { game.stage.backgroundColor = '#000000'; game.physics.startSystem(Phaser.Physics.ARCADE); game.renderer.renderSession.roundPixels = true; this.cursors = game.input.keyboard.createCursorKeys(); this.fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); this.createBullets(); this.createEnemies(game.width/2, 120, 'enemy'); }, update: function () { game.physics.arcade.collide(this.player, this.floor); game.physics.arcade.overlap(this.weapon, this.enemies, this.hitEnemy, null, this); }, createBullets: function () { this.weapon = game.add.weapon(30, 'bullet'); this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; this.weapon.bulletSpeed = 850; this.weapon.fireRate = 100; this.weapon.trackSprite(this.player); }, createEnemies: function (x,y ,size) { this.enemies = game.add.group(); this.enemies.enableBody = true; this.enemies.physicsBodyType = Phaser.Physics.ARCADE; var asteroid = this.enemies.create(x, y, size); asteroid.anchor.setTo(0.5,0.5); asteroid.name = "enemy1"; asteroid.body.immovable; }, hitEnemy: function (player, enemy) { this.enemy.kill(); console.log("Hit"); }, }; A: Found the solution. Instead of checking overlap with this.enemies and this.weapon. I was supposed to check collision with this.enemies and this.weapon.bullets
{ "pile_set_name": "StackExchange" }
Q: How to handle Google Map v2 Marker's Long click event in Android? I'm developing an android application in which I've used Google Map v2 API. I've placed one marker on the map, now I want to set its "OnLongClickListener". As I can see from Eclipse there are only two listeners available for marker: googleMap.setOnMarkerClickListener(listener); googleMap.setOnMarkerDragListener(listener); Could anybody show me any easy way to handle marker's LongClick event?? I've gone through two solutions here: Setting a LongClickListener on a map Marker How to detect long click on GoogleMap marker A: as both of the solutions you posted have shown - there is no long click event on markers in the maps api. the first link you posted had a solution that might be able to suit your needs but isn't perfect by any means i would suggest going here to the gmaps issues page and browsing through the feature requests and adding one if it does not exist
{ "pile_set_name": "StackExchange" }
Q: Time required for change the momentum of a gas molecule in a cube In a cube with side length L, consider a gas molecule with x-component of velocity being $C_x$. The question arises while dealing to calculate rate at which molecule transfers momentum to the wall. Let $m$ be the mass of gas molecule. While the change in momentum after the collision with the wall is $2mC_x$, my question remains for the time that is considered to calculate the rate. According to the source of Cambridge International A levels Physics course book, the time used to calculate rate is time between collisions but according to me the rate of change in momentum should consider the time the molecule is in contact with the wall, though negligibly small. How can the time taken for successive collisions be used? A: When we measure pressure we are measuring it on timescales that are much longer than the collision frequency of the gas molecules. So we aren't that concerned with the details of the force exerted on an individual molecule in an individual collision. We want the average force over multiple collisions. This average force is simply the total momentum change divided by time. So if for example there are $N$ collisions in one second then the total momentum change per second is just $2Nmv$, and that gives our average force. We don't need to know exactly what goes on during any individual collision to do this calculation.
{ "pile_set_name": "StackExchange" }
Q: Organising REST API web service build using Python Eve I am trying to build a REST API web service using Python Eve. I have experience in using Lithium (PHP framework) and Ruby on Rails but I am struggling to figure out the proper folder structure to use with Python Eve. Any suggestion on where to put my models and controllers (mostly pre / post hooks). A: Have you looked at the Eve demo source code? Should be enough to get you started. Hooks can then be added to the run.py script, see the documentation. A more complex application (not so much at this point in time) is Adam, still a work in progress though.
{ "pile_set_name": "StackExchange" }
Q: Vue.js - v-for indicies mixed up? What do I have: components structure <Games> // using v-for - iterate all games --<Game> // using v-for - iterate all players ----<Player 1> ------<DeleteWithConfirmation> ----<Player 2> ------<DeleteWithConfirmation> ----<Player 3> ------<DeleteWithConfirmation> ----... <DeleteWithConfirmation> implementation: two clicks are required for deleting game property. <template> <div> <button @click="incrementDelete" v-html="deleteButtonHTML"></button> <button v-if="deleteCounter === 1" @click="stopDeleting"> <i class="undo icon"></i> </button> </div> </template> <script> export default { name: 'DeleteWithConfirmation', data() { return { deleteCounter: 0 } }, computed: { deleteButtonHTML: function () { if (this.deleteCounter === 0) return '<i class="trash icon"></i>' else return 'Are you sure?' } }, methods: { incrementDelete() { this.deleteCounter++ if (this.deleteCounter === 2) { //tell parent component that deleting is confirmed. //Parent call AJAX than. this.$emit('deletingConfirmed') this.stopDeleting() } else if (this.deleteCounter > 2) this.stopDeleting() }, stopDeleting() { Object.assign(this.$data, this.$options.data()) } } } </script> My problem: seems like indicies are mixed up: Before deleting 4th player was on "Are you sure state" (deleteCounter === 1), but after deleting it went to initial state (deleteCounter === 0). Seems like 3rd component state haven't updated its deleteCounter, but its data (player's name was updated anyway). After successfull deleting <Games> component data is fetched again. A: You don't need a delete counter for achieving this. On the contrary, it makes it hard to understand your code. Just use a boolean like this: <template> <div> <button @click="clickButton" <template v-if="confirmation"> <i class="trash icon"></i> </template> <template v-else> Are you sure? </template> </button> <button v-if="confirmation" @click="confirmation = false"> <i class="undo icon"></i> </button> </div> </template> <script> export default { name: 'DeleteWithConfirmation', data() { return { confirmation: false } }, methods: { clickButton() { if (!this.confirmation) { this.confirmation = true; } else { this.$emit('deleting-confirmed'); } } } </script> The parent could then be looking e.g. like this: <div class="row" v-if="showButton"> [...] <delete-with-confirmation @deleting-confirmed="showButton = false"> </div>
{ "pile_set_name": "StackExchange" }
Q: Two lists - get common fields? I have two List<object>. A field in the objects is party_id. Is there a way, using LINQ, to get a list back of only the common party_ids? So, maybe join the lists on Party ID and then return the ones with matches? In SQL, I guess I'd do: SELECT DISTINCT party_id FROM table1 INNER JOIN table2 on table1.party_id = table2.party_id Thanks. A: You can try this: table1.Select(r => r.party_id).Intersect(table2.Select(r => r.party_id)) A: How about var results = list1.Where(f => list2.Exists(s => f.party_id == s.party_id)) .Select(x => x.party_id); A: Without pulling out Reflector and verifying the implementations of the aforementioned workable solutions, I think it would be most efficient to use Join(...): var party_on_dude = from table1 join table2 on table1.party_id equals table2.party_id select table1.party_id;
{ "pile_set_name": "StackExchange" }
Q: Add taxonomy term image to a view Can anybody tell me how I add an image field of a taxonomy term to a view of nodes with reference to the vocabolary? I have a content type called "Product" and one called "Distributors". And then a have a vocabolary called "Product categories", where a term has two fields: a title field and an image field. I am using the NAT module to add a term to the "Product categories" vocabulary every time a product is created, so that the title and image of the product becomes a new term with the value of these two fields. When I create a distributor I am using these terms as term reference to which products the distributor sells. The problem I am facing now is that I want a view of distributors, and I cant seem to get the image of the terms associated with each distributor-node. I can only get the titles. I assume that I might have to make some kind of relasionship, but I cant seem to figure it out. I hope someone can help me. A: From what I understand you have a distributor node that has a term reference (multi value) to Product categories. In your view that lists the distributors you must add a relationship: Content: Taxonomy terms on node. When presented with a choice of vocabularies you select 'Product Category'. Then you add two fields: Taxonomy term: Name, and Taxonomy term: Image (your image field might be named slightly differently). For both of these fields, during the multi form process of adding them, you will be presented with a form that says for instance: Configure field: Taxonomy term: Name. Here you must select the Relationship as term. This will create one row for each taxonomy term on the node, which might not be what you want. You can now group it under the content:title of the distributor. There are two other ways that I can see by which you can group all of the images from one distributor under a single distributor. First method: Create a new field: global custom text. Make sure that it is below all of the distributor fields. Move the image field below it. In this global text field add all of the distributor fields (using html and replacement patterns) except for the image field. For instance, you might have something like this: <div>[title]</div> <div>[address]</div> <div>[phone]</div> Now go and hide all of the fields, the global text field as well, except for the image field. Then in your grouping, select this new global text field as the field to group on. Now apply some CSS to make it look good. And if you want to get rid of that pesky h3 tag around the grouping header, then override the theme view template. Click on Theme: Information in views and select one of the Style output templates. Second method: Install the Views Field View module. This allows you to create a field in a view that will be the result of another view. Create a new view that takes as contextual filter the nid of the distributor, and then as before add a relationship to the terms etc. so that this view only outputs the pictures in groups. In your original view remove the relationship to the terms, and insert a field to the new view, and make sure to pass it the parameter of the nid.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to " Select N times"? Unfortunately, the data model for my database must change so I am looking for the most painless way to migrate my data. How it is at this moment: create table cargo{ id serial primary key, person_id int, weight_id float, reps_id int ); //skipping constraints declaration However it happened that person is able to lift different values of cargo each turn What I am going to do is modify cargo table and add turn table like this: create table cargo{ id serial primary key, person_id int, ); //skipping constraints declaration create table turn{ id serial primary key, cargo_id int, weight float ); normally I could migrate existing data like this: insert into turn (cargo_id, weight) select id, weight from cargo; but this way I am losing all of reps where reps > 1 Is it possible to create insert into select, where select would be called as many times as reps count without making script? A: Try: -- insert into turn (cargo_id, weight) SELECT c.id, c.weight_id FROM cargo c, LATERAL ( SELECT * FROM generate_series(1, greatest( c.reps_id, 1 ) ) ) xx; Demo: http://sqlfiddle.com/#!15/4923e/1
{ "pile_set_name": "StackExchange" }
Q: How to force my csv values to get in one column? I'm using ngx-papaparse to convert an array into a CSV file. But when I download my CSV file and open it with Excel my values are not in the right columns. Here is my function: downloadFile() { const tableKpi = []; for (let i = 0; i < this.kpi.indicators.length; i++) { tableKpi.push(this.kpi.indicators[i].values); } const blob = new Blob([this.papa.unparse(tableKpi)], {type: 'text/csv' }); saveAs(blob, 'myFile.csv'); } How it looks What I expected A: Solved it, the format of the CSV file depends on your Excel language. Not every languages will parse the file the same way. So I just needed to change my Excel language to English, hope it helps.
{ "pile_set_name": "StackExchange" }
Q: How can I add custom headers to an ElementAPI response? I need to add the a custom header to the ElementAPI endpoints I setup but I want to avoid editing the source of the plugin. What is the best way to go about this? The ElementAPI plugin returns some default headers by using: JsonHelper::sendJsonHeaders() To quickly achieve what I needed I added the following to the ElementApiControllor.php: HeaderHelper::setHeader(['Surrogate-Control: max-age=300']) This works for now but I'd love to learn how to extend existing plugins that don't have any documented hooks with my own if it is possible. A: You can do this by assigning your endpoint(s) to a function: return [ 'endpoints' => [ 'my-endpoint' => function() { HeaderHelper::setHeader(['Surrogate-Control: max-age=300']); return [ // ... ]; } ] ]; UPDATE Alternatively as of v1.2, you can do it from a separate plugin using the onBeforeSendData event: public function init() { craft()->on('elementApi.onBeforeSendData', function(Event $event) { HeaderHelper::setHeader(['Surrogate-Control: max-age=300']); }); } A: In case anyone finds this in a Google search, this is how you'd do it in Craft 3, if, say, you wanted to add an Expires header: $response = Craft::$app->getResponse(); $response->headers->set('Expires', gmdate('D, d M Y H:i:s \G\M\T', strtotime("+1 month"))); Yii2 Responses
{ "pile_set_name": "StackExchange" }
Q: Angular 2 testing a component with fake dependencies I m trying to test an Angular 2 component with fake dependencies. In fact, I m building a simple TODO app with Ng2 and Redux, and in one of my component, I have an instance of the redux app store. I need to mock this object and spy on its subscribe method. This way, I m having one solution that looks like following : import { TestComponentBuilder } from '@angular/compiler/testing'; import {HomeComponent} from './home.component'; import {provide} from '@angular/core'; import { it, expect, inject, describe, async, beforeEachProviders } from '@angular/core/testing'; class MockAppStore { title: String; constructor() { this.title = 'plouf'; } subscribe(callback) { callback(); } } describe('HomeComponent', () => { beforeEachProviders(() => [ provide('AppStore', { useValue: MockAppStore }) ]); it('should call the dispatch method of the appStore', async(inject([TestComponentBuilder], (tsb: TestComponentBuilder) => { tsb.createAsync(HomeComponent).then((fixture) => { // Given const component = fixture.componentInstance; spyOn(component.appStore, 'subscribe'); // When fixture.detectChanges(); // then expect(component.appStore.subscribe).toHaveBeenCalled(); }); }))); }); And that should test the following component : import {Component, Inject} from '@angular/core'; @Component({ selector: 'as-home', templateUrl: 'app/home/home.html', styleUrls: [ 'app/home/home.css' ] }) export class HomeComponent { appStore: any; constructor( @Inject('AppStore') appStore: any) { this.appStore = appStore; this.appStore.subscribe(state => { console.log(state); }); } } My problem is that the test doesn't pass at all, and the stacktrace isn't as explicit : PhantomJS 2.1.1 (Windows 8 0.0.0) HomeComponent should call the dispatch method of the appStore FAILED invoke@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:323:34 run@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:216:50 C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:571:61 invokeTask@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:356:43 runTask@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:256:58 drainMicroTaskQueue@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:474:43 invoke@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:426:41 PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 16 of 16 (1 FAILED) (0.48 secs / 0.518 secs) Remapping coverage to TypeScript format... Test Done with exit code: 1 [08:28:55] 'unit-test' errored after 7.27 s [08:28:55] Error: 1 at formatError (C:\Project\angular2\kanboard\node_modules\gulp\bin\gulp.js:169:10) at Gulp.<anonymous> (C:\Project\angular2\kanboard\node_modules\gulp\bin\gulp.js:195:15) at emitOne (events.js:77:13) at Gulp.emit (events.js:169:7) at Gulp.Orchestrator._emitTaskDone (C:\Project\angular2\kanboard\node_modules\gulp\node_modules\orchestrator\index.js:264:8) at C:\Project\angular2\kanboard\node_modules\gulp\node_modules\orchestrator\index.js:275:23 at finish (C:\Project\angular2\kanboard\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:21:8) at cb (C:\Project\angular2\kanboard\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:29:3) at DestroyableTransform.<anonymous> (C:\Project\angular2\kanboard\tasks\test.js:62:13) at emitNone (events.js:72:20) at DestroyableTransform.emit (events.js:166:7) at finishMaybe (C:\Project\angular2\kanboard\node_modules\remap-istanbul\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:475:14) at endWritable (C:\Project\angular2\kanboard\node_modules\remap-istanbul\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:485:3) at DestroyableTransform.Writable.end (C:\Project\angular2\kanboard\node_modules\remap-istanbul\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:455:41) at DestroyableTransform.onend (C:\Project\angular2\kanboard\node_modules\gulp\node_modules\vinyl-fs\node_modules\through2\node_modules\readable-stream\lib\_stream_readable.js:523:10) at DestroyableTransform.g (events.js:260:16) at emitNone (events.js:72:20) at DestroyableTransform.emit (events.js:166:7) at C:\Project\angular2\kanboard\node_modules\gulp\node_modules\vinyl-fs\node_modules\through2\node_modules\readable-stream\lib\_stream_readable.js:965:16 at nextTickCallbackWith0Args (node.js:420:9) at process._tickCallback (node.js:349:13) Remapping done! View the result in report/remap/html-report npm ERR! Test failed. See above for more details. Any idea why the test is failing ? Otherwise, I m looking for good practices concerning mocking rxjs observable / subscriptions, if anybody have an idea. Thanks for your help A: I think that the problem is in your expectation. You could try the following: expect(component.appStore.subscribe).toHaveBeenCalled(); instead of: expect(component.appStore).toHaveBeenCalled();
{ "pile_set_name": "StackExchange" }
Q: Downloading one's questions/answers Silly question... how can I download the questions/answers I've participated in on mathoverflow, as listed on my homepage, onto my computer? I'm leaving in the near future to where there is no internet, and I'd like to have them available on my laptop. Thanks. A: Stack Printer copes well with strange formatting, picture-heavy posts, and even TeX.
{ "pile_set_name": "StackExchange" }
Q: How do I UPDATE TOP 5, using a subselect? I was surprised to see that the following updated 34 rows...not 5: UPDATE Message SET StatusRawCode = 25 WHERE StatusRawCode in ( Select TOP 5 M2.StatusRawCode From Message as M2 Where M2.StatusRawCode = 5 ) Any ideas on how to pound this into the right shape? Thank you! A: My guess is the StatusRawCode values returned from your sub query are values used in the 34 records that were updated. Instead of WHERE StatusRawCode IN Use this: UPDATE Message SET StatusRawCode = 25 WHERE PrimaryKey in ( Select TOP 5 PrimaryKey From Message as M2 Where M2.StatusRawCode = 5 ) In essence, you will be selecting the primary keys of the 5 rows to be updated in the sub query. Keep in mind this will update only the top 5 records based on the clustered index ordering of your table. You will want to add an order by clause if you need to specify a specific criteria for the TOP 5 records. For example, if there is a column called Rank that you want to use as the criteria, write your query like so: UPDATE Message SET StatusRawCode = 25 WHERE PrimaryKey IN ( SELECT TOP 5 PrimaryKey FROM Message as M2 WHERE M2.StatusRawCode = 5 ORDER BY Rank DESC ) This will give you the TOP 5 records based on the Rank column values. You can substitute for your column as necessary.
{ "pile_set_name": "StackExchange" }
Q: Displaying multiple notifications at user-defined times I've been programming in Android for over a year but have never used notifications before, which I need for one of my apps. In the app, there are events that can be set at different times. Obviously, the user can choose to change these times or add/remove events. I plan to use notifications to notify the user 5 minutes before their event starts. I've read through the Android developer docs for Building a Notification and Services (which I am also new to). I have decided to use Services because I figured that the notification would need to be shown even when the app not running. To help me, I have been referring to one particular SO answer as guidance. I begun by experimenting a little with the notification builder classes in my NotificationService class like so: public class NotificationService extends IntentService { private static final int NOTIFICATION_ID = 1; public NotificationService() { super(NotificationService.class.getSimpleName()); } @Override protected void onHandleIntent(Intent intent) { showNotification(); } private void showNotification() { Intent intent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setContentTitle("Test notification") .setSmallIcon(R.drawable.ic_event_black_24dp) .setContentText("Test description") .setContentIntent(pendingIntent); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, builder.build()); } } I also use the following to start this Service in the splash screen of my app: Intent serviceIntent = new Intent(this, NotificationService.class); startService(serviceIntent); To display notifications at specific times, I've read about AlarmManager, mainly through SO questions like this one. I also know that to display multiple notifications, I would need different notification ids (like my constant NOTIFICATION_ID). However, what I am unsure of is dynamically updating the times that notifications would be shown each time an event is added, removed, or its times changed. Could someone provide me some guidance on how I could achieve this? A: You implement notification part. For notify user at Specific time you should set AlarmManager. I paste whole code you need then explain each part: public class AlarmReceiver extends WakefulBroadcastReceiver { AlarmManager mAlarmManager; PendingIntent mPendingIntent; @Override public void onReceive(Context context, Intent intent) { int mReceivedID = Integer.parseInt(intent.getStringExtra(AddReminderActivity.EXTRA_REMINDER_ID)); // Get notification title from Reminder Database ReminderDatabase rb = new ReminderDatabase(context); ApiReminderModel reminder = rb.getReminder(mReceivedID); String mTitle = reminder.getName(); // Create intent to open ReminderEditActivity on notification click // handling when you click on Notification what should happen Intent editIntent = YourActivity.createActivity(context, reminder.getChannelId(), reminder.getStartTime()); PendingIntent mClick = PendingIntent.getActivity(context, mReceivedID, editIntent, PendingIntent.FLAG_UPDATE_CURRENT); // Create Notification NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_logo)) .setSmallIcon(R.drawable.ic_logo) .setContentTitle(context.getResources().getString(R.string.app_name)) .setTicker(mTitle) .setContentText(mTitle) .setContentIntent(mClick) .setSound(ringtoneUri) .setAutoCancel(true) .setOnlyAlertOnce(true); NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nManager.notify(mReceivedID, mBuilder.build()); } public void setAlarm(Context context, Calendar calendar, int ID) { mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Put Reminder ID in Intent Extra Intent intent = new Intent(context, AlarmReceiver.class); intent.putExtra(AddReminderActivity.EXTRA_REMINDER_ID, Integer.toString(ID)); mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT); // Calculate notification time Calendar c = Calendar.getInstance(); long currentTime = c.getTimeInMillis(); long diffTime = calendar.getTimeInMillis() - currentTime; // Start alarm using notification time mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime, mPendingIntent); // Restart alarm if device is rebooted ComponentName receiver = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); } public void cancelAlarm(Context context, int ID) { mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Cancel Alarm using Reminder ID mPendingIntent = PendingIntent.getBroadcast(context, ID, new Intent(context, AlarmReceiver.class), 0); mAlarmManager.cancel(mPendingIntent); // Disable alarm ComponentName receiver = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } } As you see we have setAlarm which notify users at specific time. I also pass calendar instance which is initiated before ( assign a time which user should be notify). Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DAY_OF_YEAR, 7);// assume you want send notification 7 days later new AlarmReceiver().setAlarm(getApplicationContext(), mCalendar, id); We have another method cancelAlarm. If you want to delete a Alaram just pass unique ID of Alarm (Which already used for creation of Alarm). Also don't forget to add this Service to your AndroidManifest.xml: <receiver android:name=".service.AlarmReceiver" /> There is only on thing remain When you reboot your device you should set AlarmsManager again so you need a BootRecivier service.
{ "pile_set_name": "StackExchange" }
Q: Android Multiple Fragment Callback Confusion I'm trying to wrap my head around the order and process of removing and signaling events to the Activity from the fragments. I am trying to just have one FragmentA which is a list of items, transition to FragmentB upon a button click which loads a form to add a new item, and then when FragmentB is done with the form, add that item into the list of FragmentA. (The Main Arraylist is stored in MainActivity). Basically, I have one MainActivity which creates a FragmentA (which populates a list with items). I also have a FragmentB (which is a form that allows an item to be added to the list). What I'm getting confused about is how to properly set up the callbacks. I understand how to implement the callback with just one Fragment (using this and this tutorials) but my confusion is this: Which order is the correct one (if any)? MainActivity 'creates' (transitions) FragmentA, FragmentA then transitions to FragmentB. FragmentB then sends the callback (adding a new item) to FragmentA, and FragmentA signals to the MainActivity to add the item to the main list (callback 2). MainActivity then closes FragmentB. (I want to leave FragmentA open). MainActivity 'creates' (transitions) FragmentA, FragmentA then transitions to FragmentB. FragmentB then sends the callback (adding a new item) to MainActivity. MainActivity then closes FragmentB and returns the state back to FragmentA. MainActivity 'creates' (transitions) FragmentA, MainActivity then transitions to FragmentB when FragmentA signals a callback to switch fragments (close fragmentA or add it to the backstack). FragmentB sends a callback to MainActivity, MainActivity closes FragmentB and then reopens FragmentA. Hopefully I explained it alright enough, but I know it is kind of confusing the way I worded it. Edit One last question, would the Activity end up "implementing" 15 different Fragment listeners if you had 15 different Fragments that needed callbacks? Just seems a bit excessive. Thanks A: Just consider the Activity as a father and the Fragments are his children who have dependency to their father, So let the children make their wishes and the sugar daddy decides what is good for his sweethearts! Main advantage of this approach is consistency and modularity of your code, Actually they have a server-client relationship, Fragments send their request and tasks are done by the Activity, Each element plays its role in a clean and simple way. Don't worry about number of interfaces you have to implement, But remember why an Activity exists So you can easily realize Fragments which should be managed with a specific Activity. BroadcastReceiver and EventBus library are the other options for communication but not the best in your case!
{ "pile_set_name": "StackExchange" }
Q: checking if a table row exists in table layout WHAT I HAVE I created a table layout where the rows are dynamically added. I have 2 editTexts as columns. WHAT I WANT If a table row's second editText is focused and enter is pressed, then: If a table row exists below, focus should be set to it's edittext. If NO table row exists below, table row should be added and then focus set. I think I need something like: If(tablerow exists below){ //do the focusing } else{ //add new row //do the focusing } I used a function addView to add the rows : public void addView(Context context) { int dpConv = (int) getResources().getDisplayMetrics().density; i = i + 1; try { txt_itemName[i] = new EditText(context); txt_itemName[i].setText("itName"); txt_itemName[i].requestFocus(); txt_qty[i] = new EditText(context); txt_qty[i].setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); txt_qty[i].setImeOptions(EditorInfo.IME_ACTION_NEXT); txt_qty[i].setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if(actionId == EditorInfo.IME_ACTION_NEXT){ txt_qty[i].clearFocus(); //Need to check conditions here } return false; } }); tb_row[i] = new TableRow(context); tb_row[i].addView(txt_itemName[i]); tb_row[i].addView(txt_qty[i]); tb_lyt.addView(tb_row[i]); A: Ok. what about if you try this: if(actionId == EditorInfo.IME_ACTION_NEXT){ txt_qty[i].clearFocus(); //Need to check conditions here /* I'm assuming that: You have the value of i You add TableRows ONLY to your TableLayout */ if(tb_lyt.getChildCount() > (i+1)) { //If a child exist below //Do your focus setting } else { //Add a new Row. } }
{ "pile_set_name": "StackExchange" }
Q: Minimize a sum with a weight constraint We are given N sets, each of which has a finite number of pairs $(x_i,y_i)$. $M_1=\{(0,0), (x_{1,1},y_{1,1}), ...\}$ ... $M_N=\{(0,0), (x_{1,N},y_{1,N}), ...\}$ The problem is to select one and only one item from each set such that $Min \{\displaystyle\sum_{j=1...N}(x_{i,j})\}$ s.t. $\displaystyle\sum_{j=1..N}(y_{i,j}) > R$ where $R$ is a given constant. Is there any classic problem similar to this? or what is known about this class of problems? A: The problem you have given is similar to KNAPSACK as Yuval Filmus mentioned. KNAPSACK problem is defined as: maximize $\sum_{i=1}^n v_i x_i$ subject to $\sum_{i=1}^n w_i x_i \leq W$ and $x_i \in \{0,1\}. $ I assume the pair (0,0) is used so that you may not choose pairs for some of the $M_j$'s. Otherwise (0,0) pair is irrelevant in the problem. If this is so, then your problem can be easily shown to be NP-complete. We can reduce KNAPSACK to your problem by taking $N=n$ and have each $M_j$ as a copy to the KNAPSACK instance (after negating $v_i$'s and $w_i$'s of course). If pair (0,0) is not used in a way that I described above, then too you can circumvent the issue by adding $N$ pairs $(x_{N+i,j},y_{N+i,j})$, for $1\leq i \leq N$ in set $M_j$ for $1 \leq j \leq N$, so that each $M_j$ has now additional $N$ pairs (total of $2N+1$). Each $x_{N+i,j} = y_{N+i,j} = 0$ for all $i$'s and $j$'s. If you say that each pair need to be distinct, then we can take $x_{N+i,j} = y_{N+i,j} = \epsilon_{i}$ to make each pair distinct, where $\epsilon_{i} \ll 1$ is an arbitrarily very small quantity. We also replace $R$ by $R+\Sigma_i \epsilon_i$.
{ "pile_set_name": "StackExchange" }
Q: Flask - return items to base.html I was wondering if it is possible to make a default route which will return objects or items to the base.html (which all the other pages inherit from) something like this @app.route(all) def base(): test = 'Avaible to all' return render_template('base.html', test=test) and therefore in the base.html you can just call the desired object, test in this case. <!DOCTYPE html> <html> <head> <title>My base page</title> </head> <body> {% block body %} {% endblock %} <!-- same text to all pages --> {{ test }} </body> </html> Of course if it is just a string I could just write it manually in the HTML - Base file, but hence I am asking is because I am going to implement sqlAlchemy and dynamic objects which will be changed over time in the back-end or database. It could for example be, Greetings (username) or today it is (the-time) A: Check out context processors. Basically, they're a way to inject dictionary key/values into all templates in the app. For your example above: @app.context_processor def inject_test(): return {'test': 'Available to all'}
{ "pile_set_name": "StackExchange" }
Q: Why do the bedrooms in my home have split switched outlets? My wife and I are renting a house that was built around 2007 in Washington State. It has a peculiar wiring arrangement that I've never seen before. Every bedroom and the living room has two switches near the entry - one for the ceiling mounted light fixture and the other for wall outlets. Not just one wall outlet, but every single one. Each outlet is split so the top is always on and the bottom is switched. I find this to be a horrible idea, because it essentially eliminates half the plugs in each room, resulting in more power strips and extension cords. My recollection of building codes is that there has to be a switched outlet if there is no ceiling fixture - is that still current? If so, why would the house be wired this way - is it local custom in certain parts of the country, or perhaps just a unique request from the original homeowner? A: Is it possible that the house was originally not wired with ceiling fixtures and the ceiling fixtures were added later? A long shot possibility is that this wiring was designed as a safety measure to allow shutting off receptacles to protect a child or a (cord chewing) dog from shock or electrocution. EDIT This was a speculative suggestion on my part motivated by my finding that our new dog had chewed two cords all the way to conductors that were plugged into switched outlets that were off. This was what I imagined: The house was built by a family of dog lovers who knew they would have a succession of young dogs who will go through the "chew on everything" phase. While they have a dog in that phase they plug everything in certain rooms in switched receptacles. These are rooms that the dog would be in unsupervised. Another possibility for switching half of all the receptacles in a room is to be able to turn off all "parasitic" draws with one switch. (Of course, to be effective this would require that loads of this category be plugged into the switched receptacles.) Some people say that the total of parasitic draws in a house is significant. Another possibility is to allow multiple switched lamps all around the room.
{ "pile_set_name": "StackExchange" }
Q: dojox email validator always fails I'm trying to use a dijit/form/ValidationTextBox with an isEmailAddress validator to check for valid emails, the problem is that valid emails are flagged as invalid. Note I got the validator to work by including "dojox/validate/web", but the form always evaluates to invalid in my login function my code is: HTML: <form data-dojo-type="dijit/form/Form" id="FormLogin"> ... <input type="text" required="true" name="email" data-dojo-attach-point="tbEmail" data-dojo-type="dijit/form/ValidationTextBox" validator="dojox.validate.isEmailAddress" invalidmessage="Not a valid email" /> <button data-dojo-type="dijit/form/Button" type="button" data-dojo-attach-point="LogInButton" data-dojo-attach-event="onClick:Login"> Login </button> ... </form> JavaScript: define([ "dojo/_base/declare", "dijit/Dialog", "dijit/form/Form", "dijit/registry", "dijit/form/ValidationTextBox", "dojox/validate", "dojox/validate/web", "dijit/_WidgetBase", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin", "dojo/text!Templates/LoginForm.htm" ], function ( declare, Dialog, Form, registry, ValidationTextBox, validate, web, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, LoginFrmTpl) { return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], { templateString: LoginFrmTpl, postCreate: function () { }, Login: function () { if (registry.byId("FormLogin").validate == true) { //this never evaluates to true, even when the email is valid alert("we can submit the data") } else { alert("error in form") } } }); }); Any ideas? The invalid message appears no matter what text is entered in tbEmail Thanks A: I got it to work by validating the textbox tbEmail. I changed my Login function to the following: Login: function () { if (registry.byId("tbEmail").isValid() == true) { alert("we can submit the data") } else { alert("error in form") } }
{ "pile_set_name": "StackExchange" }
Q: event.preventDefault not working in React I've followed a tutorial & they used event.preventDefault() on the Save button & save a form into the state. I've not really written the input tags yet but so far I've added the Save button and it kinda like reloads the page which it shouldn't be doing. Here is my page component: class manageLocationPage extends React.Component { constructor(props, context) { super(props, context); this.state = { }; this.SaveLocation = this.SaveLocation.bind(this); } componentWillMount() { } componentDidMount() { } SaveLocation(event) { event.preventDefault(); console.log("Saved"); } render() { return ( <div> <LocationForm listingData={this.props.listingData} onSave={this.SaveLocation}/> </div> ); } } My locationForm component: const LocationForm = ({listingData, onSave, loading, errors}) => { return ( <form> <h1>Add / Edit Location</h1> <TextInput /> {/*Here below is where we submit out input data*/} <input type="submit" disabled={loading} value={loading ? 'Saving...' : 'Save'} className="buttonSave" onClick={onSave}/> </form> ); }; Did I miss something? A: Instead of onClick it your input.submit, you should do const LocationForm = ({listingData, onSave, loading, errors}) => { return ( <form onSubmit={onSave}> <h1>Add / Edit Location</h1> <TextInput /> {/*Here below is where we submit out input data*/} <input type="submit" disabled={loading} value={loading ? 'Saving...' : 'Save'} className="buttonSave"/> </form> ); }; So the event is the form submission which is being prevented. https://facebook.github.io/react/docs/tutorial.html#submitting-the-form
{ "pile_set_name": "StackExchange" }
Q: Find String Pattern Match in Pandas Dataframe and Return Matched Strin I have a dataframe column with variable comma separated text and just trying to extract the values that are found based on another list. So my dataframe looks like this: col1 | col2 ----------- x | a,b listformatch = [c,d,f,b] pattern = '|'.join(listformatch) def test_for_pattern(x): if re.search(pattern, x): return pattern else: return x #also can use col2.str.contains(pattern) for same results The above filtering works great but instead of returning b when it finds the match it returns the whole pattern such as a|b instead of just b whereas I want to create another column with the pattern it finds such as b. Here is my final function but still getting UserWarning: This pattern has match groups. To actually get the groups, use str.extract." groups, use str.extract.", UserWarning) I wish I can solve: def matching_func(file1, file2): file1 = pd.read_csv(fin) file2 = pd.read_excel(fin1, 0, skiprows=1) pattern = '|'.join(file1[col1].tolist()) file2['new_col'] = file2[col1].map(lambda x: re.search(pattern, x).group()\ if re.search(pattern, x) else None) I think I understand how pandas extract works now but probably still rusty on regex. How do I create a pattern variable to use for the below example: df[col1].str.extract('(word1|word2)') Instead of having the words in the argument, I want to create variable as pattern = 'word1|word2' but that won't work because of the way the string is being created. My final and preferred version with vectorized string method in pandas 0.13: Using values from one column to extract from a second column: df[col1].str.extract('({})'.format('|'.join(df[col2])) A: You might like to use extract, or one of the other vectorised string methods: In [11]: s = pd.Series(['a', 'a,b']) In [12]: s.str.extract('([cdfb])') Out[12]: 0 NaN 1 b dtype: object
{ "pile_set_name": "StackExchange" }
Q: How to know who is a good monk? I'm a Buddhist and I want to know who is a good monk. Tell me if I'm wrong but I think that monks Do not request money/things Follow the rules Do not bless for to be rich... (Its passion) etc... But how do I explain to a non-buddhist how to recognise a good monk? A: I see the original question as been modified when I went online again. The original question included "hinting/asking" I have included this under wrong livelihood. How to know who is a good monk is a little more difficult to know than who is a bad monk. People will judge differently on what factors makes one a good monk. We can start with morality according to the monks rules which he has an obligation to follow. There are a few easy signs that one is a bad monk. When he goes out into the village, if he has one shoulder exposed, this is a very clear sign that he breaks most of the rules. If he has both shoulders covered, that means he follows this rule, but maybe not others. This is just a quick way to throw out the majority of monks into the bad monk pile. Unfortunately, most monks in Myanmar break this rule and that also means that most monks break most of the rules. Monks need to follow all of the rules 227 rules and also the rules in the Culavagga and Mahavagga. Likewise, they need to follow according to the commentaries as well in most cases. Most Western Bhikkhus do not like the commentaries. That is where "interpretations" can come. Most of the information below, is from the BMC The Buddhist Monastic Code Summary: A Bhikkhu cannot use money. A Bhikkhu cannot point out a kappiya without someone asking, "Who is you kappiya?" A Bhikkhu cannot accept envelopes presumably with money inside. It is an asannya offence (in the root text). Which means, no perception is necessary for it to be unallowable. That means the monks should not be intentionally ignorant. The BMC debates and allows the modern use of "checks." A Bhikkhu cannot ask for things from "Just anyone". He needs an invitation from a non-family member ( blood relation) A Bhikkhu cannot hint to "Just anyone" (as above) A Bhikkhu cannot do the above for another bhikkhu(s) either. The BMC says checks are not money but a "promise to pay." Sri Lanka and Myanmar Vinaya traditions call this money. Money is defined as anything accepted as used in trade. A US dollar is a mere bank note too. Google "A Life Free From Money pdf" The same as above is judged with signing checks. A bhikkhu can ask for a bowl from anyone if it is broken or stolen. A bhikkhu can ask for a single robe from anyone if he is left with only one (of three). A bhikkhu can go for alms in the evening for "extra items," usually medicine or oil for light. The donors will offer food and he will refuse. Then the person may ask, "what do you need?" Then he can say. Lay people or committees can ask "just anyone" for things or money, etc. for monks if it is their own idea. This might be what you are seeing on brochures and websites, etc. A Bhikkhu cannot ask his helper, committee etc, to ask others for money for himself. A bhikkhu must be invited by a committee or kappiya before he asks them for things. The above list is followed correctly unfortunately by a small minority of monks, known as vinaya monks, or forest monks. Often the other (majority) monks do not know what proper behavior is. They may memorize the rules, but do not think it is something to be practiced since corruption is so wide spread. One of my monastic friends told me he cried when he found out that he was never supposed to touch money. A monk may purify himself at any time. Often, they just do not know. Traditions often have interpretations which makes items seem "allowable.". Sometimes this is allowed and sometimes one can just be fooling oneself. In the end it is up to them. Often bhikkhus do not reflect or question questionable practices in a tradition because of the wide spread use. Money and medicines are often such topics. "Monks, strive with heedfulness. Rare is it that Buddhas arise in the world. Rare is it that [one] it that [one] obtains a human [birth]. Rare is it to have the good fortune of [being in the right] time [and place]. Rare is it [that one has the opportunity] to take the Going forth. Rare is it [that one has the opportunity] to listen to the True Dhamma. Rare is it [that one has the opportunity] to associate with good people." (c.f. D.32.33 & A.8:29) BMC I, 2009 ed. pdf Monks must also practice right livelihood according to not doing things from the list below: Wrong Livelihood The Cullavagga, in a section that begins with the same origin story as the one for this rule (Cv.I.13-16), treats the banishment transaction in full detail, saying that a Community of bhikkhus, if it sees fit, has the authority to perform a banishment transaction against a bhikkhu with any of the following qualities: 1) He is a maker of strife, disputes, quarrels, and issues in the Community. 2) He is inexperienced, incompetent, and indiscriminately full of offenses (§). 3) He lives in unbecoming association with householders. 4) He is corrupt in his precepts, corrupt in his conduct, or corrupt in his views. 5) He speaks in dispraise of the Buddha, Dhamma, or Saṅgha. 6) He is frivolous in word, deed, or both. 7) He misbehaves in word, deed, or both. 8) He is vindictive in word, deed, or both. 9) He practices wrong modes of livelihood. This last category includes such practices as: a) running messages and errands for kings, ministers of state, householders, etc. A modern example would be participating in political campaigns. b) scheming, talking, hinting, belittling others for the sake of material gain, pursuing gain with gain (giving items of small value in hopes of receiving items of larger value in return, making investments in hopes of profit, offering material incentives to those who make donations). (For a full discussion of these practices, see Visuddhimagga I.61-82.) c) Practicing worldly arts, e.g., medicine, fortune telling, astrology, exorcism, reciting charms, casting spells, performing ceremonies to counteract the influence of the stars, determining propitious sites, setting auspicious dates (for weddings, etc.), interpreting oracles, auguries, or dreams, or — in the words of the Vibhaṅga to the Bhikkhunīs' Pc 49 & 50 — engaging in any art that is "external and unconnected with the goal." The Cullavagga (V.33.2) imposes a dukkaṭa on studying and teaching worldly arts or hedonist doctrines (lokāyata). For extensive lists of worldly arts, see the passage from DN 2 quoted in BMC2, Chapter 10. BMC I Lists wrong livelihood extensively starting on page 518 PDF ed. "Medicines" There are some things in the BMC which I think are very misleading, especially concerning, "medicines" and how "Any Reason" is defined (p232). I could not find any pāli evidence that mentions "hunger and fatigue" as a valid medical reason. I could be wrong, but I asked a couple of knowledgeable monks to verify this and they also agreed with my findings. This would exclude many things which are considered medicines. I will not cover further with lists of the "medicines." Only that there should be a valid reason for taking them and justifying their use after Noon. The reflection and criteria are below. It is in every monastery chanting book and should be chanted every day. (Nauyana chanting book source) "Medicine Reflection" Whatever requisite of medicine for treating illness has been used by me today without reflection was only to ward off painful feelings that have arisen, [and] for the maximum freedom from disease.
{ "pile_set_name": "StackExchange" }
Q: How to make URL redirection for partially dynamic URL? I would like to create a redirection rule which will always redirect a user to specified URL, for instance: from http://www.team.com/team/player/5/1.html to http://www.team.com/jose-garcia.html The number between /player/ and /1.html is dynamic. I would like to make redirection regardless from the number that is set there. A: You can use this code in your DOCUMENT_ROOT/.htaccess file: RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?team\.com$ [NC] RewriteRule ^team/player/\d+/1\.html$ /jose-garcia.html [L,NC,R=302] \d+ will match any number between team/player/ and /1.html.
{ "pile_set_name": "StackExchange" }
Q: Spring MVC Controller List as a parameter I have a Spring MVC application. Jsp page contains form, which submitting. My controller's method looks like: @RequestMapping(value = "photos/fileUpload", method = RequestMethod.POST) @ResponseBody public String fileDetailsUpload(List<PhotoDTO> photoDTO, BindingResult bindingResult, HttpServletRequest request) { // in the point **photoDTO** is null } My class is: public class PhotoDTO { private Boolean mainPhoto; private String title; private String description; private Long realtyId; //getters/setters But, if I write the same method, but param is just my object: @RequestMapping(value = "photos/fileUpload", method = RequestMethod.POST) @ResponseBody public String fileDetailsUpload(PhotoDTO photoDTO, BindingResult bindingResult, HttpServletRequest request) { // Everething is Ok **photoDTO** has all fields, which were fielded on the JSP What should I do in the situation? What if I have on Jsp many PhotoDTO objects (15) how can I recive all of them on the server part? A: The page should pass the parameters for each PhotoDTO in the list back to the server in the appropriate format. In this case you need to use the status var to specify the index of each object in the list using the name attribute. <form> <c:forEach items="${photoDTO}" var="photo" varStatus="status"> <input name="photoDTO[${status.index}].title" value="${photo.title}"/> <input name="photoDTO[${status.index}].description" value="${photo.description}"/> </c:forEach> </form>
{ "pile_set_name": "StackExchange" }
Q: java.sql.SQLException: ORA-00917: missing comma I'm pulling my hair out trying to find the cause of the SqlExcpetion below. I'm using Oracle Database 11g Express and SqlDeveloper. I've looked through other posts, but so far no help. java.sql.SQLException: ORA-00917: missing comma at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531) at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:195) at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:1029) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336) at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:1498) at oracle.jdbc.driver.OracleStatementWrapper.executeQuery(OracleStatementWrapper.java:406) at com.ets.hr.dao.EmployeeDAO.createEmployee(EmployeeDAO.java:30) at Test.main(Test.java:62) Method below: public void createEmployee(Employee e){ try{ Class.forName(oracleClass); Connection conn = DriverManager.getConnection(oracleUrl, "hr", "hr"); Statement s = conn.createStatement(); String query = "INSERT INTO employees VALUES(" + e.getEmployeeId() + ", '" + e.getFirstName() + "', '" + e.getLastName() + "', '" + e.getEmail() + "', '" + e.getPhoneNumber() + "', " + e.getHireDate() + ", '" + e.getJobId() + "', " + e.getSalary() + ", " + e.getCommissionPct() + ", " + e.getManagerId() + ", " + e.getDepartmentId() + ")"; s.executeQuery(query);//LINE 30 - SqlException Here System.out.println("Query Executed: Create Employee"); } catch(SQLException se){ se.printStackTrace(); } catch(ClassNotFoundException ce){ ce.printStackTrace(); } } Employee Class: package com.ets.hr.dto; import java.util.Date; public class Employee { //CONSTRUCTORS public Employee(){} public Employee(long eId, String firstName, String lastName, String email, String phoneNumber, Date hireDate, String jobId, double salary, double commissionPct, long managerId, long departmentId){ this.firstName = firstName; this.lastName = lastName; this.email = email; this.phoneNumber = phoneNumber; this.hireDate = hireDate; this.jobId = jobId; this.salary = salary; this.commissionPct = commissionPct; this.managerId = managerId; this.departmentId = departmentId; } //instance variables (from HR.EMPLOYEE table) private long employeeId; private String firstName; private String lastName; private String email; private String phoneNumber; private Date hireDate; private String jobId; private double salary; private double commissionPct; private long managerId; private long departmentId; //GETTERS public long getEmployeeId(){ return this.employeeId; } public String getFirstName(){ return this.firstName; } public String getLastName(){ return this.lastName; } public String getEmail(){ return this.email; } public String getPhoneNumber(){ return this.phoneNumber; } public Date getHireDate(){ return this.hireDate; } public String getJobId(){ return this.jobId; } public double getSalary(){ return this.salary; } public double getCommissionPct(){ return this.commissionPct; } public long getManagerId(){ return this.managerId; } public long getDepartmentId(){ return this.departmentId; } //SETTERS public void setEmployeeId(long employeeId){ this.employeeId = employeeId; } public void setFirstName(String firstName){ this.firstName = firstName; } public void setLastName(String lastName){ this.lastName = lastName; } public void setEmail(String email){ this.email = email; } public void setPhoneNumber(String phoneNumber){ this.phoneNumber = phoneNumber; } public void setHireDate(Date hireDate){ this.hireDate = hireDate; } public void setJobId(String jobId){ this.jobId = jobId; } public void setSalary(double salary){ this.salary = salary; } public void setCommissionPct(double commissionPct){ this.commissionPct = commissionPct; } public void setManagerId(long managerId){ this.managerId = managerId; } public void setDepartmentId(long departmentId){ this.departmentId = departmentId; } public void printEmployee(){ System.out.println("Employee ID: " + this.getEmployeeId()); System.out.println("Employee Name: " + this.getFirstName() + this.getLastName()); System.out.println("Employee Email: " + this.getEmail()); System.out.println("Employee Phone: " + this.getPhoneNumber()); System.out.println("Employee Hire Date: " + this.getHireDate()); System.out.println("Employee Job ID: " + this.getJobId()); System.out.println("Employee Salary: " + this.getSalary()); System.out.println("Employee Commission Pct: " + this.getCommissionPct()); System.out.println("Employee Manager ID: " + this.getManagerId()); System.out.println("Employee Department ID: " + this.getDepartmentId()); } } A: You shouldn't be trying to build your own SQL string, because you have to deal with quoting and escaping (which has bitten you here). Instead, use a PreparedStatement and let the JDBC API escape, quote and format (eg dates) your values for you: String query = "INSERT INTO employees VALUES (?,?,?,?,?,?,?,?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(query); ps.setInt(e.getEmployeeId(), 1); ps.setString(e.getFirstName(), 2); ps.setDate(e.getHireDate(), 6); // etc - there is a setter for each basic datatype ps.execute(); ps.close(); The coding is easier, and readability goes way up too.
{ "pile_set_name": "StackExchange" }
Q: How can I get the URL for product's page using the Shopify API? I checked out Shopify product API but result doesn't seem to return product page URL. The URL looks like resulted after some transformation on the title. Is there reliable well defined logic for this or any other method to get product page URL? A: You can do it as 'products/< product.handle >'. I'm not sure if there is a better way of doing it, but it works. A: I usually add this in config/initializers/shopify_api.rb: module ShopifyAPI class Shop def store_url_for(entity) return "http://#{self.domain}/#{entity.class.element_name}/#{entity.handle}" end end end
{ "pile_set_name": "StackExchange" }
Q: Angular counter trigger event Typescript: countDown; counter = 10; tick = 1000; this.countDown = Observable.timer(0, this.tick) .take(this.counter) .map(() => --this.counter) And in HTML: <div> <h1>Time left</h1> <h2>{{countDown | async | formatTime}}</h2> </div> How can I trigger an event wehen counter hits 0? A: Try this this.countDown = Observable .timer(0, this.tick) .take(10) .filter(value => value === 0) .do(() => {}) You can also use this because you used take this.countDown = Observable .timer(0, this.tick) .take(10) .map(() => --this.counter) .finally(() => {}) EDIT For version 6 : this.countDown = timer(0, this.tick) .pipe( take(this.counter), map(() => --this.counter), finalize(() => /* your event */), ) this.countDown = timer(0, this.tick) .pipe( take(this.counter), map(() => --this.counter), filter(value => value === 0), tap(() => /* your event */), )
{ "pile_set_name": "StackExchange" }
Q: SQL Recursive Query and Output Using the following SQL statements to create table and insert values: create table tb(id int , pid int , name nvarchar(10)) insert into tb values( 1 , null , 'A') insert into tb values( 2 , null , 'B') insert into tb values( 3 , null , 'C') insert into tb values( 4 , 1 , 'D') insert into tb values( 5 , 1 , 'E') insert into tb values( 6 , 2 , 'F') insert into tb values( 7 , 3 , 'G') insert into tb values( 8 , 4 , 'H') insert into tb values( 9 , 5 , 'I') And I want the the final output to display each line of this tree from root to leaf like this: A-D-H A-E-I B-F C-G Is anyone know how to write SQL procedure to do this?thanks. A: If you are using SQL Server then you can use a recursive query to solve it. Similar approach can be used in Oracle and PostgreSQL. with rcte as ( select t1.id, t1.pid, cast(t1.name as nvarchar(100)) name from tb t1 where not exists (select 1 from tb t2 where t2.pid = t1.id) union all select tb.id, tb.pid, cast(concat(tb.name, '-', rcte.name) as nvarchar(100)) name from rcte join tb on rcte.pid = tb.id ) select name from rcte where rcte.pid is null demo It first finds the leaf nodes and then it traverses up to a root.
{ "pile_set_name": "StackExchange" }
Q: jQuery script not recognised when injected in my view (.cshtml) Usually I create a javascript file (myfile.js) for my scripts. Example: /// <reference path="../../Scripts/Jquery/jquery-1.5.1.js" /> $(document).ready(function () { // bind 'myForm' and provide a simple callback function $('#uploadBackgroundForm').ajaxForm({ iframe: true, dataType: "json", success: BackgroundUploadedSuccess, error: BackgroundUploadedError }); }); Now I would like to place my script directly in my view (.cshtml) in a section (< script type="text/javascript">.....< / script >). Example: ...my view goes here... <script type="text/javascript"> /// <reference path="../../Scripts/jquery-1.5.1.js" /> $(document).ready(function () { // bind 'myForm' and provide a simple callback function $('#uploadBackgroundForm').ajaxForm({ iframe: true, dataType: "json", success: BackgroundUploadedSuccess, error: BackgroundUploadedError }); }); .... </script> But it doesn't work. I mean when I place my cursor on a jQuery syntax like 'ready' and click CTRL+J nothing is recognised. Any idea? Thanks. A: You have to add the reference with such construct : @if (false) { <script src="~/Scripts/jquery-1.5.1.js" type="text/javascript"></script> } With the @if (false) the script is not loaded at runtime... (You can also see this page). UPDATE : You have to insert this code just before your other script tag.
{ "pile_set_name": "StackExchange" }
Q: Reading generic types from user input ive done some research and found nothing, so I need help reading generic types from a user input. Let's say for example I want to enter a integer one case, then when i run the program again, i want to input a string. How would i do that with scanner or another input reader? Heres my code public class array <T,E> { private T [] a; private int size; private int location; private E add; private E delete; private E find; public array(){ } public array(int size){ this.size = size; this.location = 0; this.a = (T[])(new Object[size]); } public boolean add(T element){ if(location == size){ return false; }else{ this.a[location++] = element; System.out.println("Element added at location " + location); return true; } } public int find(T element){ for(int i = 0 ; i < location; i ++){ if(a[i] == element){ System.out.println("Element found at location " + i); return i; } } System.out.println("Couldn't find element"); return -1; } public boolean delete(T element){ int loc = find(element); if(loc == -1){ System.out.println("Couldn't find element"); return false; }else{ for(int x = loc; x < location - 1; x++){ a[x] = a[x+1]; } System.out.println("Element deleted"); location -= 1; return true; } } public void go(){ DataInputStream in = new DataInputStream(System.in); Scanner scanner = new Scanner(System.in); array a = null; int choice = 0; System.out.println("Chose what you want to do"); System.out.println("1: Add a value"); System.out.println("2: Delete a value"); System.out.println("3: Find a value and return the index"); System.out.println("4: Display all elements in array"); System.out.println("5: Exit"); System.out.println(); try{ choice = scanner.nextInt(); }catch(Exception e){ System.out.println("Incorrect input"); go(); } switch(choice){ case 1: System.out.println("Enter the element you want to add"); add = in.read(); a.add(add); break; case 2: System.out.println("Enter the element you want to delete"); delete = in.nextInt(); a.delete(delete); break; case 3: System.out.println("Enter the element you want to find"); find = in.nextInt(); a.find(find); break; case 4: System.out.println(a.toString()); break; case 5: System.exit(0); break; } System.out.println("Continue? 1-Yes, 2-No"); int yn = in.nextInt(); if(yn == 1){ go(); }else{ System.exit(0); } } @Override public String toString(){ String string = ""; for(int i = 0; i < location; i++){ string = string + " " + a[i]; } return "Numbers " + string; } } Heres my main class(Driver) public class ArrayManipulator<T> { private static int size; public static void main(String[] args) { Scanner in = new Scanner(System.in); array a = new array(); System.out.println("Enter the size of the array"); size = in.nextInt(); System.out.println("---------------------------"); a = new array(size); a.go(); } } So, my problem is with asking the user to input values for elements in the array in the go() method. I am not such which input reader to use to read generic types, or if that is even possible. Thanks A: Its better to decide what type you enter before creating the object of class array. probably you can get it from user. And after deciding the types, create the object using eg : array<Integer,String> arr = new array<Integer,String>. Or for having a generic type, use Object
{ "pile_set_name": "StackExchange" }
Q: Image in MPDF footer won't work as a link I'm adding the following to my MPDF footer: <a href="#bottom"><img src="arrowdownred.jpg" width="40" height = "34" />&darr;</a> It's showing up fine, and the ↓ character works fine as a link, but the image doesn't! The cursor changes when I mouse over it, but it doesn't work when clicked. Anyone got any ideas? A: So I found the answer deep in the MPDF forum, so I thought I'd post it up here: It's a bug with image links to fix it, in mpdf.php, line 18330, find: if ($this->HREF) { $objattr['link'] = $this->HREF; } // ? this isn't used and replace with: if ($this->HREF) { if (strpos($this->HREF,".") === false && strpos($this->HREF,"@") !== 0) { $href = $this->HREF; while(array_key_exists($href,$this->internallink)) $href="#".$href; $this->internallink[$href] = $this->AddLink(); $objattr['link'] = $this->internallink[$href]; } else { $objattr['link'] = $this->HREF; } }
{ "pile_set_name": "StackExchange" }
Q: Forcing buttons to be horizontal in bootstrap Been trying to build an app with some buttons, and it seems impossible to force them to be horizontal, almost like they by default want to be vertical aligned for the fun of it. As far as I can tell, it is somehow related to the width of the page, and as far as I can tell its based on column system Here is my problem, I created a menu in the layout, and got it to line up horizontally, then moved it into a directive, one part lines up correctly (the top bit) the second part is lining up as vertical. As I understand it, if I create a button group (in this case a btn-toolbar) and I tell it to be col-md-1 then each of these buttons SHOULD take up 1 column of the btn-toolbar space. But I do not know how to set the toolbar width. I am using Stylus and Jade as well as angular. Hence the look of things The two menu sniplets div.layout div.topmenu(ng-show="app.menushow") .btn-toolbar .topcontainer a(href="/about") .button.col-md-offset-10 .btn.btn-sm.col-md-1.btn-primary.btn-topmny. About a(href="/contact") .button.col-md-offset-11 .btn.btn-sm.col-md-1.btn-primary.btn-topmny. Contact-us That one works And this one div.botmenu(ng-show='app.menushow') .btn-toolbar .menucontainer.col-lg-6.col-offset-4 a(href="/boompad") .button .btn.btn-sm.col-md-1.btn-primary.btn-topmny. About .button .btn.btn-md.col-md-1.btn-xlarge. Make Music a(href="/Config") .button .btn.btn-md.col-md-1.btn-xlarge. Configure a(href="/") .button .btn.btn-md.col-md-1.btn-xlarge. Home a(href="/Login") .button .btn.btn-md.col-md-1.btn-xlarge. Login The CSS that controls it body { font-family: 'Montserrat', sans-serif; -webkit-font-smoothing: antialiased; background-color: #525252 !important; } .btn-topmny { width: 75px; } .btn-xlarge { background-color: #888; filter: blur(5px); height: 175px; width: 175px; padding: 48px 28px; font-size: 22px; line-height: normal; -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; position: relative; border: 2 !important; margin-left: 15px; margin-bottom: 25px; cursor: pointer; -webkit-font-smoothing: antialiased; font-weight: bold !important; box-shadow: 0 10 0 #006; #ccc } .btn-xlarge:focus { outline: 0; } .btn-xlarge:hover { top: 2px; } .btn-xlarge:active { top: 6px; } .topcontainer { postition: absolute; top: 5; } .menucontainer { position: absolute; bottom: 0; A: Using col-lg-* or col-md-* or col-sm-* values will become horizontal at some point when the screen become smaller than its supported sizes. The standard screen sizes are in the bootstrap site url: http://getbootstrap.com/css/#grid-options lg for screen >= 1170px will be horizontal. same for the following. md >= 970px sm >= 750px So, if you want the elements to be horizontal no matter what the screen size is, then we need to use col-xs-* values. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: How to decipher this string from sql table? I have this string in a table. [0-9]+(\*+)? ?([0-9]+)?(\*+)? ?([0-9]+)? I understand that 0-9 means any number from 0 to 9, but the rest... what is the difference between [] and (), what does ? or + or / or * mean? What is the space between? ? ? How do I decipher it? What is this called? Are all these wild cards? A: It is called regrex (see regular expression) Regular expressions are patterns used to match character combinations in strings. These patterns are used with the exec and test methods of RegExp, and with the match, replace, search, and split methods of String. here
{ "pile_set_name": "StackExchange" }
Q: Force action bar item into overflow In my app, I have two menu items, one a settings icon and the other a string of text "Quick Sites". This "Quick Sites" text takes up alot of space on the action bar. This isn't a problem on tablets but on phones with smaller, lower res displays, it takes up alot of room. It really takes away from the main part of the app. Unlike what other people have asked about this on here, I don't want to force the overflow icon to appear, I want to force the "Quick Sites" item into the overflow so that it doesn't take up some much room on certain phones. Is this possible since I only have two menu items? I've tried setting it to ifRoom but it still shows it, no matter how low res the screen is. A: Use never to force the item into the overflow menu: android:showAsAction="never" Aynway, you can set an icon to the menu item and use ifRoom|withText. This should result in showing only the icon if there is space, but showing the text + icon on large displays.
{ "pile_set_name": "StackExchange" }
Q: Difficulty proving / disproving the following equalities relations ( Big Ω) I have left with some functions I can't find witenesses for proving/disproving Big Ω equalities relations. Here are the three relations: $ \sum\limits_{i=1}^{n} (i^3 - i ^2) = \Omega(n^4) $ $log(n-\sqrt{n}) = \Omega(logn)$ $log(n+\sqrt{n}) = \Omega(logn)$ For the first one I tried to split the sum but to no avail. The second and the third - I don't even have an idea how to start proving/disproving this equality.. Thank you very much ! A: $$ S_1 = \sum_{k=1}^{n}(k^3-k^2)\geq \frac{n^4}{4}-\frac{n^3}{3} = \Omega (n^4) $$ The $\geq$ is due to comparison with the integral. $$ S_2=\log (n-\sqrt{n})=\log (\sqrt{n}(\sqrt{n}-1))\geq \frac{1}{2}\log n + \frac{1}{2} \log n - \log 2 \geq \log n -\log 2 = \Omega(\log n) $$ The first $\geq$ is due to $\log (\sqrt{n}-1) \geq \log \big( \frac{\sqrt{n}}{2} \big) $ can you handle the third one from here?
{ "pile_set_name": "StackExchange" }
Q: PHP: Regular Expression to delete text from a string if condition is true I have a variable containing a string. The string can come in several ways: // some examples of possible string $var = 'Tom Greenleaf (as John Dunn Hill)' // or $var = '(screenplay) (as The Wibberleys) &' // or $var = '(novella "Four Past Midnight: Secret Window, Secret Garden")' I need to clean up the string to get only the first element. like this: $var = 'Tom Greenleaf' $var = 'screenplay' $var = 'novella' I know this is a bit complicated to do but there is a pattern we can use. Looking at the first variable, we can first check if the string contains the text ' (as'. If it does then we need to delete ' (as' and everything that comes after that. In the second variable the rule we made in the first one also applies. We just need also to delete the parenthesis . In the third variable if ' (as' was not found we need to get the first word only and then delete the parenthesis. Well, thas all. I just need someone to help me do it because I'm new to PHP and I don't know regular expressions.... or another way to do it. Thanks!!!! A: Try this regular expression: (?:^[^(]+|(?<=^\()[^\s)]+) This will get you either anything up to the first parenthesis or the first word inside the first parenthesis. Together with preg_match: preg_match('/(?:^[^(]+|(?<=^\\()[^\\s)]+)/', $var, $match);
{ "pile_set_name": "StackExchange" }
Q: The SOAP or REST way I'm implementing a mobile app that would communicate with Magento, there is a lot of functions/endpoints not implemented in SOAP or REST api, so im definitely going to extend whichever im going to consume. But the question is which should i use, The REST api apparently needs oAuth and end-user authroization, and from i understand there is no way to bypass this. But i dont want to do that, I just want to access the api and start firing request without the user authorization or prompting him with a dialog. From what i read the SOAP fits better with what im doing here, it just needs an api user and key. Can you guys confirm this, should i go for the SOAP and extend it when needed. Regards. A: If this is purely read only data driven, You would be are better off push/polling Magento's API data into some data structure/DB to CDN and possibly cache locally. Scaling becomes a lot easier and your authentication problem isn't an obstacle anymore. But this purely depends on the requirements of the mobile app. Magento has this authentication for a reason, as it exposes both Customer and Backend facing functionality. Someone could easily sniff out the URLs you are using and have lots of fun if there was no authentication. And for pete's sake use SSL! :) In the end the purpose of the mobile app is what should be most considered. To answer your question SOAP vs REST: http://spf13.com/post/soap-vs-rest REST is most usually the answer.
{ "pile_set_name": "StackExchange" }
Q: Can you nest a Spark Dataframe in another Dataframe? In spark I want to be able to parallelise over multiple dataframes. The method I am trying is to nest dataframes in a parent dataframe but I am not sure the syntax or if it is possible. For example I have the following 2 dataframes: df1: +-----------+---------+--------------------+------+ |id |asset_id | date| text| +-----------+---------+--------------------+------+ |20160629025| A1|2016-06-30 11:41:...|aaa...| |20160423007| A1|2016-04-23 19:40:...|bbb...| |20160312012| A2|2016-03-12 19:41:...|ccc...| |20160617006| A2|2016-06-17 10:36:...|ddd...| |20160624001| A2|2016-06-24 04:39:...|eee...| df2: +--------+--------------------+--------------+ |asset_id| best_date_time| Other_fields| +--------+--------------------+--------------+ | A1|2016-09-28 11:33:...| abc| | A1|2016-06-24 00:00:...| edf| | A1|2016-08-12 00:00:...| hij| | A2|2016-07-01 00:00:...| klm| | A2|2016-07-10 00:00:...| nop| So i want to combine these to produce something like this. +--------+--------------------+-------------------+ |asset_id| df1| df2| +--------+--------------------+-------------------+ | A1| [df1 - rows for A1]|[df2 - rows for A1]| | A2| [df1 - rows for A2]|[df2 - rows for A2]| Note, I don't want to join or union them as that would be very sparse (I actually have about 30 dataframes and thousands of assets each with thousands of rows). I then plan to do a groupByKey on this so that I get something like this that I can call a function on: [('A1', <pyspark.resultiterable.ResultIterable object at 0x2534310>), ('A2', <pyspark.resultiterable.ResultIterable object at 0x25d2310>)] I'm new to spark so any help greatly appreciated. A: TL;DR It is not possible to nest DataFrames but you can use complex types. In this case you could for example (Spark 2.0 or later): from pyspark.sql.functions import collect_list, struct df1_grouped = (df1 .groupBy("asset_id") .agg(collect_list(struct("id", "date", "text")))) df2_grouped = (df2 .groupBy("asset_id") .agg(collect_list(struct("best_date_time", "Other_fields")))) df1_grouped.join(df2_grouped, ["asset_id"], "fullouter") but you have to be aware that: It is quite expensive. It has limited applications. In general nested structures are cumbersome to use and require complex and expensive (especially in PySpark) UDFs.
{ "pile_set_name": "StackExchange" }
Q: Falsified voting in Stackoverflow My stackoverflow account is suspended due to falsified voting.But I know i m very loyal and most of time I gave answer what my Sir has thought rather than googling.What vote i got is not by me but by stackoverflow users then how they can see it is wrong voting. After reading so many docs and learning and being loyal I got information that your account is suspended.Really I am feeling insulted for being loyal. Why my account is suspended? A: From what I can see, with my non-mod powers, a user upvoted 93 of your answers serially and got deleted. I'm not certain, because I'm not a mod; a mod would have all the details. From what I see, though, it looks like you made an account and upvoted all of your answers with it. Don't do that. After the suspension is over, you will get all your (legitimate) rep back. (You won't get the 930 rep from the serial voting, of course.)
{ "pile_set_name": "StackExchange" }
Q: Update start urls at scrapinghub hosted Scrapy project via API call My Scrapy spider is hosted at scrapinghub. It is managed via run spider API call. The only thing that changes in spider from call to call is a list of start urls. The list may vary from 100 urls to couple thousand. What is the best way to update start urls in this scenario? From what I see there is no direct option in SH API for this. I am thinking of updating MySql with list of urls and once updated send simple Run job API call. (Start urls will be generated from MySql table). Any comments on such solution or other options? My current setup is as follows. def __init__(self, startUrls, *args, **kwargs): self.keywords = ['sales','advertise','contact','about','policy','terms','feedback','support','faq'] self.startUrls = startUrls self.startUrls = json.loads(self.startUrls) super(MySpider, self).__init__(*args, **kwargs) def start_requests(self): for url in self.startUrls: yield Request(url=url) A: You can pass parameters to scrapy spider and read them inside your spider. Send list of URLs encoded as JSON and then decode them, and now fire requests. class MySpider(scrapy.Spider): def __init__(self, startUrls, *args, **kwargs): self.startUrls = startUrls self.startUrls = json.loads(self.startUrls) super(MySpider, self).__init__(*args, **kwargs) def start_requests(self): for url in self.startUrls: yield Request(url=url ... ) And here is how you run send this parameter to your spider. curl -u APIKEY: https://app.scrapinghub.com/api/run.json -d project=PROJECT -d spider=SPIDER -d startUrls="JSON_ARRAY_OF_LINKS_HERE" Your scrapinghub.yml file should be like this projects: default: 160868
{ "pile_set_name": "StackExchange" }
Q: Example of the right way to use QThread in PyQt? I'm trying to learn how to use QThreads in a PyQt Gui application. I have stuff that runs for a while, with (usually) points where I could update a Gui, but I would like to split the main work out to its own thread (sometimes stuff gets stuck, and it would be nice to eventually have a cancel/try again button, which obviously doesn't work if the Gui is frozen because the Main Loop is blocked). I've read https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/. That page says that re-implementing the run method is not the way to do it. The problem I am having is finding a PyQt example that has a main thread doing the Gui and a worker thread that does not do it that way. The blog post is for C++, so while it's examples do help, I'm still a little lost. Can someone please point me to an example of the right way to do it in Python? A: Here is a working example of a separate worker thread which can send and receive signals to allow it to communicate with a GUI. I made two simple buttons, one which starts a long calculation in a separate thread, and one which immediately terminates the calculation and resets the worker thread. Forcibly terminating a thread as is done here is not generally the best way to do things, but there are situations in which always gracefully exiting is not an option. from PyQt4 import QtGui, QtCore import sys import random class Example(QtCore.QObject): signalStatus = QtCore.pyqtSignal(str) def __init__(self, parent=None): super(self.__class__, self).__init__(parent) # Create a gui object. self.gui = Window() # Create a new worker thread. self.createWorkerThread() # Make any cross object connections. self._connectSignals() self.gui.show() def _connectSignals(self): self.gui.button_cancel.clicked.connect(self.forceWorkerReset) self.signalStatus.connect(self.gui.updateStatus) self.parent().aboutToQuit.connect(self.forceWorkerQuit) def createWorkerThread(self): # Setup the worker object and the worker_thread. self.worker = WorkerObject() self.worker_thread = QtCore.QThread() self.worker.moveToThread(self.worker_thread) self.worker_thread.start() # Connect any worker signals self.worker.signalStatus.connect(self.gui.updateStatus) self.gui.button_start.clicked.connect(self.worker.startWork) def forceWorkerReset(self): if self.worker_thread.isRunning(): print('Terminating thread.') self.worker_thread.terminate() print('Waiting for thread termination.') self.worker_thread.wait() self.signalStatus.emit('Idle.') print('building new working object.') self.createWorkerThread() def forceWorkerQuit(self): if self.worker_thread.isRunning(): self.worker_thread.terminate() self.worker_thread.wait() class WorkerObject(QtCore.QObject): signalStatus = QtCore.pyqtSignal(str) def __init__(self, parent=None): super(self.__class__, self).__init__(parent) @QtCore.pyqtSlot() def startWork(self): for ii in range(7): number = random.randint(0,5000**ii) self.signalStatus.emit('Iteration: {}, Factoring: {}'.format(ii, number)) factors = self.primeFactors(number) print('Number: ', number, 'Factors: ', factors) self.signalStatus.emit('Idle.') def primeFactors(self, n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.button_start = QtGui.QPushButton('Start', self) self.button_cancel = QtGui.QPushButton('Cancel', self) self.label_status = QtGui.QLabel('', self) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.button_start) layout.addWidget(self.button_cancel) layout.addWidget(self.label_status) self.setFixedSize(400, 200) @QtCore.pyqtSlot(str) def updateStatus(self, status): self.label_status.setText(status) if __name__=='__main__': app = QtGui.QApplication(sys.argv) example = Example(app) sys.exit(app.exec_())
{ "pile_set_name": "StackExchange" }
Q: Make failing when trying to build Octave-4.0.0 from source The error message I'm getting is:- Makefile:3060: warning: overriding recipe for target 'check' Makefile:2415: warning: ignoring old recipe for target 'check' GEN run-octave /bin/bash: ./build-aux/move-if-change: Permission denied Makefile:3066: recipe for target 'run-octave' failed make: *** [run-octave] Error 126 I've tried sudo make (because of the permission thing) but it hasn't helped. A: Problem solved. Closer inspection showed that most of the shell files in the source directory had "Forbidden" as their file permissions. Rather than reset them manually I did make clean deleted the source file and downloaded a new source file and the installation went without a hiccup. The old source file was from a home partition backup after updating my operating system from LMDE1 to LMDE2. I can only assume that this whole backing up process was the root cause of the problem.
{ "pile_set_name": "StackExchange" }
Q: Spark 1.5.2: Grouping DataFrame Rows over a Time Range I have a df with the following schema: ts: TimestampType key: int val: int The df is sorted in ascending order of ts. Starting with row(0), I would like to group the dataframe within certain time intervals. For example, if I say df.filter(row(0).ts + expr(INTERVAL 24 HOUR)).collect(), it should return all the rows within the 24 hr time window of row(0). Is there a way to achieve the above within Spark DF context? A: Generally speaking it is relatively simple task. All you need is basic arithmetics on UNIX timestamps. First lets cast all timestamps to numerics: val dfNum = df.withColumn("ts", $"timestamp".cast("long")) Next lets find minimum timestamp over all rows: val offset = dfNum.agg(min($"ts")).first.getLong(0) and use it to compute groups: val aDay = lit(60 * 60 * 24) val group = (($"ts" - lit(offset)) / aDay).cast("long") val dfWithGroups = dfNum.withColumn("group", group) Finally you can use it as a grouping column: dfWithGroups.groupBy($"group").agg(min($"value")). If you want meaningful intervals (interpretable as timestamps) just multiply groups by aDay. Obviously this won't handle complex cases like handling daylight saving time or leap seconds but should be good enough most of the time. If you need to handle properly any of this you use a similar logic using Joda time with an UDF.
{ "pile_set_name": "StackExchange" }
Q: How to deal with missing data for only some categories Or in other words, data for category A is irrelevant for category B. So it is not present, how can imputing missing data distort/effect learning models broadly. I can't find any logic how to deal with this relative data. So I am sorry that I don't show any effort. In the following example, geographical zone is only present for Gaz entries. Data sample: A: There are three types of missing data: Missing Completely At Random (MCAR), Missing At Random (MAR) and Missing Not At Random (MNAR). Your case is the second, where according to wikipedia it: occurs when the missingness is not random, but where missingness can be fully accounted for by variables where there is complete information This means that the presence or not of entries in zone can be derived from the column Produit. Because the values aren't missing completely at random, normal imputation techniques (e.g. fill with the most common value) shouldn't be applied. Instead I'd recommend treating the missing values as their own category. Just create a category (let's say not available) and fill the missing with this value. From a data science view this makes more sense.
{ "pile_set_name": "StackExchange" }
Q: Set File Paths - Perl Script What I am trying to do is take the bcp log file out (log folder) and move it to another directory with a current time (history folder). However, every time I execute this Perl script, it states "No such file or directory at line 18" Below is my code: ## SET FILE PATHS my $myBCPDump = "//Server-A/X:/Main Folder/Log/bcpLog.txt"; my $myBCPLog = "//Server-A/X:/Main Folder/History/bcpLog" . $myDate . ".txt"; my $isJunk = "rows successfully|rows sent to SQL|packet size|Starting copy|^\n|Clock Time"; open (LOGFILE, ">$myBCPLog") or die $!; ##Line 18 close (LOGFILE); I know that it can't find the file or directory is because the ##SET FILE PATHS is not being executed properly and I am not sure why. A: //Server-A/X:/... isn't a valid path in Windows. A colon (:) isn't allowed in a path except after a drive letter (C:...). But you have a UNC path (\\server\share\... aka //server/share/...), and those don't have a drive component. Did you perhaps mean //Server-A/X$/...? If so, "//Server-A/X:/..." should be changed to either of "//Server-A/X\$/..." and '//Server-A/X$/...'
{ "pile_set_name": "StackExchange" }
Q: No module named Pandas in Jupyter Notebook I know there is a huge number of questions on this topics, but not even one worked for me, not here, not on github. I have installed anaconda2 for macOS a few days before. I know pandas come with Anaconda by default, and in the last year I haven't any trouble with any python package on Ubuntu, but now I have a weird problem. When I run jupyter notebook and import pandas as pd, I got an error: no module named pandas. It's not just about pandas, none of libraries work. When I try to install pandas with conda, return me Requirement already satisfied. The same with pip. Also, I have tried to run jupyter notebook with a full path to jupyter package, and doesn't help either. Probably there is a problem with PATH, but I'm not really good with that and not sure what to do. But everything works fine when I run iPython in terminal, python in terminal, just doesn't work in jupyter notebook. > python --version : Python 2.7.15 :: Anaconda, Inc. > which python :/anaconda2/bin/python > which jupyter-notebook: /anaconda2/bin/jupyter-notebook > conda env list: conda environments: base * /anaconda2 Thanks for any help in advance. A: Try this in jupyter cell: !pip install pandas
{ "pile_set_name": "StackExchange" }
Q: Elixir Install on Ubuntu 17.04 Zesty Fails Just upgraded to Ubuntu 17.04 (zesty) and I'm having trouble installing elixir. I installed Erlang 20.1 from their website for Ubuntu 17.04 and this install seems successful. I downloaded esl-erlang_20.1-1~ubuntu-zesty_amd64.deb then ran: sudo apt-get install libsctp1 sudo dpkg -i esl-erlang_20.1-1~ubuntu~zesty_amd64.deb sudo apt install -y esl-erlang Now if enter the erlang shell and type "erlang:system_info(otp_release). i get "20" I then went to https://www.ubuntuupdates.org/package/core/artful/universe/base/elixir and downloaded the deb and did similar steps as above to install. I also tried install elixir from apt (sudo apt-get install elixir) but all produce the same issue. I run $elixir --version and it crashes and produced a dump file. > =erl_crash_dump:0.3 Sat Oct 21 12:37:40 2017 Slogan: init terminating in do_boot > ({{badmatch,error},[{Elixir.System,build,0,[{_},{_}]},{Elixir.System,build_info,0,[{_},{_}]},{Elixir.Kernel.CLI,parse_shared,2,[{_},{_}]},{Elixir.Kernel.CLI,shared_option?, > System version: Erlang/OTP 20 [erts-9.0.4] [source] [64-bit] [smp:4:4] > [ds:4:4:10] [async-threads:10] [kernel-poll:false] Compiled: Fri Sep > 1 13:16:32 2017 Taints: erl_tracer Atoms: 7992 Calling Thread: > scheduler:1 > =scheduler:1 Scheduler Sleep Info Flags: Scheduler Sleep Info Aux Work: ASYNC_READY_CLEAN Current Port: Run Queue Max Length: 0 Run > Queue High Length: 0 Run Queue Normal Length: 1 Run Queue Low Length: > 0 Run Queue Port Length: 0 Run Queue Flags: NONEMPTY_NORMAL | > OUT_OF_WORK | HALFTIME_OUT_OF_WORK | NONEMPTY | EXEC Current Process: > <0.0.0> Current Process State: Running Current Process Internal State: > ACT_PRIO_NORMAL | USR_PRIO_NORMAL | PRQ_PRIO_NORMAL | ACTIVE | RUNNING > | TRAP_EXIT | ON_HEAP_MSGQ Current Process Program counter: > 0x00007fb073da8b10 (init:crash/2 + 24) Current Process CP: > 0x0000000000000000 (i Thank you! A: I was able to solve this problem by compiling elixir manually. mkdir $HOME/bin cd $HOME/bin git clone https://github.com/elixir-lang/elixir.git cd elixir make clean test export PATH="$PATH:$HOME/bin/elixir/bin" I'm not too sure where I was supposed to put it but this was good enough for now.
{ "pile_set_name": "StackExchange" }
Q: Windows - automatic backup of usb drives I'm very prone to lose usb dongles, I want now to configure windows 'scheduled task' that each time it sees an event with 'insertion' of my drive it copys all the content in a specific folder (c>\usb_backups\<UUID>\<today's date>\) Now I'm tracking event 2003 (usb drive mount) that contains the ID, but I'm not able to discover on wich drive letter the drive is mounted on. The script invoked should be something like: @xcopy /E /C /Q /H /Y %%sourcedrive%%\ %systemdrive%\usb_backups\%%UUID%%\%%date%%\ But, right now, I don't know how to set %%sourcedrive%% and %%UUID%% variables. A: It appears that USBDLM would work great, it describes itself as: USBDLM is a Windows service that gives control over Windows' drive letter assignment for USB drives. Running as service makes it independent of the logged on user's privileges, so there is no need to give the users the privilege to change drive letters. It automatically solves conflicts between USB drives and network or subst drives of the currently logged on user. Furthermore you can define new default letters for USB drives and much more. It works on Windows XP to Windows 10. It's html help page [apparently translated from German?] says you can do things like one of these to copy files with a click, or automatically: let show an balloontip on drive arrival which shows the assigned drive letter run something on click on the balloontip executing an autorun, also depending on the criterions mentioned above It's settings are either in an .INI file, or the registry The desired drive letters or mount points and other settings are defined in a text file called USBDLM.INI located in the same place as the USBDLM.EXE. Modern applications often store their settings in the Windows registry but I don't like that. INI files are the 'classic' approach. ... Settings in the Registry: Since V3.3.1 USBDLM can read its settings from the registry too. It reads from HKLM/Software/Uwe Sieber/USBDLM If this registry key exists, then the USBDLM.INI is ignored! Only the log file settings are read from the INI then. Actions on click on the Balloontip Similar to autorun events you can define actions on left, right and middle click on the balloon. ;on left click, open a simple Explorer window with the drive [OnBalloonClick] open="%windir%\explorer" %drive% ;on right click, open a foto software [OnBalloonRClick] open="C:\Program Files\FotoSoft\fotosoft.exe" %drive% You can define several events depending on criterions as shown for [AutoRun]. 2. Global AutoRun settings in the USBDLM.INI 2.1 Triggered by volumes Sample 2: If the file DATA.TXT exist, copy it from the drive to C:\Data [OnArrival1] FileExists=%drive%\DATA.TXT open="%windir%\System32\cmd.exe" /c copy "%drive%\DATA.TXT" "C:\Data" cmd is the Windows command processor, /c means "execute command and end then", copy is a command which the cmd knows and copies files. Also useful might be to copy files on removal, BalloonTips have on removal settings, or an autorun (possibly time limited): AutoRun on and after Removal In analogy to the OnArrival function USBDLM can execute a command-line when a drive is "prepared for safe removal" and after a drive has been removed. 1. On preparation for safe removal When a USB or Firewire drive becomes "prepared for safe removal" the USBDLM can react while the drive is still available. This should not take too long, the maximum time is 30 Seconds under XP, and 15 Seconds since Vista/Win7. But while the notification is processed, no other events can be handled. Therefore USBDLM wait up to 10 Seconds only. If the started process is still running after this time, then USBDLM rejects the removal request. Windows then says "USBDLM prevents the removal...". Sample to copy the file c:\test.txt to the folder \backup on the drive to remove: [OnRemovalRequest] open="%windir%\System32\cmd.exe" /c copy "C:\test.txt" %drive%\backup As in the first sample but only if the file \backup\test.txt exists on the drive to remove: [OnRemovalRequest] FileExists=%drive%\backup\test.txt open="%windir%\System32\cmd.exe" /c copy "C:\test.txt" %drive%\backup There's several Variables available, like these useful looking ones Variable Description Sample -------- ----------- ------ %DriveLetter% drive letter X %Drive% drive X: %Root% drive root X:\ %DevName% device name Corsair Flash Voyager %Label% volume label My flash drive %Size% volume size 16 GB %KernelName% kernel name \Device\Harddisk3\DP(1)0-0+d %PartitionName% Partition name \Device\Harddisk2\Partition1 %DiskSignature% disk signature MBR 9810ABEF %GptDiskIdGuid% GPT disk ID GUID {GUID} %PureVolumeName% pure volume name Volume{GUID} %DateISO% Date (yyyy-mm-dd) 2016-10-31 %Time% Time (hh:mm:ss) 12:00:00 [Thanks to montonero's comment for the idea]
{ "pile_set_name": "StackExchange" }
Q: Getting index of inserted rows from a MySQL database I'm using Java (jdbc) to interact with a MySQL database. I have table with a primary index which is AUTO INCREMENT. When I insert a row, I need to get the index it just received. How do I do that? A: From: http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html#connector-j-usagenotes-last-insert-id stmt.executeUpdate( "INSERT INTO autoIncTutorial (dataField) " + "values ('Can I Get the Auto Increment Field?')", Statement.RETURN_GENERATED_KEYS); // // Example of using Statement.getGeneratedKeys() // to retrieve the value of an auto-increment // value // int autoIncKeyFromApi = -1; rs = stmt.getGeneratedKeys(); if (rs.next()) { autoIncKeyFromApi = rs.getInt(1); } else { // throw an exception from here } rs.close(); rs = null;
{ "pile_set_name": "StackExchange" }
Q: Javascript select cells in a table Lasso-style I'm really new to Javascript and I'm having trouble creating a Lasso - style table selection tool. Basically, I want to be able to drag the mouse over a table and have all the cells in that area get highlighted, so I can do something later with the selected cells. Here is a very buggy fiddle of what I am trying to achieve. http://jsfiddle.net/kooldave98/ad5Z9/ var element = $("#rectangle"); // on mousedown $(window).mousedown(function (e1) { // first move element on mouse location element.show().css({ top: e1.pageY, left: e1.pageX }); // resize that div so it will be resizing while moouse is still pressed var resize = function (e2) { // you should check for direction in here and moves with top or left element.width(e2.pageX - e1.pageX); element.height(e2.pageY - e1.pageY); }; $(window).mousemove(resize); // and finally unbind those functions when mouse click is released var unbind = function () { $(window).unbind(resize); $(window).unbind(unbind); }; $(window).mouseup(unbind); }); I need to be able to move the selection tool in any direction within the table and select additional cells afterwards using the "ctrl" key. Any help will be greatly appreciated. A: You can do this using the jQuery UI Selectable widget.
{ "pile_set_name": "StackExchange" }
Q: Orthogonality locus is a curve Consider two smooth vector fields $X$, $Y$ defined on a manifold $M$. I am interesting in the set $L=\{q\in M;\; \langle X(q),Y(q)\rangle=0\}$. I am wondering what is the geometry of the set $L$. Intuitively, I see the following cases: $L=\emptyset$ $L$ is a singleton $L$ is a union of smooth curves $L=M$ but I don't know which case appears generically A: In the case $M=\mathbb R^n$ (with $n\ge 2$), $L$ can be literally any closed subset. To see this, let $K\subset\mathbb R^n$ be an arbitrary closed subset, and let $f\colon \mathbb R^n\to \mathbb R$ be a smooth function whose zero set is exactly $K$. (Such a function exists by Theorem 2.29 in my Introduction to Smooth Manifolds, 2nd ed.) Then define $X$ and $Y$ by \begin{align*} X & = \frac{\partial}{\partial x^1},\\ Y & = \frac{\partial}{\partial x^2} + f(x) \frac{\partial}{\partial x^1}. \end{align*} Then $L=K$. On an arbitrary smooth manifold, there may be some topological restrictions. For example, to obtain vector fields for which $L=\emptyset$, there must be two independent global vector fields, which is not always possible. But $L$ can still be pretty awful -- for example, if $K$ is any closed subset contained in the domain of a coordinate chart $U$, you can always find vector fields for which $L\cap U = K$.
{ "pile_set_name": "StackExchange" }
Q: procedures in mySql I'm actually trying to insert value into table using a procedure.This is my table code create table employeeTable( employeeId varchar(20), employeeName varchar(20), qualification varchar(20), cadre varchar(15), age numeric(3), sex char(1), occupation varchar(10), dateOfBirth date, address varchar(50), city varchar(15), employeePhoto blob, constraint pk_employeeId_employeeTable primary key(employeeId) ); My insert procedure is delimiter // create procedure insertEmployee(in employeeId varchar(20),in employeeName varchar(20), in qualification varchar(20),in cadre varchar(15),in age numeric(3),in sex char(1), in occupation varchar(10),in dateOfBirth date,in address varchar(50),in city varchar(15), in employeePhoto blob) begin insert into employeetable values(upper(employeeId),employeeName,qualification, cadre,age,sex,occupation, str_to_date(dateOfBirth,'%d-%m-%Y'),address,city,employeePhoto); end;// delimiter ; And I'm trying to call this procedure with following parameters call insertEmployee('A001','Murugan','Phd','Manager',12,'M','service','30-07-1994', '30,PNG nagar,pollachi','Coimbatore',null); But values are not getting inserted and it's showing an error #1048 - Column 'dateOfBirth' cannot be null.. What is the problem here?? A: delimiter // create procedure insertEmployee(in employeeId varchar(20),in employeeName varchar(20), in qualification varchar(20),in cadre varchar(15),in age numeric(3),in sex char(1), in occupation varchar(10),in dateOfBirth varchar(15),in address varchar(50),in city varchar(15), in employeePhoto blob) begin insert into employeetable values(upper(employeeId),employeeName,qualification, cadre,age,sex,occupation, str_to_date(dateOfBirth,'%d-%m-%Y'),address,city,employeePhoto); end;// delimiter ; Try this procedure. You were accpeting the dateOfBirth as a date object in the parameter list. It should have been a VARCHAR as that is how it is passed to the procedure.
{ "pile_set_name": "StackExchange" }
Q: Calculating Running Totals - TSQL? I am trying to calculate running totals over a time period with each time period rolling up into the next period for a cumulative total. There will be multiple events in the real data along with multiple event types and cost types - but in the example below, I'm only showing one event and one type. If I can get this to work, I can make it work for the other types as well. The screenshot below is my expected output: I would like to sum the amounts for each month's number for both types of reserves: Expense & Indemnity - so month 1 would have a total of $31.7k. Month 2 has a total of approximately $4.1k so that would be added to the prior months' total giving me 35.9k. And this running total should continue on to the last record. I am trying various ways to sum through a window function but so far I am unable to get the expected outcome. Any suggestions on how to achieve this total? Sample data is found below: CREATE TABLE #temptable ( Catastrophe VARCHAR (60), Type VARCHAR (256), CostType VARCHAR (256), FirstLossDate DATE, MonthNumber INT, Amount DECIMAL (38, 6) ); INSERT INTO #temptable ( Catastrophe, Type, CostType, FirstLossDate, MonthNumber, Amount) VALUES ('Hurricane Humberto', 'Reserve', 'Expense - A&O', N'2007-09-13', 1, 13460.320000), ('Hurricane Humberto', 'Reserve', 'Indemnity', N'2007-09-13', 1, 18314.610000), ('Hurricane Humberto', 'Reserve', 'Expense - A&O', N'2007-09-13', 2, -1589.340000), ('Hurricane Humberto', 'Reserve', 'Indemnity', N'2007-09-13', 2, 5750.000000), ('Hurricane Humberto', 'Reserve', 'Expense - A&O', N'2007-09-13', 3, -2981.250000), ('Hurricane Humberto', 'Reserve', 'Indemnity', N'2007-09-13', 3, -10000.000000), ('Hurricane Humberto', 'Reserve', 'Expense - A&O', N'2007-09-13', 4, 0.000000), ('Hurricane Humberto', 'Reserve', 'Indemnity', N'2007-09-13', 4, 0.000000), ('Hurricane Humberto', 'Reserve', 'Expense - A&O', N'2007-09-13', 5, 0.000000), ('Hurricane Humberto', 'Reserve', 'Indemnity', N'2007-09-13', 5, 0.000000); SELECT Catastrophe, Type, CostType, FirstLossDate, MonthNumber, Amount, SUM ( Amount ) OVER (PARTITION BY Catastrophe, MonthNumber, Type ORDER BY MonthNumber ROWS UNBOUNDED PRECEDING ) AS RunningTotals, SUM ( Amount ) OVER (PARTITION BY Catastrophe, Type, MonthNumber) AS RunningTotal2 FROM #temptable ORDER BY Catastrophe, Type, MonthNumber; DROP TABLE #temptable; A: Try this one: SELECT Catastrophe, Type, CostType, FirstLossDate, MonthNumber, Amount, SUM(Amount) OVER (PARTITION BY Catastrophe, Type ORDER BY MonthNumber asc RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS RunningTotals FROM temptable ORDER BY Catastrophe, Type, MonthNumber; I think your main problem was with partition by clause - it is meant to "reset" the calculation - so you can calculate windowing function for many groups. As per documentation: PARTITION BY Divides the query result set into partitions. The window function is applied to each partition separately and computation restarts for each partition. REF SQL FIDDLE
{ "pile_set_name": "StackExchange" }
Q: Unable to select data from DB via Sequelize in Node.js Why does the following code give me an error? var Sequelize = require('sequelize'); var sequelize = new Sequelize('schema', 'root', ''); var Foo = sequelize.define('Foo', { name: Sequelize.STRING }); sequelize.sync().then(function() { Foo.create({ name: 'some name' }).then(function() { Foo.findAll({ where: { name: { $like: '%s%' } } }).then(function(result) { console.log(result.rows.length); }); }); }); Output Executing (default): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Foos` AS `Foo` WHERE `Foo`.`name` LIKE '%s%'; Unhandled rejection TypeError: Cannot read property 'length' of undefined at null.<anonymous> (E:\work\projects\src\preorders\server.js:13:30) at tryCatcher (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\util.js:26:23) at Promise._settlePromiseFromHandler (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\promise.js:507:31) at Promise._settlePromiseAt (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\promise.js:581:18) at Promise._settlePromises (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\promise.js:697:14) at Async._drainQueue (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\async.js:123:16) at Async._drainQueues (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\async.js:133:10) at Async.drainQueues (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\async.js:15:14) at process._tickCallback (node.js:419:13) And here is the "dependencies" option from my package.json file: "dependencies": { "mysql": "^2.9.0", "sequelize": "^3.13.0" } A: The variable result in the callback should already be an array of results and not some object holding rows. Changing it to this should get you the number of rows: Foo.findAll({ where: { name: { $like: '%s%' } } }).then(function(result) { console.log(result.length); }); Dump all of the data to see if it's actually the data you want.
{ "pile_set_name": "StackExchange" }
Q: XQuery that selects node but omits returning child nodes I'm attempting to create an xquery expression that will return selected nodes but will not return their children. This is probably best illustrated with an example. I have the following myNode node: <myNode> <myElements id="1"> <myElement key="one">aaa</myElement> <myElement key="two" >bbb</myElement> <myElement key="three">ccc</myElement> </myElements> <myElements id="2"> <myElement key="one">ddd</myElement> <myElement key="two" >eee</myElement> <myElement key="three">fff</myElement> </myElements> </myNode> I am interested in returning the <myElements > nodes, but nothing lower. My desired return would look like the following: <myNode> <myElements id="1" /> <myElements id="2" /> </myNode> or <myNode> <myElements id="1"></myElements> <myElements id="2"></myElements> </myNode> I currently have a xpath expression that would look something like the following (simplified for this illustration), which as expected, is returning the myElement children: $results/myNode/MyElements Am I barking up the wrong tree? Is this even possible in XPath/XQuery? A: Try this recursive algorithm.. xquery version "1.0"; declare function local:passthru($x as node()) as node()* { for $z in $x/node() return local:recurseReplace($z) }; declare function local:recurseReplace($x as node()) { typeswitch ($x) (: Changes based on a condition :) case element(myElements) return <myElements id="{$x/@id}" /> (: IGNORE ANY CHANGES :) case text() return $x case comment() return comment {"an altered comment"} case element() return element {fn:node-name($x)} {for $a in $x/attribute() return $a, local:passthru($x)} default return () }; let $doc := <myNode> <myElements id="1"> <myElement key="one">aaa</myElement> <myElement key="two" >bbb</myElement> <myElement key="three">ccc</myElement> </myElements> <myElements id="2"> <myElement key="one">ddd</myElement> <myElement key="two" >eee</myElement> <myElement key="three">fff</myElement> </myElements> </myNode> return local:recurseReplace($doc)
{ "pile_set_name": "StackExchange" }
Q: Как получить value в form из input? Хочу подставить вместо "ЗНАЧЕНИЕ" текст из инпута text. Как такое делается? <form class="search" method="post" action=".../ЗНАЧЕНИЕ"> <input type="text" name="text" ну и тут всякое> <input type="submit" value="Найти" class="button"> </form> A: HTML: <form class="search" method="post" action=".../ЗНАЧЕНИЕ"> <input id="ho-ho" type="text" name="text"> <input type="submit" value="Найти" class="button"> </form> JS: var inp = document.querySelector('#ho-ho'); var frm = document.querySelector('.search'); inp.addEventListener('change', (event) => { frm.action = inp.value; }); Тест: https://jsfiddle.net/a7nydt62/ P.S. - Скрипт надо добавлять после формы, иначе он выполнится еще до того как браузер догрузит необходимые элементы. <html> <body> <form class="search" method="post" action=".../ЗНАЧЕНИЕ"> <input id="ho-ho" type="text" name="text"> <input type="submit" value="Найти" class="button"> </form> <script> var inp = document.querySelector('#ho-ho'); var frm = document.querySelector('.search'); inp.addEventListener('change', (event) => { frm.action = inp.value; }); </script> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Extjs GridPanel validation how can i do a validation function that get me an error when IN1>OU1 or IN2>OU2 ?? this is my code (a grid panel with roweditor plugin) { xtype: 'gridpanel', height: 250, width: 400, title: 'My Grid Panel', columns: [ { xtype: 'datecolumn', text: 'IN1', dataindex 'F02ORAIN1', field: { xtype: 'timefield', id 'editF02ORAIN1' } }, { xtype: 'datecolumn', dataindex 'F02ORAOU1', text: 'OU1', field: { xtype: 'timefield', id 'editF02ORAOU1' } }, { xtype: 'datecolumn', text: 'IN2', dataindex 'F02ORAIN2', field: { xtype: 'timefield', id 'editF02ORAIN2' } }, { xtype: 'datecolumn', text: 'OU2', dataindex 'F02ORAOU2', field: { xtype: 'timefield', id 'editF02ORAOU2' } } ], plugins: [ Ext.create('Ext.grid.plugin.RowEditing', { }) ] } A: I think the best way is to use field's validator config: // ... { xtype: 'datecolumn', text: 'IN1', dataIndex: 'F02ORAIN1', field: { xtype: 'timefield', id: 'editF02ORAIN1', validator: function(value) { if (!Ext.getCmp('editF02ORAOU1').getValue()) return true; if (this.getValue() > Ext.getCmp('editF02ORAOU1').getValue()) return 'IN1 should be less then OU1'; return true; } } }, { xtype: 'datecolumn', dataIndex: 'F02ORAOU1', text: 'OU1', field: { xtype: 'timefield', id: 'editF02ORAOU1' } }, // ... Here is demo A: Instead of using getCmp (which you should never do unless debugging), get the data to compare to value from the Store.
{ "pile_set_name": "StackExchange" }
Q: Output multi-dimensional array with brackets So I have this and I need to be able to output all of the arrays including brackets within the array. The following example works by calling the index explicitly, but I can't seem to pass a function or a for loop where it is expecting an expression. Also, a string will not do. for (var a in obj) { var dateArray = []; var date = new Date(obj[a]); // var date = new Date('March 29, 2016 14:00:00'); var hours = date.getHours(); var minutes = date.getMinutes(); console.log(date.toString()); console.log(hours); console.log(minutes); dateArray[0] = hours; dateArray[1] = minutes; disabled_time_list.push(dateArray); } for (var i = 0; i < disabled_time_list.length; i++) { console.log(disabled_time_list[i]); } pickertime.set('disable', [ disabled_time_list[0] // [14,0], ]); A: In case anyone ever needs it, this is how I solved the problem: $('.datepicker').change(function() { var datepicker = $('.datepicker').pickadate(); var pickerdate = datepicker.pickadate('picker'); var dateInput = pickerdate.get('value'); var request = $.ajax({ type: "POST", url: 'http://apptsch.dev/index.php/appointment/get_post_date', data: { date: dateInput } }).done(function(){ disabled_time_list = []; var timepicker = $('.timepicker').pickatime(); var pickertime = timepicker.pickatime('picker'); var times_disabled = pickertime.get('disable'); console.log(times_disabled); $.each(times_disabled,function( index, value) { pickertime.set('enable', [ times_disabled[index] ]) }); // end re-enable previously disabled times var result = request.responseText; var obj = jQuery.parseJSON(result); for (var a in obj) { var dateArray = []; var date = new Date(obj[a]); var hours = date.getHours(); var minutes = date.getMinutes(); dateArray[0] = hours; dateArray[1] = minutes; disabled_time_list.push(dateArray); } $.each(disabled_time_list,function( index, value ) { pickertime.set('disable', [ disabled_time_list[index] ]); //end disable }); //end foreach }); //end ajax call }); // end change
{ "pile_set_name": "StackExchange" }
Q: Merge date/time field into email template AMPScript or SSJS? I'm new to Marketing Cloud and I'm trying to find a solution to what I think should be a pretty easy problem. I have an email template in which I would like to insert a date/time, which will be different for every subscriber(it is an appointment date for a reminder email). I have an 'Appointments' data extension where the date/time field is stored, along with the subscriber ID and I wondering the best way to access and display this data inline within my email template. I looked at using the Lookup function in AMPScript to pull in the data I want, but I'm not sure if this is the best approach and I'm not quite sure of the syntax to make sure that data, once retrieved is displayed in my email. EDIT: Here's my final code <div style="display: none">%%[ var @rows, @row, @rowCount, @AppointmentDate var @subscriberID set @subscriberID = AttributeValue("subscriberid") set @rows = LookupRows("Appointments","Contact ID", @subscriberID) set @rowCount = rowcount(@rows) if @rowCount > 0 then set @row = row(@rows,1) /* get row #1 */ set @AppointmentDate = field(@row,"Date") set @AppointmentDate = format(@AppointmentDate,"MM/dd/yyyy") else set @AppointmentDate = "not found" endif ]%% </div> Your appointment date is: %%=v(@AppointmentDate )=%% A: I have some AMPScript lookup examples on my blog. Here's an example, adjusted for the scenario you described: %%[ var @rows, @row, @rowCount, @AppointmentTime var @subscriberID set @subscriberID = AttributeValue("subscriberid") set @rows = LookupRows("Appointments","SubscriberID", @subscriberID) set @rowCount = rowcount(@rows) if @rowCount > 0 then set @row = row(@rows,1) /* get row #1 */ set @AppointmentTime = field(@row,"AppointmentTime") set @AppointmentTime = format(@AppointmentTime,"hh:mm tt") else set @AppointmentTime = "not found" endif ]%% Your appointment time is: %%=v(@AppointmentTime )=%%
{ "pile_set_name": "StackExchange" }
Q: Реализовать проверку редактирования страницы другим пользователем Всем привет. Подскажите пожалуйста как можно по простому реализовать проверку редактирования страницы другим пользователем. Допустим я открыл страницу и реадктирую ее. В этот момент другой пользователь открывает эту же страницу пишет туда что-то и сохраняет, но потом я тоже сохраняю страницу и тем самым перезапишу его труды. Как можно по простому реализовать проверку таких случаев, что бы если я уже открыл редактирование этой страницы, то другому пользователю при открытии редактирования этой страницы выдавалось уведомление, что эту страницу уже редактируют. П.С. лично я сам пока придумал только вариант, когда при открытии редактирования страницы в БД у записи этой страницы в специальное поле ставился мой ID и при сохранении страницы он удалялся. И при открытии другим пользователем этой страницы если мой ID там есть, этому пользователю выдавалось уведомление, но есть проблема. Ведь я могу начать редактировать страницу, потом передумать и тупо закрыть браузер. Но мой ID останется и другие пользователи не смогут редактировать. Все это дело желательно реализовать на php и js Подскажите пожалуйста самый просто вариант решения данной проблемы A: Самый простой вариант -- блокировка (то, что вы и описали). Для блокировок лучше создать отдельную таблицу. Вы можете хранить там не только id пользователя, который захватил блокировку, но и время до которого блокировка захвачена, атрибуты клиента (например редактирую из дома и на работе). Это позволит решить некоторые проблемы с ожиданием. Захватывайте блокировку на небольшое время и автоматически продляйте её при активности пользователя. При отсутствии активности можно вывести сообщение о том, что блокировка будет снята через 10, 9, 8... с кнопкой "Я просто задумался". Закрытие окна (вкладки) браузера обрабатывайте на клиенте и делайте запрос на снятие блокировки. Пользователям ожидающих освобождение блокировки сообщайте кто её захватил (если это не противоречит каким-то идеям работы приложения), возможно они смогут договориться. Начните с простого и наворачивайте фичи по ходу дела. Возможно вы столкнётесь с неочевидными проблемами. Например кто-то будет захватывать много документов и это будет сердить остальных пользователей или кто-то будет редактировать (действительно внося правки) документ очень долго. Или ещё что-то.
{ "pile_set_name": "StackExchange" }
Q: grunt.file write/copy with permissions Is there a way to specify the permissions of a file during a grunt.file.copy(...), except using the 'fs.chmod' after copy has finished? I will have to require the whole 'fs' module otherwise, just for changing the permissions. Will it be a lot of overhead? A: grunt.file.copy does not provide any option for that, unfortunately. But the grunt copy task (from grunt-contrib-copy) has an option for that (options.mode, see https://github.com/gruntjs/grunt-contrib-copy#mode).
{ "pile_set_name": "StackExchange" }
Q: error oauth_problem=signature_invalid for POST i am using magento rest api for get data and it work very well but when i wanna send data return this error "messages": { "error": [ { "code": 401, "message": "oauth_problem=signature_invalid" } ] } i use post man for this ... is there any one that can tell me why i get this error ? A: This is some Magento core/The client using to generate OAuth Signature issue. The client generated signature and Magento generated signatures are mismatching that's the reason behind throwing this error. For temporary testing, to works fine, you can just comment the Magento code that checks the signature and through errors, if it's mismatch Here are the lines that check sinatures. On file app/code/core/Mage/Oauth/Model/Server.php Line number 547 to 549 if ($calculatedSign != $this->_protocolParams['oauth_signature']) { $this->_throwException('', self::ERR_SIGNATURE_INVALID); } Here you can see where $calculatedSign is the Magento calculated signature and $this->_protocolParams['oauth_signature'] is what we sending. For testing purpose, you can comment this lines and work.
{ "pile_set_name": "StackExchange" }
Q: Laravel 5 Form request validation with parameters I am using form request validation and there are some rules that needs external values as a parameters. Here are my validation rules for editing a business profile inside a form request class, public function rules() { return [ 'name' => 'required|unique:businesses,name,'.$business->id, 'url' => 'required|url|unique:businesses' ]; } I can use this on the controller by type hinting it. public function postBusinessEdit(BusinessEditRequest $request, Business $business) { } But how to pass the $business object as a parameter to the rules method? A: There can be many ways to achieve this. I do it as below. You can have a hidden field 'id' in your business form like bellow, {!! Form::hidden('id', $business->id) !!} and you can retrieve this id in FormRequest as below, public function rules() { $businessId = $this->input('id'); return [ 'name' => 'required|unique:businesses,name,'.$businessId, 'url' => 'required|url|unique:businesses' ]; } A: Lets say this is your model binding: $router->model('business', 'App\Business'); Then you can reference the Business class from within the FormRequest object like this: public function rules() { $business = $this->route()->getParameter('business'); // rest of the code } Note that if you use your form request both for create and update validation, while creating the record, the business variable will be null because your object does not exists yet. So take care to make the needed checks before referencing the object properties or methods. A: For those who switched to laravel 5 : public function rules() { $business = $this->route('business'); // rest of the code }
{ "pile_set_name": "StackExchange" }
Q: Inserting Image to FlowDocument I'm working on a wpf application. I want to create a FlowDocument object and print it. As the creation step takes some seconds and freeze the UI, I move my code to new thread. The problem is that I need to set an Image in the FlowDocument and need to create Image UIElement, but UI Controls cannot be created in background threads ! I've also tried so many Dispather.Invoke() scenarios, but they catch exception about object owner thread. I wonder is there any other methods to insert image into the FlowDocument? Or is it possible to create Image UIElement in background thread? any suggestion would be appreciated. P.S : Some Example Code => BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo; Image v = new Image() { Source = bitmapImage }; currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v))); Image v = ((App)Application.Current).Dispatcher.Invoke(new Func<Image>(() => { BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo; return new Image() { Source = bitmapImage}; })); currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v))); A: If you don't need to modify the BitmapImage, then you can freeze it and use it on the UI thread. // Executing on non UI Thread BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo; bitmapImage.Freeze(); // Has to be done on same thread it was created on - maybe freeze it in the Singleton instead? Application.Current.Dispatcher.Invoke(() => { // Executing on UI Thread Image v = new Image() { Source = bitmapImage }; currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v))); }); After chatting with you, what you really needed to do was run your task in a STA thread, since you were making UI controls on it. How to do that? See this answer: Set ApartmentState on a Task
{ "pile_set_name": "StackExchange" }
Q: Cast/Convert tree structure to different type If I have the class: class NodeA { public string Name{get;set;} public List<NodeA> Children {get;set;} // etc some other properties } and some other class: class NodeB { public string Name; public IEnumerable<NodeB> Children; // etc some other fields; } If I need to convert a NodeB object to of type NodeA what will be the best approach? Create a wrapper class? If I have to create a wrapper class how could I create it so that all the wpf controls will still be able to successfully bind to the properties? Reason why I need to create such cast: There was an old algorithm that was used on a program that return the list of symbols (IMemorySymbol) in a compiled program. We have worked and created a new algorithm and the fields and properties are somewhat different (ISymbolElem). We need to perform a temporary cast in order to display the properties in the view of the wpf application. A: A couple approaches... Copy Constructor have a NodeA and NodeB contain a constructor which takes the opposite: class NodeA { public string Name{get;set;} public List<NodeA> Children {get;set;} // COPY CTOR public NodeA(NodeB copy) { this.Name = copy.Name; this.Children = new List<NodeA>(copy.Children.Select(b => new NodeA(b)); //copy other props } } Explicit or Implicit Operator http://msdn.microsoft.com/en-us/library/xhbhezf4.aspx http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx explicit you would cast like NodeA a = (NodeA)b;, while implicit you can skip the parens. public static explicit operator NodeA(NodeB b) { //if copy ctor is defined you can call one from the other, else NodeA a = new NodeA(); a.Name = b.Name; a.Children = new List<NodeA>(); foreach (NodeB child in b.Children) { a.Children.Add((NodeA)child); } }
{ "pile_set_name": "StackExchange" }
Q: Unexpected Result while joining two datatables? object combinedrows = from dt1 in DsResults.Tables[0].AsEnumerable() join dt2 in DsResults.Tables[1].AsEnumerable() on dt1.Field<string>("MethodName") equals dt2.Field<string>("MethodName") select new { dt1, dt2 }; DataTable finaldt = new DataTable("FinalTable"); finaldt.Columns.Add(new DataColumn("sp",typeof(string))); finaldt.Columns.Add(new DataColumn("Method",typeof(string))); finaldt.Columns.Add(new DataColumn("Class",typeof(string))); finaldt.Columns.Add(new DataColumn("BLLMethod",typeof(string))); DataRow newrow = finaldt.NewRow(); finaldt.Rows.Add((DataRow)combinedrows); dataGridView5.DataSource = finaldt; The above coding gives the result in the first column as follows: System.Linq.Enumerable+d__614[System.Data.DataRow,System.Data.DataRow,System.String,<>f__AnonymousType02[System.Data.DataRow,System.Data.DataRow]] A: @Prem: After understanding your code i am sure you will get exception like "Unable to cast object of type 'd__614[System.Data.DataRow,System.Data.DataRow,System.String,<>f__AnonymousType02[System.Data.DataRow,System.Data.DataRow]]' to type 'System.Data.DataRow'." on finaldt.Rows.Add((DataRow)combinedrows); line so you must store Linq return result in var and then you can add row to new DataTable by loop. your code should be var combinedrows = from dt1 in DsResults.Tables[0].AsEnumerable() join dt2 in DsResults.Tables[1].AsEnumerable() on dt1.Field<string>("MethodName") equals dt2.Field<string>("MethodName") select new { dt1, dt2 }; DataTable finaldt = new DataTable("FinalTable"); finaldt.Columns.Add(new DataColumn("sp", typeof(string))); finaldt.Columns.Add(new DataColumn("Method", typeof(string))); finaldt.Columns.Add(new DataColumn("Class", typeof(string))); finaldt.Columns.Add(new DataColumn("BLLMethod", typeof(string))); DataRow newrow = finaldt.NewRow(); foreach (var row in combinedrows) { DataRow dataRow = finaldt.NewRow(); dataRow.ItemArray = row.dt1.ItemArray; finaldt.Rows.Add(dataRow); } try it out on the behalf of you i have checked it is running if not then post the error. For to get only a particular column from DataTable you need to change LINQ like var combinedrows = from dt1 in DsResults.Tables[0].AsEnumerable() join dt2 in DsResults.Tables[1].AsEnumerable() on dt1.Field<string>("MethodName") equals dt2.Field<string>("MethodName") select new { td1Col = dt1.Field<string>("Tab1col2")}; and for Retrieving data you need to do: foreach (var row in combinedrows) { string value = row.td1Col.ToString(); }
{ "pile_set_name": "StackExchange" }
Q: How to get a function's name from a object passed as that function's parameter in Python? Let's say, I have a function named my_function and I'm passing an object as its parameter in the following way: my_obj = MyClass() my_function(my_obj) Is there a way using which I can print the name of the function inside a method of MyClass? Let's say that MyClass has a method called display_info inside it and it prints the name of the function in where the object of MyClass is passed. An example would be: class MyClass: def print_log(self): # some code def random_method_1(): pass def random_method_2(): def my_function(param1, some_name, some_number): # some code # Instantiating MyClass my_object = MyClass() # Calling my_function my_function(my_object, "John Doe", 38478347) my_object.print_log() # Above line of code should be able to print "my_function" A: Design your program better If you need this systematically you might want a better designed program, e.g. one that injects the name of the parent or calling entity into e.g. my_obj.display_info(caller='something') class MyClass: def display_info(self, caller): print caller def my_function(my_obj): my_obj.display_info(caller='my_function') The above allows that param to be injected by each caller. Or keep a reference to the caller in MyClass.caller at init time if possible, or set it on the spot as needed e.g. # pseudo code class MyClass: def __init__(self, caller): self.caller = caller def display_info(self): print self.caller my_obj = MyClass(caller='caller') my_obj.display_info() my_obj.caller = 'new_caller' my_obj.display_info() The inspect hack to avoid The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. Yes usng inspect. When you call inspect.stack() you get a record of frame objects. So we use stack()[1] to get the previous frame, which is a tuple where the third element is the name of the caller (my_function). Hence stack()[1][3]. >>> import inspect >>> class MyClass(): ... def display_info(self): ... print inspect.stack()[1][3] ... >>> def my_function(my_obj): ... my_obj.display_info() ... >>> my_obj = MyClass() >>> my_function(my_obj) my_function # <--- The result you wanted >>> >>> def another_fn(my_obj): ... my_obj.display_info() ... >>> another_fn(my_obj) another_fn This provides the result you want (prints the name of the calling function)
{ "pile_set_name": "StackExchange" }
Q: Why doesn't Windows 8.1 accelerometer API output data when device is motionless? I'm playing with the C++ accelerometer API in WinRT on a Windows 8.1 ultrabook. I'm surprised to find that the API only updates the accelerometer data when the device is in motion. If it's sitting still on a table, the accelerometer readings do not update. I tried both polling and subscribing to updates by adding an event handler to Accelerometer.ReadingChanged. When the device is motionless, the event handler does not get called. When polling while the device is motionless, I continuously get the same old data, with the same old timestamp. Here is some sample data, polled at 16ms intervals. 130724777430758219 accel x: -0.005 y: -0.836 z: -0.728 130724777430758219 accel x: -0.005 y: -0.836 z: -0.728 130724777430758219 accel x: -0.005 y: -0.836 z: -0.728 130724777430758219 accel x: -0.005 y: -0.836 z: -0.728 130724777430758219 accel x: -0.005 y: -0.836 z: -0.728 130724777430758219 accel x: -0.005 y: -0.836 z: -0.728 130724777430758219 accel x: -0.005 y: -0.836 z: -0.728 The timestamp is the first column. You can see that the timestamp does not change. I would expect the acceleration data to not change, but am surprised that the timestamp does not change. This is not how it works on other platforms (iOS, Android). I expect to see different timestamps on each sample even if the device is motionless. This leads me to suspect that Windows might be doing some filtering on the data. Does anyone know if this behavior is intended in Windows 8.1? Could it be specific to just my device model? Is Windows doing any filtering of the accelerometer data? A: Turns out Windows is indeed filtering the accelerometer data. There is a COM API called ISensor that allows you to get unfiltered data. Unfortunately, it's not the nicest API, nor is it well documented. Here's a sample app that illustrates it's use. Note that in order to get unfiltered data, you have to set the sensor's SENSOR_PROPERTY_CHANGE_SENSITIVITY to 0. The sample app does not show this.
{ "pile_set_name": "StackExchange" }
Q: Call search API after UITextField changed, Moya I am doing search feature, I want to call api after my search textField changed. I am using Moya, how can I do that? Is there anyone have idea? A: If you use Moya, it will return an Object Cancellable when you call a request. You just need to save that object, and then when you make another request, you cancel the previous request. Example: var previousRequest: Cancellable? func search(text: String) { previousRequest?.cancel() //make new request... }
{ "pile_set_name": "StackExchange" }
Q: Why Android Notification not works if setSmallIcon is Missing? My doubt is why Notification is not build if setSmallIcon is missing in code : NotificationCompat.Builder builder = new NotificationCompat.Builder(this); // builder.setSmallIcon(R.drawable.ic_launcher); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com/")); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); builder.setContentIntent(pendingIntent); builder.setContentTitle("Google"); builder.setContentText("Go to Google"); builder.setSubText("Tap to go to link in notifications."); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(0, builder.build()); app dont throws any Exception, code run's fine but Notification is not showing and if i uncomment builder.setSmallIcon(R.drawable.ic_launcher); app Notification Works fine so my Question is why builder.setSmallIcon is compulsory to show a Notification. And if I don"t want to show smallicon on status bar any Solution ? A: It's because .setSmallIcon(R.drawable.ic_launcher); it's an pre requirement. If you're using NotificationCompat.Builder. I read some where in Google Developers Blog.
{ "pile_set_name": "StackExchange" }
Q: There was a problem communicating with Google servers, try again later - Galaxy s3 Got the dreaded "There was a problem communicating with Google servers, try again later" error. This all started with notifications stating my account could not Sync with any of my apps. Seen many posts with possible solutions ... Removed the account, then tried to re-add it and got the above message. Tried to add other accounts ... same thing. Verified 2-factor auth is not enabled Cleared cache and data from all Google-type apps on the phone, uninstalled all updates for the apps ....restarted Verified the date/time setting and timezone setting are automatic and they look correct The network and wifi are fine ... can browse to the Google sites Non-rooted phone. Nevertheless verified the hosts file is legit Not willing to do a factory reset yet since other posts suggest this does not always fix the issue and that would only lead me to likely throw my phone. Unintended consequences. Tried unlocking Captcha on Google Account This happens no matter which Google Account I try to add, making me think it is not account related rather something on the phone I'm at my wits end now ... clearly there is a serious issue here and I can't put my finger on it. Does anyone have any suggestions. Thx A: I have finally found the solution for this problem and want to share it here for those of you suffering from the same issue that was not answered by any of the steps mentioned in the original post. In short, I needed to reinstall Google Play Services In your device ... Go to Settings > Security > Check Unknown sources Head over to APKMirror and get the version of Google Play Services that is applicable to the your Android version. Install Probably best to reverse step 1 once finished This worked for me.
{ "pile_set_name": "StackExchange" }
Q: JPA delete bidirectional entity I am having some problems with JPA. I am new at this topic so my question maybe is really stupid, but i hope some of you could point me to the right direction. I have Project and User entity. Every user can have as many projects assign to him as it can. I created the relationship bidirectional User OneToMany -> Project, Project ManyToOne -> User My problem is that if i want to delete a user i want all the projects to be deleted as well, but i receive an error at that point: Internal Exception: java.sql.SQLIntegrityConstraintViolationException: DELETE on table 'USER_DATA' caused a violation of foreign key constraint 'PROJECT_USERNAME' for key (Test Use1312r1). The statement has been rolled back. Error Code: -1 Call: DELETE FROM USER_DATA WHERE (USERNAME = ?) bind => [1 parameter bound] My User entity looks like this: @Entity @Table(name="USER_DATA", uniqueConstraints = @UniqueConstraint(columnNames = {"USERNAME", "link"})) public class User implements Serializable { @Column(name="USERNAME") @Id @NotNull private String name; @Column(name="USERROLE") @Enumerated(EnumType.STRING) private UserRole role; private String password; private String link; // Should be unique private String session; @OneToMany(mappedBy="user", cascade=CascadeType.ALL) private Collection<Project> projects; My Project Entity like this: @Entity @Table(name="PROJECT") @XmlRootElement public class Project implements Serializable { @Id private int id; private String name; private String description; @Temporal(TemporalType.TIMESTAMP) @Column(name="START_DATE") private Date beginDate; @Temporal(TemporalType.TIMESTAMP) @Column(name="END_DATE") private Date endDate; @ManyToOne @JoinColumn(name="USERNAME", nullable=false,updatable= true) private User user; And my BL: public User getUser(String userName) throws NoDataFoundException { EntityManager em = DbConnection.getInstance().getNewEntity(); try { User user = em.find(User.class, userName); if (user == null) { throw new NoDataFoundException("User is not found in the DB"); } return user; } finally { em.close(); } } public void deleteUser(String userName) throws ModelManipulationException { EntityManager em = DbConnection.getInstance().getNewEntity(); try { User userToBeDeleted = getUser(userName); em.getTransaction().begin(); userToBeDeleted = em.merge(userToBeDeleted); em.remove(userToBeDeleted); em.getTransaction().commit(); } catch (Exception e) { throw new ModelManipulationException( "Error in deleting user data for username" + userName + "with exception " +e.getMessage(),e); } finally{ em.close(); } } Thanks in advance guys. A: after the merge call, are there any Projects in userToBeDeleted.projects? I suspect there are none, which prevents any from being deleted. Cascade remove can only work if you populate both sides of bidirectional relationships, so check that when you associate a user to a project, you also add the project to the user's project collection.
{ "pile_set_name": "StackExchange" }
Q: bash storing the output of set -x to log file I have a simple download script and I use set -x which works great; I can see each step it performs, and I can identify errors in the script or in the download: #!/bin/bash set -x #short_date=$(/bin/date +%m%d%y) short_date=$(/bin/date -d "8 day ago" +%m%d%y) #long_date=$(/bin/date +%Y%m%d) long_date=$(/bin/date -d "8 day ago" +%Y%m%d) scp -v -P 1332 -i /home/casper/.ssh/id_rsa_BANK [email protected]:/home/friendly/transfer/out/EXCHANGE_$short_date.csv /local/casper3/dailymetrics/BANK_$long_date.csv I would like to automate this job. Is there a way I could save the set -x output to a log file? Maybe to one log file - or a different log file for each day. I don't know what would work best. Below is sample set -x output from the above script. ++ /bin/date +%m%d%y + short_date=102814 ++ /bin/date +%Y%m%d + long_date=20141028 + scp -v -P 1332 -i /home/casper/.ssh/id_rsa_BANK [email protected]:/home/friendly/transfer/out/EXCHANGE_102814.csv /local/casper3/dailymetrics/BANK_20141028.csv Executing: program /usr/bin/ssh host 192.168.1.10, user friendly, command scp -v -f /home/friendly/transfer/out/EXCHANGE_102814.csv OpenSSH_5.3p1, OpenSSL 1.0.0-fips 29 Mar 2010 debug1: Reading configuration data /home/casper/.ssh/config debug1: Reading configuration data /etc/ssh/ssh_config debug1: Applying options for * debug1: Connecting to 192.168.1.10 [192.168.1.10] port 7777. debug1: Connection established. A: Assuming bash 4, BASH_XTRACEFD can be set to override the file descriptor (by default 2, stderr) to which set -x output is written: short_date=$(/bin/date +%m%d%y) exec {BASH_XTRACEFD}>>"$short_date".log set -x If running bash 4.0 rather than 4.1 or newer, you have BASH_XTRACEFD but not automatic file descriptor allocation, meaning you'll need to assign one yourself; in the below example, I'm picking file descriptor 100: short_date=$(/bin/date +%m%d%y) exec 100>>"$short_date".log BASH_XTRACEFD=100 set -x For older releases, your only choice is to redirect all of stderr, rather than only the xtrace stream: short_date=$(/bin/date +%m%d%y) exec 2>>"$short_date.log" set -x
{ "pile_set_name": "StackExchange" }
Q: How to set the default value of an integer field to it's possible maximum? Is there any way to set a maximum value as a default one for an integer field? In other words, I'm looking for a simple and elegant way to replace the hardcoded 999 value from the code below. Schema::create('files', function(Blueprint $table) { // . . . $table->integer('display_order')->default(999); // <-- MAX_VALUE instead of 999 // . . . }); A: You can see that PHP has Predefined Constants PHP_INT_MAX (integer) The largest integer supported in this build of PHP. Usually int(2147483647). Available since PHP 5.0.5
{ "pile_set_name": "StackExchange" }