id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23529400
Like How to know this tab-bar item is selected , didSelectViewController delegate method is used but i don't understand how set image This is method using but i dont know how to set image and color - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController Here is my code -(IBAction)clicka:(id)sender { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; AViewController *viewController1 = [[AViewController alloc] initWithNibName:@"AViewController" bundle:nil]; BViewController *viewController2 = [[BViewController alloc] initWithNibName:@"BViewController" bundle:nil]; CViewController *viewController3 = [[CViewController alloc]initWithNibName:@"CViewController" bundle:nil]; DViewController *viewController4 = [[DViewController alloc]initWithNibName:@"DViewController" bundle:nil]; [self.navigationController pushViewController:viewController1 animated:YES]; self.tabBarController = [[UITabBarController alloc] init]; self.tabBarController.delegate=self; self.tabBarController.viewControllers = @[viewController1,viewController2,viewController3,viewController4]; UINavigationController *navigationController = [[UINavigationController alloc]initWithRootViewController:self.tabBarController]; UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,320,100)]; img.image=[UIImage imageNamed:@"yellow-bg.png"]; [self.tabBarController.tabBar addSubview:img]; UIImageView *imghome=[[UIImageView alloc]initWithFrame:CGRectMake(30.0,5,25,25)]; imghome.image=[UIImage imageNamed:@"splash-logo.png"]; [img addSubview:imghome]; UIImageView *imghome1=[[UIImageView alloc]initWithFrame:CGRectMake(100.0,5,25,25)]; imghome1.image=[UIImage imageNamed:@"chat-icon.png"]; [img addSubview:imghome1]; UIImageView *imghome2=[[UIImageView alloc]initWithFrame:CGRectMake(180.0,5,25,25)]; imghome2.image=[UIImage imageNamed:@"p-icon.png"]; [img addSubview:imghome2]; UIImageView *imghome3=[[UIImageView alloc]initWithFrame:CGRectMake(260.0,5,25,25)]; imghome3.image=[UIImage imageNamed:@"addddd.png"]; [img addSubview:imghome3]; self.window.rootViewController = navigationController; [self.window makeKeyAndVisible]; } - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { NSUInteger selectedIndex = self.tabBarController.selectedIndex; NSLog(@"%lu",(unsigned long)selectedIndex); } please Help me A: You can find out the render mode in UIImage.h - (UIImage *)imageWithRenderingMode:(UIImageRenderingMode)renderingMode By the default , if the image was attached to a tabbar as tabbarItem, the rednering mode is UIImageRenderingModeAlwaysTemplate, so it's is blue. You should change the image rendering mode before you set to the tabbaritem. UIImage * originalImage = [UIImage imageNamed:@"chat-icon.png"]; UIImage * selectedBlueImage = [originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; when the tab was selected, set the selectedBlueImage to the imageView. like : imageview.highlightedImage = selectedBlueImage A: I am not sure if I understood you problem correctly, but if you want to set images inside each TabBar section for each View Controllers correspondingly, you can do that from each View Controller class, for example, inside AViewController.m, override: - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { //self.tabBarItem.title = @"Title"; self.tabBarItem.image = [UIImage imageNamed:@"image-name"]; } return self; }
doc_23529401
I've attempted to fix this by putting Set-StrictMode -Off at the top of the scripts, or at the top of scripts that use the misbehaving modules. Unfortunately, it doesn't seem to have any effect. How do I temporarily disable strict mode in PowerShell? More detail: This specifically occurs with PsGet. See issue 57. I have Set-StrictMode -Version 2.0 in my profile. If I attempt to use PsGet's Install-Module from a script, I get errors saying "Property 'Verb' cannot be found on this object." This occurs even if I put Set-StrictMode -Off at the top of the script. If I run Set-StrictMode -Off at the command line before running the script, I get no errors and the script works fine. PsGet is imported in my profile, before turning on strict mode. A: Like Matt says in the comments, I do not see this issue reproduce. Can you provide more details? Contents of StrictModeTest.ps1: Set-StrictMode -Off # variable $x doesn't exist, should trigger strictmode error "Value is [$($x.Path)]" Testing (PSv3): PS C:\> Set-StrictMode -Version 2.0 PS C:\> .\StrictModeTest.ps1 Value is [] If I comment out the Set-StrictMode -Off line, I get the expected error: PS C:\> .\StrictModeTest.ps1 The variable '$x' cannot be retrieved because it has not been set. At C:\StrictModeTest.ps1:4 char:14 + "Value is [$($x.Path)]" + ~~ + CategoryInfo : InvalidOperation: (x:String) [], RuntimeException + FullyQualifiedErrorId : VariableIsUndefined Value is []
doc_23529402
Now I want to modify the behavior of the scroller so that it scrolls one-page per click. Even better, I'd like to have the scrolling animate with easing, i.e. not jump from page to page, but scroll with animation. The documentation for the ScrollBarBase http://www.flex-component.com/asdoc/kcdualslider/spark/components/supportClasses/ScrollBarBase.html suggests a number of methods which should provide a means to achieve this, but I can't find any examples of how to use these excellent methods and properties: animatePaging(newValue:Number, pageSize:Number): Animates the operation to move to newValue. button_buttonDownHandler(event:Event): Handles a click on the increment or decrement button button_buttonUpHandler(event:Event): Handles releasing the increment or decrement button decrementButton:Button An optional skin part that defines a button that, when pressed, steps the scrollbar up. incrementButton:Button An optional skin part that defines a button that, when pressed, steps the scrollbar down. My hunch is that I need to interrupt the button_buttonUp/DownHandlers for decrementButton and incrementButton and call animatePaging, but I really have no idea how to do this. These spark skins really remain quit mysterious to me in spite of having written tons of AS3 and successfully modified quite a few skins. Looking forward to any insight! Thanks! A: I found the solution to my question. I needed to extend the VScrollBar class. Once I did this is was a simple matter to override the button_buttonDown/UpHandlers. Having extended the VScrollBar class, in my skin, I substituted <my_namespace:CustomVScrollBar for <s:VScrollBar Here's the gist of my CustomVScrollBar. I'm using gs.TweenLite, but you could use any tweener for the animation package my_package { import flash.events.Event; import gs.TweenLite; import spark.components.VScrollBar; public class CustomVScrollBarextends VScrollBar { public function CustomVScrollBar() { super(); } override protected function button_buttonDownHandler(event:Event):void { var valueTo:Number; if (event.target == incrementButton) { valueTo = Math.min(value+pageSize, maximum); } else if (event.target == decrementButton) { valueTo = Math.max(value-pageSize, minimum); } if (! isNaN(valueTo)) { TweenLite.to(this.viewport, .75, {verticalScrollPosition: valueTo}); } } override protected function button_buttonUpHandler(event:Event):void { // // nothing } } }
doc_23529403
I start on a project XYZ, for which I create a work item, and I make frequent check-ins, easily 10-20 in total. ALL of the code changes will be code-read and code-reviewed. The change sets are not consecutive - other people check-in in-between my changes, although they are very unlikely to touch the exact same files. So ... at the end of the project I am interested in a "total diff" - as if there was a single check-in by me to complete the entire project. In theory this is computable. From the list of change sets associated with the work item, you get the list of all files that were affected. Then, the algorithm can aggregate individual diffs over each file and combine them into one. It is possible that a pure total diff is uncomputable due to the fact that someone else renamed files, or changed stuff around very closely, or in the same functions as me. I that case ... I suppose a total diff can include those changes by non-me as well, and warn me about the fact. I would find this very useful, but I do not know how to do t in practice. Can Visual Studio 2008/2010 (and/or TFS server) do it? Are there other source control systems capable of doing this? Thanks. A: You can certainly compute the 'total diff' yourself - make a branch of the project from the revision just prior to your first commit, then merge all your changesets into it. I don't think this really is a computable thing in the general case - only contiguous changesets can be merged automatically like this. Saying it's 'unlikely' for others to have touched the files you're working on in the interleving commits doesn't cut it, you need guarantees to be able to automate this sort of thing. A: You should be working on a branch of your own if you want to be able to do this easily. The ability to generate diff information for display or for merge purposes is functionality provided by your version control system, as Mahesh Velaga commented on another answer. If you were able to compute the diff by cherry-picking non-contiguous changesets, then logically you would also be able to merge those changes in a single operation. But this is not supported by TFS. So I strongly suspect that the construction of the cherry-picked diff information is also not supported by TFS. Other version control systems (git, mercurial, darcs come to mind) might have more support for something like this; I don't know for sure. From my reading of their answers on the TFS version control forums, I think that their recommendation for this would be to create a branch of your own for doing this work in the first place: then the changesets would be contiguous on that branch and creating the "total diff" would be trivial. Since it sounds like you are working on an independent feature anyway (otherwise a diff of only your changes would be meaningless), you should consider having an independent branch for it regardless of whether your version control system is TFS or something else. The alternative is to construct what such a branch would have looked like after the fact, which is essentially what Jim T's answer proposes. You might prefer that approach if your team is very keen on everyone working in the same kitchen, as it were. But as you are already aware, things can get messy that way. A: Create two workspaces. Get Specific Version for files specifying the date or upto those two changeset on those two workspace. Now compare folders using a compare tool. Araxis merge is best one. A: sounds like you need a tool that supports changesets (changes over multiple files and committing them all at once) instead of committing each file alone take a look at this comparison between sourcesafe and mercurial ( free and you can find tools to integrate it with visual studio )
doc_23529404
The regular algorithm works like this: You times the value by the base you're converting into. Record whole numbers, then keep going with the remaining fraction part until there is no more fraction: 0.337 in binary: 0.337*2 = 0.674 "0" 0.674*2 = 1.348 "1" 0.348*2 = 0.696 "0" 0.696*2 = 1.392 "1" 0.392*2 = 0.784 "0" 0.784*2 = 1.568 "1" 0.568*2 = 1.136 "1" Approximately .0101011 A: I have a two-step algorithm for doing the conversion. I'm not sure if this is the optimal algorithm, but it works pretty well. The basic idea is to start off by getting a decimal representation of the number, then converting that decimal representation into a negadecimal representation by handling the even powers and odd powers separately. Here's an example that motivates the idea behind the algorithm. This is going to go into a lot of detail, but ultimately will arrive at the algorithm and at the same time show where it comes from. Suppose we want to convert the number 0.523598734 to negadecimal (notice that I'm presupposing you can convert to decimal). Notice that 0.523598734 = 5 * 10^-1 + 2 * 10^-2 + 3 * 10^-3 + 5 * 10^-4 + 9 * 10^-5 + 8 * 10^-6 + 7 * 10^-7 + 3 * 10^-8 + 4 * 10^-9 Since 10^-n = (-10)^-n when n is even, we can rewrite this as 0.523598734 = 5 * 10^-1 + 2 * (-10)^-2 + 3 * 10^-3 + 5 * (-10)^-4 + 9 * 10^-5 + 8 * (-10)^-6 + 7 * 10^-7 + 3 * (-10)^-8 + 4 * 10^-9 Rearranging and regrouping terms gives us this: 0.523598734 = 2 * (-10)^-2 + 5 * (-10)^-4 + 8 * (-10)^-6 + 3 * (-10)^-8 + 5 * 10^-1 + 3 * 10^-3 + 9 * 10^-5 + 7 * 10^-7 + 4 * 10^-9 If we could rewrite those negative terms as powers of -10 rather than powers of 10, we'd be done. Fortunately, we can make a nice observation: if d is a nonzero digit (1, 2, ..., or 9), then d * 10^-n + (10 - d) * 10^-n = 10^-n (d + 10 - d) = 10^-n (10) = 10^{-n+1} Restated in a different way: d * 10^-n + (10 - d) * 10^-n = 10^{-n+1} Therefore, we get this useful fact: d * 10^-n = 10^{-n+1} - (10 - d) * 10^-n If we assume that n is odd, then -10^-n = (-10)^-n and 10^{-n+1} = (-10)^{-n+1}. Therefore, for odd n, we see that d * 10^-n = 10^{-n+1} - (10 - d) * 10^-n = (-10)^{-n+1} + (10 - d) * (-10)^-n Think about what this means in a negadecimal setting. We've turned a power of ten into a sum of two powers of minus ten. Applying this to our summation gives this: 0.523598734 = 2 * (-10)^-2 + 5 * (-10)^-4 + 8 * (-10)^-6 + 3 * (-10)^-8 + 5 * 10^-1 + 3 * 10^-3 + 9 * 10^-5 + 7 * 10^-7 + 4 * 10^-9 = 2 * (-10)^-2 + 5 * (-10)^-4 + 8 * (-10)^-6 + 3 * (-10)^-8 + (-10)^0 + 5 * (-10)^-1 + (-10)^-2 + 7 * (-10)^-3 + (-10)^-4 + 1 * (-10)^-5 + (-10)^-6 + 3 * (-10)^-7 + (-10)^-8 + 6 * (-10)^-9 Regrouping gives this: 0.523598734 = (-10)^0 + 5 * (-10)^-1 + 2 * (-10)^-2 + (-10)^-2 + 7 * (-10)^-3 + 5 * (-10)^-4 + (-10)^-4 + 1 * (-10)^-5 + 8 * (-10)^-6 + (-10)^-6 + 3 * (-10)^-7 + 3 * (-10)^-8 + (-10)^-8 + 6 * (-10)^-9 Overall, this gives a negadecimal representation of 1.537619346ND Now, let's think about this at a negadigit level. Notice that * *Digits in even-numbered positions are mostly preserved. *Digits in odd-numbered positions are flipped: any nonzero, odd-numbered digit is replaced by 10 minus that digit. *Each time an odd-numbered digit is flipped, the preceding digit is incremented. Let's look at 0.523598734 and apply this algorithm directly. We start by flipping all of the odd-numbered digits to give their 10's complement: 0.523598734 --> 0.527518336 Next, we increment the even-numbered digits preceding all flipped odd-numbered digits: 0.523598734 --> 0.527518336 --> 1.537619346ND This matches our earlier number, so it looks like we have the makings of an algorithm! Things get a bit trickier, unfortunately, when we start working with decimal values involving the number 9. For example, let's take the number 0.999. Applying our algorithm, we start by flipping all the odd-numbered digits: 0.999 --> 0.191 Now, we increment all the even-numbered digits preceding a column that had a value flipped: 0.999 --> 0.191 --> 1.1(10)1 Here, the (10) indicates that the column containing a 9 overflowed to a 10. Clearly this isn't allowed, so we have to fix it. To figure out how to fix this, it's instructive to look at how to count in negabinary. Here's how to count from 0 to 110: 000 001 002 003 ... 008 009 190 191 192 193 194 ... 198 199 180 181 ... 188 189 170 ... 118 119 100 101 102 ... 108 109 290 Fortunately, there's a really nice pattern here. The basic mechanism works like normal base-10 incrementing: increment the last digit, and if it overflows, carry a 1 into the next column, continuing to carry until everything stabilizes. The difference here is that the odd-numbered columns work in reverse. If you increment the -10s digit, for example, you actually subtract one rather than adding one, since increasing the value in that column by 10 corresponds to having one fewer -10 included in your sum. If that number underflows at 0, you reset it back to 9 (subtracting 90), then increment the next column (adding 100). In other words, the general algorithm for incrementing a negadecimal number works like this: * *Start at the 1's column. *If the current column is at an even-numbered position: * *Add one. *If the value reaches 10, set it to zero, then apply this procedure to the preceding column. *If the current column is at an odd-numbered position: * *Subtract one. *If the values reaches -1, set it to 9, then apply this procedure to the preceding column. You can confirm that this math works by generalizing the above reasoning about -10s digits and 100s digits and realizing that overflowing an even-numbered column corresponding to 10k means that you need to add in 10k+1, which means that you need to decrement the previous column by one, and that underflowing an odd-numbered column works by subtracting out 9 · 10k, then adding in 10k+1. Let's go back to our example at hand. We're trying to convert 0.999 into negadecimal, and we've gotten to 0.999 --> 0.191 --> 1.1(10)1 To fix this, we'll take the 10's column and reset it back to 0, then carry the 1 into the previous column. That's an odd-numbered column, so we decrement it. This gives the final result: 0.999 --> 0.191 --> 1.1(10)1 --> 1.001ND Overall, for positive numbers, we have the following algorithm for doing the conversion: * *Processing digits from left to right: * *If you're at an odd-numbered digit that isn't zero: * *Replace the digit d with the digit 10 - d. *Using the standard negadecimal addition algorithm, increment the value in the previous column. Of course, negative numbers are a whole other story. With negative numbers, the odd columns are correct and the even columns need to be flipped, since the parity of the (-10)k terms in the summation flip. Consequently, for negative numbers, you apply the above algorithm, but preserve the odd columns and flip the even columns. Similarly, instead of incrementing the preceding digit when doing a flip, you decrement the preceding digit. As an example, suppose we want to convert -0.523598734 into negadecimal. Applying the algorithm gives this: -0.523598734 --> 0.583592774 --> 0.6845(10)2874 --> 0.684402874ND This is indeed the correct representation. Hope this helps! A: For your question i thought about this object-oriented code. I am not sure although. This class takes two negadecimals numbers with an operator and creates an equation, then converts those numbers to decimals. public class NegadecimalNumber { private int number1; private char operator; private int number2; public NegadecimalNumber(int a, char op, int b) { this.number1 = a; this.operator = op; this.number2 = b; } public int ConvertNumber1(int a) { int i = 1; int nega, temp; temp = a; int n = a & (-10); while (n > 0) { temp = a / (-10); n = temp % (-10); n = n * i; i = i * 10; } nega = n; return nega; } public int ConvertNumber2(int b) { int i = 1; int negb, temp; temp = b; int n = b & (-10); while (n > 0) { temp = b / (-10); n = temp % (-10); n = n * i; i = i * 10; } negb = n; return negb; } public double Equation() { double ans = 0; if (this.operator == '+') { ans = this.number1 + this.number2; } else if (this.operator == '-') { ans = this.number1 - this.number2; } else if (this.operator == '*') { ans = this.number1 * this.number2; } else if (this.operator == '/') { ans = this.number1 / this.number2; } return ans; } } A: Note that https://en.wikipedia.org/wiki/Negative_base#To_Negative_Base tells you how to convert whole numbers to a negative base. So one way to solve the problem is simply to multiply the fraction by a high enough power of 100 to turn it into a whole number, convert, and then divide again: -0.06 = -6 / 100 => 14/100 = 0.14. Another way is to realise that you are trying to create a sum of the form -a/10 + b/100 -c/1000 + d/10000... to approximate the target number so you want to reduce the error as much as possible at each stage, but you need to leave an error in the direction that you can correct at the next stage. Note that this also means that a fraction might not start with 0. when converted. 0.5 => 1.5 = 1 - 5/10. So to convert -0.06. This is negative and the first digit after the decimal point is in the range [0.0, -0.1 .. -0.9] so we start with 0. to leave us -0.06 to convert. Now if the first digit after the decimal point is 0 then I have -0.06 left, which is in the wrong direction to convert with 0.0d so I need to chose the first digit after the decimal point to produce an approximation below my target -0.06. So I chose 0.1, which is actually -0.1 and leaves me with an error of 0.04, which I can convert exactly leaving me the conversion of 0.14. So at each point output the digit which gives you either 1) The exact result, in which case you are finished 2) An approximation which is slightly larger than the target number, if the next digit will be negative. 3) An approximation which is slightly smaller than the target number, if the next digit will be positive. And if you start off trying to approximate a number in the range (-1.0, 0.0] at each point you can choose a digit which keeps the remaining error small enough and in the right direction, so this always works.
doc_23529405
# Load packages library(tidyverse) library(readxl) library("openxlsx") library(segmented) library(grid) library(gridExtra) library(shiny) library(shinyWidgets) library(shinydashboard) library(DT) library(dplyr) library(shinyBS) library(shinythemes) data_table <- data.frame(c(1)) names(data_table)[1] <- "a" data_table$b <- 2 data_table$c <- 3 ui <- fluidPage(theme = shinytheme("lumen"), mainPanel( tabsetPanel( tabPanel("Dashboard", fluidRow( box(DTOutput("data_table"), title = "Selectable Data Table", width = 12) ), tags$head(tags$style(HTML(' .modal-lg { width: 99%; } '))) ) ) ) ) server <- function(input, output, session) { #DASHBOARD output$data_table <- DT::renderDataTable({ DT::datatable(data_table, selection = 'single', escape = FALSE) }) table_select <- reactive({ input$data_table_rows_selected }) observeEvent(table_select(),{ showModal(modalDialog( title = "I wish this window had a layout similar to fliudPage", size = "l", easyClose = TRUE, ) ) }) } shinyApp(ui = ui, server = server) However, in this modal window, I am not able to have the fluidPage layout i.e. row width of 12, setting fluidRows etc. I would like to have greater control of the layout of this modal window - preferably the same layout controls as a fluidPage. the only thing I have been able to do is to create a larger modal window than what is normally presented using the following code: tags$head(tags$style(HTML(' .modal-lg { width: 99%; } '))) The way I see it I have two options: Option 1 - Find a way to have the observeEvent open a new fluidPage instead of a modal window? or Option 2 - change the modal window layout somehow... any help would be greatly appreciated! Cheers, -Alex
doc_23529406
Country Entity: <?php namespace Catalog\Models\Entity; use Doctrine\ORM\Mapping as ORM; /** * A country page. * * @ORM\Entity * @ORM\Table(name="tbl_country") * @property string $name * @property string $code * @property string $latitude * @property string $longitude * @property string $countryLogo * @property int $id */ class Country { /** * @ORM\Id * @ORM\Column(type="integer"); * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="string",length=250,nullable=true) */ private $name; /** * @ORM\Column(type="string",length=5,nullable=true) */ private $code; /** * @ORM\Column(type="float",nullable=true) */ private $latitude; /** * @ORM\Column(type="float",nullable=true) */ private $longitude; /** * @ORM\Column(type="string",length=120,nullable=true) */ private $countryLogo; /** * @ORM\OneToMany(targetEntity="Catalog\Models\Entity\Region", mappedBy="country") */ protected $regions; public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getCode() { return $this->code; } public function setCode($code) { $this->code = $code; } public function getLatitude() { return $this->latitude; } public function setLatitude($latitude) { $this->latitude = $latitude; } public function getLongitude() { return $this->longitude; } public function setLongitude($longitude) { $this->longitude = $longitude; } public function getCountryLogo() { return $this->countryLogo; } public function setCountryLogo($countryLogo) { $this->countryLogo = $countryLogo; } public function getRegions() { return $this->regions; } public function setRegions($regions) { $this->regions = $regions; } } Region Entity: <?php namespace Catalog\Models\Entity; use Doctrine\ORM\Mapping as ORM; /** * A region page. * * @ORM\Entity * @ORM\Table(name="tbl_region") * @property string $name * @property string $code * @property string $latitude * @property string $longitude * @property int $id */ class Region { /** * @ORM\Id * @ORM\Column(type="integer"); * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="string",length=250,nullable=true) */ private $name; /** * @ORM\Column(type="string",length=5,nullable=true) */ private $code; /** * @ORM\Column(type="float",nullable=true) */ private $latitude; /** * @ORM\Column(type="float",nullable=true) */ private $longitude; /** * @ORM\ManyToOne(targetEntity="Catalog\Models\Entity\Country", inversedBy="regions") * @ORM\JoinColumn(name="country_id", referencedColumnName="id") */ private $country; public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getCode() { return $this->code; } public function setCode($code) { $this->code = $code; } public function getLatitude() { return $this->latitude; } public function setLatitude($latitude) { $this->latitude = $latitude; } public function getLongitude() { return $this->longitude; } public function setLongitude($longitude) { $this->longitude = $longitude; } public function getCountry() { return $this->country; } public function setCountry($country) { $this->country = $country; } } I am trying to get all the countries. But when I do like this $countries = $this->getEntityManager()->getRepository('Catalog\Models\Entity\Country')->findAll(); It is returning all the countries and regions. And when I try this $countries = $this->getEntityManager()->createQuery("SELECT Country.id, Country.name FROM Catalog\Models\Entity\Country Country")->execute(); It returns only Country in array format. How can I get only the Country in Object format? A: You could try to mark the regions assosiation as lazy load: class Country { ... /** * @ORM\OneToMany(targetEntity="Catalog\Models\Entity\Region", mappedBy="country", fetch="EXTRA_LAZY") */ protected $regions; See docs here: https://doctrine-orm.readthedocs.org/en/latest/tutorials/extra-lazy-associations.html?highlight=fetch A: The first method should work, but if your want to get your query working you should do like this: $query = $this->getEntityManager()->createQuery( "SELECT c FROM Catalog\Models\Entity\Country c" ); $countries = $query->getResult(); The problem lies in your select statement. If you want a collection of objects (entities) in your result you should only query for the entity by its alias and not specify properties in the SELECT statement. If you do this it will return only the properties you asked for in array format.
doc_23529407
<div class="container-fluid"> <div class="col-lg-4" style="height: 200px; border: 1px #ccc solid"> <h1>Block 1</h1> </div> <div class="col-lg-4" style="height: 100px; border: 1px #ff0 solid"> <h1>Block 2</h1> </div> <div class="col-lg-4" style="height: 150px; border: 1px #f00 solid"> <h1>Block 3</h1> </div> <div class="col-lg-4" style="height: 175px; border: 1px green solid"> <h1>Block 4</h1> </div> <div class="col-lg-4" style="height: 175px; border: 1px blue solid"> <h1>Block 5</h1> </div> <div class="col-lg-4" style="height: 75px; border: 1px pink solid"> <h1>Block 6</h1> </div> </div><!-- /.container --> A: To ensure block 4 is under 1, you would need to use a row: <div class="container-fluid"> <div class='row'> <div class="col-lg-4" style="height: 200px; border: 1px #ccc solid"> <h1>Block 1</h1> </div> <div class="col-lg-4" style="height: 100px; border: 1px #ff0 solid"> <h1>Block 2</h1> </div> <div class="col-lg-4" style="height: 150px; border: 1px #f00 solid"> <h1>Block 3</h1> </div> </div> <div class='row'> <div class="col-lg-4" style="height: 175px; border: 1px green solid"> <h1>Block 4</h1> </div> <div class="col-lg-4" style="height: 175px; border: 1px blue solid"> <h1>Block 5</h1> </div> <div class="col-lg-4" style="height: 75px; border: 1px pink solid"> <h1>Block 6</h1> </div> </div> </div> http://www.bootply.com/xWzvbdxvvi# And note, just to ensure you know the -lg classes only works at higher resolution. On smaller screens it will stack one on to of the other (block 2 is under block 1) for -md, -sm, and -xs sized screens. [UPDATE: 2015-03-18 per comments] If all you want to do is have them stack vertically without space, the only other option is this: <div class="container-fluid"> <div class="row"> <div class='col-lg-4'> <div style="height: 200px; border: 1px #ccc solid"> <h1>Block 1</h1> </div> <div style="height: 175px; border: 1px green solid"> <h1>Block 4</h1> </div> </div> <div class='col-lg-4'> <div style="height: 100px; border: 1px #ff0 solid"> <h1>Block 2</h1> </div> <div style="height: 175px; border: 1px blue solid"> <h1>Block 5</h1> </div> </div> <div class="col-lg-4"> <div style="height: 150px; border: 1px #f00 solid"> <h1>Block 3</h1> </div> <div style="height: 75px; border: 1px pink solid"> <h1>Block 6</h1> </div> </div> </div> </div> This is going to stack vertically within the same column, but this limits you in completely different ways. Bootstrap is about manually configuring your grid to the display you want for each viewing size...it is NOT something that's going to dynamically try to puzzle-piece your sections together like a newspaper as the link you provided seems to do. A: The link example you gave changes layout on refresh and uses js. If using bootstrap, not adding rows you will yield a less predictable layout, if using a 12 column bootstrap grid, any cols added up over 12 wrap to the next row. -lg class is for desktop/higher resolution. You can add multiple classes to each div for handling smaller resolutions.
doc_23529408
[2016-02-02 16:56:53,465] INFO - StartupFinalizerServiceComponent WSO2 Carbon started in 33 sec [2016-02-02 16:56:53,549] INFO - StatisticsServiceComponent BAM Service Stat Publishing is disabled [2016-02-02 16:56:53,969] INFO - CarbonUIServiceComponent Mgt Console URL : https://172.17.42.1:9443/carbon/ [2016-02-02 16:56:53,970] INFO - CarbonUIServiceComponent API Publisher Default Context : http://172.17.42.1:9763/publisher [2016-02-02 16:56:53,970] INFO - CarbonUIServiceComponent API Store Default Context : http://172.17.42.1:9763/store [2016-02-02 16:56:54,244] INFO - DefaultKeyValidationHandler org.wso2.carbon.apimgt.keymgt.handlers.DefaultKeyValidationHandler Initialised [2016-02-02 16:56:54,244] INFO - APIKeyValidationService Initialised KeyValidationHandler instance successfully [2016-02-02 16:56:54,245] INFO - APIKeyMgtServiceComponent Setting default carbon host for thrift key management service: 172.17.42.1 [2016-02-02 16:56:54,267] INFO - APIKeyMgtServiceComponent Started thrift key mgt service at port:10397 The console here shows to have started at https://172.17.42.1:9443/carbon/ whereas the host is different in which the server is running. A: Did you encounter any errors during the start up? The reason for having a different host IP could be due to the availability of multiple network interfaces on your CentOS machine. Also verify whether the relevant ports are opened on your CentOS6 instance. Ref.
doc_23529409
This is the code for the SplashScreenViewController: class SplashScreenViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 46/255, green: 83/255, blue: 160/255, alpha: 1.0) let image : UIImage = UIImage(named:"splashScreen.png")! let bgImage = UIImageView(image: image) bgImage.frame = CGRect(origin: CGPoint(x: 3,y: -3), size: CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height)) self.view.addSubview(bgImage) let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "GameViewController") self.present(controller, animated: true, completion: nil) self.dismiss(animated: true, completion: nil) } deinit { print("Object with name SplashScreenViewController is being released") } } A: You can set rootviewcontroller of your window to replace splash screen with game screen. The code will look like this let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window!.rootViewController = gameViewController A: As far as I can tell, you want to replace the SplashScreenViewController with your GameViewController. Your current code is presenting the GameViewControllermodally and directly after that dismissing it. So the new view controller isn't shown. Another problem in your code is the missing gap in timing, currently the splash screen get's initialized and right after that it would be replaced by the GameViewControllerif your code was working, so you would just see the GameViewController. class SplashScreenViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 46/255, green: 83/255, blue: 160/255, alpha: 1.0) let image : UIImage = UIImage(named:"splashScreen.png")! let bgImage = UIImageView(image: image) bgImage.frame = CGRect(origin: CGPoint(x: 3,y: -3), size: CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height)) self.view.addSubview(bgImage) let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "GameViewController") // Here we create a dispatch queue to do some other code after an amount of time. In this case, one second. let dispatchTime = DispatchTime.now() + .seconds(1) DispatchQueue.main.asyncAfter(deadline: dispatchTime) { self.navigationController?.setViewControllers([controller!], animated: false) } } } This setup will replace the SplashScreenViewController with the GameViewController after one second. For that to work, and for basically all navigation between view controllers, you must wrap your first view controller into a UINavigationController.
doc_23529410
map = new ol.Map({ controls:[new ol.control.LayerSwitcher({ tipLabel: 'Leyenda', }), new ol.control.defaults().extend([new ol.control.FullScreen()])], layers: [ new ol.layer.Group({ 'title': 'Mapas de base', layers: [grisOSM, mapaOSM] }), I also tried creating the map, then create and add controls like this: map = new ol.Map({ layers: [ new ol.layer.Group({ 'title': 'Mapas de base', layers: [grisOSM, mapaOSM] }), const layerSwitcher = new ol.control.LayerSwitcher({ tipLabel: 'Leyenda', }); map.addControl(layerSwitcher); const fullScreen = new ol.control.defaults().extend([new ol.control.FullScreen()]); map.addControl(fullScreen); I get Uncaught TypeError: t.element.setMap is not a function error and can't see none of them A: Either map = new ol.Map({ controls: ol.control.defaults().extend([new ol.control.FullScreen()]), layers: [ new ol.layer.Group({ 'title': 'Mapas de base', layers: [grisOSM, mapaOSM] }), ], }); or map = new ol.Map({ layers: [ new ol.layer.Group({ 'title': 'Mapas de base', layers: [grisOSM, mapaOSM] }) ], }); map.addControl(new ol.control.FullScreen()); ol.control.defaults is not a constructor so does not need new
doc_23529411
My thinking goes like this Function 1 - gets a list of a folders * *Function2 takes each folder and searches the file paths for each file created in the last week and returns an array of file paths Function 3 - Copies across the files based on the array of file paths I'm having trouble with the array. I want to specify the array size in advance based on the number of files in each folder. My code and the error is below Can anyone see the problem Public Function get_remoteTables(strPath As String) Dim objFSO As FileSystemObject Dim objFolder As Folder Dim objFiles As file Dim filedetails() As Variant Dim FileCount As Long Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.GetFolder(strPath) ' Grab all the files in the subfolders For Each objSubFolder In objFolder.SubFolders 'print folder path Debug.Print (objSubFolder.Path) Set objFiles = objFSO.GetFolder(objSubFolder.Path).Files If Err.Number <> 0 Then FileCount = 0 Else FileCount = objFiles.Count End If get_Filenames (objSubFolder.Path) Next objSubFolder End Function Sub test() Call get_remoteTables("C:\temp\ ") End Sub Compile Error Method or Data member not found: FileCount = objFiles.Count A: Although i wasnt able to understand why i was getting the error, I found a function online that seems to do what i need. I adapted the function and added the function to the code above Public Function CountFiles(xPath As String) Dim xCount As Long Dim xFile As String xPath = "C:\temp\HelloWorld\" xFile = Dir(xPath) Do While xFile <> "" xCount = xCount + 1 xFile = Dir() Loop CountFiles = xCount End Function
doc_23529412
But now i also want to create user in my application and also want to authenticate that users which is stored in my database. Is it possible to authenticate Application DB users as well with windows authentication for domain users. i did much R & D on this but didn't found any solution yet. I will appreciate your suggestions. Thanks! A: If I understand you correctly, you want to allow both Windows Authentication and Forms Authentication. This is not a common thing to do, but I have done it. Here is how I did it: You have to use forms authentication as your primary authentication. So build the Forms Authentication as you normally would: you have a login page that, after submitting, validates the credentials from your database. The tricky part is adding Windows Authentication. To do this, create one action in your authentication controller that uses Windows authentication. For this example, I'll assume your controller is AuthController and we'll call the action WinLogin. That action will look something like this: [Authorize] public ActionResult WinLogin() { var principal = HttpContext.User; if (principal == null || !principal.Identity.IsAuthenticated) { //Windows authentication failed return new HttpUnauthorizedResult(); } // User is validated, so create the form authentication cookie FormsAuthentication.SetAuthCookie(principal.Identity.Name, false); return new EmptyResult(); } It just checks if the user is validated and, if so, sets the Forms Authentication cookie with their AD username. For that to use Windows Authentication, you have to update your web.config to tell it to use Windows Authentication for only that one action. You do that with a <location> tag: <location path="Auth/WinLogin"> <system.webServer> <security> <authentication> <windowsAuthentication enabled="true" /> <anonymousAuthentication enabled="false" /> </authentication> </security> </system.webServer> <system.web> <authorization> <allow users="?" /> </authorization> </system.web> </location> By default, IIS won't let you change the authentication method at this place in the config. You need to update the "Feature Delegation" in IIS Manager to allow it. * *In IIS Manager, click the server name on the left. *On the right, double-click "Feature Delegation" under the "Management" section. *Change both "Authentication - Anonymous" and "Authentication - Windows" to "Read/Write". If you use IIS Express for debugging, you have to do something similar for that: * *In the project folder, open the file .vs\config\applicationhost.config. *Modify these two lines so they say "Allow": <section name="anonymousAuthentication" overrideModeDefault="Allow" /> <section name="windowsAuthentication" overrideModeDefault="Allow" /> Next update your login page to hide the username and password fields by default (let's say they are inside a box with an id of loginBox). The idea is that you perform an AJAX request to the WinLogin action, and if that succeeds, then you forward the user on to the main page or whichever page they were trying to go to. If you use jQuery, that will look something like this: $.get("@Url.Action("WinLogin", "Auth")") .done(function() { //success! forward to the page they want window.location.replace(returnUrl); }).fail(function() { //failed - show manual login prompt $("#loginBox").show(); }); }); As long as your website is already a trusted website (which I assume so if you already have Windows Authentication working now), then the Windows Authentication will happen during that AJAX GET request. Notice the use of window.location.replace(), which will not add the login page to the browser history, so if the user then hits the back button, they do not come back to the login page. It makes things a little more seamless. You could also add a loading circle or something to indicate that the user should wait while that GET happens, but you can decide that. With all this in place, the user experience should be: * *They access a page. *They are not authenticated, so they get redirected to the login page. *The login page attempts the Windows Authentication in the background. *If the Windows Authentication succeeds, they are automatically redirected back to the page they wanted. *If Windows Authentication failed, the username and password boxes appear and they can login manually.
doc_23529413
pls give the steps A: Try the following * *Open up your setup project *Select the Application Folder *Right click, Add/File... *Add CP210xVCPInstaller_x86.exe And that should be it. Edit To get CP210xVPInstaller_x86.exe to execute, right click on the filename and select the properties window. In the properties window, set Condition to True
doc_23529414
I want to give them to possibility to disable their account but before they must enter their password. For the first users ( who create an account with email + password ) it is ok. But for others (facebook users) I can't ask them for password because they are logged via facebook. does anyone have an idea to solve this? thanks
doc_23529415
## 'data.frame': 2 obs. of 3 variables: ## $ Var1 : Factor w/ 2 levels "correct","incorrect": 1 2 ## $ Freq : num 84 16 ## $ text_bars: chr "84%" "16%" Then I create a ggplot object. z <- ggplot(results_graph, aes(Var1, Freq)) + geom_bar(position="dodge",stat="identity", fill = "deepskyblue4") + #coord_flip() + theme(legend.title=element_blank()) + ggtitle(expression(atop(bold("Percent of correct vs. incorrect numbers"), atop(italic("test_test"), "")))) This plot runs properly. If I try this however ggplotly(z) I get the following error: Error in unique.default(proposed[[attr]]): unimplemented type 'expression' in 'HashTablesetup' Calls: <Anonymous> ... verify)attr -> structure -> uniaue -> uniaue.default In addition: Warning message: In instance$preRenderHook(instance): It seems your data is too big for client-side DataTables. Any clue what might be the issue? A: It appears that your use of mathematical notation via expression in the ggtitle function is causing the error. Remove the expression call and your ggplotly object should render correctly. Related issues (#1, #2) are open on the ropensci/plotly repo on Github. Once the first issue is closed, there is some chance that mathematical notation will be supported via MathJax.
doc_23529416
I got the solution in Java but I need the solution in react native. I need the solution like this link but in react native. https://medium.com/touch4it/fingerprint-external-scanner-with-usb-database-sdk-64c3ec5ea82d A: You'll need to bridge between React Native (Javascript) and native (Java) code. The docs are pretty good and have specific examples for Android. One approach would be to fork a react-native biometric integration library (for example https://github.com/hieuvp/react-native-fingerprint-scanner) and replace the underlying native (Java for android) implementation with the code that you found.
doc_23529417
#!/usr/bin/env python import BaseHTTPServer from BaseHTTPServer import BaseHTTPRequestHandler import SocketServer import urlparse import cgitb import cgi from cgi import parse_header, parse_multipart class S(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): self._set_headers() self.wfile.write("<html><body><h1>hi!</h1></body></html>") def do_HEAD(self): self._set_headers() def do_POST(self): ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': postvars = cgi.parse_multipart(self.rfile, pdict) elif ctype == 'application/x-www-form-urlencoded': length = int(self.headers.getheader('content-length')) postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1) else: postvars = {} def run(server_class=BaseHTTPServer.HTTPServer, handler_class=S, port=80): server_address = ('', port) httpd = server_class(server_address, handler_class) print 'Starting httpd...' httpd.serve_forever() if __name__ == "__main__": run() Clinet Client send POST request over program Postman. GET works. Post is does not work . This is Error on server when I send request http://192.168.2.108?var1=value ERROR ON SERVER Exception happened during processing of request from ('192.168.2.107', 49629) Traceback (most recent call last): File "/usr/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock self.process_request(request, client_address) File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request self.finish_request(request, client_address) File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python2.7/SocketServer.py", line 655, in init self.handle() File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle self.handle_one_request() File "/usr/lib/python2.7/BaseHTTPServer.py", line 328, in handle_one_request method() File "server.py", line 37, in do_POST ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) File "/usr/lib/python2.7/cgi.py", line 309, in parse_header parts = _parseparam(';' + line) TypeError: cannot concatenate 'str' and 'NoneType' objects A: Maybe because the request sent by your client does not include the content-type header. You did not say how you are connecting to the server. curl -X POST http://localhost:8880/?var1=value Will fail as shown above. While: curl -X POST http://localhost:8880/?var1=value -H 'Content-type: application/x-www-form-urlencoded' Will fail also, but a bit further along the way: you also need a Content-length header. What you need is to check the values returned to you by the class methods instead of trusting everything will happen as you wish it will: def do_POST(self): content_type = self.headers.getheader('content-type') if content_type is None: raise ... # 400 Invalid Request # otherwise go on.
doc_23529418
I have a problem. Let me start by laying out my table structure: CREATE TABLE Person ( id varchar(50) NOT NULL PRIMARY KEY, name varchar(50) NOT NULL, adress varchar(50) NOT NULL references Adress(id) ) CREATE TABLE Adress ( id varchar(50) NOT NULL PRIMARY KEY, addressName varchar(50), city varchar(50), aState varchar(50), linkToCountry varchar(50) references Country(id) ) CREATE TABLE Country ( id varchar(50) NOT NULL PRIMARY KEY, countryName varchar(50) ) What I want to achieve is: select a person 'name' along with their 'addressName' and the 'countryName' they're from. I know that this is a joining related issue but I can't seem to figure this one out. So any help from people who are well versed on SQL? Would appreciate it very very much any one has links to advance sql joining so I can familiarize myself with it. A: You can get the result using simple join as below. This will retrun the person name with address name, and country name. However it returns only those person names which has an address record in the address table and country record in the country table. If you want to retrieve all the persons irrespective of whether address/country exists or not, you need to use left join. SELECT Person.Name, Address.addressname,Country.countryName FROM Person JOIN Address on Person.address = Address.Id JOIN Country ON Address.linkToCountry = Country.id A: Try this: SELECT p.name, a.addressName, c.countryName FROM Person p INNER JOIN Adress a ON p.adress = a.id LEFT OUTER JOIN Country c ON a.linkToCountry = c.id
doc_23529419
it is based off of this template https://www.robvanderwoude.com/vbstech_ui_buttons.php#InternetExplorer when the script is run, the Internet Explorer button box will appear and nothing happens when i select the button for TC01 but the script will output a 2 when the button for TC02 is selected and 0322538 for when the button named TC03 is selected I need each of the buttons to output a string when they are selected ' Create an IE object Set objIE = CreateObject( "InternetExplorer.Application" ) ' specify some of the IE window's settings objIE.Navigate "about:blank" sTitle="Make your choice " & String( 80, "." ) 'Note: the String( 80,".") is to push "Internet Explorer" string off the window objIE.Document.title = sTitle objIE.MenuBar = False objIE.ToolBar = False objIE.AddressBar = false objIE.Resizable = False objIE.StatusBar = False objIE.Width = 250 objIE.Height = 500 ' Center the dialog window on the screen With objIE.Document.parentWindow.screen objIE.Left = (.availWidth - objIE.Width ) \ 2 objIE.Top = (.availHeight - objIE.Height) \ 2 End With ' Wait till IE is ready Do While objIE.Busy WScript.Sleep 200 Loop ' Insert the HTML code to prompt for user input objIE.Document.body.innerHTML = "<div align=""center"">" & vbcrlf _ & "<p><input type=""hidden"" id=""OK"" name=""OK"" value=""0"">" _ & "<input type=""submit"" value="" TC01 "" onClick=""VBScript:OK.value=EXT1GBMW0151315""></p>" _ & "<input type=""submit"" value="" TC02 "" onClick=""VBScript:OK.value=2""></p>" _ & "<input type=""submit"" value="" TC03 "" onClick=""VBScript:OK.value=0322538""></p>" _ the rest of the code is identical to the template i have used any ideas? A: So the summary of changes is: 1: Dim objIE, sTitle, iErrorNum, myVal 'add myVal declaration 2 (use 444 as a placeholder switch value that will be processed below): & "<input type=""submit"" value="" TC01 "" onClick=""VBScript:OK.value=444""></p>" _ 3 (assign myVal to your desired output, save the button value to retVal, check it and output the correct final value as the IEButtons response): myVal = "EXT1GBMW0151315" Dim retVal retVal = CStr(objIE.Document.all.OK.value) If retVal = "444" Then IEButtons = myVal Else IEButtons = CStr(objIE.Document.all.OK.value) End If Final block working to return your desired value for TC01: ' Save this code as IEButtonsDemo.vbs WScript.Echo IEButtons() Function IEButtons() ' This function uses Internet Explorer to create a dialog. Dim objIE, sTitle, iErrorNum, myVal 'Create an IE object Set objIE = CreateObject( "InternetExplorer.Application" ) ' specify some of the IE window's settings objIE.Navigate "about:blank" sTitle="Make your choice " & String( 80, "." ) 'Note: the String( 80,".") is to push "Internet Explorer" string off the window objIE.Document.title = sTitle objIE.MenuBar = False objIE.ToolBar = False objIE.AddressBar = false objIE.Resizable = False objIE.StatusBar = False objIE.Width = 250 objIE.Height = 500 ' Center the dialog window on the screen With objIE.Document.parentWindow.screen objIE.Left = (.availWidth - objIE.Width ) \ 2 objIE.Top = (.availHeight - objIE.Height) \ 2 End With ' Wait till IE is ready Do While objIE.Busy WScript.Sleep 200 Loop ' Insert the HTML code to prompt for user input objIE.Document.body.innerHTML = "<div align=""center"">" & vbcrlf _ & "<p><input type=""hidden"" id=""OK"" name=""OK"" value=""0"">" _ & "<input type=""submit"" value="" TC01 "" onClick=""VBScript:OK.value=444""></p>" _ & "<input type=""submit"" value="" TC02 "" onClick=""VBScript:OK.value=2""></p>" _ & "<input type=""submit"" value="" TC03 "" onClick=""VBScript:OK.value=0322538""></p>" _ & "<p><input type=""hidden"" id=""Cancel"" name=""Cancel"" value=""0"">" _ & "<input type=""submit"" id=""CancelButton"" value="" Cancel "" onClick=""VBScript:Cancel.value=-1""></p></div>" ' Hide the scrollbars objIE.Document.body.style.overflow = "auto" ' Make the window visible objIE.Visible = True ' Set focus on Cancel button objIE.Document.all.CancelButton.focus 'CAVEAT: If user click red X to close IE window instead of click cancel, an error will occur. ' Error trapping Is Not doable For some reason On Error Resume Next Do While objIE.Document.all.OK.value = 0 and objIE.Document.all.Cancel.value = 0 WScript.Sleep 200 iErrorNum=Err.Number If iErrorNum <> 0 Then 'user clicked red X (or alt-F4) to close IE window IEButtons = 0 objIE.Quit Set objIE = Nothing Exit Function End if Loop On Error Goto 0 objIE.Visible = False ' Read the user input from the dialog window myVal = "EXT1GBMW0151315" Dim retVal retVal = CStr(objIE.Document.all.OK.value) If retVal = "444" Then IEButtons = myVal Else IEButtons = CStr(objIE.Document.all.OK.value) End If ' Close and release the object objIE.Quit Set objIE = Nothing End Function
doc_23529420
Is there something I'm missing? import logging import boto3 from botocore.exceptions import ClientError import os def upload_file(file_name, bucket, object_name=None): if object_name is None: object_name = os.path.basename(file_name) s3_client = boto3.resource('s3') try: response = s3.client.upload_file(file_name, bucket, object_name) except ClientError as e: logging.error(e) return False return True upload = upload_file('test1.jpg','mybucket', 'test1.jpg') A: This line: response = s3.client.upload_file(file_name, bucket, object_name) should be: response = s3_client.upload_file(file_name, bucket, object_name)
doc_23529421
Thanks A: http://en.wikipedia.org/wiki/Rabin-Karp_string_search_algorithm http://www.eecs.harvard.edu/~ellard/Q-97/HTML/root/node43.html Here's a couple sources. A: This is a port of this C implementation of the Karp-Rabin algorithm: function KR($haystack, $needle) { $n = strlen($haystack); $m = strlen($needle); if ($m > $n) { return -1; } /* Preprocessing */ $d = 1 << ($m - 1); for ($hh = $hn = $i = 0; $i < $m; ++$i) { $hh = (($hh<<1) + ord($haystack[$i])); $hn = (($hn<<1) + ord($needle[$i])); } /* Searching */ $j = 0; while ($j <= $n-$m) { if ($hh == $hn && substr($haystack, $j, $m) === $needle) { return $j; } if ($j === $n-$m) { return false; } /* Rehashing */ $hh = (($hh - ord($haystack[$j]) * $d) << 1) + ord($haystack[$j + $m]); ++$j; } return false; } A: Here's a slightly altered version Gumbo's answer above, with simpler hashing and clearer variable naming, for the sake of illustration. In the illustrative hashing below I'm just adding the ord() value of each character to a number, which represents the hash, then subtracting that value/adding the ord() of the next char when advancing our search. This is very collision-prone (and therefore not good for production), but it's easier to understand if you're just learning Rabin-Karp conceptually. function rk ($needle, $haystack) { $nlen = strlen($needle); $hlen = strlen($haystack); $nhash = 0; $hhash = 0; // Special cases that don't require the rk algo: // if needle is longer than haystack, no possible match if ($nlen > $hlen) { return false; } // If they're the same size, they must just match if ($nlen == $hlen) { return ($needle === $haystack); } // Compute hash of $needle and $haystack[0..needle.length] // This is a very primitive hashing method for illustrative purposes // only. You'll want to modify each value based on its position in // the string as per Gumbo's example above (left shifting) for ($i = 0; $i < $nlen; ++$i) { $nhash += ord($needle[$i]); $hhash += ord($haystack[$i]); } // Go through each position of needle and see if // the hashes match, then do a comparison at that point for ($i = 0, $c = $hlen - $nlen; $i <= $c; ++$i) { // If the hashes match, there's a good chance the next $nlen characters of $haystack matches $needle if ($nhash == $hhash && $needle === substr($haystack, $i, $nlen)) { return $i; } // If we've reached the end, don't try to update the hash with // the code following this if() if ($i == $c) { return false; } // Update hhash to the next position by subtracting the // letter we're removing and adding the letter we're adding $hhash = ($hhash - ord($haystack[$i])) + ord($haystack[$i + $nlen]); } return false; } A: Try this out. You will have to strip the punctuation from the $needle and $haystack before sending it to match_rabinKarp(), but this basically follows the algorithm given on the wikipedia page. // this hash function is friendly, according to the wikipedia page function hash($string) { $base = ord('a'); if (strlen($string) == 1) { return ord($string); } else { $result = 0; // sum each of the character*(base^i) for ($i=strlen($string)-1; $i>=0; $i++) { $result += $string[$i]*pow($base,$i); } return $result; } } // perform the actual match function match_rabinKarp($needle, $haystack) { $needle = substr($needle); // remove capitals $haystack = substr($haystack); // remove capitals $m = strlen($needle); // length of $needle $n = strlen($haystack); // length of $haystack $h_haystack = hash($haystack); // hash of $haystack $h_needle = hash($needle); // hash of $needle // whittle away at the $haystack until we find a match for ($i=0;$i<$n-$m+1;$i++) { if ($h_needle == $h_haystack) { if (substr($haystack,$i,$i+$m-1) == $needle) { return $i; } } } return false; }
doc_23529422
I created a sessionFactory bean and inject it into Impl <bean id="GetStartedDAOBean" class="com.sample.dao.impl.GetStartedDAOImpl" > <property name="sessionfactory" ref="sessionFactory"> </property> </bean <bean id="GetStartedActionBean" class="com.sample.action.GetStartedAction"> <property name="getStartedDAOImpl" ref="GetStartedDAOBean"></property> <property name="industryDAOImpl" ref="IndustryDAOBean"></property> <property name="stateDAOImpl" ref="stateDAOBean"></property> </bean> In impl i have private SessionFactory sessionfactory; public void setSessionfactory(SessionFactory sessionfactory) { this.sessionfactory = sessionfactory; } public void save(Customer customer)throws IllegalStateException,SystemException{ try { sessionfactory.openSession().saveOrUpdate(customer); } catch(Exception e){ e.printStackTrace(); } } when i debug there is value in sessionFactory but it does not save any value. and also does not show any inserted query. There is no error. Any one can help me? A: You open your session (in-memory) and save something onto it, but the session saves in the database only when you flush(). Do a Session session = sessionfactory.openSession(); session.saveOrUpdate(customer); session.flush(); Another way is to commit the transaction, and thus Hibernate will automatically call flush(). A: Try with @Transactional at the method, and add the following to your XML: <tx:annotation-driven/> A: @Transaction you have give on method of service class and <tx:annotation-driven/> you have to give in applicaiton-context.xml file. Hence, when any one call the service class's method, the transaciton will start by spring and it will handle up to commit and rollback.
doc_23529423
Below is my example code: #!/usr/bin/env python import wx import gettext tview_Items = [ ["Overview - Job", ["Job Activities"]], ["Server", ["FLEX01", "FLEX02", "FLEX03", "FLEX03", "FLEX04", "FLEX05", "FLEX06", "FLEX07", "FLEX08", "FLEX09", "FLEX10", "FLEX11", "FLEX12"] ] ] class MyFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.tree_ctrl = wx.TreeCtrl(self, wx.ID_ANY, style=wx.TR_HAS_BUTTONS | wx.TR_LINES_AT_ROOT | wx.TR_DEFAULT_STYLE | wx.SUNKEN_BORDER) root = self.tree_ctrl.AddRoot("General") #self.tree_ctrl.Expand(root) # Adding nodes from the data set self.AddTreeNodes(root, tview_Items) # Adding nodes from the data set self.tree_ctrl.ExpandAllChildren(root) # Expand all the node's children self.notebook_1 = wx.Notebook(self, wx.ID_ANY, style=0) self.panel_JobActivities = wx.ScrolledWindow(self.notebook_1, wx.ID_ANY, style=wx.TAB_TRAVERSAL) self.panel_Flex01 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex02 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex03 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex04 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex05 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex06 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex07 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex08 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex09 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex10 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex11 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex12 = wx.Panel(self.notebook_1, wx.ID_ANY) self.__set_properties() self.__do_layout() self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelfChanged, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.tree_ctrl) # end def __set_properties(self): # begin : MyFrame.__set_properties self.SetTitle(_("Application")) self.SetSize((1070, 772)) self.SetBackgroundColour(wx.Colour(240, 240, 240)) self.tree_ctrl.SetMinSize((200, 709)) self.panel_JobActivities.SetMinSize((754, 683)) self.panel_JobActivities.SetScrollRate(10, 10) self.notebook_1.SetMinSize((841, 587)) # end def __do_layout(self): # begin : MyFrame.__do_layout grid_sizer_1 = wx.FlexGridSizer(1, 2, 2, 2) grid_sizer_1.Add(self.tree_ctrl, 1, wx.ALL | wx.EXPAND, 10) self.notebook_1.AddPage(self.panel_JobActivities, _("Job Activities")) self.notebook_1.AddPage(self.panel_Flex01, _("FLEX 01")) self.notebook_1.AddPage(self.panel_Flex02, _("FLEX 02")) self.notebook_1.AddPage(self.panel_Flex03, _("FLEX 03")) self.notebook_1.AddPage(self.panel_Flex04, _("FLEX 04")) self.notebook_1.AddPage(self.panel_Flex05, _("FLEX 05")) self.notebook_1.AddPage(self.panel_Flex06, _("FLEX 06")) self.notebook_1.AddPage(self.panel_Flex07, _("FLEX 07")) self.notebook_1.AddPage(self.panel_Flex08, _("FLEX 08")) self.notebook_1.AddPage(self.panel_Flex09, _("FLEX 09")) self.notebook_1.AddPage(self.panel_Flex10, _("FLEX 10")) self.notebook_1.AddPage(self.panel_Flex11, _("FLEX 11")) self.notebook_1.AddPage(self.panel_Flex12, _("FLEX 12")) grid_sizer_1.Add(self.notebook_1, 1, wx.ALL | wx.EXPAND, 10) self.SetSizer(grid_sizer_1) grid_sizer_1.AddGrowableRow(0) grid_sizer_1.AddGrowableCol(0) self.Layout() self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelfChanged, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.tree_ctrl) self.Bind(wx.EVT_CLOSE, self.OnClose) # end def AddTreeNodes(self, parentItem, items): # Building the tree nodes for item in items: if type(item) == str: self.tree_ctrl.AppendItem(parentItem, item) else: newItem = self.tree_ctrl.AppendItem(parentItem, item[0]) self.AddTreeNodes(newItem, item[1]) def OnSelfChanged(self, event): # wxGlade: MyFrame.<event_handler> print "OnSelChanged: ", self.GetItemText(event.GetItem()) for page in range(self.Notebook.GetPageCount()): if page == self.Notebook_1.GetSelection(): print self.Notebook_1.Item() def OnActivated(self, event): # wxGlade: MyFrame.<event_handler> print "OnActivated: ", self.GetItemText(event.GetItem()) def OnItemCollapsed(self, event): # wxGlade: MyFrame.<event_handler> print "OnItemCollapsed: ", self.GetItemText(event.GetItem()) def OnItemExpanded(self, event): # wxGlade: MyFrame.<event_handler> print "OnItemExpanded: ", self.GetItemText(event.GetItem()) def GetItemText(self, item): if item: return self.tree_ctrl.GetItemText(item) else: return "" def OnClose(self, event): dlg = wx.MessageDialog(self, "Do you really want to close this application?", "Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION) result = dlg.ShowModal() dlg.Destroy() if result == wx.ID_OK: self.Destroy() # end of class MyFrame if __name__ == "__main__": gettext.install("app") app = wx.App(0) frame = MyFrame(None, wx.ID_ANY, "") app.SetTopWindow(frame) frame.Show() app.MainLoop() A: You were very very close. You just need to compare the treectrl text with the notebook tab text, and call SetSelection if it matches. def OnSelfChanged(self, event): # wxGlade: MyFrame.<event_handler> selected = self.GetItemText(event.GetItem()) print "OnSelChanged: ", selected for page in range(self.notebook_1.GetPageCount()): print self.notebook_1.GetPageText(page) if self.notebook_1.GetPageText(page) == selected: self.notebook_1.SetSelection(page) In Addtion I had to change the names of the tabs of the notebook to match the labels in the treeview. In your code the treeview has no spaces ("FLEX01") but the notebook tabs have spaces ("FLEX 01"). I got rid of the spaces. It works. Full working code: #!/usr/bin/env python import wx import gettext tview_Items = [ ["Overview - Job", ["Job Activities"]], ["Server", ["FLEX01", "FLEX02", "FLEX03", "FLEX03", "FLEX04", "FLEX05", "FLEX06", "FLEX07", "FLEX08", "FLEX09", "FLEX10", "FLEX11", "FLEX12"] ] ] class MyFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.tree_ctrl = wx.TreeCtrl(self, wx.ID_ANY, style=wx.TR_HAS_BUTTONS | wx.TR_LINES_AT_ROOT | wx.TR_DEFAULT_STYLE | wx.SUNKEN_BORDER) root = self.tree_ctrl.AddRoot("General") #self.tree_ctrl.Expand(root) # Adding nodes from the data set self.AddTreeNodes(root, tview_Items) # Adding nodes from the data set self.tree_ctrl.ExpandAllChildren(root) # Expand all the node's children self.notebook_1 = wx.Notebook(self, wx.ID_ANY, style=0) self.panel_JobActivities = wx.ScrolledWindow(self.notebook_1, wx.ID_ANY, style=wx.TAB_TRAVERSAL) self.panel_Flex01 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex02 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex03 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex04 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex05 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex06 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex07 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex08 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex09 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex10 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex11 = wx.Panel(self.notebook_1, wx.ID_ANY) self.panel_Flex12 = wx.Panel(self.notebook_1, wx.ID_ANY) self.__set_properties() self.__do_layout() self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelfChanged, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.tree_ctrl) # end def __set_properties(self): # begin : MyFrame.__set_properties self.SetTitle(_("Application")) self.SetSize((1070, 772)) self.SetBackgroundColour(wx.Colour(240, 240, 240)) self.tree_ctrl.SetMinSize((200, 709)) self.panel_JobActivities.SetMinSize((754, 683)) self.panel_JobActivities.SetScrollRate(10, 10) self.notebook_1.SetMinSize((841, 587)) # end def __do_layout(self): # begin : MyFrame.__do_layout grid_sizer_1 = wx.FlexGridSizer(1, 2, 2, 2) grid_sizer_1.Add(self.tree_ctrl, 1, wx.ALL | wx.EXPAND, 10) self.notebook_1.AddPage(self.panel_JobActivities, _("Job Activities")) self.notebook_1.AddPage(self.panel_Flex01, _("FLEX01")) self.notebook_1.AddPage(self.panel_Flex02, _("FLEX02")) self.notebook_1.AddPage(self.panel_Flex03, _("FLEX03")) self.notebook_1.AddPage(self.panel_Flex04, _("FLEX04")) self.notebook_1.AddPage(self.panel_Flex05, _("FLEX05")) self.notebook_1.AddPage(self.panel_Flex06, _("FLEX06")) self.notebook_1.AddPage(self.panel_Flex07, _("FLEX07")) self.notebook_1.AddPage(self.panel_Flex08, _("FLEX08")) self.notebook_1.AddPage(self.panel_Flex09, _("FLEX09")) self.notebook_1.AddPage(self.panel_Flex10, _("FLEX10")) self.notebook_1.AddPage(self.panel_Flex11, _("FLEX11")) self.notebook_1.AddPage(self.panel_Flex12, _("FLEX12")) grid_sizer_1.Add(self.notebook_1, 1, wx.ALL | wx.EXPAND, 10) self.SetSizer(grid_sizer_1) grid_sizer_1.AddGrowableRow(0) grid_sizer_1.AddGrowableCol(0) self.Layout() self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelfChanged, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.tree_ctrl) self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.tree_ctrl) self.Bind(wx.EVT_CLOSE, self.OnClose) # end def AddTreeNodes(self, parentItem, items): # Building the tree nodes for item in items: if type(item) == str: self.tree_ctrl.AppendItem(parentItem, item) else: newItem = self.tree_ctrl.AppendItem(parentItem, item[0]) self.AddTreeNodes(newItem, item[1]) def OnSelfChanged(self, event): # wxGlade: MyFrame.<event_handler> selected = self.GetItemText(event.GetItem()) print "OnSelChanged: ", selected for page in range(self.notebook_1.GetPageCount()): print self.notebook_1.GetPageText(page) if self.notebook_1.GetPageText(page) == selected: self.notebook_1.SetSelection(page) def OnActivated(self, event): # wxGlade: MyFrame.<event_handler> print "OnActivated: ", self.GetItemText(event.GetItem()) def OnItemCollapsed(self, event): # wxGlade: MyFrame.<event_handler> print "OnItemCollapsed: ", self.GetItemText(event.GetItem()) def OnItemExpanded(self, event): # wxGlade: MyFrame.<event_handler> print "OnItemExpanded: ", self.GetItemText(event.GetItem()) def GetItemText(self, item): if item: return self.tree_ctrl.GetItemText(item) else: return "" def OnClose(self, event): dlg = wx.MessageDialog(self, "Do you really want to close this application?", "Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION) result = dlg.ShowModal() dlg.Destroy() if result == wx.ID_OK: self.Destroy() # end of class MyFrame if __name__ == "__main__": gettext.install("app") app = wx.App(0) frame = MyFrame(None, wx.ID_ANY, "") app.SetTopWindow(frame) frame.Show() app.MainLoop()
doc_23529424
When user press on the link it Just reloads to the same page itself the URL creates is http://www.website.com/blog/page/2/ I believe the correct URL should be http://www.website.com/blog/2014/05/page/2/ This is my code in loop.php <?php /* Display navigation to next/previous pages when applicable */ ?> <?php if ( $wp_query->max_num_pages > 1 ) : ?> <div id="nav-below" class="navigation"> <div class="nav-previous"><?php next_posts_link( __( ' Older posts', 'twentyten' ) ); ?></div> <div class="nav-next"><?php previous_posts_link( __( 'Newer posts', 'twentyten' ) ); ?></div> </div><!-- #nav-below --> <?php endif; ?> Thanks A: I dont know what are you doing in starting with loop.php This code could be helpful. <?php //The Query $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $wp_query = new WP_Query(); $wp_query->query( 'showposts=10&cat='.$category_id.'&paged='.$paged ); //The Loop while ($wp_query->have_posts()) : $wp_query->the_post(); // display posts as you need endwhile; // pager Method -1 <?php if ( $wp_query->max_num_pages > 1 ) : ?> <div id="nav-below" class="navigation"> <div class="nav-previous"><?php next_posts_link( __( ' Older posts', 'twentyten' ) ); ?></div> <div class="nav-next"><?php previous_posts_link( __( 'Newer posts', 'twentyten' ) ); ?></div> </div><!-- #nav-below --> //Or you can use Paged Method -2 // pager if($wp_query->max_num_pages>1){?> <p class="pager"> <?php for($i=1;$i<=$wp_query->max_num_pages;$i++){?> <a href="<?php echo get_category_link($category_id).'page/'.$i;?>" <?php echo ($paged==$i)? 'class="active"':'';?>><?php echo $i;?></a> <?php } if($paged!=$wp_query->max_num_pages){?> <a href="<?php echo get_category_link($category_id).'page/'.$i;?>">Category</a> <?php } ?> </p> <?php } ?>
doc_23529425
An Entity "Account" with a JOINED inheritance to two other Entities: "Author" and "AccountBackend". Then I would want the "AccountBackend" to have a SINGLE_TABLE inheritance with other two Entities: "Administrator" and "FeaturedAuthor". This is the way I have them defined: Account.php /** * @Entity (repositoryClass="Repositories\Account") * @Table(name="accounts") * @InheritanceType("JOINED") * @DiscriminatorColumn(name="discr", type="integer") * @DiscriminatorMap({"1"="Author","2"="AccountBackend"}) * @HasLifecycleCallbacks */ class Account { Curator.php /** * @Entity * @Table(name="accounts_author") */ class Author extends Account { AccountBackend.php /** * @Entity (repositoryClass="Repositories\AccountBackend") * @Table(name="accounts_backend") * @InheritanceType("SINGLE_TABLE") * @DiscriminatorColumn(name="discr", type="integer") * @DiscriminatorMap({"1"="FeaturedAuthor","2"="Administrator"}) * @HasLifecycleCallbacks */ class AccountBackend extends Account { FeaturedAuthor.php /** * @Entity */ class FeaturedAuthor extends AccountBackend { Administrator.php /** * @Entity */ class Administrator extends AccountBackend { When I have them defined, when I try to do an update through the CLI it says "Entity 'Entities\AccountBackend' has to be part of the discriminator map of 'Entities\Account' to be properly mapped in the inheritance hierachy. Alternatively you can make 'Entities\AccountBackend' an abstract class to avoid this exception from occuring." I don't see anything wrong with the way I defined them, this is the first time that I try to have inheritance on an already inherited Entity. Any idea of whats wrong? Thanks! A: You need a case for your "AccountBackend" class in your @DiscriminatorMap e.g @DiscriminatorMap({"1"="FeaturedAuthor","2"="Administrator", "3"="AccountBackend"}) As explain in the Documentation All entity classes that is part of the mapped entity hierarchy (including the topmost class) should be specified in the @DiscriminatorMap. In the case above Person class included. A: In case you came here & had problem with SINGLE_TABLE inheritance - possible that the problem occurs because your discriminator class is not abstract. My case example (solution) /** * @ORM\InheritanceType("SINGLE_TABLE") * @ORM\DiscriminatorColumn(name="entity", type="string") * @ORM\DiscriminatorMap({"product" = "ProductReview", "seller" = "SellerReview"}) * @ORM\Table(name="reviews") */ abstract class Review {} class ProductReview extends Review {} class SellerReview extends Review {}
doc_23529426
Typically one would take the setuptools approach with extras_requires setup({ extras_requires={ 'dev': [ 'pytest' ] } }) or something to that tune from within the module. Google's documentation doesn't explicitly mention how to do this, I know they're using Flask to do the actual execution and what not but outside of that I'm lost; don't know if a module can be used. Is this even possible or would I be better of making different requirements.txt files ? A: Separate requirements files are the way to go. If you wanted to make it a little easier for yourself, you could have your "development" requirements file include your production requirements file, e.g. in development.txt: pytest -r requirements.txt
doc_23529427
"Caused by: java.lang.NoSuchMethodException: org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper.<init>()" while writing pyspark dataframe to mysql database spark-submit command: spark-submit --deploy-mode client --master yarn --conf spark.pyspark.python=/usr/bin/python3 --packages mysql:mysql-connector-java:8.0.12 s3://aramark-files/test_pyspark.py And I am writing using: df.write.jdbc(url="jdbc:mysql://dbhost/dbname", table="tablename", mode="append", properties={"user":"dbuser", "password": "s3cret"}) Below is the error I am getting after executing the above spark-submit command: Traceback (most recent call last): File "/mnt/tmp/spark-8bb457ce-fc88-4384-af58-9e52e2d6e21a/test_pyspark.py", line 51, in <module> df.write.jdbc(jdbcUrl, where, mode='append', properties=dbProperties) File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/readwriter.py", line 942, in jdbc File "/usr/lib/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py", line 1257, in __call__ File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 63, in deco File "/usr/lib/spark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py", line 328, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling o79.jdbc. : java.lang.InstantiationException: org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper at java.lang.Class.newInstance(Class.java:427) at org.apache.spark.sql.execution.datasources.jdbc.DriverRegistry$.register(DriverRegistry.scala:53) at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:55) at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:54) at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:63) at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:45) at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:70) at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:68) at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:86) at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131) at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127) at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152) at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127) at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:80) at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:80) at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:654) at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:654) at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:77) at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:654) at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:273) at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:267) at org.apache.spark.sql.DataFrameWriter.jdbc(DataFrameWriter.scala:499) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:282) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:238) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.NoSuchMethodException: org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper.<init>() at java.lang.Class.getConstructor0(Class.java:3082) at java.lang.Class.newInstance(Class.java:412) ... 34 more A: I ran across the same problem in the Scala API. I'm reading from and writing to an Oracle 12c database, and both the DataFrameReader and the DataFrameWriter require the "driver" property to be set, in my case to "oracle.jdbc.OracleDriver", or else the former blows up with "No suitable driver" and the latter blows up with NoSuchMethodException. I would therefore suggest you try df.write.jdbc(url="jdbc:mysql://dbhost/dbname", table="tablename", mode="append", properties={"user":"dbuser", "password": "s3cret", "driver": "com.mysql.cj.jdbc.Driver" }) Where I've substituted the MySQL driver class name from the docs.
doc_23529428
Below is my code: $(document).ready(function() { var content=""; var quoteContent=""; var quoteAuthor=""; $("#click").click(function() { $.getJSON("//quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?", function(key) { content=key[0].content + "<p>— " + key[0].title + "</p>"; quoteContent=key[0].content; quoteAuthor=key[0].title; $("#quote-form").html(content); console.log(content); }); $("#quote-form").css({"font-family":"lucida console", "font-size": "20px","color":"rgb(255,255,150)"}); $("#tweet-prop").attr('href','https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text='+encodeURIComponent('"'+quoteContent+'"'+'-'+quoteAuthor)); }); }); .position-message{ margin-left: 25%; margin-right:25%; margin-top:5%; } div.background{ background-color: rgba(245,245,245,0.1); border-radius:10%; padding-bottom: 2%; } .button-prop{ /*transformation : translateX(-50%); */ display: inline-block; position: relative; padding-left : 50%; /*-webkit-transform: translateX(-50%); -moz-transform: translateX(-50%); -ms-transform: translateX(-50%); -o-transform: translateX(-50%); */ } .quote-shape{ border-radius: 10%; } #page{ margin-left: 5%; margin-right: 5%; margin-top:2%; margin-bottom:2%; width: 1200px; height: 450px; max-height: 450px; } #page-background{ background-image: url(http://www.wallpapers4u.org/wp-content/uploads/grid_background_line_texture_surface_50781_1920x1080.jpg); text-align: center; } #share { height:30px; width: 80px; } .space-from-quote{ padding-top: 2%; } <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&amp;lang=en" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <Title>Click to get quotes</Title> </head> <body id="page-background"> <div class="well background" id="page"> <div id="quote" class="position-message"> <span><p id="quote-form"></p></span> </div> <!--<div class="row" id="button-shape"> <div id="share" class="col"> <a class="click" href="http://www.facebook.com/dialog/feed?app_id={{fbapp_id}}&link={{link_url}}&message={{share_message|urlencode}}&display=popup&redirect_uri={{link_url}}" target="_blank"> <i class="fa fa-facebook-official"></i> Share </a> </div>--> </div> <div class="buttons"> <a class="button" id="tweet-prop" name="tweet my quote"><i class="fa fa-twitter"></i></a> <button type="button" id="click" class="btn btn-outline-secondary btn-circle button-prop" ><i class="fa fa-refresh fa-2x"></i> </button> </body> </html> A: It's "mandatory" in the sense that you don't really have a hyperlink if it doesn't have an href. If you don't want the link to navigate anywhere, the convention is href="#", with an e.preventDefault() at the end of your click handler (which needs an e parameter). But an anchor without an href isn't a hyperlink, and so isn't going to be interactive. If your anchor has a name attribute but not an href attribute, then it's a named anchor. Named anchors aren't meant to be interacted with, and are long obsolete. But more importantly, you seem to be misusing the name attribute completely and not trying to use it for its intended purpose, given that it's name="tweet my quote", which is a nonsensical value for the attribute.
doc_23529429
Code: SELECT CASE WHEN d.id = 4 THEN (SELECT CONCAT (i.start_time, i.end_time) FROM rdf_date_time i, rdf_condition_dt h WHERE ...) ELSE '' END as timedomain FROM .. JOIN ...; start_time: 0500(5 a.m.) end_time: 1300 (13p.m.) The column timedomain looks like: 5002200 I will this format as the result: [(h5){8}] = [(start_time) {duration till end_time}] How can I convert it this way? A: to calculate interval you should just extract one time from the other, eg: t=# select '0500'::time-'1300'::time diff; diff ----------- -08:00:00 (1 row) If you column is of type integer, you have to prepare it first, like here: t=# select lpad(500::text,4,'0')::time; lpad ---------- 05:00:00 (1 row) So for you smth like below should work: (lpad(i.end_time::text,4,'0')::time - lpad(i.start_time::text,4,'0')::time)
doc_23529430
a similar issue is distinguishing between changes that should be checked in, and temporary changes that should be undone. Is there method to annotate or mark the changes? EDIT The Mercurial Queues feature presented by @nicolaskruchten appears to be just what i'm looking for. Is there a similar feature (or extension) for tfs? A: I'm not sure about TFS but in Mercurial there is the mq system, which lets you manage sets of changes as a queue of patches which you can work on separately. See here: https://www.mercurial-scm.org/wiki/MqTutorial Other than that, in Git or other distributed VCS's (including Mercurial) you would usually just go ahead and make a branch or clone another repo, given how easy and common merging is.
doc_23529431
bool setMonth(int month) { bool valid = false; if (month > 0 && month < 12) { this->month = month; valid = true; } return valid; } versus void setMonth(int month) { if (month > 0 && month < 12) { this->month = month; } } The first one lets the client of the class know explicitly whether the set failed. Is this considered good practice? A: I don't think so. This would mean that anytime you set something, you have to check whether the operation was successful or not. I think raising an exception would be a better idea, for readability and logic. I find that: /*program stuff*/ try{ YourObject.setMonth(0); /* other stuff*/ }catch YourException{ /* recovery*/ } Is cleaner that: /*program stuff*/ if(!YourObject.setMonth(0)){ /*recovery*/ }else{ /*stuff*/ } In terms of logic (I would say philosophy) and readability. A: One could argue that using boolean as a return type does not hurt. In The worst case you just ignore the check. Another one could argue that throwing an exception is more elegant and more informative too (like Java's IllegalArgumentException or Python's ValueError), however this may result in more "trouble" as exceptions have to be handled one way or another from client code. A third approach, if you need to be sure that the inserted values are absolutely correct, is to encapsulate allowed values in structural entities such as classes, enums or namespaces. An example in Java would be: public void setMonth(Month month){ this.month = month; // member month is now of type Month } public enum Month{ JANUARY(1), FEBRUARY(2), MARCH(3), APRIL(4), MAY(5), JUNE(6), JULY(7), AUGUST(8), SEPTEMBER(9), OCTOBER(10), NOVEMBER(11), DECEMBER(12) private int n; private Month(int n){ this.n = n; } } and the way of using that would be: someObject.setMonth(Month.FEBRUARY); (You can achieve the same thing with a namespace in C++.) A: Better use exceptions in setters when you want to track invalid data inserted to them. In this case signature of method is: //throw exception when month is out of range void setMonth(int month) throws InvalidMonthNumberException; In case you want to setup default data when month is out of range discribe this in javadoc. /* * If month < 1 or month > 12 default month (1) accepted */ void setMonth(int month); A: If it is java (you tagged two language) then best practice is return void from setter. In case of failed to set value then throw exception. For your case, you should throw IllegalArgumentException of month setter.
doc_23529432
describe FUNCTION extended uuid uuid() - Returns a universally unique identifier (UUID) string. The value is returned as a canonical UUID 36-character string. Example: > SELECT uuid(); '0baf1f52-53df-487f-8292-99a03716b688' > SELECT uuid(); '36718a53-84f5-45d6-8796-4f79983ad49d' I am trying to generate a uuid for every row in a table: from (select *, uuid() as id from table1) t insert into table table2 select a,b,id insert into table table3 c,id; Every single row in each table ends up with an identical uuid value. However, if I replace uuid() function with rand() function, every row ends up with a different random id. Why is uuid() only generating one value? I can't use reflect('java.util.UUID','randomUUID') because reflect is blocked by sentry. A: The UUID function was added in 2.2.0, it had a bug unfortunately in that it was not tagged as non-deterministic. If you update to 2.2.3 it will work as expected, if that is not an option, you can create your own UUID generator UDF in it's place, @UDFType(deterministic = false) public class UUIDShim extends UDF { private final Text result = new Text(); public Text evaluate() { result.set(UUID.randomUUID().toString()); return result; } }
doc_23529433
override func viewDidLoad() { super.viewDidLoad() print("SEGUE SUCCESSFUL") view.backgroundColor = .black avPlayerLayer = AVPlayerLayer(player: avPlayer) view.layer.insertSublayer(avPlayerLayer, at: 0) var asset2:AVAsset? = nil PHCachingImageManager().requestAVAsset(forVideo: (vidLocation?[videoSender]!)!, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable : Any]?) in asset2 = asset! as AVAsset }) let playerItem = AVPlayerItem(asset: asset2!) avPlayer.replaceCurrentItem(with: playerItem) } However when I run the program it pauses at the PHCachingImageManager().requestAVAsset line and shows: THREAD 1 : EXC_BREAKPOINT (highlighted in green) I'm not sure what is happening and can't find anything I understand in the documentation. How do I fix this? A: There are a couple of things you're going to want to do here in order to get this working. * *You need to cache the PHCachingImageManager as a property on an object that will stay alive. If you just create it without storing it somewhere, ARC rules will cause it to be thrown away. In the code below, I use a lazy var, but that's not the only way to do it. *You should eliminate all forced unwrapped optionals ! in your code. Using the guard let ... or if let ... patterns may feel like more typing but it will save you a lot of time and frustration in the end. Think of the ! as a danger sign that says "CRASH HERE!". *You need to set up the AVPlayerItem from the resultHandler completion block. requestAVAsset is asynchronous so that it doesn't block your main thread while it does the potentially expensive work of retrieving your asset. Basically, as soon as you call requestAVAsset a separate thread goes and does work for you, while the main thread continues working on the rest of the code in the viewDidLoad method. When it has successfully retrieved the AVAsset it calls back to the block of code you provided originally (on the main thread) so you can continue processing. Here's your code rewritten to incorporate the changes I'm suggesting: lazy var imageManager = { return PHCachingImageManager() }() override func viewDidLoad() { super.viewDidLoad() print("SEGUE SUCCESSFUL") view.backgroundColor = .black avPlayerLayer = AVPlayerLayer(player: avPlayer) view.layer.insertSublayer(avPlayerLayer, at: 0) var asset2:AVAsset? = nil guard let phAsset = vidLocation?[videoSender] else { return } //No video imageManager.requestAVAsset(forVideo: phAsset, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable : Any]?) in if let avAsset = asset { self.play(asset: avAsset) } }) func play(asset: AVAsset) { let playerItem = AVPlayerItem(asset: asset) avPlayer.replaceCurrentItem(with: playerItem) } Let me know if anything is unclear.
doc_23529434
A: Networking protocols are not pieces of code or software, they are only a set of rules. When software uses a specific networking protocol, then the software is known as an implementation. There can be many different software implementations of the same protocol (i.e. Windows and UNIX have different TCP/IP implementations). It is possible to understand networking protocols without any knowledge of programming. EDIT: How are they implemented? Here's a paper on taking an abstract specification of a protocol and implementing it into C. You'll see that less-strict protocols leave out certain details that programmers have to guess on, which makes some implementations incompatible with others. A: A network protocol is basically like a spoken language. It is implemented by code that sends and receives specially prepared messages over the network/internet, much like the vocal chords you need to speak (the network and hardware) and a brain to actually understand what someone said (the protocol stack/software). Sometimes protocols are implemented directly on the hardware [for speed reasons] (like the Ethernet protocol for LANs) - but it is always software/code required to do something useful with a protocol. This might be interesting for you: * *The OSI Model *Protocol (Computing) A: Protocols are generally built upon each other. At the risk of sounding pedantic, here's an example of a protocol and where/how it's implemented: * *Application Protocol - the way a particular application talks to another instance of itself or a corresponding server; this is implemented in the application code or a shared library *TCP (or UDP, or another layer) - the way that information is sent at the binary level and split up into usable chunks, then reassembled at the destination; this is usually implemented as part of the operating system, but it is still software code *IP - the way that information (having already been split or truncated by something like TCP or UDP) makes its way from one place to another by routing over one or more "hops"; this is always software code, but is sometimes implemented in the OS and sometimes implemented in the network device (your LAN card, for example) *base-T (ethernet), token ring, etc - Here we are physically getting into how the hardware talks to one another; ie, which wire corresponds to a particular type of signal; this is always implemented in hardware *electricity /photons - the laws that govern (or at least define) how electrons (or photons) flow over a conductive material or over the air; this is usually implemented in hardware ;) In a sense, these are all "protocols" (a set of rules or expected behaviors that allow communication to take place), and they're built on one another. Bear in mind that (aside from electricity) this is not an exhaustive list of the sort of protocols that exist at any of these layers! Edit Thanks to dmckee for pointing out that electricity isn't the only physical process used in networking ;) A: Software implements the rules defined in the protocol, some protocols are formal defined and some informal. A: a protocol is a set of rules governing the communication between two entities. in the computer/programming context, a protocol is a set of rules governing the communication between two programs. in the computer network context, a protocol is a set of rules governing the communication between two programs, well, over network. in computers, in the end everything is embodied in code... A: Protocols are basically set of rules. The way to implement them is to first of all make a state machine diagram as it completely tells that what is going to be the current state and how the state is going to change on the basis of input and what output actions are going to be performed. A: Your answer is a very short one: BY READING THE RFC. A: The main networking problem is to share data between computers. All the networking protocols try to solve is a little part of that major problem. Some of them (the protocols) are implemented as software, some others as hardware. In short, protocols like algorithms, can be implemented it in many programming languages. Back to the TCP, it is implemented by the operating system.
doc_23529435
To alleviate that issue I want to just upload the file to AWS instead of returning it to the user. My question is, if the connection times out before all of the processing and uploading is done, does rails immediately stop processing the controller action?
doc_23529436
I'll have to check cells (A's) whose position depends on other cells (B's) attributes. Instead of re-guess this dependence, I thought about storing it in a collection. This operation will be done in both directions (also access B's from A's). In other terms I need a collection capable of storing a many 2 many relation, and I am concerned with the performance for retrieving the objects. I'm also concerned with the time of insertion and removal, because my board will change over time, so i will need to insert new relations and delete others. I don't know exactly what will be the ratio between insertion/removals and access.. What container could be used ? I don't know such a container in builtin nor any lib, so I tried the following. I'm hoping you can give me some advise for using some genius lib, or a better pattern than the ones I used. # -*- coding: utf-8 -*- from timeit import timeit from collections import defaultdict import random N = 1000 r = range(1,N+1) numbers = list(r) divs = list(r) def build(container_cls): container = container_cls() for item in build_set(): container.add(*item) return container def build_set(): output = set() for n in numbers: for d in divs: if n % d == 0: output.add((n,d)) return output class Container_1: def __init__(self): self._a2b = defaultdict(set) def add(self, a, b): self._a2b[a].add(b) def remove(self, a, b): self._a2b[a].remove(b) def bs_from_a(self, a): return self._a2b[a] def as_from_b(self, b): return set(a for a,bs in self._a2b.items() if b in bs ) def items(self): return set((a,b) for a,bs in self._a2b.items() for b in bs) def __contains__(self, item) : try : return item[1] in self._a2b[item[0]] except IndexError: return False class Container_2: def __init__(self): self._a2b = defaultdict(set) self._b2a = defaultdict(set) def remove(self, a, b): self._a2b[a].remove(b) self._b2a[b].remove(a) def add(self, a, b): self._a2b[a].add(b) self._b2a[b].add(a) def bs_from_a(self, a): return self._a2b[a] def as_from_b(self, b): return self._b2a[b] def items(self): return set((a,b) for a,bs in self._a2b.items() for b in bs) def __contains__(self, item) : try : return item[1] in self._a2b[item[0]] except IndexError: return False class Container_3: def __init__(self): self._items = set() def remove(self, a, b): self._items.remove((a,b)) def add(self, a, b): self._items.add((a,b)) def bs_from_a(self, a): return set(bb for aa, bb in self._items if aa == a) def as_from_b(self, b): return set(aa for aa, bb in self._items if bb == b) def items(self): return set(self._items) def __contains__(self, item) : return item in self._items def time_wrap(command, setup): N = 10 result = timeit(command, setup, number=N) print("Setup :", setup) print("Command :", command) print("Result :", result) def time_container(container_cls): args = { "cls" : container_cls.__name__, "N" : N } print("\n\n===== {cls} =====".format(**args)) print("---Bulk Add---") setup = "from __main__ import {cls}, build_set; c={cls}(); items=build_set()".format(**args) command = "for item in items: c.add(*item)".format(**args) time_wrap(command,setup) print("---As from B---") setup = "from __main__ import {cls}, build; c = build({cls})".format(**args) command = "for i in range({N}): c.as_from_b(i)".format(**args) time_wrap(command,setup) print("---Bs from A---") setup = "from __main__ import {cls}, build; c = build({cls})".format(**args) command = "for i in range({N}): c.bs_from_a(i)".format(**args) time_wrap(command,setup) print("---Get all items") setup = "from __main__ import {cls}, build; c = build({cls})".format(**args) command = "c.items()".format(**args) time_wrap(command,setup) print("---Remove all items") setup = "from __main__ import {cls}, build; c = build({cls})".format(**args) command = "for item in c.items(): c.remove(*item)".format(**args) time_wrap(command,setup) print("---Find if in") setup = "from __main__ import {cls}, build; from itertools import product; c = build({cls})".format(**args) command = "for a,b in product(*[range(4)]*2): (a,b) in c".format(**args) time_wrap(command,setup) def assert_containers_match(container_cls_1,container_cls_2): ctn_1 = build(container_cls_1) ctn_2 = build(container_cls_2) def assert_match(): assert ctn_1.items() == ctn_2.items() for i in r: assert ctn_1.bs_from_a(i) == ctn_2.bs_from_a(i) assert ctn_1.as_from_b(i) == ctn_2.as_from_b(i) assert_match() # Tests for removal # Only tests 10 samples because it's is too time consuming for item in random.sample( ctn_1.items(), 10) : assert item in ctn_1 assert item in ctn_2 ctn_1.remove(*item) ctn_2.remove(*item) assert item not in ctn_1 assert item not in ctn_2 assert_match() assert_containers_match(Container_1, Container_2) assert_containers_match(Container_1, Container_3) time_container(Container_1) time_container(Container_2) time_container(Container_3) And here are the output calculation times : ===== Container_1 ===== ---Bulk Add--- Setup : from __main__ import Container_1, build_set; c=Container_1(); items=build_set() Command : for item in items: c.add(*item) Result : 0.015180546937699546 ---As from B--- Setup : from __main__ import Container_1, build; c = build(Container_1) Command : for i in range(1000): c.as_from_b(i) Result : 0.3854760317099135 ---Bs from A--- Setup : from __main__ import Container_1, build; c = build(Container_1) Command : for i in range(1000): c.bs_from_a(i) Result : 0.0014935762328605051 ---Get all items Setup : from __main__ import Container_1, build; c = build(Container_1) Command : c.items() Result : 0.008290981613299664 ---Remove all items Setup : from __main__ import Container_1, build; c = build(Container_1) Command : for item in c.items(): c.remove(*item) Result : 0.003233156124224479 ---Find if in Setup : from __main__ import Container_1, build; from itertools import product; c = build(Container_1) Command : for a,b in product(*[range(4)]*2): (a,b) in c Result : 4.729901911559864e-05 ===== Container_2 ===== ---Bulk Add--- Setup : from __main__ import Container_2, build_set; c=Container_2(); items=build_set() Command : for item in items: c.add(*item) Result : 0.023733136010378075 ---As from B--- Setup : from __main__ import Container_2, build; c = build(Container_2) Command : for i in range(1000): c.as_from_b(i) Result : 0.0014887000452290522 ---Bs from A--- Setup : from __main__ import Container_2, build; c = build(Container_2) Command : for i in range(1000): c.bs_from_a(i) Result : 0.0014411572165045072 ---Get all items Setup : from __main__ import Container_2, build; c = build(Container_2) Command : c.items() Result : 0.008764215610426618 ---Remove all items Setup : from __main__ import Container_2, build; c = build(Container_2) Command : for item in c.items(): c.remove(*item) Result : 0.004034069921999617 ---Find if in Setup : from __main__ import Container_2, build; from itertools import product; c = build(Container_2) Command : for a,b in product(*[range(4)]*2): (a,b) in c Result : 4.705520950665232e-05 ===== Container_3 ===== ---Bulk Add--- Setup : from __main__ import Container_3, build_set; c=Container_3(); items=build_set() Command : for item in items: c.add(*item) Result : 0.016531982304513804 ---As from B--- Setup : from __main__ import Container_3, build; c = build(Container_3) Command : for i in range(1000): c.as_from_b(i) Result : 2.7582481321151135 ---Bs from A--- Setup : from __main__ import Container_3, build; c = build(Container_3) Command : for i in range(1000): c.bs_from_a(i) Result : 2.835941646664196 ---Get all items Setup : from __main__ import Container_3, build; c = build(Container_3) Command : c.items() Result : 0.0014294543666437676 ---Remove all items Setup : from __main__ import Container_3, build; c = build(Container_3) Command : for item in c.items(): c.remove(*item) Result : 0.0019024445550712699 ---Find if in Setup : from __main__ import Container_3, build; from itertools import product; c = build(Container_3) Command : for a,b in product(*[range(4)]*2): (a,b) in c Result : 4.291044979254366e-05
doc_23529437
I have used AuthGuard, for restricting users to go to protected routes,when he is not logged in. canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { if (localStorage.getItem('isLoggedIn') === null || localStorage.getItem('isLoggedIn') === 'false') { return true; } this.router.navigate([state.url]); return false; }) A: You can create an array of home and details urls. For example, const restrictedRoutes = ['about', 'details']; And after checking user loggedIn or not, you can add one more condition of checking current routes exist in restrictedRoutes. Based on that you can redirect user to other pages. if (restrictedRoutes.includes(route.url)) { // redirect path } this.router.navigate([state.url]); return false; A: // general routes are '/home', '/details' use a candeactivate authguard in other authenticated routes( where user should be loggedIn). there you can check the condition and reject/redirect. import { Injectable } from '@angular/core'; import { CanDeactivate } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { Router} from '@angular/router'; export interface CanComponentDeactivate { canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean; } @Injectable() export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> { openRoutes = ['/home', '/details']; intendedRoute: string = ''; constructor(private _router: Router) { this.intendedRoute = _router.url; } canDeactivate(component: CanComponentDeactivate) { return this.openRoutes .includes(this.intendedRoute)? component.canDeactivate() : true; } } if the condition is true you can cancel navigation by returning false from the canDeactivate method in your respective component.
doc_23529438
switch(getDrawableId(buttonRepeat)) { case R.drawable.a: mediaPlayer.setLooping(true); break; case R.drawable.b: mediaPlayer.setLooping(false); break; default: break; } A: Use getDrawable() method in ImageButton and compare them using .getConstantState().equals() Sample code: ImageButton btn = (ImageButton) findViewById(R.id.myImageBtn); Drawable drawable = btn.getDrawable(); if (drawable.getConstantState().equals(getResources().getDrawable(R.drawable.myDrawable).getConstantState())){ //Do your work here } References: http://developer.android.com/reference/android/widget/ImageButton.html Comparing two drawables in android
doc_23529439
type = numeric(length(r)) for (i in 1:10) { if ( ((s_mov[i] < s_rot[i]) & (e_rot[i] < e_mov[i])) | ((s_rot[i] < s_mov[i]) & (s_mov[i] < e_rot[i])) == TRUE) { type[i]=1 } else if ( ((s_doc[i] < s_rot[i]) & (e_rot[i] < e_doc[i]) == TRUE) { type[i]=2 } else if ( ((s_rot[i] < e_mov[i]) & (s_doc[i] < e_rot[i])) | ((s_rot[i] < s_mov[i]) & (s_doc[i] < e_rot[i])) == TRUE) { type[i]=3 } } or I've tried this way as well for (i in 1:10) { if ( ((s_mov[i] < s_rot[i]) & (e_rot[i] < e_mov[i])) | ((s_rot[i] < s_mov[i]) & (s_mov[i] < e_rot[i])) == TRUE) { type[i]=1 } else if ( ((s_doc[i] < s_rot[i]) & (e_rot[i] < e_doc[i]) == TRUE) { type <- replace(type, type[i],2 } else if ( ((s_rot[i] < e_mov[i]) & (s_doc[i] < e_rot[i])) | ((s_rot[i] < s_mov[i]) & (s_doc[i] < e_rot[i])) == TRUE) { type <- replace(type, type[i],3 } } but I'm constantly getting Error: unexpected '{' in: What's wrong? I'm not sure but I think depending on the data, when all 1:10 satisfy first if statement, it writes 1 for all 10 elements, and rather than stooping, it continues and cause error. A: It looks like you're missing several closing brackets in different places. I highly recommend using a good IDE, such as RStudio, which has a side-benefit of highlighting the matching brackets. Both the type <- replace... statements need a closing ). Just by eyeballing, it looks like the first else if is missing a closing ) as well: else if ( ((s_doc[i] < s_rot[i]) & (e_rot[i] < e_doc[i]) == TRUE) { you have 4 opening and only 3 closing brackets in there. I haven't checked the other statements, but you should. A: In the first example, your first else if has an extra (. In the second example, your first else if has an extra (, and your replace functions have no ).
doc_23529440
I have visualization of probality for every model, looks like this for number 0 -data of probability are in variable prediction0 Then i have trained final classificator and i have 1423 correct observations (from 1499) - i have vector c= containing numbers correctly predicted What i need to do, is when was 0 correctly predicted in vector c, mark that point on red on this graf. If it helps i have "ck" containing probalities for all number prediction for every test sample, where i get maximum probality, which was my final prediction. A: You can do this by using the col argument. I'll use the mtcars dataset as an example plot( mpg~disp, data=mtcars, col=ifelse(mtcars$am==0,"red","blue") )
doc_23529441
#include "stdafx.h" #include <iostream> #include <conio.h> #include <windows.h> using namespace std; void gotoxy(int x, int y) { static HANDLE h = NULL; if(!h) h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = { x, y }; SetConsoleCursorPosition(h,c); } int main() { int Keys; int poz_x = 1; int poz_y = 1; gotoxy(poz_x,poz_y); while(true) { fflush(stdin); Keys = getch(); if (Keys == 77) gotoxy(poz_x+1,poz_y); } cin.get(); return 0; } It's working but just once - second, third etc. pressed not working. A: You never change poz_x in your code. In your while loop you always move to the initial value +1. A code like this should be correct: while(true) { Keys = getch(); if (Keys == 77) { poz_x+=1; gotoxy(poz_x,poz_y); } } A: You never change poz_x, so you always end up calling gotoxy(2,1); in the loop. A: For the up, right, left, down you can make "Keys" a char value instead of int and in that case you can move with the keys "w" for up, "s" for down, "a" for left and "d" for right: char Keys; while(true){ Keys = getch(); if (Keys == 'd'){ poz_x+=1; gotoxy(poz_x,poz_y); } if(Keys=='w'){ poz_y-=1; gotoxy(poz_x,poz_y); } if(Keys=='s'){ poz_y+=1; gotoxy(poz_x,poz_y); } if(Keys=='a'){ poz_x-=1; gotoxy(poz_x,poz_y); } } A: The code below should work! :) #include <windows.h> using namespace std; POINT p; int main(){ while(true){ GetCursorPos(&p); Sleep(1); int i = 0; if(GetAsyncKeyState(VK_RIGHT)){ i++; SetCursorPos(p.x+i, p.y); } } }
doc_23529442
My backend can be very resource-intensive as I'm developing a task that processes a large amount of time-series data. It can take about 5-10 mins on my machine. I'm using a 15-inch Macbook pro as my local machine and running docker and my development setup is really pushing my machine to the limits. I'm considering running docker on another Linux PC I have and connecting to it from my MacBook pro. I use CircleCI quite a bit and they have some setup with docker where the CI containers you run don't actually run docker themselves but are networked out to a separate dedicated machine. The only issue is mapping volumes don't work too great. How can I set this up in docker so that I can run docker commands locally that run on a separate machine? Any ideas how I can map the directories to the other machine? A: You can use SSH to run commands on another machine: ssh user@server docker run hello-world I would recommend against mapping volumes, as that doesn't work well. Instead, I'd simply copy the data you needed to the server. scp -r directory-to-copy/* user@server:/destination-to-copy-into
doc_23529443
Is anyone aware of a resource that explains the process/logic flow at a higher level, to help me understand how the UserJourneys, ClaimsProviders, and other components actually interact? thanks! Martin A: Documentation can be found in this GitHub repository. This was drafted for the custom policies preview (known as the "Azure AD B2C Premium" service when this was written). Some of it is out-of-date but it does describe the high-level concepts and details the custom policy schema.
doc_23529444
So I think this must be caused by the js file, it may cause the memory leak, but I have not idea how to find the problem. Any one can give me some suggestion? A: I would give DynaTrace Ajax Edition a try. A: Here is an article about one of the ways you can find memory leaks with Chrome's Developer Tools: https://developers.google.com/chrome-developer-tools/docs/heap-profiling. Also, this article tells you about how memory leaks can take place in JavaScript, in general: http://www.javascriptkit.com/javatutors/closuresleak/index.shtml. The usual case is when there are circular references between JavaScript world and the DOM world. The JavaScript world does have a GC that knows how to clean up circular references, but the DOM world has an entirely different GC. Combining the two worlds in some ways (which look innocuous at first) can lead to memory leaks even in modern browsers. If the memory fills up quickly it is often due to detached DOM trees. If these are canvas elements or images, they can take much more memory than they appear to in the profiler tool (because the image data is store somewhere else). This is just one example, of course - there are many ways in which you can fill up the memory quickly. A: You want to use valgrind with the browser if you want to check for a memory leak.
doc_23529445
But now i wish to allow user to choose any single image from multiple images, like 10 images stored in a particular folder in SDCard, and then post to Wall. So here is my question, how to do that? My existing code to post static image on Wall, read below: @Override public void onClick(DialogInterface dialog, int which) { Bundle params = new Bundle(); params.putString("to", String.valueOf(friendId)); params.putString("caption", getString(R.string.app_name)); params.putString("description", getString(R.string.app_desc)); params.putString("link", "http://www.google.com"); params.putString("picture",FacebookUtility.HACK_ICON_URL); params.putString("name",getString(R.string.app_action)); FacebookUtility.facebook.dialog(FriendsList.this, "feed", params, (DialogListener) new PostDialogListener()); } }).setNegativeButton(R.string.no, null).show(); } catch (JSONException e) { showToast("Error: " + e.getMessage()); } FacebookUtility.java:- public static final String HACK_ICON_URL = "http://2.bp.blogspot.com/-WuasmTMjMA4/TY0SS4TzIMI/AAAAAAAAFB4/6alyfOzWsqM/s320/flowers-wallpapers-love-blooms-roses-bunch-of-flowers.jpg"; Check existing screen of my app, As you can see in above screen i am showing only single static image as i have written above, but now i wanna allow user to choose an image from multiple images using SD Card, my SDCard path like: /sdcard/FbImages/ now i want to know how to place button in above screen [because i am not using any custom xml for this, that's native feature in FacebookSDK] So here is my question how to open sdcard folder and how to choose single image to post from multiple images A: you have to find path for that image. try following code to select image btnSelect.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Picture"), 0); } }); get path for selectd image public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == 0) { Uri selectedImageUri = data.getData(); selectedImagePath = getPath(selectedImageUri); System.out.println("Image Path : " + selectedImagePath); } } } public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } then use params.putString("picture",selectedImagePath); A: Thanks for notifying me to the answer here. As you have seen here, I am sending app request to my Facebook friend. However its nothing like to post photo on Friend's wall. There you only able to post App icon with the url ASK. If you want to post photo on Friends wall with message then please check my below answer. Bundle param = new Bundle(); param.putString("message", "picture caption"); param.putByteArray("picture", ImageBytes); mAsyncRunner.request("me/photos", param, "POST", new SampleUploadListener()); In my above code, ImageBytes is the byte[] of the Image. You will have to play little to select image from the particular folder then convert that selected image in to byte[]. Use that byte[] in my above code. A: Use it when pick bitmap from sdcard and give the path also past this code. protected void share(String nameApp, String imagePath, String text) { // TODO Auto-generated method stub try { List<Intent> targetedShareIntents = new ArrayList<Intent>(); Intent share = new Intent(android.content.Intent.ACTION_SEND); share.setType("image/jpeg"); List<ResolveInfo> resInfo = getPackageManager() .queryIntentActivities(share, 0); if (!resInfo.isEmpty()) { for (ResolveInfo info : resInfo) { Intent targetedShare = new Intent( android.content.Intent.ACTION_SEND); targetedShare.setType("image/jpeg"); // put here your mime // type if (info.activityInfo.packageName.toLowerCase().contains( nameApp) || info.activityInfo.name.toLowerCase().contains( nameApp)) { targetedShare.putExtra(Intent.EXTRA_SUBJECT, text); targetedShare.putExtra(Intent.EXTRA_TEXT, text); targetedShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imagePath))); targetedShare.setPackage(info.activityInfo.packageName); targetedShareIntents.add(targetedShare); } } Intent chooserIntent = Intent.createChooser( targetedShareIntents.remove(0), "Select app to share"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[] {})); startActivity(chooserIntent); } } catch (Exception e) { } }
doc_23529446
I created a singlePod.yaml file to properly describe the kubernetes pod service that passes arguments, and can run like this: kubectl create -f ./singlePod.yaml I want the arguments called to match Docker: docker run -it -p 8080:8080 joethecoder2/spring-boot-web cassandra_ip=127.0.0.1 cassandra_port=9042 apiVersion: v1 kind: Pod metadata: name: spring-boot-web-demo labels: purpose: demonstrate-spring-boot-web spec: containers: - name: spring-boot-web image: docker.io/joethecoder2/spring-boot-web env: - name: "cassandra_ip" value: "127.0.0.1" - name: "cassandra_port" value: "9042" command: ["java","-jar", "spring-boot-web-0.0.1-SNAPSHOT.jar", "cassandra_ip=127.0.0.1", "cassandra_port=9042"] args: ["$(cassandra_ip)", "$(cassandra_port)"] restartPolicy: OnFailure <!-- Paste the part of the code that shows the problem. (Please indent 4 spaces.) --> The problem is that although the arguments have been added to the below service, the arguments do not take effect to the calling program (spring-boot-web-0.0.1-SNAPSHOT.jar) Name: spring-boot-web-demo Namespace: default Node: minikube/192.168.64.3 Start Time: Thu, 07 Dec 2017 12:08:10 -0500 Labels: purpose=demonstrate-spring-boot-web Annotations: <none> Status: Running IP: 172.17.0.2 Controllers: <none> Containers: spring-boot-web: Container ID: docker://1c9543e412b50b36182528d690121014dfe7c9dd6409ce689d1a08fbad7c2436 Image: docker.io/joethecoder2/spring-boot-web Image ID: docker-pullable://joethecoder2/spring-boot-web@sha256:ebf94365075e0ee16a50cab41d8e1307785a93c60be600f94bb82a4dbefb6bc0 Port: Command: java -jar spring-boot-web-0.0.1-SNAPSHOT.jar cassandra_ip=127.0.0.1 cassandra_port=9042 Args: $(cassandra_ip) $(cassandra_port) State: Running Started: Thu, 07 Dec 2017 12:08:11 -0500 Ready: True Restart Count: 0 Environment: cassandra_ip: 127.0.0.1 cassandra_port: 9042 Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-wgdn6 (ro) Conditions: Type Status Initialized True Ready True PodScheduled True Volumes: default-token-wgdn6: Type: Secret (a volume populated by a Secret) SecretName: default-token-wgdn6 Optional: false QoS Class: BestEffort Node-Selectors: <none> Tolerations: <none> Events: FirstSeen LastSeen Count From SubObjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 8m 8m 1 default-scheduler Normal Scheduled Successfully assigned spring-boot-web-demo to minikube 8m 8m 1 kubelet, minikube Normal SuccessfulMountVolume MountVolume.SetUp succeeded for volume "default-token-wgdn6" 8m 8m 1 kubelet, minikube spec.containers{spring-boot-web} Normal Pulling pulling image "docker.io/joethecoder2/spring-boot-web" 8m 8m 1 kubelet, minikube spec.containers{spring-boot-web} Normal Pulled Successfully pulled image "docker.io/joethecoder2/spring-boot-web" 8m 8m 1 kubelet, minikube spec.containers{spring-boot-web} Normal Created Created container 8m 8m 1 kubelet, minikube spec.containers{spring-boot-web} Normal Started Started container I am expecting the results from the calling java program: to use the cassandra_ip and cassandra_port The service, does not properly show the arguments being displayed by the service, and also the running java program inside docker, does not show that the arguments are called. Command: java -jar spring-boot-web-0.0.1-SNAPSHOT.jar cassandra_ip=127.0.0.1 cassandra_port=9042 Args: $(cassandra_ip) $(cassandra_port) A: change it like this. it will work. spec: containers: - name: spring-boot-web image: docker.io/joethecoder2/spring-boot-web env: - name: "cassandra_ip" value: "127.0.0.1" - name: "cassandra_port" value: "9042" command: ["/bin/sh","-c", "java -jar spring-boot-web-0.0.1-SNAPSHOT.jar cassandra_ip=$cassandra_ip", "cassandra_port=$cassandra_port] restartPolicy: OnFailure
doc_23529447
And there is a 3rd table that holds of the mails of the site. Mails sent from the regular users to the business_users OR the super_admins(support etc...). As such this mails table has 2 cols(from,to) where they reference the userID column is the users table. And here is the problem, suppose the business_user deletes his account.I intend deleting also the mails that he has sent(whether they are towards the regular users or the super admins) The problem is that the way the mails table is structured it is inevitable that deleting the mails described above, I will delete also the mails sent to HIM by the regular user of super_admin. There are 2 scenarios examined: * *Delete no mails at all-at which case, the discussion ends here. *Redesign the db so that mails sent to him are not deleted(the reg_users will still have the mails in their screen), but on the other hand mails send by him are deleted. What do you propose? If going with 2nd option how I should design the db. Here are the 3 tables: CREATE TABLE IF NOT EXISTS `alternative_appointm`.`users` ( `user_ID` INT(11) NOT NULL AUTO_INCREMENT , `name` VARCHAR(45) NOT NULL , `lastname` VARCHAR(45) NOT NULL , `email` VARCHAR(255) NULL DEFAULT NULL , `password` VARCHAR(100) NULL DEFAULT NULL , `hash` VARCHAR(32) NULL DEFAULT NULL , `usertype` ENUM('1','2','3','4') NULL DEFAULT NULL , PRIMARY KEY (`user_ID`) , INDEX `fk_users_usertype1_idx` (`usertype` ASC) , CONSTRAINT `fk_users_usertype1` FOREIGN KEY (`usertype` ) REFERENCES `alternative_appointm`.`usertype` (`type_id` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 CREATE TABLE IF NOT EXISTS `alternative_appointm`.`business_users` ( `crID` INT(11) NOT NULL , `address` VARCHAR(45) NULL DEFAULT NULL , `url` VARCHAR(45) NULL DEFAULT NULL , `phone` VARCHAR(20) NULL , `city` VARCHAR(100) NULL , `municipality` VARCHAR(100) NULL , `bus_user_type` ENUM('1','2','3','4','5') CHARACTER SET 'latin1' NULL , PRIMARY KEY (`crID`) , INDEX `fk_business_users_buz_usertype1_idx` (`bus_user_type` ASC) , INDEX `crID` (`crID` ASC) , CONSTRAINT `fk_business_users_buz_usertype1` FOREIGN KEY (`bus_user_type` ) REFERENCES `alternative_appointm`.`buz_usertype` (`Type_id` ) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_business_users_users1` FOREIGN KEY (`crID` ) REFERENCES `alternative_appointm`.`users` (`user_ID` ) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 CREATE TABLE IF NOT EXISTS `alternative_appointm`.`mails` ( `message-iD` INT(10) NOT NULL AUTO_INCREMENT , `from` INT(11) NULL DEFAULT NULL , `to` INT(11) NULL DEFAULT NULL , `datetime` DATETIME NULL DEFAULT NULL , `subject` TEXT NULL DEFAULT NULL , `message` TEXT NULL DEFAULT NULL , PRIMARY KEY (`message-iD`) , UNIQUE INDEX `message-iD_UNIQUE` (`message-iD` ASC) , INDEX `fk_mails_users1_idx` (`from` ASC) , INDEX `fk_mails_users2_idx` (`to` ASC) , CONSTRAINT `fk_mails_users1` FOREIGN KEY (`from` ) REFERENCES `alternative_appointm`.`users` (`user_ID` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_mails_users2` FOREIGN KEY (`to` ) REFERENCES `alternative_appointm`.`users` (`user_ID` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 A: On table alternative_appointm.mails You have to integrity constraints. Currently: CONSTRAINT `fk_mails_users1` FOREIGN KEY (`from` ) REFERENCES `alternative_appointm`.`users` (`user_ID` ) ON DELETE NO ACTION ON UPDATE NO ACTION, And CONSTRAINT `fk_mails_users2` FOREIGN KEY (`to` ) REFERENCES `alternative_appointm`.`users` (`user_ID` ) ON DELETE NO ACTION ON UPDATE NO ACTION) First step would be to add 'ON UPDATE CASCADE', you should do that on most constraints, it means if you ever update a user id it will directly be updated on the from or to columns. Next thing is that when a user is deleted on the users tables you want to delete all mails he send and not the one he receiveid. So you only want to delete mails where you can find the user id in the from column. So update the first constraint, only this one, not the one about the 'to' column: CONSTRAINT `fk_mails_users1` FOREIGN KEY (`from` ) REFERENCES `alternative_appointm`.`users` (`user_ID` ) ON DELETE CASCADE ON UPDATE CASCADE, The second constraint will prevent deleting the user if some data reference the user id that you want to delete. To allow the deletion you should empty the field (NO ACTION is the same as RESTRICT) By using this constraint: CONSTRAINT `fk_mails_users2` FOREIGN KEY (`to` ) REFERENCES `alternative_appointm`.`users` (`user_ID` ) ON DELETE SET NULL ON UPDATE CASCADE) You will have a working deletion, mail sent to this user are still on the table, but, you do not have the id of this user in the 'to' column, (and this id does not exists anymore). You could use a transaction to alter the rows impacted and set a special id in the 'to' column, something like a default 'deleted user' user account id. On postgreSQl you would have the 'ON DELETE SET DEFAULT', but this does not exists in MySQL AFAIK.
doc_23529448
<a href="#about">about</a> <a name="about"></a> This approach is not work because my page implement ui router, when I defined href="#about", it detect as otherwise url, so will be redirect to wrong state. From other source I get insight about multiple views in ui.router, so I designed config like this: .state('landing', { url: '/', views: { "" : { templateUrl: "tpl/landing/index.html"}, "header@landing" : { templateUrl: "tpl/landing/header.html"}, "about@landing" : { templateUrl: "tpl/landing/about.html"}, "contact@landing" : { templateUrl: "tpl/landing/contact.html"}, "section-a@landing" : { templateUrl: "tpl/landing/section-a.html"}, "section-b@landing" : { templateUrl: "tpl/landing/section-b.html"}, "services@landing" : { templateUrl: "tpl/landing/services.html"}, "footer@landing" : { templateUrl: "tpl/landing/footer.html"} } }) Content of tpl/landing/index.html is: <div ui-view="header" autoscroll="true"></div> <div ui-view="about" autoscroll="false"></div> <div ui-view="contact" autoscroll="false"></div> <div ui-view="section-a" autoscroll="false"></div> <div ui-view="section-b" autoscroll="false"></div> <div ui-view="services" autoscroll="false"></div> <div ui-view="footer" autoscroll="false"></div> In multi state ui.router we can go to other state by defined ui-sref="astate". How about in multiple views? how to go to other view in same state? A: What you are trying to do can be solved using $anchorScroll. See here for more information: https://docs.angularjs.org/api/ng/service/$anchorScroll In their example, you can see: <div id="scrollArea" ng-controller="ScrollController"> <a ng-click="gotoBottom()">Go to bottom</a> <a id="bottom"></a> You're at the bottom! </div> Then inside the gotoBottom() function they use: $location.hash('bottom'); // call $anchorScroll() $anchorScroll(); This will scroll to the div whose id is bottom. Hopefully that helps you.
doc_23529449
Each database consist of order history as well as all other details like contact details etc. I will get an url argument to identify customer through customer_id & I will able to get which database to use ie db name. Code - Model - class Company(models.Model): company_id = models.IntegerField(primary_key = True) name = models.CharField(max_length=256, blank=True, null=True) db_name = models.CharField(max_length=200, blank=True, null=True) db_uuid = models.CharField(max_length=100, blank=True, null=True) objects = DataFrameManager() def __str__(self): return self.name Views file - @api_view(['GET', 'POST']) def page(request, uuid): if request.method == 'GET': rtrn = Company.objects.filter(db_uuid=uuid).values('db_name') return Response(rtrn) Url file - urlpatterns = [ url(r'user/(?P<uuid>[a-zA-Z0-9-]+)/$', page, name="getfromurl"), ] Here I will return db name. But I am not able to understand and implement the change of database. Let me make you understand with an example - Lets suppose Customer name Gaurav has db 'gaurav_groceries'. By the code I get the name - gaurav_groceries. But in setting.py I have added default db as 'grocies', so how can I use this dynamic nature of db ie in this case we have 'gaurav_groceries', for further calculation and coding. Thank you A: What you are trying to do isn't trivially achieved. You may want to check out existing solutions, such as Django-multitenant which is currently the standard library used for building apps with tenanted DBs in Django.
doc_23529450
Raw data table: Interface_Bin Product 1 ADL 1 ADL 22 ADL 97 ADL 1 JSL 1 JSL 97 JSL 97 JSL 22 JSL Expected outcome: Product Bin(97)_count Total_interfacebin_count Bin_97_percentage_vs total count ADL 1 4 25% JSL 2 5 40% Thanks alot. A: Use crosstab with concat: df = pd.crosstab(df['Product'], df['Interface_Bin']) f1 = lambda x: f'Bin({x})_count' f2 = lambda x: f'Bin({x})_percentage_vs total count' s = df.sum(axis=1).rename('Total_interfacebin_count') df2 = df.div(s, axis=0).rename(columns=f2).mul(100) df = pd.concat([df.rename(columns=f1), s, df2], axis=1).sort_index(axis=1) print (df) Bin(1)_count Bin(1)_percentage_vs total count Bin(22)_count \ Product ADL 2 50.0 1 JSL 2 40.0 1 Bin(22)_percentage_vs total count Bin(97)_count \ Product ADL 25.0 1 JSL 20.0 2 Bin(97)_percentage_vs total count Total_interfacebin_count Product ADL 25.0 4 JSL 40.0 5 A: first sort the data so you get a dictionary (or list) like: {"ADL":121,"JSL":218} probably with code like for element in table row: if dict.contains(element.key) //in this case ADL or JSL dict[element.key].value+=element.value else dict[element.key]=element.value then go through and sum all the dictionary values to get the total sum, or sum them as you add to the dictionary in the above code finally get each percentage as (dict[key].value/sum)*100 + "%"
doc_23529451
I Checked My code 2 times and still throws exception, i don't know what to do anymore just can't. Any Help is greatly appreciated. EDIT: If you need more code then comment about it. terrainVertexShader #version 400 core in vec3 position; in vec2 textureCoordinates; in vec3 normal; out vec2 pass_textureCoordinates; out vec3 surfaceNormal; out vec3 toLightVector; out vec3 toCameraVector; out float visibility; uniform mat4 transformationMatrix; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform vec3 lightPosition; const float density = 0.007; const float gradient = 1.5; void main(void){ vec4 worldPosition = transformationMatrix * vec4(position,1.0); vec4 positionRelativeToCam = viewMatrix * worldPosition; gl_Position = projectionMatrix * positionRelativeToCam; pass_textureCoordinates = textureCoordinates * 40.0; surfaceNormal = (transformationMatrix * vec4(normal,0.0)).xyz; toLightVector = lightPosition - worldPosition.xyz; toCameraVector = (inverse(viewMatrix) * vec4(0.0,0.0,0.0,1.0)).xyz - worldPosition.xyz; float distance = length(positionRelativeToCam.xyz); visibility = exp(-pow((distance*density), gradient)); visibility = clamp(visibility, 0.0, 1.0); } terrainFragmentShader #version 400 core in vec2 pass_textureCoordinates; in vec3 surfaceNormal; in vec3 toLightVector; in vec3 toCameraVector; in float visibility out vec4 out_Color; uniform sampler2D modelTexture; uniform vec3 lightColour; uniform float shineDamper; uniform float reflectivity; uniform vec3 skyColour; void main(void){ vec3 unitNormal = normalize(surfaceNormal); vec3 unitLightVector = normalize(toLightVector); float nDotl = dot(unitNormal,unitLightVector); float brightness = max(nDotl,0.0); vec3 diffuse = brightness * lightColour; vec3 unitVectorToCamera = normalize(toCameraVector); vec3 lightDirection = -unitLightVector; vec3 reflectedLightDirection = reflect(lightDirection,unitNormal); float specularFactor = dot(reflectedLightDirection , unitVectorToCamera); specularFactor = max(specularFactor,0.0); float dampedFactor = pow(specularFactor,shineDamper); vec3 finalSpecular = dampedFactor * reflectivity * lightColour; out_Color = vec4(diffuse,1.0) * textureColour + vec4(finalSpecular,1.0); out_Color = mix(vec4(skyColour,1.0), out_Color, visibility); } TerrainShader package shaders; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import entities.Camera; import entities.Light; import toolbox.Maths; public class TerrainShader extends ShaderProgram{ private static final String VERTEX_FILE = "src/shaders/terrainVertexShader.txt"; private static final String FRAGMENT_FILE = "src/shaders/terrainFragmentShader.txt"; private int location_transformationMatrix; private int location_projectionMatrix; private int location_viewMatrix; private int location_lightPosition; private int location_lightColour; private int location_shineDamper; private int location_reflectivity; private int location_skyColour; public TerrainShader() { super(VERTEX_FILE, FRAGMENT_FILE); } @Override protected void bindAttributes() { super.bindAttribute(0, "position"); super.bindAttribute(1, "textureCoordinates"); super.bindAttribute(2, "normal"); } @Override protected void getAllUniformLocations() { location_transformationMatrix = super.getUniformLocation("transformationMatrix"); location_projectionMatrix = super.getUniformLocation("projectionMatrix"); location_viewMatrix = super.getUniformLocation("viewMatrix"); location_lightPosition = super.getUniformLocation("lightPosition"); location_lightColour = super.getUniformLocation("lightColour"); location_shineDamper = super.getUniformLocation("shineDamper"); location_reflectivity = super.getUniformLocation("reflectivity"); location_skyColour = super.getUniformLocation("skyColour"); } public void loadSkyColour(float r, float g, float b) { super.loadVector(location_skyColour, new Vector3f(r,g,b)); } public void loadShineVariables(float damper,float reflectivity){ super.loadFloat(location_shineDamper, damper); super.loadFloat(location_reflectivity, reflectivity); } public void loadTransformationMatrix(Matrix4f matrix){ super.loadMatrix(location_transformationMatrix, matrix); } public void loadLight(Light light){ super.loadVector(location_lightPosition, light.getPosition()); super.loadVector(location_lightColour, light.getColour()); } public void loadViewMatrix(Camera camera){ Matrix4f viewMatrix = Maths.createViewMatrix(camera); super.loadMatrix(location_viewMatrix, viewMatrix); } public void loadProjectionMatrix(Matrix4f projection){ super.loadMatrix(location_projectionMatrix, projection); } } A: In TerrainFragmentShader you are missing a semicolon after visibility #version 400 core in vec2 pass_textureCoordinates; in vec3 surfaceNormal; in vec3 toLightVector; in vec3 toCameraVector; in float visibility //<-semicolon here
doc_23529452
Somehow the BorderPane is able to tell the ScrollPane when to display Scrollbars and the TabPane unable to do so. I looked through the avaible Methods for the Tabpane but couldn't find any for this resizing. Working Example: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ScrollPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.*; import javafx.stage.Stage; public class FXApplication extends Application { private BorderPane border; private GridPane inner; private TabPane tabPane; @Override public void start(Stage primaryStage) { tabPane = new TabPane(); Tab tab = new Tab("test"); tabPane.getTabs().add(tab); border = new BorderPane(); border.setCenter(innerGrid()); tab.setContent(border); ScrollPane scp = new ScrollPane(); scp.setFitToHeight(true); scp.setFitToWidth(true); scp.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); scp.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); // scp.setContent(border); // this works scp.setContent(tabPane); // this doesnt Scene s = new Scene(scp); primaryStage.setScene(s); primaryStage.show(); } private GridPane innerGrid() { inner = new GridPane(); for(int i=0; i<11 ;i++) { ColumnConstraints columnConstraints = new ColumnConstraints(); columnConstraints.setHgrow(Priority.SOMETIMES); inner.getColumnConstraints().add(columnConstraints); RowConstraints rowConstraints = new RowConstraints(); rowConstraints.setVgrow(Priority.SOMETIMES); inner.getRowConstraints().add(rowConstraints); } for(int i=0; i<100 ;i++) { inner.add(new Button("Button " + i), i/10, i%10); } return inner; } public static void main(String[] args) { FXApplication.launch(args); } } A: Astonishingly, the exact behavior of AS_NEEDED is unspecified. All we have is the ScrollPaneSkin to look at. The decision whether or not to show the (f.i.) horizontal bar happens in its private method determineHorizontalSBVisible() private boolean determineHorizontalSBVisible() { final ScrollPane sp = getSkinnable(); if (Properties.IS_TOUCH_SUPPORTED) { return (tempVisibility && (nodeWidth > contentWidth)); } else { // RT-17395: ScrollBarPolicy might be null. If so, treat it as "AS_NEEDED", which is the default ScrollBarPolicy hbarPolicy = sp.getHbarPolicy(); return (ScrollBarPolicy.NEVER == hbarPolicy) ? false : ((ScrollBarPolicy.ALWAYS == hbarPolicy) ? true : ((sp.isFitToWidth() && scrollNode != null ? scrollNode.isResizable() : false) ? (nodeWidth > contentWidth && scrollNode.minWidth(-1) > contentWidth) : (nodeWidth > contentWidth))); } } Here nodeWidth is the actual width of the content node - has been calculated previously, respecting the node's min/max widths - and contentWidth is the width available for laying out the content. Unreadable code (for me ;) In the case of resizable content and fitting into scrollPane's content area boils down to returning true if both content's actual and min width are greater than the available width. The minWidth makes the difference in your context: BorderPane has a min > 0, TabPane has a min == 0, so the method above always returns false. The other way round: to allow the hbar being visible with the TabPane it needs a min, f.i. by relating it to its pref: tabPane.setMinWidth(Region.USE_PREF_SIZE);
doc_23529453
I have a web project, created in NetBeans 7.3, using GlassFish 3.1.2, JSF2.0, EJB3.0 and MySQL I'm at the beginning of the project and have come across this problem which is as follows: When I input some word with á, à, ã, ç, etc on the inputText, this word is stored with bizarre characters in the database. What I've done to try to resolve: 1 -) I put the project encode to UTF-8. Right click on project> Properties> Encode = UTF-8. 2 -) Compile options-enconding = UTF-8. Right click on project> Properties> Compile-encoding = UTF8. 3 -) vm-options = Dfile.encoding = UTF-8. Right click on project> Properties> Run =-Dfile.encoding = UTF-8. 4 -) private.properties project netbeans, I added the line: runtime.encoding = UTF-8. 5 -) changed the netbeans.conf file which is in the installation folder of netbeans, I added the line-J-Dfile.encoding = UTF-8 option in netbeans_default_options. 6 -) a table in my database is to encode UTF-8 By debug I've checked that by the method that saves the object in the database: public void create(T entity) { getEntityManager().persist(entity); } no problems with String, ie, with accentuation is ok. The problem happens from now on, where I can no longer debug ... I edited the connection pool's settings of GlassFish on the admin panel with the property characterEncoding = UTF-8. And finally I edited the jdbc connecion as jdbc:mysql://localhost:3306/igreja?characterEncoding=utf8 I'm going crazy with this bug. Please anyone out there has gone through this? I thank you in advance! Daniel A: I'm from Mexico, so we use ñ and this char doesn't work in other countries so what we do is use (char)+number something like this: (char)225 = á (char)224 = à (char)227 = ã (char)231 = ç maybe can help you A: I solved the problem..... I downloaded the multilingual version of GlassFish (glassfish-3.1.2.2-unix-ml.sh)... And inside the jsf page I did it: <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </h:head> <h:body> <f:view encoding="UTF-8"> <h:form enctype="multipart/form-data;charset=UTF-8"> I hope that this solution could help other users... Many thanks guys!!!!
doc_23529454
A: First, it would be nice if you provided a minimal example with some data and what you are trying to achieve. I assume you have a text and you wish to inspect how similar sentences in this text are. First, you will have to split your text into sentences and put them in separate rows (one sentence per row). There's a script for that in orange-scripts. Then use any of the clustering approaches, bag of words or document embedding. You can find tutorials on YouTube.
doc_23529455
result = urllib.urlretrieve( "https://secure.gravatar.com/avatar.php?"+ urllib.urlencode({ 'gravatar_id': hashlib.md5(email).hexdigest(), 'size': srt(size) }) ) A: Try downloading code style linters such as pep8 (a program which checks your code to see if it matches PEP 8 requirements) or pylint. You can find a more comprehensive list and comparison of Python style checkers here: What are the comprehensive lint checkers for Python? In fact, there's a pep8 checker available online: http://pep8online.com/ If we run your code through that, it tells you: Code Line Column Text E126 2 29 continuation line over-indented for hanging indent E225 2 70 missing whitespace around operator E126 4 45 continuation line over-indented for hanging indent E501 4 80 line too long (90 > 79 characters) W292 7 30 no newline at end of file The fixed version of your code would look more like this: result = urllib.urlretrieve( "https://secure.gravatar.com/avatar.php?" + urllib.urlencode({ 'gravatar_id': hashlib.md5(email).hexdigest(), 'size': srt(size) }) ) In essence, the main PEP 8 violation you had was that you were indenting too much. A single indent is fine -- you don't need to align to the opening paren of the function calls. Python is also insistent that your lines don't go beyond 80 characters, but fixing the over-indentation also fixed that issue. A: Use more variables. Not only are lines easier to read, the complete code is easier to understand: base = "https://secure.gravatar.com/avatar.php" params = urllib.urlencode({'gravatar_id': hashlib.md5(email).hexdigest(), 'size': srt(size)}) url = "{}?{}".format(base, params) result = urllib.urlretrieve(url) A: This may not be suggested by PEP8, but for readability you could break it up like this: base = "https://secure.gravatar.com/avatar.php?" params = urllib.urlencode({'gravatar_id': hashlib.md5(email).hexdigest(), 'size': srt(size)}) result = urllib.urlretrieve(base+params) Note that autopep8 is a utility for formatting Python code to conform with PEP8. In this case, it transforms your original code to result = urllib.urlretrieve( "https://secure.gravatar.com/avatar.php?" + urllib.urlencode({ 'gravatar_id': hashlib.md5(email).hexdigest(), 'size': srt(size) }) )
doc_23529456
Mean all pages shows 25%; when i give a size to iframe then it's shows scroll bar what to do... A: This isn't possible unless you can edit the source code of all four loaded web pages. There is no "zoom" parameter/attribute for an iframe, so the pages that are loaded would need to autosize to fit, themselves. A: There are several methods for hiding the scrollbars from an inline frame. Here they are: ** Using scrolling="no". This is how to remove iframe scrollbars in HTML 4.1 (the current version of HTML at the time of writing). Using overflow:hidden. This is how to hide scrollbars using CSS (Cascading Style Sheets) Using seamless="seamless". This attribute was introduced in the HTML version 5 working draft. Therefore, to cater for future browsers, this code should be included. ** Which one to use? You can safely use all three at the same time. Having said that, if you prefer to validate your webpages using the W3C validator, you should only use the method that aligns with the version of HTML that you are validating against. Therefore, if you're using HTML 4.1, use scrolling="no". If you're using HTML 5, use seamless="seamless". In any case, you can also use overflow:hidden along with any other code. Actually, you will usually find that this overrides the HTML and hides any scrollbars that have been defined.
doc_23529457
The situation is the following: I generated a WCF service client with Visual Studio 2015 using the metadata of the odata service. VS generated a class inheriting from System.Data.Services.Client.DataServiceContext. This class has some properties of type System.Data.Services.Client.DataServiceQuery<T>. The data of some of these properties change seldom. Because of performance reasons I want the WCF client to load these properties just the first time and not every time I use it in the code. Is there a built in possibility to cache the data of these properties? Or can I tell the service client not to load specific proeprties newly every time. Assuming the service client class is ODataClient and one of its properties is `Area, for now I get the values in the following way: var client = new ODataClient("url_to_the_service"); client.IgnoreMissingProperties = true; var propertyInfo = client.GetType().GetProperty("Area"); var area = propertyInfo.GetValue(client) as IEnumerable<object>; The reason why I do this in such a complicated way is, that the client should be very generic: The properties to be handled can be configured in a configuration file. * EDIT * I already tried to find properties in the System.Data.Services.Client.DataServiceContext class or the System.Data.Services.Client.DataServiceQuery<T> class for the caching. But i wasn't able to find any. A: To my knowledge there is no "out of the box" caching concept on the client. There are options for caching the output of a request on the server which is something you might want consider as well. Googling "WCF Caching" would get you a bunch of info on this. Regarding client side caching...@Evk is correct it is pretty straight forward. Here is an sample using MemoryCache. using System; using System.Runtime.Caching; namespace Services.Util { public class CacheWrapper : ICacheWrapper { ObjectCache _cache = MemoryCache.Default; public void ClearCache() { MemoryCache.Default.Dispose(); _cache = MemoryCache.Default; } public T GetFromCache<T>(string key, Func<T> missedCacheCall) { return GetFromCache<T>(key, missedCacheCall, TimeSpan.FromMinutes(5)); } public T GetFromCache<T>(string key, Func<T> missedCacheCall, TimeSpan timeToLive) { var result = _cache.Get(key); if (result == null) { result = missedCacheCall(); if (result != null) { _cache.Set(key, result, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.Add(timeToLive) }); } } return (T)result; } public void InvalidateCache(string key) { _cache.Remove(key); } } } This is an example of code that uses the cache... private class DataAccessTestStub { public const string DateTimeTicksCacheKey = "GetDateTimeTicks"; ICacheWrapper _cache; public DataAccessTestStub(ICacheWrapper cache) { _cache = cache; } public string GetDateTimeTicks() { return _cache.GetFromCache(DateTimeTicksCacheKey, () => { var result = DateTime.Now.Ticks.ToString(); Thread.Sleep(100); // Create some delay return result; }); } public string GetDateTimeTicks(TimeSpan timeToLive) { return _cache.GetFromCache(DateTimeTicksCacheKey, () => { var result = DateTime.Now.Ticks.ToString(); Thread.Sleep(500); // Create some delay return result; }, timeToLive); } public void ClearDateTimeTicks() { _cache.InvalidateCache(DateTimeTicksCacheKey); } public void ClearCache() { _cache.ClearCache(); } } And some tests if you fancy... [TestClass] public class CacheWrapperTest { private DataAccessTestStub _dataAccessTestClass; [TestInitialize] public void Init() { _dataAccessTestClass = new DataAccessTestStub(new CacheWrapper()); } [TestMethod] public void GetFromCache_ShouldExecuteCacheMissCall() { var original = _dataAccessTestClass.GetDateTimeTicks(); Assert.IsNotNull(original); } [TestMethod] public void GetFromCache_ShouldReturnCachedVersion() { var copy1 = _dataAccessTestClass.GetDateTimeTicks(); var copy2 = _dataAccessTestClass.GetDateTimeTicks(); Assert.AreEqual(copy1, copy2); } [TestMethod] public void GetFromCache_ShouldRespectTimeToLive() { _dataAccessTestClass.ClearDateTimeTicks(); var copy1 = _dataAccessTestClass.GetDateTimeTicks(TimeSpan.FromSeconds(2)); var copy2 = _dataAccessTestClass.GetDateTimeTicks(); Assert.AreEqual(copy1, copy2); Thread.Sleep(3000); var copy3 = _dataAccessTestClass.GetDateTimeTicks(); Assert.AreNotEqual(copy1, copy3); } [TestMethod] public void InvalidateCache_ShouldClearCachedVersion() { var original = _dataAccessTestClass.GetDateTimeTicks(); _dataAccessTestClass.ClearDateTimeTicks(); var updatedVersion = _dataAccessTestClass.GetDateTimeTicks(); Assert.AreNotEqual(original, updatedVersion); } }
doc_23529458
I have two lists where the first one, let's say A = [1, 2, 3, 4, 5, 6] is sorted and the second one, let's say B = [3, 4, 1, 6, 2, 5] is not sorted. What I want to achieve is to obtain the value of the index for each element of the sorted list A in list B. For example, I want to come with the result of index i = 3 when I search for the element A[5] = 6. I have implemented in the simple way as follows: for i in range(6): for j in range(6): if A[i] == B[j]: index = j I would want to come up with a way which reduces it to only one loop instead of these two nested for loops. A: If you know that all the values in B are unique, one way would be to create a dictionary that maps the values in B to their indices. b_dict = {} for i, b in enumerate(B): b_dict[b] = i Then, loop over A and get all the values from b_dict. a_indices = [b_dict[a] for a in A] With your lists, we get A: [1, 2, 3, 4, 5, 6] B: [3, 4, 1, 6, 2, 5] a_indices: [2, 4, 0, 1, 5, 3] This solution is O(n) as opposed to the others, which are O(n^2), and will therefore be much faster on large lists. A: The simplest possible solution is, A = [1, 2, 3, 4, 5, 6] B = [3, 4, 1, 6, 2, 5] x= [B.index(i) for i in A] #To store the result in a dictionary to map value and corresponding index. a=dict(zip(A,x)) A: You can use the list.index() method to find the index of a specific element within a list: indices = {} for elem in A: indices[elem] = B.index(elem) # {1: 2, 2: 4, 3: 0, 4: 1, 5: 5, 6: 3} A: Try this: for x in A: index = B.index(x) Here index is the index varaible at each iteration. To save in a dict: indices = {} for x in A: indices[x] = B.index(x)
doc_23529459
def main(args: Array[String]) { println( apply( layout, 10) ) } def apply(f: Int => String, v: Int) = f(v) def layout[A](x: A) = "[" + x.toString() + "]" } In the function def layout[A](x: A), what does [A] signify? A: It is a generic class in Scala. http://docs.scala-lang.org/tutorials/tour/generic-classes.html If you know java then [A] is equivalent to <A> in Java. The equivalent Java code will look like: <A> String layout(A x){ return "[" + x.toString() + "]"; } A: [A] declares a type parameter named A. In Haskell-like syntax, this type would be written as layout :: forall a. a -> String A: Non-generic methods are parameterized with known types: def layout(x: Int) = "[" + x.toString() + "]" //parameter x is of a known type: Int In the above example, x is explicitly set to be an Int. However, the toString method is applicable on any type in Scala. So, instead of writing multiple overloaded methods for different types like below: def layout(x: Double) = "[" + x.toString() + "]" //parameter x is of a known type: Int def layout(x: List[Int]) = "[" + x.toString() + "]" //parameter x is of a known type: Int We can write a single generic / polymorphic method by using type parameters: def layout[A](x: A) = "[" + x.toString() + "]" The A above is called a type parameter. Now, A could be of any type. Its an abstraction over the actual type. You could now call the polymorphic layout method by explicitly specifying the type of A: layout[Int](2) Or you could simply call it like below, in which case Scala will automatically infer that the parameterized type A is of type Int: layout(2)
doc_23529460
But when I hit Ctrl+B on the shell, it moves one character back instead of letting byobu/tmux handle it. A: First, I typically don't use the F9 menu stuff, so this is relatively new to me. However, when I did that and pressed B (no ctrl since that is assumed/forced), it immediately worked correctly (without a restart). I'm not certain why it would not work with your configuration. Since byobu is really keeping its own store of configuration items and forcing screen/tmux to use its versions, you can find what to change by looking in ~/.byobu/, and how to change it by reading the respective man/help pages. You can edit byobu's config files behind the scenes (not always a good idea, but should be acceptable here). Since byobu uses either screen or tmux (based on what is installed), the answer can reside in either ~/.byobu/keybindings (for screen) or ~/.byobu/keybindings.tmux. I played around with using both screen and tmux ... choose one (defaults to tmux if installed, I think) and go with it. First things first Check to make sure that echo $HOME prints what you expect (not a blank line). If there is not a directory called .byobu within that home directory, then either the byobu installation is dorked or you don't have the correct permissions set in your home directory; try mkdir "${HOME}/.byobu", and if it doesn't work than that could be part of your problem. screen From man screen ... escape xy Set the command character to x and the character generating a literal command character (by triggering the "meta" command) to y (similar to the -e option). Each argument is either a single character, a two-character sequence of the form "^x" (meaning "C-x"), a backslash followed by an octal number (specifying the ASCII code of the character), or a backslash followed by a second character, such as "\^" or "\\". The default is "^Aa". ... The first line of ~/.byobu/keybindings should have byobu's source command, so don't change it. After it, add the following: escape "^Bb" register x "^B" bindkey "^B" (This is taken verbatim from what byobu did to my install. Historically -- since I use screen/tmux without byobu much of the time -- I actually just set: escape "^Bb" defescape "^Bb" This may not be the best way, and it has some historical kludgeness to it, but it works for me.) tmux Similarly, from man tmux: prefix key Set the key accepted as a prefix key. prefix2 key Set a secondary key accepted as a prefix key. My ~/.byobu/keybindings.tmux doesn't have a source command, so my file only contained the following: unbind-key -n C-b set -g prefix ^B set -g prefix2 ^B bind b send-prefix If This Doesn't Work Knowing your OS and software versions will be useful. I tested this on ubuntu-13.10 with byobu-5.60-0ubuntu1, screen-4.0.3-14ubuntu10, and tmux-1.8-4.
doc_23529461
java.nio.file.AccessDeniedException: /storage/emulated/0/pho.txt My code is: TextView t = findViewById(R.id.mainTextView1); //t.setTextSize(1); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0); } } try { t.setText(new String(Files.readAllBytes(Paths.get("/storage/emulated/0/pho.txt")))); } catch (IOException e) { t.setText(e.toString()); } In AndroidManifest.xml: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> How I can fix it? Everything seemed to be fine before.
doc_23529462
What's the best way to do this? I put the two headers in a container div hoping that it will make it easy for me to align the two divs within the container, but I'm just not sure how to achieve it. Here's the code I currently have for this section of the page: EDIT: Code Now says (but still doesn't work): .gridContainer { margin-left: auto; margin-right: auto; width: 90.5666%; padding-left: 0.2166%; padding-right: 0.2166%; } #headercontainer { clear: both; float: left; margin-left: 0; width: 100%; display: block; font-family: Arial, Helvetica, sans-serif; color: #FFF; text-align: left; } #headerleft { clear: both; float: left; margin-left: 0; width: 49.7607%; } #headerright { clear: none; margin-left: 0.4784%; width: 49.7607%; } And the html says: <div class="gridContainer clearfix"> <div id="headercontainer"> <div id="headerright"> <h2>Support For All Your Gadgets &amp; Tech!</h2> </div> <div id="headerleft"><h2><img src="images/logo2.png" alt="alt" longdesc="desc"></h2> </div> </div> Thanks a lot! A: remove display:block; from your #headerleft and #headerright Also, you can only set float:left; on the headerleft id, and put the div headerright before the left one in your html code. A: Try this code: .gridContainer { margin-left: auto; margin-right: auto; width: auto; padding-left: 15px; padding-right: 15px; } #headercontainer { float: left; margin-left: 0; width: 100%; font-family: Arial, Helvetica, sans-serif; color: #FFF; text-align: left; position:relative; } #headerleft { float: left; margin-left: 0; width: 50%; } #headerright { clear: none; margin-left: 50%; } <div class="gridContainer clearfix"> <div id="headercontainer"> <div id="headerleft"><h2><img src="images/logo2.png" alt="alt" longdesc="desc"></h2> </div> <div id="headerright"> <h2>Support For All Your Gadgets &amp; Tech!</h2> </div> </div> </div>
doc_23529463
28 57 87 116 145 176 204 233 And I need to transform it to ranges, with names, and basically, each range corresponds to the 1st number up to the next number -1. like this: type, range1=28-56 type, range2=57-86 type, range3=87-115 type, range4=116-144 type, range5=145-175 type, range6=176-203 type, range7=204-232 Any ideas on how to? A: You may use this awk: awk 'p{printf "type, range%d=%d-%d\n", ++r, p, $1-1} {p=$1}' file type, range1=28-56 type, range2=57-86 type, range3=87-115 type, range4=116-144 type, range5=145-175 type, range6=176-203 type, range7=204-232
doc_23529464
So anyone can give me some guide or a website that catually introduce how to access data in Cassandra with PySpark?
doc_23529465
I know I should to this with POST->REDIRECT->GET pattern and storing list of strings in session data, though I can get how exactly I should acces those data - anything I tried ended just in errors, like: code error CS1002: ; expected at line 40 (which is strange, because I checked this line and others too and I didn't find any missing semicolons... I think it may be caused by some of the code working differently that I expected...) Here's one version of the code I tried: @{ Layout = null; var rules = new List<string>(); } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> </head> <body> <form action="~/Rules.cshtml" method="Post"> <p> <label for="name">New rule</label><br> <input type="text" name="rule"> <p><input type="submit" value="Add"></p> </p> </form> @{ if (Session["rules"] == null) { Session["rules"] = rules; } if (IsPost) { rules = new List<string>(); foreach (var i in (List<string>)System.Web.HttpContext.Current.Request.Session["rules"]) { rules.Add(i); } rules.Add(Request.Form["rule"]); List<string>System.Web.HttpContext.Current.Request.Session["rules"] = rules; } } } <ul> @{ foreach (var x in Request.Session["rules"]) { <li>@x</li> } } </ul> </body> </html> Rules.cshtml is obviously file with this code. (I know, that recreating whole list every time isn't most optimal solution, but I didn't find any way to do it differently... If You have some solution I'm open to advices)
doc_23529466
when adding a new user to the database, I get a new connection, create a prepared statement and execute the query. However, no results are shown in the database. For example, let's assume I manually add a new user in the database with MySql Query Browser. * *I add a new user --> name = Stefano, pin = 1010 *An auto-increment id is generated: id = 1. Suppose I decide to add a new user programmaticaly: * *I call the method addUser(String username, int pin) --> addUser("pippo", 7636); *No error occurs *I open MySql Query Browser and none user is added. Finally I add a new user manually: name = pluto , pin = 3434. Now my table result in: id name pin 1 stefano 1010 3 pluto 3434 id=2 is missing. So pippo has been added but I can't see it. What's wrong? Here my java code simplified: package simpleexample; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class SimpleExample { public static void addUser(String username, int pin) { Connection conn = null; PreparedStatement preparedStmt = null; String insertSQL = "insert into users(name, pin) values (?, ?)"; try { conn = DBConnectionPool.getConnection(); preparedStmt = conn.prepareStatement(insertSQL); preparedStmt.setString(1, username); preparedStmt.setInt(2, pin); preparedStmt.execute(); } catch (SQLException ex) { Logger.getLogger(SimpleExample.class.getName()).log(Level.SEVERE, null, ex); } finally { if (conn != null) { DBConnectionPool.releaseConnection(conn); } } } public static void main(String[] args) { addUser("pippo", 7636); } } Here the class DBConnectionPool: package simpleexample; import java.util.*; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.*; /** * This class simulates a db connection pool */ public class DBConnectionPool { /* * This code prepare the db connection pool. In particular, it creates the * free connections queue and defines the db properties. */ static { freeDbConnections = new ArrayList<Connection>(); try { DBConnectionPool.loadDbProperties(); DBConnectionPool.loadDbDriver(); } catch (ClassNotFoundException e) { System.out.println("DB DRIVER NOT FOUND!"); System.exit(1); } catch (IOException e) { System.out.println("DB CONNECTION POOL ERROR!"); System.exit(2); } } /** * The db properties (driver, url, login, and password) */ private static Properties dbProperties; /** * The free connection queue */ private static List<Connection> freeDbConnections; /** * Returns a free db connection accessing to the free db connection queue. * If the queue is empty a new db connection will be created. * * @return A db connection * @throws SQLException */ public static synchronized Connection getConnection() throws SQLException { Connection connection; if (!freeDbConnections.isEmpty()) { // Extract a connection from the free db connection queue connection = freeDbConnections.get(0); DBConnectionPool.freeDbConnections.remove(0); try { // If the connection is not valid, a new connection will be // analyzed if (connection.isClosed()) { connection = DBConnectionPool.getConnection(); } } catch (SQLException e) { connection = DBConnectionPool.getConnection(); } } else // The free db connection queue is empty, so a new connection will // be created { connection = DBConnectionPool.createDBConnection(); } return connection; } /** * Releases the connection represented by <code>pReleasedConnection</code> * parameter * * @param pReleasedConnection The db connection to release */ public static synchronized void releaseConnection( Connection pReleasedConnection) { // Add the connection to the free db connection queue DBConnectionPool.freeDbConnections.add(pReleasedConnection); } /** * Creates a new db connection * * @return A db connection * @throws SQLException */ private static Connection createDBConnection() throws SQLException { Connection newConnection = null; // Create a new db connection using the db properties // newConnection = DriverManager.getConnection( // "jdbc:mysql://localhost/resources", "root", ""); newConnection = DriverManager.getConnection( DBConnectionPool.dbProperties.getProperty("url"), DBConnectionPool.dbProperties.getProperty("username"), DBConnectionPool.dbProperties.getProperty("password")); newConnection.setAutoCommit(false); return newConnection; } private static void loadDbDriver() throws ClassNotFoundException { Class.forName(DBConnectionPool.dbProperties.getProperty("driver")); } /** * Loads the db properties * * @throws IOException */ private static void loadDbProperties() throws IOException { InputStream fileProperties = new FileInputStream("database.properties"); DBConnectionPool.dbProperties = new Properties(); DBConnectionPool.dbProperties.load(fileProperties); } } Note: I have a file Database.properties in the project with * *driver=org.gjt.mm.mysql.Driver *url=jdbc:mysql://localhost/name_db *username=root *password='password' I already used the DBConnectionPool class in other projects and it's always worked fine. So I don't understand what's wrong. Maybe something about transactions? A: You disable auto commit in your connection pool (seriously: don't roll your own, use an existing one, they will do a better job than this). You never call commit anywhere in your code, therefor the result is never committed (and eventually when the connection really gets closed or otherwise lost, the change will get rolled back). My advice: * *Call commit() (or rollback()) when you have finished your unit of work. *Start using a real connection pool, like HikariCP, DBCP or c3p0 A: You need to use executeUpdate() not execute(). https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String) int executeUpdate(String sql) throws SQLException Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement. https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#execute(java.lang.String) boolean execute(String sql) throws SQLException The execute method executes an SQL statement and indicates the form of the first result. You must then use the methods getResultSet or getUpdateCount to retrieve the result, and getMoreResults to move to any subsequent result(s).
doc_23529467
Without Ajax Call (Things work well) With Ajax Call (Things break) A: Set autoInitializePage to false. $(document).bind("mobileinit", function(){ $.mobile.autoInitializePage = false; }); and then call $.mobile.initializePage(); explicitly. Example
doc_23529468
int main(int argc, char *argv[]){ int N = 10, i = 0, n = 10; double v[2] = {0.0,0.0}; double meanS2 = 0.0, sum = 0.0; time_t t; srand((unsigned) time(&t)); for(i=0;i<n;i++){ RW(N, v); meanS2 += v[0]*v[1]; sum += v[1]; } meanS2 = meanS2/sum; printf("%f\n", meanS2); fflush(stdout); return(0); } RW is a function that works (I tried it independently). When I run the program it gives me nothing. But really nothing! As you can see I tried to put the fflush function but it stilll gives me nothing. From what I've read the problems with printf usually arise when there is an infinite loop in the program, but my loop is far from being infinite! I just really don't understand. I tried putting : RW(N, v); meanS2 += v[0]*v[1]; sum += v[1]; ten times in a row but it gives me nothing, actually it works when I put it two times, but stops working at three times. Does it mean that my RW function overflows the memory or something? I'm a beginner so I'm really lost right now. If there was a problem like that, wouldn't there be a message or something? Thanks for any kind of help you can provide! Here is the rest of the program just in case, it's supposed to be a simulation for a random walk with survival biasing : #define XY(x,y) ((x)*(2*N+1) + (y)) double product(int a, int b) // This function calculate the "scalar product" of two "vectors"; { // a and b are the vectors giving the directions taken by the walk double res=0; // +1 and -1 represent going up and down respectively and // +2 and -2 represent going right and left respectively if(a == b) // if both of the vectors point in the same direction, the product is 1 { // since the vectors are of length 1 res = 1.0; // if they point in opposite directions, the result is -1 and } // if they point in different direction, the result is 0 else if(a == -b) { res = -1.0; } return res; } void RW(int N, double *v) { int i, j, step, i_diff, j_diff, p, q, nspots, k, r; int *lattice, *index_i, *index_j; int xi; int dir_i[3], dir_j[3], vec_dir[3]; int *vec; double S2 = 0; double w; lattice = malloc((2*N+1)*(2*N+1)*sizeof(int)); // A lattice big enough so that if the walk goes index_i = malloc((N+1)*sizeof(int)); // always in the same direction, it stops at the index_j = malloc((N+1)*sizeof(int)); // edge vec = malloc(N*sizeof(int)); // index_i and index_j keep tracks of the indices of the different spots the walk goes by, vec keeps tracks of the different directions corresponding (up (1), down (-1), right (2), left (-2)) i = N + 1; // start at the center of the lattice j = N + 1; step = 0; srand (time(NULL)); index_i[step] = i; index_j[step] = j; lattice[XY(i,j)] = 1; // 1 means that the walk passed here xi = rand() % 4 + 1; //For the first step, we take a random number between 1,2,3 and 4 step = 1; switch(xi) { case 1:// if 1, the walk goes down i++; index_i[step] = i; index_j[step] = j; lattice[XY(i,j)] = 1; vec[step-1] = -1; break; case 2:// if 2, the walk goes up i--; index_i[step] = i; index_j[step] = j; lattice[XY(i,j)] = 1; vec[step-1] = 1; break; case 3:// if 3, the walk goes right j++; index_i[step] = i; index_j[step] = j; lattice[XY(i,j)] = 1; vec[step-1] = 2; break; case 4:// if 4, the walk goes left j--; index_i[step] = i; index_j[step] = j; vec[step-1] = -2; break; } for(step = 2; step<N+1; step++) { nspots = 0; i_diff = i - index_i[step-2]; // difference between the indices we are at right now, and those j_diff = j - index_j[step-2]; // from one step before if(i_diff != 0){//dir_i and dir_j represent the indices of the available spots in each case, vec_dir the available direction corresponding dir_i[0] = i + i_diff; dir_j[0] = j; vec_dir[0] = -i_diff; dir_i[1] = i; dir_j[1] = j - 1; vec_dir[1] = -2; dir_i[2] = i; dir_j[2] = j + 1; vec_dir[2] = 2; for(r=0; r<3; r++){ if(lattice[XY(dir_i[r],dir_j[r])] == 0){ dir_i[nspots] = dir_i[r]; dir_j[nspots] = dir_j[r]; vec_dir[nspots] = vec_dir[r]; nspots++; } } if(nspots == 0){// program aborts if there is nowhere to go v[0] = 0; exit(0); } } else if(j_diff != 0){ dir_i[0] = i; dir_j[0] = j + j_diff; vec_dir[0] = 2*j_diff; dir_i[1] = i + 1; dir_j[1] = j; vec_dir[1] = -1; dir_i[2] = i - 1; dir_j[2] = j; vec_dir[2] = 1; for(r=0; r<3; r++){ if(lattice[XY(dir_i[r],dir_j[r])] == 0){ dir_i[nspots] = dir_i[r]; dir_j[nspots] = dir_j[r]; vec_dir[nspots] = vec_dir[r]; nspots++; } } if(nspots == 0){ v[0] = 0; exit(0); } } w = w*nspots/3; xi = rand() % nspots;//there are only nspots directions to chose from (no going back) i = dir_i[xi]; j = dir_j[xi]; lattice[XY(i,j)] = 1; index_i[step] = i; index_j[step] = j; vec[step-1] = vec_dir[xi]; } // if the walk is completed, calculate S2, the total distance squared for(p=0; p<N; p++) { for(q=0; q<N; q++) { S2 += product(vec[p],vec[q]); } } free(lattice); free(index_i); free(index_j); free(vec); v[0] = S2; v[1] = w; }
doc_23529469
The regular expression I use right now is: return preg_replace('/ \<[^\>]+\>/', '', $text); How should I change it to exclude the tags I mentioned? I looked through similar questions but they don't provide a solution to the specific problem I mentioned here. A: If you can't use PHP's strip_tags(), use HTMLPurifier, which will allow you to implement all sorts of rules, safely. A: To answer your question anyway, you could use an assertion (?!..) to exclue things from matching: preg_replace('#<(?!/?(a|b|i|div)\b)[^>]+>#' But take in mind that this is not a very reliable approach. Filtering tag names is the easy part. For a complete sanitization you'd have to clean up attributes, where it becomes complicated. Try HTMLPurifier, which already contains heaps of regular expressions to do so. A: $wl = '(?!(?:b|tr|td)\b)'; // whitelist in group $rxtags = ' < (?: (?: (?: (?:' ."$wl". 'script|' ."$wl". 'style) \s* | (?:' ."$wl". 'script|' ."$wl". 'style) \s+ (?:".*?"|\'.*?\'|[^>]*?)+\s* )> .*? </(?:' ."$wl". 'script|' ."$wl". 'style)\s* ) | (?: /?' ."$wl". '\w+\s*/? | ' ."$wl". '\w+\s+ (?:".*?"|\'.*?\'|[^>]*?)+\s*/? | !(?:DOCTYPE.*?|--.*?--) ) ) >'; s/$rxtags//xsg "/$rxtags/xs", modifiers: expanded, span, globally And change ' . "$wl" . ' to ' + "$wl" + ' or however catenation is done in php.
doc_23529470
My Avro Schema has string,double and ints. I have around 201 columns in schema. I read Avro should improve performance while reading the avro file. but i result shows Gz ( with single mapper) is performing better than Plain text (6 Mappers) and plain text is better than avro ( 3 mappers). Is there a way to improve the performance of avro file. As per different blogs, Avro is showing better results than gz and text file. is there some thing Im missing in hive settings. Im already using TEZ engine.
doc_23529471
The latest two automated Quality Central reports generated when importing ProcessSalesLead schema from the StarStandard set of schemas. http://qc.embarcadero.com/wc/qcmain.aspx?d=98391 http://qc.embarcadero.com/wc/qcmain.aspx?d=98392 Schemas are available online and are widely utilized in the automotive industry http://www.starstandard.org/SIGXMLSTAR5/XMLSchemas A: Try to use XSDTool v.3.0.0.2 by Thomas Kerkmann.
doc_23529472
How to tell entity manager to re-synchronize, e.g. to forgot all the entites in cache? I know there is refresh(Object) method, but is there any possibility how to do refreshAll() or something what results in this? It is sure this is expensive operation but if it has to be done. A: I had a similar issue and the evictAll() line above worked for me. Alternatively, the @Cache annotation on the entity class worked too, with the benefit of being able to control caching parameters: @Cache(coordinationType=CacheCoordinationType.INVALIDATE_CHANGED_OBJECTS) See: http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching A: entityManager.getEntityManagerFactory().getCache().evictAll() Refresh is something different since it modifies your object. This line will just empty the cache, so if you fetch objects changed outside the entity manager, it will do an actual database query instead of using the outdated cached value. A: If you are using EclipseLink instead of Hibernate the hint is: em.createNamedQuery("SomeEntity.SomeNamedQuery") .setHint(QueryHints.REFRESH, true) .getResultList(); A: Well, for some people (like me) that tried to add factory.getCache().evictAll(); and doesn't work, and are used JPA + Hibernate, to refresh a query add the hint org.hibernate.cacheMode to IGNORE. Example: em.createNamedQuery("SomeEntity.SomeNamedQuery") .setHint("org.hibernate.cacheMode", "IGNORE") .getResultList(); A: cache.evictAll is not working for me. So to retrieve data pushed from another app, I peform : em.getTransaction().begin(); em.getTransaction().commit(); After that, my find query retrieves refreshed data. I don't know if it's very safe solution but it works properly. A: When you read an object into an EntityManager, it becomes part of the persistence context, and the same object will remain in the EntityManager until you either clear() it and get a new EntityManager. So if you update the database, the EntityManager will not see the change unless you call refresh() on the object, or clear() the EntityManager. This has nothing to do with the shared cache (L2) or the persistence context (L1). If you also also using a shared cache, and updating the database directly, then your shared cache will be out of date. You need to refresh() the object, or mark it as invalid to be refreshed the next time it is queried. Code must follow the way like. DETACH REFRESH MERGE FLUSH
doc_23529473
$userip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']); $date = date('Y-m-d'); $result = mysql_query("SELECT `ip` FROM `popupip` where ip = '$userip' AND userid = $secid AND date='$date'"); $num = mysql_num_rows($result); if ($num > 0) { // **it is duplicate Do not insert it in popupip table** }else{ // **it is not duplicate ip insert it in popupip table** } above code is an example.I know full code. but when I look to my phpmyadmin popupip table there is a few duplicate ip for user (the exact same ip address for the user on the same date) how is it possible? extra information: in popupip userid is int(11) , date is "date type like 2014-05-30" and ip is varchar. this page may opens "as fast as possible at the same time" by popup pages. is there a relation between openning a page fast at same time by a user and duplicate ip creation? is there a bug in MySQL? (maybe a big bug!!!!) A: Yes, it is possible. It's a classical case of a race condition. The quick explanation: There is a chance that 2 requests simultaneously pass the first check, get $num == 0 and both insert a new row. To eliminate it you need to create a UNIQUE constraint that covers (user_id, ip, date) columns The long explanation: * *Wikipedia - Race Condition *Stackoverflow - What is a race condition? A: If multiple requests are coming from the same ip at the same time, it is possible that a few of them are executing the select query before any of them executes the insert query (resulting in multiple inserts with the same ip and date). A solution for this is to create a UNIQUE index with ip, user_id and date (you can easily do this in phpMyAdmin by running the query below): ALTER TABLE `popupip` ADD UNIQUE (`ip`, `user_id`, `date`); After that you can optimize your code and simply execute an "INSERT IGNORE" query that only inserts if the combination (ip, user_id, date) doesn't already exist in the table: mysql_query("INSERT IGNORE INTO `popupip` (`ip`, `user_id`, `date`) VALUES ('$userip', $secid, '$date');"); With this solution you don't need to do the extra "SELECT" query, or the "if" to check if there are results.
doc_23529474
Note that I don't want to find the pod using a specific label since then (I assume) I may not always find the right pod if it's scaled with a replication controller. A: You can tell Kubernetes to put the pod name in an environment variable of your choice using the downward API. For example: apiVersion: v1 kind: Pod metadata: name: dapi-test-pod spec: containers: - name: test-container image: gcr.io/google_containers/busybox command: [ "/bin/sh", "-c", "env" ] env: - name: MY_POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: MY_POD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: MY_POD_IP valueFrom: fieldRef: fieldPath: status.podIP restartPolicy: Never A: The pod name is written to /etc/hostname so it's possible to read it from there. In Java (which I'm using) you can also get the hostname (and thus the name of the pod) by calling System.getenv("HOSTNAME").
doc_23529475
Only pass callback_url to get_authentication_tokens if your application is a Web Application Desktop and Mobile Applications do not require a callback_url Does anyone know if I require one? I tried putting in "google.com" but returned a 401 error. Here's my code currently: app_name = "AppNameTestScript" APP_KEY = "exAmPlE" APP_SECRET = "exAmPlEexAmPlEexAmPlE" twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens(callback_url='http://google.com.au') A: If you use application-level authorisaion, you should use Oath2 authorisation path Oath1 authorisation is a bit trickier, your application is authorised to act on behalf of an end user, so the latter has to grant this authority to your application. End user opens auth['auth_url'] url and grants permissions to your app on twitter.com, then he is redirected back to the application, that is where callback is used for. By processing this redirect, a web-based application communicates for access token. Read oauth begguide for more details. There is a pin-based authoriazation flow in case you can't implement redirect handling. For this, you don't need to provide callback_url, as user acceptance is handled differently. Your end user however still need somehow communicate to your application his pin code. See twython docs for steps starting from when you know pin implementation details
doc_23529476
app.post("/api/get/signin", (req,res)=>{ const userid = req.body.userId; userIdG = userid; const password = req.body.password; const consumerKey = req.body.consumerKey; const sqlSelect = `SELECT userid FROM signup WHERE userid = ? AND password = ? AND consumerKey = ?`; db.query(sqlSelect,[userid , password , consumerKey], (err, result)=> { console.log(result.userid); console.log(err); //console.log(err); if(result.userid == userid && result.password == password && result.consumerKey == consumerKey) { //res.send(result); console.log("Successfully Login"); auth = true; } else { console.log('Local'); console.log(userid); console.log(password); console.log(consumerKey); console.log("UnSuccessfully Login"); auth = false; } }) }) A: result will be an array (because queries can have multiple results), so to access the userid (of the first result, provided that there is one!): console.log(result[0].userid)
doc_23529477
and I need to remove it using XSLT for stylesheet version="2.0" I used <xsl:output method="xml" omit-xml-declaration="yes" /> but it did not work as I think it works with stylesheet version="1.0" the xml file I have (input) <?xml version="1.0" encoding="UTF-8"?> <eExact> <GLEntries> <GLEntry> <Description>Report 2020-08</Description> <Date>23-09-2020</Date> <DocumentDate>23-09-2020</DocumentDate> <Journal code="70"/> <FinEntryLine number="1"> <GLAccount code="4590"/> <Creditor code="520094"/> <Description>Heidi Draaisma</Description> <Date>23-09-2020</Date> <Amount> <Currency code="EUR"/> <Debit>37.61</Debit> </Amount> </FinEntryLine> </GLEntry> </GLEntries> </eExact> The output I need <eExact> <GLEntries> <GLEntry> <Description>Report 2020-08</Description> <Date>23-09-2020</Date> <DocumentDate>23-09-2020</DocumentDate> <Journal code="70"/> <FinEntryLine number="1"> <GLAccount code="4590"/> <Creditor code="520094"/> <Description>Heidi Draaisma</Description> <Date>23-09-2020</Date> <Amount> <Currency code="EUR"/> <Debit>37.61</Debit> </Amount> </FinEntryLine> </GLEntry> </GLEntries> </eExact> A: I have XML file with declaration and I need to remove it using XSLT for stylesheet version="2.0" This is the transformation you want: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> </xsl:stylesheet> Explanation: * *<xsl:output omit-xml-declaration="yes"/> *The identity rule/template
doc_23529478
a. Should we inherit from Comparer abstract class ? or b. Should we implement IComparer interface. What are the pros and cons? A: I would recommend that you extend the Comparer<T> class instead of implementing the IComparer<T> interface, as does Microsoft (see first reference below). Now, if you want your object itself (whatever T is) to be able to compare against itself, it can implement the IComparable interface (see second reference below). From: http://msdn.microsoft.com/en-us/library/8ehhxeaf(v=vs.110).aspx (IComparer<T>) We recommend that you derive from the Comparer<T> class instead of implementing the IComparer interface, because the Comparer<T> class provides an explicit interface implementation of the IComparer.Compare method and the Default property that gets the default comparer for the object. From: http://msdn.microsoft.com/en-us/library/cfttsh47(v=vs.110).aspx (Comparer<T>) Derive from this class to provide a custom implementation of the IComparer<T> interface for use with collection classes such as the SortedList<TKey, TValue> and SortedDictionary<TKey, TValue> generic classes. The difference between deriving from the Comparer class and implementing the System.IComparable interface is as follows: * *To specify how two objects should be compared by default, implement the System.IComparable interface in your class. This ensures that sort operations will use the default comparison code that you provided. *To define a comparer to use instead of the default comparer, derive from the Comparer class. You can then use this comparer in sort operations that take a comparer as a parameter. A: From this article on MSDN: We recommend that you derive from the Comparer class instead of implementing the IComparer interface, because the Comparer class provides an explicit interface implementation of the IComparer.Compare method and the Default property that gets the default comparer for the object.
doc_23529479
map :: (s -> t) -> [s] -> [t] map f [] = [] map f (x:xs) = f x : map f xs I understand what the function does, and that map has a function f :: s -> t as a parameter. But I read map :: (s -> t) -> [s] -> [t] as "map is a function which maps a function mapping from s to t to s and then to t", which is obviously wrong. Could someone clear this up for me? A: It might be helpful to define a couple type aliases, to make it a bit more explicit what all those arrows and brackets are doing: type F1 a b = a -> b -- type synonym for single-argument functions type List a = [a] -- type synonym for lists so now you can write map's type signature as: map :: F1 s t -> List s -> List t which, if you're more familiar with Java or C++ or whatever, looks syntactically a bit more like: List<T> map(F1<S, T> fun, List<S> list); // applies fun to each element in list So you can think of it this way: map takes a function and a list, and returns another list. However, since functions are curried in Haskell, you don't have to pass all parameters at once. You could get away with partially applying map to just its first argument. So really its type signature is more like: F1<List<S>, List<T>> map(F1<S, T> fun); // returns a function that applies fun to each element in a list ... which, when you call map with just that one fun argument, gives you something that sort of looks like: List<T> mapFun(List<S> list); // applies fun to each element in list So now back to Haskell: you can read map :: (s -> t) -> [s] -> [t] either as: * *"map takes a function from s to t, and a list of s, and returns a list of t" *"map takes a function from s to t, and turns it into a function from a list of s to a list of t" The former is fine; the latter is more helpful. A: The type (s -> t) -> [s] -> [t] can be read in two ways. One way is to treat it as a function of two arguments, the first a function of type s -> t and the second a list of type [s]. The return value is of type [t]. The other way is to understand that function arrows are right-associative, so the type is equivalent to (s -> t) -> ([s] -> [t]). Under this interpretation, map is a function that takes a function from element to element s -> t and turns it into a function from list to list [s] -> [t]. Similarly, when using the function, you can think of map foo xs as applying the function map to two arguments foo and xs. Or, since function application is left-associative, you can think of it as (map foo) xs, applying map to the single argument foo to get back a new function which you then apply to xs. Since Haskell functions are curried, these are just two ways of looking at the exact same thing. A: How about "map is a function which maps a (function from s to t) over a (list of s) giving a (list of t)"? That is a direct translation of the type signature into English (albeit not very elegant English). A: Read the signature from the end: -> [t] means returns a list of t. The rest is 'regular' parameters. So, map takes a function that from an s makes a t, and a list of s. Now it's easy: take a function s->t, apply it to each element of [s] and the result of it is [t].
doc_23529480
def test(a,b, c=3, *args): pass args = [1,2,3] test(1,2,c=3, *args) . TypeError: test() got multiple values for argument 'c' At first I thought I found the answer here: TypeError: got multiple values for argument But it turns out that the first argument in that qusetion was being explictly overwritten, so in my own example this would be the same thing as saying test(1,2, a=3, *args) where a would be given values 1 and 3. However here that is not the case. This question might be a possible duplicate of this one "got multiple values for keyword argument" when using *args, **kwargs in a python function but honestly, there are a lot more details in that question that is beyond the scope of what am asking for and I really can't follow it through. So if this is a duplicate, then it abstracts everything away from the other question down to the actual problem itself. A: You need to swap it so the c=3 is last because python requires optional arguments to be at the end. The code functions when it is done like this: def test(a,b, *args, c=3): pass args = [1,2,3] test(1,2, *args, c=3) A: You're specifying a keyword argument and after a list of positional arguments, which is why you're getting the error. Specify first all positional arguments and then keyword arguments: def test(a,b, *args, c=3): print(args) test(1,2,c=3, *args) # (1, 2, 3)
doc_23529481
In Android, however, it doesn't work and returns this message in the log: org.json.JSONException: Unterminated array at character 5 of [idd=52, ido=1, when=10] This is the PHP code: <?php $dbhost = "127.0.0.1"; $dbuser = "root"; $dbpass = ""; $dbname = "clinic_last"; $link = @mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die("Impossibile collegarsi al server: " . mysqli_error()); mysqli_select_db($link ,'clinic_last') or die("unable to select database 'dbname': " . mysqli_error()); $idd = $_GET['idd']; $ido = $_GET['ido']; $when = $_GET['when']; $string = ("INSERT INTO obsindiaries (`when`, ido, idd) SELECT $when,$ido,idd FROM diaries WHERE idd = $idd LIMIT 1"); $string2 = "INSERT INTO obsindiaries (idod,idd,ido,`when`) VALUES (NULL,'$idd','$ido','$when')"; $flag['code']=0; $result = mysqli_query($link,$string); // check if row inserted or not if ($result) { // successfully inserted into database $response["success"] = 1; $response["message"] = "**successfully Registration.**"; // echoing JSON response echo json_encode($response); } if (!$result) { // failed to insert row $response["success"] = 0; $response["message"] = "Oops! An error occurred."; // echoing JSON response echo json_encode($response); } if (!$result) { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } mysqli_close($link); ?> This is part of file .class: public void ClickSaveObsindiaries(){ SavingObs=(ImageButton)findViewById(R.id.saveObsindiaries); SavingObs.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //INSERISCO VALORI DENTRO LISTA StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("idd", ID_diary.getText().toString())); int positionTypeObs = typeObsindiaries.getSelectedItemPosition() + 1; String valueType = String.valueOf(positionTypeObs); nameValuePairs.add(new BasicNameValuePair("ido",valueType)); char first = hours.getSelectedItem().toString().charAt(0); if (first=='I') nameValuePairs.add(new BasicNameValuePair("when", IntervalHours.getText().toString())); else nameValuePairs.add(new BasicNameValuePair("when", hours.getSelectedItem().toString())); System.out.println("valore di RESULT: "+nameValuePairs.toString()); try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://10.0.2.2/newObsindiaries.php"); Log.e("httpPost is:"," "+httpPost.toString()); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));//,"UTF-8" HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); is = entity.getContent(); Log.e("pass 1", "connection success "); } catch(Exception e) { Log.e("Fail 1", e.toString()); Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); Log.e("pass 2", "connection success "); } catch(Exception e) { Log.e("Fail 2", e.toString()); } try { JSONObject json_data = new JSONObject(nameValuePairs.toString()); code=(json_data.getInt("code")); if(code==1) { Toast.makeText(getBaseContext(), "Inserted Successfully", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show(); } } catch(Exception e) { Log.e("Fail 3", e.toString()); Log.e("JSON Parser", "Error parsing data " + e.toString()); } AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(add_obsindiaries.this, R.style.myDialog)); builder.setMessage("Misurazione inserita! Premere OK per tornare alla lista delle misurazioni") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent listOBS = new Intent(add_obsindiaries.this,obsindiaries_list.class); fromObsList.putString("idDiary", fromObsList.getString("idDiary")); listOBS.putExtras(fromObsList); add_obsindiaries.this.finish(); startActivity(listOBS); } }); AlertDialog alert = builder.create(); alert.show(); } }); } A: I think that the problem is from this line JSONObject json_data = new JSONObject(nameValuePairs.toString()); You are trying to parse data return from your param. It doesn't make sense. And nameValuePairs.toString() will return the string that doesn't match with Json format, that is why you got the error. You should use result instead of nameValuePairs.toString() JSONObject json_data = new JSONObject(result);
doc_23529482
In Visual Studio XAML designer it changes (it shows "button 2" text), but when I deploy it to the phone or to the emulator, the default template is applied. I tried to right click the control, "Edit template", "Edit a copy...", but it's not available. Is it possible, to redefine this template? My XAML code (just a very simplified example): <Page.BottomAppBar> <CommandBar> <CommandBar.SecondaryCommands> <AppBarButton Label="button"> <AppBarButton.Template> <ControlTemplate> <TextBlock Text="button 2" /> </ControlTemplate> </AppBarButton.Template> </AppBarButton> </CommandBar.SecondaryCommands> </CommandBar> </Page.BottomAppBar> I have Windows 8.1 Pro with Visual Studio Community 2013 Update 4 installed. A: No, it is not possible to customize the app bar on Windows Phone 8.1 beyond the foreground and background colors. On Windows Phone the app bar is system UI rather than app as UI. If you want to customize your app bar buttons you can put them in a custom panel docked at the bottom of the page instead of in a Page.BottomAppBar A: You can definitely right click and edit a copy. I just did this recently. Try putting a temporary AppBarButton at the top of your page and right click that one. Here is the default style in case you need it: <Style x:Key="AppBarButtonStyle1" TargetType="AppBarButton"> <Setter Property="Foreground" Value="{ThemeResource AppBarItemForegroundThemeBrush}"/> <Setter Property="VerticalAlignment" Value="Top"/> <Setter Property="HorizontalAlignment" Value="Left"/> <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/> <Setter Property="FontWeight" Value="Normal"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="AppBarButton"> <StackPanel x:Name="LayoutRoot" Background="Transparent" Width="80"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="ApplicationViewStates"> <VisualState x:Name="FullSize"/> <VisualState x:Name="Compact"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="TextLabel"> <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Width" Storyboard.TargetName="LayoutRoot"> <DiscreteObjectKeyFrame KeyTime="0" Value="48"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="Pressed"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="Ellipse"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="Ellipse"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="Content"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource AppBarItemPressedForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="Ellipse"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource AppBarItemDisabledForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="Content"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource AppBarItemDisabledForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="TextLabel"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource AppBarItemDisabledForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Grid HorizontalAlignment="Center" Height="38.5" Margin="0,12,0,4" Width="38.5"> <Ellipse x:Name="Ellipse" Fill="{ThemeResource AppBarItemBackgroundThemeBrush}" Height="38.5" Stroke="{ThemeResource AppBarItemForegroundThemeBrush}" StrokeThickness="2.5" UseLayoutRounding="False" Width="38.5"/> <Grid x:Name="ContentRoot" Background="Transparent"> <ContentPresenter x:Name="Content" AutomationProperties.AccessibilityView="Raw" Content="{TemplateBinding Icon}" Foreground="{TemplateBinding Foreground}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/> </Grid> </Grid> <TextBlock x:Name="TextLabel" Foreground="{ThemeResource AppBarItemForegroundThemeBrush}" FontSize="9.5" FontFamily="{TemplateBinding FontFamily}" Margin="0,0,0,10.5" TextAlignment="Center" TextWrapping="Wrap" Text="{TemplateBinding Label}" Width="70.5"/> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style>
doc_23529483
To you know how can it be done? Thanks and regards, A: You can subclass NSTableView like this : @interface myTableView ( ) @property( strong, nonatomic ) NSTableHeaderView * tableHeaderView; @end @implementation myTableView - ( void )awakeFromNib { [ super awakeFromNib ]; // For example CGFloat headerHeight = 50; self.tableHeaderView = [ [ NSTableHeaderView alloc ] initWithFrame:NSMakeRect( 0, 0, self.width, headerHeight ) ]; [ self setHeaderView:self.tableHeaderView ]; And voilà!
doc_23529484
In my project the user can save markers/timestamps by pushing a button, which triggers a function saving the data in CoreData. When the recording, during the user can save timestamps, is finished by a button press a function saves the recording to CoreData. My aim is that the recording saves and includes all created and saved markers/timestamps, so the user can click in i his history on a Project/Recording and gets all markers/timestamps for this recodring. At that point I can save and create a marker and recording but not link them to each other. How can I do it the easiest way - with a Many to Many Relationship? How do Many to Many Relationships work in my code? I would be really thankfull for help and ideas! Robert PS: On the phtos you can see that I already tried to create Relationships, but I can't create them with a function... Data Model Functions Relationships A: If I understand correctly, your UsedMarker represents the use of a particular MarkerItem, at a particular timestamp, of a particular Recording. Hence I would model the relationship from UsedMarker to Recording as to-one. Looking at your current model, the UsedMarker has attributes for the colour, name and icon, which you describe as coming from the MarkerItem entity. I would avoid that duplication, and replace those attributes with a to-one relationship from UsedMarker to MarkerItem. Defining the relationships in code is quite straight forward when they are to-one. If you have a Recording object, say currentRecording, and the user adds a particular MarkerItem, say chosenMarker, at a given timestamp, then you can create a new UsedMarker at assign the relationships: let useMarker = UsedMarker(context: self.context) useMarker.recording = currentRecording useMarker.markerItem = chosenMarker useMarker.id = UUID() useMarker.hours = ... // etc
doc_23529485
Say I need to process three or four different events, like calculating some number from market data feeds, order/trade feeds and 'outputting' some derivative of this data. Most of the time, these events or streams of data need to be processed in order (at least in order with respect to some key...for example, all orders for a specific symbol have to be processed in order, but in parallel with respect to unrelated symbols) I create a normal Java object with methods which mutate state. Rather than letting those methods directly change state, I put their parameters (by converting them to a command object) in a fifo queue (erlang's mailbox), and a react() method which processes that queue. This way, all updates have to go through a single queue and the react() method can only be accessed one update at a time. Theoretically this should save me the need to lock or synchronize on this method. However, this queue is basically an producer/consumer queue, which means it is a blocking queue. Blocking is very bad for scalability. Also, having a single queue means all my update command objects (of different types) come out of the queue with some overly generic super type (like Object) and I have to cast them back to the right type and let react() process them. Once this actorized object produces an output, to be consumed by another such object, I go through the same process. In other words, I've changed the programming model from object oriented, with methods which return results, to some sort of continuation passing nightmare where all my methods become asynchronous. Any ideas how I can approach this? A: More recently akka provides an actor framework for Scala and is based on Erlang. A: Use one of the excellent Actors libraries that have appeared recently. Alex Miller wrote a good two part piece for Javaworld on Actors. I also personally quite like Actor's Guild. A: You might also want to look into Scala's actors (you could see them as a kind of Java library), see for instance: The busy Java developer's guide to Scala: Dive deeper into Scala concurrency. A: You might also want to take a look at esper, which is not quite as low-level as the actor frameworks being mentioned, more like a generalized event-processing system you'd build on top of an actor framework. Very mature, complete, and I think developed for complex-event processing in financial transactions. A: Kontraktor is a new actor library designed for java 8. https://github.com/RuedigerMoeller/kontraktor A: You can consider another option, namely Netty along with LMAX Disruptor, both of them written in pure java. Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. What is the Disruptor? LMAX aims to be the fastest trading platform in the world. Clearly, in order to achieve this we needed to do something special to achieve very low-latency and high-throughput with our Java platform. Performance testing showed that using queues to pass data between stages of the system was introducing latency, so we focused on optimising this area. The Disruptor is the result of our research and testing. We found that cache misses at the CPU-level, and locks requiring kernel arbitration are both extremely costly, so we created a framework which has "mechanical sympathy" for the hardware it's running on, and that's lock-free... (this taken from https://lmax-exchange.github.io/disruptor/)
doc_23529486
I want to instrument some instructions in that. Is it possible to get objdump using pin tool, before (This can be easily done by objdump) and after instrumentation? I have created a tool which prints all the instructions. #include <stdio.h> #include "pin.H" #include <cstdint> FILE * trace; KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "pinatrace.out","A pin tool"); VOID Count(INS ins, void *v) { fprintf(trace,"\n%s",(INS_Disassemble(ins)).c_str()); } VOID Fini(INT32 code, VOID *v) { printf("count = %ld\n",(long)icount); fprintf(trace, "#eof\n"); fclose(trace); } /* ===================================================================== */ /* Print Help Message */ /* ===================================================================== */ INT32 Usage() { PIN_ERROR( "This Pintool prints a trace of memory addresses\n" + KNOB_BASE::StringKnobSummary() + "\n"); return -1; } /* ===================================================================== */ /* Main */ /* ===================================================================== */ int main(int argc, char *argv[]) { if (PIN_Init(argc, argv)) return Usage(); trace = fopen("pinatrace.out", "w"); INS_AddInstrumentFunction(Count, 0); PIN_AddFiniFunction(Fini, 0); // Never returns PIN_StartProgram(); return 0; } It prints the assembly instructions, but I am not sure if it includes the instrumented instructions. Is this the proper way to do this? Could you please help me? A: Is it possible to get objdump using pin tool, before (This can be easily done by objdump) and after instrumentation? You'll need a way to tell the PIN engine what you want to do with the results from objdump. You might want to link both of them though a script for example. It totally depends on what you want to do though. Is this the proper way to do this? Depends on what you want to do exactly, but I guess it's not. There's a clear distinction between instrumentation and analysis in PIN. Once you understand it, the rest is (relatively) easy. Conceptually, PIN instrumentation consists of two components: * *A mechanism that decides where and what code is inserted: the instrumentation. *The code to execute at insertion points: the analysis. That being said, one more important point: * *The instrumentation is only run once: when the instruction (or BBL, or TRACE) is discovered for the first time. *The analysis is run each time the instruction (or BBL, TRACE) is executed. So when you have: // set up the **instrumentation** INS_AddInstrumentFunction(Func_Instrumentation, 0); You are setting up the instrumentation (which is then only called once). If you need a callback to be called each time an instruction (or BBL, TRACE) is executed you need to set up an analysis routine, for example: // this is the **analysis** routine. // This function is called before every instruction is executed VOID docount() { icount++; } // The is the **instrumentation routine**, called by INS_AddInstrumentFunction(). // Pin calls this function each time a **new** instruction is encountered // Note that is won't be called for the same instruction after the first time. VOID Func_Instrumentation(INS ins, VOID *v) { // Insert a call to docount before every instruction, no arguments are passed INS_InsertCall( ins, // a representation of the instruction IPOINT_BEFORE, // where to insert, relative to the instruction (AFUNPTR)docount, // the analysis routine IARG_END); // no args to pass to the analysis routine } Check carefully the instruction count sample available: * *In source/tools/ManualExamples/inscount0.cpp *In the PIN Manual
doc_23529487
The file contains the data like this: TH|166777|20130930110716|2|Till 1|Customer Support|002|Manchester|-99.00|-82.50|-16.50|0.00|0.00|0.00|-99.00|0.00|0.00|0.00|till|sold|9|2-1007-9999||Balding|Claire|Ms| Customer |Ashby Road|Loughborough|Leicestershire|LE11 3NG|GBR|01509 232200|||||||||||||||||| TO|4SA671:MULTI:10|5252525000026|Andrea Shirt|COLOUR: Multi / COLOUR: Multi-pack / SIZE: 10. / |1|0.00|-82.50| 110.00|-99.00|0.00|20.00|1|0.00|refund|n/a||WTOP||0|0|0.00||0.00|486|1666|485||GOOD Goodwill TT|card|-99.00|GBP||Visa Credit ||| TF|3|1 A: Try this : SUBSTRING([Column 0],1,2) == "TH"
doc_23529488
User Query Error :XMLHttpRequest failed: {} Below is my code : user.signUp(null, { success: function(user){ alert("Successfully signed up !") //Copy the Object ID generated for the user to the UserId field in the profile table. var User = Parse.Object.extend("User"); var user = new User(); var userQuery = new Parse.Query(User); userQuery.find({ success: function(results) { for (var i in results) { //Comparing the username from the User table to the typed username and obtaining //the corresponding objectId. if(results[i].get("username")==userName) { var objectId = results[i].get("objectId"); console.log("ObjectId : "+objectId); } else { console.log("No such user.") } } } ,error: function(error) { console.log("User Query Error :"+error.message); } }); window.location.href = "index.html"; } , error: function(user, error){ console.log("signup error:"+error.message); alert(" Error in sign up"); } }); I am not able to figure out the exact problem. Can anyone help me out here. A: Go the answer myself. I had the same name variables. All I did was change 2 lines. var myUser = Parse.Object.extend("User"); var userQuery = new Parse.Query(myUser); userQuery.find({ It ran like a charm.
doc_23529489
Ant version - Ant Target -debug Build file -path of my project/build.xml Properties -sdk.dir=/Users/Mac002/Android However when I try to build the project I am getting below error: Buildfile: /Users/Shared/Jenkins/Home/jobs/Project/workspace/build.xml -set-mode-check: -set-debug-files: -check-env: [checkenv] Android SDK Tools Revision 24.4.1 [checkenv] Installed at /Users/Mac002/Android -setup: [echo] Project Name: Project [gettype] Project Type: Application -set-debug-mode: -debug-obfuscation-check: -pre-build: -build-setup: [getbuildtools] Using latest Build Tools: 23.0.2 [echo] Resolving Build Target for Project... [gettarget] Project Target: Android 4.4.2 [gettarget] API level: 19 [echo] ---------- [echo] Creating output directories if needed... [echo] ---------- [echo] Resolving Dependencies for Project... BUILD FAILED /Users/Mac002/Android/tools/ant/build.xml:573: ../../../../android-support-v7-appcompat resolve to a path with no project.properties file for project /Users/Shared/Jenkins/Home/jobs/Project/workspace Total time: 3 seconds Build step 'Invoke Ant' marked build as failure
doc_23529490
How can I ensure that the connection close down properly when closing down or clicking on a new link within the application? This is my live event controller. def events response.headers["Content-Type"] = "text/event-stream" redis = Redis.new redis.psubscribe("participants.*") do |on| on.pmessage do |pattern, event, data| response.stream.write("event: #{event}\n") response.stream.write("data: #{data}\n\n") end end rescue IOError ensure redis.quit response.stream.close end Database conf production: adapter: postgresql encoding: unicode database: ************ pool: 1000 username: ************ password: ************ timeout: 5000 I'm using puma as standalone webserver (i don't have heavy static files that need to be served by nginx) on Ubuntu 10.04 with postgresql 9.2.x. A: You have to change the development environment settings to enable this feature. Add or change this in your config/environments/development.rb: config.cache_classes = true config.eager_load = true See http://railscasts.com/episodes/401-actioncontroller-live?view=asciicast A: Puma shouldn't be blocking and should allow multiple threads to allow multiple requests. To walk you through what is happening in your code. You are currently using two threads in this code per request. The thread the request came in on, and a background thread used to hold open the connection. Your connections will properly close due to the ensure block at the end of your action method. def events response.headers["Content-Type"] = "text/event-stream" redis = Redis.new # blocks the current thread redis.psubscribe("participants.*") do |on| on.pmessage do |pattern, event, data| response.stream.write("event: #{event}\n") response.stream.write("data: #{data}\n\n") end end # stream is on a background thread and will remain open until # redis.psubscrie exits. (IO Error, etc) rescue IOError ensure redis.quit response.stream.close end You could also investigate another server called rainbows (http://rainbows.rubyforge.org/index.html) which is another very good rack server for open requests. Here is also a thread related to streaming threads hanging https://github.com/rails/rails/issues/10989
doc_23529491
How do I properly specify a minimum memory requirement without causing AWS Batch to kill jobs that go slightly above that? It seems very strange to me that the "memory" parameter appears to be both a minimum and a maximum. I assume I'm misunderstanding something. A: The memory requirements in the resourceRequirements property are always the maximum/upper bound. You specify there how much memory at max your job container is going to use. Quote from https://docs.aws.amazon.com/batch/latest/userguide/job_definition_parameters.html : The hard limit (in MiB) of memory to present to the container. If your container attempts to exceed the memory specified here, the container is killed. A lower/minimum bound would not make much sense, since AWS needs to put your job container onto a host that actually supports the upper bound/limit, because there is no way to tell a priori how much actual memory your container is going to use. Or put another way: If there were such a thing as a "minimum" requirement and you specified minimum = 1 MiB and maximum = 16 GiB, what is AWS Batch supposed to do with this information? It cannot put your job container onto a host with say 512 MiB of memory because your job container, as it runs, may exceed that, since you said the maximum was 16 GiB (in this example). And AWS Batch is not going to freeze a running job and migrate it onto another host, once the current host's memory is reached. The fact that AWS Batch decided to put your concrete job container onto an instance with 64 GiB may be coincidental because 32 GiB is just the border of an instance's memory size 32 GiB <-> 64 GiB. And if your job were to use the full 32 GiB then there wouldn't be any memory left for the host (without swapping).
doc_23529492
I wrote this code but it can't work successfully. Someone can understand why? if __name__ == '__main__': # if "pro" begin with "test", delete "test" from "pro". pro = "001001111010010101001" test = "0010" if pro.startswith(test): pro = pro.lstrip(test) # My ideal -> pro == "01111010010101001" print pro print pro This code doesn't output anything. A: str.lstrip() removes all characters that appear in the set of characters you gave it. Since you gave it both 0 and 1 in that set, and the string consists of only zeros and ones, you removed the whole string. In other words, str.lstrip() does not remove a prefix. It removes one character at a time, provided that character is named in the argument: >>> '0123'.lstrip('0') '123' >>> '0123'.lstrip('10') '23' >>> '0123'.lstrip('20') '123' Remove the first len(test) characters instead: pro = pro[len(test):] A: lstrip(chars) returns a copy of the string in which all chars have been stripped from the beginning of the string. so if you pass test that contain 1,0 it remove all the characters from pro (pro contain only 0,1) . >>> pro = pro.lstrip('10') >>> pro '' instead you can Just use slicing : >>> if pro.startswith(test): ... pro=pro[len(test):] ... >>> pro '01111010010101001' A: This is because lstrip removes all of the left characters from the set given so removes everything: I think that you need: pro = pro.startswith(test) and pro[len(test):] or pro this will remove test from the start of pro if it is there. A: Just as extra.. This will also work: >>> pro = "001001111010010101001" >>> test = "0010" >>> if pro.startswith(test): pro = pro.partition(test)[-1] print pro 01111010010101001
doc_23529493
This is my interface repository: public interface InterfaceRepositroy: IDisposable { IEnumerable<SubjectContent> GetAll(); SubjectContent Get(string id); } This is the toher repository: public class SubjectRepository : InterfaceRepositroy,IDisposable { private irfwebpage20161013070934_dbEntities2 db; public IEnumerable<SubjectContent> GetAll() { return db.Set<SubjectContent>().ToList(); } public SubjectContent Get(string id) { return db.Set<SubjectContent>().Find(id); } public void Dispose() { throw new NotImplementedException(); } } Here is my controller: private InterfaceRepositroy subjectreposi; public ActionResult Details(string id) { SubjectContent subject = subjectreposi.Get(id); return View(subject); } My View is a standard details template. It gets an error at this point in the controller: SubjectContent subject = subjectreposi.Get(id); I would really appreciate the help. This is like the fourth version of a repository pattern i am trying to implement but none of them worked so far. I have tried it without interface, with the instance of the subjecrepository or with different linq to sql in the repository. It either gets http error or it doesnt show the data just the names of the data. A: Create constructors that initialise your data context: public SubjectRepository() { db = new irfwebpage20161013070934_dbEntities2(); } public SubjectRepository(irfwebpage20161013070934_dbEntities2 dbContext) { db = dbContext; } This allows you to either initialise your repository with no parameters which will initialise you data context or specify your own data context. You can now use this like this: var repo = new SubjectRepository(); SubjectContent subject = repo.Get(id);
doc_23529494
I want to sprintf the data from this pointer in a buffer like this : void send_bin(uint8_t* binarypayload, uint8_t size, uint32_t mode) { char buffer[256]; sprintf(buffer, "AT+ZF=%s,%lu\r\n", binarypayload, mode); HAL_UART_Transmit(&husart1, (uint8_t*)buffer, strlen((char*) buffer), 1000); } But on my uart I can only see the binary value on my uart: þTÞ­˜. Where am I going wrong ? Sorry I have forgotten to say that my datas is like : uint8_t buffer[4] = {0x45, 0xAD, 0xEF, 0x5B}; And I want it to look like this on my uart : AT+ZF=45ADEF5B,45 but I only have access to its pointer A: You need to convert the binary data into a hexadecimal format. The easiest way, is to convert each byte individually: void send_bin(uint8_t* binarypayload, uint8_t size, uint32_t mode) { char buffer[256]; strcpy(buffer, "AT+ZF="); for (int i = 0; i < size; i++) { sprintf(buffer + strlen(buffer), "%02x", binarypayload[i]); } sprintf(buffer + strlen(buffer), ",%lud\r\n", mode); HAL_UART_Transmit(&husart1, (uint8_t*)buffer, strlen(buffer), 1000); } A: snprintf can convert the bytes into their hexadecimal format in a string, but it doesn't have the automatic ability to do that to an array of them. We can call it multiple times in a for loop to enable that ability though. void send_bin(uint8_t* binarypayload, uint8_t size, uint32_t mode) { char buffer[256] = {}; int offset = 0; int ret = snprintf(buffer + offset, sizeof(buffer) - offset, "AT+ZF="); assert(ret == 6); offset += ret; for (int i = 0; i < size; i++) { ret = snprintf(buffer + offset, sizeof(buffer) - offset; "%02X", binarypayload[i]); assert(ret == 2); offset += ret; } ret = snprintf(buffer + offset, sizeof(buffer) - offset, "\r\n"); assert(ret == 2); HAL_UART_Transmit(&husart1, (uint8_t*)buffer, strlen((char*) buffer), 1000); } A: sprintf on uC for this simple task is overkill. And it will not work if you decide to use RTOS in your project. I would: const char digits[] = "0123456789ABCDEF"; char *dumphex(char *buff, const void *data, size_t size) { char *wrk = buff; const uint8_t *u8data = data; if(buff && data) { while(size--) { *wrk++ = digits[*u8data >> 4]; *wrk++ = digits[*u8data & 0x0f]; } *wrk = 0; } return buff; } or if you do not want to use lookup string #define GETDIGIT(x) ((x) > 9 ? ((x) - 10) + 'A' : (x) + '0') char *dumphex1(char *buff, const void *data, size_t size) { char *wrk = buff; const uint8_t *u8data = data; if(buff && data) { while(size--) { *wrk++ = GETDIGIT(*u8data >> 4); *wrk++ = GETDIGIT(*u8data & 0x0f); } *wrk = 0; } return buff; }
doc_23529495
I am trying to aggregate (sum) total sales revenue EXCEPT for orders that contain Item X (from the orders_products table), but for some reason the sum of sales revenues aren't adding up properly when I introduce the third table (orders_products). I know how to do the aggregation and the item exception separately with any two of three tables, but the complexity for me is combining both functions by introducing the third table. Here is my properly working query so far with just the two original tables: SELECT o.orders_id, ot.orders_id, o.delivery_state, SUM(ot.revenue) AS ordersum FROM orders_total ot, orders o WHERE ot.orders_id = o.orders_id GROUP BY o.delivery_state ORDER BY ordersum DESC; How would I implement the exception to ignore orders that contain Item X? A: You can simply exclude any orders from your original query which are identified via a subselect: SELECT o.orders_id, ot.orders_id, o.delivery_state, SUM(ot.revenue) AS ordersum FROM orders_total ot INNER JOIN orders o ON ot.orders_id = o.orders_id WHERE ot.orders_id NOT IN (SELECT orders_id FROM orders_products WHERE product_name = '?') GROUP BY o.delivery_state ORDER BY ordersum DESC; Note that ? represents the product_name you are trying to exclude. You also probably don't want orders_id information as part of your select, as that is meaningless data with regards to this aggregation. For this query to run well make sure you have indexes on: orders_products.product_name orders.delivery_date orders.orders_id orders_total.orders_id A: Join to your main query a subquery that selects the orders that contain item X, and then filter out those that don't in the argument to SUM(). SELECT o.orders_id, ot.orders_id, o.delivery_state, SUM(CASE WHEN op.orders_id IS NULL THEN ot.revenue ELSE 0 END) AS ordersum FROM orders_total ot INNER JOIN orders o ON ot.orders_id = o.orders_id LEFT OUTER JOIN ( SELECT DISTINCT orders_id FROM orders_products WHERE ... -- Add your condition to select only item X ) op ON op.orders_id = o.orders_id GROUP BY o.delivery_state ORDER BY ordersum DESC;
doc_23529496
It would be nice if I could say: "remove the oldest table", but assuming this is not available, I'm ready to compromise on which exact partition I want to remove. I know I can just execute drop table EVENTS_p2015_07_16 but I'm wondering if it ain't going to mess up anything with partman data and configuration. Is there another way to do that?
doc_23529497
doc_23529498
I need to loop through the recordsets an have it append into a table. I am having a problem trying to parse out the initial txt file. I am using where Mid("AllData", 1, 2) = "BR" I have the code below. What am I doing wrong? Sub BR_Records() On Error GoTo ErrorHandler Dim strSQL As String Dim rs As DAO.Recordset strSQL = "TBL_AllData" Set rs = CurrentDb.OpenRecordset(strSQL) With rs If Not .BOF And Not .EOF Then .MoveLast .MoveFirst While (Not .EOF) Debug.Print rs.Fields("AllData"); where.Mid("AllData", 1, 2) = "BR" .MoveNext Wend End If .Close End With ExitSub: Set rs = Nothing Exit Sub ErrorHandler: Resume ExitSub End Sub A: Try this: With rs If .RecordCount > 0 Then .MoveFirst While Not .EOF If Mid(.Fields("AllData").Value, 1, 2) = "BR" Then Debug.Print .Fields("AllData").Value End If .MoveNext Wend End If .Close End With
doc_23529499
C:\Users\myStuff\Documents\C_Codes>gcc -v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.8.1/lto-wrapper.exe Target: mingw32 Configured with: ../gcc-4.8.1/configure --prefix=/mingw --host=mingw32 --build=m ingw32 --without-pic --enable-shared --enable-static --with-gnu-ld --enable-lto --enable-libssp --disable-multilib --enable-languages=c,c++,fortran,objc,obj-c++ ,ada --disable-sjlj-exceptions --with-dwarf2 --disable-win32-registry --enable-l ibstdcxx-debug --enable-version-specific-runtime-libs --with-gmp=/usr/src/pkg/gm p-5.1.2-1-mingw32-src/bld --with-mpc=/usr/src/pkg/mpc-1.0.1-1-mingw32-src/bld -- with-mpfr= --with-system-zlib --with-gnu-as --enable-decimal-float=yes --enable- libgomp --enable-threads --with-libiconv-prefix=/mingw32 --with-libintl-prefix=/ mingw --disable-bootstrap LDFLAGS=-s CFLAGS=-D_USE_32BIT_TIME_T Thread model: win32 gcc version 4.8.1 (GCC) I have looked in c:\minGW\include\ to try to find string.h and it is there but when I try to have I my C code something like: string temp I get the following compile error: error: unknown type name 'string' how can I fix this so I can use strings?? I have also included stdio.h, stdlib.h, and there are two string headers, string.h and strings.h A: Try to compile the code using g++, because c language doesn't support a string type or else you can use character array for the same. You can define character array and copy contents into array like this char arr[SIZE]; strcpy(arr,"Your String");