text
stringlengths
15
59.8k
meta
dict
Q: Creating a Docker volume at a specific location Can I tell Docker to create a volume at a specific location on the host machine? The host machine has some storage restrictions and I'd like the volume to be stored in /data instead of /var/lib/docker/vfs/dir/. This isn't even mentioned in the documentation so I suspect I misunderstood something. A: Do you want to use a different directory than the default /var/lib/docker as Docker runtime? You can do this by starting docker daemon with -g option and path to the directory of your choice. From the man page: -g, --graph="" Path to use as the root of the Docker runtime. Default is /var/lib/docker. A: When firing up your container with "docker run": docker run -v /data/some_directory:/mount/location/in/your/container your_docker_image You cannot do this in the same way via Dockerfile because of portability.
{ "language": "en", "url": "https://stackoverflow.com/questions/31747061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way I can specify a different repository for the CocoaPods master repo? At my work, we have a private cocoapods repository that we use to host whitelisted libraries for developers, and I am trying to validate a library I wrote. Whenever i do a pod spec lint MYPODNAME --verbose, CocoaPods tries to validate my spec against the master repo instead of my private repo. Is there any way to get around this behavior? I have tried completely removing the master repo, but it still attempts to validate my pod's dependencies against master EDIT: This issue seems to describe what I am experiencing. A: Answering my own question. You have to manually specify the --sources for what CocoaPods will validate the spec against. pod spec lint MYPODNAME --verbose --sources=git@<DOMAIN>:<REPO>.git
{ "language": "en", "url": "https://stackoverflow.com/questions/34053927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to access php variable out side of a foreach loop i have a veriable named (num) which is used for increments changes names of ids by 1 num+1 but in my foreachloop i cant access it . i tried declaring it before the loop still doesnot work <?php $num = 0; ?> <?php foreach($listings as $list):?> <li> <div class="checkbox"> <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num+1;?>" name="treatment<?php echo $num+1;?>"> <label for="visit<?php echo $num+1;?>" class="css-label"><?php echo $list['title']?> <strong><?php echo $list['price'];?><span>&#163;</span></strong></label> </div> </li> <?php endforeach; ?> </ul> <hr> <input type="hidden" value="<?php echo $num;?>" name="total"/> i want the input ids to be incremented by 1 like treatment1,treatment2 A: You should increment the $num variable by doing $num++; once inside the loop, then print it where you need it with <?php echo $num; ?> without using <?php echo $num+1; ?> - as doing so will only increment it as you echo it - not add one to each iteration. <?php $num = 0; foreach($listings as $list): $num++; // Increment $num for each iteration ?> <li> <div class="checkbox"> <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>"> <label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <strong><?php echo $list['price'];?><span>&#163;</span></strong></label> </div> </li> <?php endforeach; ?> If your $listings is numeric indexed, you can use the key of each element in the array instead by doing foreach($listings as $num=>$list): ?> <li> <div class="checkbox"> <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>"> <label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <strong><?php echo $list['price'];?><span>&#163;</span></strong></label> </div> </li> <?php endforeach; ?> A: The problem is you did not set the value of $num variable you just only print or echo it inside the html tags. You need to add or increment the $num variable inside the loop like this. <?php $num++; ?> or <?php $num = $num+1; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/56226277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Vagrant broken with Ruby 'Segmentation Fault' Error All of a sudden Vagrant is broken on my machine. I don't see what might have caused this. It came up with an older version of Virtualbox and Vagrant 1.9.8. I updated both to the current version in hope to get it fixed. I run * *Windows 10 Pro 1709 *Virtualbox 5.2.0-118431 *Vagrant 2.0.1 I was using a current Ruby installation in parallel but removed it for testing. For any Vagrant command I get this error: https://gist.github.com/cfoellmann/b8c50dc386d241d44ed0fca60e7680d1 I have read about issues with the ffi gem but I see no way to fix the bundled components of the vagrant install. Any pointer into debugging this will be much appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/47249602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In text classification, how to find the part of sentence that is important for the classification? I have trained a text classification model that works well. I wanted to get deeper and understand what words/phrases from a sentence were most impactful in the classification outcome. I want to understand what words are most important for each classification outcome I am using Keras for the classification and below is the code I am using to train the model. It's a simple embedding plus max-pooling text classification model that I am using. from tensorflow.keras.models import Sequential from tensorflow.keras import layers import tensorflow as tf from tensorflow.keras.callbacks import EarlyStopping # early stopping callbacks = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', min_delta=0, patience=5, verbose=2, mode='auto', restore_best_weights=True) # select optimizer opt = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False, name="Adam") embedding_dim = 50 # declare model model = Sequential() model.add(layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=maxlen)) model.add(layers.GlobalMaxPool1D()) model.add(layers.Dense(10, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy']) model.summary() # fit model history = model.fit(X_tr, y_tr, epochs=20, verbose=True, validation_data=(X_te, y_te), batch_size=10, callbacks=[callbacks]) loss, accuracy = model.evaluate(X_tr, y_tr, verbose=False) How do I extract the phrases/words that have the maximum impact on the classification outcome? A: It seems that the keyword you need are "neural network interpretability" and "feature attribution". One of the best known methods in this area is called Integrated Gradients; it shows how model prediction depend on each input feature (each word embedding, in your case). This tutorial shows how to implement IG in pure tensorflow for images, and this one uses the alibi library to highlight the words in the input text with the highest impact on a classification model.
{ "language": "en", "url": "https://stackoverflow.com/questions/70121559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Modal view controller not in the window hierarchy The App I'm trying to do has a tabbar controller. When the App starts, I'm getting the user location in the AppDelegate and when I've got the accuracy I need the AppDelegate sends an NSNotification to my App's starting page (index 0 of the tab bar controller). Upon receiving the notification, this view tries to send an email with the user coordinates and other data, but as soon as the MFMailComposeViewController is presented I get the following error: Warning: Attempt to present <MFMailComposeViewController: 0x98a0270> on <UITabBarController: 0x988c630> whose view is not in the window hierarchy! What am I missing? Thanks. EDIT: adding some code... This is what I've got in my AppDelegate.m: - (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSUserDefaults *phoneNumbers = [NSUserDefaults standardUserDefaults]; NSDate *eventDate = newLocation.timestamp; NSTimeInterval howRecent = [eventDate timeIntervalSinceNow]; if (abs(howRecent) < 10.0) { [self locationUpdate:newLocation]; smsLoc = newLocation; if ([[phoneNumbers objectForKey:@"sendSMS"] isEqualToString:@"yes"]) { [[NSNotificationCenter defaultCenter] postNotificationName:@"sendSMS" object:nil]; } else if ([[phoneNumbers objectForKey:@"sendEmail"] isEqualToString:@"yes"]) { [[NSNotificationCenter defaultCenter] postNotificationName:@"sendEmail" object:nil]; } } } Then, in my first view controller I have: - (void)viewDidLoad { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendSMS:) name:@"sendSMS" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendEmail:) name:@"sendEmail" object:nil]; } And at the end, the selector for "sendSMS" (the other is pretty similar): - (void)sendSMS: (NSNotification *)notification { NSUserDefaults *phoneNumbers = [NSUserDefaults standardUserDefaults]; if ([phoneNumbers objectForKey:@"first"] || [phoneNumbers objectForKey:@"second"]) { MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init]; if ([MFMessageComposeViewController canSendText]) { AppDelegate *deleg = (AppDelegate *)[[UIApplication sharedApplication] delegate]; controller.body = [NSString stringWithFormat:@"some message with coordinates %.4f - %.4f", [deleg currentLocation].coordinate.latitude, [deleg currentLocation].coordinate.longitude]; controller.recipients = [NSArray arrayWithObjects:[phoneNumbers objectForKey:@"first"], [phoneNumbers objectForKey:@"second"], nil]; controller.messageComposeDelegate = self; [self presentModalViewController:controller animated:YES]; } } } } Second edit: adding some more code. UITabBarController *tabBarController = [[UITabBarController alloc] init]; tabBarController.delegate = self; tabBarController.selectedIndex = 0; [[tabBarController.tabBar.items objectAtIndex:0] setTitle:NSLocalizedString(@"Home", nil)]; [[tabBarController.tabBar.items objectAtIndex:1] setTitle:NSLocalizedString(@"Requests", nil)]; [[tabBarController.tabBar.items objectAtIndex:2] setTitle:NSLocalizedString(@"Account", nil)]; [[tabBarController.tabBar.items objectAtIndex:3] setTitle:NSLocalizedString(@"Settings", nil)]; //some other controls from DB [[tabBarController.tabBar.items objectAtIndex:1] setBadgeValue:[NSString stringWithFormat:@"%d",number]]; The tabbarController has been made via IB, but I've added the code above in my AppDelegate because I need to localize the tab bar items and to add a badge to one of them. Am I doing something wrong here? A: Using this may help someone: [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:picker animated:NO completion:nil]; A: I'm not sure if you have solve this issue. The error message means the viewcontroller you use to present another modal viewcontroller is not visible on the window. This can happen for e.g: [VC1 presentModalViewController:VC2]; // Error here, since VC1 is no longer visible on the window [VC1 presentModalViewController:VC3]; If your issue is like above, you can fix it like: if (self.modalViewController != nil) { [self.modalViewController presentModalViewController:VC3 animated:YES]; } else { [self.tabBarController presentModalViewController:VC3 animated:YES]; } If that doesn't fix your issue, maybe you can try to present using self.tabBarController instead of self. Again just suggestion, not sure if it works though. A: Since modalViewController and presentModalViewController are deprecated, the following is what works for me: presentingVC = [[UIApplication sharedApplication] keyWindow].rootViewController; if (presentingVC.presentedViewController) { [presentingVC.presentedViewController presentViewController:VC3 animated:YES completion:nil]; } else { [presentingVC presentViewController:VC3 animated:YES completion:nil]; } A: You can follow this pattern [VC1 presentModalViewController:VC2]; // [**VC2** presentModalViewController:VC3];
{ "language": "en", "url": "https://stackoverflow.com/questions/12391425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Detecting a pattern in a list/array This is rather an algorithmic question. I have a Java List (sorted) or array that consists of chars (X and Y) and I need to detect a certain pattern of the way the values are ordered. The List size is fixed (for example 5). The patterns I'd like to detect are the following: XYYYY XXYYY XXXYY XXXXY XXXXX So X is always followed by only Y's. Simple String.equals or contains doesn't work, since it's not scalable and is restricted to a known list size. A: You can use a simple regular expression for this: boolean matches = s.matches("^X+Y*$"); This means: * *^ matches the start of the string *X+ means one or more consecutive Xs *Y* means zero or more consecutive Ys *$ is the end of the string Alternatively, you can check the string character-wise: int i = 0; while (i < s.length() && s.charAt(i) == 'X') { ++i; } if (i < s.length()) { if (s.charAt(i) != 'Y') { return false; } while (i < s.length() && s.charAt(i) == 'Y') { ++i; } } return i == s.length(); A: You can use the following regular expression to detect the particular pattern. String pattern = "^(X){1,}Y*$"; Here's the complete java code, import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternMatch { public static void main(String[] args){ // String to be scanned to find the pattern. String line = "XXXXY"; String pattern = "^(X){1,}Y*$"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); } else { System.out.println("NO MATCH"); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/33592693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What goes into writing a cache simulator program? Can any one explain or point me to a source that explain what goes into writing a cache simulator program. It's a school project and I have no intention to use anyone else's code as it does me no good. I will be tested on understanding of the program and concept, but I would like so see some detailed material, a pseudo code or gant chart or something. I'm asking here because text book and lectures have not given me enough information and I've googled for hours this week and found nothing relevant. A: Try this. But keep in mind about Academic Integrity, which is posted at the bottom of the page. It may not be the same school you go to, but I'm sure AI is universal regardless of whatever school assignment you're going through. You can also try Googling your problem, I found ~five references for doing so.
{ "language": "en", "url": "https://stackoverflow.com/questions/14913140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How Do I Draw Two Overlapping JPanels such that the Graphics Drawn On Both Of Them Display On The Screen? I have two JPanels. One panel has a 100x100 rectangle drawn at 0,0. And the other has a 100x100 rectangle drawn at 100, 100. My problem is that when both JPanels are drawn on the JFrame's content pane, one JPanel (the last one drawn) covers the other, hiding its graphics. Below is oversimplified code drawing two rectangles and the things I've tried. package playground; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import javax.swing.JFrame; import javax.swing.JPanel; public class Playground{ public Playground(){ JFrame frame = new JFrame("My Frame"); frame.setSize(400, 400); JPanel backPanel = new JPanel(){; @Override public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; Rectangle2D rect = new Rectangle2D.Double(0, 0, 100, 100); g2.draw(rect); } }; JPanel frontPanel = new JPanel(){ @Override public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; Rectangle2D rect = new Rectangle2D.Double(150, 150, 100, 100); g2.draw(rect); } }; frontPanel.setOpaque(true); //Does nothing frontPanel.setBackground(new Color(0, 0, 0, 0)); //Does nothing frontPanel.setForeground(new Color(0, 0, 0, 0)); //Erases the rectangle drawn frame.getContentPane().add(backPanel); frame.getContentPane().add(frontPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String[] args){ System.out.println("Hello World"); new Playground(); } } If anyone cares why I want to do this, I'm creating the game breakout. I am a novice programmer and I have no knowledge of gaming theory. So I decided the smartest way to avoid a lot of rendering and buffering is to have four JPanels. A static JPanel at the very back with an image drawn on it (fun background image). A JPanel with the paddle drawn on it. A JPanel with bricks drawn on it. And a JPanel with a ball drawn on it. My rationale is that I won't have to redraw the paddle if it is not being moved, the background, and bricks that are not being hit. If a brick lets say is hit, I will update an arrayList of bricks and call repaint on the corresponding JPanel. A: I am a novice programmer and I have no knowledge of gaming theory. Ok, we can work with that. So I decided the smartest way to avoid a lot of rendering and buffering is to have four JPanels. You've just unnecessarily complicated your program. Think of a JPanel as a canvas. You want to draw the entire Breakout game; bricks, paddle, and ball, on one JPanel canvas. Don't worry, you'll be able to redraw the entire canvas fast enough to get 60 frames per second if you want. The way to do this is to create a Brick class, a Paddle class, and a Ball class. You create a Game Model class that contains one instance of the Paddle class, one instance pf the Ball class, and a List of instances of the Brick class. The Brick class would have fields to determine its position in the wall, the number of points scored when the ball collides with the brick, the color of the brick, and a draw method that knows how to draw one brick. The ball class would have fields to determine its x, y position, its direction, its velocity, and a draw method that knows how to draw the ball. The Paddle class would have fields to determine its x, y position, its direction, its velocity, and a draw method that knows haw to draw the paddle. The Game Model class would have methods to determine when the ball collides with a brick, determine when the ball collides with a brick, determine when the ball collides with a wall, and a draw method that calls the other model class draw methods to draw a ball, a paddle, and a wall of bricks. This should be enough for now to get you started going in the right direction. Edited to answer questions: How would I implement a draw method in all these classes? Here's an example Ball class. I haven't tested the moveBall method, so it might need some adjustment import java.awt.Graphics; import java.awt.geom.Point2D; public class Ball { private Point2D position; /** velocity in pixels per second */ private double velocity; /** * direction in radians * <ul> * <li>0 - Heading east (+x)</li> * <li>PI / 2 - Heading north (-y)</li> * <li>PI - Heading west (-x)</li> * <li>PI * 3 / 2 - Heading south (+y)</li> * </ul> * */ private double direction; public Point2D getPosition() { return position; } public void setPosition(Point2D position) { this.position = position; } public double getVelocity() { return velocity; } public void setVelocity(double velocity) { this.velocity = velocity; } public double getDirection() { return direction; } public void setDirection(double direction) { this.direction = direction; } public void moveBall(long milliseconds) { Point2D oldPosition = position; // Calculate distance of ball motion double distance = velocity / (1000.0D * milliseconds); // Calculate new position double newX = distance * Math.cos(direction); double newY = distance * Math.sin(direction); newX = oldPosition.getX() + newX; newY = oldPosition.getY() - newY; // Update position position.setLocation(newX, newY); } public void draw(Graphics g) { int radius = 3; int x = (int) Math.round(position.getX()); int y = (int) Math.round(position.getY()); // Draw circle of radius and center point x, y g.drawOval(x - radius, y - radius, radius + radius, radius + radius); } } The draw method draws the ball wherever it actually is located. That's all the draw method does. Actually moving the ball is the responsibility of the Game Model class. The method for moving the ball is included in this class because the information necessary to move the ball is stored in the Ball class. I gave the ball a radius of 3, or a diameter of 6 pixels. You may want to make the ball bigger, and use the fillOval method instead of drawOval. should I just call repaint() at a 30ms interval Basically, yes. In psudeocode, you create a game loop while (running) { update game model(); draw game(); wait; } First, you update the game model. I gave you a Ball class. You would have similar classes for the paddle and bricks. They all have draw methods. Your Game model class calls all of these draw methods in the proper order. In Breakout, you would draw the boundaries first, then the bricks, then the paddle, and finally, the ball. Your JPanel (canvas) calls the one draw method in the Game Model class. I don't have an example game to show you, but if you read the article Sudoku Solver Swing GUI, you'll see how to put together a Swing GUI and you'll see how model classes implement draw methods. I suggest that you stop working on Breakout for a while and go through the Oracle Swing Tutorial. Don't skip any sections in your haste to write a program. Go through the entire tutorial so you understand how Swing works before you try and use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/16739225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery: I need to show consecutive fields in a form at each new click I have 5 upload fields but I need to hide them except the first. Then at each click to show them one by one. I created the following script but it seems like item.show() is not displaying the hidden fields.10x first = $('.webform-client-form').find('div[id$="-ajax-wrapper"]').first(); first.after('<a id="addmore" href=#>[+] Add more</a>'); $('.webform-client-form').find('div[id$="-ajax-wrapper"]').each(function(){ $(this).hide(); first.show(); }); var c = 1;//counter $('#addmore').bind('click', function(e) { item = $('edit-submitted-file'+c+'-ajax-wrapper'); item.show(); ++c; if (c == 5) { $('#addmore').hide(); return false; } }); A: shouldn't this: var item = $('edit-submitted-file'+c+'-ajax-wrapper'); be var item = $('#edit-submitted-file'+c+'-ajax-wrapper'); //if using id or var item = $('.edit-submitted-file'+c+'-ajax-wrapper'); //if using class A: You need to prepend '#' to the selector for -ajax-wrapper because you are selecting it by ID. The counter needs to start at 2 and hide addmore on 6. The return false (should actually be e.preventDefault() should be outside of that conditional. addmore should be added after the last of the file input rows, not the first. A: Just use the next() function and :visible selector Example: HTML <label><span>File</span> <input type="file" /></label> <label><span>File</span> <input type="file" /></label> <label><span>File</span> <input type="file" /></label> ... JQuery $('label:gt(0)').hide(); // hide all except the first one $('label:visible').click($(this).next('label').show()); // show the following :visible is not necessary, as you can't click on hidden elements, but it's just an optimisation.
{ "language": "en", "url": "https://stackoverflow.com/questions/13930742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find Instance ID for Azure Servers In AWS we have instance IDs to identify machines. What's the equivalent in Azure and how do I find that? I'd like to list the instance ID in powershell so I can put that into a script. A: If I have not misunderstood, I suppose you want to get the InstanceId of the VM in the Azure VM Scale set. You could try to use Get-AzureRmVmssVM to get it. Get-AzureRmVmssVM -ResourceGroupName <ResourceGroupName> -VMScaleSetName <VMScaleSetName> Update: If you want to get the ResourceId of azure resource, you could use Get-AzureRmResource to do it, just specify the properties what you want. For example: 1.Get ResourceId of the specific resource: $resource = Get-AzureRmResource -ResourceGroupName <ResourceGroupName> -ResourceType <ResourceType> -ResourceName <ResourceName> $resource.ResourceId 2.Get ResourceIds of all resources in the specific resource group $resource = Get-AzureRmResource -ResourceGroupName <ResourceGroupName> $resource.ResourceId 3.Get ResourceIds of all resources under your subscription. $resource = Get-AzureRmResource $resource.ResourceId The result will like(actual result will decided by your properties):
{ "language": "en", "url": "https://stackoverflow.com/questions/52189383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best approach to upload a file using Jersey client? I want to upload a file (a zip file to be specific) to a Jersey-backed REST server. Basically there are two approaches (I mean using Jersey Client, otherwise one can use pure servlet API or various HTTP clients) to do this: 1) WebResource webResource = resource(); final File fileToUpload = new File("D:/temp.zip"); final FormDataMultiPart multiPart = new FormDataMultiPart(); if (fileToUpload != null) { multiPart.bodyPart(new FileDataBodyPart("file", fileToUpload, MediaType.valueOf("application/zip"))); } final ClientResponse clientResp = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post( ClientResponse.class, multiPart); System.out.println("Response: " + clientResp.getClientResponseStatus()); 2) File fileName = new File("D:/temp.zip"); InputStream fileInStream = new FileInputStream(fileName); String sContentDisposition = "attachment; filename=\"" + fileName.getName() + "\""; ClientResponse response = resource().type(MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", sContentDisposition).post(ClientResponse.class, fileInStream); System.out.println("Response: " + response.getClientResponseStatus()); For sake of completeness here is the server part: @POST @Path("/import") @Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_OCTET_STREAM}) public void uploadFile(File theFile) throws PlatformManagerException, IOException { ... } So I am wondering what is the difference between those two clients? Which one to use and why? Downside (for me) of using 1) approach is that it adds dependency on jersey-multipart.jar (which additionally adds dependency on mimepull.jar) so why would I want those two jars in my classpath if pure Jersey Client approach 2) works just as fine. And maybe one general question is whether there is a better way to implement ZIP file upload, both client and server side... A: Approach 1 allows you to use multipart features, for example, uploading multiple files at the same time, or adding extra form to the POST. In which case you can change the server side signature to: @POST @Path("upload") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadMultipart(FormDataMultiPart multiPart) throws IOException { } I also found that I had to register the MultiPartFeature in my test client... public FileUploadUnitTest extends JerseyTest { @Before public void before() { // to support file upload as a test client client().register(MultiPartFeature.class); } } And server public class Application extends ResourceConfig { public Application() { register(MultiPartFeature.class); } } Thanks for your question, it helped me write my jersey file unit test!
{ "language": "en", "url": "https://stackoverflow.com/questions/17702425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can you have WPF references in an XNA project for xbox 360 I'm writing a XNA project in both Windows and Xbox 360 and the Windows side of it has a console I bring up written as a WPF application. What I was wondering is if I leave this in my library code with the references to WPF, will the dll still work on the 360? A: No. You're limited to using the .NET Compact Framework on the XBOX 360. This will not include WPF. In fact, you're limited to the XBOX 360's implementation of the Compact Framework, which is built off the .NET 2.0 Compact Framework. This means that any .NET 3.0/3.5 specific classes will not work. MSDN lists the entire collection of the supported namespaces, types, and members for the XBOX 360.
{ "language": "en", "url": "https://stackoverflow.com/questions/1400437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any problem with using HTML5's "data-*" attributes for older browsers? I want to associate some custom data with some HTML nodes. I was going to use the new HTML5 style 'data-*' attributes. e.g.: <tr class="foo" data-typeid="7">…, and then I was going to select this HTML node and show/hide it etc. by reading the value with $(node).attr("data-typeid"). However this web page needs to work with older browsers aswell. I'm not using the data-* attribute as a special attribute, but I'd like to know if older browsers will ignore, wipe, or make inaccessible this attribute since it's not valid HTML4. A: There isn't really, they're not 100% correct/valid usage in HTML4 of course....but they don't cause problems either, so they're still a great way to solve the "I need an attribute for this" problem. If it helps, I've used these while supporting IE6 and have had zero issues thus far, and I can't recall a single SO question reporting any either. A: Internet Explorer and Microsoft has added several custom attributes that are not valid HTML4. Browsers don't check the element attributes against a specification, you can name an attribute roryscoolinfo="hello" if you like (though you shouldn't). The Dojo Toolkit adds its custom dojo* attributes. It's fine to use data- today, with a HTML5 doctype.
{ "language": "en", "url": "https://stackoverflow.com/questions/3957867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: How to visualize CGAL resutls with VTK library I am new in this forum. I have a problem in my project in c++. I used vtk and Itk and Qt, but the mesh was not perfect so I tried to include CGAL with cmake. I can do everything using CGAL, but I can't visualize the object created with CGAL. I have tried to export the results (coordinates, vertices, triangles...) to a generic file like xml or txt to be able to read it from vtk and render it. Please can you help me to find a way to visualize the CGAL operations? Thank you A: There is a mesh to vtk converter which I used a while ago.
{ "language": "en", "url": "https://stackoverflow.com/questions/24485540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: mysql delete and then insert. Does not insert into delete line for AI table! Why? I am not sure I am correct in this. I have insert 5 rows with values with id as primary key and autoincrement. Then I delete row number 2-4. when I insert on a new line with none id, the new id becomes "6". Is this normal? How is it possible if you want the mysql to insert in the deleted row? what are the settings? A: Yes, this is normal. If you want to insert with a specific ID number you have to specify that number on your insert statement. The idea of auto increment is for the value to continually increase. A: This is normal, though for some database engines you might receive 2, but usually it will be 6. In MSSQL it is possible to specify a value for an autoinc field with particular setting. Not sure what it is in mysql. A: That's the expected behavior. Autoincrement primary keys are designed to be unique and continually increasing - so they are not assigned again. If you TRUNCATE a table the autoincrement value is being reset while it stays as it is if you delete all rows with an DELETE query - that's a subtle but sometimes important difference. As webdestroya suggested, the only possibility to reuse old and deleted autoincrement values is to set them specifically on the INSERT statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/3326170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Zapier Javascript: Unexpected token ] - working in IDE, Repl.it, & Node v6.3.1 The Solution: Thanks to @Kunal Mukherjee for the help. const pattern = /\](,)\s{2,}?/gm let res = inputData.rows.replace(pattern, (match, group1, offset, string) => "]") .split(/\s{2,}/gm) .map(x => JSON.parse(x)); res = res[0]; //reassign to scrape an array layer let resultString = ''; for (let i = 0; i < res[0].length; i += 1) { let cv = res[0][i]; if (cv.length === 0) resultString += ` ${res[1][i]}: ${inputData.rows[2][i]}\n` else resultString += `${cv}\n ${res[1][i]}: ${res[2][i]}\n`; } output = {KPI: resultString}; Original Post: The problem In a Zapier Zap, I'm extracting data from Google Sheets and using JS to prettify it to later send in an email. I'm bumping into an error with the following message: SyntaxError: Unexpected token ] stringOfArraysToArrayOfArrays (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:22:52) theFunction (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:29:18) eval (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:51:20) Domain.<anonymous> (/var/task/index.js:53:5) Domain.run (domain.js:242:14) module.exports.handler (/var/task/index.js:51:5) What I've tried I've successfully run this code from the most current version of Node back to Node v6.3.1 in different environments - local IDE, Repl.It IDE, and an online IDE set to Node v6.3.1. They all clear. I've also tried clearing the code of all ES6+ syntax (sans the example data) Example of data let inputData = { rows: `["Prioritized Tasks", "", "", "", "Operational Tasks", "", "", "", "Eight Dimensions", "", "", "", "", "", "", "", "Burn-Out", "", "", "", "", "", "", "", "", "", "Violations"], ["Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Emotional", "Environmental", "Financial", "Intellectual", "Occupational", "Physical", "Social", "Spiritual", "Feeling Stressed", "Feeling Depleted", "Having Trouble Concentrating", "Feeling Forgetful", "Wanting to avoid social situations", "Feeling pessimistic", "Feeling cynical", "Feeling apathetic or disinterested", "Not feeling engaged with my work", "My overall energy level", "Temperance", "Silence", "Order", "Resolution", "Frugality", "Industry", "Sincerity", "Justice", "Moderation", "Cleanliness", "Tranquility", "Chastity", "Humility"], ["70.33", "4", "6.67", "380", "3.67", "3.67", "66.67", "100", "8", "5.33", "5.67", "4.67", "4", "5", "4.67", "6.67", "1.33", "4", "5", "4.67", "3.33", "3.33", "1.33", "5", "6", "5.67", "0.3333333333", "0.3333333333", "0.3333333333", "0", "1", "0", "0", "0", "0", "0.3333333333", "0.3333333333", "0.3333333333", "0.3333333333"]` } Code producing the error function stringOfArraysToArrayOfArrays(string) { let arrayPointers = [0, 1]; let arrOfArr = []; for (let i = 0; i < string.length; i += 1) { let cv = string[i]; if (cv === "[") arrayPointers[0] = i; else if (cv === "]") { arrayPointers[1] = i + 1; arrOfArr.push(string.slice(arrayPointers[0], arrayPointers[1])); arrOfArr[arrOfArr.length - 1] = eval(arrOfArr[arrOfArr.length - 1]); } } return arrOfArr; } inputData.rows = stringOfArraysToArrayOfArrays(inputData.rows); let resultString = ''; for (let i = 0; i < inputData.rows[0].length; i += 1) { let cv = inputData.rows[0][i]; if (cv.length === 0) resultString += ' ' + inputData.rows[1][i] + ': ' + inputData.rows[2][i] + '\n'; else resultString += cv + '\n ' + inputData.rows[1][i] + ': ' + inputData.rows[2][i] + '\n'; } output = {KPI: resultString}; Expected results I'm expecting for the code to run, first off, then I'm expecting output.KPI to be a prettified string. Thanks for the time & help :) A: This approach may be a little functional. You need to first replace the ], in every row to an empty string I have used this Regex to split it. After that, I split the strings by whitespaces which are more than 2 characters. Then finally I used .map to project over the splitted items to parse it back and make an array of array. const inputData = { rows: `["Prioritized Tasks", "", "", "", "Operational Tasks", "", "", "", "Eight Dimensions", "", "", "", "", "", "", "", "Burn-Out", "", "", "", "", "", "", "", "", "", "Violations"], ["Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Emotional", "Environmental", "Financial", "Intellectual", "Occupational", "Physical", "Social", "Spiritual", "Feeling Stressed", "Feeling Depleted", "Having Trouble Concentrating", "Feeling Forgetful", "Wanting to avoid social situations", "Feeling pessimistic", "Feeling cynical", "Feeling apathetic or disinterested", "Not feeling engaged with my work", "My overall energy level", "Temperance", "Silence", "Order", "Resolution", "Frugality", "Industry", "Sincerity", "Justice", "Moderation", "Cleanliness", "Tranquility", "Chastity", "Humility"], ["70.33", "4", "6.67", "380", "3.67", "3.67", "66.67", "100", "8", "5.33", "5.67", "4.67", "4", "5", "4.67", "6.67", "1.33", "4", "5", "4.67", "3.33", "3.33", "1.33", "5", "6", "5.67", "0.3333333333", "0.3333333333", "0.3333333333", "0", "1", "0", "0", "0", "0", "0.3333333333", "0.3333333333", "0.3333333333", "0.3333333333"]` }; const pattern = /\](,)\s{2,}?/gm const res = inputData.rows.replace(pattern, (match, group1, offset, string) => "]") .split(/\s{2,}/gm) .map(x => JSON.parse(x)); const output = { KPI: res }; console.log(output);
{ "language": "en", "url": "https://stackoverflow.com/questions/56081202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML nested numbered list with starting index In my application I have a page which lists some data grouped by categories. Each item on the list can have subitems. So I'd it to look like this: * *List item 1.1 List item 1.2 List item *List item 2.1 List item 2.2 List item I can achieve this easily using this three lines of css code: OL { counter-reset: item } LI { display: block } LI:before { content: counters(item, ".") " "; counter-increment: item } However on this page I have tabs for each category, which contains such nested list of items and I want to make index of first item of next tab to be x+1-th item, where x is number of last item from previous tab ( category ). #tab 1 1. List item 1.1 List item 1.2 List item 2. List item 2.1 List item 2.2 List item #tab 2 3. List item 3.1 List item 3.2 List item 4. List item 4.1 List item 4.2 List item So I need functionality to provide starting index to <ol> tag. I found out that there is attribute start="x", however it doesn't work with these 3 lines of css code for nested lists. Any idea how to do something like this? A: From http://www.w3.org/TR/css3-lists/#html4: /* The start attribute on ol elements */ ol[start] { counter-reset: list-item attr(start, integer, 1); counter-increment: list-item -1; } Adding this to the CSS allowed the start attribute to be recognized in my tests. EDIT: Instead of using the start attribute, you can use CSS classes for each new starting point. The downside is that this will require more maintenance should you need to change anything. CSS: ol.start4 { counter-reset: item 4; counter-increment: item -1; } ol.start6 { counter-reset: item 6; counter-increment: item -1; } HTML: <div> <ol> <li>Item 1</li> <li>Item 2 <ol> <li>Item 1</li> <li>Item 2</li> </ol></li> <li>Item 3 <ol> <li>Item 1</li> <li>Item 2</li> </ol></li> </ol> </div> <div> <ol class="start4"> <li>Item 4 <ol> <li>Item 1</li> <li>Item 2</li> </ol></li> <li>Item 5</li> </ol> </div> <div> <ol class="start6"> <li>Item 6</li> <li>Item 7 <ol> <li>Item 1</li> <li>Item 2</li> </ol></li> </ol> </div> A: Just remove the css, and correctly close and reopen <ol> tags. If you need to split the list in two separate tabs, you have to close the first <ol> inside the first tab. Then, reopen the new list with the start parameter inside the second tab: <ol start="3">. Working fiddle - (I set start="5" to show it's working; for your purposes, just set it to 3 or what you need) UPDATE: Keep the CSS, and wrap all the tabs in the main <ol> and </ol>, so the counter doesn't reset. http://jsfiddle.net/qGCUk/227/
{ "language": "en", "url": "https://stackoverflow.com/questions/17948337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get object dictionary representation in Python I have objects message of type azure.servicebus.common.message.Message. I can print it and get representation that looks like dictinorary. print(message) {b'Type': b'TEST', b'Subtype': b'subtype'} print(type(message)) <class 'azure.servicebus.common.message.Message'> print(dict(message)) TypeError: 'Message' object is not iterable I would like to add dictionary representation of this object to the list, not the object like below batch.append(message) How to convert representation of the object to dictionary ?
{ "language": "en", "url": "https://stackoverflow.com/questions/58203348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.net IdentiyServer 3 AuthorizationCodeReceived not firing when a user authenticates with Identity Server 3, AuthorizationCodeReceived never fires. RedirectToIdentityProvider does get fired but thats it. I am trying to call a function that will get the users email or windows ID, and then add a custom claim. But without the AuthorizationCodeReceived method being called, I am not sure how to do that. Anyone have experience with this? Not sure if it matters, but my code is ASP.net windows form (not MVC) Here is my code: Public Sub ConfigureAuth(app As IAppBuilder) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = New Dictionary(Of String, String) app.UseCookieAuthentication(New CookieAuthenticationOptions() With { .AuthenticationType = CookieAuthenticationDefaults.AuthenticationType }) Dim OpenIdAuthOption = New OpenIdConnectAuthenticationOptions() With { .Authority = "https://myidentityserver.azurewebsites.net/core/", .ClientId = "adfafasfasdfa", .RedirectUri = "https://localhost:44321/default.aspx/", .ResponseType = ("access_token"), .RequireHttpsMetadata = False, .SignInAsAuthenticationType = "Cookies", .Notifications = New OpenIdConnectAuthenticationNotifications() With { .AuthorizationCodeReceived = Function(ctx) Dim claimPrincipal As ClaimsPrincipal = ctx.AuthenticationTicket.Identity.Claims TransformClaims(claimPrincipal) Return Task.FromResult(0) End Function, .RedirectToIdentityProvider = Function(context) RedirectLogin(context) Return Task.FromResult(0) End Function } } app.UseOpenIdConnectAuthentication(OpenIdAuthOption) End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/54466505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is the Binding Format event called twice? I am playing around with data binding and noticed that the Binding Format is called twice upon loading the form in the code below. I thought it would only happen once when the test class TextBoxText property is fist bound to textbox1. Is this normal? If not, then what can I do to prevent it? Note, when I press button1 and it changes the TextBoxText property of the test class, the format event fires once as expected. public partial class Form1 : Form { Test _test = new Test(); public Form1() { InitializeComponent(); Binding binding = new Binding("Text", _test, "TextBoxText"); binding.Format += new ConvertEventHandler(Binding_Format); this.textBox1.DataBindings.Add(binding); } private void Binding_Format(object sender, ConvertEventArgs e) { Debug.WriteLine("Format"); } private void button1_Click(object sender, EventArgs e) { _test.TextBoxText = "test1"; } } class Test : INotifyPropertyChanged { private string _text; public string TextBoxText { get { return _text; } set { _text = value; OnPropertyChanged(new PropertyChangedEventArgs("TextBoxText")); } } private void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged(this, e); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion A: The simple answer: "Because that is the way Microsoft implemented it". The goal is to just respond to the event... whenever it happens... however often it occurs. We can't make any assumptions. There are cases where you might get called six times on the same event. We just have to roll with it and continue to be awesome.
{ "language": "en", "url": "https://stackoverflow.com/questions/3239754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: delphi7 converted to delphi tokyo app taskbar icon does not like to move to second screen app my delphi7 apps always show in the primary screen monitor taskbar , Now in delphi 10.2 If I move the app to the second screen the taskbar icon move to that seconds screen . So now my issue is with the old delphi7 apps which I open and compile with delphi 10.2, they still have the old behavior . So how can I solve that?? A: In Delphi 7, all TForm windows are owned by the hidden TApplication window at runtime, which is the window that actually manages the app's Taskbar button. That window remains on the primary monitor when you move your Forms to other monitors. That is why you don't see the app's Taskbar button move to other monitors. In Delphi 2007 and later, TForm windows are no longer owned by the hidden TApplication window by default on Vista+. This behavior is controlled by the TApplication.MainFormOnTaskBar property, which did not exist yet in Delphi 7. Being owned by the hidden TApplication window causes all kinds of problems in Vista+ for the Taskbar, the Task switcher, Aero, etc, so ShowMainFormOnTaskBar should always be set to true. When you upgrade your Delphi 7 project to Delphi 10.2, be sure to set Application.MainFormOnTaskBar := true; in the app's main startup code so the app interacts with Vista+ properly. MainFormOnTaskBar is false by default when migrating a pre-D2007 project.
{ "language": "en", "url": "https://stackoverflow.com/questions/54988814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jQuery UI - make div not resizable I have a div that is made resizable using jQuery UI. How can I dynamically make it not resizable anymore? I tried calling resizable({ disabled: true }) but the handle still showed. A: Use this code: .resizable( "destroy" ) A: Try .resizable("option", "disabled", true); http://jqueryui.com/demos/resizable/#option-disabled Your solution is not working because, as per the documentation you need use the setter that I mentioned, if you want to disable it after initialization (you code will only work if its an initialization call) A: Oops... I was disabling "resizable" before I enabled it...
{ "language": "en", "url": "https://stackoverflow.com/questions/4670801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Consuming an XML API in CakePHP I have a web application that involves calling a number of different XML/API webservices. The application has already been implemented in old school procedural code (by my predecessor) and I have managed to convince the IT director that it needs to be coded into a more robust framework. I've settled on CakePHP because it's the framework I am most familiar with. I have Googled extensively for advice on how to consume an XML/API. One blog post did it in the controller, but I feel it belongs more in the model. Perhaps I could create a behaviour that handles the transfers and then code methods in the Model that will strip out the information I need from the returned XML? Does anybody have some advice on this or a pointer? A: I imagine you are using it to get database like data or config data, this is normally done in the model, though there is not restriction in where you do it. You could do the extracting and preparing of the data in the model and the logic in the controller. Something like loading the config parameters and putting them in variables and then using this variables in the controller. Also you may use cakephp XML library to do all this. Since is a library you MAY do it either in controller or model. Hope this helps you :)
{ "language": "en", "url": "https://stackoverflow.com/questions/9112328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Convert Apple Emoji (String) to UIImage I need all Apple Emojis. I can get all the emojis and put them into a String by copying them from the site getemoji but in my app i need the emojis in the right order as images. Is there a nice way to convert the emojis I copy into a String to a UIImage? Or a better solution to get all the Apple emojis in the right order? A: Updated @Luca Angeletti answer for Swift 3.0.1 extension String { func image() -> UIImage? { let size = CGSize(width: 30, height: 35) UIGraphicsBeginImageContextWithOptions(size, false, 0); UIColor.white.set() let rect = CGRect(origin: CGPoint(), size: size) UIRectFill(CGRect(origin: CGPoint(), size: size)) (self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30)]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } A: Swift 4.2 I really liked @Luca Angeletti solution. I hade the same question as @jonauz about transparent background. So with this small modification you get the same thing but with clear background color. I didn't have the rep to answer in a comment. import UIKit extension String { func emojiToImage() -> UIImage? { let size = CGSize(width: 30, height: 35) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIColor.clear.set() let rect = CGRect(origin: CGPoint(), size: size) UIRectFill(CGRect(origin: CGPoint(), size: size)) (self as NSString).draw(in: rect, withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 30)]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } A: Swift 5: ( with optional fontSize, imageSize and bgColor) use it like this: let image = "".image() let imageLarge = "".image(fontSize:100) let imageBlack = "".image(fontSize:100, bgColor:.black) let imageLong = "".image(fontSize:100, imageSize:CGSize(width:500,height:100)) import UIKit extension String { func image(fontSize:CGFloat = 40, bgColor:UIColor = UIColor.clear, imageSize:CGSize? = nil) -> UIImage? { let font = UIFont.systemFont(ofSize: fontSize) let attributes = [NSAttributedString.Key.font: font] let imageSize = imageSize ?? self.size(withAttributes: attributes) UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) bgColor.set() let rect = CGRect(origin: .zero, size: imageSize) UIRectFill(rect) self.draw(in: rect, withAttributes: [.font: font]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } A: Updated version of @Luca Angeletti's answer using UIGraphicsImageRenderer: extension String { func image() -> UIImage? { let size = CGSize(width: 100, height: 100) let rect = CGRect(origin: CGPoint(), size: size) return UIGraphicsImageRenderer(size: size).image { (context) in (self as NSString).draw(in: rect, withAttributes: [.font : UIFont.systemFont(ofSize: 100)]) } } } A: Here's an updated answer with the following changes: * *Centered: Used draw(at:withAttributes:) instead of draw(in:withAttributes:) for centering the text within the resulting UIImage *Correct Size: Used size(withAttributes:) for having a resulting UIImage of size that correlates to the actual size of the font. *Comments: Added comments for better understanding Swift 5 import UIKit extension String { func textToImage() -> UIImage? { let nsString = (self as NSString) let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here let stringAttributes = [NSAttributedString.Key.font: font] let imageSize = nsString.size(withAttributes: stringAttributes) UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) // begin image context UIColor.clear.set() // clear background UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context UIGraphicsEndImageContext() // end image context return image ?? UIImage() } } Swift 3.2 import UIKit extension String { func textToImage() -> UIImage? { let nsString = (self as NSString) let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here let stringAttributes = [NSFontAttributeName: font] let imageSize = nsString.size(attributes: stringAttributes) UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) // begin image context UIColor.clear.set() // clear background UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context UIGraphicsEndImageContext() // end image context return image ?? UIImage() } } A: Same thing for Swift 4: extension String { func emojiToImage() -> UIImage? { let size = CGSize(width: 30, height: 35) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIColor.white.set() let rect = CGRect(origin: CGPoint(), size: size) UIRectFill(rect) (self as NSString).draw(in: rect, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 30)]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } A: Updated for Swift 4.1 Add this extension to your project import UIKit extension String { func image() -> UIImage? { let size = CGSize(width: 40, height: 40) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIColor.white.set() let rect = CGRect(origin: .zero, size: size) UIRectFill(CGRect(origin: .zero, size: size)) (self as AnyObject).draw(in: rect, withAttributes: [.font: UIFont.systemFont(ofSize: 40)]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } The code above draws the current String to an Image Context with a white background color and finally transform it into a UIImage. Now you can write Example Given a list of ranges indicating the unicode values of the emoji symbols let ranges = [0x1F601...0x1F64F, 0x2702...0x27B0] you can transform it into a list of images let images = ranges .flatMap { $0 } .compactMap { Unicode.Scalar($0) } .map(Character.init) .compactMap { String($0).image() } Result: I cannot guarantee the list of ranges is complete, you'll need to search for it by yourself A: This variation is based on @Luca's accepted answer, but allows you to optionally customize the point size of the font, should result in a centered image, and doesn't make the background color white. extension String { func image(pointSize: CGFloat = UIFont.systemFontSize) -> UIImage? { let nsString = self as NSString let font = UIFont.systemFont(ofSize: pointSize) let size = nsString.size(withAttributes: [.font: font]) UIGraphicsBeginImageContextWithOptions(size, false, 0) let rect = CGRect(origin: .zero, size: size) nsString.draw(in: rect, withAttributes: [.font: font]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
{ "language": "en", "url": "https://stackoverflow.com/questions/38809425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: How do you choose where to put information based on an index into a pandas DataFrame? In MATLAB, the loop I create looks like: header_names = {'InvoiceNo','Customer',...} for i = 1:length(x) entry(index+i,:) = [InvoiceNo, Customer,...] end % Create a table from the data. fin_table = cell2table(entry,'VariableNames',header_names); % Write to the finish file. writetable(fin_table,finish); With the table values and headers, I will end up getting something that looks like: InvoiceNo Customer 1000 Jimmy 1001 Bob 1002 Max 1003 April 1004 Tom ... ... ... ... ... ... ... ... I would like to know how to accomplish this in Python. My main question is how do I create the entry? How do I put a table in a for loop and ask it to print information on the next row for each iteration? In Python, I currently have the following: for i in range(len(item)): entry = pd.DataFrame( [InvoiceNo, Customer, invoice, due, terms, Location, memo, item[i], item[i], quan[i], rate[i], taxable, tax_rate, invoice, email, Class], columns=['InvoiceNo', 'Customer', 'InvoiceDate', 'DueDate', 'Terms', 'Location', 'Memo', 'Item', 'ItemDescription', 'ItemQuantity', 'ItemRate', 'ItemAmount', 'Taxable', 'TaxRate', 'ServiceDate', 'Email', 'Class']) # Increment the index for entry values to be correct. index += len(item) Any help would be awesome! A: Although I do not get your question completely, I will try to give you some tools that might be useful: To get input value you can use (and put this inside of a 'for' loop depending on the number of rows you want to create) new_InvoiceNo= input("Enter InvoiceNo:\n") new_Customer= input("Enter Customer:\n") new_invoice = input("Enter invoice:\n") ... then you can either append these values as list into the main DF : to_append = [new_InvoiceNo, new_Customer, new_invoice, ...] new_values = pd.Series(to_append, index = df.columns) df = df.append(new_values , ignore_index=True) or , you can use '.loc' method: to_append = [new_InvoiceNo, new_Customer, new_invoice, ...] df_length = len(df) df.loc[df_length] = to_append Try to implement this in your code and report it back here.
{ "language": "en", "url": "https://stackoverflow.com/questions/69982015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MultiThreading with searchbox I have a listbox with list of persons (first name ,last name , addresses...) and a searchbox (TextBox with TextChaned event the thing is i'm running a search throw database and it take a long time and the UI freeze for seconds ...so,how can I make it responsive ? A: Assuming that you are working with DataTables, here is what you can do: private async void btnSearch_Click(object sender, EventArgs e) // async is important { DataTable dt = await Task.Run(() => // await is important (avoids the UI freeze) { return GetData(); // Fetch your data from DB }); // Fill your listbox with the data in dt }
{ "language": "en", "url": "https://stackoverflow.com/questions/55787348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to enable and disable button accordingly if i select the dropdown options in Angular js If I click on the dropdown which is marked inside the blue border, I want the buttons below to be enabled/disabled according to the condition. If I select first dropdown value. I want the 3rd and 4th button to disabled and 1st and 2nd should be active. I was looking some angular js code (ng-disabled or ng-class) A: The selector must be binded to some ng-model, which keep track of the current value. Supposing you have something like this: <select ng-model="FooBar"> Some options... (with their respectives value) </select> you can enable or desable multiple buttons using this var "FooBar": <input ng-disabled="FooBar !== desiredEnableValue">
{ "language": "en", "url": "https://stackoverflow.com/questions/43092584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it worth mitigating against the effects of garbage collection? I have an application where the memory profile looks something like this: (source: kupio.com) The slow upwards crawl of memory usage is caused by the allocation of lots and lots of small, simple, transient objects. In low-memory situations (This is a mobile app) the GC overhead is noticeable when compared to less restrictive memory amounts. Since we know, due to the nature of the app, that these spikes will just keep on coming, I was considering some sort of pool of multitudinous transient objects (Awesome name). These objects would live for the lifetime of the app and be re-used wherever possible (Where the lifetime of the object is short and highly predictable). Hopefully this would mitigate against the effects of GC by reducing the number of objects collected and improve performance. Obviously this would also have its own performance limits since "allocation" would be more expensive and there would be an overhead in maintaining the cache itself. Since this would be a rather large and intrusive change into a large amount of code, I was wondering if anyone had tried something similar and if it was a benefit, or if there were any other known ways of mitigating against GC in this sort of situation. Ideas for efficient ways to manage a cache of re-usable objects are also welcome. A: This is similar to the flyweight pattern detailed in the GoF patterns book (see edit below). Object pools have gone out of favour in a "normal" virtual machine due to the advances made in reducing the object creation, synchronization and GC overhead. However, these have certainly been around for a long time and it's certainly fine to try them to see if they help! Certainly Object Pools are still in use for objects which have a very expensive creation overhead when compared with the pooling overheads mentioned above (database connections being one obvious example). Only a test will tell you whether the pooling approach works for you on your target platforms! EDIT - I took the OP "re-used wherever possible" to mean that the objects were immutable. Of course this might not be the case and the flyweight pattern is really about immutable objects being shared (Enums being one example of a flyweight). A mutable (read: unshareable) object is not a candidate for the flyweight pattern but is (of course) for an object pool. A: Normally, I'd say this was a job for tuning the GC parameters of the VM, the reduce the spiky-ness, but for mobile apps that isn't really an option. So if the JVms you are using cannot have their GC behavioure modified, then old-fashioned object pooling may be the best solution. The Apache Commons Pool library is good for that, although if this is a mobile app, then you may not want the library dependency overhead. A: Actually, that graph looks pretty healthy to me. The GC is reclaiming lots of objects and the memory is then returning to the same base level. Empirically, this means that the GC is working efficiently. The problem with object pooling is that it makes your app slower, more complicated and potentially more buggy. What is more, it can actually make each GC run take longer. (All of the "idle" objects in the pool are non-garbage and need to be marked, etc by the GC.) A: Does J2ME have a generational garbage collector? If so it does many small, fast, collections and thus the pauses are reduced. You could try reducing the eden memory space (the small memory space) to increase the frequency and reduce the latency for collections and thus reduce the pauses. Although, come to think of it, my guess is that you can't adjust gc behaviour because everything probably runs in the same VM (just a guess here). A: You could check out this link describing enhancements to the Concurrent Mark Sweep collector, although I'm not sure it's available for J2ME. In particular note: "The concurrent mark sweep collector, also known as the concurrent collector or CMS, is targeted at applications that are sensitive to garbage collection pauses." ... "In JDK 6, the CMS collector can optionally perform these collections concurrently, to avoid a lengthy pause in response to a System.gc() or Runtime.getRuntime().gc() call. To enable this feature, add the option" -XX:+ExplicitGCInvokesConcurrent A: Check out this link. In particular: Just to list a few of the problems object pools create: first, an unused object takes up memory space for no reason; the GC must process the unused objects as well, detaining it on useless objects for no reason; and in order to fetch an object from the object pool a synchronization is usually required which is much slower than the asynchronous allocation available natively. A: You're talking about a pool of reusable object instances. class MyObjectPool { List<MyObject> free= new LinkedList<MyObject>(); List<MyObject> inuse= new LinkedList<MyObject>(); public MyObjectPool(int poolsize) { for( int i= 0; i != poolsize; ++i ) { MyObject obj= new MyObject(); free.add( obj ); } } pubic makeNewObject( ) { if( free.size() == 0 ) { MyObject obj= new MyObject(); free.add( obj ); } MyObject next= free.remove(0); inuse.add( next ); return next; } public freeObject( MyObject obj ) { inuse.remove( obj ); free.add( obj ); } } return in A: Given that this answer suggests that there is not much scope for tweaking garbage collection itself in J2ME then if GC is an issue the only other option is to look at how you can change your application to improve performance/memory usage. Maybe some of the suggestions in the answer referenced would apply to your application. As oxbow_lakes says, what you suggest is a standard design pattern. However, as with any optimisation the only way to really know how much it will improve your particular application is by implementing and profiling.
{ "language": "en", "url": "https://stackoverflow.com/questions/1232437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: HTML: Accept-Charset attribute and Accept attribute I'm using angularJS, and when i try to set there Accept-Charset attribute i get: Refused to set unsafe header "Accept-Charset", but when i set manually something like: headers: { 'Content-Type': 'text/csv', 'Accept': 'application/json, text/plain; charset=WIN-1251' } all is ok so... question) Is there any difference between this two attributes? or server will recognize my accept with charset, and i do not need Accept-Charset anymore?
{ "language": "en", "url": "https://stackoverflow.com/questions/32313595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Menu flow is wrong in android mobile phones I have one word-press site ,the menu flow of the site is working fine in desktop and i-phone , but flow is wrong in all android phones . the problem is : i have a main menu "courses" and sub menu under courses is "school programs". when ever i click "courses" then the page "school programs" will load aromatically instead of "courses" page . and i am clear that this problem is with android mobiles only . code is : <li id="menu-item-36" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-36"> <a href="http://www.kravmagaoz.com.au/courses/"><span>Courses</span></a> <div class="sub-menu-wrapper"> <ul class="sub-menu"> <li id="menu-item-63" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-63"><a href="http://www.kravmagaoz.com.au/school-programs/"><span>School Programs</span></a></li> <li id="menu-item-66" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-66"><a href="http://www.kravmagaoz.com.au/womens-self-defence/"><span>Women’s self defence</span></a></li> <li id="menu-item-67" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-67"><a href="http://www.kravmagaoz.com.au/security-programs/"><span>Security Programs</span></a></li> <li id="menu-item-68" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-68"><a href="http://www.kravmagaoz.com.au/business-workshops/"><span>Business Workshops</span></a></li> <li id="menu-item-4780" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-4780"><a href="http://www.kravmagaoz.com.au/instructor-courses/"><span>Krav Maga Instructor Course</span></a></li> </ul> </div> </li> site URL : http://www.kravmagaoz.com.au/ any help . A: Actually there is some overlapping of your div of <li> tag so you need to check the css and add updated code in @media query. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/42523422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javacard form factors I'm totally new in the Smartcard world, and would really appreciate some clarifications regarding Javacard form factors and interfaces, as I've found it very hard to research the different options. Ideally I would like to find a contactless Javacard 2 (or 3) chip + antenna that is not encased in plastic, because I want to put it inside another product. I want it to be as small as possible, and therefore just contactless, not dual interface. However all the Javacards I've found that's sold by manufacturers, seem to only have the "business card" form factor. Does anyone know if this is available at all or if not, or at least theoretically possible to produce? Does the Javacard version make any difference in feasibility of this form factor (My applet only requires Javacard 2+)? If anyone knows what a reasonable bulk price per chip with such a form factor would be, that would also be very interesting to hear. Thank you! A: The reason that you find these chips only in smart cards is that that is the best method of developing on them without hassle. There are also form factors for use in e.g. key fobs, which is probably what you're after. That means smaller antenna space and less chance of a good response. These chips and antenna's are tricky to get right so that all distances and orientations work well. Paper smart cards are commonly not smart cards but throw away memory cards like MiFare or MiFare ultra-light. Usually smart cards come in credit card form, like -uh- those in credit cards. And then they are in plastic (PVC) or polycarbonate for the higher end cards. Demo cards are usually plastic though. Manufacturers aren't shy of not putting any chips or antenna's in there at all when it comes to demo cards (they might be showing off their printing capabilities instead). The classic Java cards can be in any form factor. However, the more memory the larger the die may be. That can be an issue with some packaging, the small container that the IC is put in and to which the antenna's are connected. Although Java Card 3 is somewhat of a jump in functionality, most cards capable of version 2 would also be OK to run version 3 of Java Card. The failed web-based "connected" Java Card requires a lot of memory and if you can find it, it will probably be limited to specific form factors. Java Card 3.1 seems to be another jump in functionality for the common "classic" platform and I would expect for high end smart cards to lead the way. Generally we don't talk prices here. If you are interested in bulk pricing for specific form factors then you need to contact the resellers, not us. But I would first try and read into it. There are some great general purpose books out there on smart cards. That way you'd at least know a bit what you're talking about when contacting such vendor, and in that case you're more likely to be taken seriously.
{ "language": "en", "url": "https://stackoverflow.com/questions/57874975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to nest transactions in EF Core 6? I am already using transactions inside my repository functions in some cases because I sometimes need to insert data into two tables at once and I want the whole operation to fail if one of the inserts fails. Now I ran into a situation where I had to wrap calls to multiple repositories / functions in another transaction, but when one of those functions already uses a transaction internally I will get the error The connection is already in a transaction and cannot participate in another transaction. I do not want to remove the transaction from the repository function because this would mean that I have to know for which repository functions a transaction is required which I would then have to implement in the service layer. On the other hand, it seems like I cannot use repository functions in a transaction when they already use a transaction internally. Here is an example for where I am facing this problem: // Reverse engineered classes public partial class TblProject { public TblProject() { TblProjectStepSequences = new HashSet<TblProjectStepSequence>(); } public int ProjectId { get; set; } public virtual ICollection<TblProjectStepSequence> TblProjectStepSequences { get; set; } } public partial class TblProjectTranslation { public int ProjectId { get; set; } public string Language { get; set; } public string ProjectName { get; set; } public virtual TblProject Project { get; set; } } public partial class TblProjectStepSequence { public int SequenceId { get; set; } public int ProjectId { get; set; } public int StepId { get; set; } public int SequencePosition { get; set; } public virtual TblStep Step { get; set; } public virtual TblProject Project { get; set; } } // Creating a project in the ProjectRepository public async Task<int> CreateProjectAsync(TblProject project, ...) { using (var transaction = this.Context.Database.BeginTransaction()) { await this.Context.TblProjects.AddAsync(project); await this.Context.SaveChangesAsync(); // Insert translations... (project Id is required for this) await this.Context.SaveChangesAsync(); transaction.Commit(); return entity.ProjectId; } } // Creating the steps for a project in the StepRepository public async Task<IEnumerable<int>> CreateProjectStepsAsync(int projectId, IEnumerable<TblProjectStepSequence> steps) { await this.Context.TblProjectStepSequences.AddRangeAsync(steps); await this.Context.SaveChangesAsync(); return steps.Select(step => { return step.SequenceId; } ); } // Creating a project with its steps in the service layer public async Task<int> CreateProjectWithStepsAsync(TblProject project, IEnumerable<TblProjectStepSequence> steps) { // This is basically a wrapper around Database.BeginTransaction() and IDbContextTransaction using (Transaction transaction = await transactionService.BeginTransactionAsync()) { int projectId = await projectRepository.CreateProjectAsync(project); await stepRepository.CreateProjectStepsAsync(projectId, steps); return projectId; } } Is there a way how I can nest multiple transactions inside each other without already knowing in the inner transactions that there could be an outer transaction? I know that it might not be possible to actually nest those transactions from a technical perspective but I still need a solution which either uses the internal transaction of the repository or the outer one (if one exists) so there is no way how I could accidentally forget to use a transaction for repository functions which require one. A: You could check the CurrentTransaction property and do something like this: var transaction = Database.CurrentTransaction ?? Database.BeginTransaction() If there is already a transaction use that, otherwise start a new one... Edit: Removed the Using block, see comments. More logic is needed for Committing/Rollback the transcaction though... A: I am answering the question you asked "How to nest transactions in EF Core 6?" Please note that this is just a direct answer, but not an evaluation what is best practice and what not. There was a lot of discussion going around best practices, which is valid to question what fits best for your use case but not an answer to the question (keep in mind that Stack overflow is just a Q+A site where people want to have direct answers). Having said that, let's continue with the topic: Try to use this helper function for creating a new transaction: public CommittableTransaction CreateTransaction() => new System.Transactions.CommittableTransaction(new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }); Using the Northwind database as example database, you can use it like: public async Task<int?> CreateCategoryAsync(Categories category) { if (category?.CategoryName == null) return null; using(var trans = CreateTransaction()) { await this.Context.Categories.AddAsync(category); await this.Context.SaveChangesAsync(); trans.Commit(); return category?.CategoryID; } } And then you can call it from another function like: /// <summary>Create or use existing category with associated products</summary> /// <returns>Returns null if transaction was rolled back, else CategoryID</returns> public async Task<int?> CreateProjectWithStepsAsync(Categories category) { using var trans = CreateTransaction(); int? catId = GetCategoryId(category.CategoryName) ?? await CreateCategoryAsync(category); if (!catId.HasValue || string.IsNullOrWhiteSpace(category.CategoryName)) { trans.Rollback(); return null; } var product1 = new Products() { ProductName = "Product A1", CategoryID = catId }; await this.Context.Products.AddAsync(product1); var product2 = new Products() { ProductName = "Product A2", CategoryID = catId }; await this.Context.Products.AddAsync(product2); await this.Context.SaveChangesAsync(); trans.Commit(); return catId; } To run this with LinqPad you need an entry point (and of course, add the NUGET package EntityFramework 6.x via F4, then create an EntityFramework Core connection): // Main method required for LinqPad UserQuery Context; async Task Main() { Context = this; var category = new Categories() { CategoryName = "Category A1" // CategoryName = "" }; var catId = await CreateProjectWithStepsAsync(category); Console.WriteLine((catId == null) ? "Transaction was aborted." : "Transaction successful."); } This is just a simple example - it does not check if there are any product(s) with the same name existing, it will just create a new one. You can implement that easily, I have shown it in the function CreateProjectWithStepsAsync for the categories: int? catId = GetCategoryId(category.CategoryName) ?? await CreateCategoryAsync(category); First it queries the categories by name (via GetCategoryId(...)), and if the result is null it will create a new category (via CreateCategoryAsync(...)). Also, you need to consider the isolation level: Check out System.Transactions.IsolationLevel to see if the one used here (ReadCommitted) is the right one for you (it is the default setting). What it does is creating a transaction explicitly, and notice that here we have a transaction within a transaction. Note: * *I have used both ways of using - the old one and the new one. Pick the one you like more. A: Just don't call SaveChanges multiple times. The problem is caused by calling SaveChanges multiple times to commit changes made to the DbContext instead of calling it just once at the end. It's simply not needed. A DbContext is a multi-entity Unit-of-Work. It doesn't even keep an open connection to the database. This allows 100-1000 times better throughput for the entire application by eliminating cross-connection blocking. A DbContext tracks all modifications made to the objects it tracks and persists/commits them when SaveChanges is called using an internal transaction. To discard the changes, simply dispose the DbContext. That's why all examples show using a DbContext in a using block - that's actually the scope of the Unit-of-Work "transaction". There's no need to "save" parent objects first. EF Core will take care of this itself inside SaveChanges. Using the Blog/Posts example in the EF Core documentation tutorial : public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } public string DbPath { get; } // The following configures EF to create a Sqlite database file in the // special "local" folder for your platform. protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlServer($"Data Source=.;Initial Catalog=tests;Trusted_Connection=True; Trust Server Certificate=Yes"); } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; } = new(); } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } The following Program.cs will add a Blog with 5 posts but only call SaveChanges once at the end : using (var db = new BloggingContext()) { Blog blog = new Blog { Url = "http://blogs.msdn.com/adonet" }; IEnumerable<Post> posts = Enumerable.Range(0, 5) .Select(i => new Post { Title = $"Hello World {i}", Content = "I wrote an app using EF Core!" }); blog.Posts.AddRange(posts); db.Blogs.Add(blog); await db.SaveChangesAsync(); } The code never specifies or retrieves the IDs. Add is an in-memory operation so there's no reason to use AddAsync. Add starts tracking both the blog and the related Posts in the Inserted state. The contents of the tables after this are : select * from blogs select * from posts; ----------------------- BlogId Url 1 http://blogs.msdn.com/adonet PostId Title Content BlogId 1 Hello World 0 I wrote an app using EF Core! 1 2 Hello World 1 I wrote an app using EF Core! 1 3 Hello World 2 I wrote an app using EF Core! 1 4 Hello World 3 I wrote an app using EF Core! 1 5 Hello World 4 I wrote an app using EF Core! 1 Executing the code twice will add another blog with another 5 posts. PostId Title Content BlogId 1 Hello World 0 I wrote an app using EF Core! 1 2 Hello World 1 I wrote an app using EF Core! 1 3 Hello World 2 I wrote an app using EF Core! 1 4 Hello World 3 I wrote an app using EF Core! 1 5 Hello World 4 I wrote an app using EF Core! 1 6 Hello World 0 I wrote an app using EF Core! 2 7 Hello World 1 I wrote an app using EF Core! 2 8 Hello World 2 I wrote an app using EF Core! 2 9 Hello World 3 I wrote an app using EF Core! 2 10 Hello World 4 I wrote an app using EF Core! 2 Using SQL Server XEvents Profiler shows that these SQL calls are made: exec sp_executesql N'SET NOCOUNT ON; INSERT INTO [Blogs] ([Url]) VALUES (@p0); SELECT [BlogId] FROM [Blogs] WHERE @@ROWCOUNT = 1 AND [BlogId] = scope_identity(); ',N'@p0 nvarchar(4000)',@p0=N'http://blogs.msdn.com/adonet' exec sp_executesql N'SET NOCOUNT ON; DECLARE @inserted0 TABLE ([PostId] int, [_Position] [int]); MERGE [Posts] USING ( VALUES (@p1, @p2, @p3, 0), (@p4, @p5, @p6, 1), (@p7, @p8, @p9, 2), (@p10, @p11, @p12, 3), (@p13, @p14, @p15, 4)) AS i ([BlogId], [Content], [Title], _Position) ON 1=0 WHEN NOT MATCHED THEN INSERT ([BlogId], [Content], [Title]) VALUES (i.[BlogId], i.[Content], i.[Title]) OUTPUT INSERTED.[PostId], i._Position INTO @inserted0; SELECT [i].[PostId] FROM @inserted0 i ORDER BY [i].[_Position]; ',N'@p1 int,@p2 nvarchar(4000),@p3 nvarchar(4000),@p4 int,@p5 nvarchar(4000),@p6 nvarchar(4000),@p7 int,@p8 nvarchar(4000),@p9 nvarchar(4000),@p10 int,@p11 nvarchar(4000),@p12 nvarchar(4000),@p13 int,@p14 nvarchar(4000),@p15 nvarchar(4000)',@p1=3,@p2=N'I wrote an app using EF Core!',@p3=N'Hello World 0',@p4=3,@p5=N'I wrote an app using EF Core!',@p6=N'Hello World 1',@p7=3,@p8=N'I wrote an app using EF Core!',@p9=N'Hello World 2',@p10=3,@p11=N'I wrote an app using EF Core!',@p12=N'Hello World 3',@p13=3,@p14=N'I wrote an app using EF Core!',@p15=N'Hello World 4' The unusual SELECT and MERGE are used to ensure IDENTITY values are returned in the order the objects were inserted, so EF Core can assign them to the object properties. After calling SaveChanges all Blog and Post objects will have the correct database-generated IDs
{ "language": "en", "url": "https://stackoverflow.com/questions/70958670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to convert byte[] to float[] and back in Java? I'm reading data from .wav files through InputStream, and read() returns bytes. A sound processing library I use, only accepts float[] to process. After it it done it gives me a float[] back. Now I need to write to the Android's AudioTrack in byte format again. How do I convert these bytes to floats[], and back to byte[]? I've searched a bit, but everything seemed to be kinda a different situation to mine, and all problems seemed to be solved in different ways... so i'm kinda lost right now. If something like this conversion is already offered in some kind of library, i'd be glad to hear about that too! Thanks! A: You can use of java.nio.ByteBuffer. It has a lot of useful methods for pulling different types out of a byte array and should also handle most of your issues. byte[] data = new byte[36]; ByteBuffer buffer = ByteBuffer.wrap(data); float second = buffer.getFloat(); //This helps to float x = 0; buffer.putFloat(x); A: You just need to copy the bits. Try using BlockCopy. float[] fArray = new float[] { 1.0f, ..... }; byte[] bArray= new byte[fArray.Length*4]; Buffer.BlockCopy(fArray,0,bArray,0,bArray.Length); The *4 is since each float is 4 bytes.
{ "language": "en", "url": "https://stackoverflow.com/questions/19466217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.NET MVC3 - Redirect to a different directory We have a bunch of published URLs that reference a directory called "events" http://www.mysite.com/anniversary/events/ http://www.mysite.com/anniversary/events/[...] They now want to rename "events" to "events1" so I need to redirect all URLs that look like this: http://www.mysite.com/anniversary/events/[...] To: http://www.mysite.com/anniversary/events1 http://www.mysite.com/anniversary/events1/[...] I've done these in Apache - Not sure if I am on the right track? <rule name="events1" stopProcessing="true"> <match url="^/anniversary/events(/.+)?$" /> <action type="Redirect" url="http://www.mysite.com/aniverssary/events1{C:1}" redirectType="Found" /> </rule> What should this look like? Thanks A: Well, it turns out that IIS has a really nice rewrite rule pattern tester. I found this tutorial extremely helpful. If you use the IIS URL Rewrite GUI, you can create a test redirect and then the URL Rewrite will write the redirect into web.config. You can then look in there and check your syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/21165373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding argmax indices along a dimension and negate the corresponding values if the index is 1 Given a tensor in size DxCx2xHxW I try to find the argmax indices for the third dimension (between two values) and if the index is 0 I'll keep it or if it is 1 I'll negate the value and reduce the tensor to size DxCxHxW with the modified values and ignoring the non argmax indices. Could you suggest a way to do this correctly? Thanks in advance for any further comment... Here also my first stupid attempt that might give some insights about what am I trying to do. max_val = self.pool_function(input_reshaped, axis=self.axis + 1) //input_rehshaed in size DxCx2xHxW max_arg = T.argmax(input_reshaped, axis= self.axis+1) //find argmax indices for the third dimension return ifelse(T.lt(max_arg, 1), max_val, -max_val) //negate argmax indices > 0 and return modified matrix ignoring the nonargmax indices A: For the potential benefit of other people, this question was answered on the theano-users mailing list: https://groups.google.com/forum/#!topic/theano-users/6P5KxLph2I8 The recommended solution, by Pierre Luc Carrier, was: mask = input_reshaped.argmax(axis=3).astype("float32") * -2 + 1 return input_reshaped.max(axis=3) * mask
{ "language": "en", "url": "https://stackoverflow.com/questions/32995147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Github Action trigger on release not working on tag I've created a "publish" workflow in new repository that publish my project on new release with this trigger on: release: types: - created In my local machine I created a tag and pushed it: git tag v0.0.1 main git push origin v0.0.1 Now I see that my repo contains 1 tag and 1 release, but the workflow did not run. Why the release trigger did not fire when new release created with the tag? A: This is confusing in the GitHub Actions documentation on the "Events that Trigger Workflows." https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#release It states that Activity Types are "published," "unpublished," and "prerelease" but it doesn't tell you how to invoke these activities. You need to create a GitHub "Release" Event by either using the web portal or the gh CLI. Follow this documentation: https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository If that link changes look for the Release button in the GitHub web portal. Just creating a git tag is not enough. From the gh CLI the command is like: gh release create v1.3.2 --title "v1.3.2 (beta)" --notes "this is a beta release" --prerelease In short git tag is not the event that triggers a GitHub Release event.
{ "language": "en", "url": "https://stackoverflow.com/questions/66992201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is the map mask register used to do plane switching in VGA? I've got an understanding problem when it comes to the memory mapping of VGA. So I think I've got a wrong assumption somewhere. From what I've understood, I think that a VGA adapter has 256 KB of memory but usually only exposes 64 KB to the host at any given time. So if you like to have a resolution of 640x480 pixels with 16 colors then you would need 153 600 bytes of the memory. But since the host can only access 64 KB it needs to swap the planes/banks behind the 64 KB window to access different parts of the 256 KB of video memory. So when I set a mode I write the value 0001|b to the map mask register to select plane #0. When the OS asks my miniport driver for the bank switching code then I return some code that changes the value in the map mask register to 0010|b for example to switch to plane #1. Now my problem is, that I seem to be the only person who does this. For example, when I looked at how Microsoft sets a mode, I noticed that they write 1111|b in the map mask register and when it comes to providing the code for the bank switching they simply provide a return-instruction with the comment that this function should never be called anyway. When a miniport driver sets a mode they even overwrite the map mask register right afterwards to make sure it contains 1111|b. When I looked at ReactOS I noticed that they haven't even implemented the function that provides the bank switching code. But how is this possible?
{ "language": "en", "url": "https://stackoverflow.com/questions/73759658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is Spring Cache clusterable? I've got an application that uses Spring Cache (Ehcache), but now we need to add a 2nd node (same application). Can the cache be shared between the nodes or each with their own instance but synched? Or do I need to look at a different solution? Thanks. A: That depends on your cache implementation - not on Spring, which only provides an abstract caching API. You are using EhCache as your caching implementation, which comes with a Terracotta server for basic clustering support and is open source. See http://www.ehcache.org/documentation/3.1/clustered-cache.html#clustering-concepts for more details
{ "language": "en", "url": "https://stackoverflow.com/questions/40982507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there an API that will return how many results there are based your query search? Is there an api that returns how many results/logs there are based off your query search? or like a built in feature with NEST that will tell you how many results there is like i.e. count? Because I have a NEST query search that will do the following: var response = await _elasticClient.SearchAsync<EsSource>(s => s .Size(3000) // must see about this .Source(src => src.Includes(i => i .Fields(f => f.timestamp, fields => fields.messageTemplate, fields => fields.message))) .Index("customer-simulation-es-app-logs*") .Query(q => +q .DateRange(dr => dr .Field("@timestamp") .GreaterThanOrEquals("2021-06-07T17:13:54.414-05:00") .LessThanOrEquals(DateTime.Now)))); but I realized that the search api cannot go past 10,000 results because the array is empty when you paginate beyond 10,000 results. search api So, if there is an api or a feature that will let you know how much results there is based on your index or if you are doing a monthly query search as I am above; with knowing that number I can then create a forloop to paginate through each of those documents say the first 10,0000 hits I can view then the next iteration for the next 10,000 hits and so on. Hope this makes sense, i'll clarify if needed. A: Is there an API that will return how many results there are based your query search? I'm not aware of any ES API that will return an exact count. At high values, it becomes very approximate. array is empty when you paginate beyond 10,000 results. First, returning >10k search results is highly unusual. It sounds like you're trying to use ElasticSearch as a database, which you can do for some things, but don't go depending on ACID or anything like that. To page over large result sets in ElasticSearch, create a point in time and pass that to the search API with the search_after parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/68352128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Django or Nodejs or Ruby on Rails? I want to learn web development, I know little bit Python and Nodejs. I dont have any knowledge on Ruby. So, In the below 3, which one should I choose for Web Development? * *Django *Nodejs *Ruby on Rails Thanks in advance. A: Of course this question will be opinionated because it's fairly broad. Everyone has their own preferred choice. Though if you are a beginner to web programming and you'd like to use python I'd say start with flask.
{ "language": "en", "url": "https://stackoverflow.com/questions/20292688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Amcharts5 chart add tooltip to circle I`m trying to add a tooltip to my chart but it doesn't work. I've added it both to bullet and to series as well. There is no enough info in docs about how to add tooltip in this case. When I add tooltip to series in which graphic is based everything works perfectly Can you help? "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." am5.ready(function() { // Create root element // https://www.amcharts.com/docs/v5/getting-started/#Root_element var root = am5.Root.new("chartdiv"); // Set themes // https://www.amcharts.com/docs/v5/concepts/themes/ root.setThemes([ am5themes_Animated.new(root) ]); // Create chart // https://www.amcharts.com/docs/v5/charts/xy-chart/ var chart = root.container.children.push(am5xy.XYChart.new(root, { panX: true, panY: true, wheelY: "zoomXY", pinchZoomX: true, pinchZoomY: true })); chart.get("colors").set("step", 2); // Create axes // https://www.amcharts.com/docs/v5/charts/xy-chart/axes/ var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, { renderer: am5xy.AxisRendererX.new(root, {}), maxDeviation: 0.3, })); var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, { renderer: am5xy.AxisRendererY.new(root, {}), maxDeviation: 0.3, })); var tooltip = am5.Tooltip.new(root, { labelText: "MCaPos: {valueY}\nRN: ${valueY}", getFillFromSprite: false, getStrokeFromSprite: false, autoTextColor: false, getLabelFillFromSprite: false, }); tooltip.get('background').setAll({ fill: am5.color('#ffffff'), strokeWidth: 0, }) tooltip.label.setAll({ fill: am5.color('#000000') }); console.log(tooltip) // Create series // https://www.amcharts.com/docs/v5/charts/xy-chart/series/ var series0 = chart.series.push(am5xy.LineSeries.new(root, { calculateAggregates: true, xAxis: xAxis, yAxis: yAxis, valueYField: "y", valueXField: "x", valueField: "value", tooltip: am5.Tooltip.new(root, { labelText: "{valueY}" }) })); // Create series // https://www.amcharts.com/docs/v5/charts/xy-chart/series/ var series = chart.series.push(am5xy.LineSeries.new(root, { name: "Series 1", xAxis, yAxis, valueYField: "y", valueXField: "x", tooltip: am5.Tooltip.new(root, { labelText: "{valueY}" }) })); series.strokes.template.setAll({ strokeWidth: 2, strokeDasharray: [3, 3] }); series.data.setAll([{ "x": 0.01, "y": 1409090.91 }, { "x": 0.06, "y": 1589743.59 }, { "x": 0.11, "y": 1823529.41 }, { "x": 0.16, "y": 2137931.03 }, { "x": 0.21, "y": 2583333.33 }, { "x": 0.26, "y": 3263157.89 }, { "x": 0.31, "y": 4428571.43 }, { "x": 0.36, "y": 6888888.89 }, { "x": 0.41, "y": 15500000 }]); var circleTemplate = am5.Template.new({}); series0.bullets.push(function() { var graphics = am5.Circle.new(root, { fill: am5.color('#31DB42'), }, circleTemplate); return am5.Bullet.new(root, { sprite: graphics, radius: 1 }); }); // Add heat rule // https://www.amcharts.com/docs/v5/concepts/settings/heat-rules/ series0.set("heatRules", [{ target: circleTemplate, min: 3, max: 35, dataField: "value", key: "radius" }]); // Add bullet // https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets var starTemplate = am5.Template.new({}); series0.strokes.template.set("strokeOpacity", 0); series0.set('tooltip', tooltip); // Add cursor // https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/ chart.set("cursor", am5xy.XYCursor.new(root, { xAxis, yAxis, snapToSeries: [series0, series] })); series0.data.setAll([{ "x": 0.09271021903999942, "y": 2712290 }]); series0.appear(1000); // Make stuff animate on load // https://www.amcharts.com/docs/v5/concepts/animations/ series.appear(1000); chart.appear(1000, 100); }); // end am5.ready() <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script> <script src="https://cdn.amcharts.com/lib/5/xy.js"></script> <script src="https://cdn.amcharts.com/lib/5/index.js"></script> <div id="chartdiv" class="mt-20"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/72041568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Firebase query hex codes contained within randomly generated keys I would like to query a particular child from the array of color hex codes. Here's a snapshot of my database structure: How do I query a particular hex code and obtain the entire array of its parent object? A: You cannot query whether a specific value exists in a list. This is one of the many reasons why the Firebase documentation recommends against using arrays in the database. But in this case (and most cases that I encounter), you may likely don't really need an array. Say that you just care about what colors your user picked. In that case, you can more efficiently store the colors as a set: palettes -KSmJZ....A5I "0x474A39": true "0xbA9A7C": true "0xDEDEDF": true "0x141414": true "0x323E35": true A: I did it in a different way, made a function that does this: let databaseRef = FIRDatabase.database().reference() let HEX1 = hex1.text! as String let HEX2 = hex2.text! as String let HEX3 = hex3.text! as String let HEX4 = hex4.text! as String let HEX5 = hex5.text! as String let URL = url.text! as String // First set let colorArray1 = [HEX2, HEX3, HEX4, HEX5, URL] databaseRef.child("palette").child(HEX1).setValue(colorArray1) // second set let colorArray2 = [HEX1, HEX3, HEX4, HEX5, URL] databaseRef.child("palette").child(HEX2).setValue(colorArray2) // third set let colorArray3 = [HEX1, HEX2, HEX4, HEX5, URL] databaseRef.child("palette").child(HEX3).setValue(colorArray3) // fourth set let colorArray4 = [HEX1, HEX2, HEX3, HEX5, URL] databaseRef.child("palette").child(HEX4).setValue(colorArray4) // fifth set let colorArray5 = [HEX1, HEX2, HEX3, HEX4, URL] databaseRef.child("palette").child(HEX5).setValue(colorArray5) so that when I target any of the 5 hexes, it will bring me back the whole array together with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/39756884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL query for counting combinations and including entries that don't exist This is a simplified version of the table I am dealing with which is Orders +-------------------+------------------+---------------+ | Order_Base_Number | Order_Lot_Number | Other Cols... | +-------------------+------------------+---------------+ | 1 | 3 | | | 1 | 3 | | | 1 | 4 | | | 1 | 4 | | | 1 | 4 | | | 1 | 5 | | | 2 | 3 | | | 2 | 5 | | | 2 | 9 | | | 2 | 10 | | +-------------------+------------------+---------------+ What I want to do is to get a count for the unique entries base on Base and Lot numbers. I have two set of numbers, one is a set of Base numbers and the other is a set of Lot numbers. for example, lets say the two sets are Base In (1,2,3) and Lot is in (3,4,20). I am looking for an SQL query that can return all the possible combination of (Base,Lot) from the two sets with a count that shows how many times the combination was found in the table. My problem is that I want to include all the possible combinations and if a combination is not in the Orders table, I want the count to show zero. So, the output I am looking for is something like this. +------+-----+-----------+ | Base | Lot | Frequency | +------+-----+-----------+ | 1 | 3 | 2 | | 1 | 4 | 3 | | 1 | 20 | 0 | | 2 | 3 | 1 | | 2 | 4 | 0 | | 2 | 20 | 0 | | 3 | 3 | 0 | | 3 | 4 | 0 | | 3 | 20 | 0 | +------+-----+-----------+ I tried a lot of queries but never got close to this and not even sure if it can be done. Right now I am figuring out the combinations on the client side and hence I am performing too many queries to get the frequencies. A: Perhaps the clearest way is to start with the lists as CTEs: with bases as ( select 1 as base from dual union all select 2 as base from dual union all select 3 as base from dual ), lots as ( select 3 as lot from dual union all select 4 as lot from dual union all select 20 as lot from dual ) select b.base, l.lot, count(Order_Base_Number) as Frequency from bases b cross join lots l left outer join Orders o on o.base = b.base and o.lot = l.lot group by b.base, l.lot Note that this makes the cross join explicit, purposely not using the , for a Cartesian product. The first part of this query could also be written as something like the following (assuming that each base and lot has at least one record in the table): with bases as ( select distinct base from Orders -- or some other table, perhaps Orders ? where base in (1, 2, 3) ), select distinct lot from Orders -- or some other table, perhaps Lots ? where lot in (3, 4, 20) ) . . . This is more succinct, but might result in a less efficient query. A: What you need in the innermost subquery is called CROSS JOIN, which gets cartesian products (all possible combinations) of records. That's what you get when you have neither JOIN..ON condition nor WHERE: SELECT Base.Id as baseid, Lot.Id as lotid FROM Bases, Lots Now put it into subquery and LEFT JOIN to the rest of your stuff: SELECT ... FROM (SELECT Base.Id as baseid, Lot.Id as lotid FROM Bases, Lots) baseslots LEFT JOIN Orders ON Order_Base_Number = baseid, Order_Lot_Number = lotid .... With this LEFT JOIN, you'll get NULL for nonexistent combinations. Use COALESCE (or something like this) to turn them into 0. A: I don't have Oracle to test it but this is what I would do: CREATE TABLE pairs AS ( SELECT DISTINCT Base.Order_Base_Number, Lot.Order_Lot_Number FROM ORDERS Base CROSS JOIN ORDERS Lot ); CREATE TABLE counts AS ( SELECT Order_Base_Number, Order_Lot_Number, Count(*) AS C FROM ORDERS GROUP BY Order_Base_Number, Order_Lot_Number ); SELECT P.Order_Base_Number, P.Order_Lot_Number, COALESCE(C.C,0) AS [Count] FROM Pairs P LEFT JOIN counts C ON P.Order_Base_Number = C.Order_Base_Number AND P.Order_Lot_Number = C.Order_Lot_Number
{ "language": "en", "url": "https://stackoverflow.com/questions/14265496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java wait for Serial Input I linked a caliper to my computer with a RS232C-USB cable and I managed to get the data and print them in console. The caliper sends data everytime I press a pedal. The problem is I can only acquire data once at the beginning, I'm searching for a function that would freeze the program, waiting for an input from the caliper before printing. The only one I have in mind is read(), but it doesn't seem to make the program wait for input. Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/37207385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Lxml not finding all tables on page? I'm trying to get some data and when I'm using lxml it's find 2 tables and not the 3rd which I want. I suspect this has to do with the xpath or the way that specific table is being generated. I'm trying to get the price history from: http://web.tmxmoney.com/pricehistory.php?qm_symbol=WDO.DB.A Here are the different attempts I've made and the results. import requests from lxml import html def financialPriceData(): priceData = requests.get('http://web.tmxmoney.com/pricehistory.php?qm_symbol=WDO.DB.A') PriceScraperTree = html.fromstring(priceData.content) #PriceTreeTickers = PriceScraperTree.xpath('//*[@id="innerContent"]/div[4]/div[1]/div[1]/div[1]/table/tbody/tr[1]/td/table/tbody/tr[5]/td/table/tbody/tr/td/table/tbody/tr[2]/td[1]/text()') # no luck. From Chrome. # PriceTreeTickers = PriceScraperTree.xpath('//table[@id="qm_history_historyContent"]') # no luck, can't find the table PriceTreeTickers = PriceScraperTree.xpath('//table') # no luck, finds only 2 tables top of the page and bottom of the page data. When I look at text result the daily price is missing. print(PriceTreeTickers) financialPriceData()
{ "language": "en", "url": "https://stackoverflow.com/questions/38128318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: validate and match the zip code with bill/ship country in magento checkout I want to validate the zip code as per bill/ship country in magento checkout process. entered bill/ship country should matches the entered zipcode. If the entered zipcode and country did not match - customer should not be able to save the address and appropriate error message should be displayed. Example:- customer entered zip code 12345 and selected country as US. Then it should display the message "Zip code do not match with selected country." can anyone suggest me , how can i validate the zip as per country ? Can i use the google API to validate the zip code ? What portion of magento file i need to customize ? A: If you want to achieve this functionality, first you need to map the zipcodes with countries or use any plugin for it. Then, define a model or table for it. Then, during checkout make an ajax call from zipcode field to your controller, call your model there and then check the pincode. Based on your comparison, return the result and display what you want to.
{ "language": "en", "url": "https://stackoverflow.com/questions/36760059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python Produce empty list if condition not satisafied I am creating a if condition-based list. I want to create an empty list if the condition is not satisfied. My code: ip_list = [] op_list= [ip_list[0] if len(ip_list)>0 else ''] Present output: op_list = [''] Expected output: op_list = [] A: This can be accomplished more succinctly via slicing: op_list = ip_list[:1] If ip_list has at least one element, op_list will be a singleton list with the first element of ip_list. Otherwise, op_list will be an empty list. >>> a = [1, 2, 3] >>> b = [] >>> a[:1] [1] >>> b[:1] [] A: op_list = [] if ip_list else [ip_list[0]] A: You only need the first element if ip_list has any. Here is one of the easiest solution for that: [ip_list[0]] if ip_list else []
{ "language": "en", "url": "https://stackoverflow.com/questions/67542590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ng2-smart-table: is possible to pass data rows without keys? I want to pass to my data table some values as rows, like the following: ["ab", "b", "c"]. So, my json is just an array that doesn't have any keys, just a value. I know that we need to have a keys for each element that is the same of the column, but is there any solution? thanks A: According to the documentation, the type of table row data can only be object. You can convert raw data, for example, like this: // We should know the columns order var columns = ['id', 'name', 'username', 'email']; var data = rawData.map(function(item) { return item.reduce( function(result, item, columnIndex) { result[columns[columnIndex]] = item; return result; }, {} ); }); https://jsfiddle.net/jLwmhbwv/
{ "language": "en", "url": "https://stackoverflow.com/questions/45954212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving file properties results in Value does not fall in range exception I have the following code that is supposed to retrieve a canvas, save an image, and then write File properties to it. Sadly, it crashes when trying to save the properties. They are in string form, and the Property requires a string too, so I don't see what might be wrong: try { using (Windows.Storage.Streams.IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) { stream.Size = 0; await MyInkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream); } ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync(); string title = CanvasGrid.Width + " x " + CanvasGrid.Height; imageProperties.Title = title; await imageProperties.SavePropertiesAsync(); //MainPage.NotifyUser("File has been saved!", NotifyType.StatusMessage); } catch (Exception ex) { //MainPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); } Value does not fall within the expected range.
{ "language": "en", "url": "https://stackoverflow.com/questions/47763281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Renaming coat colors in R goes wrong with str_detect I have a dataset with horses and want to group them based on coat colors. In my dataset more than 140 colors are used, I would like to go back to only a few coat colors and assign the rest to Other. But for some horses the coat color has not been registered, i.e. those are unknown. Below is what the new colors should be. (To illustrate the problem I have an old coat color and a new one. But I want to simply change the coat colors, not create a new column with colors) Horse ID Coatcolor(old) Coatcolor 1 black Black 2 bayspotted Spotted 3 chestnut Chestnut 4 grey Grey 5 cream dun Other 6 Unknown 7 blue roan Other 8 chestnutgrey Grey 9 blackspotted Spotted 10 Unknown Instead, I get the data below(second table), where unknown and other are switched. Horse ID Coatcolor 1 Black 2 Spotted 3 Chestnut 4 Grey 5 Unknown 6 Other 7 Unknown 8 Grey 9 Spotted 10 Other I used the following code mydata <- data %>% mutate(Coatcolor = case_when( str_detect(Coatcolor, "spotted") ~ "Spotted", str_detect(Coatcolor, "grey") ~ "Grey", str_detect(Coatcolor, "chestnut") ~ "Chestnut", str_detect(Coatcolor, "black") ~ "Black", str_detect(Coatcolor, "") ~ "Unknown", TRUE ~ Coatcolor )) mydata$Coatcolor[!mydata$Coatcolor %in% c("Spotted", "Grey", "Chestnut", "Black", "Unknown")] <- "Other" So what am I doing wrong/missing? Thanks in advance. A: You can use the recode function of thedplyr package. Assuming the missing spots are NA' s, you can then subsequently set all NA's to "Other" with replace_na of the tidyr package. It depends on the format of your missing data spots. mydata <- tibble( id = 1:10, coatcol = letters[1:10] ) mydata$coatcol[5] <- NA mydata$coatcol[4] <- "" mydata <- mydata %>% mutate_all(list(~na_if(.,""))) %>% # convert empty string to NA mutate(Coatcolor_old = replace_na(coatcol, "Unknown")) %>% #set all NA to Unknown mutate(Coatcolor_new = recode( Coatcolor_old, 'spotted'= 'Spotted', 'bayspotted' = 'Spotted', 'old_name' = 'new_name', 'a' = 'A', #etc. )) mydata
{ "language": "en", "url": "https://stackoverflow.com/questions/66637532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PostgreSQL - "Include Error Detail" connection string parameter - how sensitive is the information returned? https://www.npgsql.org/doc/connection-string-parameters.html Include Error Detail - When enabled, PostgreSQL error and notice details are included on PostgresException.Detail and PostgresNotice.Detail. These can contain sensitive data. If I provide the "Include Error Detail=True" in the connection stringg to PostgreSQL, what sensitive data do I need to be concerned about? If the query itself is returned in an exception or error message, that is fine by me, but if say the connection password were returned in plaintext obviously that would be bad. What sensitive data is conditionally included in errors based on this parameter? A: These messages include no sensitive data that the database user should not see. So I wouldn't worry, unless perhaps you show the information to the application user rather than logging them. Your database user may have access to information that the application user shouldn't see.
{ "language": "en", "url": "https://stackoverflow.com/questions/74141729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading from a pre-populated database file for android I followed this tutorial at this page. I followed it thoroughly but I still can't get the prepopulated database file to work. I keep getting an error saying .getReadableDatabase or .getWritableDatabase is called recursively. Also tried the solution of the answer for this page and also it doesn't work. Is there a simpler way to copy a prepopulated database to a local database which enables me to update and create data? A: Try this : public class DatabaseManager { private DatabaseHelper dataHelper; private SQLiteDatabase mDb; private Context ctx; private String DATABASE_PATH = "/data/data/Your_Package_Name/databases/"; private static String DATABASE_NAME = "Your_Database"; private static String TABLE_NAME = "Your_Table"; private static final int DATABASE_VERSION = 1; String Class_Tag = "DatabaseManager"; public DatabaseManager(Context ctx) { this.ctx = ctx; dataHelper = new DatabaseHelper(ctx); } private static class DatabaseHelper extends SQLiteOpenHelper { @SuppressWarnings("unused") Context myContext = null; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.myContext = context; } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w("DBHelper", "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); onCreate(db); } } public boolean checkDataBase() { File f = null; try { String myPath = DATABASE_PATH + DATABASE_NAME; f = new File(myPath); } catch (Exception e) { Log.e(Class_Tag, "checkDataBase()", e); } return f.exists(); } public void createDataBase() { try { openDB(); InputStream myInput = ctx.getAssets().open(DATABASE_NAME + ".db"); OutputStream myOutput = new FileOutputStream(DATABASE_PATH + DATABASE_NAME); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } if (mDb.isOpen()) mDb.close(); myOutput.flush(); myOutput.close(); myInput.close(); } catch (Exception e) { Log.e(Class_Tag, "createDataBase()", e); } } public DatabaseManager openDB() throws SQLException { mDb = dataHelper.getWritableDatabase(); return this; } public void closeDB() { try { if (mDb != null) { mDb.close(); } } catch (Exception e) { e.printStackTrace(); } } } and in MainActivity DatabaseManager dbMgr=new DatabaseManager(this); try { if (!dbMgr.checkDataBase()) { dbMgr.createDataBase(); } } catch (Exception e) { Log.e(Class_Tag, "onCreate()", e); } finally { dbMgr.closeDB(); } Hope it helps...
{ "language": "en", "url": "https://stackoverflow.com/questions/6910099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Localized dates inconsistency I am localizing my date strings, but having issues. I expect UK locales to have dayOfTheMonth then Month while US ones to have Month then DayOfTheMonth. It seems to be the case for getMediumDateFormat but not for getDateFormat. If I use: android.text.format.DateFormat.getMediumDateFormat then I get: UK: 25 Nov 2015 US: Nov 25, 2015 Which is what I expect (day and month are in reverse order) However, if I use: android.text.format.DateFormat.getDateFormat Then I get: UK and US: 25/11/2015 In both cases the format is: dd/MM/yyyy Did I miss something here? Is there a better way to get a localized short date format?
{ "language": "en", "url": "https://stackoverflow.com/questions/33711706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Yeoman/Grunt clean:dist task property undefined I'm new to grunt and having trouble with the clean:dist task for grunt-contrib-clean. This is my code for the task. clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git*', '!<%= yeoman.dist %>/Procfile', '!<%= yeoman.dist %>/package.json', '!<%= yeoman.dist %>/web.js', '!<%= yeoman.dist %>/node_modules' ] }] }, server: '.tmp' }, When I run grunt build I get the following warning "An error occurred while processing a template (Cannot read property 'dist' of undefined). Use --force to continue." I'm thinking it must be a syntax error or something wrong with a plugin, but I don't know enough to keep figure it out. A: For some reason, changing from <%= yeoman.dist %> to <%= config.dist %> solves the problem from me. Not sure when using yeoman.dist syntax is appropriate, but in any case I solved my own problem. So the solutions is... clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= config.dist %>/*', '!<%= config.dist %>/.git*', '!<%= config.dist %>/Procfile', '!<%= config.dist %>/package.json', '!<%= config.dist %>/web.js', '!<%= config.dist %>/node_modules' ] }] }, server: '.tmp' },
{ "language": "en", "url": "https://stackoverflow.com/questions/25771696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone Emulator error, Hyper-V components not running, Windows 8.1 hosted in Windows Azure Environment: Windows 8.1 Enterprise 64-bit hosted in Windows Azure Visual Studio Ultimate 2013 (Update 2) I get the following error when trying to run a very simple phone app. I know MS says a VM-within-a-VM environment isn't supported, but I know it can work. Has anyone had success with this? Any help is greatly appreciated. Windows Phone Emulator The Windows Phone Emulator wasn't able to ensure the virtual machine was running: Something happened while starting a virtual machine: 'Emulator WVGA 512 MB.' failed to start. (Virtual machine ID CADD6546-129A-4683-9A2D-52EAE777E888) The Virtual Machine Management Service failed to start the virtual machine 'Emulator WVGA 512 MB.' because one of the Hyper-V components is not running (Virtual machine ID CADD6546-129A-4683-9A2D-52EAE777E888). Prior to seeing the error, the emulator emits the on-screen messages: Loading ... The Windows Phone OS is starting ... And then the error. Of all the Hyper-V services available, the Hyper-V Virtual Machine Management service is the only one which is running. Thanks, Chris A: I had the same issue with Visual Studio running on windows 8.1 in vmware player What I had to do to solve the problem was this : Tick the box "Virtualize Intel VT-x/EPT or AMD-V/RVI" in the processor settings of your VM Add the line "hypervisor.cpuid.v0 = FALSE" in the file "Windows 8 x64.vmx" (add it between line 5 and 6. Not sure this matters, but at this line I'm sure it works) Should be working fine A: "You cannot host it in Azure. It needs to be a physical machine." -- Jeff Sanders (MSFT) A: Florian.C's answer got me on the right track to get the emulator working correctly in VMware Fusion on my MacBook Pro. In Fusion, the settings are under the "Processors & Memory" section. You have to open the "Advanced" section at the bottom and check the "Enable hypervisor applications for this virtual machine". Once that was done, I had to also open the .vmx file and add the "hypervisor.cpuid.v0 = "FALSE"" line. Originally I copied and pasted from SO and the VM threw an error when I booted it. It turns out the " I added around FALSE were not normal quotes. Once I fixed that, the VM booted and the emulator ran just fine under Fusion. Thanks for the great info!
{ "language": "en", "url": "https://stackoverflow.com/questions/23794062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Class with multiple interfaces i have 2 interfaces inter1 and inter2 and class that implements both of them: public interface Interface1 { method1(); } public interface Interface2 { method2(); } public class Implementer implements Interface1, Interface2 { method1() { // something } method2() { // something } } public class Test { public static void main(String[] args) { Interface1 obj = quest(); obj.method1(); if(obj instanceof Interface2) { obj.method2(); //exception } } public static Interface1 quest() { return new cl(); } } How to cast obj to Interface2 and call method2() or it is possible to call method2() without casting ? A: If you write inter1 obj = ... then you will not be able to write obj.method2) unless you cast to inter2 or to a type that implements inter2. For example inter1 obj = quest(); if (obj instanceof class1) ((class1) obj).method2(); or inter1 obj = quest(); if (obj instanceof inter2) ((inter2) obj).method2(); As an aside, when you write in Java you normally give classes and interfaces names that begin the a capital letter, otherwise you confuse people reading your code. A: Using genecics it is possible to declare generic reference implementing more than one type. You can invoke method from each interface it implements without casting. Example below: public class TestTwoTypes{ public static void main(String[] args) { testTwoTypes(); } static <T extends Type1 & Type2> void testTwoTypes(){ T twoTypes = createTwoTypesImplementation(); twoTypes.method1(); twoTypes.method2(); } static <T extends Type1 & Type2> T createTwoTypesImplementation(){ return (T) new Type1AndType2Implementation(); } } interface Type1{ void method1(); } interface Type2{ void method2(); } class Type1AndType2Implementation implements Type1, Type2{ @Override public void method1() { System.out.println("method1"); } @Override public void method2() { System.out.println("method2"); } } The output is: method1 method2 A: If you want to do this in spring, the general idea would be: // Test.java public class Test { private final Interface1 i1; private final Interface2 i2; public Test(Interface1 i1, Interface2 i2) { this.i1 = i1; this.i2 = i2; } } <!-- application-context.xml --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="implementer" class="org.mypackage.Implementer" /> <bean id="test" class="org.mypackage.Test"> <constructor-arg ref="implementer"/> <constructor-arg ref="implementer"/> </bean> </beans> // Main.java public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml"); Test t = (Test) context.getBean("test"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/32639090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set Image as pdf page background I'm having problems to use an image as background in table column. I need the image to be the background of each page in pdf. The image is being displayed but it seems to be zoomed in. It sizes are width : 2487px, heigth : 3516px (width : 21.06cm, height : 29.77cm). This is my code: <xsl:template name="template-body"> <fo:block backgorund-color="yellow"> <fo:table> <fo:table-column background-image="image.jpg"/> <fo:table-body> <fo:table-row height="29.7cm"> <fo:table-cell> <fo:block color="white"> SOME TEXT INSIDE THE IMAGE </fo:block> </fo:table-cell> </fo:table-row> </fo:table-body> </fo:table> </fo:block> </xsl:template> This code generates this: But i need this: I also tried to put the image as background of <fo:region-body> but i had the same problem. I think i need some way to specify the image width and height. Any help? Thanks in advance. A: Since you are using FOP, I believe there is no provision to scale a background-image to fit. This would be an extension to the XSL FO Specification. RenderX XEP supports this (http://www.renderx.com/reference.html#Background_Image). It is unclear if you actually want the image behind the table (and you have other content) or you actually want the image behind the whole page. You could put the image in an absolute positioned block-container and use content-width and content-height to scale, but this is not going to repeat for only the table. This would work for the page. If it is only the table, you are likely going to have to resize the actual image to fit correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/26178863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Magento manipulate weight on checkout I have simple products in Magento 1.9 that I can combine ship and would like to change the total shipping weight at checkout (and in shopping cart view for shipping estimate calculation etc) based on sku. For example, if one or two widgets with the correct sku are purchased, their weight is 1 lbs combined. If three to five widgets with the correct sku are purchased, their weight is 2 lbs combined etc. Tablerates could handle this if all items were included. However, I must limit it to certain items determined by sku. So currently in Magento, each item has a weight of 1 lbs and total weight is number of items * 1 lbs. I have found answers to display total weight, or update the item's weight in the database, but nothing that fulfills these requirements. I'm very new to Magento and am struggling to achieve this. If you reply back with suggested code changes, could you please be specific as to the file's location that should be edited? Edit Following Mladen Ilić's suggestions, I have come up with the follow code that calculates the total weight on the event sales_quote_collect_totals_after event. How do I send the new adjusted weight to Magneto to use it through checkout? /app/etc/modules/Weight_Extension.xml <?xml version="1.0"?> <config> <modules> <Weight_Extension> <codePool>local</codePool> <active>true</active> </Weight_Extension> </modules> </config> /app/code/locale/Weight/Extension/etc/config.xml <?xml version="1.0"?> <config> <modules> <Weight_Extension> <version>0.0.1</version> </Weight_Extension> </modules> <global> <models> <weight_extension> <class>Weight_Extension_Model</class> </weight_extension> </models> <events> <sales_quote_collect_totals_after> <observers> <weight_extension> <class>weight_extension/observer</class> <method>adjustTotalWeight</method> </weight_extension> </observers> </sales_quote_collect_totals_after> </events> </global> </config> /app/code/locale/Weight/Extension/Model <?php class Weight_Extension_Model_Observer { public function adjustTotalWeight($observer) { $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems(); $combinedItems = 0; foreach($items as $item) { if($item->getSku() == 1 || $item->getSku() == 2) { $combinedItems++; } } if($combinedItems > 0 && $combinedItems < 3) $weight = 1; if($combinedItems >= 3 && $combinedItems < 6) $weight = 2; //send new $weight to Magento and persist through checkout? } } How do I send the new adjusted weight to Magneto to use it through checkout? A: Magento calculates weight used for getting shipping rates in Mage_Sales_Model_Quote_Address_Total_Shipping::collect. When collecting shipping address totals, items are looped and their weight accumulated and then set to address object. That being said, you have to be careful how are you going to change this behavior. On a first look, it seems that using sales_quote_collect_totals_after event could be the right way. When event is triggered get all shipping address items, loop through them and use custom logic for calculating weight. Best of luck. A: You writted event in adminhtml context, you have to change it to frontend.
{ "language": "en", "url": "https://stackoverflow.com/questions/42933786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: sound for notification I want to play an mp3 sound when my Notification is triggered. For this, I have put an mp3 file in my "res/raw" folder and used the following instruction: notification.sound=Uri.parse("android.resource://"+getPackageName()+"/" + R.raw.mySound);. But I am getting no sound when the Notifications appears! Any idea? A: I found an example here - * *How to play an android notification sound This is the code that is used try { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone ring = RingtoneManager.getRingtone(getApplicationContext(), notification); ring.play(); } catch (Exception e) {} On the other hand, if you want to customize the sound (as I ausume you do), you should use this code taken from here notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd); notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE ; A: Simply put this below code inside the block which will be triggered when notification occurs.. mMediaPlayer = new MediaPlayer(); mMediaPlayer = MediaPlayer.create(this, R.raw.mySound); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setLooping(true); // Set false if you don't want it to loop mMediaPlayer.start();
{ "language": "en", "url": "https://stackoverflow.com/questions/13421176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XAML GridView to GridView Drag and Drop Mouse vs Touch Here's XAML code where you can drag and drop GridView elements between different GridViews, however, this approach only works with mouse input and just partially with touch input. With touch input the elements "unlock" from the GridView only on vertical drag. On horizontal drag the UI tries to scroll the screen instead of just moving the GridView element. So mouse works perfectly and touch works only on inital vertical drag, after the inital vertical drag you can move the element around just as you could with mouse. This is a Windows 8 app. <Page.Resources> <DataTemplate x:Key="ItemTemplate1"> <Border Background="#25BDC0"> <Grid Width="230" Height="230" Margin="10"> <TextBlock Text="{Binding Title}" Style="{StaticResource HeaderTextStyle}" HorizontalAlignment="Center" VerticalAlignment="Center"/> </Grid> </Border> </DataTemplate> </Page.Resources> <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Width="Auto" Height="Auto"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <GridView Grid.Column="0" ItemTemplate="{StaticResource ItemTemplate1}" ItemsSource="{Binding FirstCollection}" AllowDrop="True" CanDragItems="True" DragItemsStarting="GridViewDragItemsStarting" Drop="GridViewDrop" Margin="10"> </GridView> <GridView Grid.Column="1" ItemTemplate="{StaticResource ItemTemplate1}" ItemsSource="{Binding SecondCollection}" AllowDrop="True" CanDragItems="True" DragItemsStarting="GridViewDragItemsStarting" Drop="GridViewDrop" Margin="10"> </GridView> </Grid> A: I've stumbled upon the same issue and found the answer here : http://social.msdn.microsoft.com/Forums/windowsapps/en-US/7fcf8bb8-16e5-4be8-afd3-a21e565657d8/drag-and-drop-gridview-items-and-disabled-scrollbar It appears that with a GridView you can't initiate the drag horizontally, you have to do it vertically and it's the exact opposite with the ListView. So if you want to drag 'n drop items horizontally you have to use a ListView. (as recommended in the MS guidelines http://msdn.microsoft.com/en-us/library/windows/apps/hh465299.aspx ) Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/16483739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the connected SSID in Xamarin.Forms? I need to get the SSID of the current network that I am connected to. Here is the code I used to find the SSID in Xamarin.Android: WifiManager wifiManager = (WifiManager)(Application.Context.GetSystemService(WifiService)); if (wifiManager != null) { var ssid = wifiManager.ConnectionInfo.SSID; } else { var str = "WiFiManager is NULL"; } But I need to implement this in Xamarin.Forms. How can I do this ? A: You can use DependencyService. The DependencyService class is a service locator that enables Xamarin.Forms applications to invoke native platform functionality from shared code. 1º Create a public interface (for organization sake, maybe under Mobile > Services > IGetSSID) public interface IGetSSID { string GetSSID(); } 2º Create the Android Implementation [assembly: Dependency(typeof(GetSSIDAndroid))] namespace yournamespace { public class GetSSIDAndroid : IGetSSID { public string GetSSID() { WifiManager wifiManager = (WifiManager)(Android.App.Application.Context.GetSystemService(Context.WifiService)); if (wifiManager != null && !string.IsNullOrEmpty(wifiManager.ConnectionInfo.SSID)) { return wifiManager.ConnectionInfo.SSID; } else { return "WiFiManager is NULL"; } } } } 3º Then in your forms you get the SSID like this: var ssid = DependencyService.Get<IGetSSID>().GetSSID(); Note: Don't forget to add this permission on your Android Manifest <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> A: Get SSID and BSSID API31 Xamarin C# Example Required permissions: CHANGE_NETWORK_STATE, ACCESS_FINE_LOCATION If API<31 TransportInfo will return Null using Android.Content; using Android.Net; using Android.Net.Wifi; protected override void OnStart() { base.OnStart(); NetworkRequest request = new NetworkRequest.Builder().AddTransportType(transportType: TransportType.Wifi).Build(); ConnectivityManager connectivityManager = Android.App.Application.Context.GetSystemService(Context.ConnectivityService) as ConnectivityManager; NetworkCallbackFlags flagIncludeLocationInfo = NetworkCallbackFlags.IncludeLocationInfo; NetworkCallback networkCallback = new NetworkCallback((int)flagIncludeLocationInfo); connectivityManager.RequestNetwork(request, networkCallback); } private class NetworkCallback : ConnectivityManager.NetworkCallback { public NetworkCallback(int flags) : base(flags) { } public override void OnCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) { base.OnCapabilitiesChanged(network, networkCapabilities); WifiInfo wifiInfo = (WifiInfo)networkCapabilities.TransportInfo; if (wifiInfo != null) { string ssid = wifiInfo.SSID.Trim(new char[] {'"', '\"' }); string bssid = wifiInfo.BSSID; } } } Click Android API reference.ConnectivityManager.NetworkCallback(int)!
{ "language": "en", "url": "https://stackoverflow.com/questions/60486196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Formula to reference data from a PivotTable I am having some difficulty writing a specific Excel formula. I have a summary sheet that pulls data from various other sheets extracted from a database. One of these is a PivotTable whereby using the Item Number in the first column and the dates along the top row as a reference I can pinpoint the data I need. eg: To address the highlighted cell I would normally manually write: =GETPIVOTDATA(HighPiv,"SPN010977-204 11333") HighPiv is the name I gave to the pivot table as I am referring to it from my summary sheet. This works, however the Week numbers along the top will continuously be changing in the pivot every month and therefore this formula will not pick up the values accurately once the pivot is updated. I have been looking into a way to make the referencing more dynamic. This is the summary where the data is required: Rather than within the quotation marks of the formula (adding the specific Item number and Week number word for word), I was hoping to refer to the cell references of the summary sheet. (So if I wanted Item number, say A55, and Week number, say H50). The dates in the summary sheet change according to the pivot so referring to the dates on the summaries to get the data would be a better way for it to be kept up-to-date. The problem here is I don't know how to go about it. I have tired to refer to the cells in question but it doesn't seem to work giving me #REF! or #VALUE! errors. A: I think what you would like is: =GETPIVOTDATA("Qty",HighPiv,"Item",A55,"Week",H50) I find the easiest way to write such a formula is to start by ensuring that Pivot Table Tools > Options > PivotTable – Options, Generate GetPivotData is checked then in the desired cell enter = and select the required entry from the PT (here63). That would show (for example) “SPN010977-204” and 11333 or ”11333” but these can be changed to A55 and H50.
{ "language": "en", "url": "https://stackoverflow.com/questions/18012089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How Would I replace a string if its input in a certain order? var xboxConverter = { "1" : "Up", "2" : "Down", "3" : "Down Foward", "4" : "Backward", "5" : "Standing", "6" : "Forward", "7" : "Up Backward", "8" : "Up", "9" : "Up Foward", "236S": "Quarter Circle Special", ",": " ", "H" : "B", "M": "Y", "L": "X", "S": "A", "2" : "Down", "RB" : "RB", "236" : "Quarter Circle Forward", "214" : "Quarter Circle Backwards", "214S" : "Quarter Circle Backwards Special", }; document.querySelector("textarea").addEventListener("keyup", (e) => { const input = e.target.value.toUpperCase(); const inputValidated = input.replace(/[^a-zA-Z0-9 ,]/g, ""); const arrOfIns = inputValidated.split(" "); const arrOfOuts = arrOfIns.map((e) => xboxConverter[e] ? xboxConverter[e] : "" ); if (parseInt.innerText == 236 & 214) return const out = arrOfOuts.join(" , "); document.getElementById("output").innerText = out; }); To better describe what I mean if someone inputs 236 together it should say "Quarter Circle Forward" or if they input 236RT it should say "Quarter Circle Forward Right Trigger". A: From your comments, I can understand that you are looking for a value matching the key that the user inputs. You can simply check for it without any splits and for loops like: var xboxConverter = { "1": "Up", "2": "Down", "3": "Down Foward", "4": "Backward", "5": "Standing", "6": "Forward", "7": "Up Backward", "8": "Up", "9": "Up Foward", "236S": "Quarter Circle Special", ",": " ", "H": "B", "M": "Y", "L": "X", "S": "A", "2": "Down", "RB": "RB", "236": "Quarter Circle Forward", "214": "Quarter Circle Backwards", "214S": "Quarter Circle Backwards Special", }; document.querySelector("textarea").addEventListener("keyup", (e) => { const input = e.target.value.toUpperCase(); const inputValidated = input.replace(/[^a-zA-Z0-9 ,]/g, ""); document.getElementById("output").innerText = xboxConverter[inputValidated] ? xboxConverter[inputValidated] : "No data"; }); <textarea></textarea> <div id="output"></div> Is this what you're looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/70416467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to bring BigDecimal to fractional power? BigDecimal was the choice to store numbers that have up to 5 digits after decimal point. I need to raise the BigDecimal to fractional power (up to 2 digits after decimal point). For example I have to bring 9.09671 to power of 1.51. Do I need some conversions from/to BigDecimal? How to do it? EDIT: I cannot use 3rd party libraries as described in Java's BigDecimal.power(BigDecimal exponent): Is there a Java library that does it? Is there more elegant, succint way for this case than described in How to do a fractional power on BigDecimal in Java?
{ "language": "en", "url": "https://stackoverflow.com/questions/28242717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: multi-part identifier could not be bound on insert from another database on another server I am trying to insert information from one database on one server into a table on another with out inserting a duplicate and i get the title error. here is the code INSERT INTO [Datamaxx].[dbo].[data_job_t] (JobCode, Description) SELECT job_no, description FROM OPENDATASOURCE('SQLNCLI', 'Data Source=server\server;Integrated Security=SSPI') .cas_tekworks.dbo.jobs WHERE Job_Status ='A' and data_job_t.JobCode not in (select Jobcode from [Datamaxx].[dbo].[data_job_t]) A: Did you tried this.... job_no not in instead of data_job_t.JobCode INSERT INTO [Datamaxx].[dbo].[data_job_t] (JobCode, Description) SELECT job_no, description FROM OPENDATASOURCE('SQLNCLI', 'Data Source=server\server;Integrated Security=SSPI') .cas_tekworks.dbo.jobs WHERE Job_Status ='A' and job_no not in (select Jobcode from [Datamaxx].[dbo].[data_job_t])
{ "language": "en", "url": "https://stackoverflow.com/questions/19056006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: image auto rotate counterclockwise when width is less than height My all images auto rotate counterclockwise when width is less than height. Example: this example Help me please! Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/51496388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript, find object in list of objects by id I have a list of objects in where I need to find one specifically by an ID. So very simply like so: { { "id": "1" },{ "id": "2" } } I have a function where I want to find the object by it's id, that does not work like so function findOb (id) { return _.find(myList, function(obj) { return obj.id === id } ); } it is not returning the correct object (this is using lodash) uncertain what I am doing incorrect and could use some help. Thanks! edit - I don't know if this helps but I am building and trying to search an object in this format - https://github.com/pqx/react-ui-tree/blob/gh-pages/example/tree.js . So there are just objects with module and leaf sometimes, and I want to be able to search and find by the 'module' key. Thanks for the feedback everyone! A: Your code should have worked, but it can be simplified. If you provide a property name for the predicate argument to _.find, it will search that property for the thisArg value. function findOb(id) { return _.find(myList, 'id', id); } The only problem I can see with your code is that you use === in your comparisons. If you pass 1 as the ID argument instead of "1", it won't match because === performs strict type checking.
{ "language": "en", "url": "https://stackoverflow.com/questions/33269048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does Azure TableQuery handle continuation tokens internally? I'm trying to find a definitive answer to the question of continuation tokens and the Azure Storage Library 2.0, as there seems to be significant differences between pre-2.0 versions (StorageClient) and the current version (Storage). Aside from the MSDN documentation, which doesn't clarify the above question for me, its very hard to find information on continuation tokens which specifically relates to version 2.0 and above of the library, because earlier versions are named so similarly (CloudTableQuery vs TableQuery) search results get polluted with information about the earlier versions. So, are continuation tokens handled internally on the Microsoft.WindowsAzure.Storage client (version 2.0 of the storage library)? Can I trust that the result sets I get back are the full result sets? Thanks! A: There're two methods in question when it comes to executing queries against a table: CloudTable.ExecuteQuery and CloudTable.ExecuteQuerySegmented. The first one (ExecuteQuery) will handle the continuation token internally while the second one (ExecuteQuerySegmented) will return you the continuation token as a part of result set which you can use to fetch next set of data.
{ "language": "en", "url": "https://stackoverflow.com/questions/16017001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: pulling out list from wordpress post I want to pull out the list (ul) element from my wordpress post(s) so I can put it in a different location. My current css pulls out the images and blockqute and puts just the text html <?php $content = preg_replace('/<blockquote>(.*?)<\/blockquote>/', '', get_the_content()); $content = preg_replace('/(<img [^>]*>)/', '', $content); $content = wpautop($content); // Add paragraph-tags $content = str_replace('<p></p>', '', $content); // remove empty paragraphs echo $content; ?> A: Just a friendly reminder is that it is generally not recommended to parse html with regex. If you would like to do that anyway you could try like this: $pattern = '~<ul>(.*?)</ul>~s'; So in your code it would look like this: preg_match_all('/(~<ul>(.*?)</ul>~s)/', $content, $ulElements); And then for removing it from the original string: preg_replace('/(~<ul>(.*?)</ul>~s)/', '', $content);
{ "language": "en", "url": "https://stackoverflow.com/questions/37585007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android java.lang.OutOfMemoryError: GC overhead limit exceeded I got an error as of title. I know there are many answers but it didn't works. What I did already, First. add code on build.gradle(Module:app) "multiDexEnabled true" at defaultConfig & "compile 'com.android.support:multidex:1.0.1'" at dependencies add code on AndroidMenifest android:name="android.support.multidex.MultiDexApplication" at application Second. add code on build.gradle(Project:~~)(I also tried on build.gradle(Module:app) "dexOptions{ javaMaxHeapSize "2g" (I also tried for "4g" }" First one was not works which means show same error.(Out of memory) Second one was show another error(could not find method~~) which means I use higher targetSDKVersion to use it.(My app is 23 for targetSDKVersion.) So there were no answer until I tried google it.... How could I solve it....? is there anybody who can help me? I'm waiting for you such a kind person.... Thank you in advance.....
{ "language": "en", "url": "https://stackoverflow.com/questions/43003151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ist possible to convert my own HTML to PDF, without breaking the pages, preserving the formatting and supporting the hyperlinks? I have already searched for many questions at Stackoverflow, but I really didn't consider the questions and the answers for my needs. DocRaptor is really not a good app because it breaks the pages and it doesn't recognise the extended Latin letters, as à, é, ã,, etc. I used many HTML to PDF converter web-based apps, it didn't work for me, because they didn't preserve the formatting and the hyperlinks. I used capture apps for Mac, as W3Capture and Layouts.1) Layouts capture one whole HTML and CSS page as a PDF without breaking the pages and also preserving the formatting. But, it didn't support the hyperlinks, because it captures the page as PDF, behaving as PNG-like. 2) W3captures supports the hyperlinks, converting the HTML/CSS pages, but it breaks the pages and really doesn't preserve the formatting. I also tested TextEdit, which can exports as PDF, but when it exports as PDF, it breaks the pages. Pages from iWork and Word also do it. I'm really frustrated. Is it possible to convert the own HTML page to PDF, without breaking the pages, preserving the formatting and supporting the hyperlinks? A: I think you can open you html file in Chrome. Then print it to pdf format. Then it will works. That is when you print it, you choose "save as pdf" rather than your printer.
{ "language": "en", "url": "https://stackoverflow.com/questions/13814875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: is there a way to allow a phone "-" in phone format using numeric in vuelidate? I'm using vuelidate to validate a form in VUE build. I have a phone number input that needs to be formatted as 222-222-2222 which I have setup using a phone mask. My issue is now the input will not validate when the phone is filled in. My error message is still displayed. Is there a way to allow for numbers only along with a dash "-"??? <div class="form-field"> <label for="phone"> Phone Number </label> <input type="text" class="form-input text-input" name="phone" id="phone" @input="phoneNumberMask()" v-model.trim="$v.formData.phone.$model"> <label v-if="($v.formData.phone.$dirty && !$v.formData.phone.required) || ($v.formData.phone.$dirty && !$v.formData.phone.numeric) || ($v.formData.phone.$dirty && !$v.formData.phone.minLength) || ($v.formData.phone.$dirty && !$v.formData.phone.maxLength)" class="error"> Please enter a valid phone number. </label> </div> validations: { formData: { phone: { required, numeric, minLength: minLength(12), maxLength: maxLength(12) } } } methods: { phoneNumberMask(){ const x = this.formData.phone.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/); this.formData.phone = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : ''); }, } A: As pointed out in the comments, you can create a regular expression that validates you phone number format, in this case /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ could be a starting point. Here a complete example. <template> <div class=""> <label :class="{ error: $v.number.$error, green: $v.number.$dirty && !$v.number.$error }" > <input class="" v-model="number" @change="$v.number.$touch()" placeholder="Phone number" /> </label> <div class="" v-if="$v.number.$dirty && $v.number.$error"> <p class="">NOT VALID</p> </div> <button class=" " :disabled="$v.$invalid" @click="saveClick()" > <span class="">Save</span> </button> </div> </template> Script part import { required, helpers } from "vuelidate/lib/validators" const number = helpers.regex( "serial", /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ ) export default { data() { return { number: null } }, computed: { serial: { get() { return this.number }, set(value) { this.number = value } } }, methods: { saveClick() { //TODO } }, validations: { number: { required, number } } } Note This is for Vue 2.x and vuelidate ^0.7.6
{ "language": "en", "url": "https://stackoverflow.com/questions/65799680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to implement a Master Detail Form as part of a MultiPageEditor in Eclipse? I have created a sample multi page editor via the Eclipse wizard. Now, I want to extend this editor with a Master Detail Form, so basically, there should be two pages, one standard text editor and the beforesaid Master Detail Form. Please note: I am using this a demo code for my MasterDetailsPage.java. Here is my code so far: MultiPageEditor: package multipageeditortest.editors; import java.io.StringWriter; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FontDialog; import org.eclipse.ui.*; import org.eclipse.ui.editors.text.TextEditor; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.MultiPageEditorPart; import org.eclipse.ui.ide.IDE; /** * An example showing how to create a multi-page editor. * This example has 3 pages: * <ul> * <li>page 0 contains a nested text editor. * <li>page 1 allows you to change the font used in page 2 * <li>page 2 shows the words in page 0 in sorted order * </ul> */ public class MultiPageEditor extends MultiPageEditorPart implements IResourceChangeListener{ /** The text editor used in page 0. */ private TextEditor editor; /** The font chosen in page 1. */ private Font font; /** The text widget used in page 2. */ private StyledText text; /** * Creates a multi-page editor example. */ public MultiPageEditor() { super(); ResourcesPlugin.getWorkspace().addResourceChangeListener(this); } /** * Creates page 0 of the multi-page editor, * which contains a text editor. */ void createPage0() { try { editor = new TextEditor(); int index = addPage(editor, getEditorInput()); setPageText(index, editor.getTitle()); } catch (PartInitException e) { ErrorDialog.openError( getSite().getShell(), "Error creating nested text editor", null, e.getStatus()); } } /** * Creates page 1 of the multi-page editor, * which allows you to change the font used in page 2. */ void createPage1() { Composite composite = new Composite(getContainer(), SWT.NONE); GridLayout layout = new GridLayout(); composite.setLayout(layout); layout.numColumns = 2; Button fontButton = new Button(composite, SWT.NONE); GridData gd = new GridData(GridData.BEGINNING); gd.horizontalSpan = 2; fontButton.setLayoutData(gd); fontButton.setText("Change Font..."); fontButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { setFont(); } }); int index = addPage(composite); setPageText(index, "Properties"); } /** * Creates page 2 of the multi-page editor, * which shows the sorted text. */ void createPage2() { Composite composite = new Composite(getContainer(), SWT.NONE); FillLayout layout = new FillLayout(); composite.setLayout(layout); text = new StyledText(composite, SWT.H_SCROLL | SWT.V_SCROLL); text.setEditable(false); int index = addPage(composite); setPageText(index, "Preview"); } void createMasterDetailPage() { int index = addPage(new MasterDetailsPage(this)); // ERROR setPageText(index, "Master Detail Page"); } /** * Creates the pages of the multi-page editor. */ protected void createPages() { createPage0(); createPage1(); createPage2(); createMasterDetailPage(); } /** * The <code>MultiPageEditorPart</code> implementation of this * <code>IWorkbenchPart</code> method disposes all nested editors. * Subclasses may extend. */ public void dispose() { ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); super.dispose(); } /** * Saves the multi-page editor's document. */ public void doSave(IProgressMonitor monitor) { getEditor(0).doSave(monitor); } /** * Saves the multi-page editor's document as another file. * Also updates the text for page 0's tab, and updates this multi-page editor's input * to correspond to the nested editor's. */ public void doSaveAs() { IEditorPart editor = getEditor(0); editor.doSaveAs(); setPageText(0, editor.getTitle()); setInput(editor.getEditorInput()); } /* (non-Javadoc) * Method declared on IEditorPart */ public void gotoMarker(IMarker marker) { setActivePage(0); IDE.gotoMarker(getEditor(0), marker); } /** * The <code>MultiPageEditorExample</code> implementation of this method * checks that the input is an instance of <code>IFileEditorInput</code>. */ public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException { if (!(editorInput instanceof IFileEditorInput)) throw new PartInitException("Invalid Input: Must be IFileEditorInput"); super.init(site, editorInput); } /* (non-Javadoc) * Method declared on IEditorPart. */ public boolean isSaveAsAllowed() { return true; } /** * Calculates the contents of page 2 when the it is activated. */ protected void pageChange(int newPageIndex) { super.pageChange(newPageIndex); if (newPageIndex == 2) { sortWords(); } } /** * Closes all project files on project close. */ public void resourceChanged(final IResourceChangeEvent event){ if(event.getType() == IResourceChangeEvent.PRE_CLOSE){ Display.getDefault().asyncExec(new Runnable(){ public void run(){ IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages(); for (int i = 0; i<pages.length; i++){ if(((FileEditorInput)editor.getEditorInput()).getFile().getProject().equals(event.getResource())){ IEditorPart editorPart = pages[i].findEditor(editor.getEditorInput()); pages[i].closeEditor(editorPart,true); } } } }); } } /** * Sets the font related data to be applied to the text in page 2. */ void setFont() { FontDialog fontDialog = new FontDialog(getSite().getShell()); fontDialog.setFontList(text.getFont().getFontData()); FontData fontData = fontDialog.open(); if (fontData != null) { if (font != null) font.dispose(); font = new Font(text.getDisplay(), fontData); text.setFont(font); } } /** * Sorts the words in page 0, and shows them in page 2. */ void sortWords() { String editorText = editor.getDocumentProvider().getDocument(editor.getEditorInput()).get(); StringTokenizer tokenizer = new StringTokenizer(editorText, " \t\n\r\f!@#\u0024%^&*()-_=+`~[]{};:'\",.<>/?|\\"); ArrayList editorWords = new ArrayList(); while (tokenizer.hasMoreTokens()) { editorWords.add(tokenizer.nextToken()); } Collections.sort(editorWords, Collator.getInstance()); StringWriter displayText = new StringWriter(); for (int i = 0; i < editorWords.size(); i++) { displayText.write(((String) editorWords.get(i))); displayText.write(System.getProperty("line.separator")); } text.setText(displayText.toString()); } } MasterDetailsPage: public class MasterDetailsPage extends FormPage { private ScrolledPropertiesBlock block; public MasterDetailsPage(FormEditor editor) { super(editor, "fourth", "test"); //$NON-NLS-1$ //$NON-NLS-2$ block = new ScrolledPropertiesBlock(this); } protected void createFormContent(final IManagedForm managedForm) { final ScrolledForm form = managedForm.getForm(); //FormToolkit toolkit = managedForm.getToolkit(); form.setText("Test"); //$NON-NLS-1$ block.createContent(managedForm); } } The problem is in this method: void createMasterDetailPage() { int index = addPage(new MasterDetailsPage(this)); // ERROR setPageText(index, "Master Detail Page"); } How can I add the MasterDetailsPage to my MultiPageEditor? A: You normally use FormEditor rather than MultiPageEditorPart when using FormPage (FormEditor extends MultiPageEditorPart). FormEditor has an addPage that accepts a FormPage.
{ "language": "en", "url": "https://stackoverflow.com/questions/34400617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Upload,read and display the image with Tkinter and Opencv-Python I want to upload this file using tkinter method and read it using cv2.imread and display .But i have a problem,this is the code i am using: wid=Tk() def myown(): file = tkFileDialog.askopenfile(parent=wid,mode='rb',title='Choose a file') if file != None: data = file.read() b=cv2.imread(data) cv2.imshow('img',b) cv2.waitKey(0) file.close() after this, wid3=Button(None,text="upload it",command=myown) wid.mainloop but i am getting an opencv error,the image is not being displayed by the imshow,it says size.width>0 && size.height>0
{ "language": "en", "url": "https://stackoverflow.com/questions/36644511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not getting the right result in base64 string when I try to convert base64 encoded string EC Public Key generated on iOS to Java PublicKey As the title suggests I am trying to convert base64 encoded string (EC Public Key) generated on IOS device(Swift) to Java PublicKey which will be used to calculate a Shared Secret Key between two parties. There is neither runtime nor compile time exception/error in the code, it compiles and runs successfully and generates a PublicKey but when I encode the PublicKey (Base64.encodeToString(PublicKey.encoded), Base64.NO_WRAP) back to Base64 string to confirm whether I have gotten the same public key I have passed as an argument, they are not the same. import android.util.Base64 import org.bouncycastle.asn1.sec.SECNamedCurves import org.bouncycastle.math.ec.ECCurve import java.math.BigInteger import java.nio.charset.StandardCharsets import java.security.* import java.security.spec.* import javax.crypto.* import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec fun iosB64EncodedStrPKToPK(iOSB64EncodedPK: String): PublicKey { val decodedPK = Base64.decode(iOSB64EncodedPK, Base64.NO_WRAP) val x9ECParamSpec = SECNamedCurves.getByName("secp256r1") val curve = x9ECParamSpec.curve val point = curve.decodePoint(decodedPK) val xBcEC = point.affineXCoord.toBigInteger() val yBcEC = point.affineYCoord.toBigInteger() val gBcEC = x9ECParamSpec.g val xGBcEC = gBcEC.affineXCoord.toBigInteger() val yGBcEC = gBcEC.affineYCoord.toBigInteger() val hBcEC = x9ECParamSpec.h.toInt() val nBcEC = x9ECParamSpec.n val jPEC = ECPoint(xBcEC, yBcEC) val gJpEC = ECPoint(xGBcEC, yGBcEC) val jEllipticCurve = convertECCurveToEllipticCurve(curve, gJpEC, nBcEC, hBcEC) val eCParameterSpec = ECParameterSpec(jEllipticCurve, gJpEC, nBcEC, hBcEC) val ecPubLicKeySpec = ECPublicKeySpec(jPEC, eCParameterSpec) val keyFactorySpec = KeyFactory.getInstance("EC") return keyFactorySpec.generatePublic(ecPubLicKeySpec) } private fun convertECCurveToEllipticCurve( curve: ECCurve, ecPoint: ECPoint, n: BigInteger, h: Int ): EllipticCurve { val ecField = ECFieldFp(curve.field.characteristic) val firstCoefficient = curve.a.toBigInteger() val secondCoefficient = curve.b.toBigInteger() val ecParams = ECParameterSpec( EllipticCurve(ecField, firstCoefficient, secondCoefficient), ecPoint, n, h ) return ecParams.curve } The public key I am passing to the iosB64EncodedStrPKToPK() function: BAlWWu46il/ly6Axd/qclmhEVhGth93QN5+h3JBJEKEmhKd1LfqkpCqX1cT1cQDs9nPq9Lq0/FtZitkjr7Rqd94= The output I get: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAECVZa7jqKX+XLoDF3+pyWaERWEa2H3dA3n6HckEkQoSaEp3Ut+qSkKpfVxPVxAOz2c+r0urT8W1mK2SOvtGp33g== val pkIOS = "BAlWWu46il/ly6Axd/qclmhEVhGth93QN5+h3JBJEKEmhKd1LfqkpCqX1cT1cQDs9nPq9Lq0/FtZitkjr7Rqd94=" Log.i("SOME_TAG","PUBLIC_KEY_IOS:${Base64.encodeToString(iosB64EncodedStrPKToPK(pkIOS).encoded,Base64.NO_WRAP)}") I am not an expert on the matter, maybe someone may guide me in the right direction and can see the mistake I am making. Cryptography is out of my field expertise. I have tried Googling, ChatGPT and other insightful resources, if you know a source around the issue I would gladly accept it too. I am running the code in an Android Environment The version of BouncyCastle I am using: def bouncy_castle_version = '1.70' implementation "org.bouncycastle:bcpkix-jdk15on:$bouncy_castle_version" implementation "org.bouncycastle:bcprov-jdk15on:$bouncy_castle_version" A: The keys are identical, only their formats differ: * *The input BAlW... is an uncompressed public EC key (Base64 encoded). *The output MFkw... is an ASN.1/DER encoded key in X.509/SPKI format (Base64) encoded. This can be easily verified by encoding both keys not in Base64 but in hex: input : 0409565aee3a8a5fe5cba03177fa9c9668445611ad87ddd0379fa1dc904910a12684a7752dfaa4a42a97d5c4f57100ecf673eaf4bab4fc5b598ad923afb46a77de output: 3059301306072a8648ce3d020106082a8648ce3d0301070342000409565aee3a8a5fe5cba03177fa9c9668445611ad87ddd0379fa1dc904910a12684a7752dfaa4a42a97d5c4f57100ecf673eaf4bab4fc5b598ad923afb46a77de As can be seen, the ASN.1/DER encoded X.509/SPKI key contains the uncompressed public key at the end (the last 65 bytes). Background: Keep in mind that a public EC key is a point (x, y) on an EC curve (obtained by multiplying the private key by the generator point) and that there are different formats for its representation, e.g. the following two: * *The uncompressed format, which corresponds to the concatenation of a 0x04 byte, and the x and y coordinates of the point: 04|x|y. For the secp256r1 curve (aka prime256v1 aka NIST P-256), x and y are both 32 bytes, so the uncompressed key is 65 bytes. *The X.509/SPKI format as defined in RFC 5280. This format is described with ASN.1 and serialized/encoded with DER (s. here). PublicKey#getEncoded() returns the ASN.1/DER encoded X.509/SPKI key. With an ASN.1/DER parser the ASN.1/DER can be decoded, e.g. https://lapo.it/asn1js/.
{ "language": "en", "url": "https://stackoverflow.com/questions/75631098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can display text only when mouse over I have this sample: link CODE HTML: SED PERSPICIATIS Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. <div class="col-md-4 tab-bottom"> <div class="tab-bottom-img"><img width="380" height="380" src="http://dg-design.ch/bagel/wp-content/uploads/2016/02/1-380x380.png" class="attachment-news wp-post-image" alt="1"> </div> <div class="tab-bottom-content"> <div> <p class="title_bottom">SED PERSPICIATIS</p> <p class="content_bottom"></p><p> Sed ut perspiciatis unde omnis iste natus error sit<br> voluptatem accusantium doloremque laudantium,<br> totam rem aperiam, eaque ipsa quae ab illo inventore<br> veritatis et quasi architecto beatae vitae dicta sunt<br> explicabo. </p> <p></p> </div> </div> </div> <div class="col-md-4 tab-bottom"> <div class="tab-bottom-img"><img width="380" height="380" src="http://dg-design.ch/bagel/wp-content/uploads/2016/02/1-380x380.png" class="attachment-news wp-post-image" alt="1"> </div> <div class="tab-bottom-content"> <div> <p class="title_bottom">SED PERSPICIATIS</p> <p class="content_bottom"></p><p> Sed ut perspiciatis unde omnis iste natus error sit<br> voluptatem accusantium doloremque laudantium,<br> totam rem aperiam, eaque ipsa quae ab illo inventore<br> veritatis et quasi architecto beatae vitae dicta sunt<br> explicabo. </p> <p></p> </div> </div> </div> CODE CSS: .col-md-4 { width: 33.33333333%; } .tab-bottom { position: relative; height: 400px; float:left; } .tab-bottom-img { width: 100%; position: absolute; top: 50%; height: 100%; left: 50%; transform: translate(-50%, -50%); } .tab-bottom-content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } CODE JS: $(".tab-bottom").bind('mouseover',function(event){ $(this).find("tab-bottom-content").css("display", "block"); }); $('.tab-bottom-img').bind('mouseleave', function(e) { }); I want the text in the div tab-bottom-content to be displayed only when the mouse is over. I tried to use the script above but unfortunately does not work Can you help me to solve this problem? Thanks in advance! A: I would solve this using CSS instead. like this fiddle Example html: <div class=tab-bottom> <div class=tab-bottom-content> Test </div> </div> CSS: .tab-bottom{ border: 1px SOLID #F00; /* For display purpose */ width: 200px; height: 200px; } .tab-bottom.tab-bottom-content{ display: none; } .tab-bottom:hover .tab-bottom-content{ display: block; } There is no need for JavaScript or jQuery here :) A: You should initially hide .tab-bottom-content using display: none like following. .tab-bottom-content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: none } And the use following jQuery. You missed the . before tab-bottom-content $(".tab-bottom").mouseover(function(event){ $(this).find(".tab-bottom-content").show(300); }).mouseleave(function(e) { $(this).find(".tab-bottom-content").hide(300); }); A: You need '.' in this .find("tab-bottom-content") $(".tab-bottom").on('mouseover',function(event){ $(this).find(".tab-bottom-content").show(300); }); $('.tab-bottom').on('mouseleave', function(e) { $(this).find(".tab-bottom-content").hide(300); }); Here is the pen You must also add CSS .tab-bottom-content { display:none; } or inline style to hide the 'tab-bottom-content' content first A: You can set the opacity of the tab-bottom-content to 0 and then change it to 1 in its :hover pseudo-selector class so that the text appears when you hover over the tab-bottom-content div. You may even want to add a transition so that the opacity changes smoothly. Do this, .tab-bottom-content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid black; opacity: 0; transition: opacity .4s ease-in; } .tab-bottom-content:hover { opacity: 1 } Check it out https://jsfiddle.net/5s1fv2a9/
{ "language": "en", "url": "https://stackoverflow.com/questions/35255988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++: Storing user inputs I just want the user to enter some numbers. If the number is -1 the program stops and then outputs those same numbers. Why is that so difficult? I don't understand why the logic is not working here. For example when the user types: 1 2 3 -1 The program should then print out: 1 2 3 -1 #include <iostream> using namespace std; int main() { int input, index=0; int array[200]; do { cin >> input; array[index++]=input; } while(input>0); for(int i=0; i < index; i++) { cout << array[index] << endl; } } A: Change this for(int i=0; i < index; i++) { cout << array[index] << endl; } To for(int i=0; i < index; i++) { cout << array[i] << endl; } You used index at the seconde loop causing your program to print all the array cell's after the user input. Also, if -1 is your condition you should change it to } while(input>=0); ^^ Otherwise, also 0 will stop the loop, which is not what you asking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/17903852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sending email in Asp.net / C# with attachments - Issues with Gmail In an ASP/C# application I'm sending an email with 3 file attached. The 3 files are the same type, same extension and more or less same size ( but none are empty ). The email is sent correctly. If I open it using outlook, I have no problems. I can see the body, and the 3 files attached. But here is my issue: If I send that mail to a Gmail Adress, then on Gmail I can see only 2 attachments. And if I click on the download all attachment icon ( on the right ), it will download the 2 visible attachment + the third one but empty. It's a really weird issue. Also there is a 4th attachment which is an embedded image. And this image is display correctly in the mail body. Here is the code I'm using to send the mail: MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("SMTP_IP_ADRESS", SMTP_IP_PORT); mail.From = new MailAddress("[email protected]"); mail.To.Add("GMAIL_EMAIL"); mail.To.Add("OUTLOOK_EMAIL"); mail.Subject = "MSN "+Request.Params["nameMsn"]; Attachment imageAttachment = new Attachment(Server.MapPath(Url.Content("~/Content/images/image.png"))); string contentID = "logoCare"; imageAttachment.ContentId = contentID; mail.IsBodyHtml = true; mail.Body = "<html><body>Have a good day.<br/>Best regards. <br/><br/><img width='200' src=\"cid:" + contentID + "\"></body></html>"; for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; var attachment = new Attachment(file.InputStream, file.FileName, MediaTypeNames.Application.Octet); mail.Attachments.Add(attachment); } mail.Attachments.Add(imageAttachment); SmtpServer.Send(mail); A: The third attachment you see empty can possibly be the CID embedded image that web based email clients (like Gmail) can't manage, meanwhile it works with desktop email clients like Outlook. Can you verify this? Please take a look at here
{ "language": "en", "url": "https://stackoverflow.com/questions/59302730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Out of memory errors in Java API that uses finalizers in order to free memory allocated by C calls We have a Java API that is a wrapper around a C API. As such, we end up with several Java classes that are wrappers around C++ classes. These classes implement the finalize method in order to free the memory that has been allocated for them. Generally, this works fine. However, in high-load scenarios we get out of memory exceptions. Memory dumps indicate that virtually all the memory (around 6Gb in this case) is filled with the finalizer queue and the objects waiting to be finalized. For comparison, the C API on its own never goes over around 150 Mb of memory usage. Under low load, the Java implementation can run indefinitely. So this doesn't seem to be a memory leak as such. It just seem to be that under high load, new objects that require finalizing are generated faster than finalizers get executed. Obviously, the 'correct' fix is to reduce the number of objects being created. However, that's a significant undertaking and will take a while. In the meantime, is there a mechanism that might help alleviate this issue? For example, by giving the GC more resources. A: Java was designed around the idea that finalizers could be used as the primary cleanup mechanism for objects that go out of scope. Such an approach may have been almost workable when the total number of objects was small enough that the overhead of an "always scan everything" garbage collector would have been acceptable, but there are relatively few cases where finalization would be appropriate cleanup measure in a system with a generational garbage collector (which nearly all JVM implementations are going to have, because it offers a huge speed boost compared to always scanning everything). Using Closable along with a try-with-resources constructs is a vastly superior approach whenever it's workable. There is no guarantee that finalize methods will get called with any degree of timeliness, and there are many situations where patterns of interrelated objects may prevent them from getting called at all. While finalize can be useful for some purposes, such as identifying objects which got improperly abandoned while holding resources, there are relatively few purposes for which it would be the proper tool. If you do need to use finalizers, you should understand an important principle: contrary to popular belief, finalizers do not trigger when an object is actually garbage collected"--they fire when an object would have been garbage collected but for the existence of a finalizer somewhere [including, but not limited to, the object's own finalizer]. No object can actually be garbage collected while any reference to it exists in any local variable, in any other object to which any reference exists, or any object with a finalizer that hasn't run to completion. Further, to avoid having to examine all objects on every garbage-collection cycle, objects which have been alive for awhile will be given a "free pass" on most GC cycles. Thus, if an object with a finalizer is alive for awhile before it is abandoned, it may take quite awhile for its finalizer to run, and it will keep objects to which it holds references around long enough that they're likely to also earn a "free pass". I would thus suggest that to the extent possible, even when it's necessary to use finalizer, you should limit their use to privately-held objects which in turn avoid holding strong references to anything which isn't explicitly needed for their cleanup task. A: Phantom references is an alternative to finalizers available in Java. Phantom references allow you to better control resource reclamation process. * *you can combine explicit resource disposal (e.g. try with resources construct) with GC base disposal *you can employ multiple threads for postmortem housekeeping Using phantom references is complicated tough. In this article you can find a minimal example of phantom reference base resource housekeeping. In modern Java there are also Cleaner class which is based on phantom reference too, but provides infrastructure (reference queue, worker threads etc) for ease of use.
{ "language": "en", "url": "https://stackoverflow.com/questions/64264807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hibernate Search Error Can someone help, i'm trying a simple example with hibernate search but getting the following error: Exception in thread "main" org.hibernate.HibernateException: could not init listeners at org.hibernate.event.EventListeners.initializeListeners(EventListeners.java:205) at org.hibernate.cfg.Configuration.getInitializedEventListeners(Configuration.java:1396) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385) at FirstExample.main(FirstExample.java:32) Caused by: java.lang.NullPointerException at java.io.Reader.<init>(Reader.java:61) at java.io.InputStreamReader.<init>(InputStreamReader.java:55) at org.hibernate.search.util.HibernateSearchResourceLoader.getLines(HibernateSearchResourceLoader.java:52) at org.apache.solr.analysis.StopFilterFactory.inform(StopFilterFactory.java:53) at org.hibernate.search.impl.SolrAnalyzerBuilder.buildAnalyzer(SolrAnalyzerBuilder.java:79) at org.hibernate.search.impl.InitContext.buildAnalyzer(InitContext.java:185) at org.hibernate.search.impl.InitContext.initLazyAnalyzers(InitContext.java:155) at org.hibernate.search.impl.SearchFactoryImpl.initDocumentBuilders(SearchFactoryImpl.java:541) at org.hibernate.search.impl.SearchFactoryImpl.<init>(SearchFactoryImpl.java:171) at org.hibernate.search.event.ContextHolder.getOrBuildSearchFactory(ContextHolder.java:60) at org.hibernate.search.event.FullTextIndexEventListener.initialize(FullTextIndexEventListener.java:122) at org.hibernate.event.EventListeners$1.processListener(EventListeners.java:198) at org.hibernate.event.EventListeners.processListeners(EventListeners.java:181) at org.hibernate.event.EventListeners.initializeListeners(EventListeners.java:194) ... 3 more My Item Class: @Indexed @AnalyzerDef(name="customanalyzer", tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class), filters = { @TokenFilterDef(factory = ISOLatin1AccentFilterFactory.class), @TokenFilterDef(factory = LowerCaseFilterFactory.class), @TokenFilterDef(factory = StopFilterFactory.class, params = { @Parameter(name="words", value= "org/hibernate/search/test/analyzer/solr/stoplist.properties" ), @Parameter(name="ignoreCase", value="true") }) }) public class Item { @DocumentId private Integer id; @Field @Analyzer(definition = "customanalyzer") private String title; @Field @Analyzer(definition = "customanalyzer") private String description; @Field(index=Index.UN_TOKENIZED, store=Store.YES) private String ean; private String imageURL; //public getters and setters } Program code: Session session = null; Transaction tx = null; SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); session =sessionFactory.openSession(); FullTextSession ftem = org.hibernate.search.Search.getFullTextSession(session); ftem.beginTransaction(); List <Item> AllItem=session.createQuery("From Item").list(); for (Item item : AllItem) { ftem.index(item); } ftem.getTransaction().commit(); String searchQuery = "title:Batman"; QueryParser parser = new QueryParser( "title", ftem.getSearchFactory().getAnalyzer("customanalyzer") ); org.apache.lucene.search.Query luceneQuery; try { luceneQuery = parser.parse(searchQuery); } catch (ParseException e) { throw new RuntimeException("Unable to parse query: " + searchQuery, e); } org.hibernate.Query query = ftem.createFullTextQuery( luceneQuery, Item.class); query.setFirstResult(20).setMaxResults(20); List results = query.list(); A: It looks like Hibernate Search can't find org/hibernate/search/test/analyzer/solr/stoplist.properties in the classpath. Make sure it's there.
{ "language": "en", "url": "https://stackoverflow.com/questions/4906202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Efficient way to calculate average MAPE and MSE in R I have a real data and predicted data and I want to calculate overall MAPE and MSE. The data are time series, with each column representing data for different weeks. I predict value for each of the 52 weeks for each of the items as shown below. What would be the best possible calculate overall Error in R. real = matrix( c("item1", "item2", "item3", "item4", .5, .7, 0.40, 0.6, 0.3, 0.29, 0.7, 0.09, 0.42, 0.032, 0.3, 0.37), nrow=4, ncol=4) colnames(real) <- c("item", "week1", "week2", "week3") predicted = matrix( c("item1", "item2", "item3", "item4", .55, .67, 0.40, 0.69, 0.13, 0.9, 0.47, 0.19, 0.22, 0.033, 0.4, 0.37), nrow=4, ncol=4) colnames(predicted) <- c("item", "week1", "week2", "week3") A: How do you get the predicted values in the first place? The model you use to get the predicted values is probably based on minimising some function of prediction errors (usually MSE). Therefore, if you calculate your predicted values, the residuals and some metrics on MSE and MAPE have been calculated somewhere along the line in fitting the model. You can probably retrieve them directly. If the predicted values happened to be thrown into your lap and you have nothing to do with fitting the model, then you calculate MSE and MAPE as per below: You have only one record per week for every item. So for every item, you can only calculate one prediction error per week. Depending on your application, you can choose to calculate the MSE and MAPE per item or per week. This is what your data looks like: real <- matrix( c(.5, .7, 0.40, 0.6, 0.3, 0.29, 0.7, 0.09, 0.42, 0.032, 0.3, 0.37), nrow = 4, ncol = 3) colnames(real) <- c("week1", "week2", "week3") predicted <- matrix( c(.55, .67, 0.40, 0.69, 0.13, 0.9, 0.47, 0.19, 0.22, 0.033, 0.4, 0.37), nrow = 4, ncol = 3) colnames(predicted) <- c("week1", "week2", "week3") Calculate the (percentage/squared) errors for every entry: pred_error <- real - predicted pct_error <- pred_error/real squared_error <- pred_error^2 Calculate MSE, MAPE: # For per-item prediction errors apply(squared_error, MARGIN = 1, mean) # MSE apply(abs(pct_error), MARGIN = 1, mean) # MAPE # For per-week prediction errors apply(squared_error, MARGIN = 0, mean) # MSE apply(abs(pct_error), MARGIN = 0, mean) # MAPE
{ "language": "en", "url": "https://stackoverflow.com/questions/43402183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy nodes with changed element values XSLT I have input xml <?xml version="1.0" encoding="UTF-8"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1981</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1985</year> </cd> <cd> <title>Greatest Hits</title> <artist>Dolly Parton</artist> <country>USA</country> <company>RCA</company> <price>9.90</price> <year>1982</year> </cd> </catalog> How do the follow? For each "catalog/cd" 1) if "year" = '1985', then copy all elemets of "catalog/cd" without changed values 2) else copy all elements "catalog/cd" without changed values, exclude elements "company" (need to set value 'MyCompany') and "country" (need to set value 'MyCountry') Result XML <?xml version="1.0" encoding="UTF-8"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>MyCountry</country> <company>MyCompany</company> <price>10.90</price> <year>1981</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1985</year> </cd> <cd> <title>Greatest Hits</title> <artist>Dolly Parton</artist> <country>MyCountry</country> <company>MyCompany</company> <price>9.90</price> <year>1982</year> </cd> </catalog> A: There are different options to achieve what you need. You need to start with an identity template that would copy the input XML as is to output. <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()" /> </xsl:copy> </xsl:template> Next you can declare separate templates for modifying country and company where the year != 1985. <xsl:template match="cd[year != '1985']/country"> <country>MyCountry</country> </xsl:template> <xsl:template match="cd[year != '1985']/company"> <company>MyCompany</company> </xsl:template> Another option is to change the values of both elements in a single template cd whose child element year != 1985. <xsl:template match="cd[year != '1985']"> <xsl:copy> <xsl:apply-templates select="title | artist" /> <country>MyCountry</country> <company>MyCompany</company> <xsl:apply-templates select="price | year" /> </xsl:copy> </xsl:template> Hope this helps. However you need to go online and do some reading / hands on tutorials related to XSLT. A: <xsl:template match="catalog"> <catalog> <xsl:for-each select="cd"> <cd> <title> <xsl:value-of select="title"/> </title> <artist> <xsl:value-of select="artist"/> </artist> <xsl:choose> <xsl:when test="not(year = 1985)"> <country>MY Country</country> <company>My Company</company> </xsl:when> <xsl:otherwise> <country><xsl:value-of select="country"/></country> <company><xsl:value-of select="company"/></company> </xsl:otherwise> </xsl:choose> <price><xsl:value-of select="price"/></price> <year><xsl:value-of select="year"/></year> </cd> </xsl:for-each> </catalog> </xsl:template> Check it, I may be helful for you
{ "language": "en", "url": "https://stackoverflow.com/questions/51476738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mongodb query about listing one field as an array with all collections in detailed Assume I have db structure as; [ {name: "alex" , age: 21, school: "x university" }, {name: "felix" , age: 24, school: "y university" }, {name: "tom" , age: 43, school: "z university" } ] I want to write a query to get the details of the collection plus the array of the names. I mean as a result of the query I expect to get; details:[ {name: "alex" , age: 21, school: "x university" }, {name: "felix" , age: 24, school: "y university" }, {name: "tom" , age: 43, school: "z university" } ], names: ["alex", "felix", "tom"] To able to get the names as an array I wrote, db.colletion.aggregate([ {$group: {_id: "", names: {$addToSet : "$name"}}} ]) But this just prints the names as; { "_id" : "", "names" : [ "alex", "felix", "tom"] } In grouping I can project fields something like, db.colletion.aggregate([ {$group: {age: {$first: "$age"}, _id: "", names: {$addToSet : "$name"}}} ]) But this db is just an example, I have dynamic fields that I don't know in advanced. So how can I build this query?
{ "language": "en", "url": "https://stackoverflow.com/questions/44495413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between margin and padding in html? I have made a educational website and I am facing problem to set the paragraph block in the on the background page. So kindly help me. I was trying to manage the text on the background image but it was coming on the top-left of the image.
{ "language": "en", "url": "https://stackoverflow.com/questions/74687207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to calculate cubes and functions inside AnyLogic? I have a AnyLogic simulation which is set up to use system dynamic to calculate the power of a cyclist. For part of this I need to calculate the cube of a function and then "sin(tan^-1) of a function". Within a dynamic variable calculation I have tried this code: cube(double Velocity) and sin(atan(double Gradient)) However this is not working, any assistance would be appreciated. A: Quick glance at the help reveals the code you need. In your case: pow(velocity, 3) and sin(pow(tan(myValue), -1)) Please learn to use the help first. And also add what errors/problems you hit when you tried something already :)
{ "language": "en", "url": "https://stackoverflow.com/questions/67321860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: angular 2 *ngfor custom orderby causing chrome inspector to refresh constantly I have tried to make a custom orderBy pipe in angular 2 (ionic app) and for some reason, it's making the chrome inspector (maybe even the entire app) refresh constantly. <ion-card class="event" *ngFor="let position of positions | OrderBy : 'event.startDateTime'"> ... </ion-card> The event.startDateTime is format as such: "2017-05-26 00:00". I followed this answer: Angular 2 OrderBy Pipe to make this pipe. The only thing I've changed is using moment.js to turn a dateTime stamp into a unix timestamp static _orderByComparator(a: any, b: any): number { a = moment(a).unix(); b = moment(b).unix(); So, I'm not sure why it's doing this to chrome, and I'm wondering if anyone else has experienced this? full code below import { Pipe, PipeTransform } from "@angular/core"; import * as moment from 'moment'; //Angular 2 OrderBy Pipe @Pipe({ name: "OrderBy", pure: false }) export class OrderBy implements PipeTransform { value: string[] = []; static _orderByComparator(a: any, b: any): number { a = moment(a).unix(); b = moment(b).unix(); if (a === null || typeof a === "undefined") { a = 0; } if (b === null || typeof b === "undefined") { b = 0; } if ( (isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b)) ) { // Isn"t a number so lowercase the string to properly compare a = a.toString(); b = b.toString(); if (a.toLowerCase() < b.toLowerCase()) { return -1; } if (a.toLowerCase() > b.toLowerCase()) { return 1; } } else { // Parse strings as numbers to compare properly if (parseFloat(a) < parseFloat(b)) { return -1; } if (parseFloat(a) > parseFloat(b)) { return 1; } } return 0; // equal each other } public transform(input: any, config = "+"): any { if (!input) { return input; } // make a copy of the input"s reference this.value = [...input]; let value = this.value; if (!Array.isArray(value)) { return value; } if (!Array.isArray(config) || (Array.isArray(config) && config.length === 1)) { let propertyToCheck: string = !Array.isArray(config) ? config : config[0]; let desc = propertyToCheck.substr(0, 1) === "-"; // Basic array if (!propertyToCheck || propertyToCheck === "-" || propertyToCheck === "+") { return !desc ? value.sort() : value.sort().reverse(); } else { let property: string = propertyToCheck.substr(0, 1) === "+" || propertyToCheck.substr(0, 1) === "-" ? propertyToCheck.substr(1) : propertyToCheck; return value.sort(function(a: any, b: any) { let aValue = a[property]; let bValue = b[property]; let propertySplit = property.split("."); if (typeof aValue === "undefined" && typeof bValue === "undefined" && propertySplit.length > 1) { aValue = a; bValue = b; for (let j = 0; j < propertySplit.length; j++) { aValue = aValue[propertySplit[j]]; bValue = bValue[propertySplit[j]]; } } return !desc ? OrderBy._orderByComparator(aValue, bValue) : -OrderBy._orderByComparator(aValue, bValue); }); } } else { // Loop over property of the array in order and sort return value.sort(function(a: any, b: any) { for (let i = 0; i < config.length; i++) { let desc = config[i].substr(0, 1) === "-"; let property = config[i].substr(0, 1) === "+" || config[i].substr(0, 1) === "-" ? config[i].substr(1) : config[i]; let aValue = a[property]; let bValue = b[property]; let propertySplit = property.split("."); if (typeof aValue === "undefined" && typeof bValue === "undefined" && propertySplit.length > 1) { aValue = a; bValue = b; for (let j = 0; j < propertySplit.length; j++) { aValue = aValue[propertySplit[j]]; bValue = bValue[propertySplit[j]]; } } let comparison = !desc ? OrderBy._orderByComparator(aValue, bValue) : -OrderBy._orderByComparator(aValue, bValue); // Don"t return 0 yet in case of needing to sort by next property if (comparison !== 0) { return comparison; } } return 0; // equal each other }); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/43671449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP/MYSQL Query as a Function for Multi-Use I am trying to clean a ton of select queries inside about 15 pages of a website and I thought using a function that then I can use to call all the different queries and tables, would reduce the clutter a bunch. I am running into a problem and can't seem to figure out a way to get it right. Here is the function: function dbGet($conn, $table, $select, $where, $cond) { require($conn); if ( $stmt = $db->prepare(" SELECT $select FROM `" . $table . "` WHERE $where=? ")) { $stmt->bind_param("i", $cond); $stmt->execute(); $result = $stmt->get_result(); $rowNum = $result->num_rows; if ( $rowNum > 0 ) { while( $data = $result->fetch_assoc() ){ return $data; } } $stmt->close(); } else { die($db->error); } $db->close(); } And here is how I call the function in the various different pages: $settings = dbGet('php/connect.php', 'settings', '*', 'userId', $sessionId); echo $settings->toName; The problem I am running into, is that it is only displaying the first record from the settings table. I thought using the while loop in the function would return all the records. As a matter of fact, if I do a print_r for $data instead of return, I get all the records. How can I pass along all the records into the return $data to be access in any other page? OR If you guys happen to have any suggestions of an existing function that is highly regarded and true-and-tested that I can implement instead of writing my own, please let me know. Thanks. A: When return is triggered, the function ends and every other line of code after it is not executed. If you want to delay the return of your data until later in the function, then create a variable, assign value(s), and return the variable when you're ready. For example, you can adapt your code to create an array for $data, like so: function dbGet($conn, $table, $select, $where, $cond) { $data = array(); ... while ( $row = $result->fetch_assoc() ) { $data[] = $row; } $stmt->close(); ... $db->close(); return $data; }
{ "language": "en", "url": "https://stackoverflow.com/questions/45282796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R create multiple variables with one condition Is there a simpler way to write it,create multiple variables for one condition? like this if am == 1 then do; a=""; b=""; c=; end; else if am == 0 then do; ... end; The following is the R code I wrote library(dplyr) dt1 <- mtcars dt2 <- dt1 %>% mutate(a = case_when(am == 1 ~ "a1", am == 0 ~ "a2", am == 2 ~ "a3"), b = case_when(am == 1 ~ "a2", am == 0 ~ "a2", am == 2 ~ "a2"), c = case_when(am == 1 ~ 0, am == 0 ~ 1, am == 2 ~ 2)) A: lookup <- data.frame( am = c(1, 0, 2), a = c('a1', 'a2', 'a3'), b = 'a2', c = c(0, 1, 2) ) left_join(dt1, lookup, 'am')
{ "language": "en", "url": "https://stackoverflow.com/questions/72166768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I get rid of this error: error: unreported exception FileNotFoundException; Here's my code. I have to write it without using the FileNotFoundException class. The code reads from a file which contains array info. I get the this error: F:\FanClub.java:59: error: unreported exception FileNotFoundException; must be caught or declared to be thrown Scanner inputFile = new Scanner(file); Thanks import java.util.Scanner; import java.util.ArrayList; import java.io.*; public class FanClub { private static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) throws IOException { final int NUM_FANS = 100; int numFans = 0; int[] ages = new int[NUM_FANS]; String[] names = new String[NUM_FANS]; numFans = fillArrays(names, ages, NUM_FANS); } public static int fillArrays(String[] names, int[] ages, int NUM_FANS) { int counter = 0; System.out.print("Enter the file name: "); String fileName = keyboard.nextLine(); File file = new File(fileName); Scanner inputFile = new Scanner(file); if (!file.exists()) { System.out.println("File " + fileName + " not found."); System.exit(0); } int[] numFans = new int[NUM_FANS]; while (inputFile.hasNext() && counter < numFans.length) { numFans[counter] = inputFile.nextInt(); counter++; } inputFile.close(); return counter; } } A: Try to do this instead: File file = null; try { file = new File(fileName); Scanner inputFile = new Scanner(file); } catch(IOException ioe) // should actually catch FileNotFoundException instead { System.out.println("File " + fileName + " not found."); System.exit(0); } A: As I tried to explain in the comments, you're reading the file in the wrong order. You say your file looks like this: Chris P. Cream 5 Scott Free 9 Lou Tenant 3 Trish Fish 12 Ella Mentry 4 Holly Day 3 Robyn DeCradle 12 Annette Funicello 4 Elmo 7 Grover 3 Big Bird 9 Bert 7 Ernie 3 You're just calling inputFile.nextInt(), which attempts to read an int, but "Chris P. Cream" is not an int, which is why you're getting that input mismatch exception. So first you need to read the name, then you can read that number. Now, since it isn't clear how your text file is delimited (it's all on one line), this presents a problem because the names can be one, two, or even three words, and are followed by a number. You can still do this, but you'll need a regular expression that tells it to read up to that number. while (inputFile.hasNext() && counter < numFans.length) { names[counter] = inputFile.findInLine("[^\\d]*").trim(); numFans[counter] = inputFile.nextInt(); System.out.println(names[counter] + ": " + numFans[counter]); counter++; } However, if your file is actually formatted like this (separate lines): Chris P. Cream 5 Scott Free 9 Lou Tenant 3 Trish Fish 12 Ella Mentry 4 Holly Day 3 Robyn DeCradle 12 Annette Funicello 4 Elmo 7 Grover 3 Big Bird 9 Bert 7 Ernie 3 Then you're in luck, because you can do this instead (doesn't require a regular expression): while (inputFile.hasNext() && counter < numFans.length) { names[counter] = inputFile.nextLine(); numFans[counter] = inputFile.nextInt(); if (inputFile.hasNext()) inputFile.nextLine(); // nextInt() will read a number, but not the newline after it System.out.println(names[counter] + ": " + numFans[counter]); counter++; } What did Ernie say when Bert asked if he wanted icecream? Sure Bert.
{ "language": "en", "url": "https://stackoverflow.com/questions/18500920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read and write into a txt file using VB.NET with words in between I want to open a txt file and write into it numbers from 1 to 100 and put between every number enter. A: One way you could try is to write the numbers into a StringBuilder and then use it's ToString() method to get the resulting text: Imports System.IO Imports System.Text Public Class NumberWriter Private ReadOnly OutputPath as String = _ Path.Combine(Application.StartupPath, "out.txt") Public Sub WriteOut() Dim outbuffer as New StringBuilder() For i as integer = 1 to 100 outbuffer.AppendLine(System.Convert.ToString(i)) Next i File.WriteAllText(OutputPath, outbuffer.ToString(), true) End Sub Public Shared Sub Main() Dim writer as New NumberWriter() Try writer.WriteOut() Catch ex as Exception Console.WriteLine(ex.Message) End Try End Sub End Class A: There's a good example over at Home and Learn Dim FILE_NAME As String = "C:\test2.txt" If System.IO.File.Exists(FILE_NAME) = True Then Dim objWriter As New System.IO.StreamWriter(FILE_NAME) objWriter.Write(TextBox1.Text) objWriter.Close() MsgBox("Text written to file") Else MsgBox("File Does Not Exist") End If A: You could also use the "My.Computer.FileSystem" namespace, like: Dim str As String = "" For num As Int16 = 1 To 100 str += num.ToString & vbCrLf Next My.Computer.FileSystem.WriteAllText("C:\Working\Output.txt", str, False) A: See System.IO namespace, especially the System.IO.File class.
{ "language": "en", "url": "https://stackoverflow.com/questions/3122370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why would one want to predefine a template parameter type in C++? I was writing some code for a project, and I was using a library named APA102. In this library, there is a class titled APA102 defined as follows, template<uint8_t dataPin, uint8_t clockPin> class APA102 : public APA102Base { ... I am confused why anyone would use a template class to define a value that could have easily been passed as a class constructor parameter. And to extend on my original question, I was attempting to create a class method that used this APA102 class as a parameter, but I was not able to define a parameter as this type if I tried to do as follows: void someMethod(APA102<uint8_t, uint8_t> &param) As I kept getting the error error: type/value mismatch at argument 1 in template parameter list for 'template<unsigned char dataPin, unsigned char clockPin> class Pololu::APA102' virtual void someMethod(APA102<const uint8_t, const uint8_t> &ledStrip) = 0; The only way I could have an APA102 object as a parameter was to define two uint8_t values, and use those as the template parameters first. For example, this worked: const uint8_t clockPin = 11; const uint8_t dataPin = 12; virtual void someMethod(APA102<clockPin, dataPin> &ledStrip) = 0; Can anyone help me understand these template classes with predefined template parameters? Why did I get the error I did?
{ "language": "en", "url": "https://stackoverflow.com/questions/63006650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: throw MissingPluginException('No implementation found for method $method on channel $name'); i have a flutter app and i use google sign in with Firebase, but i run app and click in sign in button there is an error while debug if (result == null) { if (missingOk) { return null; } throw MissingPluginException('No implementation found for method $method on channel $name'); } return codec.decodeEnvelope(result) as T?; } any help please? A: It's Solve is so easy just stop your app and run it again i hope this is useful
{ "language": "en", "url": "https://stackoverflow.com/questions/66931606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the difference between minmax() and clamp() in CSS? Both CSS functions clamp the value between an upper and lower bound. The only difference that I know is that minmax() can only be used in CSS grid. A: From developer.mozilla.org: clamp() enables selecting a middle value within a range of values between a defined minimum and maximum. It takes three parameters: a minimum value, a preferred value, and a maximum allowed value. minmax() only accepts the two extreme values, plus the difference that you already mentioned. A: minmax() may only be used in Grid and picks between two (2) parameters. clamp() can be used anywhere in CSS and picks between three (3) parameters: minimum, preferred, and maximum, selecting the middle (preferred) parameter when possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/67821560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does dup work on jagged arrays? I would expect it to duplicate only nested arrays slices instead of the whole deep copy of array, but suddenly I've got a doubt. A: ratchet freak is right, it is a shallow copy. You can see the source to the dup function in dmd2/src/druntime/src/rt/lifetime.d. The function is called _adDupT. It is a pretty short function where the main work is a call to memcpy(). Above the function, you can see a representation of an array: struct { size_t length; void* ptr; } A jagged array would be an array of arrays, so the memory would look like [length0, ptr0, length1, ptr1, length2, ptr2....] Since memcpy over those pointers doesn't follow them, that means slice.dup is a shallow copy. This is generally true with anything that copies slices, it is always shallow copies unless you do something yourself. So struct A {char[] str; } A a, b; a = b; would also shallow copy, so assert(a.str is b.str). If you want to do a deep copy, the simplest way is to just loop over it: T[][] newArray; foreach(item; oldArray) newArray ~= item.dup; (you can also preallocat newArray.length = oldArray.length and assign with indexes if you want to speed it up a bit) A deep copy of a struct could be done with compile time reflection, though I prefer to write a clone method or something in there since it is a bit more clear. I'm not aware of a phobos function with this premade.
{ "language": "en", "url": "https://stackoverflow.com/questions/19244350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to correctly use PLAY_VIDEO in Mirror API I've been playing around with the Google Glass Mirror API and want to be able to stream a video. This is the Python code snippet I tried: def _insert_item_video_stream(self): """Insert a timeline item with streaming video.""" logging.info('Inserting timeline item with streaming video') body = { 'notification': {'level': 'DEFAULT'}, 'menuItems' : [{'action' : 'PLAY_VIDEO'}, {'payload' : 'https://eye-of-the-hawk.appspot.com/static/videos/waterfall.mp4'}], } self.mirror_service.timeline().insert(body=body).execute() return 'A timeline item with streaming video has been inserted.' However, the video was just blank. Any ideas would be super helpful! A: Was able to fix this after removing two brackets! Oh, Python. :/ This is the fixed line: 'menuItems' : [{'action' : 'PLAY_VIDEO', 'payload' : 'https://eye-of-the-hawk.appspot.com/static/videos/waterfall.mp4'}],
{ "language": "en", "url": "https://stackoverflow.com/questions/18833359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Light UIAlertView/UIActionView customization Would this type of customization be considered App Store safe ? UIColor *veBlueColor = [UIColor colorWithRed:3.0/255.0 green:147.0/255.0 blue:215.0/255.0 alpha:1]; UIColor *veRedColor = [UIColor colorWithRed:242.0/255.0 green:93.0/255.0 blue:69.0/255.0 alpha:1]; for (UIView *subview in actionSheet.subviews) { if ([subview isKindOfClass:[UIButton class]]) { UIButton *button = (UIButton*)subview; UIColor *buttonColor = [button titleColorForState:UIControlStateNormal]; NSString *buttonColorString = [buttonColor description]; UIColor *destructiveColor = [UIColor colorWithRed:0.992157 green:0.278431 blue:0.168627 alpha:1]; NSString *destructiveColorString = [destructiveColor description]; bool isDestructiveButton = ([buttonColorString isEqual:destructiveColorString]?YES:NO); if (!isDestructiveButton) { [button setTitleColor:veBlueColor forState:UIControlStateNormal]; } else { [button setTitleColor:veRedColor forState:UIControlStateNormal]; } } } I have read the Human Interface Guidelines but there are always "gray areas" and a google search returns quite a few people claiming they got there App approved with customizations that are clearly not allowed by Apple. So my question is, what are your experiences are with "light" customization ? A: No in my opinion it's not safe. The Apple documentation clearly states: "UIActionSheet is not designed to be subclassed, nor should you add views to its hierarchy. If you need to present a sheet with more customization than provided by the UIActionSheet API, you can create your own and present it modally with presentViewController:animated:completion:." In this case you're not adding subviews but you're actually retrieving the ones that are already there and customising them - which from an Apple perspective I assume is quite similar. I would suggest creating your own ActionSheet if the UIActionSheet API is too restrictive for what you need. (I recommend having a look on Git Hub as there are different solutions that might be a good fit for you).
{ "language": "en", "url": "https://stackoverflow.com/questions/21329590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to keep folder structure while share common code across projects in git? I have the following directory structure that I'd like to keep it while share some of the directories across different projects. I'd like to achieve something like this: root |_dir1 (git repo1) |_dir2 (git repo1) |_dir3 (git repo1) |_project<n> (git repo2 contains project specific code in different branches, e.g. project1's code in branch1 and project2's code in branch2, etc.) dir1...3 are common code shared across different projects and I'd like to keep the folder structure unchanged. I'm thinking about using git submodules but not sure how to do it. Is it possible to put dir1...3 in git repo1, as a submodule, then all project codes in project folder in git repo2, which is the main git repo that hosts git repo1 as the submodule? A: Is it possible to put dir1...3 in git repo1, as a submodule, then all project codes in project folder in git repo2, which is the main git repo that hosts git repo1 as the submodule? That's totally feasible. But the .git of the master project have to be in the root directory (it's up to you to say if it's good for you or not), since submodules have to be located inside the repo's path (which is defined by the location of the .git folder). From root : git init git submodule add <remote_url> dir1 git submodule add <remote_url> dir2 git submodule add <remote_url> dir3 mkdir project<n> git submodule update --init --recursive git commit -m "Added the submodule to the project."
{ "language": "en", "url": "https://stackoverflow.com/questions/70784537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ProgrammingError - sqlalchemy - on_conflict_do_update Following this question: As Ilja Everilä mentioned in his answer, I created a table object: from sqlalchemy import * metadata = MetaData() idTagTable = Table('id_tag', metadata, Column('id', String(255), primary_key = True), Column('category', String(20), nullable = False), Column('createddate', Date, nullable = False), Column('updatedon', Date, nullable = False) ) After creating a table object, I changed insert and update statements: insert_statement = sqlalchemy.dialects.postgresql.insert(idTagTable) upsert_statement = insert_statement.on_conflict_do_update( constraint=PrimaryKeyConstraint('id'), set_={"updatedon": insert_statement.excluded.updateon, "category":insert_statement.excluded.category} ) insert_values = df.to_dict(orient='records') conn.execute(upsert_statement, insert_values) Now I am getting Programming Error: Traceback (most recent call last): File "<ipython-input-66-0fc6a1bf9c6b>", line 7, in <module> conn.execute(upsert_statement, insert_values) File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute return meth(self, multiparams, params) File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement compiled_sql, distilled_params File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context context) File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception exc_info File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1159, in _execute_context context) File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 467, in do_executemany cursor.executemany(statement, parameters) ProgrammingError: (psycopg2.ProgrammingError) syntax error at or near ")" LINE 1: ...category) VALUES ('sports') ON CONFLICT () DO UPDAT... ^ Not Able to understand why I am getting this error. A: The PrimaryKeyConstraint object you're using as constraint= argument is not bound to any table and would seem to produce nothing when rendered, as seen in ON CONFLICT (). Instead pass the primary key(s) of your table as the conflict_target and Postgresql will perform unique index inference: upsert_statement = insert_statement.on_conflict_do_update( constraint=idTagTable.primary_key, set_={"updatedon": insert_statement.excluded.updateon, "category":insert_statement.excluded.category} )
{ "language": "en", "url": "https://stackoverflow.com/questions/49915990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Receive formatted 'multipart/form-data' response in Angular 7.x I am developing an Angular application that shows some images to the user. I would like to obtain those images from a single REST call to a web service: given the fact i am already uploading the images via a FormData object, i would like to receive those images in the same way (so, basically, via content-type: multipart/form-data). At the moment, using the following code: this.http.post('api/load', {}, {headers: {'Accept': 'multipart/form-data'}, responseType:'text', observe: 'response'}); i am actually receiving the full body of the response in a text format, like this: --974b5730-ab25-4554-8a69-444664cab379 Content-Disposition: form-data; name=result {"bar":[1,2,3,4], "foo": true} --974b5730-ab25-4554-8a69-444664cab379 Content-Disposition: form-data; name=image; filename=image1.jpg; filename*=utf-8''image1.jpg --- binarycontent... But it's in a raw, text format. How can i receive a multipart/form-data response formatted by its boundaries, or a in clean way in Angular 7.x? A: One of the solution is to implement an interceptor service where you can format multipart/form-data response. For example, your inteceptor will be - multipart.interceptor.ts : @Injectable() export class MultipartInterceptService implements HttpInterceptor { private parseResponse(response: HttpResponse<any>): HttpResponse<any> { const headerValue = response.headers.get('Content-Type'); const body = response.body; const contentTypeArray = headerValue ? headerValue.split(';') : []; const contentType = contentTypeArray[0]; switch (contentType) { case 'multipart/form-data': if (!body) { return response.clone({ body: {} }); } const boundary = body?.split('--')[1].split('\r')[0]; const parsed = this.parseData(body, boundary); // function which parse your data depends on its content (image, svg, pdf, json) if (parsed === false) { throw Error('Unable to parse multipart response'); } return response.clone({ body: parsed }); default: return response; } } // intercept request and add parse custom response public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(customRequest).pipe( map((response: HttpResponse<any>) => { if (response instanceof HttpResponse) { return this.parseResponse(response); } }) ); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/54713717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }