Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
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.
The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
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.
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Let's, just as example:
public class Test { public Test() { System.out.println("NO ARGS"); } public Test(String s) { this(); System.out.println("1 ARG"); } public static void main(String args[]) { Test t = new Test("s"); } }
It will print
>>> NO ARGS >>> 1 ARG
The correct way to call the constructor is by:
this();
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
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();
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
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.
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.
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.
No -P needed; -E is sufficient:
grep -E '(^|\s)abc(\s|$)'
or even without -E:
grep '\(^\|\s\)abc\(\s\|$\)'
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
var Text = File.ReadAllLines("Path"); foreach (var i in Text) { var SplitText = i.Split().Where(x=> x.Lenght>1).ToList(); //@Array1 add SplitText[0] //@Array2 add SpliteText[1] }
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
The link you gave does actually describe the differences, but it's buried at the bottom of the page:
http://www.cplusplus.com/reference/cstdio/fopen/
Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.
The conversion could be to normalize \r\n
to \n
(or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.
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');
both your conditions are the same:
if(s < f) { calc = f - s; n = s; }else if(f > s){ calc = s - f; n = f; }
so
if(s < f)
and
}else if(f > s){
are the same
change to
}else if(f < s){
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
You can use Jquery's on method and listen for the scroll
event.
Here's one way in XSLT 2
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"','''')"/> </xsl:template> </xsl:stylesheet>
Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:variable name="apos">'</xsl:variable> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"',$apos)"/> </xsl:template> </xsl:stylesheet>
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 } }
Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:
<script type="text/javascript"> $(function() { //jQuery trick to say after all the HTML is parsed. $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); }); </script>
EDIT: This code works for me
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <strong>Choose a base package:</strong> <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942 <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313 <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829 <strong>Choose an add on:</strong> <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0 <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146) <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455) <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764) <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073) <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382) <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691) <strong>Your total is:</strong> <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); </script> </body> </html>
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.
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.
Instead of adding the line breaks with nl2br() and then removing the line breaks with explode(), try using the line break character '\r' or '\n' or '\r\n'.
<?php $options= file_get_contents("employees.txt"); $options=explode("\n",$options); // try \r as well. foreach ($options as $singleOption){ echo "<option value='".$singleOption."'>".$singleOption."</option>"; } ?>
This could also fix the issue if the problem was due to Google Spreadsheets reading the line breaks.
I changed Scanner fin = new Scanner(file);
to Scanner fin = new Scanner(new File(file));
and it works perfectly now. I didn't think the difference mattered but there you go.
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.
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
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
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
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);
Change <?php echo $proxy ?>
to ' . $proxy . '
.
You use <?php
when you're outputting HTML by leaving PHP mode with ?>
. When you using echo
, you have to use concatenation, or wrap your string in double quotes and use interpolation.
The Laravel 8 documentation actually answers this issue more succinctly and clearly than any of the answers here:
In previous releases of Laravel, the RouteServiceProvider
contained a $namespace
property. This property's value would automatically be prefixed onto controller route definitions and calls to the action
helper / URL::action
method. In Laravel 8.x, this property is null
by default. This means that no automatic namespace prefixing will be done by Laravel. Therefore, in new Laravel 8.x applications, controller route definitions should be defined using standard PHP callable syntax:
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
Calls to the action
related methods should use the same callable syntax:
action([UserController::class, 'index']);
return Redirect::action([UserController::class, 'index']);
If you prefer Laravel 7.x style controller route prefixing, you may simply add the $namespace
property into your application's RouteServiceProvider
.
There's no explanation as to why Taylor Otwell added this maddening gotcha, but I presume he had his reasons.
My experience, yesterday my iOS 13.6
is supported by Xcode 11.7
and now today the Xcode rejected my iPhone and I update the Xcode to version 12
and everything get back on track.
Solution:
Update your Xcode to the latest version.
Hint: there is no need to update iOS.
Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a SourceMap is, I suggest you check out this answer, where it explains how it's something that helps you debug:
The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.
First solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jquery, font-awesome, preload and so on.. (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your js/css destination folder)
Second solution (the one I used): add the source files using a CDN (here all the advantages of using a CDN). Using the Content delivery network (CDN) you can simply add the cdn link, instead of the path to your folder. You can find cdn on official websites (Bootstrap, jquery, popper, etc..) or you can easily search on some websites like cloudflare, cdnjs, etc..
This is what worked for me: instead of
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
try
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"> </script>
After that change I am not seeing the error anymore.
Restarting your server may not work always. I have got this error when I imported MatFormFieldModule.
In app.module.ts, I have imported MatFormField instead of MatFormFieldModule which lead to this error.
Now change it and restart the server, Hope this answer helps you.
I solved the same issue by following steps:
Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10
After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap
In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",
Now after updating package.json, use the command npm update
After this use command ng serve and my error got resolved
Quick solution: Update package.json
"devDependencies": {
...
"typescript": "~3.7.4",
}
In tsconfig.json
{
...,
"angularCompilerOptions": {
...,
"disableTypeScriptVersionCheck": true
}
}
then remove node_modules folder and reinstall with
npm install
For more visit here
This error occured to me too. I did what Muhammad umer said above. But, it only solved error for spring-boot-dependencies and spring-boot-dependencies has child dependencies. Now, there were 21 errors. Previously, it was 2 errors. Like this:
Non-resolvable import POM: Could not transfer artifact org.springframework.cloud:spring-cloud-dependencies:pom:Hoxton.SR3 from/to central
and also https required in the error message.
I updated the maven version from 3.2.2 to 3.6.3 and java version from 8 to 11. Now, all errors of https required are gone.
To update maven version
/opt/maven/
export PATH=$PATH:/opt/maven/bin
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
In my case (nginx on windows proxying an app while serving static assets on its own) page was showing multiple assets including 14 bigger pictures; those errors were shown for about 5 of those images exactly after 60 seconds; in my case it was a default send_timeout of 60s making those image requests fail; increasing the send_timeout made it work
I am not sure what is causing nginx on windows to serve those files so slow - it is only 11.5MB of resources which takes nginx almost 2 minutes to serve but I guess it is subject for another thread
I'm also in a "trial and error" for that, but this answer from Google Chrome Labs' Github helped me a little. I defined it into my main file and it worked - well, for only one third-party domain. Still making tests, but I'm eager to update this answer with a better solution :)
EDIT: I'm using PHP 7.4 now, and this syntax is working good (Sept 2020):
$cookie_options = array(
'expires' => time() + 60*60*24*30,
'path' => '/',
'domain' => '.domain.com', // leading dot for compatibility or use subdomain
'secure' => true, // or false
'httponly' => false, // or false
'samesite' => 'None' // None || Lax || Strict
);
setcookie('cors-cookie', 'my-site-cookie', $cookie_options);
If you have PHP 7.2 or lower (as Robert's answered below):
setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");
If your host is already updated to PHP 7.3, you can use (thanks to Mahn's comment):
setcookie('cookieName', 'cookieValue', [
'expires' => time()+(7*24*3600,
'path' => '/',
'domain' => 'domain.com',
'samesite' => 'None',
'secure' => true,
'httponly' => true
]);
Another thing you can try to check the cookies, is to enable the flag below, which—in their own words—"will add console warning messages for every single cookie potentially affected by this change":
chrome://flags/#cookie-deprecation-messages
See the whole code at: https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md, they have the code for same-site-cookies
too.
A PR with a fix has been merged in the metro repository. Now we just need to wait until the next release. For now the best option is to downgrade to NodeJS v12.10.0
. As Brandon pointed out, modifying anything in node_modules/
isa really bad practice and will not be a final solution.
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
When we do something like this obj[key] Typescript can't know for sure if that key exists in that object. What I did:
Object.entries(data).forEach(item => {
formData.append(item[0], item[1]);
});
You can convert class component to hooks,but Material v4 has a withStyles HOC. https://material-ui.com/styles/basics/#higher-order-component-api Using this HOC you can keep your code unchanged.
I got the same error when upgraded angular from 6 to 8.
Simple update angular cli to latest version & node version to 10+.
1) Visit this link to get the latest node version. Angular 8 requires 10+.
2) Execute npm i @angular/cli@latest to update cli.
This is what I have currently
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');
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_
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.
Use following commands to install node v11.15.0
and gulp v3.9.1
:
npm install -g n
sudo n 11.15.0
npm install gulp@^3.9.1
npm install
npm rebuild node-sass
Will solve this issue:
ReferenceError: primordials is not defined in node
Just pass the function as the argument in the array of useEffect...
useEffect(() => {
functionName()
}, [functionName])
Ended up to have a file named polyfill.js in projectpath\src\polyfill.js That file only contains this line: import 'core-js'; this polyfills not only es-6, but is the correct way to use core-js since version 3.0.0.
I added the polyfill.js to my webpack-file entry attribute like this:
entry: ['./src/main.scss', './src/polyfill.js', './src/main.jsx']
Works perfectly.
I also found some more information here : https://github.com/zloirock/core-js/issues/184
The library author (zloirock) claims:
ES6 changes behaviour almost all features added in ES5, so core-js/es6 entry point includes almost all of them. Also, as you wrote, it's required for fixing broken browser implementations.
(Quotation https://github.com/zloirock/core-js/issues/184 from zloirock)
So I think import 'core-js'; is just fine.
The "usual" solution is make a function that return an empty formGroup or a fullfilled formGroup
createFormGroup(data:any)
{
return this.fb.group({
user: [data?data.user:null],
questioning: [data?data.questioning:null, Validators.required],
questionType: [data?data.questionType, Validators.required],
options: new FormArray([this.createArray(data?data.options:null])
})
}
//return an array of formGroup
createArray(data:any[]|null):FormGroup[]
{
return data.map(x=>this.fb.group({
....
})
}
then, in SUBSCRIBE, you call the function
this.qService.editQue([params["id"]]).subscribe(res => {
this.editqueForm = this.createFormGroup(res);
});
be carefull!, your form must include an *ngIf to avoid initial error
<form *ngIf="editqueForm" [formGroup]="editqueForm">
....
</form>
Many advise you to remove the package-lock.json
or the yarn.lock
. This is clearly a bad idea!
I am using Yarn and I was able to correct this problem by removing only the caniuse-db
and caniuse-lite
entries in my yarn.lock
and doing a yarn
.
It is not necessary to break the main function of the lockfile by deleting it.
I just removed the slash at the end of url and it began working...
/managers/games/id/push/
to:
$http({
method: 'POST',
url: "/managers/games/id/push",
This may have to do with upgrading to laravel 5.8?
Open the developer setting and click console and type the following
JSON.parse(document.getElementById('jupyter-config-data').textContent).token
Then try saving the Notebook. The notebook that was not saving previously will save now.
you should add
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
to
resources/android/xml/network_security_config.xml
like this
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
</domain-config> </network-security-config>
I used apt-get to install python3.7 in ubuntu18.04. The installations are as follows.
sudo apt-get install python3.7
sudo apt-get install python3-pip
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1
Hope it works for you.
You can use this plugin timer_builder
timer_builder widget that rebuilds itself on scheduled, periodic, or dynamically generated time events.
Examples
Periodic rebuild
import 'package:timer_builder/timer_builder.dart';
class ClockWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return TimerBuilder.periodic(Duration(seconds: 1),
builder: (context) {
return Text("${DateTime.now()}");
}
);
}
}
Rebuild on a schedule
import 'package:timer_builder/timer_builder.dart';
class StatusIndicator extends StatelessWidget {
final DateTime startTime;
final DateTime endTime;
StatusIndicator(this.startTime, this.endTime);
@override
Widget build(BuildContext context) {
return TimerBuilder.scheduled([startTime, endTime],
builder: (context) {
final now = DateTime.now();
final started = now.compareTo(startTime) >= 0;
final ended = now.compareTo(endTime) >= 0;
return Text(started ? ended ? "Ended": "Started": "Not Started");
}
);
}
}
The issue looks to me to be a backward incompatibility with PHP 7.3 for the continue
keyword in Switch statements. Take a look at the "Continue Targeting Switch issues Warning" section in Backward Incompatible Changes.
I ran into the same issue with Symfony 3.3 using PHP 7.3 and downgrading to PHP 7.2 resolved the warning.
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
I just finished a rewrite with useReducer, following @kentcdobs article (ref below) which really gave me a solid result that suffers not one bit from these closure problems.
see: https://kentcdodds.com/blog/how-to-use-react-context-effectively
I condensed his readable boilerplate to my preferred level of DRYness -- reading his sandbox implementation will show you how it actually works.
Enjoy, I know I am !!
import React from 'react'
// ref: https://kentcdodds.com/blog/how-to-use-react-context-effectively
const ApplicationDispatch = React.createContext()
const ApplicationContext = React.createContext()
function stateReducer(state, action) {
if (state.hasOwnProperty(action.type)) {
return { ...state, [action.type]: state[action.type] = action.newValue };
}
throw new Error(`Unhandled action type: ${action.type}`);
}
const initialState = {
keyCode: '',
testCode: '',
testMode: false,
phoneNumber: '',
resultCode: null,
mobileInfo: '',
configName: '',
appConfig: {},
};
function DispatchProvider({ children }) {
const [state, dispatch] = React.useReducer(stateReducer, initialState);
return (
<ApplicationDispatch.Provider value={dispatch}>
<ApplicationContext.Provider value={state}>
{children}
</ApplicationContext.Provider>
</ApplicationDispatch.Provider>
)
}
function useDispatchable(stateName) {
const context = React.useContext(ApplicationContext);
const dispatch = React.useContext(ApplicationDispatch);
return [context[stateName], newValue => dispatch({ type: stateName, newValue })];
}
function useKeyCode() { return useDispatchable('keyCode'); }
function useTestCode() { return useDispatchable('testCode'); }
function useTestMode() { return useDispatchable('testMode'); }
function usePhoneNumber() { return useDispatchable('phoneNumber'); }
function useResultCode() { return useDispatchable('resultCode'); }
function useMobileInfo() { return useDispatchable('mobileInfo'); }
function useConfigName() { return useDispatchable('configName'); }
function useAppConfig() { return useDispatchable('appConfig'); }
export {
DispatchProvider,
useKeyCode,
useTestCode,
useTestMode,
usePhoneNumber,
useResultCode,
useMobileInfo,
useConfigName,
useAppConfig,
}
with a usage similar to this:
import { useHistory } from "react-router-dom";
// https://react-bootstrap.github.io/components/alerts
import { Container, Row } from 'react-bootstrap';
import { useAppConfig, useKeyCode, usePhoneNumber } from '../../ApplicationDispatchProvider';
import { ControlSet } from '../../components/control-set';
import { keypadClass } from '../../utils/style-utils';
import { MaskedEntry } from '../../components/masked-entry';
import { Messaging } from '../../components/messaging';
import { SimpleKeypad, HandleKeyPress, ALT_ID } from '../../components/simple-keypad';
export const AltIdPage = () => {
const history = useHistory();
const [keyCode, setKeyCode] = useKeyCode();
const [phoneNumber, setPhoneNumber] = usePhoneNumber();
const [appConfig, setAppConfig] = useAppConfig();
const keyPressed = btn => {
const maxLen = appConfig.phoneNumberEntry.entryLen;
const newValue = HandleKeyPress(btn, phoneNumber).slice(0, maxLen);
setPhoneNumber(newValue);
}
const doSubmit = () => {
history.push('s');
}
const disableBtns = phoneNumber.length < appConfig.phoneNumberEntry.entryLen;
return (
<Container fluid className="text-center">
<Row>
<Messaging {...{ msgColors: appConfig.pageColors, msgLines: appConfig.entryMsgs.altIdMsgs }} />
</Row>
<Row>
<MaskedEntry {...{ ...appConfig.phoneNumberEntry, entryColors: appConfig.pageColors, entryLine: phoneNumber }} />
</Row>
<Row>
<SimpleKeypad {...{ keyboardName: ALT_ID, themeName: appConfig.keyTheme, keyPressed, styleClass: keypadClass }} />
</Row>
<Row>
<ControlSet {...{ btnColors: appConfig.buttonColors, disabled: disableBtns, btns: [{ text: 'Submit', click: doSubmit }] }} />
</Row>
</Container>
);
};
AltIdPage.propTypes = {};
Now everything persists smoothly everywhere across all my pages
Nice!
Thanks Kent!
Functional component approach (Minimal Demo, Full Demo):
import React, { useState } from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpFetch from "cp-fetch"; //cancellable c-promise fetch wrapper
export default function TestComponent(props) {
const [text, setText] = useState("");
useAsyncEffect(
function* () {
setText("fetching...");
const response = yield cpFetch(props.url);
const json = yield response.json();
setText(`Success: ${JSON.stringify(json)}`);
},
[props.url]
);
return <div>{text}</div>;
}
Class component (Live demo)
import { async, listen, cancel, timeout } from "c-promise2";
import cpFetch from "cp-fetch";
export class TestComponent extends React.Component {
state = {
text: ""
};
@timeout(5000)
@listen
@async
*componentDidMount() {
console.log("mounted");
const response = yield cpFetch(this.props.url);
this.setState({ text: `json: ${yield response.text()}` });
}
render() {
return <div>{this.state.text}</div>;
}
@cancel()
componentWillUnmount() {
console.log("unmounted");
}
}
In my case it was database connection problem. This error needs to be more clear. I hope they will do it in the future. Basically it is a problem at ConfigureServices function in Startup. My advise is try to add all lines try catch in ConfigureServices function and you can findout where is problem.
For future purposes, this may help too:
It's ok to use setState in useEffect
you just need to have attention as described already to not create a loop.
But it's not the only problem that may occur. See below:
Imagine that you have a component Comp
that receives props
from parent and according to a props
change you want to set Comp
's state. For some reason, you need to change for each prop in a different useEffect
:
DO NOT DO THIS
useEffect(() => {
setState({ ...state, a: props.a });
}, [props.a]);
useEffect(() => {
setState({ ...state, b: props.b });
}, [props.b]);
It may never change the state of a as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w
The reason why this happen in this example it's because both useEffects run in the same react cycle when you change both prop.a
and prop.b
so the value of {...state}
when you do setState
are exactly the same in both useEffect
because they are in the same context. When you run the second setState
it will replace the first setState
.
DO THIS INSTEAD
The solution for this problem is basically call setState
like this:
useEffect(() => {
setState(state => ({ ...state, a: props.a }));
}, [props.a]);
useEffect(() => {
setState(state => ({ ...state, b: props.b }));
}, [props.b]);
Check the solution here: https://codesandbox.io/s/mutable-surf-nynlx
Now, you always receive the most updated and correct value of the state when you proceed with the setState
.
I hope this helps someone!
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
image: AssetImage('assets/images/pizza0.png')
In this answer, I will consider practical examples.
The first one, is of pandas.concat
.
The second one, of merging dataframes from the index of one and the column of another one.
Considering the following DataFrames
with the same column names:
Preco2018 with size (8784, 5)
Preco 2019 with size (8760, 5)
That have the same column names.
You can combine them using pandas.concat
, by simply
import pandas as pd
frames = [Preco2018, Preco2019]
df_merged = pd.concat(frames)
Which results in a DataFrame with the following size (17544, 5)
If you want to visualize, it ends up working like this
(Source)
2. Merge by Column and Index
In this part, I will consider a specific case: If one wants to merge the index of one dataframe and the column of another dataframe.
Let's say one has the dataframe Geo
with 54 columns, being one of the columns the Date Data
, which is of type datetime64[ns]
.
And the dataframe Price
that has one column with the price and the index corresponds to the dates
In this specific case, to merge them, one uses pd.merge
merged = pd.merge(Price, Geo, left_index=True, right_on='Data')
Which results in the following dataframe
Add this to your .prettierrc file and open the VSCODE
"endOfLine": "auto"
I believe this is the simplest example:
header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
You can also add a header for Access-Control-Max-Age
and of course you can allow any headers and methods that you wish.
Finally you want to respond to the initial request:
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
Edit (June 2019): We now use gorilla for this. Their stuff is more actively maintained and they have been doing this for a really long time. Leaving the link to the old one, just in case.
Old Middleware Recommendation below: Of course it would probably be easier to just use middleware for this. I don't think I've used it, but this one seems to come highly recommended.
You should preferably only have your component depend on state and props and it will work as expected, but if you really need a function to force the component to re-render, you could use the useState
hook and call the function when needed.
Example
const { useState, useEffect } = React;_x000D_
_x000D_
function Foo() {_x000D_
const [, forceUpdate] = useState();_x000D_
_x000D_
useEffect(() => {_x000D_
setTimeout(forceUpdate, 2000);_x000D_
}, []);_x000D_
_x000D_
return <div>{Date.now()}</div>;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Foo />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
MainAxisAlignment
start - Place the children as close to the start of the main axis as possible.
end - Place the children as close to the end of the main axis as possible.
center - Place the children as close to the middle of the main axis as possible.
spaceBetween - Place the free space evenly between the children.
spaceAround - Place the free space evenly between the children as well as half of that space before and after the first and last child.
spaceEvenly - Place the free space evenly between the children as well as before and after the first and last child.
Example:
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Row1'),
Text('Row2')
],
)
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
Pass an empty array as the second argument to useEffect
. This effectively tells React, quoting the docs:
This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.
Here's a snippet which you can run to show that it works:
function App() {_x000D_
const [user, setUser] = React.useState(null);_x000D_
_x000D_
React.useEffect(() => {_x000D_
fetch('https://randomuser.me/api/')_x000D_
.then(results => results.json())_x000D_
.then(data => {_x000D_
setUser(data.results[0]);_x000D_
});_x000D_
}, []); // Pass empty array to only run once on mount._x000D_
_x000D_
return <div>_x000D_
{user ? user.name.first : 'Loading...'}_x000D_
</div>;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="app"></div>
_x000D_
In my case I had curly braces where it should have been parentheses.
const Button = () => {
<button>Hello world</button>
}
Where it should have been:
const Button = () => (
<button>Hello world</button>
)
The reason for this, as explained in the MDN Docs is that an arrow function wrapped by ()
will return the value it wraps, so if I wanted to use curly braces I had to add the return
keyword, like so:
const Button = () => {
return <button>Hello world</button>
}
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
)
],
)
Just use padding to wrap it like this:
Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(8.0),
child: Text('Hello World!'),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text('Hello World2!'),
)
]);
You can also use Container(padding...) or SizeBox(height: x.x). The last one is the most common but it will depents of how you want to manage the space of your widgets, I like to use padding if the space is part of the widget indeed and use sizebox for lists for example.
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.
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.
This is because the form requires a csrf. In version 5.7, they changed it to @csrf
<form action="" method="post">
@csrf
...
Referene: https://laravel.com/docs/5.7/csrf
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
if I remove this row from application gradle
:
apply plugin: 'io.fabric'
error will not appear anymore.
I also occured the error,and I sloved it by removing the curly braces,hope it will help someone else.
You can see that ,I did not put the con in the curly brace,and the error occured ,when I remove the burly brace , the error disappeared.
const modal = (props) => {
const { show, onClose } = props;
let con = <div className="modal" onClick={onClose}>
{props.children}
</div>;
return show === true ? (
{con}
) : (
<div>hello</div>
);
There are an article about the usage of the curly brace.click here
Open Keychain Access on your Mac and delete the old expired Apple Development certificates. This solved the issue for me.
Still surprised that no one proposed the shortest solution with align-center justify-center
to center content vertically and horizontally. Check this CodeSandbox and code below:
<v-container fluid fill-height>
<v-layout align-center justify-center>
<v-flex>
<!-- Some HTML elements... -->
</v-flex>
</v-layout>
</v-container>
The problem is pyaudio does not have wheels for python 3.7 just try some lower version like 3.6
then install pyaudio
It works
I faced the same issue while trying to transpile some jsx with babel. Below is the solution that worked for me. You can add the following json to your .babelrc
{
"presets": [
[
"@babel/preset-react",
{ "targets": { "browsers": ["last 3 versions", "safari >= 6"] } }
]
],
"plugins": [["@babel/plugin-proposal-class-properties"]]
}
Check out BoxShadow and BoxDecoration
A Container
can take a BoxDecoration
(going off of the code you had originally posted) which takes a boxShadow
return Container(
margin: EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)
),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 3), // changes position of shadow
),
],
),
)
Screenshot
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.
The reason for this error occurs is that you are using the CryptoListPresenter _presenter
without initializing.
I found that CryptoListPresenter _presenter
would have to be initialized to fix because _presenter.loadCurrencies()
is passing through a null variable at the time of instantiation;
there are two ways to initialize
Can be initialized during an declaration, like this
CryptoListPresenter _presenter = CryptoListPresenter();
In the second, initializing(with assigning some value) it when initState
is called, which the framework will call this method once for each state object.
@override
void initState() {
_presenter = CryptoListPresenter(...);
}
Add the lines in the gradle.properties file
android.useAndroidX=true
android.enableJetifier=true
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
Container(
color: Color.fromRGBO(224, 251, 253, 1.0),
child: ListTile(
dense: true,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
RichText(
textAlign: TextAlign.left,
softWrap: true,
text: TextSpan(children: <TextSpan>
[
TextSpan(text: "hello: ",
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold)),
TextSpan(text: "I hope this helps",
style: TextStyle(color: Colors.black)),
]
),
),
],
),
),
),
just add these two lines of code to your Manifest file
tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"
Two way to add Scroll in page
1. Using SingleChildScrollView :
SingleChildScrollView(
child: Column(
children: [
Container(....),
SizedBox(...),
Container(...),
Text(....)
],
),
),
2. Using ListView : ListView is default provide Scroll no need to add extra widget for scrolling
ListView(
children: [
Container(..),
SizedBox(..),
Container(...),
Text(..)
],
),
For maximum flexibility, I usually prefer working with SizedBox like this:
Row(
children: <Widget>[
SizedBox(
width: 235,
child: Text('Hey, ')),
SizedBox(
width: 110,
child: Text('how are'),
SizedBox(
width: 10,
child: Text('you?'))
],
)
I've experienced problems with text alignment when using alignment in the past, whereas sizedbox always does the work.
The process below worked in my case- First check Gradle Version:
cd android
./gradlew -v
In my case it was 6.5
Go to https://developer.android.com/studio/releases/gradle-plugin and you'll get the plugin version for your gradle version. For gradle version 6.5, the plugin version is 4.1.0
Then go to app/build.gradle
and change classpath 'com.android.tools.build:gradle:<plugin_version>
I am using angular 6 and I have been searching on best way to match password and confirm password. This can also be used to match any two inputs in a form. I used Angular Directives. I have been wanting to use them
ng g d compare-validators --spec false and i will be added in your module. Below is the directive
import { Directive, Input } from '@angular/core';
import { Validator, NG_VALIDATORS, AbstractControl, ValidationErrors } from '@angular/forms';
import { Subscription } from 'rxjs';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[compare]',
providers: [{ provide: NG_VALIDATORS, useExisting: CompareValidatorDirective, multi: true}]
})
export class CompareValidatorDirective implements Validator {
// tslint:disable-next-line:no-input-rename
@Input('compare') controlNameToCompare;
validate(c: AbstractControl): ValidationErrors | null {
if (c.value.length < 6 || c.value === null) {
return null;
}
const controlToCompare = c.root.get(this.controlNameToCompare);
if (controlToCompare) {
const subscription: Subscription = controlToCompare.valueChanges.subscribe(() => {
c.updateValueAndValidity();
subscription.unsubscribe();
});
}
return controlToCompare && controlToCompare.value !== c.value ? {'compare': true } : null;
}
}
Now in your component
<div class="col-md-6">
<div class="form-group">
<label class="bmd-label-floating">Password</label>
<input type="password" class="form-control" formControlName="usrpass" [ngClass]="{ 'is-invalid': submitAttempt && f.usrpass.errors }">
<div *ngIf="submitAttempt && signupForm.controls['usrpass'].errors" class="invalid-feedback">
<div *ngIf="signupForm.controls['usrpass'].errors.required">Your password is required</div>
<div *ngIf="signupForm.controls['usrpass'].errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="bmd-label-floating">Confirm Password</label>
<input type="password" class="form-control" formControlName="confirmpass" compare = "usrpass"
[ngClass]="{ 'is-invalid': submitAttempt && f.confirmpass.errors }">
<div *ngIf="submitAttempt && signupForm.controls['confirmpass'].errors" class="invalid-feedback">
<div *ngIf="signupForm.controls['confirmpass'].errors.required">Your confirm password is required</div>
<div *ngIf="signupForm.controls['confirmpass'].errors.minlength">Password must be at least 6 characters</div>
<div *ngIf="signupForm.controls['confirmpass'].errors['compare']">Confirm password and Password dont match</div>
</div>
</div>
</div>
I hope this one helps
Here's my simple solution. That does not require any dependency.
However, the date will be in string format. If you want the time then change the substring values
print(new DateTime.now()
.toString()
.substring(0,10)
); // 2020-06-10
Try:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children:children...)
you can use localStorage for storing the json data:
the example is given below:-
let JSONDatas = [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "Find", "label": "Find..."},
{"id": "FindAgain", "label": "Find Again"},
{"id": "Copy"},
{"id": "CopyAgain", "label": "Copy Again"},
{"id": "CopySVG", "label": "Copy SVG"},
{"id": "ViewSVG", "label": "View SVG"}
]
localStorage.setItem("datas", JSON.stringify(JSONDatas));
let data = JSON.parse(localStorage.getItem("datas"));
console.log(data);
<div (mouseenter)="changeText=true" (mouseout)="changeText=false">
<span *ngIf="!changeText">Hide</span>
<span *ngIf="changeText">Show</span>
</div>
and if you want to use in *ngFor then assign the object value of hover data and then check its id and show hover info/icon or anything like that:-
<div (mouseenter)="hoverCard(d)" (mouseleave)="hoverCard(null)" *ngFor="let d of data" class="col-lg-3 col-md-4 col-sm-6 mt-4">
<a *ngIf="hoverData && hoverData.id == d.id" class="text-right"><i class="fas fa-edit"></i>Hover Text</a>
Normal Text
</div>
in TS File
hoverData!:Data|null;
hoverCard(d: Data|null){
this.hoverData = sCatg;
}
axios({
method: 'post', //put
url: url,
headers: {'Authorization': 'Bearer'+token},
data: {
firstName: 'Keshav', // This is the body part
lastName: 'Gera'
}
});
_mytexteditingcontroller.value = new TextEditingController.fromValue(new TextEditingValue(text: "My String")).value;
This seems to work if anyone has a better way please feel free to let me know.
Kotlin allows for even simpler code than what's shown in other answers.
To get the new token whenever it's refreshed:
class MyFirebaseMessagingService: FirebaseMessagingService() {
override fun onNewToken(token: String?) {
Log.d("FMS_TOKEN", token)
}
...
}
To get the token from anywhere at runtime:
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener {
Log.d("FMS_TOKEN", it.token)
}
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.
To create an environment named py37
with python 3.7, using the channel conda-forge and a list of packages:
conda create -y --name py37 python=3.7
conda install --force-reinstall -y -q --name py37 -c conda-forge --file requirements.txt
conda activate py37
...
conda deactivate
Flags explained:
-y
: Do not ask for confirmation.--force-reinstall
: Install the package even if it already exists.-q
: Do not display progress bar.-c
: Additional channel to search for packages. These are URLs searched in the orderThe ansible-role dockpack.base_miniconda can manage conda environments and can be used to create a docker base image.
Alternatively you can create an environment.yml file instead of requirements.txt:
name: py37
channels:
- conda-forge
dependencies:
- python=3.7
- numpy=1.9.*
- pandas
Use this command to list the environments you have:
conda info --envs
Use this command to remove the environment:
conda env remove -n py37
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
Another case that could cause this error is
>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index
Using the actual shape will fix it.
>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>
For me, Error has been fixed when activated Billing in google console. (I got 1-year developer trial)
you can install this package... https://github.com/UB-Mannheim/tesseract/wiki after that you should go this path C:\Program Files (x86)\Tesseract-OCR\ tesseract.exe then run tesseract file. I think this will help you...
assets/images
folderpubspec.yaml
file.assets
or images
. You don't even need to make images
a subfolder. Whatever name you use, though, is what you will regester in the pubspec.yaml
file.assets/images
. The relative path of lake.jpg
, for example, would be assets/images/lake.jpg
.pubspec.yaml
Open the pubspec.yaml
file that is in the root of your project.
Add an assets
subsection to the flutter
section like this:
flutter:
assets:
- assets/images/lake.jpg
If you have multiple images that you want to include then you can leave off the file name and just use the directory name (include the final /
):
flutter:
assets:
- assets/images/
Get the asset in an Image widget with Image.asset('assets/images/lake.jpg')
.
The entire main.dart
file is here:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Image from assets"),
),
body: Image.asset('assets/images/lake.jpg'), // <--- image
),
);
}
}
When making changes to pubspec.yaml I find that I often need to completely stop my app and restart it again, especially when adding assets. Otherwise I get a crash.
Running the app now you should have something like this:
The first video here goes into a lot of detail about how to include images in your app. The second video covers more about how to adjust how they look.
A Stack
allows you to stack elements on top of each other, with the last element in the array taking the highest priority. You can use Align
, Positioned
, or Container
to position the children of a stack.
Align
Widgets are moved by setting the alignment with Alignment
, which has static properties like topCenter
, bottomRight, and so on. Or you can take full control and set Alignment(1.0, -1.0)
, which takes x,y values ranging from 1.0 to -1.0, with (0,0) being the center of the screen.
Stack(
children: [
Align(
alignment: Alignment.topCenter,
child: Container(
height: 80,
width: 80, color: Colors.blueAccent
),
),
Align(
alignment: Alignment.center,
child: Container(
height: 80,
width: 80, color: Colors.deepPurple
),
),
Container(
alignment: Alignment.bottomCenter,
// alignment: Alignment(1.0, -1.0),
child: Container(
height: 80,
width: 80, color: Colors.amber
),
)
]
)
Use like below:
yourFunc(input: any):Observable<string> {
var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json' });
}
I cross that situation by replacing all androidx.*
to appropiate package name
.
change your line
implementation 'androidx.appcompat:appcompat:1.0.0-alpha3'
implementation 'androidx.constraintlayout:constraintlayout:1.1.1'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'
to
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.1'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
NOTED
tools:replace="android:appComponentFactory"
from AndroidManifestI was also having the trouble to route to a different view using navlink.
My implementation was as follows and works perfectly;
<NavLink tag='li'>
<div
onClick={() =>
this.props.history.push('/admin/my- settings')
}
>
<DropdownItem className='nav-item'>
Settings
</DropdownItem>
</div>
</NavLink>
Wrap it with a div, assign the onClick handler to the div. Use the history object to push a new view.
I don't know if this will help anyone. The previous messages have helped me so I'm here to suggest a few things:
import 'package:intl/intl.dart';
DateTime convertTimeStampToDateTime(int timeStamp) {
var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
return dateToTimeStamp;
}
String convertTimeStampToHumanDate(int timeStamp) {
var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
return DateFormat('dd/MM/yyyy').format(dateToTimeStamp);
}
String convertTimeStampToHumanHour(int timeStamp) {
var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
return DateFormat('HH:mm').format(dateToTimeStamp);
}
int constructDateAndHourRdvToTimeStamp(DateTime dateTime, TimeOfDay time ) {
final constructDateTimeRdv = dateTimeToTimeStamp(DateTime(dateTime.year, dateTime.month, dateTime.day, time.hour, time.minute)) ;
return constructDateTimeRdv;
}
Add maven { url "https://maven.google.com" } to your root level build.gradle file
repositories {
maven { url "https://maven.google.com" }
flatDir {
dirs 'libs'
}
}
You can use TextAlign
property of Text
constructor.
Text("text", textAlign: TextAlign.center,)
All you need to do is put it in a list and then add it as the children of the widget.
you can do something like this:
Widget listOfWidgets(List<String> item) {
List<Widget> list = List<Widget>();
for (var i = 0; i < item.length; i++) {
list.add(Container(
child: FittedBox(
fit: BoxFit.fitWidth,
child: Text(
item[i],
),
)));
}
return Wrap(
spacing: 5.0, // gap between adjacent chips
runSpacing: 2.0, // gap between lines
children: list);
}
After that call like this
child: Row(children: <Widget>[
listOfWidgets(itemList),
])
I tried all the possible commands listed above and none of them worked for me, Check if Package.json contain "@angular-devkit/build-angular" if not just install it using(in my case version 0.803.19 worked)
npm i @angular-devkit/[email protected]
Or checkout at npm website repositories for version selection
You can try the margin
property in the Container
. Wrap the TextField
inside a Container
and adjust the margin
property.
new Container(
margin: const EdgeInsets.only(right: 10, left: 10),
child: new TextField(
decoration: new InputDecoration(
hintText: 'username',
icon: new Icon(Icons.person)),
)
),
remove the connect .jar file if you added the multiple version connector jar file only add the connector jar file that match with your sql version.
I faced the same problem.
Surprisingly, it was just because the version
specified in package.json
was not in the expected format.
I switched from version "version": "0.1"
to "version": "0.0.1"
and it solved the problem.
Angular NEEDS semantic versioning (also read Semver) with three parts.
Wrap RaisedButton inside Container and give width to Container Widget.
e.g
Container(
width : 200,
child : RaisedButton(
child :YourWidget ,
onPressed(){}
),
)
I implement like this:
static createUserWithEmail(String username, String email, String password) async{
var url = 'http://www.yourbackend.com/'+ "users";
var body = {
'user' : {
'username': username,
'address': email,
'password': password
}
};
return http.post(
url,
body: json.encode(body),
headers: {
"Content-Type": "application/json"
},
encoding: Encoding.getByName("utf-8")
);
}
Apart from the possible solutions in other answers, it is also possible that somehow Maven dependency corruption has occurred on your machine. I was facing the same error on trying to run my (Web) Spring boot application, and it got resolved by running the following -
mvn dependency:purge-local-repository -DreResolve=true
followed by
mvn package
I came onto this solution looking into another issue where Eclipse wouldn't let me run the main application class from the IDE, due to a different error, similar to one on this SO thread -> The type org.springframework.context.ConfigurableApplicationContext cannot be resolved. It is indirectly referenced from required .class files
This worked for me.
mongoose.Promise = global.Promise;
.connect(
"mongodb://127.0.0.1:27017/mydb",
{ useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}).then(db => {
console.log("Database connected");
}).catch(error => console.log("Could not connect to mongo db " + error));
I was using localhost, so i changed it to:
mongodb://127.0.0.1:27017/mydb
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide(color: Colors.red)
),
I just run into this problem too, with all the MySQL re-config mentioned above the error still appears. It turns out that I misspelled the database name.
So be sure you're connecting with the right database name especially the case.
If you don't want to use OutlineButton
and want to stick to normal RaisedButton
, you can wrap your button in ClipRRect
or ClipOval
like:
ClipRRect(
borderRadius: BorderRadius.circular(40),
child: RaisedButton(
child: Text("Button"),
onPressed: () {},
),
),
you can do that wit MaterialButton
MaterialButton(
padding: EdgeInsets.all(12.0),
minWidth: double.infinity,
onPressed: () {},
child: Text("Btn"),
)
If you want to round corners with transparent background, the best approach is using ClipRRect.
return ClipRRect(
borderRadius: BorderRadius.circular(40.0),
child: Container(
height: 800.0,
width: double.infinity,
color: Colors.blue,
child: Center(
child: new Text("Hi modal sheet"),
),
),
);
You should use html autofocus for this:
<input *ngIf="show" #search type="text" autofocus />
Note: if your component is persisted and reused it will only autofocus the first time the fragment is attached. This can be overcome by having a global dom listener that checks for autofocus attribute inside a dom fragment when it is attached and then reapplying it or focus via javascript.
You can go like this:
error.response.data
In my case, I got error property from backend. So, I used error.response.data.error
My code:
axios
.get(`${API_BASE_URL}/students`)
.then(response => {
return response.data
})
.then(data => {
console.log(data)
})
.catch(error => {
console.log(error.response.data.error)
})
Check your folder structure where you are executing the command, you should run the command 'ng serve' where there should be a angular.json file in the structure.
angular.json file will be generated by default when we run the command
npm install -g '@angular/cli' ng new Project_name then cd project_folder then, run ng serve. it worked for me
Place dependency in pubspec.yaml
flutter_responsive_screen: ^1.0.0
Function hp = Screen(MediaQuery.of(context).size).hp;
Function wp = Screen(MediaQuery.of(context).size).wp;
Example :
return Container(height: hp(27),weight: wp(27));
Colab research team has a notebook for helping you out.
Still, in short, if you are dealing with a zip file, like for me it is mostly thousands of images and I want to store them in a folder within drive then do this --
!unzip -u "/content/drive/My Drive/folder/example.zip" -d "/content/drive/My Drive/folder/NewFolder"
-u
part controls extraction only if new/necessary. It is important if suddenly you lose connection or hardware switches off.
-d
creates the directory and extracted files are stored there.
Of course before doing this you need to mount your drive
from google.colab import drive
drive.mount('/content/drive')
I hope this helps! Cheers!!
2019 Update: I realize that this is somewhat bad advice. As the first comment states, this heavily depends on the situation, and it is not a bad practice to use the [hidden] attribute: see the comments for some of the cases where you need to use it and not *ngIf
Original answer:
You should always try to use *ngIf
instead of [hidden]
.
<input *ngIf="!isHidden" class="txt" type="password" [(ngModel)]="input_pw" >
There are several blog posts about that topics, but the bottom line is, that Hidden usually means you do not want the browser to render the object - using angular you still waste resource on rendering it, and it will end up in the DOM anyway (and tricky users can see it with basic browser manipulation).
About the removal of componentWillReceiveProps
: you should be able to handle its uses with a combination of getDerivedStateFromProps
and componentDidUpdate
, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps
updates the state similarly to an object passed to setState
.
In case you really need the old value of a prop, you can always cache it in your state with something like this:
state = {
cachedSomeProp: null
// ... rest of initial state
};
static getDerivedStateFromProps(nextProps, prevState) {
// do things with nextProps.someProp and prevState.cachedSomeProp
return {
cachedSomeProp: nextProps.someProp,
// ... other derived state properties
};
}
Anything that doesn't affect the state can be put in componentDidUpdate
, and there's even a getSnapshotBeforeUpdate
for very low-level stuff.
UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.
This also happened to me but using Dynamic Features. I already had Java 8 compatibility enabled in the app module but I had to add this compatibility lines to the Dynamic Feature module and then it worked.
I encountered this error simply because I misspelled the spring.datasource.url
value in the application.properties file and I was using postgresql:
Problem was:
jdbc:postgres://localhost:<port-number>/<database-name>
Fixed to:
jdbc:postgresql://localhost:<port-number>/<database-name>
NOTE: the difference is postgres
& postgresql
, the two are 2 different things.
Further causes and solutions may be found here
You can simply use named constructors for creating different types of buttons with icons. For instance
FlatButton.icon(onPressed: null, icon: null, label: null);
RaisedButton.icon(onPressed: null, icon: null, label: null);
But if you have specfic requirements then you can always create custom button with different layouts or simply wrap a widget in GestureDetector.
Run export DOCKER_CONTENT_TRUST=0
and then try it again.
place the value inside the items.then it will work,
new DropdownButton<String>(
items:_dropitems.map((String val){
return DropdownMenuItem<String>(
value: val,
child: new Text(val),
);
}).toList(),
hint:Text(_SelectdType),
onChanged:(String val){
_SelectdType= val;
setState(() {});
})
I had the same issue and I installed this cordova plugin and problem solved.
cordova plugin add cordova-android-support-gradle-release --save
As android latest update doesn't support 'compile' keyword use 'implementation' in place inside your module build.gradle file.
And check thoroughly in build.gradle for dependancy with + sign like this.
implementation 'com.android.support:support-v4:28.+'
If there are any dependencies like this, just update them with a specific version. After that:
I also read the Spring docs, as lapkritinis suggested - and luckily this brought me on the right path! But I don´t think, that the Spring docs explain this good right now. At least for me, they aren´t consistent IMHO.
The original problem/question is on what to do, if you upgrade an existing Spring Boot 1.5.x application to 2.0.x, which is using PostgreSQL/Hibernate. The main reason, you get your described error, is that Spring Boot 2.0.x uses HikariCP instead of Tomcat JDBC pooling DataSource as a default - and Hikari´s DataSource doesn´t know the spring.datasource.url
property, instead it want´s to have spring.datasource.jdbc-url
(lapkritinis also pointed that out).
So far so good. BUT the docs also suggest - and that´s the problem here - that Spring Boot uses spring.datasource.url
to determine, if the - often locally used - embedded Database like H2 has to back off and instead use a production Database:
You should at least specify the URL by setting the spring.datasource.url property. Otherwise, Spring Boot tries to auto-configure an embedded database.
You may see the dilemma. If you want to have your embedded DataBase like you´re used to, you have to switch back to Tomcat JDBC. This is also much more minimally invasive to existing applications, as you don´t have to change source code! To get your existing application working after the Spring Boot 1.5.x --> 2.0.x upgrade with PostgreSQL, just add tomcat-jdbc
as a dependency to your pom.xml:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
And then configure Spring Boot to use it accordingly inside application.properties:
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
Hope to help some folks with this, was quite a time consuming problem. I also hope my beloved Spring folks update the docs - and the way new Hikari pool is configured - to get a more consistent Spring Boot user experience :)
Container(
height: 50,
// margin: EdgeInsets.only(top: 20),
decoration: BoxDecoration(
color: Colors.tealAccent,
borderRadius: BorderRadius.circular(32)),
child: TextFormField(
cursorColor: Colors.black,
// keyboardType: TextInputType.,
decoration: InputDecoration(
hintStyle: TextStyle(fontSize: 17),
hintText: 'Search your trips',
suffixIcon: Icon(Icons.search),
border: InputBorder.none,
contentPadding: EdgeInsets.all(18),
),
),
),
If you want to use Unix shell commands on Windows, you can use Windows Powershell, which includes both Windows and Unix commands as aliases. You can find more info on it in the documentation.
PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with experience in other shells to use common command names that they already know for similar operations in PowerShell.
The PowerShell equivalents may not produce identical results. However, the results are close enough that users can do work without knowing the PowerShell command name.
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
# Method 1
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name) # Write inside file
f.close() # Close file
# Method 2
with open("Path/To/Your/File.txt", "w") as f: # Opens file and casts as f
f.write("Hello World form " + f.name) # Writing
# File closed automatically
There are many more methods but these two are most common. Hope this helped!
For projects that use .editorconfig
file by default. The formatter will ignore the rules in the settings and use the rules in .editorconfig
, then you can either:
.editorconfig
file, and use your VSCode settings.quote_type = single
to the .editorconfig
file regarding your file type. You can also set quote_type
value to double
or auto
.For anyone who lands here and all the other solutions did not work give this a try. I am using typescript + react and my problem was that I was associating the files in vscode as javascriptreact
not typescriptreact
so check your settings for the following entries.
"files.associations": {
"*.tsx": "typescriptreact",
"*.ts": "typescriptreact"
},
I faced the same issue but the reason was none of the ones listed above. I created a task, created a scope inside the task and asked the container to obtain a service. That worked fine but then I used a second service inside the task and I forgot to also asked for it to the new scope. Because of that, the 2nd service was using a DbContext that was already disposed.
Task task = Task.Run(() =>
{
using (var scope = serviceScopeFactory.CreateScope())
{
var otherOfferService = scope.ServiceProvider.GetService<IOfferService>();
// everything was ok here. then I did:
productService.DoSomething(); // (from the main scope) and this failed because the db context associated to that service was already disposed.
...
}
}
I should have done this:
var otherProductService = scope.ServiceProvider.GetService<IProductService>();
otherProductService.DoSomething();
I read all answers but I think one of the best method is using openCV library.
import cv2
img = cv2.imread('your_image.png',0)
and for displaying the image, use the following code :
from matplotlib import pyplot as plt
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
F1 key opens the shortcuts for me using windows 10. Then type Terminal and you see the clear option.
You maybe having this error on your java
files because there is one or more XML
file with error.
Go through all your XML
files and resolve errors, then clean
or rebuild
project from build menu
Start with your most recent edited XML
file
ReactJS: Maximum update depth exceeded error
inputDigit(digit){
this.setState({
displayValue: String(digit)
})
<button type="button"onClick={this.inputDigit(0)}>
why that?
<button type="button"onClick={() => this.inputDigit(1)}>1</button>
The function onDigit sets the state, which causes a rerender, which causes onDigit to fire because that’s the value you’re setting as onClick which causes the state to be set which causes a rerender, which causes onDigit to fire because that’s the value you’re… Etc
Old one but I would add my answer as per my findings:
var ancestralState = context.findAncestorStateOfType<ParentState>();
ancestralState.setState(() {
// here you can access public vars and update state.
...
});
pickle
module is part of the standard library in Python for a very long time now so there is no need to install it via pip
. I wonder if you IDE or command line is not messed up somehow so that it does not find python installation path. Please check if your %PATH%
contains a path to python (e.g. C:\Python36\
or something similar) or if your IDE correctly detects root path where Python is installed.
In my case i forgot to add the () after the function name inside the render function of a react component
public render() {
let ctrl = (
<>
<div className="aaa">
{this.renderView}
</div>
</>
);
return ctrl;
};
private renderView() : JSX.Element {
// some html
};
Changing the render method, as it states in the error message to
<div className="aaa">
{this.renderView()}
</div>
fixed the problem
You can simply make use of the code snippets on the left of the screen. enter image description here
Insert "Mounting Google Drive in your VM"
run the code and copy&paste the code in the URL
and then use !ls to check the directories
!ls /gdrive
for most cases, you will find what you want in the directory "/gdrive/My drive"
then you may carry it out like this:
from google.colab import drive
drive.mount('/gdrive')
import glob
file_path = glob.glob("/gdrive/My Drive/***.txt")
for file in file_path:
do_something(file)
This is a very common question seen on Stackoverflow.
The important part here is not the command displayed in the error, but what the actual error tells you instead.
a Quick breakdown on why this error is received.
cmd.exe
Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.
How do I fix this:
When Actual Command/executable fails
First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.
If you have any executable which you are attempting to run from cmd.exe
then you need to tell cmd.exe
where this file is located. There are 2 ways of doing this.
specify the full path to the file.
"C:\My_Files\mycommand.exe"
Add the location of the file to your environment Variables.
Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables
In the System Variables
Window, locate path
and select edit
Now simply add your path to the end of the string, seperated by a semicolon ;
as:
;C:\My_Files\
Save the changes and exit. You need to make sure that ANY cmd.exe
windows you had open are then closed and re-opened to allow it to re-import the environment variables.
Now you should be able to run mycommand.exe from any path, within cmd.exe
as the environment is aware of the path to it.
When C:\Program
or Similar fails
This is a very simple error. Each string after a white space is seen as a different command in cmd.exe
terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe
to see it as a single string, and not separate commands.
So to execute C:\Program Files\My-App\Mobile.exe
simply run as:
"C:\Program Files\My-App\Mobile.exe"
Mcrypt PECL extenstion
sudo apt-get -y install gcc make autoconf libc-dev pkg-config
sudo apt-get -y install libmcrypt-dev
sudo pecl install mcrypt-1.0.1
When you are shown the prompt
libmcrypt prefix? [autodetect] :
Press [Enter] to autodetect.
After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.
The output will look like this:
...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so' ----> this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini
Grab installing path and add to cli and apache2 php.ini configuration.
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"
Verify that the extension was installed
Run command:
php -i | grep "mcrypt"
The output will look like this:
/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value
You can follow this.
Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can add the multidex support library to your project:
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown here:
android {
defaultConfig {
...
minSdkVersion 21
targetSdkVersion 28
multiDexEnabled true
}
...
}
This is specific to Typescript+Express
I ctrl+f'd "Typescript" and ".ts" and found nothing in these answers, so I'll add my solution here, since it was caused by (my inexperience with) typescript, and the solutions I've read don't explicit solve this particular issue.
The problem was that Typescript was compiling my app.ts
file into a javascript file in my project's dist
directory, dist/app.js
Here's my directory structure, see if you can spot the problem:
+-- app.ts
+-- dist
¦ +-- app.js
¦ +-- app.js.map
¦ +-- js
¦ +-- dbclient.js
¦ +-- dbclient.js.map
¦ +-- mutators.js
¦ +-- mutators.js.map
+-- public
¦ +-- css
¦ ¦ +-- styles.css
+-- tsconfig.json
+-- tslint.json
+-- views
+-- index.hbs
+-- results.hbs
My problem is that in app.ts
, I was telling express to set my public directory as /public
, which would be a valid path if Node actually were running Typescript. But Node is running the compiled javascript, app.js
, which is in the dist
directory.
So having app.ts
pretend it's dist/app.js
solved my problem. Thus, I fixed the problem in app.ts
by changing
app.use(e.static(path.join(__dirname, "/public")));
to
app.use(e.static(path.join(__dirname, "../public")));
You can try as follows:
//------ js/functions.js ------
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ js/main.js ------
import { square, diag } from './functions.js';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
You can also import completely:
//------ js/main.js ------
import * as lib from './functions.js';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
Normally we use ./fileName.js
for importing own js file/module
and fileName.js
is used for importing package/library
module
When you will include the main.js file to your webpage you must set the type="module" attribute as follows:
<script type="module" src="js/main.js"></script>
For more details please check ES6 modules
You have two records in your json file, and json.loads()
is not able to decode more than one. You need to do it record by record.
See Python json.loads shows ValueError: Extra data
OR you need to reformat your json to contain an array:
{
"foo" : [
{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
]
}
would be acceptable again. But there cannot be several top level objects.
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
The only solution that really works :
Change:
<item name="android:windowIsTranslucent">true</item>
to:
<item name="android:windowIsTranslucent">false</item>
in styles.xml
But this might induce a problem with your splashscreen (white screen at startup)... In this case, add the following line to your styles.xml:
<item name="android:windowDisablePreview">true</item>
just below the windowIsTranslucent line.
Last chance if the previous tips do not work : target SDK 26 instead o 27.
I found the solution as Its problem with Android Studio 3.1 Canary 6
My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.
Now My build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '27.0.2'
defaultConfig {
applicationId "com.example.demo"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
dataBinding {
enabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.squareup.retrofit2:retrofit:2.3.0"
implementation "com.google.code.gson:gson:2.8.2"
implementation "com.android.support.constraint:constraint-layout:1.0.2"
implementation "com.squareup.retrofit2:converter-gson:2.3.0"
implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
implementation "com.squareup.picasso:picasso:2.5.2"
implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
compile 'com.github.elevenetc:badgeview:v1.0.0'
annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
testImplementation "junit:junit:4.12"
androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
exclude group: "com.android.support", module: "support-annotations"
})
}
and My gradle is:
classpath 'com.android.tools.build:gradle:3.1.0-alpha06'
and its working finally.
I think there problem in Android Studio 3.1 Canary 6
Thank you all for your time.
Was getting the error while I was using jupyter.
ModuleNotFoundError: No module named 'xlrd'
...
ImportError: Install xlrd >= 0.9.0 for Excel support
it was resolved for me after using.
!pip install xlrd
npm install
npm run start
if this didn't work, try to install the nodejs and run repair
or clean npm cache npm cache clean --force
Edit the system environmental variable
Environment Variables...
Path
variable nameEdit..
C:\Program Files\nodejs
on the list, if not add thisA Spring Boot project configured through Maven can be run using the following command from the project source folder
mvn spring-boot:run
None of the solutions worked for me. I ended up downloading a different emulator image.
First I had arm64-v8a, which was giving this error. I download armeabi-v7a, which worked fine.
Unfortunately I was not able to install HAXM accelerator as organization's softwares were blocking the installation. Hence, had to go with arm.
yu have to install the correct version for your computer 32 or 63 bits thats all
I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to npm uninstall mongodb; then npm install to install this version.
This resolved the issue for me. Seems to be a bug or docs need to be updated.
You need to pass an array of element to jsx
. The problem is that forEach
does not return anything (i.e it returns undefined
). So it's better to use map
because map
returns an array:
class QuestionSet extends Component {
render(){
<div className="container">
<h1>{this.props.question.text}</h1>
{this.props.question.answers.map((answer, i) => {
console.log("Entered");
// Return the element. Also pass key
return (<Answer key={answer} answer={answer} />)
})}
}
export default QuestionSet;
Yes, ConfigurationManager.AppSettings
is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager
.
Credits goes to @JeroenMostert for giving me the solution.
A simple trick is to define the $_SESSION array as a global variable. For that, edit the core.php file in the extension folder by adding this function :
public function getGlobals() {
return array(
'session' => $_SESSION,
) ;
}
Then, you'll be able to acces any session variable as :
{{ session.username }}
if you want to access to
$_SESSION['username']
You could use viewport-percentage lenghts.
See: http://stanhub.com/how-to-make-div-element-100-height-of-browser-window-using-css-only/
It works like this:
.element{
height: 100vh; /* For 100% screen height */
width: 100vw; /* For 100% screen width */
}
More info also available through Mozilla Developer Network and W3C.
Well then: welcome to the R world ;-)
Here you go
urls <- c(
"http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
"http://en.wikipedia.org/wiki/Xz",
"xxxxx"
)
readUrl <- function(url) {
out <- tryCatch(
{
# Just to highlight: if you want to use more than one
# R expression in the "try" part then you'll have to
# use curly brackets.
# 'tryCatch()' will return the last evaluated expression
# in case the "try" part was completed successfully
message("This is the 'try' part")
readLines(con=url, warn=FALSE)
# The return value of `readLines()` is the actual value
# that will be returned in case there is no condition
# (e.g. warning or error).
# You don't need to state the return value via `return()` as code
# in the "try" part is not wrapped inside a function (unlike that
# for the condition handlers for warnings and error below)
},
error=function(cond) {
message(paste("URL does not seem to exist:", url))
message("Here's the original error message:")
message(cond)
# Choose a return value in case of error
return(NA)
},
warning=function(cond) {
message(paste("URL caused a warning:", url))
message("Here's the original warning message:")
message(cond)
# Choose a return value in case of warning
return(NULL)
},
finally={
# NOTE:
# Here goes everything that should be executed at the end,
# regardless of success or error.
# If you want more than one expression to be executed, then you
# need to wrap them in curly brackets ({...}); otherwise you could
# just have written 'finally=<expression>'
message(paste("Processed URL:", url))
message("Some other message at the end")
}
)
return(out)
}
> y <- lapply(urls, readUrl)
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
URL does not seem to exist: xxxxx
Here's the original error message:
cannot open the connection
Processed URL: xxxxx
Some other message at the end
Warning message:
In file(con, "r") : cannot open file 'xxxxx': No such file or directory
> head(y[[1]])
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"
[2] "<html><head><title>R: Functions to Manipulate Connections</title>"
[3] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
[4] "<link rel=\"stylesheet\" type=\"text/css\" href=\"R.css\">"
[5] "</head><body>"
[6] ""
> length(y)
[1] 3
> y[[3]]
[1] NA
tryCatch
tryCatch
returns the value associated to executing expr
unless there's an error or a warning. In this case, specific return values (see return(NA)
above) can be specified by supplying a respective handler function (see arguments error
and warning
in ?tryCatch
). These can be functions that already exist, but you can also define them within tryCatch()
(as I did above).
The implications of choosing specific return values of the handler functions
As we've specified that NA
should be returned in case of error, the third element in y
is NA
. If we'd have chosen NULL
to be the return value, the length of y
would just have been 2
instead of 3
as lapply()
will simply "ignore" return values that are NULL
. Also note that if you don't specify an explicit return value via return()
, the handler functions will return NULL
(i.e. in case of an error or a warning condition).
"Undesired" warning message
As warn=FALSE
doesn't seem to have any effect, an alternative way to suppress the warning (which in this case isn't really of interest) is to use
suppressWarnings(readLines(con=url))
instead of
readLines(con=url, warn=FALSE)
Multiple expressions
Note that you can also place multiple expressions in the "actual expressions part" (argument expr
of tryCatch()
) if you wrap them in curly brackets (just like I illustrated in the finally
part).
I had the same ERROR
message. tbrisker's solution did not work in my case. Instead this solved the issue:
$ python3 -m venv .env
If you are doing this in a DB upgrade statement, perhaps the simplest way is to just catch the exception thrown if you are attempting to add a field that may already exist.
try {
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN foo TEXT default null");
} catch (SQLiteException ex) {
Log.w(TAG, "Altering " + TABLE_NAME + ": " + ex.getMessage());
}
I don't know if this is 'efficient', but it also works:
x = [1,2,3,4]
x.insert(0,x.pop())
EDIT: Hello again, I just found a big problem with this solution! Consider the following code:
class MyClass():
def __init__(self):
self.classlist = []
def shift_classlist(self): # right-shift-operation
self.classlist.insert(0, self.classlist.pop())
if __name__ == '__main__':
otherlist = [1,2,3]
x = MyClass()
# this is where kind of a magic link is created...
x.classlist = otherlist
for ii in xrange(2): # just to do it 2 times
print '\n\n\nbefore shift:'
print ' x.classlist =', x.classlist
print ' otherlist =', otherlist
x.shift_classlist()
print 'after shift:'
print ' x.classlist =', x.classlist
print ' otherlist =', otherlist, '<-- SHOULD NOT HAVE BIN CHANGED!'
The shift_classlist() method executes the same code as my x.insert(0,x.pop())-solution, otherlist is a list indipendent from the class. After passing the content of otherlist to the MyClass.classlist list, calling the shift_classlist() also changes the otherlist list:
CONSOLE OUTPUT:
before shift:
x.classlist = [1, 2, 3]
otherlist = [1, 2, 3]
after shift:
x.classlist = [3, 1, 2]
otherlist = [3, 1, 2] <-- SHOULD NOT HAVE BIN CHANGED!
before shift:
x.classlist = [3, 1, 2]
otherlist = [3, 1, 2]
after shift:
x.classlist = [2, 3, 1]
otherlist = [2, 3, 1] <-- SHOULD NOT HAVE BIN CHANGED!
I use Python 2.7. I don't know if thats a bug, but I think it's more likely that I missunderstood something here.
Does anyone of you know why this happens?
This answer is for users of SourceTree with limited terminal git experience.
Open the problematic submodule from within the Git project (super-project).
Fetch and ensure 'Fetch all tags' is checked.
Rebase pull your Git project.
This will solve the 'reference is not a tree' problem 9 out of ten times. That 1 time it won't, is a terminal fix as described by the top answer.
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
try this one http://code.google.com/p/geckofx/ hope it ain't dupe or this one i think is better http://webkitdotnet.sourceforge.net/
gcc
can use an assembly file as input, and invoke the assembler as needed. There is a subtlety, though:
.s
" (lowercase 's'), then gcc
calls the assembler..S
" (uppercase 'S'), then gcc
applies the C preprocessor on the source file (i.e. it recognizes directives such as #if
and replaces macros), and then calls the assembler on the result.So, on a general basis, you want to do things like this:
gcc -S file.c -o file.s
gcc -c file.s
On iOS 9.2 Profiles
renamed to Device Management
.
Now navigation looks like that:
Settings -> General -> Device Management -> Tap on necessary profile in list -> Trust.
In .Net Core 3+ and .Net 5+:
string escapedJsonString = JsonEncodedText.Encode(jsonString);
You can use like the following:
[ ! -z $(docker images -q someimage:sometag) ] || echo "does not exist"
Or:
[ -z $(docker images -q someimage:sometag) ] || echo "already exists"
I think you just need to add 2 more options (contentType
and dataType
):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Did you try using System.Net.WebClient
?
$url = 'https://IPADDRESS/resource'
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential("username","password")
$wc.DownloadString($url)
If you have one large dataframe and only a few update values I would use apply like this:
import pandas as pd
df = pd.DataFrame({'filename' : ['test0.dat', 'test2.dat'],
'm': [12, 13], 'n' : [None, None]})
data = {'filename' : 'test2.dat', 'n':16}
def update_vals(row, data=data):
if row.filename == data['filename']:
row.n = data['n']
return row
df.apply(update_vals, axis=1)
This is from the book Hackers: Heroes of the Computer Revolution by Steven Levy.
.. the memory had been reduced to 4096 "words" of eighteen bits each. (A "bit" is a binary digit, either a 1 or 0. A series of binary numbers is called a "word").
As the other answers suggest, a "word" does not seem to have a fixed length.
USE [master];
GO
CREATE DATABASE db;
GO
CREATE DATABASE db2;
GO
BACKUP DATABASE db TO DISK = 'c:\temp\db.bak' WITH INIT, COMPRESSION;
GO
RESTORE DATABASE db2
FROM DISK = 'c:\temp\db.bak'
WITH REPLACE,
MOVE 'db' TO 'c:\temp\db2.mdf',
MOVE 'db_log' TO 'c:\temp\db2.ldf';
Johann-S solution works great. (And it looks like he created the awesome plugin)
The Bootstrap 4.3 documentation example page uses this plugin to modify the filename: https://github.com/Johann-S/bs-custom-file-input
Use the Bootstrap custom file input classes. Add the plugin to your project, and add this code in your script file on the page.
$(document).ready(function () {
bsCustomFileInput.init()
})
Javascript document.getElementById("<%=contrilid.ClientID%>").value; or using jquery
$("#<%= txt_iplength.ClientID %>").val();
This is for Visual Studio 2019, After trying a lot of suggestions that failed to work (including changing the port number etc) I solved my problem by deleting a file that was generated on my project's root folder called "debug". As soon as this file was deleted everything started working.
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
methods for setting attributes(for example class) on an element: 1. el.className = string 2. el.setAttribute('class',string) 3. el.attributes.setNamedItem(object) 4. el.setAttributeNode(node)
I have made a simple benchmark test (here)
and it seems that setAttributeNode is about 3 times faster then using setAttribute.
so if performance is an issue - use "setAttributeNode"
Explaining how you can use cut
:
cat yourxmlfile | cut -d'"' -f2
It will 'cut' all the lines in the file based on " delimiter, and will take the 2nd field , which is what you wanted.
A mix fix for the underscore map bug :P
_.mixin({
mapobj : function( obj, iteratee, context ) {
if (obj == null) return [];
iteratee = _.iteratee(iteratee, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
results = {},
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
}
if ( _.isObject( obj ) ) {
return _.object( results ) ;
}
return results;
}
});
A simple workaround that keeps the right key and return as object It is still used the same way as i guest you could used this function to override the bugy _.map function
or simply as me used it as a mixin
_.mapobj ( options , function( val, key, list )
Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .
*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*
So error is raised..
Please refere sample script:
DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)
insert into #temp1 values(@id)
Select * from #temp1
Drop Table #temp1
If you want all the units, not just the biggest one, use one of these 2 methods (based on @Ankish's answer):
Example output: 28 D | 23 H | 59 M | 59 S
+ (NSString *) remaningTime:(NSDate *)startDate endDate:(NSDate *)endDate
{
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units fromDate: startDate toDate: endDate options: 0];
return [NSString stringWithFormat:@"%ti D | %ti H | %ti M | %ti S", [components day], [components hour], [components minute], [components second]];
}
+ (NSString *) timeFromNowUntil:(NSDate *)endDate
{
return [self remaningTime:[NSDate date] endDate:endDate];
}
git read-tree -um @ $commit_to_revert_to
will do it. It's "git checkout" but without updating HEAD.
You can achieve the same effect with
git checkout $commit_to_revert_to
git reset --soft @{1}
if you prefer stringing convenience commands together.
These leave you with your worktree and index in the desired state, you can just git commit
to finish.
First, HTTP-REST is a "representational state transfer" architecture. This implies a lot of interesting things:
Second, HTTP-REST is fully compliant with HTTP (see "safe" and "idempotent" in the previous part), therefore you will be able to reuse HTTP libraries (existing for every existing language) and HTTP reverse proxies, which will give you the ability to implement advanced features (cache, authentication, compression, redirection, rewriting, logging, etc.) with zero line of code.
Last but not least, using HTTP as an RPC protocol is a huge error according to the designer of HTTP 1.1 (and inventor of REST): http://www.ics.uci.edu/~fielding/pubs/dissertation/evaluation.htm#sec_6_5_2
Foreground needs a Brush, so you can use
textBlock.Foreground = Brushes.Navy;
If you want to use the color from RGB or ARGB then
textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35));
or
textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy);
To get the Color from Hex
textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991"));
Java does not check consistency in a strict sense, only notifies you if it runs into serious trouble. Also it does not give you much information from the error.
I was puzzled with what's happening in my sorter and made a strict consistencyChecker, maybe this will help you:
/**
* @param dailyReports
* @param comparator
*/
public static <T> void checkConsitency(final List<T> dailyReports, final Comparator<T> comparator) {
final Map<T, List<T>> objectMapSmallerOnes = new HashMap<T, List<T>>();
iterateDistinctPairs(dailyReports.iterator(), new IPairIteratorCallback<T>() {
/**
* @param o1
* @param o2
*/
@Override
public void pair(T o1, T o2) {
final int diff = comparator.compare(o1, o2);
if (diff < Compare.EQUAL) {
checkConsistency(objectMapSmallerOnes, o1, o2);
getListSafely(objectMapSmallerOnes, o2).add(o1);
} else if (Compare.EQUAL < diff) {
checkConsistency(objectMapSmallerOnes, o2, o1);
getListSafely(objectMapSmallerOnes, o1).add(o2);
} else {
throw new IllegalStateException("Equals not expected?");
}
}
});
}
/**
* @param objectMapSmallerOnes
* @param o1
* @param o2
*/
static <T> void checkConsistency(final Map<T, List<T>> objectMapSmallerOnes, T o1, T o2) {
final List<T> smallerThan = objectMapSmallerOnes.get(o1);
if (smallerThan != null) {
for (final T o : smallerThan) {
if (o == o2) {
throw new IllegalStateException(o2 + " cannot be smaller than " + o1 + " if it's supposed to be vice versa.");
}
checkConsistency(objectMapSmallerOnes, o, o2);
}
}
}
/**
* @param keyMapValues
* @param key
* @param <Key>
* @param <Value>
* @return List<Value>
*/
public static <Key, Value> List<Value> getListSafely(Map<Key, List<Value>> keyMapValues, Key key) {
List<Value> values = keyMapValues.get(key);
if (values == null) {
keyMapValues.put(key, values = new LinkedList<Value>());
}
return values;
}
/**
* @author Oku
*
* @param <T>
*/
public interface IPairIteratorCallback<T> {
/**
* @param o1
* @param o2
*/
void pair(T o1, T o2);
}
/**
*
* Iterates through each distinct unordered pair formed by the elements of a given iterator
*
* @param it
* @param callback
*/
public static <T> void iterateDistinctPairs(final Iterator<T> it, IPairIteratorCallback<T> callback) {
List<T> list = Convert.toMinimumArrayList(new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return it;
}
});
for (int outerIndex = 0; outerIndex < list.size() - 1; outerIndex++) {
for (int innerIndex = outerIndex + 1; innerIndex < list.size(); innerIndex++) {
callback.pair(list.get(outerIndex), list.get(innerIndex));
}
}
}
For the special case of HH:MM:SS.MS (eq: "00:04:33.637") as used by FFMPEG to specify milliseconds.
[-][HH:]MM:SS[.m...]
HH expresses the number of hours, MM the number of minutes for a maximum of 2 digits, and SS the number of seconds for a maximum of 2 digits. The m at the end expresses decimal value for SS.
/* HH:MM:SS.MS to (FLOAT)seconds ---------------*/
function timerToSec(timer){
let vtimer = timer.split(":")
let vhours = +vtimer[0]
let vminutes = +vtimer[1]
let vseconds = parseFloat(vtimer[2])
return vhours * 3600 + vminutes * 60 + vseconds
}
/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
let o = new Date(0)
let p = new Date(sec*1000)
return new Date(p.getTime()-o.getTime())
.toISOString()
.split("T")[1]
.split("Z")[0]
}
/* Example: 7hours, 4 minutes, 33 seconds and 637 milliseconds */
const t = "07:04:33.637"
console.log(
t + " => " +
timerToSec(t) +
"s"
)
/* Test: 25473 seconds and 637 milliseconds */
const s = 25473.637 // "25473.637"
console.log(
s + "s => " +
secToTimer(s)
)
_x000D_
Example usage, a milliseconds transport timer:
/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
let o = new Date(0)
let p = new Date(sec*1000)
return new Date(p.getTime()-o.getTime())
.toISOString()
.split("T")[1]
.split("Z")[0]
}
let job, origin = new Date().getTime()
const timer = () => {
job = requestAnimationFrame(timer)
OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
}
requestAnimationFrame(timer)
_x000D_
span {font-size:4rem}
_x000D_
<span id="OUT"></span>
<br>
<button onclick="origin = new Date().getTime()">RESET</button>
<button onclick="requestAnimationFrame(timer)">RESTART</button>
<button onclick="cancelAnimationFrame(job)">STOP</button>
_x000D_
Example usage, binded to a media element
/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
let o = new Date(0)
let p = new Date(sec*1000)
return new Date(p.getTime()-o.getTime())
.toISOString()
.split("T")[1]
.split("Z")[0]
}
VIDEO.addEventListener("timeupdate", function(e){
OUT.textContent = secToTimer(e.target.currentTime)
}, false)
_x000D_
span {font-size:4rem}
_x000D_
<span id="OUT"></span><br>
<video id="VIDEO" width="400" controls autoplay>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>
_x000D_
Outside the question, those functions written in php:
<?php
/* HH:MM:SS to (FLOAT)seconds ------------------*/
function timerToSec($timer){
$vtimer = explode(":",$timer);
$vhours = (int)$vtimer[0];
$vminutes = (int)$vtimer[1];
$vseconds = (float)$vtimer[2];
return $vhours * 3600 + $vminutes * 60 + $vseconds;
}
/* Seconds to (STRING)HH:MM:SS -----------------*/
function secToTimer($sec){
return explode(" ", date("H:i:s", $sec))[0];
}
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
This community wiki attempts to collect existing answers.
Python 2.7
In python 2, the keys()
, values()
, and items()
functions of OrderedDict
return lists. Using values
as an example, the simplest way is
d.values()[0] # "python"
d.values()[1] # "spam"
For large collections where you only care about a single index, you can avoid creating the full list using the generator versions, iterkeys
, itervalues
and iteritems
:
import itertools
next(itertools.islice(d.itervalues(), 0, 1)) # "python"
next(itertools.islice(d.itervalues(), 1, 2)) # "spam"
The indexed.py package provides IndexedOrderedDict
, which is designed for this use case and will be the fastest option.
from indexed import IndexedOrderedDict
d = IndexedOrderedDict({'foo':'python','bar':'spam'})
d.values()[0] # "python"
d.values()[1] # "spam"
Using itervalues can be considerably faster for large dictionaries with random access:
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 1000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i:i+1]'
1000 loops, best of 3: 259 usec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 10000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i:i+1]'
100 loops, best of 3: 2.3 msec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 100000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i:i+1]'
10 loops, best of 3: 24.5 msec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 1000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); next(itertools.islice(d.itervalues(), i, i+1))'
10000 loops, best of 3: 118 usec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 10000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); next(itertools.islice(d.itervalues(), i, i+1))'
1000 loops, best of 3: 1.26 msec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 100000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); next(itertools.islice(d.itervalues(), i, i+1))'
100 loops, best of 3: 10.9 msec per loop
$ python2 -m timeit -s 'from indexed import IndexedOrderedDict; from random import randint; size = 1000; d = IndexedOrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i]'
100000 loops, best of 3: 2.19 usec per loop
$ python2 -m timeit -s 'from indexed import IndexedOrderedDict; from random import randint; size = 10000; d = IndexedOrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i]'
100000 loops, best of 3: 2.24 usec per loop
$ python2 -m timeit -s 'from indexed import IndexedOrderedDict; from random import randint; size = 100000; d = IndexedOrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i]'
100000 loops, best of 3: 2.61 usec per loop
+--------+-----------+----------------+---------+
| size | list (ms) | generator (ms) | indexed |
+--------+-----------+----------------+---------+
| 1000 | .259 | .118 | .00219 |
| 10000 | 2.3 | 1.26 | .00224 |
| 100000 | 24.5 | 10.9 | .00261 |
+--------+-----------+----------------+---------+
Python 3.6
Python 3 has the same two basic options (list vs generator), but the dict methods return generators by default.
List method:
list(d.values())[0] # "python"
list(d.values())[1] # "spam"
Generator method:
import itertools
next(itertools.islice(d.values(), 0, 1)) # "python"
next(itertools.islice(d.values(), 1, 2)) # "spam"
Python 3 dictionaries are an order of magnitude faster than python 2 and have similar speedups for using generators.
+--------+-----------+----------------+---------+
| size | list (ms) | generator (ms) | indexed |
+--------+-----------+----------------+---------+
| 1000 | .0316 | .0165 | .00262 |
| 10000 | .288 | .166 | .00294 |
| 100000 | 3.53 | 1.48 | .00332 |
+--------+-----------+----------------+---------+
Use mvn dependency:purge-local-repository -DactTransitively=false -Dskip=true
if you have maven plugins as one of the modules. Otherwise Maven will try to recompile them, thus downloading the dependencies again.
I'll post this comment as answer, as I'm confident enough that what I asked is not possible.
I) Couple of similar questions trying to do the same, without success:
II) This article: Excel Pivot Table Calculated Field for example lists many restrictions of Calculated Field:
III) There is tiny limited possibility to use AVERAGE()
and similar function for a range of cells, but that applies only if Pivot table doesn't have grouped cells, which allows listing the cells as items in new group (right to "Fileds" listbox in above screenshot) and then user can calculate AVERAGE()
, referencing explicitly every item (cell), from Items listbox, as argument. Maybe it's better explained here: Calculate values in a PivotTable report
For my Pivot table it wasn't applicable because my range wasn't small enough, this option to be sane choice.
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
This will format column A as text, B as General, C as a number.
Sub formatColumns()
Columns(1).NumberFormat = "@"
Columns(2).NumberFormat = "General"
Columns(3).NumberFormat = "0"
End Sub
Try the following snippet. You can call the the below stored procedure from your application, so that NoOfUses
in the coupon table will be updated.
CREATE PROCEDURE [dbo].[sp_UpdateCouponCount]
AS
Declare @couponCount int,
@CouponName nvarchar(50),
@couponIdFromQuery int
Declare curP cursor For
select COUNT(*) as totalcount , Name as name,couponuse.couponid as couponid from Coupon as coupon
join CouponUse as couponuse on coupon.id = couponuse.couponid
where couponuse.id=@cuponId
group by couponuse.couponid , coupon.Name
OPEN curP
Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery
While @@Fetch_Status = 0 Begin
print @couponCount
print @CouponName
update Coupon SET NoofUses=@couponCount
where couponuse.id=@couponIdFromQuery
Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery
End -- End of Fetch
Close curP
Deallocate curP
Hope this helps!
Use strpos
. If the string is not found it returns false
, otherwise something that is not false
. Be sure to use a type-safe comparison (===
) as 0
may be returned and it is a falsy value:
if (strpos($string, $substring) === false) {
// substring is not found in string
}
if (strpos($string, $substring2) !== false) {
// substring2 is found in string
}
For iOS 6 devices, there is an option: Promoting Apps with Smart App Banners
My problem was that I needed to have the ""
outside the expression since I have a dynamic variable inside the sed expression itself. So than the actual solution is that one from lenn jackman that you replace the "
inside the sed regex with [\"]
.
So my complete bash is:
RELEASE_VERSION="0.6.6"
sed -i -e "s#value=[\"]trunk[\"]#value=\"tags/$RELEASE_VERSION\"#g" myfile.xml
Here is:
#
is the sed separator
[\"]
= "
in regex
value = \"tags/$RELEASE_VERSION\"
= my replacement string, important it has just the \"
for the quotes
what is a SID and Service name
please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm
In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"
When I have to use one or another? Why do I need two of them?
Consider below mapping in a RAC Environment,
SID SERVICE_NAME
bob1 bob
bob2 bob
bob3 bob
bob4 bob
if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.
Please refer, https://community.oracle.com/thread/4049517
If the set of colors is more or less fixed, the most efficient and also most readable way would be to use string constants in your app and then use MySQL's SET
type with FIND_IN_SET('red',colors)
in your queries. When using the SET
type with FIND_IN_SET, MySQL uses one integer to store all values and uses binary "and"
operation to check for presence of values which is way more efficient than scanning a comma-separated string.
In SET('red','blue','green')
, 'red'
would be stored internally as 1
, 'blue'
would be stored internally as 2
and 'green'
would be stored internally as 4
. The value 'red,blue'
would be stored as 3
(1|2
) and 'red,green'
as 5
(1|4
).
I knew I'd seen this somewhere. Here is the FreeBSD login tip:
Do you need to remove all those ^M characters from a DOS file? Try
tr -d \\r < dosfile > newfile
-- Originally by Dru <[email protected]>
Debug.Print
outputs to the "Immediate" window.
Also, you can simply type ?
and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:
This can be very handy to quickly output the property of an object...
? myWidget.name
...to set the property of an object...
myWidget.name = "thingy"
...or to even execute a function or line of code, while in debugging mode:
Sheet1.MyFunction()
The answers in question you linked-to are all about configuring git so that you can enter very short git push
commands and have them do whatever you want. Which is great, if you know what you want and how to spell that in Git-Ese, but you're new to git! :-)
In your case, Petr Mensik's answer is the (well, "a") right one. Here's why:
The command git push remote
roots around in your .git/config
file to find the named "remote" (e.g., origin
). The config file lists:
ssh://hostname/path
)git fetch remote
When you first cloned the repo—whenever that was—git set up default values for some of these. The URL is whatever you cloned from and the rest, if set or unset, are all "reasonable" defaults ... or, hmm, are they?
The issue with these is that people have changed their minds, over time, as to what is "reasonable". So now (depending on your version of git and whether you've configured things in detail), git may print a lot of warnings about defaults changing in the future. Adding the name of the "branch to push"—amd_qlp_tester
—(1) shuts it up, and (2) pushes just that one branch.
If you want to push more conveniently, you could do that with:
git push origin
or even:
git push
but whether that does what you want, depends on whether you agree with "early git authors" that the original defaults are reasonable, or "later git authors" that the original defaults aren't reasonable. So, when you want to do all the configuration stuff (eventually), see the question (and answers) you linked-to.
As for the name origin/amd_qlp_tester
in the first place: that's actually a local entity (a name kept inside your repo), even though it's called a "remote branch". It's git's best guess at "where amd_qlp_tester
is over there". Git updates it when it can.
If you are installed Skype, Please check this option.
Another case is Windows 10
Check this:
If you've changed the search_path
, specify the public schema in the function call:
public.uuid_generate_v4()
Solved on Laravel/Homestead (Vagrant Windows)
Edit Homestead.yaml
and increase memory from 2048 to 4096
vagrant up
vagrant ssh
Install Symfony with this line on the folder you choose (must be without files)
COMPOSER_MEMORY_LIMIT=-1 composer create-project symfony/website-skeleton . -s dev
Fun fact, in objective-c if you want to check null / nil For example:
-(NSString*) getSomeStringSafeCheck
{
NSString *string = [self getSomeString];
if(string != nil){
return String;
}
return @"";
}
The quick way to do it is:
-(NSString*) getSomeStringSafeCheck
{
return [self getSomeString] != nil ? [self getSomeString] : @"";
}
Then you can update it to a simplest way:
-(NSString*) getSomeStringSafeCheck
{
return [self getSomeString]?: @"";
}
Because in Objective-C:
So let say you write:
[self getSomeString] != nil?: @"";
the second parameter is returning a boolean value, thus a exception is thrown.
First you should create a div
with id='footer'
after your content
div and then simply do this.
Your HTML should look like this:
<html>
<body>
<div id="content">
...
</div>
<div id="footer"></div>
</body>
</html>
And the CSS:
?html, body {
height: 100%;
}
#content {
height: 100%;
}
#footer {
clear: both;
}
If you want to change the table default character set
and all character columns to a new character set, use a statement like this:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;
So query will be:
ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;
GUIDs may seem to be a natural choice for your primary key - and if you really must, you could probably argue to use it for the PRIMARY KEY of the table. What I'd strongly recommend not to do is use the GUID column as the clustering key, which SQL Server does by default, unless you specifically tell it not to.
You really need to keep two issues apart:
the primary key is a logical construct - one of the candidate keys that uniquely and reliably identifies every row in your table. This can be anything, really - an INT
, a GUID
, a string - pick what makes most sense for your scenario.
the clustering key (the column or columns that define the "clustered index" on the table) - this is a physical storage-related thing, and here, a small, stable, ever-increasing data type is your best pick - INT
or BIGINT
as your default option.
By default, the primary key on a SQL Server table is also used as the clustering key - but that doesn't need to be that way! I've personally seen massive performance gains when breaking up the previous GUID-based Primary / Clustered Key into two separate key - the primary (logical) key on the GUID, and the clustering (ordering) key on a separate INT IDENTITY(1,1)
column.
As Kimberly Tripp - the Queen of Indexing - and others have stated a great many times - a GUID
as the clustering key isn't optimal, since due to its randomness, it will lead to massive page and index fragmentation and to generally bad performance.
Yes, I know - there's newsequentialid()
in SQL Server 2005 and up - but even that is not truly and fully sequential and thus also suffers from the same problems as the GUID
- just a bit less prominently so.
Then there's another issue to consider: the clustering key on a table will be added to each and every entry on each and every non-clustered index on your table as well - thus you really want to make sure it's as small as possible. Typically, an INT
with 2+ billion rows should be sufficient for the vast majority of tables - and compared to a GUID
as the clustering key, you can save yourself hundreds of megabytes of storage on disk and in server memory.
Quick calculation - using INT
vs. GUID
as Primary and Clustering Key:
TOTAL: 25 MB vs. 106 MB - and that's just on a single table!
Some more food for thought - excellent stuff by Kimberly Tripp - read it, read it again, digest it! It's the SQL Server indexing gospel, really.
PS: of course, if you're dealing with just a few hundred or a few thousand rows - most of these arguments won't really have much of an impact on you. However: if you get into the tens or hundreds of thousands of rows, or you start counting in millions - then those points become very crucial and very important to understand.
Update: if you want to have your PKGUID
column as your primary key (but not your clustering key), and another column MYINT
(INT IDENTITY
) as your clustering key - use this:
CREATE TABLE dbo.MyTable
(PKGUID UNIQUEIDENTIFIER NOT NULL,
MyINT INT IDENTITY(1,1) NOT NULL,
.... add more columns as needed ...... )
ALTER TABLE dbo.MyTable
ADD CONSTRAINT PK_MyTable
PRIMARY KEY NONCLUSTERED (PKGUID)
CREATE UNIQUE CLUSTERED INDEX CIX_MyTable ON dbo.MyTable(MyINT)
Basically: you just have to explicitly tell the PRIMARY KEY
constraint that it's NONCLUSTERED
(otherwise it's created as your clustered index, by default) - and then you create a second index that's defined as CLUSTERED
This will work - and it's a valid option if you have an existing system that needs to be "re-engineered" for performance. For a new system, if you start from scratch, and you're not in a replication scenario, then I'd always pick ID INT IDENTITY(1,1)
as my clustered primary key - much more efficient than anything else!
For ASP.NET on Linux, check out Mono.
That said, thousands of sites run on Windows Server without any issues. A poorly-configured server with any OS will be vulnerable; Linux won't save you from a poor admin.
So I guess my "best practice" for deplying an ASP.NET app would be to use Windows Server 2008 (likely Web edition). And hire a good administrator.
You can give yourself permissions to fix this problem.
Right click on cacerts > choose properties > select Securit tab > Allow all permissions to all the Group and user names.
This worked for me.
In your phone go to Settings->Connect
to PC.
There you will see the option Default Connection Type
. Select it and set it to your preference.
None of the other answers worked for me. Note that SQL Server will give different results if you pass in a hard-coded string versus feed it from a column in your result set. Below is the magic that worked for me to give a perfect match between SQL Server and MySql
select LOWER(CONVERT(VARCHAR(32), HashBytes('MD5', CONVERT(varchar, EmailAddress)), 2)) from ...
When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe
You can do it using:
driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();
In case if your frameId is dynamic, and you only have one iframe, you can use something like:
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));
For windows
npm install -g grunt-cli
npm install load-grunt-tasks
Then run
grunt
You could also use lambda
. Useful if you're using django.utils.timezone.now
date = models.DateField(_("Date"), default=lambda: now().date())
I was using single quotes around the password parameter when I got the error
/p:password='my secret'
bad
and changed it to use double quotes to resolve the issue.
/p:password="my secret"
good
Likely the same would apply to any parameter that needs quotes for values that contain a space.
By default time zone of laravel project is **UTC*
'timezone' => 'UTC',
now change according to your time zone for me it's Asia/Calcutta
so for me setting will be 'timezone' => 'Asia/Calcutta',
*for time zone list visit this url https://www.w3schools.com/php/php_ref_timezones.asp
DELEGATES IN SWIFT 2
I am explaining with example of Delegate with two viewControllers.In this case, SecondVC Object is sending data back to first View Controller.
Class with Protocol Declaration
protocol getDataDelegate {
func getDataFromAnotherVC(temp: String)
}
import UIKit
class SecondVC: UIViewController {
var delegateCustom : getDataDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backToMainVC(sender: AnyObject) {
//calling method defined in first View Controller with Object
self.delegateCustom?.getDataFromAnotherVC(temp: "I am sending data from second controller to first view controller.Its my first delegate example. I am done with custom delegates.")
self.navigationController?.popViewControllerAnimated(true)
}
}
In First ViewController Protocol conforming is done here:
class ViewController: UIViewController, getDataDelegate
Protocol method definition in First View Controller(ViewController)
func getDataFromAnotherVC(temp : String)
{
// dataString from SecondVC
lblForData.text = dataString
}
During push the SecondVC from First View Controller (ViewController)
let objectPush = SecondVC()
objectPush.delegateCustom = self
self.navigationController.pushViewController(objectPush, animated: true)
This problem commonly occurs when switching from py2 to py3. In py2 plaintext
is both a string and a byte array type. In py3 plaintext
is only a string, and the method outfile.write()
actually takes a byte array when outfile
is opened in binary mode, so an exception is raised. Change the input to plaintext.encode('utf-8')
to fix the problem. Read on if this bothers you.
In py2, the declaration for file.write made it seem like you passed in a string: file.write(str)
. Actually you were passing in a byte array, you should have been reading the declaration like this: file.write(bytes)
. If you read it like this the problem is simple, file.write(bytes)
needs a bytes type and in py3 to get bytes out of a str you convert it:
py3>> outfile.write(plaintext.encode('utf-8'))
Why did the py2 docs declare file.write
took a string? Well in py2 the declaration distinction didn't matter because:
py2>> str==bytes #str and bytes aliased a single hybrid class in py2
True
The str-bytes class of py2 has methods/constructors that make it behave like a string class in some ways and a byte array class in others. Convenient for file.write
isn't it?:
py2>> plaintext='my string literal'
py2>> type(plaintext)
str #is it a string or is it a byte array? it's both!
py2>> outfile.write(plaintext) #can use plaintext as a byte array
Why did py3 break this nice system? Well because in py2 basic string functions didn't work for the rest of the world. Measure the length of a word with a non-ASCII character?
py2>> len('¡no') #length of string=3, length of UTF-8 byte array=4, since with variable len encoding the non-ASCII chars = 2-6 bytes
4 #always gives bytes.len not str.len
All this time you thought you were asking for the len of a string in py2, you were getting the length of the byte array from the encoding. That ambiguity is the fundamental problem with double-duty classes. Which version of any method call do you implement?
The good news then is that py3 fixes this problem. It disentangles the str and bytes classes. The str class has string-like methods, the separate bytes class has byte array methods:
py3>> len('¡ok') #string
3
py3>> len('¡ok'.encode('utf-8')) #bytes
4
Hopefully knowing this helps de-mystify the issue, and makes the migration pain a little easier to bear.
import sys
try:
print("stuff")
except:
sys.exit(1) # exiing with a non zero value is better for returning from an error
You can create a macro for Ctrl +Shift + S (for example) that do all this things:
Edit > Macros > Start Macro Recording (the recording will start). Click where you need.
For example:
Code > Reformat Code
Code > Auto-Indent Lines
Code > Optimize Imports
Code > Rearrange Code
File > Save All
... (all that you want)
Then, click on red button in bottom-right of the IDE to stop the Macro recording.
Set a macro name.
Go to File > Settings > Macros > YOUR MACRO NAME.
Right Click > Add Keyboard Shortcut, and type Ctrl + Shift + S.
I faced with the same error, when i downloaded the Jmeter Source
, and it got fixed once i downloaded Jmeter Binary
. Please watch this video.
<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox
<div id="div1" style="display:none;">NOTICE</div>
<script type="text/javascript">
<!--
function showMe (box) {
var chboxs = document.getElementById("div1").style.display;
var vis = "none";
if(chboxs=="none"){
vis = "block"; }
if(chboxs=="block"){
vis = "none"; }
document.getElementById(box).style.display = vis;
}
//-->
</script>
Try it using CONCAT
CONCAT('site.com/path/','%', CAST(t1.id AS CHAR(25)), '%','/more')
Up until jQuery 1.11.1, you could use the following URLs to get the latest version of jQuery:
For example:
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
However, since jQuery 1.11.1, both jQuery and Google stopped updating these URL's; they will forever be fixed at 1.11.1. There is no supported alternative URL to use. For an explanation of why this is the case, see this blog post; Don't use jquery-latest.js.
Both hosts support https
as well as http
, so change the protocol as you see fit (or use a protocol relative URI)
See also: https://developers.google.com/speed/libraries/devguide
Deleting the .vs folder in the solution solved my issue. You have to exit from Visual Studio and then delete the .vs folder and start Visual Studio again.
On Ubuntu 14.04 I resolved this by using the pip installation bootstrap script, as described in the documentation
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
That's an OK solution for a development environment.
alter sequence serial restart start with 1;
This feature was officially added in 18c but is unofficially available since 12.1.
It is arguably safe to use this undocumented feature in 12.1. Even though the syntax is not included in the official documentation, it is generated by the Oracle package DBMS_METADATA_DIFF. I've used it several times on production systems. However, I created an Oracle Service request and they verified that it's not a documentation bug, the feature is truly unsupported.
In 18c, the feature does not appear in the SQL Language Syntax, but is included in the Database Administrator's Guide.
How about
...
C() : arr{ {1,2,3} }
{}
...
?
Compiles fine on g++ 4.8
display:
is not transitionable. You'll probably need to use jQuery to do what you want to do.
Use test.md
as a example:
? spark-1.6.1 cat test.md
This is the first line;
This is the second line;
This is the last line.
scala> val textFile = sc.textFile("test.md")
scala> textFile.map(line => line.split(" ")).count()
res2: Long = 3
scala> textFile.flatMap(line => line.split(" ")).count()
res3: Long = 15
scala> textFile.map(line => line.split(" ")).collect()
res0: Array[Array[String]] = Array(Array(This, is, the, first, line;), Array(This, is, the, second, line;), Array(This, is, the, last, line.))
scala> textFile.flatMap(line => line.split(" ")).collect()
res1: Array[String] = Array(This, is, the, first, line;, This, is, the, second, line;, This, is, the, last, line.)
If you use map
method, you will get the lines of test.md
, for flatMap
method, you will get the number of words.
The map
method is similar to flatMap
, they are all return a new RDD. map
method often to use return a new RDD, flatMap
method often to use split words.
I am using MacOS catalina 10.15.4. None of the posted solutions worked for me. What worked for me is:
>> xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
>> env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip install psycopg2==2.8.4
Collecting psycopg2==2.8.4
Using cached psycopg2-2.8.4.tar.gz (377 kB)
Installing collected packages: psycopg2
Attempting uninstall: psycopg2
Found existing installation: psycopg2 2.7.7
Uninstalling psycopg2-2.7.7:
Successfully uninstalled psycopg2-2.7.7
Running setup.py install for psycopg2 ... done
Successfully installed psycopg2-2.8.4
use pip3 for python3
Depending on how you are running the command, you can put /k
after cmd
to keep the window open.
cmd /k my_script.bat
Simply adding cmd /k
to the end of your batch file will work too. Credit to Luigi D'Amico who posted about this in the comments below.
this is the easiest way:
Make list
Select list
right click: Define Name (e.g. ItemStatus)
select a cell where the list should appear (copy paste can be done later, so not location critical)
Data > Data Validation
Allow: Select List
Source: =ItemStatus (don't forget the = sign)
click Ok
dropdown appears in the cell you selected
Home > Conditional Formatting
Manage Rules
New Rule
etc.
I would prefer the C++ min/max functions, if you are using C++, because they are type-specific. fmin/fmax will force everything to be converted to/from floating point.
Also, the C++ min/max functions will work with user-defined types as long as you have defined operator< for those types.
HTH
My 5 (wrong) cents
'a' in "".join(['A']).lower()
Ouch, totally agree @jpp, I'll keep as an example of bad practice :(
SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';
Since pg_stat_activity
contains connection statistics of all databases having any state, either idle
or active
, database name and connection state should be included in the query to get the desired output.
class Graph<E> {
private List<Vertex<E>> vertices;
private static class Vertex<E> {
E elem;
List<Vertex<E>> neighbors;
}
}
I agree with what Joachim Sauer said, not possible to know (the variable type! not value type!) unless your variable is a class attribute (and you would have to retrieve class fields, get the right field by name...)
Actually for me it's totally impossible that any a.xxx().yyy()
method give you the right answer since the answer would be different on the exact same object, according to the context in which you call this method...
As teehoo said, if you know at compile a defined list of types to test you can use instanceof but you will also get subclasses returning true...
One possible solution would also be to inspire yourself from the implementation of java.lang.reflect.Field
and create your own Field
class, and then declare all your local variables as this custom Field
implementation... but you'd better find another solution, i really wonder why you need the variable type, and not just the value type?
logout your account in skype.. then in xampp control panel click start from the line of Apache..
your div looks like this:
<div id="someId">Some Value</div>
With jquery:
<script type="text/javascript">
$(function(){
var text = $('#someId').html();
//or
var text = $('#someId').text();
};
</script>
Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
Exchanges will usually publish an up-to-date list of securities on their web pages. For example, these pages offer CSV downloads:
NASDAQ Updated their site, so you will have to modify the URLS:
NASDAQ
AMEX
NYSE
Depending on your requirement, you could create the map of these URLs by exchange in your own code.
what language is this? If you're using a language that passes everything by reference like Java (except for native types), typically you can call .clone()
method. The .clone() method is typically implemented by copying/cloning all relevant instance fields into the new object.
MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.
It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.
The feature doesn't prevent any other type of data forgery or tampering based attacks.
To use it, decorate the action method or controller with the ValidateAntiForgeryToken
attribute and place a call to @Html.AntiForgeryToken()
in the forms posting to the method.
If you switch from Web to Express you will no longer be able to use the SQL Server Agent service so you need to set up a different scheduler for maintenance and backups.
Generic List<T>
have the Where<T>(Func<T, Boolean>)
extension method that can be used to filter data.
In your case with a row array:
var rows = rowsArray.Where(row => row["LastName"].ToString().StartsWith("a"));
If you are using DataRowCollection
, you need to cast it first.
var rows = dataTableRows.Cast<DataRow>().Where(row => row["LastName"].ToString().StartsWith("a"));
private System.Windows.Forms.TabControl _tabControl;
private System.Windows.Forms.TabPage _tabPage1;
private System.Windows.Forms.TabPage _tabPage2;
...
// Initialise the controls
...
// "hides" tab page 2
_tabControl.TabPages.Remove(_tabPage2);
// "shows" tab page 2
// if the tab control does not contain tabpage2
if (! _tabControl.TabPages.Contains(_tabPage2))
{
_tabControl.TabPages.Add(_tabPage2);
}
if you want to scroll within a particular view/frame (WebElement), what you only need to do is to replace "body" with a particular element that you intend to scroll within. i get that element via "getElementById" in the example below:
self.driver.execute_script('window.scrollTo(0, document.getElementById("page-manager").scrollHeight);')
this is the case on YouTube, for example...
I developed a plugin and installed it on a Wordpress site running on Nginx and it was fine. I only had this error when I switched to Apache, turned out the web server was not accepting the <?
, so I just replaced the <?
tags to <?php
then it worked.
From gamedev
string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.
Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.
In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.
Option Explicit
Sub test()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A1:IV65536"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Code goes here for whatever it is you want to do.
End If
Next iCol
Next iRow
End Sub
To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:
Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need
The -nc
, --no-clobber
option isn't the best solution as newer files will not be downloaded. One should use -N
instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:
wget -N http://www.example.com/images/misc/pic.png
Then running Wget with -N, with or without
-r
or-p
, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file.-nc
may not be specified at the same time as-N
.
-N
,--timestamping
: Turn on time-stamping.
Try this:
$(function () {
$('#row_dim').hide(); // this line you can avoid by adding #row_dim{display:none;} in your CSS
$('#type').change(function () {
$('#row_dim').hide();
if (this.options[this.selectedIndex].value == 'parcel') {
$('#row_dim').show();
}
});
});
There is an another option to insert data into table ..
insert into tablename values(&column_name1,&column_name2,&column_name3);
it will open another window for inserting the data value..
From the documentation:
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called
static
in your package or next to your module and it will be available at/static
on the application.To generate URLs for static files, use the special
'static'
endpoint name:url_for('static', filename='style.css')
The file has to be stored on the filesystem as
static/style.css
.
An other implementation of @qneill code which include CRC checksum of the original message, it throw an exception if the check fail:
import hashlib
import struct
import zlib
def vigenere_encode(text, key):
text = '{}{}'.format(text, struct.pack('i', zlib.crc32(text)))
enc = []
for i in range(len(text)):
key_c = key[i % len(key)]
enc_c = chr((ord(text[i]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc))
def vigenere_decode(encoded_text, key):
dec = []
encoded_text = base64.urlsafe_b64decode(encoded_text)
for i in range(len(encoded_text)):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(encoded_text[i]) - ord(key_c)) % 256)
dec.append(dec_c)
dec = "".join(dec)
checksum = dec[-4:]
dec = dec[:-4]
assert zlib.crc32(dec) == struct.unpack('i', checksum)[0], 'Decode Checksum Error'
return dec
Some of the provided answers did not work for me (javaw.exe still running after closing the window) or, eclipse showed an exception after the application was closed.
On the other hand, this works perfectly:
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent t) {
Platform.exit();
System.exit(0);
}
});
Just use the following command
git show a2c25061
or (the exact equivalent):
git log -p -1 a2c25061
Give this a try :P
s = '#'.repeat(10)_x000D_
_x000D_
document.body.innerHTML = s
_x000D_
Same as matt said. The "SQL Server(SQLEXPRESS)" was stopped. Enabled it by opening Control Panel > Administrative Tools > Services, right-clicking on the "SQL Server(SQLEXPRESS)" service and selecting "Start" from the available options. Could connect fine after that.
I'd consider using a nullable types.
DateTime? myDate
instead of DateTime myDate
.
Sometimes the same program must handle different database stuctures. So I could not use a column list in the program to avoid errors in select
statements.
*
gives me all the optional fields. I check if the fields exist in the data table before use. This is my reason for using *
in select
.
This is how I handle excluded fields:
Dim da As New SqlDataAdapter("select * from table", cn)
da.FillSchema(dt, SchemaType.Source)
Dim fieldlist As String = ""
For Each DC As DataColumn In DT.Columns
If DC.ColumnName.ToLower <> excludefield Then
fieldlist = fieldlist & DC.Columnname & ","
End If
Next
REGEXP_COUNT should do the trick:
select REGEXP_COUNT('123-345-566', '-') from dual;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
public class JavaYoutubeDownloader {
public static String newline = System.getProperty("line.separator");
private static final Logger log = Logger.getLogger(JavaYoutubeDownloader.class.getCanonicalName());
private static final Level defaultLogLevelSelf = Level.FINER;
private static final Level defaultLogLevel = Level.WARNING;
private static final Logger rootlog = Logger.getLogger("");
private static final String scheme = "http";
private static final String host = "www.youtube.com";
private static final Pattern commaPattern = Pattern.compile(",");
private static final Pattern pipePattern = Pattern.compile("\\|");
private static final char[] ILLEGAL_FILENAME_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };
private static void usage(String error) {
if (error != null) {
System.err.println("Error: " + error);
}
System.err.println("usage: JavaYoutubeDownload VIDEO_ID DESTINATION_DIRECTORY");
System.exit(-1);
}
public static void main(String[] args) {
if (args == null || args.length == 0) {
usage("Missing video id. Extract from http://www.youtube.com/watch?v=VIDEO_ID");
}
try {
setupLogging();
log.fine("Starting");
String videoId = null;
String outdir = ".";
// TODO Ghetto command line parsing
if (args.length == 1) {
videoId = args[0];
} else if (args.length == 2) {
videoId = args[0];
outdir = args[1];
}
int format = 18; // http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs
String encoding = "UTF-8";
String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
File outputDir = new File(outdir);
String extension = getExtension(format);
play(videoId, format, encoding, userAgent, outputDir, extension);
} catch (Throwable t) {
t.printStackTrace();
}
log.fine("Finished");
}
private static String getExtension(int format) {
// TODO
return "mp4";
}
private static void play(String videoId, int format, String encoding, String userAgent, File outputdir, String extension) throws Throwable {
log.fine("Retrieving " + videoId);
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("video_id", videoId));
qparams.add(new BasicNameValuePair("fmt", "" + format));
URI uri = getUri("get_video_info", qparams);
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("User-Agent", userAgent);
log.finer("Executing " + uri);
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
InputStream instream = entity.getContent();
String videoInfo = getStringFromInputStream(encoding, instream);
if (videoInfo != null && videoInfo.length() > 0) {
List<NameValuePair> infoMap = new ArrayList<NameValuePair>();
URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding);
String token = null;
String downloadUrl = null;
String filename = videoId;
for (NameValuePair pair : infoMap) {
String key = pair.getName();
String val = pair.getValue();
log.finest(key + "=" + val);
if (key.equals("token")) {
token = val;
} else if (key.equals("title")) {
filename = val;
} else if (key.equals("fmt_url_map")) {
String[] formats = commaPattern.split(val);
for (String fmt : formats) {
String[] fmtPieces = pipePattern.split(fmt);
if (fmtPieces.length == 2) {
// in the end, download somethin!
downloadUrl = fmtPieces[1];
int pieceFormat = Integer.parseInt(fmtPieces[0]);
if (pieceFormat == format) {
// found what we want
downloadUrl = fmtPieces[1];
break;
}
}
}
}
}
filename = cleanFilename(filename);
if (filename.length() == 0) {
filename = videoId;
} else {
filename += "_" + videoId;
}
filename += "." + extension;
File outputfile = new File(outputdir, filename);
if (downloadUrl != null) {
downloadWithHttpClient(userAgent, downloadUrl, outputfile);
}
}
}
}
private static void downloadWithHttpClient(String userAgent, String downloadUrl, File outputfile) throws Throwable {
HttpGet httpget2 = new HttpGet(downloadUrl);
httpget2.setHeader("User-Agent", userAgent);
log.finer("Executing " + httpget2.getURI());
HttpClient httpclient2 = new DefaultHttpClient();
HttpResponse response2 = httpclient2.execute(httpget2);
HttpEntity entity2 = response2.getEntity();
if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
long length = entity2.getContentLength();
InputStream instream2 = entity2.getContent();
log.finer("Writing " + length + " bytes to " + outputfile);
if (outputfile.exists()) {
outputfile.delete();
}
FileOutputStream outstream = new FileOutputStream(outputfile);
try {
byte[] buffer = new byte[2048];
int count = -1;
while ((count = instream2.read(buffer)) != -1) {
outstream.write(buffer, 0, count);
}
outstream.flush();
} finally {
outstream.close();
}
}
}
private static String cleanFilename(String filename) {
for (char c : ILLEGAL_FILENAME_CHARACTERS) {
filename = filename.replace(c, '_');
}
return filename;
}
private static URI getUri(String path, List<NameValuePair> qparams) throws URISyntaxException {
URI uri = URIUtils.createURI(scheme, host, -1, "/" + path, URLEncodedUtils.format(qparams, "UTF-8"), null);
return uri;
}
private static void setupLogging() {
changeFormatter(new Formatter() {
@Override
public String format(LogRecord arg0) {
return arg0.getMessage() + newline;
}
});
explicitlySetAllLogging(Level.FINER);
}
private static void changeFormatter(Formatter formatter) {
Handler[] handlers = rootlog.getHandlers();
for (Handler handler : handlers) {
handler.setFormatter(formatter);
}
}
private static void explicitlySetAllLogging(Level level) {
rootlog.setLevel(Level.ALL);
for (Handler handler : rootlog.getHandlers()) {
handler.setLevel(defaultLogLevelSelf);
}
log.setLevel(level);
rootlog.setLevel(defaultLogLevel);
}
private static String getStringFromInputStream(String encoding, InputStream instream) throws UnsupportedEncodingException, IOException {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
instream.close();
}
String result = writer.toString();
return result;
}
}
/**
* <pre>
* Exploded results from get_video_info:
*
* fexp=90...
* allow_embed=1
* fmt_stream_map=35|http://v9.lscache8...
* fmt_url_map=35|http://v9.lscache8...
* allow_ratings=1
* keywords=Stefan Molyneux,Luke Bessey,anarchy,stateless society,giant stone cow,the story of our unenslavement,market anarchy,voluntaryism,anarcho capitalism
* track_embed=0
* fmt_list=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
* author=lukebessey
* muted=0
* length_seconds=390
* plid=AA...
* ftoken=null
* status=ok
* watermark=http://s.ytimg.com/yt/swf/logo-vfl_bP6ud.swf,http://s.ytimg.com/yt/swf/hdlogo-vfloR6wva.swf
* timestamp=12...
* has_cc=False
* fmt_map=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
* leanback_module=http://s.ytimg.com/yt/swfbin/leanback_module-vflJYyeZN.swf
* hl=en_US
* endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vflk19iTq.swf
* vq=auto
* avg_rating=5.0
* video_id=S6IZP3yRJ9I
* token=vPpcFNh...
* thumbnail_url=http://i4.ytimg.com/vi/S6IZP3yRJ9I/default.jpg
* title=The Story of Our Unenslavement - Animated
* </pre>
*/
The one with the "Pings" helped me... but may be explained a little better...
For me the solution was to change:
copy $(TargetDir)$(TargetName).* $(SolutionDir)bin
to this:
copy "$(TargetDir)$(TargetName).*" "$(SolutionDir)bin"
Hope it works for you. :-)
It's an old question, but I don't see mentioned that, depending on the details, the sharey
option may be able to do all of this for you, instead of digging up axis limits, margins, etc. There's a demo in the docs that shows how to use sharex
, but the same can be done with y-axes.
If you just want to list all the sites (ie. to find a binding)
Change the working directory to "C:\Windows\system32\inetsrv"
cd c:\Windows\system32\inetsrv
Next run "appcmd list sites" (plural) and output to a file. e.g c:\IISSiteBindings.txt
appcmd list sites > c:\IISSiteBindings.txt
Now open with notepad from your command prompt.
notepad c:\IISSiteBindings.txt
Use Css Selector for this, or learn more about Css Selector just go here
https://www.w3schools.com/cssref/css_selectors.asp
#main_text > .title {
/* Style goes here */
}
#main_text .title {
/* Style goes here */
}
Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,
or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.
=ADDRESS(ROW(),COLUMN())
=ADDRESS(ROW(),COLUMN(),1)
=ADDRESS(ROW(),COLUMN(),2)
=ADDRESS(ROW(),COLUMN(),3)
=ADDRESS(ROW(),COLUMN(),4)
Another way to make objects in Javascript
using JQuery
, getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be:
var box = {}; // my object
var boxes = []; // my array
$('div.test').each(function (index, value) {
color = $('p', this).attr('color');
box = {
_color: color // being _color a property of `box`
}
boxes.push(box);
});
Hope it helps!
Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):
To install additional ESP8266WiFi library:
After above steps, you should compile the sketch normally.
Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.
In relation to the top answer I have a possible solution to the security risk.
<?php
if(isset($_GET['path'])){
if(in_array($_GET['path'], glob("*/*.*"))){
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
}
}
?>
Using the glob() function (I tested the download file in a path one folder up from the file to be downloaded) I was able to make a quick array of files that are "allowed" to be downloaded and checked the passed path against it. Not only does this insure that the file being grabbed isn't something sensitive but also checks on the files existence at the same time.
~Note: Javascript / HTML~
HTML:
<iframe id="download" style="display:none"></iframe>
and
<input type="submit" value="Download" onclick="ChangeSource('document_path');return false;">
JavaScript:
<script type="text/javascript">
<!--
function ChangeSource(path){
document.getElementByID('download').src = 'path_to_php?path=' + document_path;
}
-->
</script>
I was having this issue on OS X and it seemed to be caused by a version mismatch between my globally installed webpack
and my locally installed webpack-dev-server
. Updating both to the latest version got rid of the issue.
Hopefully this would get you started
See it live on http://ideone.com/l23He (using stdin)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* getfield(char* line, int num)
{
const char* tok;
for (tok = strtok(line, ";");
tok && *tok;
tok = strtok(NULL, ";\n"))
{
if (!--num)
return tok;
}
return NULL;
}
int main()
{
FILE* stream = fopen("input", "r");
char line[1024];
while (fgets(line, 1024, stream))
{
char* tmp = strdup(line);
printf("Field 3 would be %s\n", getfield(tmp, 3));
// NOTE strtok clobbers tmp
free(tmp);
}
}
Output:
Field 3 would be nazwisko
Field 3 would be Kowalski
Field 3 would be Nowak
The simplest way to do this is to add the .config
file in the deployment section on your unit test.
To do so, open the .testrunconfig
file from your Solution Items. In the Deployment section, add the output .config
files from your project's build directory (presumably bin\Debug
).
Anything listed in the deployment section will be copied into the test project's working folder before the tests are run, so your config-dependent code will run fine.
Edit: I forgot to add, this will not work in all situations, so you may need to include a startup script that renames the output .config
to match the unit test's name.
It goes like ng-bind-html-unsafe="opt.text"
:
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
{{ opt.text }}
</li>
</ul>
<p>{{opt}}</p>
</div>
Or you can define a function in scope:
$scope.getContent = function(obj){
return obj.value + " " + obj.text;
}
And use it this way:
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="getContent(opt)" >
{{ opt.value }}
</li>
Note that you can not do it with an option
tag: Can I use HTML tags in the options for select elements?
<?php
$table = 'orders';
$query = "SHOW COLUMNS FROM $table";
if($output = mysql_query($query)):
$columns = array();
while($result = mysql_fetch_assoc($output)):
$columns[] = $result['Field'];
endwhile;
endif;
echo '<pre>';
print_r($columns);
echo '</pre>';
?>
The URL approach will only work for small HTML fragements. The more solid approach is to generate an object URL from a blob and use it as a source of the dynamic iframe.
const html = '<html>...</html>';
const iframe = document.createElement('iframe');
const blob = new Blob([html], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
document.body.appendChild(iframe);
For PHP7, use
sudo apt-get install php7.0-sqlite3
and restart Apache
sudo apache2ctl restart
You could do it this way:
res.status(400).json(json_response);
This will set the HTTP status code to 400, it works even in express 4.
You can just call it.
function test(){
print_r(func_get_args());
}
test("blah");
test("blah","blah");
Output:
Array ( [0] => blah ) Array ( [0] => blah [1] => blah )
This code works for me:
$rootScope.$$listeners.nameOfYourEvent=[];
Assuming you want to delete 3 by value at multiple places in an array, I think the ruby way to do this task would be to use the delete_if method:
[2,4,6,3,8,3].delete_if {|x| x == 3 }
You can also use delete_if in removing elements in the scenario of 'array of arrays'.
Hope this resolves your query
Hi sorry for bump this post just face this problem and i would like to show my case.
My code look like this.
<button onClick="product.delete('1')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('2')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('3')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('4')" class="btn btn-danger">Delete</button>
Javascript code
<script>
var product = {
// Define your function
'add':(product_id)=>{
// Do some thing here
},
'delete':(product_id)=>{
// Do some thig here
}
}
</script>
print "Number of lines: $nids\n";
print "Content: $ids\n";
How did Perl complain? print $ids
should work, though you probably want a newline at the end, either explicitly with print
as above or implicitly by using say
or -l/$\.
If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}
:
print "foo${ids}bar";
I just constructed a command that helped me find my lost stash commit:
for ref in `find .git/objects | sed -e 's#.git/objects/##' | grep / | tr -d /`; do if [ `git cat-file -t $ref` = "commit" ]; then git show --summary $ref; fi; done | less
This lists all the objects in the .git/objects tree, locates the ones that are of type commit, then shows a summary of each one. From this point it was just a matter of looking through the commits to find an appropriate "WIP on work: 6a9bb2" ("work" is my branch, 619bb2 is a recent commit).
I note that if I use "git stash apply" instead of "git stash pop" I wouldn't have this problem, and if I use "git stash save message" then the commit might have been easier to find.
Update: With Nathan's idea, this becomes shorter:
for ref in `git fsck --unreachable | grep commit | cut -d' ' -f3`; do git show --summary $ref; done | less
Create a setOptionsTitle() method and set a field in your class. Such as:
String bedStatus = "Set to 'Out of Bed'";
...
public void setOptionsTitle(String status)
{
bedStatus = status;
}
Now when the menu gets populated, change the title to whatever your status is:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(bedStatus);
// Return true so that the menu gets displayed.
return true;
}
Oracle JavaFX from Java SE supports only OS X (macOS), GNU/Linux and Microsoft Windows. On these platforms, JavaFX applications are typically run on JVM from Java SE or OpenJDK.
There is also a JavaFXPorts project, which is an open-source project sponsored by a third-party. It aims to port JavaFX library to Android and iOS.
On Android, this library can be used like any other Java library; the JVM bytecode is compiled to Dalvik bytecode. It's what people mean by saying that "Android runs Java".
On iOS, situation is a bit more complex, as neither Java SE nor OpenJDK supports Apple mobile devices. Till recently, the only sensible option was to use RoboVM ahead-of-time Java compiler for iOS. Unfortunately, on 15 April 2015, RoboVM project was shut down.
One possible alternative is Intel's Multi-OS Engine. Till recently, it was a proprietary technology, but on 11 August 2016 it was open-sourced. Although it can be possible to compile an iOS JavaFX app using JavaFXPorts' JavaFX implementation, there is no evidence for that so far. As you can see, the situation is dynamically changing, and this answer will be hopefully updated when new information is available.
With Windows Phone it's simple: there is no JavaFX support of any kind.
The isdigit
method of the str
type returns True
iff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.
There is no decent way to get that setting, at least not something browser independent.
But the server has that info, because it is part of the HTTP request header (the Accept-Language field, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)
So the only reliable way is to get an answer back from the server. You will need something that runs on the server (like .asp, .jsp, .php, CGI) and that "thing" can return that info. Good examples here: http://www.developershome.com/wap/detection/detection.asp?page=readHeader
You need to rename your main class to Main
, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main
.
That's all.
I am beginner to iOS development so I would like to share whole info I got in this section.
First from image assets (images.xcassets) create image set .
According to Documentation here is all sizes need to create background image.
For iPhone 5:
640 x 1136
For iPhone 6:
750 x 1334 (@2x) for portrait
1334 x 750 (@2x) for landscape
For iPhone 6 Plus:
1242 x 2208 (@3x) for portrait
2208 x 1242 (@3x) for landscape
iPhone 4s (@2x)
640 x 960
iPad and iPad mini (@2x)
1536 x 2048 (portrait)
2048 x 1536 (landscape)
iPad 2 and iPad mini (@1x)
768 x 1024 (portrait)
1024 x 768 (landscape)
iPad Pro (@2x)
2048 x 2732 (portrait)
2732 x 2048 (landscape)
call the image background we can call image from image assets by using this method UIImage(named: "background")
here is full code example
override func viewDidLoad() {
super.viewDidLoad()
assignbackground()
// Do any additional setup after loading the view.
}
func assignbackground(){
let background = UIImage(named: "background")
var imageView : UIImageView!
imageView = UIImageView(frame: view.bounds)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
imageView.image = background
imageView.center = view.center
view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
}
I authored the G2 project, a friendly environment for the command line git lover.
Please get the project from github - G2 https://github.com/orefalo/g2
It has a bunch of handy commands, one of them being exactly what your are looking for: freeze
freeze - Freeze all files in the repository (additions, deletions, modifications) to the staging area, thus staging that content for inclusion in the next commit. Also accept a specific path as parameter
If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest
android:exported="true"
Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.
finish();
The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class
in the code, so compile will fail.
I searched on the web and found something like this below, and it works well.
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);
You can also use the setClassName method:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();
You can also pass the values from one app to another app :
Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
launchIntent.putExtra("AppID", "MY-CHILD-APP1");
launchIntent.putExtra("UserID", "MY-APP");
launchIntent.putExtra("Password", "MY-PASSWORD");
startActivity(launchIntent);
finish();
} else {
Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}
Refer to example at this link. It may be help to you.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx
void Page_Load(Object sender, EventArgs e)
{
// Load data for the DropDownList control only once, when the
// page is first loaded.
if(!IsPostBack)
{
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
ColorList.DataSource = CreateDataSource();
ColorList.DataTextField = "ColorTextField";
ColorList.DataValueField = "ColorValueField";
// Bind the data to the control.
ColorList.DataBind();
// Set the default selected item, if desired.
ColorList.SelectedIndex = 0;
}
}
void Selection_Change(Object sender, EventArgs e)
{
// Set the background color for days in the Calendar control
// based on the value selected by the user from the
// DropDownList control.
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
}
bytes[] buffer = UnicodeEncoding.UTF8.GetBytes(string something); //for converting to UTF then get its bytes
bytes[] buffer = ASCIIEncoding.ASCII.GetBytes(string something); //for converting to ascii then get its bytes
Your alternatives are to override the toString()
method of your object to output its contents in a way that you like, or to use reflection to inspect the object (in a way similar to what debuggers do).
The advantage of using reflection is that you won't need to modify your individual objects to be "analysable", but there is added complexity and if you need nested object support you'll have to write that.
This code will list the fields and their values for an Object
"o"
Field[] fields = o.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
System.out.println(fields[i].getName() + " - " + fields[i].get(o));
}
For what it's worth, I got inspired by the other answers and wrote a small utility which calls the platform specific APIs to be used universally from either Node.js or a browser:
/**
* Encode a string of text as base64
*
* @param data The string of text.
* @returns The base64 encoded string.
*/
function encodeBase64(data: string) {
if (typeof btoa === "function") {
return btoa(data);
} else if (typeof Buffer === "function") {
return Buffer.from(data, "utf-8").toString("base64");
} else {
throw new Error("Failed to determine the platform specific encoder");
}
}
/**
* Decode a string of base64 as text
*
* @param data The string of base64 encoded text
* @returns The decoded text.
*/
function decodeBase64(data: string) {
if (typeof atob === "function") {
return atob(data);
} else if (typeof Buffer === "function") {
return Buffer.from(data, "base64").toString("utf-8");
} else {
throw new Error("Failed to determine the platform specific decoder");
}
}
_x000D_
Intellij 2021.3.2 Basic Shortcuts
I think that is easier than this.
You can change 'tabs' at left side of the wizard (General, Files, Options)
Here is a version with configurable parameters that you can set programmatically:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8" />
<xsl:param name="delim" select="','" />
<xsl:param name="quote" select="'"'" />
<xsl:param name="break" select="'
'" />
<xsl:template match="/">
<xsl:apply-templates select="projects/project" />
</xsl:template>
<xsl:template match="project">
<xsl:apply-templates />
<xsl:if test="following-sibling::*">
<xsl:value-of select="$break" />
</xsl:if>
</xsl:template>
<xsl:template match="*">
<!-- remove normalize-space() if you want keep white-space at it is -->
<xsl:value-of select="concat($quote, normalize-space(), $quote)" />
<xsl:if test="following-sibling::*">
<xsl:value-of select="$delim" />
</xsl:if>
</xsl:template>
<xsl:template match="text()" />
</xsl:stylesheet>
Addition to the above answer by @djechlin
d = '1394104654000';
new Date(parseInt(d));
converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.
If you are embracing the type hints in Python 3.6, you can do it like this:
def from_json(data, cls):
annotations: dict = cls.__annotations__ if hasattr(cls, '__annotations__') else None
if issubclass(cls, List):
list_type = cls.__args__[0]
instance: list = list()
for value in data:
instance.append(from_json(value, list_type))
return instance
elif issubclass(cls, Dict):
key_type = cls.__args__[0]
val_type = cls.__args__[1]
instance: dict = dict()
for key, value in data.items():
instance.update(from_json(key, key_type), from_json(value, val_type))
return instance
else:
instance : cls = cls()
for name, value in data.items():
field_type = annotations.get(name)
if inspect.isclass(field_type) and isinstance(value, (dict, tuple, list, set, frozenset)):
setattr(instance, name, from_json(value, field_type))
else:
setattr(instance, name, value)
return instance
Which then allows you do instantiate typed objects like this:
class Bar:
value : int
class Foo:
x : int
bar : List[Bar]
obj : Foo = from_json(json.loads('{"x": 123, "bar":[{"value": 3}, {"value": 2}, {"value": 1}]}'), Foo)
print(obj.x)
print(obj.bar[2].value)
This syntax requires Python 3.6 though and does not cover all cases - for example, support for typing.Any... But at least it does not pollute the classes that need to be deserialized with extra init/tojson methods.
As a general way to handle error in a loop like your sample code, I would rather use:
on error resume next
for each...
'do something that might raise an error, then
if err.number <> 0 then
...
end if
next ....
The way I cam across this question was when I tried doing something similar where I was defining a function and it was being called with the array like others pointed out
You could do something like this however for this scenarios its less elegant compared to Sven's method.
sapply(a, function(x) afunc(x))
afunc<-function(a){
if (a>0){
a/sum(a)
}
else 1
}
The same as David's, but without attr()
$('<input>', {
type: 'hidden',
id: 'foo',
name: 'foo',
value: 'bar'
}).appendTo('form');
The problem is the way you are using it in code. Just try the below code
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource =
new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
this.Background = myBrush;
}
}
You can find more details regarding this in
http://msdn.microsoft.com/en-us/library/aa970069.aspx
I had a same kind of issue starting Genymotion on Ubuntu 16.04 and solved it in this way https://medium.com/@avanvitharana/genymotion-on-ubuntu-16-04-cb8ef8fc70e9#.6y0bgmmjb
If you want to change in AppServiceProvider then you need to define the length of email field in migration. just replace the first line of code to the second line.
create_users_table
$table->string('email')->unique();
$table->string('email', 50)->unique();
create_password_resets_table
$table->string('email')->index();
$table->string('email', 50)->index();
After successfully changes you can run the migration.
Note: first you have to delete (if you have) users table, password_resets table from the database and delete users and password_resets entries from migration table.
^((?!hede).)*$
is an elegant solution, except since it consumes characters you won't be able to combine it with other criteria. For instance, say you wanted to check for the non-presence of "hede" and the presence of "haha." This solution would work because it won't consume characters:
^(?!.*\bhede\b)(?=.*\bhaha\b)
Try this, you can change for even when you want. this example use jQuery.
$('#iframe').live('mousemove', function (event) {
var theFrame = $(this, parent.document.body);
this.height($(document.body).height() - 350);
});
Change 2 to 1 as the first parameter in the splice call when removing the element:
var tmp = playlist.splice(1, 1);
playlist.splice(2, 0, tmp[0]);
It is bad practice to throw Exception, as that requires anyone who calls your constructor to catch Exception which is a bad practice.
It is a good idea to have a constructor (or any method) throw an exception, generally speaking IllegalArgumentException, which is unchecked, and thus the compiler doesn't force you to catch it.
You should throw checked exceptions (things that extend from Exception, but not RuntimeException) if you want the caller to catch it.
I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:
Yourhostname here -vvvvvvvvvv
s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state
When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.
The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.
You are clearly sending a certificate. The server is clearly rejecting it.
The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.
June 2014:
This is the configuration I used and it working fine after banging my head on the wall for some days. I use Express 3.4 (I think is the same for Express 4.0)
var privateKey = fs.readFileSync('helpers/sslcert/key.pem', 'utf8');
var certificate = fs.readFileSync('helpers/sslcert/csr.pem', 'utf8');
files = ["COMODORSADomainValidationSecureServerCA.crt",
"COMODORSAAddTrustCA.crt",
"AddTrustExternalCARoot.crt"
];
ca = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
_results.push(fs.readFileSync("helpers/sslcert/" + file));
}
return _results;
})();
var credentials = {ca:ca, key: privateKey, cert: certificate};
// process.env.PORT : Heroku Config environment
var port = process.env.PORT || 4000;
var app = express();
var server = http.createServer(app).listen(port, function() {
console.log('Express HTTP server listening on port ' + server.address().port);
});
https.createServer(credentials, app).listen(3000, function() {
console.log('Express HTTPS server listening on port ' + server.address().port);
});
// redirect all http requests to https
app.use(function(req, res, next) {
if(!req.secure) {
return res.redirect(['https://mydomain.com', req.url].join(''));
}
next();
});
Then I redirected the 80 and 443 ports:
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 4000
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 3000
As you can see after checking my certifications I have 4 [0,1,2,3]:
openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "
ubuntu@ip-172-31-5-134:~$ openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify error:num=19:self signed certificate in certificate chain
verify return:0
0 s:/OU=Domain Control Validated/OU=PositiveSSL/CN=mydomain.com
i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
1 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
2 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
3 s:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
Protocol : TLSv1.1
Cipher : AES256-SHA
Session-ID: 8FDEAEE92ED20742.....3E7D80F93226142DD
Session-ID-ctx:
Master-Key: C9E4AB966E41A85EEB7....4D73C67088E1503C52A9353C8584E94
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 300 (seconds)
TLS session ticket:
0000 - 7c c8 36 80 95 4d 4c 47-d8 e3 ca 2e 70 a5 8f ac |.6..MLG....p...
0010 - 90 bd 4a 26 ef f7 d6 bc-4a b3 dd 8f f6 13 53 e9 ..J&..........S.
0020 - f7 49 c6 48 44 26 8d ab-a8 72 29 c8 15 73 f5 79 .I.HD&.......s.y
0030 - ca 79 6a ed f6 b1 7f 8a-d2 68 0a 52 03 c5 84 32 .yj........R...2
0040 - be c5 c8 12 d8 f4 36 fa-28 4f 0e 00 eb d1 04 ce ........(.......
0050 - a7 2b d2 73 df a1 8b 83-23 a6 f7 ef 6e 9e c4 4c .+.s...........L
0060 - 50 22 60 e8 93 cc d8 ee-42 22 56 a7 10 7b db 1e P"`.....B.V..{..
0070 - 0a ad 4a 91 a4 68 7a b0-9e 34 01 ec b8 7b b2 2f ..J......4...{./
0080 - e8 33 f5 a9 48 11 36 f8-69 a6 7a a6 22 52 b1 da .3..H...i....R..
0090 - 51 18 ed c4 d9 3d c4 cc-5b d7 ff 92 4e 91 02 9e .....=......N...
Start Time: 140...549
Timeout : 300 (sec)
Verify return code: 19 (self signed certificate in certificate chain)
Good luck! PD: if u want more answers please check: http://www.benjiegillam.com/2012/06/node-dot-js-ssl-certificate-chain/
To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length
.
double sum = 0.0;
int length = 0;
for( double number : numbers ) {
sum += number;
length++;
}
return sum/length;
Variance is calculated similarly. Standard deviation is simply the square root of the variance:
double stddev = Math.sqrt( variance );
const el = document.getElementById("editable");
el.focus()
let char = 1, sel; // character at which to place caret
if (document.selection) {
sel = document.selection.createRange();
sel.moveStart('character', char);
sel.select();
}
else {
sel = window.getSelection();
sel.collapse(el.lastChild, char);
}
If you want to run the program to see what it does without infecting your computer, use with a virtual machine like VMWare or Microsoft VPC, or a program that can sandbox the program like SandboxIE
PHP 7.4+; with the null coalescing assignment operator
$var ??= '';
PHP 7.0+; with the null coalescing operator
$var = $var ?? '';
PHP 5.3+; with the ternary operator shorthand
isset($var) ?: $var = '';
Or for all/older versions with isset:
$var = isset($var) ? $var : '';
or
!isset($var) && $var = '';
Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.
import React from 'react';
import { Link } from 'react-router';
export default class Nav extends React.Component {
render() {
return (
<nav className="Nav">
<div className="Nav__container">
<Link to="/" className="Nav__brand">
<img src="logo.svg" className="Nav__logo" />
</Link>
<div className="Nav__right">
<ul className="Nav__item-wrapper">
<li className="Nav__item">
<Link className="Nav__link" to="/path1">Link 1</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path2">Link 2</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path3">Link 3</Link>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<div>
<Nav />
<Switch>
<Route exactly component={Landing} pattern="/" />
<Route exactly component={Page1} pattern="/path1" />
<Route exactly component={Page2} pattern="/path2" />
<Route exactly component={Page3} pattern="/path3" />
<Route component={Page404} />
</Switch>
</div>
</Router>
</div>
);
}
}
Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar
A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
const NavRoute = ({exact, path, component: Component}) => (
<Route exact={exact} path={path} render={(props) => (
<div>
<Header/>
<Component {...props}/>
</div>
)}/>
)
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<Switch>
<NavRoute exactly component={Landing} pattern="/" />
<Route exactly component={Login} pattern="/login" />
<NavRoute exactly component={Page1} pattern="/path1" />
<NavRoute exactly component={Page2} pattern="/path2" />
<NavRoute component={Page404} />
</Switch>
</Router>
</div>
);
}
}
I believe this regex handles more situations:
/(\b\S+\b)\s+\b\1\b/
A good selection of test strings can be found here: http://callumacrae.github.com/regex-tuesday/challenge1.html
This is a classic self-join, try the following:
SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
emp e, emp m
WHERE e.mgr = m.empno
And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax:
SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
emp e, emp m
WHERE e.mgr = m.empno(+)
Or in ANSI SQL syntax:
SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
emp e
LEFT OUTER JOIN emp m
ON e.mgr = m.empno
You're calling e.nextElement()
twice inside your loop when you're only guaranteed that you can call it once without an exception. Rewrite the loop like so:
while(e.hasMoreElements()){
String param = e.nextElement();
System.out.println(param);
}
In C, unlike say C++, you would need a format specifier that states the datatype of the variable you want to print-in this case %d as the data type is an integer . Try printf("%d",addNumbers(a,b));
I know that its late but it might be helpful for people who need to change the Bundle Identifier of the app. In the finder go to the project folder:
the project file --> Right click on your project file '*.xcodeproj'
--> choose 'Show Package Contents'
--> Double click to open 'project.pbxproj' file
--> find 'productName = NAME_YOU_WANT_TO_CHANGE' in the
'/* Begin PBXNativeTarget section */'
The ${PRODUCT_NAME:rfc1034identifier} variable will be replaced with the name you have entered and new Bundle Identifier will be updated to what you need it to be.
It's VBA. VBA means Visual Basic for Applications, and it is used for macros on Office documents. It doesn't have access to VB.NET features, so it's more like a modified version of VB6, with add-ons to be able to work on the document (like Worksheet in VBA for Excel).
Here is more functional example with some ES6 features:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
You can't modify the default dialogue for onbeforeunload
, so your best bet may be to work with it.
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
onbeforeunload
is called, it will take the return value of the handler as window.event.returnValue
.false
is parsed as a string, the dialogue box will fire, which will then pass an appropriate true
/false
.The result is, there doesn't seem to be a way of assigning false
to onbeforeunload
to prevent it from the default dialogue.
Additional notes on jQuery:
onbeforeunload
events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.jQuery doesn't have a shortcut for onbeforeunload
so you'd have to use the generic bind
syntax.
$(window).bind('beforeunload', function() {} );
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)
A Modern Solution
Most of the proposed solutions here will break with nested tables or other elements inside your td elements. I frequently use other elements inside my tables, but only want to export the topmost table. I took some of the code found here from Calumah and added in some modern vanilla ES6 JS.
Using textContent is a better solution than innerText as innerText will return any HTML inside your td elements. However, even textContent will return the text from nested elements. An even better solution is to use custom data attributes on your td and pull the values for you CSV from there.
Happy coding!
function downloadAsCSV(tableEle, separator = ','){
let csvRows = []
//only get direct children of the table in question (thead, tbody)
Array.from(tableEle.children).forEach(function(node){
//using scope to only get direct tr of node
node.querySelectorAll(':scope > tr').forEach(function(tr){
let csvLine = []
//again scope to only get direct children
tr.querySelectorAll(':scope > td').forEach(function(td){
//clone as to not remove anything from original
let copytd = td.cloneNode(true)
let data
if(copytd.dataset.val) data = copytd.dataset.val.replace(/(\r\n|\n|\r)/gm, '')
else {
Array.from(copytd.children).forEach(function(remove){
//remove nested elements before getting text
remove.parentNode.removeChild(remove)
})
data = copytd.textContent.replace(/(\r\n|\n|\r)/gm, '')
}
data = data.replace(/(\s\s)/gm, ' ').replace(/"/g, '""')
csvLine.push('"'+data+'"')
})
csvRows.push(csvLine.join(separator))
})
})
var a = document.createElement("a")
a.style = "display: none; visibility: hidden" //safari needs visibility hidden
a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvRows.join('\n'))
a.download = 'testfile.csv'
document.body.appendChild(a)
a.click()
a.remove()
}
Edit: cloneNode() updated to cloneNode(true) to get insides
To facilitate svg editing you can use an intermediate function:
function getNode(n, v) {
n = document.createElementNS("http://www.w3.org/2000/svg", n);
for (var p in v)
n.setAttributeNS(null, p, v[p]);
return n
}
Now you can write:
svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );
Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):
function getNode(n, v) {_x000D_
n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
for (var p in v)_x000D_
n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
If you're using Rails 3+, remove the gem from the Gemfile and run bundle install
.
If you're using Rails 2, hopefully you've put the declaration in config/environment.rb. If so, removing it from there and running rake gems:install
should do the trick.
A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr
:
>>> print(chr(92))
\
Xampp and Mamp Users
Had the same error while importing a database (after emptying it) trough MySQL. I found that i had a tablename.ibd
file left while all others were deleted.
I deleted it manually from mysql/data/database_name
and the error was gone.
I wrote this function:
public static String encode(@NonNull String uriString) {
if (TextUtils.isEmpty(uriString)) {
Assert.fail("Uri string cannot be empty!");
return uriString;
}
// getQueryParameterNames is not exist then cannot iterate on queries
if (Build.VERSION.SDK_INT < 11) {
return uriString;
}
// Check if uri has valid characters
// See https://tools.ietf.org/html/rfc3986
Pattern allowedUrlCharacters = Pattern.compile("([A-Za-z0-9_.~:/?\\#\\[\\]@!$&'()*+,;" +
"=-]|%[0-9a-fA-F]{2})+");
Matcher matcher = allowedUrlCharacters.matcher(uriString);
String validUri = null;
if (matcher.find()) {
validUri = matcher.group();
}
if (TextUtils.isEmpty(validUri) || uriString.length() == validUri.length()) {
return uriString;
}
// The uriString is not encoded. Then recreate the uri and encode it this time
Uri uri = Uri.parse(uriString);
Uri.Builder uriBuilder = new Uri.Builder()
.scheme(uri.getScheme())
.authority(uri.getAuthority());
for (String path : uri.getPathSegments()) {
uriBuilder.appendPath(path);
}
for (String key : uri.getQueryParameterNames()) {
uriBuilder.appendQueryParameter(key, uri.getQueryParameter(key));
}
String correctUrl = uriBuilder.build().toString();
return correctUrl;
}
Following document published by W3C also describes the differences between SOAP 1.1 and 1.2:
There is obviously another process listening on the port. You might find out that process by using the following command:
$ lsof -i :8000
or change your tornado app's port. tornado's error info not Explicitly on this.
Here is the entire script with an AJAX call to target a single list within a page with multiple lists. None of the other stuff above worked for me until I used the "id" attribute even though my attribute name is "ItemKey". By using the debugger
I was able to see that the selected option had attributes: with a map to the JQuery "id" and the value.
<html>
<head>
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<select id="List1"></select>
<select id="List2">
<option id="40000">List item #1</option>
<option id="27888">List item #2</option>
</select>
<div></div>
</body>
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#List1');
//request the JSON data and parse into the select element
$.ajax({
url: 'list.json',
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.List, function(key, val){
$select.append('<option id="' + val.ItemKey + '">' + val.ItemText + '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});
$( "#List1" ).change(function () {
var optionSelected = $('#List1 option:selected').attr('id');
$( "div" ).text( optionSelected );
});
</script>
</html>
Here is the JSON File to create...
{
"List":[
{
"Sort":1,
"parentID":0,
"ItemKey":100,
"ItemText":"ListItem-#1"
},
{
"Sort":2,
"parentID":0,
"ItemKey":200,
"ItemText":"ListItem-#2"
},
{
"Sort":3,
"parentID":0,
"ItemKey":300,
"ItemText":"ListItem-#3"
},
{
"Sort":4,
"parentID":0,
"ItemKey":400,
"ItemText":"ListItem-#4"
}
]
}
Hope this helps, thank you all above for getting me this far.
this is how I do it
JAVASCRIPT:
var module = angular.module('yourModuleName', ['ui.router']);
module.run( ['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
HTML:
<pre id="uiRouterInfo">
$state = {{$state.current.name}}
$stateParams = {{$stateParams}}
$state full url = {{ $state.$current.url.source }}
</pre>
EXAMPLE
You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.
Here is a lazier way to do that:
function jump(h){
var url = location.href; //Save down the URL without hash.
location.href = "#"+h; //Go to the target element.
history.replaceState(null,null,url); //Don't like hashes. Changing it back.
}
This uses replaceState
to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:
function jump(h){
var top = document.getElementById(h).offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there directly or some transition
}?
Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/
You can also use .scrollIntoView
:
document.getElementById(h).scrollIntoView(); //Even IE6 supports this
(Well I lied. It's not complicated at all.)
This is how I do:
$('#my_input').select2('destroy').val('').select2();
The actual way to end a program, is to call
raise SystemExit
It's what sys.exit
does, anyway.
A plain SystemExit
, or with None
as a single argument, sets the process' exit code to zero. Any non-integer exception value (raise SystemExit("some message")
) prints the exception value to sys.stderr
and sets the exit code to 1. An integer value sets the process' exit code to the value:
$ python -c "raise SystemExit(4)"; echo $?
4
There's yet another way to do it using Shared Connections, ie: somebody initiates the connection, using a password, and every subsequent connection will multiplex over the same channel, negating the need for re-authentication. ( And its faster too )
# ~/.ssh/config
ControlMaster auto
ControlPath ~/.ssh/pool/%r@%h
then you just have to log in, and as long as you are logged in, the bash script will be able to open ssh connections.
You can then stop your script from working when somebody has not already opened the channel by:
ssh ... -o KbdInteractiveAuthentication=no ....
Here's a one-liner using LINQ and avoiding any run-time evaluation of select strings:
someDataTable.Rows.Cast<DataRow>().Where(
r => r.ItemArray[0] == someValue).ToList().ForEach(r => r.Delete());
I had an error where my project was compiled as x64 project. and I've used a Library that was compiled as x86.
I've recompiled the library as x64 and it solved it.
You should need to convert your PHP array to javascript array using PHP syntax json_encode. json_encode convert PHP array to JSON string
Single Dimension PHP array to javascript array
<?php
var $itemsarray= array("Apple", "Bear", "Cat", "Dog");
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[2]); // Output: Bear
// OR
alert(items[0]); // Output: Apple
</script>
Multi Dimension PHP array to javascript array
<?php
var $itemsarray= array(
array('name'='Apple', 'price'=>'12345'),
array('name'='Bear', 'price'=>'13344'),
array('name'='Potato', 'price'=>'00440')
);
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[1][name]); // Output: Bear
// OR
alert(items[0][price]); // Output: Apple
</script>
For more detail, you can also check php array to javascript array
Sending an HTTP POST request on iOS (Objective c):
-(NSString *)postexample{
// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
//RESPONDE DATA
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if([responseCode statusCode] != 200){
NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
return nil;
}
//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}