Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
I found a solution on Stack Overflow for Java program run configurations which also works for JUnit run configurations.
You can get the full command executed by your configuration on the Debug tab, or more specifically the Debug view.
- Run your application
- Go to your Debug perspective
- There should be an entry in there (in the Debug View) for the app you've just executed
- Right-click the node which references java.exe or javaw.exe and select Properties In the dialog that pops up you'll see the Command Line which includes all jars, parameters, etc
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:
#include <stdio.h> #include <stdlib.h> void outchar(char ch); int main() { outchar('A'); outchar('B'); outchar('C'); return 0; } void outchar(char ch) { printf("%c", ch); }
Also, you should be specifying the return type of every function. I added that for you.
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
The difference between pointers and references is quite simple: a pointer can be null, a reference can not.
Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).
Here it looks like references are more appropriate.
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task
or Task<T>
, if you return nothing and you want your method will be run asyncronously you should define your method like this:
private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); }
And in Main method you can't await for DoDownloadAsync
, because you can't use await keyword in non-async function, and you can't make Main
async. So consider this:
var result = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); result.Wait();
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
Instead of using the placeholder text, you'll want to set the actual text
property of the field to MM/YYYY, set the delegate of the text field and listen for this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // update the text of the label }
Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
Unless the role was made dbo, db_owner or db_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:
GRANT ALL ON table1 TO doctor
Users in that role will have no permissions whatsoever to other tables (not even read).
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
You can use Jquery's on method and listen for the scroll
event.
The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:
<ul> {% for page in site.pages %} {% if page.title != 'index' %} <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li> {% endif %} {% endfor %} </ul>
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
I'm not sure what you're trying to do, but here's something to consider: c();
won't do anything. c
is an instance of the class checkbox
and not a method to be called. So consider this:
public class FirstWindow extends JFrame { public FirstWindow() { checkbox c = new checkbox(); c.yourMethod(yourParameters); // call the method you made in checkbox } } public class checkbox extends JFrame { public checkbox(yourParameters) { // this is the constructor method used to initialize instance variables } public void yourMethod() // doesn't have to be void { // put your code here } }
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
The problem might be your split()
call. Try just split(" ")
without the square brackets.
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
The folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
From the docs:
_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.
So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.
Edit: Further reading led me here:
http://www.analyticsmarket.com/blog/edit-ecommerce-data
Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.
DateTime
inherits its equals
method from AbstractInstant
. It is implemented as such
public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); }
Notice the last line comparing chronology. It's possible your instances' chronologies are different.
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
Small update: Incase if you get below error in regard to node-sass follow the steps given below.
code EPERM
npm ERR! syscall unlink
steps to solve the issue:
I found that
Build Active Architecture Only
set to YES
for everything, in both Project and Targetpodfile
:post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings["ONLY_ACTIVE_ARCH"] = "YES"
end
end
end
worked for me.
We had both Pods and SPM and they didn't work with any of the combinations of other answers. My colleagues all use Intel MacBooks and we haven't tested this config on their computers, though.
I do not think the warnings you have received are related. I had the same warnings which turned out to be the chrome extension React Dev Tools. Removed the extension and the errors have gone.
For me I was working under Ubuntu
The error disappeared if I use sudo with ng
sudo ng build
sudo ng serve
These issue arise generally due to mismatch between @ngx-translate/core version and Angular .Before installing check compatible version of corresponding ngx_trnalsate/Core, @ngx-translate/http-loader and Angular at https://www.npmjs.com/package/@ngx-translate/core
Eg: For Angular 6.X versions,
npm install @ngx-translate/core@10 @ngx-translate/http-loader@3 rxjs --save
Like as above, follow below command and rest of code part is common for all versions(Note: Version can obtain from( https://www.npmjs.com/package/@ngx-translate/core)
npm install @ngx-translate/core@version @ngx-translate/http-loader@version rxjs --save
I had this error when i deleted several components while the server was on(after running the ng serve command). Although i deleted the references from the routes component and module, it didnt solve the problem. Then i followed these steps:
In my case the tensorflow install was looking for cudart64_101.dll
The 101 part of cudart64_101 is the Cuda version - here 101 = 10.1
I had downloaded 11.x, so the version of cudart64 on my system was cudart64_110.dll
This is the wrong file!! cudart64_101.dll ? cudart64_110.dll
Download Cuda 10.1 from https://developer.nvidia.com/
Install (mine crashes with NSight Visual Studio Integration, so I switched that off)
When the install has finished you should have a Cuda 10.1 folder, and in the bin the dll the system was complaining about being missing
Check that the path to the 10.1 bin folder is registered as a system environmental variable, so it will be checked when loading the library
You may need a reboot if the path is not picked up by the system straight away
I add the following code to my pom.xml
file. It solved my problem.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
So I've gone through all the steps here, but non helped.
TLDR; run npx --ignore-existing create-react-app
I am on a Mac with Mojave 10.15.2
CRA was not installed globally - didn't find it in /usr/local/lib/node_modules
or /usr/local/bin
either.
Then I came across this comment on CRA's github issues. Running the command with the --ignore-existing
flag helped.
If you are testing on localhost and you have no control of the response headers, you can disable it with a chrome flag.
Visit the url and disable it: chrome://flags/#same-site-by-default-cookies
I need to disable it because Chrome Canary just started enforcing this rule as of approximately V 82.0.4078.2 and now it's not setting these cookies.
Note: I only turn this flag on in Chrome Canary that I use for development. It's best not to turn the flag on for everyday Chrome browsing for the same reasons that google is introducing it.
I faced this error several times and, it was due to transferring large resources(larger than 3MB) from server to client.
I don't know whether this has appeared obvious here. I would like to point out that as far as client-side (browser) JavaScript is concerned, you can add type="module"
to both external as well as internal js scripts.
Say, you have a file 'module.js':
var a = 10;
export {a};
You can use it in an external script, in which you do the import, eg.:
<!DOCTYPE html><html><body>
<script type="module" src="test.js"></script><!-- Here use type="module" rather than type="text/javascript" -->
</body></html>
test.js:
import {a} from "./module.js";
alert(a);
You can also use it in an internal script, eg.:
<!DOCTYPE html><html><body>
<script type="module">
import {a} from "./module.js";
alert(a);
</script>
</body></html>
It is worthwhile mentioning that for relative paths, you must not omit the "./" characters, ie.:
import {a} from "module.js"; // this won't work
For those can not create PHP session and working with live domain at local. You should delete live sites secure cookie first.
Full answer ; https://stackoverflow.com/a/64073275/1067434
I was facing same problem when I installed JRE by Oracle and solved this problem after my research.
I moved the environment path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
below H:\Program Files\Java\jdk-13.0.1\bin
Like this:
Path
H:\Program Files\Java\jdk-13.0.1\bin
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
OR
Path
%JAVA_HOME%
%JRE_HOME%
I just got a similar error for the first time today. It appears in \node_modules\metro-config\src\defaults\blacklist.js
, there is an invalid regular expression that needed changed. I changed the first expression under sharedBlacklist
from:
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
to:
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
I solved my problem by running below command
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
This works fine for me, and no more errors.
mongoose
.connect(URL_of_mongodb, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log('DB Connected!'))
.catch(err => {
console.log(`DB Connection Error: ${err}`);
});
I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the pagefile size, as it was a Memory overcommitment problem for me too.
Windows 8
Windows 10
Note: I did not have the enough memory on my system for the ~282GB in this example but for my particular case this worked.
EDIT
From here the suggested recommendations for page file size:
There is a formula for calculating the correct pagefile size. Initial size is one and a half (1.5) x the amount of total system memory. Maximum size is three (3) x the initial size. So let's say you have 4 GB (1 GB = 1,024 MB x 4 = 4,096 MB) of memory. The initial size would be 1.5 x 4,096 = 6,144 MB and the maximum size would be 3 x 6,144 = 18,432 MB.
Some things to keep in mind from here:
However, this does not take into consideration other important factors and system settings that may be unique to your computer. Again, let Windows choose what to use instead of relying on some arbitrary formula that worked on a different computer.
Also:
Increasing page file size may help prevent instabilities and crashing in Windows. However, a hard drive read/write times are much slower than what they would be if the data were in your computer memory. Having a larger page file is going to add extra work for your hard drive, causing everything else to run slower. Page file size should only be increased when encountering out-of-memory errors, and only as a temporary fix. A better solution is to adding more memory to the computer.
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
Perhaps many of the previous solutions are no longer working. For example, this bellow code continues to create new code cells in Colab, working though. Undoubtedly, creating a bunch of code cells is an inconvenience. If too many code cells are created in some hours of running and there is no enough RAM, the browser may freeze.
This repetedly creates code cells—
function ClickConnect(){
console.log("Working");
document.querySelector("colab-toolbar-button").click()
}setInterval(ClickConnect,60000)
But I found the code below is working, it doesn't cause any problems. In the Colab notebook tab, click on the Ctrl + Shift + i
key simultaneously and paste the below code in the console. 120000 intervals are enough.
function ClickConnect(){
console.log("Working");
document.querySelector("colab-toolbar-button#connect").click()
}setInterval(ClickConnect,120000)
I have tested this code in firefox, in November 2020. It will work on chrome too.
I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.
First, define this function to use:
const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }
In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T
before T extends object
you break the no-use-before-define
rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>
).
Anyways, with those modifications you can just use it like this:
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
getKeyValue(user, "name")
Which, again, I find to be a bit more readable.
I was having this problem after I installed the dotnet-ef tool using Ansible with sudo escalated previllage on Ubuntu. I had to add become: no for the Playbook task, then the dotnet-ef tool became available to the current user.
- name: install dotnet tool dotnet-ef
command: dotnet tool install --global dotnet-ef --version {{dotnetef_version}}
become: no
As far as I can tell, this was caused by a conflict with the version of Python 3.7 that was recently added into the Windows Store. It looks like this added two "stubs" called python.exe and python3.exe into the %USERPROFILE%\AppData\Local\Microsoft\WindowsApps
folder, and in my case, this was inserted before my existing Python executable's entry in the PATH
.
Moving this entry below the correct Python folder (partially) corrected the issue.
The second part of correcting it is to type manage app execution aliases
into the Windows search prompt and disable the store versions of Python altogether.
It's possible that you'll only need to do the second part, but on my system I made both changes and everything is back to normal now.
it is because view child require two argument try like this
@ViewChild('nameInput', { static: false, }) nameInputRef: ElementRef;
@ViewChild('amountInput', { static: false, }) amountInputRef: ElementRef;
The comment by @xicocaio should be highlighted.
tkinter is python version-specific in the sense that sudo apt-get install python3-tk
will install tkinter exclusively for your default version of python. Suppose you have different python versions within various virtual environments, you will have to install tkinter for the desired python version used in that virtual environment. For example, sudo apt-get install python3.7-tk
. Not doing this will still lead to No module named ' tkinter'
errors, even after installing it for the global python version.
According to Apple's session on "Implementing Dark Mode on iOS" (https://developer.apple.com/videos/play/wwdc2019/214/ starting at 31:13) it is possible to set overrideUserInterfaceStyle
to UIUserInterfaceStyleLight
or UIUserInterfaceStyleDark
on any view controller or view, which will the be used in the traitCollection
for any subview or view controller.
As already mentioned by SeanR, you can set UIUserInterfaceStyle
to Light
or Dark
in your app's plist file to change this for your whole app.
I know this will not work for everyone, but I thought it interesting that just adding a Divider solves for this.
struct DividerTest: View {
var body: some View {
VStack(alignment: .leading) {
Text("Foo")
Text("Bar")
Divider()
}.background(Color.red)
}
}
CORS headers should be sent from the server. If you use PHP it will be like this:
header('Access-Control-Allow-Origin: your-host');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: your-methods like POST,GET');
header('Access-Control-Allow-Headers: content-type or other');
header('Content-Type: application/json');
Here is the solution for Objective-C
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ViewController *vc = [storyBoard instantiateViewControllerWithIdentifier:@"ViewController"];
vc.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:vc animated:YES completion:nil];
Another one solution can be used for class components - just override default MUI Theme properties with MuiThemeProvider. This will give more flexibility in comparison with other methods - you can use more than one MuiThemeProvider inside your parent component.
simple steps:
please, check this doc for more details: https://material-ui.com/customization/theming/
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import { MuiThemeProvider } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';
const InputTheme = createMuiTheme({
overrides: {
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
}
});
class HigherOrderComponent extends React.Component {
render(){
const { classes } = this.props;
return (
<MuiThemeProvider theme={InputTheme}>
<Button className={classes.root}>Higher-order component</Button>
</MuiThemeProvider>
);
}
}
HigherOrderComponent.propTypes = {
classes: PropTypes.object.isRequired,
};
export default HigherOrderComponent;
_x000D_
On my side it was package
@angular-devkit/build-angular
and
@angular-devkit/build-ng-packagr
was not the same version, Updating build-ng-packagr
to same version as build-angular
fixed my problem.
Problem occurs when we want to import CommonJS module into ES6 module codebase.
Before these flags we had to import CommonJS modules with star (* as something
) import:
// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec
// transpiled js (simplified):
const moment = require("moment");
moment();
We can see that *
was somehow equivalent to exports
variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment
in our case) can be only a plain object, not callable (moment()
is not allowed).
With flag esModuleInterop
we can import CommonJS modules in compliance with es6
modules spec. Now our import code looks like this:
// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec
// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();
It works and it's perfectly valid with es6 modules spec, because moment
is not namespace from star import, it's default import.
But how does it work? As you can see, because we did a default import, we called the default
property on a moment
object. But we didn't declare a default
property on the exports
object in the moment library. The key is the __importDefault
function. It assigns module (exports
) to the default
property for CommonJS modules:
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default
key. This makes it possible to import defaults on CommonJS modules.
__importStar
does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default
property:
// index.ts file in our app
import * as moment from 'moment'
// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
And what about allowSyntheticDefaultImports
- what is it for? Now the docs should be clear:
Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
In moment
typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop
on. So allowSyntheticDefaultImports
will not report an error if we want to import default from a third-party module which doesn't have a default export.
Add <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version> in property tag
problem resolve
https://medium.com/@saannjaay/unknown-error-in-pom-xml-66fb2414991b
This issue is still up on keras git. I hope it gets solved as soon as possible. Until then, try downgrading your numpy version to 1.16.2. It seems to solve the problem.
!pip install numpy==1.16.1
import numpy as np
This version of numpy has the default value of allow_pickle
as True
.
tf.contrib
has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2
script
https://www.tensorflow.org/alpha/guide/upgrade
Firstly you can run every time with root privileges
sudo npm start
Or you can delete node_modules folder and use npm install
to install again
or you can get permanent solution
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
For ng9 upgraders:
npm i -g core-js@^3
..then:
npm cache clean -f
..followed by:
npm i
You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.
A possible solution is
/Applications
. It's possible to have multiple Xcode versions in the same directory.Create a symbolic link in Terminal.app to have access to the 12.2 device support folder in Xcode 10.2
ln -s /Applications/Xcode102.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/12.2\ \(16E226\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
You can move Xcode 10.2 to somewhere else but then you have to adjust the path.
Now Xcode 10.1 supports devices running iOS 12.2
These steps really help me:
Step 1: Create a directory in android/app/src/main/assets
Linux command: mkdir android/app/src/main/assets
Step 2: Rename index.android.js
(in root directory) to index.js
(Maybe there is an index.js
file in which case you do not need to rename it) then run the following command:
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
Step 3:
Build your APK: react-native run-android
Please use index.js in latest version.
Enjoy :)
Try following command sequence on Ubuntu terminal:
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip
Just change "target": "es2015" to "target": "es5" in your tsconfig.json.
Work for me with Angular 8.2.XX
Tested on IE11 and Edge
Open this folder "C:\ProgramData\" and right-click on "\Anaconda3". go to properties -> security and check all the boxes for each user. This worked for me.
You can prevent from this error by using hooks inside a function
If you don't have cocoa pods installed you need to sudo gem install cocoapods
cd ios
pod install
react-native run-ios
if error persists,
1. delete build folder again
2. open the /ios
folder in x-code
3. navigate File -> Project Settings -> Build System -> change (Shared workspace settings and Per-User workspace settings): Build System -> Legacy Build System
Using Anaconda + Spyder (Python 3.7)
[code]
import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
print(soma)
sess = tf.compat.v1.Session()
with sess:
print(sess.run(soma))
[console]
import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
Tensor("Const_8:0", shape=(), dtype=int32)
Out[18]: tensorflow.python.framework.ops.Tensor
print(soma)
Tensor("add_4:0", shape=(), dtype=int32)
sess = tf.compat.v1.Session()
with sess:
print(sess.run(soma))
5
This is the easiest way.
I did not need to open a new notebook. Instead, I reopened the tree, and reconnected the kernel. At some point I also restarted the kernel. – user650654 Oct 9 '19 at 0:17
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
When i use apt install python3-pip
, i get a lot of packages need install, but i donot need them. So, i DO like this:
apt update
apt-get install python3-setuptools
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
rm -f get-pip.py
Here is an example using Timer.periodic :
Countdown starts from 10
to 0
on button click :
import 'dart:async';
[...]
Timer _timer;
int _start = 10;
void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) {
if (_start == 0) {
setState(() {
timer.cancel();
});
} else {
setState(() {
_start--;
});
}
},
);
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text("Timer test")),
body: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
startTimer();
},
child: Text("start"),
),
Text("$_start")
],
),
);
}
Result :
You can also use the CountdownTimer class from the quiver.async library, usage is even simpler :
import 'package:quiver/async.dart';
[...]
int _start = 10;
int _current = 10;
void startTimer() {
CountdownTimer countDownTimer = new CountdownTimer(
new Duration(seconds: _start),
new Duration(seconds: 1),
);
var sub = countDownTimer.listen(null);
sub.onData((duration) {
setState(() { _current = _start - duration.elapsed.inSeconds; });
});
sub.onDone(() {
print("Done");
sub.cancel();
});
}
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text("Timer test")),
body: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
startTimer();
},
child: Text("start"),
),
Text("$_current")
],
),
);
}
EDIT : For the question in comments about button click behavior
With the above code which uses Timer.periodic
, a new timer will indeed be started on each button click, and all these timers will update the same _start
variable, resulting in a faster decreasing counter.
There are multiple solutions to change this behavior, depending on what you want to achieve :
Timer.periodic
creation with a non null condition so that clicking the button multiple times has no effectif (_timer != null) {
_timer = new Timer.periodic(...);
}
if (_timer != null) {
_timer.cancel();
_start = 10;
}
_timer = new Timer.periodic(...);
if (_timer != null) {
_timer.cancel();
_timer = null;
} else {
_timer = new Timer.periodic(...);
}
You could also use this official async package which provides a RestartableTimer class which extends from Timer
and adds the reset
method.
So just call _timer.reset();
on each button click.
Finally, Codepen now supports Flutter ! So here is a live example so that everyone can play with it : https://codepen.io/Yann39/pen/oNjrVOb
For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.
I know this is kinda late answer but another way besides yannick's answer https://stackoverflow.com/a/57062363/6603342 to use ! is to cast it as string thus telling TypeScript i am sure this is a string thus converting
let name1:string = person.name;//<<<Error here
to
let name1:string = person.name as string;
This will make the error go away but if by any chance this is not a string you will get a run-time error which is one of the reassons we are using TypeScript to ensure that the type matches and avoid such errors at compile time.
I have conda 4.6 with a similar block of code that was added by conda. In my case, there's a conda configuration setting to disable the automatic base activation:
conda config --set auto_activate_base false
The first time you run it, it'll create a ./condarc
in your home directory with that setting to override the default.
This wouldn't de-clutter your .bash_profile
but it's a cleaner solution without manual editing that section that conda manages.
As distributionUrl
is still pointing to older version, upgrade wrapper using:
gradle wrapper --gradle-version 5.1.1
Note: Use gradle
and not gradlew
I tried many solutions but didn't work for me. The below solution works for me.
locate the sdkmanager file in android SDK.
In my case : ~/Android/Sdk/tools/bin
go to that path : cd ~/Android/Sdk/tools/bin
Accept licenses manually : ./sdkmanager --licenses
Enter Yes or y
Generally you should watch out for deeply nested objects in React state. To avoid unexpected behavior, the state should be updated immutably. When you have deep objects, you end up deep cloning them for immutability, which can be quite expensive in React. Why?
Once you deep clone the state, React will recalculate and re-render everything that depends on the variables, even though they haven't changed!
So, before trying to solve your issue, think how you can flatten the state first. As soon as you do that, you will find beautiful tools that will help dealing with large states, such as useReducer().
In case you thought about it, but are still convinced you need to use a deeply nested state tree, you can still use useState() with libraries like immutable.js and Immutability-helper. They make it simple to update or clone deep objects without having to worry about mutability.
My project module was set to 8 but the pom.xml was set to 11. When I changed from 8 to 11 in the module, it worked.
I use this "Win64 OpenSSL v1.1.1h" -> EXE from https://slproweb.com/products/Win32OpenSSL.html
i've installed it and works
// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;
Now you should see, that your code actually does work. What does not work is the console.log(movies)
. This is because movies
points to the old state. If you move your console.log(movies)
outside of useEffect
, right above the return, you will see the updated movies object.
I encountered the same problem after freshly installing git on Windows 10 and running it for the first time. Restarting the bash window solved the problem.
To remove - Can't perform a React state update on an unmounted component warning, use componentDidMount method under a condition and make false that condition on componentWillUnmount method. For example : -
class Home extends Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
news: [],
};
}
componentDidMount() {
this._isMounted = true;
ajaxVar
.get('https://domain')
.then(result => {
if (this._isMounted) {
this.setState({
news: result.data.hits,
});
}
});
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
...
}
}
I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem
Here is a shorter, but complete code.
If you need a dialog with only one button:
await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Message'),
content: Text(
'Your file is saved.'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(); // dismisses only the dialog and returns nothing
},
child: new Text('OK'),
),
],
),
);
If you need a dialog with Yes/No buttons:
onPressed: () async {
bool result = await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Confirmation'),
content: Text('Do you want to save?'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(false); // dismisses only the dialog and returns false
},
child: Text('No'),
),
FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(true); // dismisses only the dialog and returns true
},
child: Text('Yes'),
),
],
);
},
);
if (result) {
if (missingvalue) {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text('Missing Value'),
));
} else {
saveObject();
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
} else {
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
}
I got this problem when my Azure service was immediately trying to get a secret from Azure KeyVault and I had forgotten to give the service permission by KeyVault.
As described here, you need to edit (as root) the file /etc/apt/sources.list
(the easiest way to do this is to type sudo gedit /etc/apt/sources.list
). On the line that mentions http://packages.ros.org/ros/ubuntu you need to add [trusted=yes]
after the word deb
(you might need to add it as a separate word). Then save the file and try again.
Issue has been resolved after updating Android studio version to 3.3-rc2 or latest released version.
cr: @shadowsheep
have to change version under /gradle/wrapper/gradle-wrapper.properties. refer below url https://stackoverflow.com/a/56412795/7532946
This post will go through the following topics:
merge
has shortcomings here)Oftentimes, the situation arises when multiple DataFrames are to be merged together. Naively, this can be done by chaining merge
calls:
df1.merge(df2, ...).merge(df3, ...)
However, this quickly gets out of hand for many DataFrames. Furthermore, it may be necessary to generalise for an unknown number of DataFrames.
Here I introduce pd.concat
for multi-way joins on unique keys, and DataFrame.join
for multi-way joins on non-unique keys. First, the setup.
# Setup.
np.random.seed(0)
A = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'valueA': np.random.randn(4)})
B = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'valueB': np.random.randn(4)})
C = pd.DataFrame({'key': ['D', 'E', 'J', 'C'], 'valueC': np.ones(4)})
dfs = [A, B, C]
# Note, the "key" column values are unique, so the index is unique.
A2 = A.set_index('key')
B2 = B.set_index('key')
C2 = C.set_index('key')
dfs2 = [A2, B2, C2]
If your keys (here, the key could either be a column or an index) are unique, then you can use pd.concat
. Note that pd.concat
joins DataFrames on the index.
# merge on `key` column, you'll need to set the index before concatenating
pd.concat([
df.set_index('key') for df in dfs], axis=1, join='inner'
).reset_index()
key valueA valueB valueC
0 D 2.240893 -0.977278 1.0
# merge on `key` index
pd.concat(dfs2, axis=1, sort=False, join='inner')
valueA valueB valueC
key
D 2.240893 -0.977278 1.0
Omit join='inner'
for a FULL OUTER JOIN. Note that you cannot specify LEFT or RIGHT OUTER joins (if you need these, use join
, described below).
concat
is fast, but has its shortcomings. It cannot handle duplicates.
A3 = pd.DataFrame({'key': ['A', 'B', 'C', 'D', 'D'], 'valueA': np.random.randn(5)})
pd.concat([df.set_index('key') for df in [A3, B, C]], axis=1, join='inner')
ValueError: Shape of passed values is (3, 4), indices imply (3, 2)
In this situation, we can use join
since it can handle non-unique keys (note that join
joins DataFrames on their index; it calls merge
under the hood and does a LEFT OUTER JOIN unless otherwise specified).
# join on `key` column, set as the index first
# For inner join. For left join, omit the "how" argument.
A.set_index('key').join(
[df.set_index('key') for df in (B, C)], how='inner').reset_index()
key valueA valueB valueC
0 D 2.240893 -0.977278 1.0
# join on `key` index
A3.set_index('key').join([B2, C2], how='inner')
valueA valueB valueC
key
D 1.454274 -0.977278 1.0
D 0.761038 -0.977278 1.0
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
$myVar = $someVar ?? 42;
Is equivalent to :
$myVar = isset($someVar) ? $someVar : 42;
For constants, the behaviour is the same when using a constant that already exists :
define("FOO", "bar");
define("BAR", null);
$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";
echo $MyVar . PHP_EOL; // bar
echo $MyVar2 . PHP_EOL; // 42
However, for constants that don't exist, this is different :
$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL; // IDONTEXIST
Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)
Php will convert the non-existing constant to a string.
You can use constant("ConstantName")
that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @
to ignore the warning message :
$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
More of an addendum. I did repro the experiment using the latest Java 8 JVM from IBM:
java version "1.8.0_191"
Java(TM) 2 Runtime Environment, Standard Edition (IBM build 1.8.0_191-b12 26_Oct_2018_18_45 Mac OS X x64(SR5 FP25))
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)
And this shows very similar results:
0.374653912 s
n = 119860736
0.447778698 s
n = 119860736
(second results using 2 * i * i).
Interestingly enough, when running on the same machine, but using Oracle Java:
Java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
results are on average a bit slower:
0.414331815 s
n = 119860736
0.491430656 s
n = 119860736
Long story short: even the minor version number of HotSpot matter here, as subtle differences within the JIT implementation can have notable effects.
Enable cross-origin requests in ASP.NET Web API click for more info
Enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:
Install-Package Microsoft.AspNet.WebApi.Cors
This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Next, add the [EnableCors] attribute to your controller/ controller methods
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebService.Controllers
{
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
Another non-angular answer (I was facing the same issue building a react app on AWS Amplify).
As mentioned by Emmanuel it seems that it comes from the difference in the way memory is handled by node v10 vs node v12.
I tried to increase memory with no avail. But using node v12 did it.
Check how you can add nvm use $VERSION_NODE_12
to your build settings as explained by richard
frontend: phases: preBuild: commands: - nvm use $VERSION_NODE_12 - npm ci build: commands: - nvm use $VERSION_NODE_12 - node -v - npm run-script build
Yesterday, I got the same error: Failed building wheel for hddfancontrol
when I ran pip3 install hddfancontrol
. The result was Failed to build hddfancontrol
. The cause was error: invalid command 'bdist_wheel'
and Running setup.py bdist_wheel for hddfancontrol ... error
. The error was fixed by running the following:
pip3 install wheel
(From here.)
Alternatively, the "wheel" can be downloaded directly from here. When downloaded, it can be installed by running the following:
pip3 install "/the/file_path/to/wheel-0.32.3-py2.py3-none-any.whl"
I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/
"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:
Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."
If you only want to run the function given to useEffect
after the initial render, you can give it an empty array as second argument.
function MyComponent() {
useEffect(() => {
loadDataOnlyOnce();
}, []);
return <div> {/* ... */} </div>;
}
Assuming that you already downloaded chromeDriver, this error is also occurs when already multiple chrome tabs are open.
If you close all tabs and run again, the error should clear up.
Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.
Quick fix:
helloWorld
inside the src
folder.helloWorld.java
file in that package. Just drag and drop on
the package. Error should disappear.Explanation:
Latest version of Eclipse required java11 or above. The module
feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules
When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java
file. If you select don't create
then module-info.java
will not create and your project will free from this issue.
Best practice is while crating project, after giving project name. Click on next
button instead of finish
. On next page at the bottom it ask for creation of module-info.java
file. Select or deselect as per need.
If selected: (by default) click on finish
button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.
If deselect: No issue
Here's an alternative way of tackling the problem:
Instead of trying to "fix it in post" why don't you truncate the description before the table needs to try and fit it into its columns? I did it like this:
<ng-container matColumnDef="description">
<th mat-header-cell *matHeaderCellDef> {{ 'Parts.description' | translate }} </th>
<td mat-cell *matCellDef="let element">
{{(element.description.length > 80) ? ((element.description).slice(0, 80) + '...') : element.description}}
</td>
</ng-container>
So I first check if the array is bigger than a certain length, if Yes then truncate and add '...' otherwise pass the value as is. This enables us to still benefit from the auto-spacing the table does :)
As pointed out in some comments, you need to edit the policies of ImageMagick in /etc/ImageMagick-7/policy.xml
. More particularly, in ArchLinux at the time of writing (05/01/2019) the following line is uncommented:
<policy domain="coder" rights="none" pattern="{PS,PS2,PS3,EPS,PDF,XPS}" />
Just wrap it between <!--
and -->
to comment it, and pdf conversion should work again.
Reason for the error:
Column
tries to expands in vertical axis, and so does the ListView
, hence you need to constrain the height of ListView
.
Solutions
Use either Expanded
or Flexible
if you want to allow ListView
to take up entire left space in Column
.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
Use SizedBox
if you want to restrict the size of ListView
to a certain height.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
Use shrinkWrap
, if your ListView
isn't too big.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)
Solution:
Add the below line in your application
tag:
android:usesCleartextTraffic="true"
As shown below:
<application
....
android:usesCleartextTraffic="true"
....>
UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"
No Need to set clear text traffic to true as shown above, instead use the below code:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
....
....
</domain-config>
<base-config cleartextTrafficPermitted="false"/>
</network-security-config>
Set the cleartextTrafficPermitted
to true
Hope it helps.
Normally when an optimization algorithm does not converge, it is usually because the problem is not well-conditioned, perhaps due to a poor scaling of the decision variables. There are a few things you can try.
C
, is set appropriately.max_iter
to a larger value. The default is 1000.dual = True
if number of features > number of examples and vice versa. This solves the SVM optimization problem using the dual formulation. Thanks @Nino van Hooff for pointing this out, and @JamesKo for spotting my mistake.Note: One should not ignore this warning.
This warning came about because
Solving the linear SVM is just solving a quadratic optimization problem. The solver is typically an iterative algorithm that keeps a running estimate of the solution (i.e., the weight and bias for the SVM). It stops running when the solution corresponds to an objective value that is optimal for this convex optimization problem, or when it hits the maximum number of iterations set.
If the algorithm does not converge, then the current estimate of the SVM's parameters are not guaranteed to be any good, hence the predictions can also be complete garbage.
Edit
In addition, consider the comment by @Nino van Hooff and @5ervant to use the dual formulation of the SVM. This is especially important if the number of features you have, D, is more than the number of training examples N. This is what the dual formulation of the SVM is particular designed for and helps with the conditioning of the optimization problem. Credit to @5ervant for noticing and pointing this out.
Furthermore, @5ervant also pointed out the possibility of changing the solver, in particular the use of the L-BFGS solver. Credit to him (i.e., upvote his answer, not mine).
I would like to provide a quick rough explanation for those who are interested (I am :)) why this matters in this case. Second-order methods, and in particular approximate second-order method like the L-BFGS solver, will help with ill-conditioned problems because it is approximating the Hessian at each iteration and using it to scale the gradient direction. This allows it to get better convergence rate but possibly at a higher compute cost per iteration. That is, it takes fewer iterations to finish but each iteration will be slower than a typical first-order method like gradient-descent or its variants.
For e.g., a typical first-order method might update the solution at each iteration like
x(k + 1) = x(k) - alpha(k) * gradient(f(x(k)))
where alpha(k), the step size at iteration k, depends on the particular choice of algorithm or learning rate schedule.
A second order method, for e.g., Newton, will have an update equation
x(k + 1) = x(k) - alpha(k) * Hessian(x(k))^(-1) * gradient(f(x(k)))
That is, it uses the information of the local curvature encoded in the Hessian to scale the gradient accordingly. If the problem is ill-conditioned, the gradient will be pointing in less than ideal directions and the inverse Hessian scaling will help correct this.
In particular, L-BFGS mentioned in @5ervant's answer is a way to approximate the inverse of the Hessian as computing it can be an expensive operation.
However, second-order methods might converge much faster (i.e., requires fewer iterations) than first-order methods like the usual gradient-descent based solvers, which as you guys know by now sometimes fail to even converge. This can compensate for the time spent at each iteration.
In summary, if you have a well-conditioned problem, or if you can make it well-conditioned through other means such as using regularization and/or feature scaling and/or making sure you have more examples than features, you probably don't have to use a second-order method. But these days with many models optimizing non-convex problems (e.g., those in DL models), second order methods such as L-BFGS methods plays a different role there and there are evidence to suggest they can sometimes find better solutions compared to first-order methods. But that is another story.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
If you are working with Anaconda, then
conda install python=3.5.0
# or maybe
conda install python=2.7.8
# or whatever you want....
might work.
To stay with a specific major release, activate the AdoptOpenJDK tap with brew tap and then install the desired version with brew cask install:
$ brew tap AdoptOpenJDK/openjdk
$ brew cask install <version>
To install AdoptOpenJDK 14 with HotSpot, run:
$ brew tap AdoptOpenJDK/openjdk
$ brew cask install adoptopenjdk14
From the comment by @ZhekaKozlov: ojdkbuild has OpenJDK builds (currently 8 and 11) for Windows (zip
and msi
).
After trying every answer I could find here and online, I was still getting errors for some missing headers. When trying to compile pyRFR, I was getting errors about stdexcept
not being found, which apparently was not installed in /usr/include
with the other headers. However, I found where it was hiding in Mojave and added this to the end of my ~/.bash_profile
file:
export CPATH=/Library/Developer/CommandLineTools/usr/include/c++/v1
Having done that, I can now compile pyRFR and other C/C++ programs. According to echo | gcc -E -Wp,-v -
, gcc was looking in the old location for these headers (without the /c++/v1
), but not the new location, so adding that to CFLAGS fixed it.
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
This fixed my problem.. All I needed to do was to downgrade my google-services plugin in buildscript in the build.gradle(Project) level file as follows
buildscript{
dependencies {
// From =>
classpath 'com.google.gms:google-services:4.3.0'
// To =>
classpath 'com.google.gms:google-services:4.2.0'
// Add dependency
classpath 'io.fabric.tools:gradle:1.28.1'
}
}
In short:
Explanation:
Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.
OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.
OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.
Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.
AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.
OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.
Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".
Donald Smith, Java product manager at Oracle writes:
Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.
---------------------------------------------------------------------------------------- | Provider | Free Builds | Free Binary | Extended | Commercial | Permissive | | | from Source | Distributions | Updates | Support | License | |--------------------------------------------------------------------------------------| | AdoptOpenJDK | Yes | Yes | Yes | No | Yes | | Amazon – Corretto | Yes | Yes | Yes | No | Yes | | Azul Zulu | No | Yes | Yes | Yes | Yes | | BellSoft Liberica | No | Yes | Yes | Yes | Yes | | IBM | No | No | Yes | Yes | Yes | | jClarity | No | No | Yes | Yes | Yes | | OpenJDK | Yes | Yes | Yes | No | Yes | | Oracle JDK | No | Yes | No** | Yes | No | | Oracle OpenJDK | Yes | Yes | No | No | Yes | | ojdkbuild | Yes | Yes | No | No | Yes | | RedHat | Yes | Yes | Yes | Yes | Yes | | SapMachine | Yes | Yes | Yes | Yes | Yes | ----------------------------------------------------------------------------------------
Free Builds from Source - the distribution source code is publicly available and one can assemble its own build
Free Binary Distributions - the distribution binaries are publicly available for download and usage
Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle
Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)
Permissive License - the distribution license is non-protective, e.g. Apache 2.0
In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.
What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.
Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).
If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.
Additional information
Time to look beyond Oracle's JDK by Stephen Colebourne
Java Is Still Free by Java Champions community (published on September 17, 2018)
Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)
Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)
I did try all the answers above and had no luck. After that I restart my iPhone and problem seems gone. I know it is so stupid but it worked. Answers above most probably solves the problem but if not try to restart your iOS device.
None of the above solutions worked for me. After some guess work, I tried (Xcode v10.2.1 cocoapods v1.7.1)
pod deintegrate
followed by
pod install
Then:
No build errors.
I have solved following this way
import { Router, ActivatedRoute } from '@angular/router';
constructor(private router: Router
, private activeRoute: ActivatedRoute) {
}
reloadCurrentPage(){
let currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
For me, just cleaning project works using ShiftCommandK & OptionShiftCommandK.
preferences -> mysql -> initialize database -> use legacy password encryption(instead of strong) -> entered same password
as my config.inc.php file, restarted the apache server and it worked. I was still suspicious about it so I stopped the apache and mysql server and started them again and now it's working.
Seems PyAudio is supported by Python 2.7, 3.4, 3.5, and 3.6. Refer https://people.csail.mit.edu/hubert/pyaudio/
Please suggest if there is any alternate way to install PyAudio on Python 3.8.2
Updated Answer
As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.
This answer is no longer valid
As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.
Some browser may block popup created by window.open(url, "_blank");
.
An alternative is to create a link and click on it.
...
constructor(@Inject(DOCUMENT) private document: Document) {}
...
openNewWindow(): void {
const link = this.document.createElement('a');
link.target = '_blank';
link.href = 'http://www.your-url.com';
link.click();
link.remove();
}
Install the plugin-proposal-class-properties
npm install @babel/plugin-proposal-class-properties --save-dev
Update your webpack.config.js by adding
'plugins': ['@babel/plugin-proposal-class-properties']}]
This worked for me (using WSL)
sudo /etc/init.d/redis start
(for any other service, check the init.d folder for filenames)
new Buffer(number) // Old
Buffer.alloc(number) // New
new Buffer(string) // Old
Buffer.from(string) // New
new Buffer(string, encoding) // Old
Buffer.from(string, encoding) // New
new Buffer(...arguments) // Old
Buffer.from(...arguments) // New
Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.
I prefer to hide all code complexity in my services... so, I generally use something like this:
In my events.service.ts
async getEvents() {
const snapchot = await this.db.collection('events').ref.get();
return new Promise <Event[]> (resolve => {
const v = snapchot.docs.map(x => {
const obj = x.data();
obj.id = x.id;
return obj as Event;
});
resolve(v);
});
}
In my sth.page.ts
myList: Event[];
construct(private service: EventsService){}
async ngOnInit() {
this.myList = await this.service.getEvents();
}
Enjoy :)
Because of your initialization wrong.
Don't do like this,
MethodName _methodName;
Do like this,
MethodName _methodName = MethodName();
I used these two lines of code in application tag in manifest.xml and it worked.
tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"
Source: https://github.com/android/android-ktx/issues/576#issuecomment-437145192
my solution: org.springframework.boot 2.0.5.RELEASE
Rather: org.springframework.boot 2.1.0.RELEASE
In case you need the []
syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:
[routerLink]="['edit', business._id]"
As for an "about page" with no parameters like yours,
[routerLink]="/about"
or
[routerLink]=['about']
will do the trick.
When you loop in an array like you did, your for variable(in this example i
) is current element of your array.
For example if your ar
is [1,5,10]
, the i
value in each iteration is 1
, 5
, and 10
.
And because your array length is 3, the maximum index you can use is 2. so when i = 5
you get IndexError
.
You should change your code into something like this:
for i in ar:
theSum = theSum + i
Or if you want to use indexes, you should create a range from 0 ro array length - 1
.
for i in range(len(ar)):
theSum = theSum + ar[i]
For me (in windows), I had to restart the terminal and run it as Administrator (if you are using pycharm terminal, simply close pycharm, and reopen it as administrator then try again), That's solved the problem and installation succeed.
Good luck
Very easy if you are already using a statelessWidget checkOut my code
class _MyThirdPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Understanding Material-Cards'),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
_buildStack(),
_buildCard(),
SingleCard(),
_inkwellCard()
],
)),
);
}
}
Here is a simple and fast code in PHP.
function solution($A) {
$x = 1;
sort($A);
foreach($A as $i){
if($i <=0) continue;
if($x < $i) return $x;
else $x = $i+1;
}
return $x;
}
Using Blob
as a source for an img
:
template:
<img [src]="url">
component:
public url : SafeResourceUrl;
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
this.getImage('/api/image.jpg').subscribe(x => this.url = x)
}
public getImage(url: string): Observable<SafeResourceUrl> {
return this.http
.get(url, { responseType: 'blob' })
.pipe(
map(x => {
const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
}),
);
}
Further reference about trusting save values
The simplest solution, although a little time consuming would be to restart your computer or simple logout from the current user and login again.
DefaultTextStyle
is unrelated to the problem. Removing it simply uses the default style, which is far bigger than the one you used so it hides the problem.
textAlign
aligns the text in the space occupied by Text
when that occupied space is bigger than the actual content.
The thing is, inside a Column
, your Text
takes the bare minimum space. It is then the Column
that aligns its children using crossAxisAlignment
which defaults to center
.
An easy way to catch such behavior is by wrapping your texts like this :
Container(
color: Colors.red,
child: Text(...)
)
Which using the code you provided, render the following :
The problem suddenly becomes obvious: Text
don't take the whole Column
width.
You now have a few solutions.
You can wrap your Text
into an Align
to mimic textAlign
behavior
Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Container(
color: Colors.red,
child: Text(
"Should be left",
),
),
),
],
)
Which will render the following :
or you can force your Text
to fill the Column
width.
Either by specifying crossAxisAlignment: CrossAxisAlignment.stretch
on Column
, or by using SizedBox
with an infinite width
.
Column(
children: <Widget>[
SizedBox(
width: double.infinity,
child: Container(
color: Colors.red,
child: Text(
"Should be left",
textAlign: TextAlign.left,
),
),
),
],
),
which renders the following:
In that example, it is TextAlign
that placed the text to the left.
Solution for the issue: deprecated gradle features were used in this build making it incompatible with gradle 6.0. android studio This provided solution worked for me.
First change the classpath in dependencies of build.gradle of your project
From: classpath 'com.android.tools.build:gradle:3.3.1'
To: classpath 'com.android.tools.build:gradle:3.6.1'
Then make changes in the gradle-wrapper.properties file this file exists in the Project's gradle>wrapper folder
From: distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
To: distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
Then Sync your gradle.
I found a bug in AJT_82's answer. Since I do not have enough reputation to comment under AJT_82's answer, I have to post the bug and solution in this answer.
Here is the bug:
Solution: In the following code:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const invalidCtrl = !!(control && control.invalid && control.parent.dirty);
const invalidParent = !!(control && control.parent && control.parent.invalid && control.parent.dirty);
return (invalidCtrl || invalidParent);
}
}
Change control.parent.invalid
to control.parent.hasError('notSame')
will solve this problem.
After the small changes, the problem solved.
Edit: To validate the Confirm Password field only after the user starts typing you can return this instead
return ((invalidCtrl || invalidParent) && control.valid);
With Column, use:
mainAxisAlignment: MainAxisAlignment.center
It align its children(s) to center of its parent Space vertically
This is how i renamed package for both ios and android
applicationId "com.company.name"
app/src/main
and rename package="com.company.name"
and android:label="App Name"
app/src/debug
and rename package="com.company.name"
app/src/profile
and rename package="com.company.name"
app/src/main/kotlin/com/something/something/MainActivity.kt
and rename package="com.company.name"
app/src/main/kotlin/
and rename each directory so that the structure looks like app/src/main/kotlin/com/company/name/
pubspec.yaml
in your project and change name: something
to name: name
, example :- if package name is com.abc.xyz
the name: xyz
com.company.name
flutter clean
user decoration Image for a container.
@override
Widget build(BuildContext context) {
final alucard = Container(
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(10),
image: new DecorationImage(
image: new AssetImage("images/logo.png"),
fit: BoxFit.fill,
)
)
);
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
As the other answers suggest, editing/removing credentials in the Manage Windows Credentials
work and does the job. However, you need to do this each time when the password changes or credentials do not work for some work. Using ssh key
has been extremely useful for me where I don't have to bother about these again once I'm done creating a ssh-key
and adding them on the server repository (github/bitbucket/gitlab).
Generating a new ssh-key
Open Git Bash.
Paste the text below, substituting in your repo's email address.
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.
Then you'll be asked to type a secure passphrase. You can type a passphrase, hit enter and type the passphrase again.
Or, Hit enter twice for empty passphrase.
Copy this on the clipboard:
clip < ~/.ssh/id_rsa.pub
And then add this key into your repo's profile. For e.g, on github->setting->SSH keys -> paste the key that you coppied ad hit add
You're done once and for all!
You can use the below for passing the raw text.
axios.post(
baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
body,
{
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain'
}
}
).then(response => {
this.setState({data:response.data});
console.log(this.state.data);
});
Just have your raw text within body
or pass it directly within quotes as 'raw text to be sent'
in place of body
.
The signature of the axios post is axios.post(url[, data[, config]])
, so the data
is where you pass your request body.
I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem
Strangely, even though the tensorflow website 1 mentions that CUDA 10.1 is compatible with tensorflow-gpu-1.13.1, it doesn't work so far. tensorflow-gpu gets installed properly though but it throws out weird errors when running.
So far, the best configuration to run tensorflow with GPU is CUDA 9.0 with tensorflow_gpu-1.12.0 under python3.6.
Following this configuration with the steps mentioned in https://stackoverflow.com/a/51307381/2562870 (the answer above), worked for me :)
We are rolling out a new package structure to make it clearer which packages are bundled with the Android operating system, and which are packaged with your app's APK. Going forward, the android.* package hierarchy will be reserved for Android packages that ship with the operating system. Other packages will be issued in the new androidx.* package hierarchy as part of the AndroidX library.
AndroidX is a redesigned library to make package names more clear. So from now on android hierarchy will be for only android default classes, which comes with android operating system and other library/dependencies will be part of androidx (makes more sense). So from now on all the new development will be updated in androidx.
com.android.support.** : androidx.
com.android.support:appcompat-v7 : androidx.appcompat:appcompat
com.android.support:recyclerview-v7 : androidx.recyclerview:recyclerview
com.android.support:design : com.google.android.material:material
Complete Artifact mappings for AndroidX packages
Previously, support library
used the SDK version but AndroidX uses the Semantic-version
. It’s going to re-version from 28.0.0 ? 1.0.0.
In Android Studio 3.2 (September 2018), there is a direct option to migrate existing project to AndroidX
. This refactor all packages automatically.
Before you migrate, it is strongly recommended to backup your project.
Existing project
New project
Put these flags in your gradle.properties
android.enableJetifier=true
android.useAndroidX=true
Check @Library mappings for equal AndroidX package.
Check @Official page of Migrate to AndroidX
From Android Support Revision 28.0.0
This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0
So go with AndroidX, because Android will update only androidx package from now.
https://developer.android.com/topic/libraries/support-library/androidx-overview
https://android-developers.googleblog.com/2018/05/hello-world-androidx.html
For me the resource folder was getting excluded on a maven update/build. I went to Build Path>Source and found that src/main/resources have "Excluded **". I removed that entry (Clicked on Excluded **>Remove>Apply and Close).
Then it worked fine.
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)
Simply change the text
property
TextField(
controller: txt,
),
RaisedButton(onPressed: () {
txt.text = "My Stringt";
}),
while txt
is just a TextEditingController
var txt = TextEditingController();
What I did was first I installed python 3.7
brew install python3
brew unlink python
then I installed python 3.6.5 using above link
brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb --ignore-dependencies
After that I ran brew link --overwrite python
. Now I have all pythons in the system to create the virtual environments.
mian@tdowrick2~ $ python --version
Python 2.7.10
mian@tdowrick2~ $ python3.7 --version
Python 3.7.1
mian@tdowrick2~ $ python3.6 --version
Python 3.6.5
To create Python 3.7 virtual environment.
mian@tdowrick2~ $ virtualenv -p python3.7 env
Already using interpreter /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.7'
New python executable in /Users/mian/env/bin/python3.7
Also creating executable in /Users/mian/env/bin/python
Installing setuptools, pip, wheel...
done.
mian@tdowrick2~ $ source env/bin/activate
(env) mian@tdowrick2~ $ python --version
Python 3.7.1
(env) mian@tdowrick2~ $ deactivate
To create Python 3.6 virtual environment
mian@tdowrick2~ $ virtualenv -p python3.6 env
Running virtualenv with interpreter /usr/local/bin/python3.6
Using base prefix '/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/mian/env/bin/python3.6
Not overwriting existing python script /Users/mian/env/bin/python (you must use /Users/mian/env/bin/python3.6)
Installing setuptools, pip, wheel...
done.
mian@tdowrick2~ $ source env/bin/activate
(env) mian@tdowrick2~ $ python --version
Python 3.6.5
(env) mian@tdowrick2~ $
And here the solution for C#/Xamarin.Android:
var token = await FirebaseInstallations.Instance.GetToken(forceRefresh: false).AsAsync<InstallationTokenResult>();
https://fettblog.eu/gulp-4-parallel-and-series/
Because
gulp.task(name, deps, func)
was replaced by gulp.task(name, gulp.{series|parallel}(deps, func))
.
You are using the latest version of gulp but older code. Modify the code or downgrade.
As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx
Template
<form [formGroup]="mainForm" ng-submit="submitForm()">
Global Price: <input type="number" formControlName="globalPrice">
<button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
<table border formArrayName="orderLines">
<ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
<tr>
<td>{{orderLine.time | date}}</td>
<td>{{orderLine.quantity}}</td>
<td><input formControlName="price" type="number"></td>
</tr>
</ng-container>
</table>
</form>
Component
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
mainForm: FormGroup;
orderLines = [
{price: 10, time: new Date(), quantity: 2},
{price: 20, time: new Date(), quantity: 3},
{price: 30, time: new Date(), quantity: 3},
{price: 40, time: new Date(), quantity: 5}
]
constructor() {
this.mainForm = this.getForm();
}
getForm(): FormGroup {
return new FormGroup({
globalPrice: new FormControl(),
orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
})
}
getFormGroupForLine(orderLine: any): FormGroup {
return new FormGroup({
price: new FormControl(orderLine.price)
})
}
applyPriceToAll() {
const formLines = this.mainForm.get('orderLines') as FormArray;
const globalPrice = this.mainForm.get('globalPrice').value;
formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
// optionally recheck value and validity without emit event.
}
submitForm() {
}
}
Not the solution, but you can use debug key for signing release builds to avoid blocking the installation from Google Play Protect. It looks like Play Protect doesn't warn for builds signed with automatically generated debug.keystore
.
Note that your debug builds are not unsigned, they are just signed with a debug key.
Of course, you cannot use the build for production distribution (Google Play, Amazon, etc.), but it's still worth for pre-production internal testing which requires a high-frequency feedback loop.
You can add a task to build release with debug.keystore by adding the configuration in build.gradle
, something like:
android {
buildTypes {
// add after the `release` definition
releaseDebugKey { initWith release }
}
signingConfigs {
// use debug.keystore for releaseDebugKey builds
releaseDebugKey { initWith debug }
}
}
then execute ./gradlew assembleReleaseDebugKey
to build a release build with debug key.
The general answer to your question is that it depends. And you get to decide by specifying what your "Content-Type" is in the HTTP headers.
A value of "application/x-www-form-urlencoded" means that your POST body will need to be URL encoded just like a GET parameter string. A value of "multipart/form-data" means that you'll be using content delimiters and NOT url encoding the content.
This answer has a much more thorough explanation if you'd like more information.
For an answer specific to the PHP libraries you're using (CURL), you should read the documentation here.
Here's the relevant information:
CURLOPT_POST
TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_POSTFIELDS
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix.
Forget trying to decipher the example .ts - as others have said it is often incomplete.
Instead just click on the 'pop-out' icon circled here and you'll get a fully working StackBlitz example.
You can quickly confirm the required modules:
Comment out any instances of ReactiveFormsModule
, and sure enough you'll get the error:
Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'.
DUAL we mainly used for getting the next number from the sequences.
Syntax : SELECT 'sequence_name'.NEXTVAL FROM DUAL
This will return the one row one column value(NEXTVAL column name).
I've been facing this problem for long but what this solves my problem Go inside the tsconfig.json and add the following under compilerOptions
{
"compilerOptions": {
...
"allowJs": true
...
}
}
You can still use map
if you can afford to create a makeshift array:
{
new Array(this.props.level).fill(0).map((_, index) => (
<span className='indent' key={index}></span>
))
}
This works because new Array(n).fill(x)
creates an array of size n
filled with x
, which can then aid map
.
It seems like two different scenarios are being mixed together in this discussion:
Scenario 1
Using my parent repository's pointers to submodules, I want to check out the commit in each submodule that the parent repository is pointing to, possibly after first iterating through all submodules and updating/pulling these from remote.
This is, as pointed out, done with
git submodule foreach git pull origin BRANCH
git submodule update
Scenario 2, which I think is what OP is aiming at
New stuff has happened in one or more submodules, and I want to 1) pull these changes and 2) update the parent repository to point to the HEAD (latest) commit of this/these submodules.
This would be done by
git submodule foreach git pull origin BRANCH
git add module_1_name
git add module_2_name
......
git add module_n_name
git push origin BRANCH
Not very practical, since you would have to hardcode n paths to all n submodules in e.g. a script to update the parent repository's commit pointers.
It would be cool to have an automated iteration through each submodule, updating the parent repository pointer (using git add
) to point to the head of the submodule(s).
For this, I made this small Bash script:
git-update-submodules.sh
#!/bin/bash
APP_PATH=$1
shift
if [ -z $APP_PATH ]; then
echo "Missing 1st argument: should be path to folder of a git repo";
exit 1;
fi
BRANCH=$1
shift
if [ -z $BRANCH ]; then
echo "Missing 2nd argument (branch name)";
exit 1;
fi
echo "Working in: $APP_PATH"
cd $APP_PATH
git checkout $BRANCH && git pull --ff origin $BRANCH
git submodule sync
git submodule init
git submodule update
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"
for i in $(git submodule foreach --quiet 'echo $path')
do
echo "Adding $i to root repo"
git add "$i"
done
git commit -m "Updated $BRANCH branch of deployment repo to point to latest head of submodules"
git push origin $BRANCH
To run it, execute
git-update-submodules.sh /path/to/base/repo BRANCH_NAME
Elaboration
First of all, I assume that the branch with name $BRANCH (second argument) exists in all repositories. Feel free to make this even more complex.
The first couple of sections is some checking that the arguments are there. Then I pull the parent repository's latest stuff (I prefer to use --ff (fast-forwarding) whenever I'm just doing pulls. I have rebase off, BTW).
git checkout $BRANCH && git pull --ff origin $BRANCH
Then some submodule initializing, might be necessary, if new submodules have been added or are not initialized yet:
git submodule sync
git submodule init
git submodule update
Then I update/pull all submodules:
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"
Notice a few things: First of all, I'm chaining some Git commands using &&
- meaning previous command must execute without error.
After a possible successful pull (if new stuff was found on the remote), I do a push to ensure that a possible merge-commit is not left behind on the client. Again, it only happens if a pull actually brought in new stuff.
Finally, the final || true
is ensuring that script continues on errors. To make this work, everything in the iteration must be wrapped in the double-quotes and the Git commands are wrapped in parentheses (operator precedence).
My favourite part:
for i in $(git submodule foreach --quiet 'echo $path')
do
echo "Adding $i to root repo"
git add "$i"
done
Iterate all submodules - with --quiet
, which removes the 'Entering MODULE_PATH' output. Using 'echo $path'
(must be in single-quotes), the path to the submodule gets written to output.
This list of relative submodule paths is captured in an array ($(...)
) - finally iterate this and do git add $i
to update the parent repository.
Finally, a commit with some message explaining that the parent repository was updated. This commit will be ignored by default, if nothing was done. Push this to origin, and you're done.
I have a script running this in a Jenkins job that chains to a scheduled automated deployment afterwards, and it works like a charm.
I hope this will be of help to someone.
Mysql Converting column from VARCHAR to TEXT when under limit size!!!
mysql> CREATE TABLE varchars1(ch3 varchar(6),ch1 varchar(3),ch varchar(4000000))
;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> SHOW WARNINGS;
+-------+------+---------------------------------------------+
| Level | Code | Message |
+-------+------+---------------------------------------------+
| Note | 1246 | Converting column 'ch' from VARCHAR to TEXT |
+-------+------+---------------------------------------------+
1 row in set (0.00 sec)
mysql>
The following cites the C11 standard (final draft).
6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
bool
(mapped by stdbool.h
to the internal name _Bool
for C) itself is an unsigned integer type:
... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.
According to 6.2.5p2:
An object declared as type _Bool is large enough to store the values 0 and 1.
AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool
for C++ and _Bool
for C.
Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool
behaves as in C++.
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
Quite simple:
new File("/Path/To/File/or/Directory").exists();
And if you want to be certain it is a directory:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
Adding the following avoids problems with quotes in file names, e.g.
"freddy's pic.jpg"
which are acceptable on some operating systems.
Before:
$pic=($_FILES['photo']['name']);
After:
$pic=(mysql_real_escape_string($_FILES['photo']['name']));
The top answer is the best! However, it was not triggering mouse events for me in Firefox when etype = 'click'
.
So, I changed the document.createEvent
to 'MouseEvents'
and that fixed the problem. The extra code is to test whether or not another bit of code was interfering with the event, and if it was cancelled I would log that to console.
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent(etype, true, false);
var canceled = !el.dispatchEvent(evObj);
if (canceled) {
// A handler called preventDefault.
console.log("automatic click canceled");
} else {
// None of the handlers called preventDefault.
}
}
}
I'd wonder why someone would try to "override" the container width, since its purpose is to keep its content with some padding, but I had a similar situation (that's why I wanted to share my solution, even though there're answers).
In my situation, I wanted to have all content (of all pages) rendered inside a container, so this was the piece of code from my _Layout.cshtml:
<div id="body">
@RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
<div class="container">
@RenderBody()
</div>
</section>
</div>
In my Home Index page, I had a background header image I'd like to fill the whole screen width, so the solution was to make the Index.cshtml like this:
@section featured {
<!-- This content will be rendered outside the "container div" -->
<div class="intro-header">
<div class="container">SOME CONTENT WITH A NICE BACKGROUND</div>
</div>
}
<!-- The content below will be rendered INSIDE the "container div" -->
<div class="content-section-b">
<div class="container">
<div class="row">
MORE CONTENT
</div>
</div>
</div>
I think this is better than trying to make workarounds, since sections are made with the purpose of allowing (or forcing) views to dynamically replace some content in the layout.
All that the test
attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"
<c:if test="true">Hello world!</c:if>
The code within the <%= %>
returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if>
tag looks for.
I've recently stumbled upon the following solution to this problem:
Source: Multiple versions of Chrome
...this is registry data problem: How to do it then (this is an example for 2.0.172.39 and 3.0.197.11, I'll try it with next versions as they will come, let's assume I've started with Chrome 2):
Install Chrome 2, you'll find it
Application Data
folder, since I'm from Czech Republic and my name is Bronislav Klucka the path looks like this:C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome
and run Chrome
Open registry and save
[HKEY_CURRENT_USER\Software\Google\Update\Clients\{8A69D345-D564-463c-AFF1-A69D9E530F96}] [HKEY_CURRENT_USER\Software\Google\Update\ClientState\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
keys, put them into one chrome2.reg file and copy this file next to
chrome.exe
(ChromeDir\Application)Rename Chrome folder to something else (e.g. Chrome2)
Install Chrome 3, it will install to Chrome folder again and run Chrome
- Save the same keys (there are changes due to different version) and save it to the
chrome3.reg
file next tochrome.exe
file of this new version againRename the folder again (e.g. Chrome3)
the result would be that there is no Chrome dir (only Chrome2 and Chrome3)
Go to the Application folder of Chrome2, create
chrome.bat
file with this content:@echo off regedit /S chrome2.reg START chrome.exe -user-data-dir="C:\Docume~1\Bronis~1\LocalS~1\Dataap~1\Google\Chrome2\User Data" rem START chrome.exe -user-data-dir="C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome2\User Data"
the first line is generic batch command, the second line will update registry with the content of
chrome2.reg
file, the third lines starts Chrome pointing to passed directory, the 4th line is commented and will not be run.Notice short name format passed as
-user-data-dir
parameter (the full path is at the 4th line), the problem is that Chrome using this parameter has a problem with diacritics (Czech characters)Do 7. again for Chrome 3, update paths and reg file name in bat file for Chrome 3
Try running both bat files, seems to be working, both versions of Chrome are running simultaneously.
Updating: Running "About" dialog displays correct version, but an error while checking for new one. To correct that do (I'll explain form Chrome2 folder): 1. rename Chrome2 to Chrome 2. Go to Chrome/Application folder 3. run chrome2.reg file 4. run chrome.exe (works the same for Chrome3) now the version checking works. There has been no new version of Chrome since I've find this whole solution up. But I assume that update will be downloaded to this folder so all you need to do is to update reg file after update and rename Chrome folder back to Chrome2. I'll update this post after successful Chrome update.
Bronislav Klucka
One very quick way is to do something like:
substr(md5(rand()),0,10);
This will generate a random string with the length of 10 chars. Of course, some might say it's a bit more heavy on the computation side, but nowadays processors are optimized to run md5 or sha256 algorithm very quickly. And of course, if the rand()
function returns the same value, the result will be the same, having a 1 / 32767 chance of being the same. If security's the issue, then just change rand()
to mt_rand()
I'm thinking of many things here:
This is how I solved this issue:
git pull origin master
git push origin master
This usually happens when your remote branch is not updated. And after this if you get an error like "Please enter a commit message" Refer to this ( For me xiaohu Wang answer worked :) )
Check both lists are not nulls. If their sizes are different, then these lists are not equal. Build maps consisting of the lists' elements as keys and their repeats as values and compare the maps.
Assumptions, if both lists are nulls, I consider them equal.
private boolean compareLists(List<?> l1, List<?> l2) {
if (l1 == null && l2 == null) {
return true;
} else if (l1 == null || l2 == null) {
return false;
}
if (l1.size() != l2.size()) {
return false;
}
Map<?, Integer> m1 = toMap(l1);
Map<?, Integer> m2 = toMap(l2);
return m1.equals(m2);
}
private Map<Object, Integer> toMap(List<?> list) {
//Effective size, not to resize in the future.
int mapSize = (int) (list.size() / 0.75 + 1);
Map<Object, Integer> map = new HashMap<>(mapSize);
for (Object o : list) {
Integer count = map.get(o);
if (count == null) {
map.put(o, 1);
} else {
map.put(o, ++count);
}
}
System.out.println(map);
return map;
}
Please, note, method equals should be properly defined for these objects. https://stackoverflow.com/a/24814634/4587961
Just do Ctrl + Enter inside the text box
Answer to the original question:
os.urandom(n)
Quote from: http://docs.python.org/2/library/os.html
Return a string of n random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a UNIX-like system this will query /dev/urandom, and on Windows it will use CryptGenRandom. If a randomness source is not found, NotImplementedError will be raised.
For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom.
password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
submit.performClick();
return true;
}
return false;
}
});
Works very fine for me
In addition hide keyboard
I found this solution to work best for creating a log file that maintains itself:
setlocal enabledelayedexpansion
SET /A maxlines= 10
set "cmd=findstr /R /N "^^" "filename.txt" | find /C ":""
for /f %%a in ('!cmd!') do set linecount=%%a
GOTO NEXT
:NEXT
FOR /F %%A IN ("filename.txt") DO (
IF %linecount% GEQ %maxlines% GOTO ExitLoop
echo %clientname% %Date% %Time% >> "filename.txt")
EXIT
:ExitLoop
echo %clientname% %Date% %Time% > "filename.txt"
EXIT
Environmental variables included are %clientname% the computername of the remote client %Date% is the current date and %Time% the current time. :NEXT is called after getting the number of lines in the file. If the file line count is greater than the %maxlines% variable it goes to the :EXITLOOP where it overwrites the file, creating a new one with the first line of information. if it is less than the %maxlines% variable it simply adds the line to the current file.
Contrary to some of the answers here, editing the stylesheet itself with Javascript is not only possible, but higher performance. Simply doing $('.myclass').css('color: red')
will end up looping through every item matching the selector and individually setting the style attribute. This is really inefficient and if you have hundreds of elements, it's going to cause problems.
Changing classes on the items is a better idea, but you still suffer from the same problem in that you're changing an attribute on N items, which could be a large number. A better solution might be to change the class on one single parent item or a small number of parents and then hit the target items using the "Cascade" in css. This serves in most situations, but not all.
Sometimes you need to change the CSS of a lot of items to something dynamic, or there's no good way for you to do so by hitting a small number of parents. Changing the stylesheet itself, or adding a small new one to override the existing css is an extremely efficient way to change the display of items. You're only interacting with the DOM in one spot and the browser can handle deploying those changes really efficiently.
jss is one library that helps make it easier to directly edit the stylesheet from javascript.
Using regexp to solve this kind of problem is a bad idea and will likely lead in unmaintainable and unreliable code. Better use an HTML parser.
In that case it's better to split the process into two parts :
I will assume your doc is not xHTML strict so you can't use an XML parser. E.G. with this web page source code :
/* preg_match_all match the regexp in all the $html string and output everything as
an array in $result. "i" option is used to make it case insensitive */
preg_match_all('/<img[^>]+>/i',$html, $result);
print_r($result);
Array
(
[0] => Array
(
[0] => <img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />
[1] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />
[2] => <img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />
[3] => <img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />
[4] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />
[...]
)
)
Then we get all the img tag attributes with a loop :
$img = array();
foreach( $result as $img_tag)
{
preg_match_all('/(alt|title|src)=("[^"]*")/i',$img_tag, $img[$img_tag]);
}
print_r($img);
Array
(
[<img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />] => Array
(
[0] => Array
(
[0] => src="/Content/Img/stackoverflow-logo-250.png"
[1] => alt="logo link to homepage"
)
[1] => Array
(
[0] => src
[1] => alt
)
[2] => Array
(
[0] => "/Content/Img/stackoverflow-logo-250.png"
[1] => "logo link to homepage"
)
)
[<img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />] => Array
(
[0] => Array
(
[0] => src="/content/img/vote-arrow-up.png"
[1] => alt="vote up"
[2] => title="This was helpful (click again to undo)"
)
[1] => Array
(
[0] => src
[1] => alt
[2] => title
)
[2] => Array
(
[0] => "/content/img/vote-arrow-up.png"
[1] => "vote up"
[2] => "This was helpful (click again to undo)"
)
)
[<img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />] => Array
(
[0] => Array
(
[0] => src="/content/img/vote-arrow-down.png"
[1] => alt="vote down"
[2] => title="This was not helpful (click again to undo)"
)
[1] => Array
(
[0] => src
[1] => alt
[2] => title
)
[2] => Array
(
[0] => "/content/img/vote-arrow-down.png"
[1] => "vote down"
[2] => "This was not helpful (click again to undo)"
)
)
[<img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />] => Array
(
[0] => Array
(
[0] => src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
[1] => alt="gravatar image"
)
[1] => Array
(
[0] => src
[1] => alt
)
[2] => Array
(
[0] => "http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
[1] => "gravatar image"
)
)
[..]
)
)
Regexps are CPU intensive so you may want to cache this page. If you have no cache system, you can tweak your own by using ob_start and loading / saving from a text file.
First, we use preg_ match_ all, a function that gets every string matching the pattern and ouput it in it's third parameter.
The regexps :
<img[^>]+>
We apply it on all html web pages. It can be read as every string that starts with "<img
", contains non ">" char and ends with a >.
(alt|title|src)=("[^"]*")
We apply it successively on each img tag. It can be read as every string starting with "alt", "title" or "src", then a "=", then a ' " ', a bunch of stuff that are not ' " ' and ends with a ' " '. Isolate the sub-strings between ().
Finally, every time you want to deal with regexps, it handy to have good tools to quickly test them. Check this online regexp tester.
EDIT : answer to the first comment.
It's true that I did not think about the (hopefully few) people using single quotes.
Well, if you use only ', just replace all the " by '.
If you mix both. First you should slap yourself :-), then try to use ("|') instead or " and [^ø] to replace [^"].
reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.
Is there any better choice in this kind of scenario?
it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.
fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?
Use this code to find top most UIViewController
func getTopViewController() -> UIViewController? {
var topController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController
while topController?.presentedViewController != nil {
topController = topController?.presentedViewController
}
return topController
}
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.keshav.retroft2arrayinsidearrayexamplekeshav"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
compile 'com.android.support:appcompat-v7:26.0.1'
compile 'com.android.support:recyclerview-v7:26.0.1'
compile 'com.android.support:cardview-v7:26.0.1'
The issue you have encountered is that UDF
s cannot modify the Excel environment, they can only return a value to the calling cell.
There are several alternatives
For the sample given you don't actually need VBA. This formula will work
='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2
Use a rather messy work around: See this answer
You can use ExecuteExcel4Macro
or OLEDB
For iOS7+ and if you are using Interface Builder then subclass your cell and implement:
Objective-C
- (void)awakeFromNib {
[super awakeFromNib];
// Default Select background
UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
self.selectedBackgroundView = v;
}
Swift 2.2
override func awakeFromNib() {
super.awakeFromNib()
// Default Select background
self.selectedBackgroundView = { view in
view.backgroundColor = .redColor()
return view
}(UIView())
}
gradlew
(On Windows gradlew.bat
)
adb install -r exampleApp.apk
(The -r
makes it replace the existing copy, add an -s
if installing on an emulator)
I set up an alias in my ~/.bash_profile
, to make it a 2char command.
alias bi="gradlew && adb install -r exampleApp.apk"
(Short for Build and Install)
With matplotlib
:
import matplotlib
matplotlib.image.imsave('name.png', array)
Works with matplotlib 1.3.1, I don't know about lower version. From the docstring:
Arguments:
*fname*:
A string containing a path to a filename, or a Python file-like object.
If *format* is *None* and *fname* is a string, the output
format is deduced from the extension of the filename.
*arr*:
An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array.
If you are using Godaddy as your certificate authority, and you are running into this issue; All you have to do is Re-key the certificate. I tried the above certutil -repairstore my "paste the serial # in here" but the system wanted me to use smart card for authentication. (Running IIS10 on Server 2016 and 2012R2)
When I Created a Certificate Request, gone through the process of Re-keying and gone through the process of "Complete Certificate Request" I was able to sucessfuly configure "Bindings..." without the certificate disappearing.
Here, I summarize a few ways which may return different results to your question, so be careful:
# First assign your "id"s to an R object.
# Here's a hypothetical example:
id <- c("a","b","b","c","c","c","d","d","d","d")
#To return ALL MINUS ONE duplicated values:
id[duplicated(id)]
## [1] "b" "c" "c" "d" "d" "d"
#To return ALL duplicated values by specifying fromLast argument:
id[duplicated(id) | duplicated(id, fromLast=TRUE)]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
#Yet another way to return ALL duplicated values, using %in% operator:
id[ id %in% id[duplicated(id)] ]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
Hope these help. Good luck.
You can solve this problem by using AJAX. You don't need to load JQuery for AJAX but it has a better error and success handling than native JS.
I would do it like so:
1) add an click eventlistener to all my anchors on the page. 2) on click, you can setup an ajax-request to your php, in the POST-DATA you set the anchor id or the text-value 3) the php gets the value and you can setup a request to your database. Then you return the value which you need and echo it to the ajax-request. 4) your success function of the ajax-request is doing some stuff
For more information about ajax-requests look back here:
-> Ajax-Request NATIVE https://blog.garstasio.com/you-dont-need-jquery/ajax/
A simple JQuery examle:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
For me the easiest solution was to import swagger (v2) into Postman and then go to the web view. There you can choose "single column" view and use the browser to print to pdf. Not a automated/integrated solution but good for single-use. It handles paper-width much better than printing from editor2.swagger.io, where scrollbars cause portions of the content to be hidden.
You need to use DateTime.ParseExact
with format "dd/MM/yyyy"
DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Its safer if you use d/M/yyyy
for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.
Your date format day/Month/Year
might be an acceptable date format for some cultures. For example for Canadian Culture en-CA
DateTime.Parse
would work like:
DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));
Or
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture
Both the above lines would work because the the string's format is acceptable for en-CA
culture. Since you are not supplying any culture to your DateTime.Parse
call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.
Another method for parsing is using DateTime.TryParseExact
DateTime dt;
if (DateTime.TryParseExact("24/01/2013",
"d/M/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//valid date
}
else
{
//invalid date
}
The TryParse
group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool
value indicating success or failure in parsing.
Notice that I have used single d
and M
for day and month respectively. Single d
and M
works for both single/double digits day and month. So for the format d/M/yyyy
valid values could be:
For further reading you should see: Custom Date and Time Format Strings
See ?read.table
. Basically, when you use read.table
, you specify a number indicating the column:
##Row names in the first column
read.table(filname.txt, row.names=1)
No.
First off, append
is a function, so you can't write append[i+1:i+4]
because you're trying to get a slice of a thing that isn't a sequence. (You can't get an element of it, either: append[i+1]
is wrong for the same reason.) When you call a function, the argument goes in parentheses, i.e. the round ones: ()
.
Second, what you're trying to do is "take a sequence, and put every element in it at the end of this other sequence, in the original order". That's spelled extend
. append
is "take this thing, and put it at the end of the list, as a single item, even if it's also a list". (Recall that a list is a kind of sequence.)
But then, you need to be aware that i+1:i+4
is a special construct that appears only inside square brackets (to get a slice from a sequence) and braces (to create a dict
object). You cannot pass it to a function. So you can't extend
with that. You need to make a sequence of those values, and the natural way to do this is with the range
function.
Why not just place your button inside of a reference tag e.g
<a href="https://www.google.com/"><button>Next</button></a>
This seems to work perfectly for me and does not add any %20 tags to the link, just how you want it. I have used a link to google to demonstrate.
You could of course wrap this in a form tag but it is not necessary.
When linking another local file just put it in the same folder and add the file name as the reference. Or specify the location of the file if in is not in the same folder.
<a href="myOtherFile"><button>Next</button></a>
This does not add any character onto the end of the URL either, however it does have the files project path as the url before ending with the name of the file. e.g
If my project structure was...
.. denotes a folder - denotes a file while four | denote a sub directory or file in parent folder
..public
|||| ..html
|||| |||| -main.html
|||| |||| -secondary.html
If I open main.html the URL would be,
http://localhost:0000/public/html/main.html?_ijt=i7ms4v9oa7blahblahblah
However, when I clicked the button inside main.html to change to secondary.html, the URL would be,
http://localhost:0000/public/html/secondary.html
No special characters included at the end of the URL. I hope this helps. By the way - (%20 denotes a space in a URL its encoded and inserted in the place of them.)
Note: The localhost:0000 will obviously not be 0000 you'll have your own port number there.
Furthermore the ?_ijt=xxxxxxxxxxxxxx at the end off the main.html URL, x is determined by your own connection so obviously will not be equal to mine.
It might seem like I'm stating some really basic points but I just want to explain as best as I can. Thank you for reading and I hope this help someone at the very least. Happy programming.
The shortest approach (ES6)
// randomly generated N = 40 length array 0 <= A[N] <= 39
Array.from({length: 40}, () => Math.floor(Math.random() * 40));
Enjoy!
Actually select
does select but not placing the selected values to the respective field . Where wondered the below snippet works perfectly
driver.findElement(By.name("period")).sendKeys("Last 52 Weeks");
I've run into this problem with ICS/JB because the default buttons for the Holo theme consist of images that are slightly transparent. For a background this is especially noticeable.
Gingerbread vs. ICS+:
Copying over all of the drawable states and images for each resolution and making the transparent images solid is a pain, so I've opted for a dirtier solution: wrap the button in a holder that has a white background. Here's a crude XML drawable (ButtonHolder) which does exactly that:
Your XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/Content">
<RelativeLayout style="@style/ButtonHolder">
<Button android:id="@+id/myButton"
style="@style/Button"
android:text="@string/proceed"/>
</RelativeLayout>
</LinearLayout>
ButtonHolder.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
</shape>
</item>
</layer-list>
styles.xml
.
.
.
<style name="ButtonHolder">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:background">@drawable/buttonholder</item>
</style>
<style name="Button" parent="@android:style/Widget.Button">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:textStyle">bold</item>
</style>
.
.
.
However, this results in a white border because the Holo button images include margins to account for the pressed space:
So the solution is to give the white background a margin (4dp worked for me) and rounded corners (2dp) to completely hide the white yet make the button solid:
ButtonHolder.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
</shape>
</item>
<item android:top="4dp" android:bottom="4dp" android:left="4dp" android:right="4dp">
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
<corners android:radius="2dp" />
</shape>
</item>
</layer-list>
The final result looks like this:
You should target this style for v14+, and tweak or exclude it for Gingerbread/Honeycomb because their native button image sizes are different from ICS and JB's (e.g. this exact style behind a Gingerbread button results in a small bit of white below the button).
A generalization of coobird's answer's utility function for creating new HashSet
s:
public static <T> Set<T> newHashSet(T... objs) {
Set<T> set = new HashSet<T>();
for (T o : objs) {
set.add(o);
}
return set;
}
Ultimately you will need to:
Keep in mind flash wont work on Apple devices if that's required.
A print screen will allow someone to recreate the low res image you present, and in this case you could add a watermark to the image.
Go to the Font's stylesheet.css and add font-display: block; in all @font-face { }
This Stackoverflow Answer helped me..
Below is the Summary of the answer
If you can access to css of this extension, simply add font-display:block; on font-face definition or send feedback to developer of this extension:)
@font-face {
font-family: ExampleFont;
src: url(/path/to/fonts/examplefont.woff) format('woff'),
url(/path/to/fonts/examplefont.eot) format('eot');
font-weight: 400;
font-style: normal;
font-display: block;
}
The compiler can't figure out what type to make the Dictionary, because it's not homogenous. You have values of different types. The only way to get around this is to make it a [String: Any]
, which will make everything clunky as all hell.
return [
"title": title,
"is_draft": isDraft,
"difficulty": difficulty,
"duration": duration,
"cost": cost,
"user_id": userId,
"description": description,
"to_sell": toSell,
"images": [imageParameters, imageToDeleteParameters].flatMap { $0 }
] as [String: Any]
This is a job for a struct. It'll vastly simplify working with this data structure.
Unfortunately all the answers in this post didn't work for me. I kept getting following error.
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
I found out that this happens if you use some 3rd party widgets (demandforce in my case) that also call additional external JavaScript files and try to insert HTML. Looking at the console and the JavaScript code, I noticed multiple lines like this:
document.write("<script type='text/javascript' "..."'></script>");
I used 3rd party JavaScript files (htmlParser.js and postscribe.js) from: https://github.com/krux/postscribe. That solved the problem in this post and fixed the above error at the same time.
(This was a quick and dirty way around under the tight deadline I have now. I am not comfortable with using 3rd party JavaScript library however. I hope someone can come up with a cleaner and better way.)
I cannot quickly reproduce the symptoms: if I try myscript '"test"'
with a batch file myscript.bat
containing just @echo.%1
or even @echo.%~1
, I get all quotes: '"test"'
Perhaps you can try the escape character ^
like this: myscript '^"test^"'
?
1- Explanation of Scripts
A)Syntax for inserting data in table is as below
Insert into table(col1,col2,col3,col4,col5)
-- To achieve this part i
--have used below variable
------@CSV_COLUMN-------
values(Col1 data in quote, Col2..quote,..Col5..quote)
-- To achieve this part
-- i.e column data in
--quote i have used
--below variable
----@QUOTED_DATA---
C)To get above data from existing table we have to write the select query in such way that the output will be in form of as above scripts
D)Then Finally i have Concatenated above variable to create final script that's will generate insert script on execution
E)
@TEXT='SELECT ''INSERT INTO
'+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER_CONDITION
F)And Finally Executed the above query EXECUTE(TEXT)
G)QUOTENAME()
function is used to wrap
column data inside quote
H)ISNULL
is used because if any row has NULL
data for any column the query fails
and return NULL
thats why to avoid
that i have used ISNULL
I)And created the sp sp_generate_insertscripts
for same
1- Just put the table name for which you want insert script
2- Filter condition if you want specific results
----------Final Procedure To generate Script------
CREATE PROCEDURE sp_generate_insertscripts
(
@TABLE_NAME VARCHAR(MAX),
@FILTER_CONDITION VARCHAR(MAX)=''
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @CSV_COLUMN VARCHAR(MAX),
@QUOTED_DATA VARCHAR(MAX),
@TEXT VARCHAR(MAX)
SELECT @CSV_COLUMN=STUFF
(
(
SELECT ',['+ NAME +']' FROM sys.all_columns
WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
is_identity!=1 FOR XML PATH('')
),1,1,''
)
SELECT @QUOTED_DATA=STUFF
(
(
SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns
WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
is_identity!=1 FOR XML PATH('')
),1,1,''
)
SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER_CONDITION
--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT
EXECUTE (@TEXT)
SET NOCOUNT OFF
END
From command prompt Run as Administrator. Example below is to print a list of Services running on your PC run the command below:
net start > c:\netstart.txt
You should see a copy of the text file you just exported with a listing all the PC services running at the root of your C:\
drive.
just had the same question, and answered this way, if this could help.
select *
from table
where start_date between '2012-01-01' and '2012-04-13'
or end_date between '2012-01-01' and '2012-04-13'
First step would be making the function object, then applying it. If you want a matrix object that has the same number of rows, you can predefine it and use the object[] form as illustrated (otherwise the returned value will be simplified to a vector):
bvnormdens <- function(x=c(0,0),mu=c(0,0), sigma=c(1,1), rho=0){
exp(-1/(2*(1-rho^2))*(x[1]^2/sigma[1]^2+
x[2]^2/sigma[2]^2-
2*rho*x[1]*x[2]/(sigma[1]*sigma[2]))) *
1/(2*pi*sigma[1]*sigma[2]*sqrt(1-rho^2))
}
out=rbind(c(1,2),c(3,4),c(5,6));
bvout<-matrix(NA, ncol=1, nrow=3)
bvout[] <-apply(out, 1, bvnormdens)
bvout
[,1]
[1,] 1.306423e-02
[2,] 5.931153e-07
[3,] 9.033134e-15
If you wanted to use other than your default parameters then the call should include named arguments after the function:
bvout[] <-apply(out, 1, FUN=bvnormdens, mu=c(-1,1), rho=0.6)
apply() can also be used on higher dimensional arrays and the MARGIN argument can be a vector as well as a single integer.
First of all thanks for this code. I have made some drawing changes in this function to remove corner problem of drawing.
-(void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, [fillColor CGColor]);
CGContextSetStrokeColorWithColor(c, [borderColor CGColor]);
CGContextSetLineWidth(c, 2);
if (position == CustomCellBackgroundViewPositionTop) {
CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
minx = minx + 1;
miny = miny + 1;
maxx = maxx - 1;
maxy = maxy ;
CGContextMoveToPoint(c, minx, maxy);
CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE);
CGContextAddArcToPoint(c, maxx, miny, maxx, maxy, ROUND_SIZE);
CGContextAddLineToPoint(c, maxx, maxy);
// Close the path
CGContextClosePath(c);
// Fill & stroke the path
CGContextDrawPath(c, kCGPathFillStroke);
return;
} else if (position == CustomCellBackgroundViewPositionBottom) {
CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
minx = minx + 1;
miny = miny ;
maxx = maxx - 1;
maxy = maxy - 1;
CGContextMoveToPoint(c, minx, miny);
CGContextAddArcToPoint(c, minx, maxy, midx, maxy, ROUND_SIZE);
CGContextAddArcToPoint(c, maxx, maxy, maxx, miny, ROUND_SIZE);
CGContextAddLineToPoint(c, maxx, miny);
// Close the path
CGContextClosePath(c);
// Fill & stroke the path
CGContextDrawPath(c, kCGPathFillStroke);
return;
} else if (position == CustomCellBackgroundViewPositionMiddle) {
CGFloat minx = CGRectGetMinX(rect) , maxx = CGRectGetMaxX(rect) ;
CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
minx = minx + 1;
miny = miny ;
maxx = maxx - 1;
maxy = maxy ;
CGContextMoveToPoint(c, minx, miny);
CGContextAddLineToPoint(c, maxx, miny);
CGContextAddLineToPoint(c, maxx, maxy);
CGContextAddLineToPoint(c, minx, maxy);
CGContextClosePath(c);
// Fill & stroke the path
CGContextDrawPath(c, kCGPathFillStroke);
return;
}
}
You can use the viewport height, just set the height of your div to height:100vh;
, this will set the height of your div to the height of the viewport of the device, furthermore, if you want it to be exactly as your device screen, set the margin and padding to 0.
Plus, It will be a good idea to set the viewport meta tag:
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0" />
Please Note that this is relatively new and is not supported in IE8-, take a look at the support list before considering this approach (http://caniuse.com/#search=viewport).
Hope this helps.
In the View, modify the current view or create a new view and make a filter change, select the radio button "Show items only when the following is true", in the below columns type "Created" and in the next dropdown select "is less than" and fill the next column [Today]-7.
The keyword [Today] denotes the current day for the calculation and this view will show as per your requirement
Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:
Hopefully like me you have a MySQL database backup handy!
Just write:
date("Y") // A full numeric representation of a year, 4 digits
// Examples: 1999 or 2003
Or:
date("y"); // A two digit representation of a year Examples: 99 or 03
And 'echo' this value...
In preferences Java -> Code Style -> Formatter, edit the profile. Under the Line Wrapping tab is the primary option for line width (Maximum line width:). In the Comments tab you have a separate option Maximum line width for comments:, which will also need to be changed to affect comment wrapping.
You will need to make your own profile to make these changes in if you using one of the [Built-in]
ones. Just click "New..." on the formatter preferences page.
Usually in ruby when you are looking for "type" you are actually wanting the "duck-type" or "does is quack like a duck?". You would see if it responds to a certain method:
@some_var.respond_to?(:each)
You can iterate over @some_var because it responds to :each
If you really want to know the type and if it is Hash or Array then you can do:
["Hash", "Array"].include?(@some_var.class) #=> check both through instance class
@some_var.kind_of?(Hash) #=> to check each at once
@some_var.is_a?(Array) #=> same as kind_of
Here's a project with a rotating camera. Looking through the source it seems to just move the camera position in a circle.
function onDocumentMouseMove( event ) {
event.preventDefault();
if ( isMouseDown ) {
theta = - ( ( event.clientX - onMouseDownPosition.x ) * 0.5 )
+ onMouseDownTheta;
phi = ( ( event.clientY - onMouseDownPosition.y ) * 0.5 )
+ onMouseDownPhi;
phi = Math.min( 180, Math.max( 0, phi ) );
camera.position.x = radious * Math.sin( theta * Math.PI / 360 )
* Math.cos( phi * Math.PI / 360 );
camera.position.y = radious * Math.sin( phi * Math.PI / 360 );
camera.position.z = radious * Math.cos( theta * Math.PI / 360 )
* Math.cos( phi * Math.PI / 360 );
camera.updateMatrix();
}
mouse3D = projector.unprojectVector(
new THREE.Vector3(
( event.clientX / renderer.domElement.width ) * 2 - 1,
- ( event.clientY / renderer.domElement.height ) * 2 + 1,
0.5
),
camera
);
ray.direction = mouse3D.subSelf( camera.position ).normalize();
interact();
render();
}
Here's another demo and in this one I think it just creates a new THREE.TrackballControls
object with the camera as a parameter, which is probably the better way to go.
controls = new THREE.TrackballControls( camera );
controls.target.set( 0, 0, 0 )
Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.
This plugin supports dates just as well, so they get converted to their DateTime
counterpart without a problem.
You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.
All you have to do is to use this plugin on the client side. An Ajax request would look like this:
$.ajax({
type: "POST",
url: "SomeURL",
data: $.toDictionary(yourComplexJSONobject),
success: function() { ... },
error: function() { ... }
});
But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error
function would get called as it's supposed to be.
All type information is erased in JavaScript side and therefore you can't new up T just like @Sohnee states, but I would prefer having typed parameter passed in to constructor:
class A {
}
class B<T> {
Prop: T;
constructor(TCreator: { new (): T; }) {
this.Prop = new TCreator();
}
}
var test = new B<A>(A);
Do keep in mind that you don't need a stable sort if you compare all members. The 2.0 solution, as requested, can look like this:
public void SortList() {
MyList.Sort(delegate(MyClass a, MyClass b)
{
int xdiff = a.x.CompareTo(b.x);
if (xdiff != 0) return xdiff;
else return a.y.CompareTo(b.y);
});
}
Do note that this 2.0 solution is still preferable over the popular 3.5 Linq solution, it performs an in-place sort and does not have the O(n) storage requirement of the Linq approach. Unless you prefer the original List object to be untouched of course.
Just add this function and call it, it will convert List to DataTable.
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Defining type of data column gives proper data table
var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
//Setting column names as Property names
dataTable.Columns.Add(prop.Name, type);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.
I have done the following using OpenCV 3.0.0 and python:
import cv2
#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)
cv2.imshow("img",img)
#-----Converting image to LAB Color model-----------------------------------
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imshow("lab",lab)
#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)
#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)
#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)
#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)
#_____END_____#
You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.
classes are like blueprints to create objects. Let's make a metaphor with building a house. You have the blueprint of the house so you can build a house. You can build as many houses as your resources allow.
In this metaphor, the blueprint is the class and the house is the instantiation of the class, creating an object.
The houses have common attributes like having a roof, living room, etc. This is where you init method goes. It constructs the object (house) with the attributes you want.
Lets suppose you have:
`class house:`
`roof = True`
`def __init__(self, color):`
`self.wallcolor = color`
>> create little goldlock's house:
>> goldlock = house() #() invoke's class house, not function
>> goldlock.roof
>> True
all house's have roofs, now let's define goldlock's wall color to white:
>> goldlock.wallcolor = 'white'
>>goldlock.wallcolor
>> 'white'
Objective-C:
NSString to NSData:
NSString* str= @"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSData to NSString:
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
Swift:
String to Data:
var testString = "string"
var somedata = testString.data(using: String.Encoding.utf8)
Data to String:
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
After reading the documentation: http://momentjs.com/docs/#/displaying/difference/, you have to consider the diff
function like a minus operator.
// today < future (31/01/2014)
today.diff(future) // today - future < 0
future.diff(today) // future - today > 0
Therefore, you have to reverse your condition.
If you want to check that all is fine, you can add an extra parameter to the function:
moment().diff(SpecialTo, 'days') // -8 (days)
You can use this code snippet ...
<html>
<body>
<form>
<input type="radio" name="color" value="black" required />
<input type="radio" name="color" value="white" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Specify "required" keyword in one of the select statements. If you want to change the default way of its appearance. You can follow these steps. This is just for extra info if you have any intention to modify the default behavior.
Add the following into you .css
file.
/* style all elements with a required attribute */
:required {
background: red;
}
For more information you can refer following URL.
math.sqrt
is the C implementation of square root and is therefore different from using the **
operator which implements Python's built-in pow
function. Thus, using math.sqrt
actually gives a different answer than using the **
operator and there is indeed a computational reason to prefer numpy
or math
module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas **
operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow
function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".
See this Stack Overflow question for more information on the difference between **
and math.sqrt
.
In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like **
e.g. C++. So **
is probably more Pythonic, but whether or not it's objectively better depends on the use case.
you could also change from the .get()
method to the .getJSON()
method, jQuery will then parse the string returned as data
to a javascript object and/or array that you can then reference like any other javascript object/array.
using your code above, if you changed .get
to .getJSON
, you should get an alert of [object Object]
for each element in the array. If you changed the alert to alert(item.name)
you will get the names.
Try to call your proc in this way:
DECLARE @UserIDout int
EXEC YOURPROC @EmailAddress = 'sdfds', @NickName = 'sdfdsfs', ..., @UserId = @UserIDout OUTPUT
SELECT @UserIDout
You can use absolute of fixed positioning. This CSS for example will dock a 2em-bar on the left side of your page:
body {
padding-left: 2.5em;
}
body > #bar {
position:fixed;
top:0; left:0;
width: 2em;
height: 100%;
border-right: 2px solid #55F; background: #ddd;
}
For fixing such an issue I have used below code
a.divide(b, 2, RoundingMode.HALF_EVEN)
2 is precision. Now problem was resolved.
You can configure your build.gradle file for proguard implementation. It can be at module level or the project level.
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
The configuration shown is for debug level but you can write you own build flavors like shown below inside buildTypes:
myproductionbuild{
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
Better to have your debug with minifyEnabled false
and productionbuild and other builds as minifyEnabled true
.
Copy your proguard-rules.txt file in the root of your module or project folder like
$YOUR_PROJECT_DIR\YoutProject\yourmodule\proguard-rules.txt
You can change the name of your file as you want. After configuration use one of the three options available to generate your build as per the buildType
Go to gradle task in right panel and search for assembleRelease/assemble(#your_defined_buildtype)
under module tasks
Go to Build Variant in Left Panel and select the build from drop down
Go to project root directory in File Explorer and open cmd/terminal and run
Linux ./gradlew assembleRelease or assemble(#your_defined_buildtype)
Windows gradlew assembleRelease or assemble(#your_defined_buildtype)
You can find apk in your module/build directory.
More about the configuration and proguard files location is available at the link
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Running-ProGuard
Notepad++ changed in the past couple of years, and it requires a few extra steps to set up a dark theme.
The answer by Amit-IO is good, but the example theme that is needed has stopped being maintained. The DraculaTheme is active. Just download the XML and put it in a themes folder. You may need Admin access in Windows.
C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes
There is an alternative approach I used when I couldn't rely on the EXCEPTION
block at the bottom of my procedure. I had variables declared at the beginning:
my_value VARCHAR := 'default';
number_rows NUMBER := 0;
.
.
.
SELECT count(*) FROM TABLE INTO number_rows (etc.)
IF number_rows > 0 -- Then obtain my_value with a query or constant, etc.
END IF;
Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
.GroupBy(o => o.PropertyName)
.ToDictionary(g => g.Key, g => g.ToList());
Warning: Both solutions given ( astype() and apply() ) do not preserve NULL values in either the nan or the None form.
import pandas as pd
import numpy as np
df = pd.DataFrame([None,'string',np.nan,42], index=[0,1,2,3], columns=['A'])
df1 = df['A'].astype(str)
df2 = df['A'].apply(str)
print df.isnull()
print df1.isnull()
print df2.isnull()
I believe this is fixed by the implementation of to_string()
Left joins in LINQ are possible with the DefaultIfEmpty() method. I don't have the exact syntax for your case though...
Actually I think if you just change pets to pets.DefaultIfEmpty() in the query it might work...
EDIT: I really shouldn't answer things when its late...
Unless the variable k
is defined, that's probably what's causing your trouble. Something like this will do what you want:
var new_tweets = { };
new_tweets.k = { };
new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;
new_tweets.k.data = { };
new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';
// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);
You can also do it all at once:
var new_tweets = {
k: {
tweet_id: 98745521,
user_id: 54875,
data: {
in_reply_to_screen_name: 'other_user',
text: 'tweet_text'
}
}
}
git pull
wants you to either remove or save your current work so that the merge it triggers doesn't cause conflicts with your uncommitted work. Note that you should only need to remove/save untracked files if the changes you're pulling create files in the same locations as your local uncommitted files.
git checkout -f
git clean -fd
git stash
git stash -u
git pull
:git stash pop
Cookie-Based Authentication
Cookies based Authentication works normally in these 4 steps-
Browser will submit this session Id on each subsequent requests, the session ID is verified against the database, based on this session id website will identify the session belonging to which client and then give access the request.
Once a user logs out of the app, the session is destroyed both client-side and server-side.
You can use dict.pop
:
mydict.pop("key", None)
Note that if the second argument, i.e. None
is not given, KeyError
is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.
If you are sending alphanumeric data try changing
'Content-Type': 'multipart/form-data'
to
'Content-Type': 'application/x-www-form-urlencoded'
If you are sending non-alphanumeric data try to remove 'Content-Type' at all.
If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)
Don't worry about any performance differences, they're going to be minimal in this case normally.
Method 2 is preferable because
it doesn't require mutating a collection that exists outside the lambda expression,
it's more readable because the different steps that are performed in the collection pipeline are written sequentially: first a filter operation, then a map operation, then collecting the result (for more info on the benefits of collection pipelines, see Martin Fowler's excellent article),
you can easily change the way values are collected by replacing the Collector
that is used. In some cases you may need to write your own Collector
, but then the benefit is that you can easily reuse that.
okay one other solution that I thought of just for the fun of it would be to turn your decimal into a string and then cut the string into 2 strings, one containing the point and the decimals and the other containing the Int to the left of the point. after that you limit the String of the point and decimals to 3 chars, one for the decimal point and the others for the decimals. then just recombine.
double shippingCost = ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;
String ShippingCost = (String) shippingCost;
String decimalCost = ShippingCost.subString(indexOf('.'),ShippingCost.Length());
ShippingCost = ShippingCost.subString(0,indexOf('.'));
ShippingCost = ShippingCost + decimalCost;
There! Simple, right?
To answer the second part of your question, to convert to binary you can use a format string and the ord
function:
>>> byte = 'a'
>>> '{0:08b}'.format(ord(byte))
'01100001'
Note that the format pads with the right number of leading zeros, which seems to be your requirement. This method needs Python 2.6 or later.
JULI logging levels for Tomcat
SEVERE - Serious failures
WARNING - Potential problems
INFO - Informational messages
CONFIG - Static configuration messages
FINE - Trace messages
FINER - Detailed trace messages
FINEST - Highly detailed trace messages
You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html
nmap is a useful tool for this kind of thing
If you dont have SDK or you are setting up 3rd party app here is another way:
To get Ant running on your Mac in 5 minutes, follow these steps.
Open up your terminal.
Perform these commands in order:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install ant
If you don't have Java installed yet, you will get the following error: "Error: An unsatisfied requirement failed this build."
Run this command next: brew cask install java
to fix this.
The installation will resume.
Check your version of by running this command:
ant -version
And you're ready to go!
to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php
$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");
$json_object = json_decode($unparsed_json);
then json_decode() parses JSON into a PHP object, or an array if you pass true
to the second parameter.
http://php.net/manual/en/function.json-decode.php
For example:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json)); // Object
var_dump(json_decode($json, true)); // Associative array
On top of the answers already given, to open a new tab the javascript command window.open()
can be used.
For example:
# Opens a new tab
self.driver.execute_script("window.open()")
# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])
# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here
You're then able to close the original tab as follows
# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
# Close original tab
self.driver.close()
# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])
Or close the newly opened tab
# Close current tab
self.driver.close()
# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
Hope this helps.
The easy way:
var pi=new ProcessStartInfo("C:\file.docx");
pi.UseShellExecute = true;
pi.Verb = "print";
var process = System.Diagnostics.Process.Start(pi);
I know how to create a custom row + custom array adapter to support a custom row for the entire list view. But how can one listview support many different row styles?
You already know the basics. You just need to get your custom adapter to return a different layout/view based on the row/cursor information being provided.
A ListView
can support multiple row styles because it derives from AdapterView:
An AdapterView is a view whose children are determined by an Adapter.
If you look at the Adapter, you'll see methods that account for using row-specific views:
abstract int getViewTypeCount()
// Returns the number of types of Views that will be created ...
abstract int getItemViewType(int position)
// Get the type of View that will be created ...
abstract View getView(int position, View convertView, ViewGroup parent)
// Get a View that displays the data ...
The latter two methods provide the position so you can use that to determine the type of view you should use for that row.
Of course, you generally don't use AdapterView and Adapter directly, but rather use or derive from one of their subclasses. The subclasses of Adapter may add additional functionality that change how to get custom layouts for different rows. Since the view used for a given row is driven by the adapter, the trick is to get the adapter to return the desired view for a given row. How to do this differs depending on the specific adapter.
For example, to use ArrayAdapter,
getView()
to inflate, populate, and return the desired view for the given position. The getView()
method includes an opportunity reuse views via the convertView
parameter.But to use derivatives of CursorAdapter,
newView()
to inflate, populate, and return the desired view for the current cursor state (i.e. the current "row") [you also need to override bindView
so that widget can reuse views]However, to use SimpleCursorAdapter,
SimpleCursorAdapter.ViewBinder
with a setViewValue()
method to inflate, populate, and return the desired view for a given row (current cursor state) and data "column". The method can define just the "special" views and defer to SimpleCursorAdapter's standard behavior for the "normal" bindings.Look up the specific examples/tutorials for the kind of adapter you end up using.
Angular: "9.0.0"
Angular CLI: 9.0.1
Node: 13.10.1
OS: linux x64
.html file
<input [(ngModel)]="userConsent" id="userConsent" required type="checkbox"/> " I Accept"
.ts file
userConsent: boolean = false;
Combination of two previous answers:
var selected = [];
$('#checkboxes input:checked').each(function() {
selected.push($(this).attr('name'));
});
This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx
An example of this is to make a collection of items of a specific type.
class MyArray<T>
{
T[] array = new T[10];
public T GetItem(int index)
{
return array[index];
}
}
In your code, you could then do something like this:
MyArray<int> = new MyArray<int>();
In this case, T[] array
would work like int[] array
, and public T GetItem
would work like public int GetItem
.
You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.
The github repo will be created as a new project in android studio.
If you convert a Bash script into a function, you typically replace exit N
with return N
. The code that calls the function will treat the return value the same as it would an exit code from a subprocess.
Using exit
inside the function will force the entire script to end.
var myDate = DateTime.Now;
var startOfMonth = new DateTime(myDate.Year, myDate.Month, 1);
var endOfMonth = startOfMonth.AddMonths(1).AddDays(-1);
That should give you what you need.
Is there any reason not to use threads? You can use the threading
class.
Instead of finished()
function use the isAlive()
. The result()
function could join()
the thread and retrieve the result. And, if you can, override the run()
and __init__
functions to call the function specified in the constructor and save the value somewhere to the instance of the class.
If security is important to you then opening the file for writing and closing it again will not be enough. At least some of the information will still be on the storage device and could be found, for example, by using a disc recovery utility.
Suppose, for example, the file you're erasing contains production passwords and needs to be deleted immediately after the present operation is complete.
Zero-filling the file once you've finished using it helps ensure the sensitive information is destroyed.
On a recent project we used the following code, which works well for small text files. It overwrites the existing contents with lines of zeros.
import os
def destroy_password_file(password_filename):
with open(password_filename) as password_file:
text = password_file.read()
lentext = len(text)
zero_fill_line_length = 40
zero_fill = ['0' * zero_fill_line_length
for _
in range(lentext // zero_fill_line_length + 1)]
zero_fill = os.linesep.join(zero_fill)
with open(password_filename, 'w') as password_file:
password_file.write(zero_fill)
Note that zero-filling will not guarantee your security. If you're really concerned, you'd be best to zero-fill and use a specialist utility like File Shredder or CCleaner to wipe clean the 'empty' space on your drive.
Why not just use the WordPress get_query_var()
function? WordPress Code Reference
// Test if the query exists at the URL
if ( get_query_var('ppc') ) {
// If so echo the value
echo get_query_var('ppc');
}
Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php
by adding an action during initialization:
add_action('init','add_get_val');
function add_get_val() {
global $wp;
$wp->add_query_var('ppc');
}
Or by adding a hook to the query_vars filter:
function add_query_vars_filter( $vars ){
$vars[] = "ppc";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
@Guffa 's answer is excellent, just point out that maybe is cleaner with an IF statement
select count(IF(Position = 'Manager', 1, NULL)) as ManagerCount
from ...
df[!(is.na(df$start_pc) | df$start_pc==""), ]
Like this:
var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag)
root.setAttribute( 'class', 'myCssClass' );
Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)
root.className += ' myCssClass';
Or, depending on the required browser support, you can use the classList.add()
method:
root.classList.add('myCssClass');
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist
UPDATE:
A more elegant solution for referencing the HTML
element might be this:
var root = document.documentElement;
root.className += ' myCssClass';
// ... or:
// root.classList.add('myCssClass');
//
var c = 'Yash' + '=' + 'Yash-777';
document.cookie = c; // Set the value: "Yash=Yash-777"
document.cookie // Get the value:"Yash=Yash-777"
From Google GWT project Cookies.java
class native code. I have prepared the following functions to perform actions on Cookie.
Function to get all the cookies list as JSON object.
var uriEncoding = false;
function loadCookiesList() {
var json = new Object();
if (typeof document === 'undefined') {
return json;
}
var docCookie = document.cookie;
if (docCookie && docCookie != '') {
var crumbs = docCookie.split('; ');
for (var i = crumbs.length - 1; i >= 0; --i) {
var name, value;
var eqIdx = crumbs[i].indexOf('=');
if (eqIdx == -1) {
name = crumbs[i];
value = '';
} else {
name = crumbs[i].substring(0, eqIdx);
value = crumbs[i].substring(eqIdx + 1);
}
if (uriEncoding) {
try {
name = decodeURIComponent(name);
} catch (e) {
// ignore error, keep undecoded name
}
try {
value = decodeURIComponent(value);
} catch (e) {
// ignore error, keep undecoded value
}
}
json[name] = value;
}
}
return json;
}
To set and Get a Cookie with a particular Name.
function getCookieValue(name) {
var json = loadCookiesList();
return json[name];
}
function setCookie(name, value, expires, domain, path, isSecure) {
var c = name + '=' + value;
if ( expires != null) {
if (typeof expires === 'number') {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
var timeInMs = Date.now();
if (expires > timeInMs ) {
console.log("Seting Cookie with provided expire time.");
c += ';expires=' + (new Date(expires)).toGMTString();
} else if (expires < timeInMs) {
console.log("Seting Cookie with Old expire time, which is in Expired State.");
timeInMs = new Date(timeInMs + 1000 * expires);
c += ';expires=' + (new Date(timeInMs)).toGMTString();
}
} else if (expires instanceof window.Date) {
c += ';expires=' + expires.toGMTString();
}
}
if (domain != null && typeof domain == 'string')
c += ';domain=' + domain;
if (path != null && typeof path == 'string')
c += ';path=' + path;
if (isSecure != null && typeof path == 'boolean')
c += ';secure';
if (uriEncoding) {
encodeURIComponent(String(name))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
.replace(/[\(\)]/g, escape);
encodeURIComponent(String(value))
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
}
document.cookie = c;
}
function removeCookie(name) {
document.cookie = name + "=;expires=Fri, 02-Jan-1970 00:00:00 GMT";
}
function removeCookie(name, path) {
document.cookie = name + "=;path=" + path + ";expires=Fri, 02-Jan-1970 00:00:00 GMT";
}
Checks whether a cookie name is valid: can't contain '=', ';', ',', or whitespace
. Can't begin with $
.
function isValidCookieName(name) {
if (uriEncoding) {
// check not necessary
return true;
} else if (name.includes("=") || name.includes(";") || name.includes(",") || name.startsWith("$") || spacesCheck(name) ) {
return false;
} else {
return true;
}
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
function spacesCheck(name) {
var whitespace = new RegExp('.*\\s+.*');
var result = whitespace.test(name);
console.log("Name:isContainSpace = ", name, ":", result);
return result;
}
Test steps to check the above functions:
setCookie("yash1", "Yash-777");
setCookie("yash2", "Yash-Date.now()", Date.now() + 1000 * 30);
setCookie("yash3", "Yash-Sec-Feature", 30);
setCookie("yash4", "Yash-Date", new Date('November 30, 2020 23:15:30'));
getCookieValue("yash4"); // Yash-Date
getCookieValue("unknownkey"); // undefined
var t1 = "Yash", t2 = "Y ash", t3 = "Yash\n";
spacesCheck(t1); // False
spacesCheck(t2); // True
spacesCheck(t3); // True
Don't use localhost in the url!
Use like this:
The answer given by Jeremy Ruten is great, but I think it's not exactly what Paul Wicks was searching for. If I understand correctly Paul asked about expression to match non-english words like können
or móc
. Jeremy's regex matches only non-english letters, so there's need for small improvement:
([^\x00-\x7F]|\w)+
or
([^\u0000-\u007F]|\w)+
This [^\x00-\x7F]
and this [^\u0000-\u007F]
parts allow regullar expression to match non-english letters.
This (|)
is logical or and \w
is english letter, so ([^\u0000-\u007F]|\w)
will match single english or non-english letter.
+
at the end of the expression means it could be repeated, so the whole expression allows all english or non-english letters to match.
Here you can test the first expression with various strings and here is the second.
Below command will display the modfied files alone in windows.
svn status | findstr "^M"
Just set the property as follows:
When the user press "clear button" or "delete key" do
dtpData.CustomFormat = " " 'An empty SPACE
dtpData.Format = DateTimePickerFormat.Custom
On DateTimePicker1_ValueChanged
event do
dtpData.CustomFormat = "dd/MM/yyyy hh:mm:ss"
letronje's solution only works for very simple pages. document.body.innerHTML +=
takes the HTML text of the body, appends the iframe HTML, and sets the innerHTML of the page to that string. This will wipe out any event bindings your page has, amongst other things. Create an element and use appendChild
instead.
$.post('/create_binary_file.php', postData, function(retData) {
var iframe = document.createElement("iframe");
iframe.setAttribute("src", retData.url);
iframe.setAttribute("style", "display: none");
document.body.appendChild(iframe);
});
Or using jQuery
$.post('/create_binary_file.php', postData, function(retData) {
$("body").append("<iframe src='" + retData.url+ "' style='display: none;' ></iframe>");
});
What this actually does: perform a post to /create_binary_file.php with the data in the variable postData; if that post completes successfully, add a new iframe to the body of the page. The assumption is that the response from /create_binary_file.php will include a value 'url', which is the URL that the generated PDF/XLS/etc file can be downloaded from. Adding an iframe to the page that references that URL will result in the browser promoting the user to download the file, assuming that the web server has the appropriate mime type configuration.
def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
In you want to know the data from de selected row, you can try this snippet code:
DataGridView1.SelectedRows.Item(0).Cells(1).Value
I discovered while following the above suggestions that for line in f: does not work for a pandas dataframe (not that anyone said it would) because the end of file in a dataframe is the last column, not the last row. for example if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the 3rd iteration, not after the 9th iteration. Teresa
For me, I was receiving this error when connecting to the new IP Address I had configured FileZilla to bind to and saved the configuration. After trying all of the other answers unsuccessfully, I decided to connect to the old IP Address to see what came up; lo and behold it responded.
I restarted the FileZilla Windows Service and it immediately came back listening on the correct IP. Pretty elementary, but it cost me some time today as a noob to FZ.
Hopefully this helps someone out in the same predicament.
You can see and select which Swift version Xcode is using in:
Target -> Build Settings -> Swift Language Version:
This is available in Xcode 8.3 and Xcode 9 (haven't checked older versions)
I had this problem and for me it was due to creating and manipulating resource files outside Android Studio. I followed the instructions on creating new resource files and folders through Android Studio and solved the problem. You need to create a new Resource File Not directory. It will let you specify or create a directory for you if you need it. If you are creating directories for layouts for different versions, enter the info at the top including the name of the resource file you want to copy to the new folder and select Version and enter the Android version. It will create the appropriate directory with a copy of your resource in it.
Incase you have multiple versions of Postgres installed on your machine. You can remove all via brew
command as:
brew uninstall --force postgresql
I think we should use click
instead change
Working DEMO
import urllib2
try:
fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
data = fileHandle.read()
fileHandle.close()
except urllib2.URLError, e:
print 'you got an error with the code', e
$(function() {
$('.phrase .items').each(function(i, items_list){
var myText = "";
$(items_list).find('li').each(function(j, li){
alert(li.text());
})
alert(myText);
});
};
It's the conditional operator.
a ? b : c
It's a shortcut for IF/THEN/ELSE.
means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.
"Include of non-modular header inside framework module"
When you get this error the solution in some circumstances can be to simply to mark the file you're trying to import as "public" in the file inspector "Target Membership". The default is "Project", and when set this way it can cause this error. That was the case with me when trying to import Google Analytic's headers into a framework, for example.
The cURL extension to PHP is designed to allow you to use a variety of web resources from within your PHP script.
I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder
range = 10..50
rand(range)
or
range.to_a.sample
or
range.to_a.shuffle(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)
True you can't have different sized slides. NOT true the size of you slide doesn't matter. It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.
Run this convenient SQL query to see running MySQL queries. It can be run from any environment you like, whenever you like, without any code changes or overheads. It may require some MySQL permissions configuration, but for me it just runs without any special setup.
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep';
The only catch is that you often miss queries which execute very quickly, so it is most useful for longer-running queries or when the MySQL server has queries which are backing up - in my experience this is exactly the time when I want to view "live" queries.
You can also add conditions to make it more specific just any SQL query.
e.g. Shows all queries running for 5 seconds or more:
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND TIME >= 5;
e.g. Show all running UPDATEs:
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND INFO LIKE '%UPDATE %';
For full details see: http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html
Error
and Exception
both extend Throwable
, but mostly Error
is thrown by JVM in a scenario which is fatal and there is no way for the application program to recover from that error. For instance OutOfMemoryError
.
Though even application can raise an Error
but its just not a good a practice, instead applications should use checked exceptions for recoverable conditions and runtime exceptions for programming errors.
This is what you are looking for. It has examples for each side you want with a shadow.
.top-box
{
box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.4);
}
.left-box
{
box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.4);
}
.right-box
{
box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.4);
}
.bottom-box
{
box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.4);
}
See the snippet for more examples:
body {
background-color:#0074D9;
}
div {
background-color:#ffffff;
padding:20px;
margin-top:10px;
}
.top-box {
box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.7);
}
.left-box {
box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.7);
}
.right-box {
box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.7);
}
.bottom-box {
box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.7);
}
.top-gradient-box {
background: linear-gradient(to bottom, #999 0, #ffffff 7px, #ffffff 100%);
}
.left-gradient-box {
background: linear-gradient(to right, #999 0, #ffffff 7px, #ffffff 100%);
}
.right-gradient-box {
background: linear-gradient(to left, #999 0, #ffffff 7px, #ffffff 100%);
}
.bottom-gradient-box {
background: linear-gradient(to top, #999 0, #ffffff 7px, #ffffff 100%);
}
_x000D_
<div class="top-box">
This area has a top shadow using box-shadow
</div>
<div class="left-box">
This area has a left shadow using box-shadow
</div>
<div class="right-box">
This area has a right shadow using box-shadow
</div>
<div class="bottom-box">
This area has a bottom shadow using box-shadow
</div>
<div class="top-gradient-box">
This area has a top shadow using gradients
</div>
<div class="left-gradient-box">
This area has a left shadow using gradients
</div>
<div class="right-gradient-box">
This area has a right shadow using gradients
</div>
<div class="bottom-gradient-box">
This area has a bottom shadow using gradients
</div>
_x000D_
Here is a complete example
#include <thread>
#include <iostream>
class Wrapper {
public:
void member1() {
std::cout << "i am member1" << std::endl;
}
void member2(const char *arg1, unsigned arg2) {
std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
}
std::thread member1Thread() {
return std::thread([=] { member1(); });
}
std::thread member2Thread(const char *arg1, unsigned arg2) {
return std::thread([=] { member2(arg1, arg2); });
}
};
int main(int argc, char **argv) {
Wrapper *w = new Wrapper();
std::thread tw1 = w->member1Thread();
std::thread tw2 = w->member2Thread("hello", 100);
tw1.join();
tw2.join();
return 0;
}
Compiling with g++ produces the following result
g++ -Wall -std=c++11 hello.cc -o hello -pthread
i am member1
i am member2 and my first arg is (hello) and second arg is (100)
With ggplot2 version 2.1.0 it is
+ scale_y_continuous(labels = scales::percent)
no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.
The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of asp.net.
edit:
here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:
public ActionResult GetData()
{
var data = new { Name="kevin", Age=40 };
return Json(data, JsonRequestBehavior.AllowGet);
}
This return data could be called via JQuery as an ajax call thusly:
$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); });
I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:
TypeError: 'int' object is not callable
My code for Python 3 is as follows:
# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: {M_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: {F_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: {G_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: {inches_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
# Printing error in the line below
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
I hope this helps.
Pushwatch is a free to use online GCM and APNS push notification tester developed by myself in Django/Python as I have found myself in a similar situation while working on multiple projects. It can send both GCM
and APNS
notifications and also support JSON messages for extra arguments. Following are the links to the testers.
Please let me know if you have any questions or face issues using it.
You can add a comment to an MSAccess query as follows: Create a dummy field in the query. Not elegant but is self-documentating and contained in the query, which makes cheking it into source code control alot more feasible! Jere's an example. Go into SQL view and add the dummy field (you can do from design view too):
SELECT "2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;" as qryHISTORY, ...rest of query here...
Run the query:
qryHISTORY FIELD01 FIELD02 ...
2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;" 0000001 ABCDEF ...
Note the use of ";" as field delimiter in qryHISTORY field, and ";;" as an end of comment, and use of ISO date format and intials, as well as comment. Have tested this with up to 646 characters in the qryHISTORY field.
It's possible that you're creating your controls on the wrong thread. Consider the following documentation from MSDN:
This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created.
In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.
You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.
Let's see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)
Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let's follow the logic:
public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
if (uiElement == null)
{
throw new ArgumentNullException("uiElement");
}
if (uiElement.InvokeRequired)
{
if (forceSynchronous)
{
uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
}
else
{
uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
}
}
else
{
if (uiElement.IsDisposed)
{
throw new ObjectDisposedException("Control is already disposed.");
}
updater();
}
}
Consider the case where we're calling SafeInvoke
from the non-gui thread for a control whose handle has not been created.
uiElement
is not null, so we check uiElement.InvokeRequired
. Per the MSDN docs (bolded) InvokeRequired
will return false
because, even though it was created on a different thread, the handle hasn't been created! This sends us to the else
condition where we check IsDisposed
or immediately proceed to call the submitted action... from the background thread!
At this point, all bets are off re: that control because its handle has been created on a thread that doesn't have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you're encountering?
Just had that problem in a production system in the company where I live... A webpage that made a LDAP bind stopped working after an IP changed.
The solution... ... I installed Basic Authentication to perform the troubleshooting indicated here: https://support.microsoft.com/en-us/kb/329986
And after that, things just started to work. Even after I re-disabled Basic Authentication in the page I was testing, all other pages started working again with Windows Authentication.
Regards, Acácio
str_pad
from the stringr
package is an alternative.
anim = 25499:25504
str_pad(anim, width=6, pad="0")
To expand one what CheeseConQueso is saying, here are the entire steps to update a view using PHPMyAdmin:
SHOW CREATE VIEW your_view_name
CREATE VIEW
... syntax) to make sure it runs as you expect it to.CREATE VIEW...
syntax).I hope that helps somebody. Special thanks to CheesConQueso for his/her insightful answer.
Thinking more about it, I would like to throw out tuples as a more general-purpose way of dealing with this problem. While tuples are not native to Java, I use Javatuples to provide me the same functionality which would exist in other languages. An example of how to deal with the question asked is
Map<Pair<Integer, String>, String> arr = new HashMap<Pair<Integer, String>, String>();
Pair p1 = new Pair(0, "name");
arr.put(p1, "demo");
I like this approach because it can be extended to triples and other higher ordered groupings with api provided classes and methods.
Update July 2012 (git 1.7.12+)
You now can rebase all commits up to root, and select the second commit Y
to be squashed with the first X
.
git rebase -i --root master
pick sha1 X
squash sha1 Y
pick sha1 Z
git rebase [-i] --root $tip
This command can now be used to rewrite all the history leading from "
$tip
" down to the root commit.
See commit df5df20c1308f936ea542c86df1e9c6974168472 on GitHub from Chris Webb (arachsys
).
Original answer (February 2009)
I believe you will find different recipes for that in the SO question "How do I combine the first two commits of a git repository?"
Charles Bailey provided there the most detailed answer, reminding us that a commit is a full tree (not just diffs from a previous states).
And here the old commit (the "initial commit") and the new commit (result of the squashing) will have no common ancestor.
That mean you can not "commit --amend
" the initial commit into new one, and then rebase onto the new initial commit the history of the previous initial commit (lots of conflicts)
(That last sentence is no longer true with git rebase -i --root <aBranch>
)
Rather (with A
the original "initial commit", and B
a subsequent commit needed to be squashed into the initial one):
Go back to the last commit that we want to form the initial commit (detach HEAD):
git checkout <sha1_for_B>
Reset the branch pointer to the initial commit, but leaving the index and working tree intact:
git reset --soft <sha1_for_A>
Amend the initial tree using the tree from 'B':
git commit --amend
Temporarily tag this new initial commit (or you could remember the new commit sha1 manually):
git tag tmp
Go back to the original branch (assume master for this example):
git checkout master
Replay all the commits after B onto the new initial commit:
git rebase --onto tmp <sha1_for_B>
Remove the temporary tag:
git tag -d tmp
That way, the "rebase --onto
" does not introduce conflicts during the merge, since it rebases history made after the last commit (B
) to be squashed into the initial one (which was A
) to tmp
(representing the squashed new initial commit): trivial fast-forward merges only.
That works for "A-B
", but also "A-...-...-...-B
" (any number of commits can be squashed into the initial one this way)
In classic mode IIS works h ISAPI extensions and ISAPI filters directly. And uses two pipe lines , one for native code and other for managed code. You can simply say that in Classic mode IIS 7.x works just as IIS 6 and you dont get extra benefits out of IIS 7.x features.
In integrated mode IIS and ASP.Net are tightly coupled rather then depending on just two DLLs on Asp.net as in case of classic mode.
This happened to me when I have multiple angular modules in the same page
I encountered this error when I used partial views
One partial view had
<script src="~/Scripts/Items.js"></script>
<div ng-app="SearchModule">
<div ng-controller="SearchSomething" class="col-md-1">
<input class="searchClass" type="text" placeholder="Search" />
</div>
</div>
Other had
<div ng-app="FeaturedItems" ng-controller="featured">
<ul>
<li ng-repeat="item in Items">{{item.Name}}</li>
</ul>
</div>
I had them in same module with different controller and it started working
I know this is kinda an old question but:
root["bg"] = "black"
will also do what you want and it involves less typing.
You may be trying to use a JSON object:
var myMappings = { "name": "10%", "phone": "10%", "address": "50%", etc.. }
To access:
myMappings.name;
myMappings.phone;
etc..
please set dataType config property in your ajax call and give it another try!
another point is you are using ajax call setup configuration properties as string and it is wrong as reference site
$.ajax({
url : 'http://voicebunny.comeze.com/index.php',
type : 'GET',
data : {
'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I hope be helpful!
You can use MediaQuery for parent's dimension or FractionallySizedBox as containers.
Using jackson, you can do it as follows:
ObjectMapper mapper = new ObjectMapper();
String clientFilterJson = "";
try {
clientFilterJson = mapper.writeValueAsString(filterSaveModel);
} catch (IOException e) {
e.printStackTrace();
}
I was facing the same error while running command
pip install --upgrade pip
in a virtual venvironment (created with python -m venv venv).
using the --user flag fixed the problem for me
pip install --upgrade pip --user
If the problem not resolved use --user flag in a command prompt with admin rights.
It's possible that you already have the Lombok
plugin, and still the generated methods are not recognised by Android Studio
. In such case the plugin might be out of date, so the solution is to simply update it.
Preferences -> Plugins -> Lombok Plugin -> Update Plugin
All of these answers, as of January 2016, are unnecessary. In Interface Builder, set the View Semantic to Force Right-to-Left
, or if you prefer programmatic way, semanticContentAttribute = .forceRightToLeft
That will cause the image to appear on the right of your text.
Based on Mohammed Radwan's answer I came up with the following jQuery solution. Basically what it does is keep track of what iFrame people are hovering. Then if the window blurs that most likely means the user clicked the iframe banner.
the iframe should be put in a div with an id, to make sure you know which iframe the user clicked on:
<div class='banner' bannerid='yyy'>
<iframe src='http://somedomain.com/whatever.html'></iframe>
<div>
so:
$(document).ready( function() {
var overiFrame = -1;
$('iframe').hover( function() {
overiFrame = $(this).closest('.banner').attr('bannerid');
}, function() {
overiFrame = -1
});
... this keeps overiFrame at -1 when no iFrames are hovered, or the 'bannerid' set in the wrapping div when an iframe is hovered. All you have to do is check if 'overiFrame' is set when the window blurs, like so: ...
$(window).blur( function() {
if( overiFrame != -1 )
$.post('log.php', {id:overiFrame}); /* example, do your stats here */
});
});
Very elegant solution with a minor downside: if a user presses ALT-F4 when hovering the mouse over an iFrame it will log it as a click. This only happened in FireFox though, IE, Chrome and Safari didn't register it.
Thanks again Mohammed, very useful solution!
Try adding the other two non COUNT columns to the GROUP BY:
select CURRENT_DATE-1 AS day,
model.name,
attempt.type,
CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END,
count(*)
from attempt attempt, prod_hw_id prod_hw_id, model model
where time >= '2013-11-06 00:00:00'
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
group by 1,2,3,4
order by model.name, attempt.type, attempt.result;
When git stash -p
(or git add -p
with stash --keep-index
) would be too cumbersome, I found it easier to use diff
, checkout
and apply
:
To "stash" a particular file/dir only:
git diff path/to/dir > stashed.diff
git checkout path/to/dir
Then afterwards
git apply stashed.diff
in your Xcode:
use PlaceHolderView
@Layout(R.layout.item_view_1)
public class View1{
@View(R.id.txt)
public TextView txt;
@Resolve
public void onResolved() {
txt.setText(String.valueOf(System.currentTimeMillis() / 1000));
}
@Click(R.id.btn)
public void onClick(){
txt.setText(String.valueOf(System.currentTimeMillis() / 1000));
}
}
Some handy script:
hour = df['assess_time'].dt.hour.values[0]
ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:
// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);
// => "Yo, Brendan!"
var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);
//=> JavaScript first appeared 20 years ago. Crazy!
I just had to figure this out for a client presentation and found a work around to having the GIF play a few times by making a fake loop.
Hope this helps.
Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want
x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)
WORD.C <- function(WORDS){
require(wordcloud)
L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))
# Takes a dataframe and the text you want to display
FUN <- function(X, text){
windows()
wordcloud(X[, 1], X[, 2], min.freq=1)
mtext(text, 3, padj=-4.5, col="red") #what I'm trying that isn't working
}
# Now creates the sequence 1,...,length(L2)
# Loops over that and then create an anonymous function
# to send in the information you want to use.
lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})
# Since you asked about loops
# you could use i in seq_along(L2)
# instead of 1:length(L2) if you wanted to
#for(i in 1:length(L2)){
# FUN(L2[[i]], names(L2)[i])
#}
}
WORD.C(list.xy)
I created .pfx file from .key and .pem files.
Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx
That's not the direct answer but still maybe it helps out someone else.
As stated in the official migration guide, this error is encountered when:
Your app includes a build type that a library dependency does not
android {
buildTypes {
release {
...
}
dexOptions {
...
// release & debug is in project animators
matchingFallbacks = ['release', 'debug']
}
debug {
...
}
}
}
Correct place to find the info is now this documentation
remove leading and trailing white space in 2nd column
awk 'BEGIN{FS=OFS=","}{gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2)}1' input.txt
another way by one gsub:
awk 'BEGIN{FS=OFS=","} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' infile
Try to create remote origin first, maybe is missing because you change name of the remote repo
git remote add origin URL_TO_YOUR_REPO
you can use default ng-submitted is set if the form was submitted.
https://docs.angularjs.org/api/ng/directive/form
example: http://jsbin.com/cowufugusu/1/
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
I started seeing the
Fatal error in launcher: Unable to create process using '"'
after installing Python 3.6 onto a Windows 10 machine. I set the Path variable to point to the Python36 folder. The python command functioned correctly, but the pip command did not.
To fix the error, I opend up the command prompt shell with administrator privileges and ran the pip commands.
If you can make a abstract class for all the possibilities then that is highly recommended:
public Hardware GetAnything()
{
Computer computer = new Computer();
return computer;
}
abstract Hardware {
}
class Computer : Hardware {
}
Or an interface:
interface IHardware {
}
class Computer : IHardware {
}
If it can be anything then you could consider using "object" as your return type, because every class derives from object.
public object GetAnything()
{
Hello hello = new Hello();
return hello;
}
At some point a duplicate copy of apply plugin: 'com.android.application'
got added to my build gradle. Removing the duplicate copy and making sure all my apply plugins were at the top fixed the issue for me.
Found the solution in Spring security examples posted in Github.
WebSecurityConfigurerAdapter
has a overloaded configure
message that takes WebSecurity
as argument which accepts ant matchers on requests to be ignored.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/authFailure");
}
See Spring Security Samples for more details
If you have source as a string like "abcd"
and want to produce a list like this:
{ "a.a" },
{ "b.b" },
{ "c.c" },
{ "d.d" }
then call:
List<string> list = source.Select(c => String.Concat(c, ".", c)).ToList();
This is an annoying Eclipse Bug which seems to bite now and then. See http://dev-answers.blogspot.de/2009/06/eclipse-build-errors-javalangobject.html for a possible solution, otherwise try the following;
Close the project and reopen it.
Clean the project (It will rebuild the buildpath hence reconfiguring with the JDK libraries)
OR
Delete and Re-import the project and if necessary do the above steps again.
The better cure is to try NetBeans instead of Eclipse :-)
Surprised no one has suggested a yield solution:
public static IEnumerable<char> Alphabet()
{
for (char letter = 'A'; letter <= 'Z'; letter++)
{
yield return letter;
}
}
Example:
foreach (var c in Alphabet())
{
Console.Write(c);
}
If you know the width of the span you could just stuff in a left margin.
Try this:
.center { text-align: center}
div.center span { display: table; }
Add the "center: class to your .
If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.
You can use the :nth-child
pseudo class like this:
.countTable table table td:nth-child(2)
Note though, this won't work in older browsers (or IE), you'll need to give the cells a class or use javascript in that case.
One way to keep the Enums and to create a Dynamic list of values at the same time is to use the Enums that you currently have with a Dynamically created Dictionary.
Since most Enums are used in the context that they are defined to be used, and the "dynamic enums" will be supported by dynamic processes, you can distinguish the 2.
The first step is to create a table/collection that houses the IDs and References for the Dynamic Entries. In the table you will autoincrement much larger than your largest Enum value.
Now comes the part for your dynamic Enums, I am assuming that you will be using the Enums to create a set of conditions that apply a set of rules, some are dynamically generated.
Get integer from database
If Integer is in Enum -> create Enum -> then run Enum parts
If Integer is not a Enum -> create Dictionary from Table -> then run Dictionary parts.
Personally, I find it both elegant and convenient to wrap the fill function.
To fill between two equally sized row vectors Y1
and Y2
that share the support X
(and color C):
fill_between_lines = @(X,Y1,Y2,C) fill( [X fliplr(X)], [Y1 fliplr(Y2)], C );
I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.
See help(Sys.sleep)
.
For example, from ?Sys.sleep
testit <- function(x)
{
p1 <- proc.time()
Sys.sleep(x)
proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)
Yielding
> testit(3.7)
user system elapsed
0.000 0.000 3.704
i have this error using datatables.net
i fixed changing the default ajax Get to POST in te properties of the DataTable()
"ajax": {
"url": "../ControllerName/MethodJson",
"type": "POST"
},
In a programming context, directives provide guidance to the compiler to alter how it would otherwise process input, i.e change some behaviour.
“Directives allow you to attach behavior to elements in the DOM.”
directives are split into the 3 categories:
Yes, in Angular 2, Components are a type of Directive. According to the Doc,
“Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.”
Angular 2 Components are an implementation of the Web Component concept. Web Components consists of several separate technologies. You can think of Web Components as reusable user interface widgets that are created using open Web technology.
Answer 1:
Downloading bootstrap through npm (or bower) permits you to gain some latency time. Instead of getting a remote resource, you get a local one, it's quicker, except if you use a cdn (check below answer)
"npm" was originally to get Node Module, but with the essort of the Javascript language (and the advent of browserify), it has a bit grown up. In fact, you can even download AngularJS on npm, that is not a server side framework. Browserify permits you to use AMD/RequireJS/CommonJS on client side so node modules can be used on client side.
Answer 2:
If you npm install bootstrap (if you dont use a particular grunt or gulp file to move to a dist folder), your bootstrap will be located in "./node_modules/bootstrap/bootstrap.min.css" if I m not wrong.
What Arne said - you can't reliably style select boxes and have them look anything like consistent across browsers.
Uniform: https://github.com/pixelmatrix/uniform is a javascript solution which gives you good graphic control over your form elements - it's still Javascript, but it's about as nice as javascript gets for solving this problem.
There is a way simpler way. You put the href in a paragraph just created for that href. For example:
HREF name
To get a list of all childs of a specific type you can use:
private static IEnumerable<DependencyObject> FindInVisualTreeDown(DependencyObject obj, Type type)
{
if (obj != null)
{
if (obj.GetType() == type)
{
yield return obj;
}
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
foreach (var child in FindInVisualTreeDown(VisualTreeHelper.GetChild(obj, i), type))
{
if (child != null)
{
yield return child;
}
}
}
}
yield break;
}
I'm not using YUI, but in case it helps anyone else - my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).
Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.
@JustinCave - The "when value_error" replacement for "when others" is a nice refinement to your approach above. This slight additional tweak, while conceptually the same, removes the requirement for the definition of and consequent memory allocation to your l_num variable:
function validNumber(vSomeValue IN varchar2)
return varchar2 DETERMINISTIC PARALLEL_ENABLE
is
begin
return case when abs(vSomeValue) >= 0 then 'T' end;
exception
when value_error then
return 'F';
end;
Just a note also to anyone preferring to emulate Oracle number format logic using the "riskier" REGEXP approach, please don't forget to consider NLS_NUMERIC_CHARACTERS and NLS_TERRITORY.
Try disabling the extension Bundler & Minifier
This displays files with its permisions
stat -c '%a - %n' directory/*
Just to add that using os.listdir() does not "take a lot of processing vs very simple os.walk().next()[1]". This is because os.walk() uses os.listdir() internally. In fact if you test them together:
>>>> import timeit
>>>> timeit.timeit("os.walk('.').next()[1]", "import os", number=10000)
1.1215229034423828
>>>> timeit.timeit("[ name for name in os.listdir('.') if os.path.isdir(os.path.join('.', name)) ]", "import os", number=10000)
1.0592019557952881
The filtering of os.listdir() is very slightly faster.
When you just want to do a try catch without handling the exception, how do you do it in Python?
It depends on what you mean by "handling."
If you mean to catch it without taking any action, the code you posted will work.
If you mean that you want to take action on an exception without stopping the exception from going up the stack, then you want something like this:
try:
do_something()
except:
handle_exception()
raise #re-raise the exact same exception that was thrown
Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.
You can use the result variable as your temporary, like this:
dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();
This, however, is hard to read.
You can do it using old DirectShow functionality.
This answer teaches you how to create QuartzTypeLib.dll
:
Run tlbimp tool (in your case path will be different):
Run TlbImp.exe %windir%\system32\quartz.dll /out:QuartzTypeLib.dll
Alternatively, this project contains the library interop.QuartzTypeLib.dll
, which is basically the same thing as steps 1. and 2. The following steps teach how to use this library:
Add generated QuartzTypeLib.dll as a COM-reference to your project (click right mouse button on the project name in "Solution Explorer", then select "Add" menu item and then "Reference")
In your Project, expand the "References", find the QuartzTypeLib reference. Right click it and select properties, and change "Embed Interop Types" to false. (Otherwise you won't be able to use the FilgraphManager class in your project (and probably a couple of other ones)).
In Project Settings, in the Build tab, I had to disable the Prefer 32-bit flag, Otherwise I would get this Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040266
Use this class to play your favorite MP3 file:
using QuartzTypeLib;
public sealed class DirectShowPlayer
{
private FilgraphManager FilterGraph;
public void Play(string path)
{
FilgraphManager = new FilgraphManager();
FilterGraph.RenderFile(path);
FilterGraph.Run();
}
public void Stop()
{
FilterGraph?.Stop();
}
}
PS: TlbImp.exe
can be found here:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin"
, or in
"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools"