I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
Typically this is bad practice. Since it is possible to call addEdge before addNode and have a NullPointerException (NPE) thrown, addEdge should check if the result is null and throw a more descriptive Exception. In my opinion, the only time it is acceptable not to check for nulls is when you expect the result to never be null, in which case, an NPE is plenty descriptive.
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.
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();
Your database table structure should have a books table and a chapters table with columns like:
books
chapters
Then to reduce the number of queries use a join table in your search query.
Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID
before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.
You have to nest the requests:
$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ obj = name; // sID is only now available! sID = obj.id; console.log(sID); });
name.id
is sufficient unless you really need the other variables outside the function.$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ // We don't need sID or obj here - name.id is sufficient console.log(name.id); doSecondRequest(name.id); }); /// TODO Choose a better name function doSecondRequest(sID) { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){ console.log(stats); }); }
Hapy New Year :)
It's canonical to use references for this; precedence: ostream::operator<<
. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
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.
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.
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);
No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO ---- Assign Role To users ------- CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username' ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO
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');
You can use Jquery's on method and listen for the scroll
event.
The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
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:
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -
eventually decided to use CLINT as an answer that was given there by great and smart people
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
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.
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
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
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
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);
I can spot a few different problems with this. However, in the interest of time, try this chunk of code instead:
<?php require 'db.php'; ?> <?php if (isset($_POST['search'])) { $limit = $_POST['limit']; $country = $_POST['country']; $state = $_POST['state']; $city = $_POST['city']; $data = mysqli_query( $link, "SELECT * FROM proxies WHERE country = '{$country}' AND state = '{$state}' AND city = '{$city}' LIMIT {$limit}" ); while ($assoc = mysqli_fetch_assoc($data)) { $proxy = $assoc['proxy']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Sock5Proxies</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <link href="./style.css" rel="stylesheet" type="text/css" /> <link href="./buttons.css" rel="stylesheet" type="text/css" /> </head> <body> <center> <h1>Sock5Proxies</h1> </center> <div id="wrapper"> <div id="header"> <ul id="nav"> <li class="active"><a href="index.html"><span></span>Home</a></li> <li><a href="leads.html"><span></span>Leads</a></li> <li><a href="payout.php"><span></span>Pay out</a></li> <li><a href="contact.html"><span></span>Contact</a></li> <li><a href="logout.php"><span></span>Logout</a></li> </ul> </div> <div id="content"> <div id="center"> <table cellpadding="0" cellspacing="0" style="width:690px"> <thead> <tr> <th width="75" class="first">Proxy</th> <th width="50" class="last">Status</th> </tr> </thead> <tbody> <tr class="rowB"> <td class="first"> <?php echo $proxy ?> </td> <td class="last">Check</td> </tr> </tbody> </table> </div> </div> <div id="footer"></div> <span id="about">Version 1.0</span> </div> </body> </html> <?php } } ?> <html> <form action="" method="POST"> <input type="text" name="limit" placeholder="10" /><br> <input type="text" name="country" placeholder="Country" /><br> <input type="text" name="state" placeholder="State" /><br> <input type="text" name="city" placeholder="City" /><br> <input type="submit" name="search" value="Search" /><br> </form> </html>
If the error is
Error: Node Sass version 5.0.0 is incompatible with ^4.0.0
Step1: stop the server
Step2: run commands are npm uninstall node-sass
Step3: check node-sass in package.json
if node-sass is available in the file then again run Step2.
Step4: npm install [email protected]
<=== run command
Step5: wait until the command successfully runs.
Step6: start-server using npm start
I had this error message because I was trying to import a component in a new module instead of importing the other module where my component was declared.
Removing the component import from my new module and importing the other module solved it for me.
To fix this issue simply upgrade react-scripts package (check latest version with npm info react-scripts version
):
"react-scripts": "^3.x.x"
with "react-scripts": "^3.4.1"
(or the latest available version)npm install
or yarn install
Some people reported that this issue was caused by running npm audit fix
(avoid it!).
According to your package.json, you're using Angular 8.3, but you've imported angular/cdk v9. You can downgrade your angular/cdk version or you can upgrade your Angular version to v9 by running:
ng update @angular/core @angular/cli
That will update your local angular version to 9. Then, just to sync material, run:
ng update @angular/material
I had this error when i deleted several components while the server was on(after running the ng serve command). Although i deleted the references from the routes component and module, it didnt solve the problem. Then i followed these steps:
If you are using Netbeans older version, you have to make changes in maven to use https over http
Open C:\Program Files\NetBeans8.0.2\java\maven\conf\settings.xml and paste below code in between mirrors tag
<mirror>
<id>maven-mirror</id>
<name>Maven Mirror</name>
<url>https://repo.maven.apache.org/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>
It will force maven to use https://repo.maven.apache.org/maven2 url.
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)
This problem occurred because there is global installs of create-react-app
are no longer supported. For solving this problem, you should uninstall and remove completely create-react-app
from your system, so run these command respectively:
npm uninstall -g create-react-app
or
yarn global remove create-react-app
Then please check if the create-react-app exists or not with this command
which create-react-app
If it returns any correct path like a
/c/Users/Dell/AppData/Local/Yarn/bin/create-react-app
Then run this command to remove create-react-app
globally
rm -rf /c/Users/Dell/AppData/Local/Yarn/bin/create-react-app
Now you can create a new react app with one of these commands:
npx create-react-app my-app
npm init react-app my-app
yarn create react-app my-app
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
Intelephense 1.3 added undefined type, function, constant, class constant, method, and property diagnostics, where previously in 1.2 there was only undefined variable diagnostics.
Some frameworks are written in a way that provide convenient shortcuts for the user but make it difficult for static analysis engines to discover symbols that are available at runtime.
Stub generators like https://github.com/barryvdh/laravel-ide-helper help fill the gap here and using this with Laravel will take care of many of the false diagnostics by providing concrete definitions of symbols that can be easily discovered.
Still, PHP is a very flexible language and there may be other instances of false undefined symbols depending on how code is written. For this reason, since 1.3.3, intelephense has config options to enable/disable each category of undefined symbol to suit the workspace and coding style.
These options are:
intelephense.diagnostics.undefinedTypes
intelephense.diagnostics.undefinedFunctions
intelephense.diagnostics.undefinedConstants
intelephense.diagnostics.undefinedClassConstants
intelephense.diagnostics.undefinedMethods
intelephense.diagnostics.undefinedProperties
intelephense.diagnostics.undefinedVariables
Setting all of these to false except intelephense.diagnostics.undefinedVariables
will give version 1.2 behaviour. See the VSCode settings UI and search for intelephense
.
npm
decided to add a new command:
npm fund
that will provide more visibility to npm users on what dependencies are actively looking for ways to fund their work.
npm install
will also show a single message at the end in order to let user aware that dependencies are looking for funding, it looks like this:
$ npm install
packages are looking for funding.
run `npm fund` for details.
Running npm fund <package>
will open the url listed for that given package right in your browser.
For me, it was the StackOverFlow Exception because of recursive code.
I got same problem.
"error Invalid regular expression: /(.\fixtures\.|node_modules[\]react[\]dist[\].|website\node_modules\.|heapCapture\bundle.js|.\tests\.)$/: Unterminated character class."
Change the regular expression in \node_modules\metro-config\src\defaults\blacklist.js
From
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
To
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
This change resolved my error.
Working on android studio: 3.6.3 and gradle version:
classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"
Adding this line in
gradle.properties file
org.gradle.jvmargs=-Xmx512m
I was also having this same error but hopefully after spending 1 day on this error i have got this solution and it got started perfectly and i also hope this works for you guys also...
var startColabHandler = function startColabHandler(interval = 60000, enableConnectButton = false) {
console.log("colabHandler - configure - start: " + new Date());
var colabClick = function colabClick() {
console.log("colabHandler - click - start: " + new Date());
if (enableConnectButton === true) {
var button1 = document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect");
if (button1) {
button1.click()
}
}
button2 = document.querySelector("html body colab-dialog.yes-no-dialog paper-dialog div.buttons paper-button#ok");
if (button2) {
button2.click()
}
console.log("colabHandler - click - end: " + new Date());
};
var intervalId = setInterval(colabClick, interval);
window.stopColabHandler = function stopColabHandler() {
console.log("colabHandler - stop - start: " + new Date());
clearInterval(intervalId);
console.log("colabHandler - stop - start: " + new Date());
};
console.log("colabHandler - configure - end: " + new Date());
};
With out typescript
error
const formData = new FormData();
Object.keys(newCategory).map((k,i)=>{
var d =Object.values(newCategory)[i];
formData.append(k,d)
})
complementing the following comment
For those who use redux:
class AllowanceClass extends Component{
...
render() {
const classes = this.props.classes;
...
}
}
const COMAllowanceClass = (props) =>
{
const classes = useStyles();
return (<AllowanceClass classes={classes} {...props} />);
};
const mapStateToProps = ({ InfoReducer }) => ({
token: InfoReducer.token,
user: InfoReducer.user,
error: InfoReducer.error
});
export default connect(mapStateToProps, { actions })(COMAllowanceClass);
Don't Use Any, Use Generics
// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];
// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];
// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
obj[key];
Bad - the reason for the error is the object
type is just an empty object by default. Therefore it isn't possible to use a string
type to index {}
.
Better - the reason the error disappears is because now we are telling the compiler the obj
argument will be a collection of string/value (string/any
) pairs. However, we are using the any
type, so we can do better.
Best - T
extends empty object. U
extends the keys of T
. Therefore U
will always exist on T
, therefore it can be used as a look up value.
Here is a full example:
I have switched the order of the generics (U extends keyof T
now comes before T extends object
) to highlight that order of generics is not important and you should select an order that makes the most sense for your function.
const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) =>
obj[key];
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
const getUserName = getKeyValue<keyof User, User>("name")(user);
// => 'John Smith'
const getKeyValue = <T, K extends keyof T>(obj: T, key: K): T[K] => obj[key];
Instead of converting the class to a function, an easy step would be to create a function to include the jsx for the component which uses the 'classes', in your case the <container></container>
and then call this function inside the return of the class render() as a tag. This way you are moving out the hook to a function from the class. It worked perfectly for me. In my case it was a <table>
which i moved to a function- TableStmt outside and called this function inside the render as <TableStmt/>
Simply add below maven jar version in properties tag in pom.xml, <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
Then follow below steps,
Step 1: mvn clean
Step 2 : update project
Problem solved for me! You should also try this :)
Use const App instead of const app
The solution is also given by react, they advice you use useCallback
which will return a memoize version of your function :
The 'fetchBusinesses' function makes the dependencies of useEffect Hook (at line NN) change on every render. To fix this, wrap the 'fetchBusinesses' definition into its own useCallback() Hook react-hooks/exhaustive-deps
useCallback
is simple to use as it has the same signature as useEffect
the difference is that useCallback returns a function.
It would look like this :
const fetchBusinesses = useCallback( () => {
return fetch("theURL", {method: "GET"}
)
.then(() => { /* some stuff */ })
.catch(() => { /* some error handling */ })
}, [/* deps */])
// We have a first effect thant uses fetchBusinesses
useEffect(() => {
// do things and then fetchBusinesses
fetchBusinesses();
}, [fetchBusinesses]);
// We can have many effect thant uses fetchBusinesses
useEffect(() => {
// do other things and then fetchBusinesses
fetchBusinesses();
}, [fetchBusinesses]);
I had the same problem by using library wifi
but when i changed my network it worked perfectly.
Change your network connection
For npm
npm install --save core-js@^3
for yarn
yarn add core-js@^3
possibility of this error is also the wrong path,check once
export ANDROID_HOME=/Users/microrentindia/Library/Android/sdk/
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Change all "es6" and "es7" to "es" in your polyfills.ts and polyfills.ts
In Reactive Form, there are 2 primary solutions to update value(s) of form field(s).
Initialize Model Structure in Constructor:
this.newForm = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],
lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]]
});
If you want to update all fields of form:
this.newForm.setValue({
firstName: 'abc',
lastName: 'def'
});
If you want to update specific field of form:
this.newForm.controls.firstName.setValue('abc');
Note: It’s mandatory to provide complete model structure for all form field controls within the FormGroup. If you miss any property or subset collections, then it will throw an exception.
If you want to update some/ specific fields of form:
this.newForm.patchValue({
firstName: 'abc'
});
Note: It’s not mandatory to provide model structure for all/ any form field controls within the FormGroup. If you miss any property or subset collections, then it will not throw any exception.
You must link an event in your onClick. Additionally, the click function must receive the event. See the example
export default function Component(props) {
function clickEvent (event, variable){
console.log(variable);
}
return (
<div>
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={e => clickEvent(e, 10)}
>
</div>
)
}
After upgrading react-native, you may have stale dependencies. The steps below should fix it.
cd ios
pod deintegrate && pod install
react-native run-ios
Hope this helps, I did this after upgrading to react-native 0.61
Since the cleanup is not dependent on the username
, you could put the cleanup in a separate useEffect
that is given an empty array as second argument.
Example
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
const [name, setName] = useState("");_x000D_
const [username, setUsername] = useState("");_x000D_
_x000D_
useEffect(_x000D_
() => {_x000D_
console.log("effect");_x000D_
},_x000D_
[username]_x000D_
);_x000D_
_x000D_
useEffect(() => {_x000D_
return () => {_x000D_
console.log("cleaned up");_x000D_
};_x000D_
}, []);_x000D_
_x000D_
const handleName = e => {_x000D_
const { value } = e.target;_x000D_
_x000D_
setName(value);_x000D_
};_x000D_
_x000D_
const handleUsername = e => {_x000D_
const { value } = e.target;_x000D_
_x000D_
setUsername(value);_x000D_
};_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<div>_x000D_
<input value={name} onChange={handleName} />_x000D_
<input value={username} onChange={handleUsername} />_x000D_
</div>_x000D_
<div>_x000D_
<div>_x000D_
<span>{name}</span>_x000D_
</div>_x000D_
<div>_x000D_
<span>{username}</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
function App() {_x000D_
const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
useEffect(() => {_x000D_
setTimeout(() => {_x000D_
setShouldRender(false);_x000D_
}, 5000);_x000D_
}, []);_x000D_
_x000D_
return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
I use jupyter notebooks daily and had never experienced this issue before... until today. I had the notebook open all day but it wasn't running anything and then for no apparent reason stopped auto-saving with the '_xsrf' argument missing from POST
error message in the top right. FYI - this is a python3 notebook.
I don't know the cause of this problem but I have recently upgraded my python3 version to 3.7.2 and upgraded all of my site-packages to their latest version as of a few days ago which could possibly be the cause.
As for a solution, as suggested in the comment by @AlexK, I opened the same notebook in a new window (different browser in fact), using
jupyter notebook list
in the terminal to get the URL with login token.
This resulted in me having the notebook open and savable again but the information I had entered since the last successful auto-save was missing. Thankfully, my broken instance was still open and working apart from saving so I was able to simply copy and paste the information across then hit save. So, keep the broken instance open if you try this!
Another way to achieve this:
const [Name, setName] = useState({val:"", callback: null});_x000D_
React.useEffect(()=>{_x000D_
console.log(Name)_x000D_
const {callback} = Name;_x000D_
callback && callback();_x000D_
}, [Name]);_x000D_
setName({val:'foo', callback: ()=>setName({val: 'then bar'})})
_x000D_
You can append array of Data at the end of custom state:
const [vehicleData, setVehicleData] = React.useState<any[]>([]);
setVehicleData(old => [...old, ...newArrayData]);
For example, In below, you appear an example of axios:
useEffect(() => {
const fetchData = async () => {
const result = await axios(
{
url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
method: 'get',
}
);
setVehicleData(old => [...old, ...result.data.data]);
};
fetchData();
}, [page]);
When i use apt install python3-pip
, i get a lot of packages need install, but i donot need them. So, i DO like this:
apt update
apt-get install python3-setuptools
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
rm -f get-pip.py
I faced the same problem. Initially I deleted the .bash_profile but this is not the right way. After installing anaconda it is showing the instructions clearly for this problem. Please check the image for solution provided by Anaconda
gray = cv2.cvtColor(cv2.UMat(imgUMat), cv2.COLOR_RGB2GRAY)
UMat is a part of the Transparent API (TAPI) than help to write one code for the CPU and OpenCL implementations.
I'm late to the party.. :)
@aseferov answer works very well when the intention is to re-enter the entire object structure. However, if the target/goal is to update a specific field value in an Object, I believe the approach below is better.
situation:
const [infoData, setInfoData] = useState({
major: {
name: "John Doe",
age: "24",
sex: "M",
},
minor:{
id: 4,
collegeRegion: "south",
}
});
Updating a specific record will require making a recall to the previous State prevState
Here:
setInfoData((prevState) => ({
...prevState,
major: {
...prevState.major,
name: "Tan Long",
}
}));
perhaps
setInfoData((prevState) => ({
...prevState,
major: {
...prevState.major,
name: "Tan Long",
},
minor: {
...prevState.minor,
collegeRegion: "northEast"
}));
I hope this helps anyone trying to solve a similar problem.
Much like setState in Class components created by extending React.Component
or React.PureComponent
, the state update using the updater provided by useState
hook is also asynchronous, and will not be reflected immediately.
Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.
Even if you add a setTimeout
the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout
will still use the value from its previous closure and not the updated one.
setMovies(result);
console.log(movies) // movies here will not be updated
If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate
in class components since the setter returned by useState doesn't have a callback pattern
useEffect(() => {
// action on update of movies
}, [movies]);
As far as the syntax to update state is concerned, setMovies(result)
will replace the previous movies
value in the state with those available from the async request.
However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like
setMovies(prevMovies => ([...prevMovies, ...result]));
Open angular.json file and find budgets
keyword.
It should look like:
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
As you’ve probably guessed you can increase the maximumWarning
value to prevent this warning, i.e.:
"budgets": [
{
"type": "initial",
"maximumWarning": "4mb", <===
"maximumError": "5mb"
}
]
A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.
In our case budget is the limit for bundle sizes.
See also:
I had the same problem, all I did was to restart the command line and then navigate to the document folder rather than the user folder using the command '' cd documents '' . That should be all thats needed. Also ensure that the link is correct.
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");
}
}
showAlertDialog(BuildContext context) {
// set up the button
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () { },
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("My title"),
content: Text("This is my message."),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
showAlertDialog(BuildContext context) {
// set up the buttons
Widget cancelButton = FlatButton(
child: Text("Cancel"),
onPressed: () {},
);
Widget continueButton = FlatButton(
child: Text("Continue"),
onPressed: () {},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("AlertDialog"),
content: Text("Would you like to continue learning how to use Flutter alerts?"),
actions: [
cancelButton,
continueButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
showAlertDialog(BuildContext context) {
// set up the buttons
Widget remindButton = FlatButton(
child: Text("Remind me later"),
onPressed: () {},
);
Widget cancelButton = FlatButton(
child: Text("Cancel"),
onPressed: () {},
);
Widget launchButton = FlatButton(
child: Text("Launch missile"),
onPressed: () {},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Notice"),
content: Text("Launching this missile will destroy the entire universe. Is this what you intended to do?"),
actions: [
remindButton,
cancelButton,
launchButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
The onPressed
callback for the buttons in the examples above were empty, but you could add something like this:
Widget launchButton = FlatButton(
child: Text("Launch missile"),
onPressed: () {
Navigator.of(context).pop(); // dismiss dialog
launchMissile();
},
);
If you make the callback null
, then the button will be disabled.
onPressed: null,
Here is the code for main.dart
in case you weren't getting the functions above to run.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter'),
),
body: MyLayout()),
);
}
}
class MyLayout extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
child: Text('Show alert'),
onPressed: () {
showAlertDialog(context);
},
),
);
}
}
// replace this function with the examples above
showAlertDialog(BuildContext context) { ... }
The accepted answer shows the correct way to setState but it does not lead to a well functioning select box.
import React, { useState } from "react";
import ReactDOM from "react-dom";
const initialValue = { id: 0,value: " --- Select a State ---" };
const options = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const StateSelector = () => {
const [ selected, setSelected ] = useState(initialValue);
return (
<div>
<label>Select a State:</label>
<select value={selected}>
{selected === initialValue &&
<option disabled value={initialValue}>{initialValue.value}</option>}
{options.map((localState, index) => (
<option key={localState.id} value={localState}>
{localState.value}
</option>
))}
</select>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
This issue is due to incompatible of your plugin Verison and required Gradle version; they need to match with each other. I am sharing how my problem was solved.
Required Gradle version is here
more compatibility you can see from here. Android Plugin for Gradle Release Notes
if you have the android studio version 4.0.1
then your top level gradle file must be like this
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.2'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
and the gradle version should be
and your app gradle look like this
In order to use <Aux>
in your JSX, it needs to be a function that returns ReactElement<any> | null
. That's the definition of a function component.
However, it's currently defined as a function that returns React.ReactNode
, which is a much wider type. As React typings say:
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
Make sure the unwanted types are neutralized by wrapping the returned value into React Fragment (<></>
):
const aux: React.FC<AuxProps> = props =>
<>{props.children}</>;
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
$x = $y ?? 'dev'
is short hand for x = y if y is set, otherwise x = 'dev'
There is also
$x = $y =="SOMETHING" ? 10 : 20
meaning if y equals 'SOMETHING' then x = 10, otherwise x = 20
Fixed - My .eslintrc.js looks like this:
module.exports = {
root: true,
extends: '@react-native-community',
rules: {'prettier/prettier': ['error', {endOfLine: 'auto'}]},
};
axios signature for post is axios.post(url[, data[, config]])
. So you want to send params object within the third argument:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
There is a nice workaround to implement componentDidMount
and componentWillUnmount
with useEffect
.
Based on the documentation, useEffect
can return a "cleanup" function. this function will not be invoked on the first useEffect
call, only on subsequent calls.
Therefore, if we use the useEffect
hook with no dependencies at all, the hook will be called only when the component is mounted and the "cleanup" function is called when the component is unmounted.
useEffect(() => {
console.log('componentDidMount');
return () => {
console.log('componentWillUnmount');
};
}, []);
The cleanup return function call is invoked only when the component is unmounted.
Hope this helps.
Here's a custom hook that I use which I believe is more intuitive than using usePrevious
.
import { useRef, useEffect } from 'react'
// useTransition :: Array a => (a -> Void, a) -> Void
// |_______| |
// | |
// callback deps
//
// The useTransition hook is similar to the useEffect hook. It requires
// a callback function and an array of dependencies. Unlike the useEffect
// hook, the callback function is only called when the dependencies change.
// Hence, it's not called when the component mounts because there is no change
// in the dependencies. The callback function is supplied the previous array of
// dependencies which it can use to perform transition-based effects.
const useTransition = (callback, deps) => {
const func = useRef(null)
useEffect(() => {
func.current = callback
}, [callback])
const args = useRef(null)
useEffect(() => {
if (args.current !== null) func.current(...args.current)
args.current = deps
}, deps)
}
You'd use useTransition
as follows.
useTransition((prevRate, prevSendAmount, prevReceiveAmount) => {
if (sendAmount !== prevSendAmount || rate !== prevRate && sendAmount > 0) {
const newReceiveAmount = sendAmount * rate
// do something
} else {
const newSendAmount = receiveAmount / rate
// do something
}
}, [rate, sendAmount, receiveAmount])
Hope that helps.
I suggest to look at Dan Abramov (one of the React core maintainers) answer here:
I think you're making it more complicated than it needs to be.
function Example() {
const [data, dataSet] = useState<any>(null)
useEffect(() => {
async function fetchMyAPI() {
let response = await fetch('api/data')
response = await response.json()
dataSet(response)
}
fetchMyAPI()
}, [])
return <div>{JSON.stringify(data)}</div>
}
Longer term we'll discourage this pattern because it encourages race conditions. Such as — anything could happen between your call starts and ends, and you could have gotten new props. Instead, we'll recommend Suspense for data fetching which will look more like
const response = MyAPIResource.read();
and no effects. But in the meantime you can move the async stuff to a separate function and call it.
You can read more about experimental suspense here.
If you want to use functions outside with eslint.
function OutsideUsageExample() {
const [data, dataSet] = useState<any>(null)
const fetchMyAPI = useCallback(async () => {
let response = await fetch('api/data')
response = await response.json()
dataSet(response)
}, [])
useEffect(() => {
fetchMyAPI()
}, [fetchMyAPI])
return (
<div>
<div>data: {JSON.stringify(data)}</div>
<div>
<button onClick={fetchMyAPI}>manual fetch</button>
</div>
</div>
)
}
If you will use useCallback, look at example of how it works useCallback. Sandbox.
import React, { useState, useEffect, useCallback } from "react";
export default function App() {
const [counter, setCounter] = useState(1);
// if counter is changed, than fn will be updated with new counter value
const fn = useCallback(() => {
setCounter(counter + 1);
}, [counter]);
// if counter is changed, than fn will not be updated and counter will be always 1 inside fn
/*const fnBad = useCallback(() => {
setCounter(counter + 1);
}, []);*/
// if fn or counter is changed, than useEffect will rerun
useEffect(() => {
if (!(counter % 2)) return; // this will stop the loop if counter is not even
fn();
}, [fn, counter]);
// this will be infinite loop because fn is always changing with new counter value
/*useEffect(() => {
fn();
}, [fn]);*/
return (
<div>
<div>Counter is {counter}</div>
<button onClick={fn}>add +1 count</button>
</div>
);
}
I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e
export const addPost = (id) =>{
...
}
Note while importing you need to wrap it in curly braces
i.e. import {addPost} from '../URL';
But when using export default i.e
const addPost = (id) =>{
...
}
export default addPost
,
Then you can import without curly braces i.e.
import addPost from '../url';
export default addPost
I hope this helps anyone who got confused as me.
Just type this in the terminal:
export NODE_OPTIONS="--max-old-space-size=8192"
My variation of forceUpdate
is not via a counter
but rather via an object:
// Emulates `forceUpdate()`
const [unusedState, setUnusedState] = useState()
const forceUpdate = useCallback(() => setUnusedState({}), [])
Because {} !== {}
every time.
useState
is one of build-in react hooks available in 0.16.7
version.
useState
should be used only inside functional components. useState
is the way if we need an internal state and don't need to implement more complex logic such as lifecycle methods.
const [state, setState] = useState(initialState);
Returns a stateful value, and a function to update it.
During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).
The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.
Please note that useState
hook callback for updating the state behaves differently than components this.setState
. To show you the difference I prepared two examples.
class UserInfoClass extends React.Component {_x000D_
state = { firstName: 'John', lastName: 'Doe' };_x000D_
_x000D_
render() {_x000D_
return <div>_x000D_
<p>userInfo: {JSON.stringify(this.state)}</p>_x000D_
<button onClick={() => this.setState({ _x000D_
firstName: 'Jason'_x000D_
})}>Update name to Jason</button>_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
// Please note that new object is created when setUserInfo callback is used_x000D_
function UserInfoFunction() {_x000D_
const [userInfo, setUserInfo] = React.useState({ _x000D_
firstName: 'John', lastName: 'Doe',_x000D_
});_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<p>userInfo: {JSON.stringify(userInfo)}</p>_x000D_
<button onClick={() => setUserInfo({ firstName: 'Jason' })}>Update name to Jason</button>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<div>_x000D_
<UserInfoClass />_x000D_
<UserInfoFunction />_x000D_
</div>_x000D_
, document.querySelector('#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_
New object is created when setUserInfo
callback is used. Notice we lost lastName
key value. To fixed that we could pass function inside useState
.
setUserInfo(prevState => ({ ...prevState, firstName: 'Jason' })
See example:
// Please note that new object is created when setUserInfo callback is used_x000D_
function UserInfoFunction() {_x000D_
const [userInfo, setUserInfo] = React.useState({ _x000D_
firstName: 'John', lastName: 'Doe',_x000D_
});_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<p>userInfo: {JSON.stringify(userInfo)}</p>_x000D_
<button onClick={() => setUserInfo(prevState => ({_x000D_
...prevState, firstName: 'Jason' }))}>_x000D_
Update name to Jason_x000D_
</button>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<UserInfoFunction />_x000D_
, document.querySelector('#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_
Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:
setState(prevState => { // Object.assign would also work return {...prevState, ...updatedValues}; });
For more about useState
see official documentation.
There are many ways of doing it, I'm listing a few here:
Use SizedBox
if you want to set some specific space
Row(
children: <Widget>[
Text("1"),
SizedBox(width: 50), // give it width
Text("2"),
],
)
Use Spacer
if you want both to be as far apart as possible.
Row(
children: <Widget>[
Text("1"),
Spacer(), // use Spacer
Text("2"),
],
)
Use mainAxisAlignment
according to your needs:
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, // use whichever suits your need
children: <Widget>[
Text("1"),
Text("2"),
],
)
Use Wrap
instead of Row
and give some spacing
Wrap(
spacing: 100, // set spacing here
children: <Widget>[
Text("1"),
Text("2"),
],
)
Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.
More information on the answer can be found here
Enable TLS 1.2 at the system (SCHANNEL) level:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
(equivalent keys are probably also available for other TLS versions)
Tell .NET Framework to use the system TLS versions:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.
we developed a module on GitHub that has hooks for fetching data so you can use it like this for your purpose:
import { useFetching } from "react-concurrent";
const app = () => {
const { data, isLoading, error , refetch } = useFetching(() =>
fetch("http://example.com"),
);
};
You can fork that out, but any PRs are welcome. https://github.com/hosseinmd/react-concurrent#react-concurrent
i faced the same problem but i solved it by moving the chromedriver to this path '/opt/google/chrome/'
and this code works correctly
from selenium.webdriver import Chrome
driver = Chrome('/opt/google/chrome/chromedrive')
driver.get('https://google.com')
You can do it by using below CSS:
table {
width: 100%;
table-layout: fixed;
}
th, td {
overflow: hidden;
width: 200px;
text-overflow: ellipsis;
white-space: nowrap;
}
Here is a StackBlitz Example
with Sample Data
If You're using JSX inside a function with curly braces you need to modify it to parenthesis.
Wrong Code
return this.props.todos.map((todo) => {
<h3> {todo.author} </h3>;
});
Correct Code
//Change Curly Brace To Paranthesis change {} to => ()
return this.props.todos.map((todo) => (
<h3> {todo.author} </h3>;
));
I had a similir problem, but in my case, I put a row in the leading of the ListView, and it was consuming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recommend to check if the problem is a larger widget than its container can have.
Expanded(child:MyListView())
When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.
change your @csrf
in welcome.blade.php to <input type="hidden" name="_token" value="{{ csrf_token() }}">
so your code like this:
<form method="POST" action="/foo" >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="name"/><br/>
<input type="submit" value="Add"/>
<button type="submit">Submit</button>
</form>
Try this:
sudo xcode-select --reset
sudo xcodebuild -license
or this:
xcode-select --install
I hope it will help someone else.
This error seems to occur also when you UNintentionally send an object to React child components.
Example of it is passing to child component new Date('....') as follows:
const data = {name: 'ABC', startDate: new Date('2011-11-11')}
...
<GenInfo params={data}/>
If you send it as value of a child component parameter you would be sending a complex Object and you may get the same error as stated above.
Check if you are passing something similar (that generates Object under the hood).
Not really refreshing the page but thought it would help someone else out there looking for something simple
ngOnInit(){
startUp()
}
startUp(){
// Codes
}
refresh(){
// Code to destroy child component
startUp()
}
First install the: @babel/plugin-proposal-class-properties as dev dependency:
npm install @babel/plugin-proposal-class-properties --save-dev
Then edit your .babelrc so it will be exact like this:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
[
"@babel/plugin-proposal-class-properties"
]
]
}
.babelrc file located in the root directory, where package.json is.
Note that you should re-start your webpack dev server to changes take affect.
I prefer to hide all code complexity in my services... so, I generally use something like this:
In my events.service.ts
async getEvents() {
const snapchot = await this.db.collection('events').ref.get();
return new Promise <Event[]> (resolve => {
const v = snapchot.docs.map(x => {
const obj = x.data();
obj.id = x.id;
return obj as Event;
});
resolve(v);
});
}
In my sth.page.ts
myList: Event[];
construct(private service: EventsService){}
async ngOnInit() {
this.myList = await this.service.getEvents();
}
Enjoy :)
You have a CryptoListPresenter _presenter
but you are never initializing it. You should either be doing that when you declare it or in your initState()
(or another appropriate but called-before-you-need-it method).
One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.
EDIT:
I see diegoveloper beat me to answering this, and that the OP asked a follow up.
@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);
, or
CryptoListPresenter _presenter;
@override
void initState() {
_presenter = new CryptoListPresenter(...);
}
As the error says your router link should match the existing routes configured
It should be just routerLink="/about
"
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.
Finally found a quick and easy solution by adding two lines in the android/build.gradle
file.
googlePlayServicesVersion = "16.+"
firebaseVersion = "17.6.0"
Please follow this 100% correct.
Finally decided to downgrade the junit 5 to junit 4 and rebuild the testing environment.
I surggest using the CopyTo method, so here is my two cent on a solution that is easy to explain and simple. The CopyTo method copies the array to another array at a given index. In this case myArray is copied to newArr starting at index 1 so index 0 in newArr can hold the new value.
var newValue = 1;
var myArray = new int[5] { 2, 3, 4, 5, 6 };
var newArr = new int[myArray.Length + 1];
myArray.CopyTo(newArr, 1);
newArr[0] = newValue;
//debug
for(var i = 0; i < newArr.Length; i++){
Console.WriteLine(newArr[i].ToString());
}
//output
1
2
3
4
5
6
The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.
axios.request({
method: 'post',
url: 'http://foo.bar/',
data: {},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
transformRequest: [(data, header) => {
data = 'grant_type=client_credentials'
return data
}]
})
MSDocs state this for your scenario:
In order to execute the first time, PackageManagement requires an internet connection to download the Nuget package provider. However, if your computer does not have an internet connection and you need to use the Nuget or PowerShellGet provider, you can download them on another computer and copy them to your target computer. Use the following steps to do this:
Run
Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force
to install the provider from a computer with an internet connection.After the install, you can find the provider installed in
$env:ProgramFiles\PackageManagement\ReferenceAssemblies\\\<ProviderName\>\\\<ProviderVersion\>
or$env:LOCALAPPDATA\PackageManagement\ProviderAssemblies\\\<ProviderName\>\\\<ProviderVersion\>
.Place the folder, which in this case is the Nuget folder, in the corresponding location on your target computer. If your target computer is a Nano server, you need to run Install-PackageProvider from Nano Server to download the correct Nuget binaries.
Restart PowerShell to auto-load the package provider. Alternatively, run
Get-PackageProvider -ListAvailable
to list all the package providers available on the computer. Then useImport-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201
to import the provider to the current Windows PowerShell session.
AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Put these flags in your gradle.properties
android.enableJetifier=true
android.useAndroidX=true
Changes in gradle:
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'
When migrating on Android studio, the app/gradle file is automatically updated with the correction library impleemntations from the standard library
Refer to: https://developer.android.com/jetpack/androidx/migrate
If you added "spring-boot-starter-data-jpa" dependency in pom.xml, Please add respective database in dependency like h2 and etc.
axios.delete is passed a url and an optional configuration.
axios.delete(url[, config])
The fields available to the configuration can include the headers.
This makes it so that the API call can be written as:
const headers = {
'Authorization': 'Bearer paperboy'
}
const data = {
foo: 'bar'
}
axios.delete('https://foo.svc/resource', {headers, data})
I tried Jurij Pitulja solution but I just wasn't able to find getOnBackPressedDispatcher or addOnBackPressedCallback also using Kiryl Tkach's solution wasn't able to find the current fragment, so here's mine:
interface OnBackPressedListener {
fun onBackPressed(): Boolean
}
override fun onBackPressed() {
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment)
val currentFragment = navHostFragment?.childFragmentManager!!.fragments[0]
if (currentFragment !is OnBackPressedListener || !(currentFragment as OnBackPressedListener).onBackPressed()) super.onBackPressed()
this way you can decide in fragment whether the activity should take control of back pressed or not.
Alternatively, you have BaseActivity for all your activities, you can implement like this
override fun onBackPressed() {
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment)
if (navHostFragment != null){
val currentFragment = navHostFragment.childFragmentManager.fragments[0]
if (currentFragment !is AuthContract.OnBackPressedListener ||
!(currentFragment as AuthContract.OnBackPressedListener).onBackPressed()) super.onBackPressed()
} else {
super.onBackPressed()
}
}
Unless you tell the development server that it's running in development mode, it will assume you're using it in production and warn you not to. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure.
Enable development mode by setting the FLASK_ENV
environment variable to development
.
$ export FLASK_APP=example
$ export FLASK_ENV=development
$ flask run
If you're running in PyCharm (or probably any other IDE) you can set environment variables in the run configuration.
Development mode enables the debugger and reloader by default. If you don't want these, pass --no-debugger
or --no-reloader
to the run
command.
That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.
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.
There are already many nice answers to this problem but I would like to share a wonderful site that I came across when I couldnt solve the 'TesseractNotFound Error: tesseract is not installed or it's not in your path” Please refer this site: https://www.thetopsites.net/article/50655738.shtml
I realised that I got this error because I installed pytesseract with pip but forget to install the binary. You are probably missing tesseract-ocr from your machine. Check the installation instructions here: https://github.com/tesseract-ocr/tesseract/wiki
On a Mac, you can just install using homebrew:
brew install tesseract
It should run fine after that!
Under Windows 10 OS environment, the following method works for me:
Go to this link and Download tesseract and install it. Windows version is available here: https://github.com/UB-Mannheim/tesseract/wiki
Find script file pytesseract.py from C:\Users\User\Anaconda3\Lib\site-packages\pytesseract and open it. Change the following code from tesseract_cmd = 'tesseract' to: tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe' (This is the path where you install Tesseract-OCR so please check where you install it and accordingly update the path)
You may also need to add environment variable C:/Program Files (x86)/Tesseract-OCR/
Hope it works for you!
your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
their is no need to create asset directory and under it images directory and then you put image. Better is to just create Images directory inside your project where pubspec.yaml exist and put images inside it and access that images just like as shown in tutorial/documention
assets: - images/lake.jpg // inside pubspec.yaml
Look for an installation subdirectory, likely named eclipse. Under that subdirectory, if you see files like eclipse.ini, icon.xpm and subdirectories like plugins and dropins, remove the subdirectory parent (the one named eclipse).
That will remove your installation except for anything you've set up yourself (like workspaces, projects, etc.).
Hope this helps.
Below code worked perfectly with me:
dependencies {
api 'com.android.support:design:28.0.0-alpha3'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha2'
}
The @Nadun's version did not work for me, sizing wasn't working well. Removed the direction="column"
or changing it to row
, helps with building vertical login forms with responsive sizing.
<Grid
container
spacing={0}
alignItems="center"
justify="center"
style={{ minHeight: "100vh" }}
>
<Grid item xs={6}></Grid>
</Grid>;
As Sagiv b.g. pointed out, the npm start
command is a shortcut for npm run start
. I just wanted to add a real-life example to clarify it a bit more.
The setup below comes from the create-react-app
github repo. The package.json
defines a bunch of scripts which define the actual flow.
"scripts": {
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"start-js": "react-scripts start"
},
For clarity, I added a diagram.
The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name>
command. But as you can see, actually there are only 2 practical flows:
npm run start
npm run build
The grey boxes are commands which can be executed from the command line.
So, for instance, if you run npm start
(or npm run start
) that actually translate to the npm-run-all -p watch-css start-js
command, which is executed from the commandline.
In my case, I have this special npm-run-all
command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2>
switch. So, here it executes 2 scripts, i.e. watch-css
and start-js
. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)
The watch-css
makes sure that the *.scss
files are translated to *.css
files, and looks for future updates.
The start-js
points to the react-scripts start
which hosts the website in a development mode.
In conclusion, the npm start
command is configurable. If you want to know what it does, then you have to check the package.json
file. (and you may want to make a little diagram when things get complicated).
I have the exact same problem, and here is the solution I make use of now: (Note, this seems ideal to me because it keeps the files closely tied to the SinglePageApplication React app, that loads from Amazon S3. So, it's like storing on S3, and in an application, that knows where it is in S3, relatively speaking.
3 steps:
npm install file-saver
or something)public
folder, under a resource
or an asset
name. Webpack doesn't touch the public
folder and index.html
and your resources get copied over in production build as is, where you may refer them as shown in next step.import FileSaver from 'file-saver';
FileSaver.saveAs(
process.env.PUBLIC_URL + "/resource/file.anyType",
"fileNameYouWishCustomerToDownLoadAs.anyType");
Link
component of react-router
react-router-docs/Link. The zip file would download, and somehow would unzip properly. Generally, links have blue color, to inherit parent color scheme, simply add a prop like: style={color: inherit}
or simply assign a class of your CSS library like button button-primary
or something if you're Bootstrappin'One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'
HTML
<mat-form-field>
<mat-select [(ngModel)]="modeSelect" placeholder="Mode">
<mat-option *ngFor="let obj of Array" [value]="obj.value">{{obj.value}}</mat-option>
</mat-select>
Now set your default value to
modeSelect
, where you are getting the values in Array variable.
I was trying to find a way with Redirect but failed. Redirecting onClick is simpler than we think. Just place the following basic JavaScript within your onClick function, no monkey business:
window.location.href="pagelink"
I had the same error, and I found out that the cause was because my computer disk was full. After deleting some unnecessary files, the error went away.
npx
runs a command of a package without installing it explicitly.
Use cases:
package.json
to execute something without installing these packages as project's dependencies.Syntax:
npx [options] [-p|--package <package>] <command> [command-arg]...
Package is optional:
npx -p uglify-js uglifyjs --output app.min.js app.js common.js
+----------------+ +--------------------------------------------+
package (optional) command, followed by arguments
For example:
Start a HTTP Server : npx http-server
Lint code : npx eslint ./src
# Run uglifyjs command in the package uglify-js
Minify JS : npx -p uglify-js uglifyjs -o app.min.js app.js common.js
Minify CSS : npx clean-css-cli -o style.min.css css/bootstrap.css style.css
Minify HTML : npx html-minifier index-2.html -o index.html --remove-comments --collapse-whitespace
Scan for open ports : npx evilscan 192.168.1.10 --port=10-9999
Cast video to Chromecast : npx castnow http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4
More about command
:
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
D:project/contactlist npm install then D:project/contactlist ng new client
D:project/contactlist/client ng serve
this worked for me for some reason i had to delete the client folder and start npm install from the contactlist folder. i tried every thing even clearing the cache and finally this worked.
Starting with MySQL 8.0.4, they have changed the default authentication plugin for MySQL server from mysql_native_password to caching_sha2_password.
You can run the below command to resolve the issue.
sample username / password => student / pass123
ALTER USER 'student'@'localhost' IDENTIFIED WITH mysql_native_password BY 'pass123';
Refer the official page for details: MySQL Reference Manual
npm start
runs a script that the app maker built for easy starting of the app
npm install
installs all the packages in package.json
run npm install
first
then run npm start
I didn't have a package.json. Make sure you have one.
If you want to go with the add-open option, here's a command to find which module provides which package ->
java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d
the name of the module will be shown with the @ while the name of the packages without it
NOTE: tested with JDK 11
IMPORTANT: obviously is better than the provider of the package does not do the illegal access
I had the same error and solved the problem by running the program code below:
# install_certifi.py
#
# sample script to install or update a set of default Root Certificates
# for the ssl module. Uses the certificates provided by the certifi package:
# https://pypi.python.org/pypi/certifi
import os
import os.path
import ssl
import stat
import subprocess
import sys
STAT_0o775 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
| stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
| stat.S_IROTH | stat.S_IXOTH )
def main():
openssl_dir, openssl_cafile = os.path.split(
ssl.get_default_verify_paths().openssl_cafile)
print(" -- pip install --upgrade certifi")
subprocess.check_call([sys.executable,
"-E", "-s", "-m", "pip", "install", "--upgrade", "certifi"])
import certifi
# change working directory to the default SSL directory
os.chdir(openssl_dir)
relpath_to_certifi_cafile = os.path.relpath(certifi.where())
print(" -- removing any existing file or link")
try:
os.remove(openssl_cafile)
except FileNotFoundError:
pass
print(" -- creating symlink to certifi certificate bundle")
os.symlink(relpath_to_certifi_cafile, openssl_cafile)
print(" -- setting permissions")
os.chmod(openssl_cafile, STAT_0o775)
print(" -- update complete")
if __name__ == '__main__':
main()
I had this problem during migration to Spring Boot. I've found a advice to remove dependencies and it helped. So, I removed dependency for jsp-api Project had. Also, servlet-api dependency has to be removed as well.
compileOnly group: 'javax.servlet.jsp', name: 'jsp-api', version: '2.2'
In addition to other answers which helped me, you can also add to surrounding div. In my case this was for sign on with user Name/Password fields.
<div (keyup.enter)="login()" class="container-fluid">
There are two possible reasons 1. If you are using HttpClient in your service you need to import HttpClientModule in your module file and mention it in the imports array.
import { HttpClientModule } from '@angular/common/http';
If you are using normal Http in your services you need to import HttpModule in your module file and mention it in the imports array.
import { HttpModule } from '@angular/http
'
By default, this is not available in the angular then you need to install @angular/http
If you wish you can use both HttpClientModule and HttpModule in your project.
In pycharm I wrote the code for accessing the IP Camera like:
import cv2
cap=VideoCapture("rtsp://user_name:password@IP_address:port_number")
ret, frame=cap.read()
You will need to replace user_name
, password
, IP
and port
with suitable values
call the request function from anywhere without having to use catch().
First, while handling most errors in one place is a good Idea, it's not that easy with requests. Some errors (e.g. 400 validation errors like: "username taken" or "invalid email") should be passed on.
So we now use a Promise based function:
const baseRequest = async (method: string, url: string, data: ?{}) =>
new Promise<{ data: any }>((resolve, reject) => {
const requestConfig: any = {
method,
data,
timeout: 10000,
url,
headers: {},
};
try {
const response = await axios(requestConfig);
// Request Succeeded!
resolve(response);
} catch (error) {
// Request Failed!
if (error.response) {
// Request made and server responded
reject(response);
} else if (error.request) {
// The request was made but no response was received
reject(response);
} else {
// Something happened in setting up the request that triggered an Error
reject(response);
}
}
};
you can then use the request like
try {
response = await baseRequest('GET', 'https://myApi.com/path/to/endpoint')
} catch (error) {
// either handle errors or don't
}
Try to use mousemove event lisentner
var audio = document.createElement("AUDIO")
document.body.appendChild(audio);
audio.src = "./audio/rain.m4a"
document.body.addEventListener("mousemove", function () {
audio.play()
})
I experienced this when upgrading .NET Core 1.1 to 2.1.
I followed the instructions outlined here.
Try to remove <RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion>
or <NetStandardImplicitPackageVersion>
section in the .csproj.
Use python -m pip install
instead of pip install
Example:
python -m pip install --user somepackage
python3 -m pip install --user somepackage
The pip
(resp. pip3
) executable is provided by your distro (python-pip
package on Ubuntu 16.04) and located at /usr/bin/pip
.
Therefore, it is not kept up-to date with the pip
package itself as you upgrade pip, and may break.
If you just use python -m pip
directly, e.g. as in:
python -m pip install --user somepackage
python3 -m pip install --user somepackage
it goes through your Python path, finds the latest version of pip and executes that file.
It relies on the fact that file is executable through import
, but that is a very standard type of interface, and therefore less likely to break than the hackier Debian script.
Then I recommend adding the following aliases to your .bashrc
:
pip() ( python -m pip "$@" )
pip3() ( python3 -m pip "$@" )
The Ubuntu 18.04 /usr/bin/pip3
file does:
from pip import main
and presumably main
was removed from pip
at some point which is what broke things.
The breaking pip commit appears to be: 95bcf8c5f6394298035a7332c441868f3b0169f4 "Move all internal APIs to pip._internal" which went into pip 18.0.
Tested in Ubuntu 16.04 after an update from pip3
9.0.1 to 18.0.
pyenv
Ultimately however, for serious Python development I would just recommend that you install your own local Python with pyenv + virtualenv, which would also get around this Ubuntu bug: https://askubuntu.com/questions/682869/how-do-i-install-a-different-python-version-using-apt-get/1195153#1195153
If you want to update any specific version from the package.json you can update the version of the package by doing ==>
yarn add package-name@version-number
npm install --save package-name@version-number
If you want to update all packages to the latest version you can run command ==>
npm audit fix --force
RawMaterialButton is better suited I think.
RawMaterialButton(
onPressed: () {},
elevation: 2.0,
fillColor: Colors.white,
child: Icon(
Icons.pause,
size: 35.0,
),
padding: EdgeInsets.all(15.0),
shape: CircleBorder(),
)
Here is what worked for me (Angular 7):
First import HttpClientModule in your app.module.ts if you didn't:
import { HttpClientModule } from '@angular/common/http';
...
imports: [
HttpClientModule
],
Then change your service
@Injectable()
export class FooService {
to
@Injectable({
providedIn: 'root'
})
export class FooService {
Hope it helps.
Edit:
providedIn
Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:
'root' : The application-level injector in most apps.
'platform' : A special singleton platform injector shared by all applications on the page.
'any' : Provides a unique instance in every module (including lazy modules) that injects the token.
Be careful platform
is available only since Angular 9 (https://blog.angular.io/version-9-of-angular-now-available-project-ivy-has-arrived-23c97b63cfa3)
Read more about Injectable here: https://angular.io/api/core/Injectable
props.children
represents the content between the opening and the closing tags when invoking/rendering a component:
const Foo = props => (
<div>
<p>I'm {Foo.name}</p>
<p>abc is: {props.abc}</p>
<p>I have {props.children.length} children.</p>
<p>They are: {props.children}.</p>
<p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
</div>
);
const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;
invoke/call/render Foo
:
<Foo abc={123}>
<Baz />
<Bar />
</Foo>
in my idea, you must go to a certain path for example:
from google.colab import drive drive.mount('/content/drive/') cd drive/MyDrive/f/
then :
!apt install unzip !unzip zip_folder.zip -d unzip_folder enter image description here
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.
If in case you are getting the values as undefined
, then you should consider restarting the node server and recompile again.
As CommonsWare mentioned, for reference add this inside the android {...}
closure in the build.gradle for your app module to resolve issue:
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
...
}
your dependency based on data is trying to find their respective entities which one has not been created, comments the dependencies based on data and runs the app again.
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter-data-jpa</artifactId> -->
<!-- </dependency> -->
Try the following steps:
1. Make sure you have the latest npm (npm install -g npm).
2. Add an exception to your antivirus to ignore the node_modules folder in your project.
3. $ rm -rf node_modules package-lock.json .
4. $ npm install
As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the maven-compiler-plugin:3.8.0
to specify a release of either 9,10,11 without any explicit dependencies.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release> <!--or <release>10</release>-->
</configuration>
</plugin>
Note:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- release notes.
Edit [30.12.2018]
In fact, you can make use of the same version of maven-compiler-plugin
while compiling the code against JDK/12 as well.
More details and a sample configuration in how to Compile and execute a JDK preview feature with Maven.
I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.
The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api
Relevant passages as of January 2021 are below. These are excerpts from the text.
4.6 HTTP-network fetch
To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.
To append a name/value name/value pair to a Headers object (headers), run these steps:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If headers’s guard is "immutable", then throw a TypeError.
Filling Headers object headers with a given object object:
To fill a Headers object headers with a given object object, run these steps:
- If object is a sequence, then for each header in object:
- If header does not contain exactly two items, then throw a TypeError.
Method steps sometimes throw TypeError:
The delete(name) method steps are:
- If name is not a name, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
The get(name) method steps are:
- If name is not a name, then throw a TypeError.
- Return the result of getting name from this’s header list.
The has(name) method steps are:
- If name is not a name, then throw a TypeError.
The set(name, value) method steps are:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
To extract a body and a
Content-Type
value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.
In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin
In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:
The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method isGET
orHEAD
, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In the Response class:
The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...
The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In section "The Fetch method"
The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.
In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.
My case was really different. I had set android:text=" ??? " property of my TetxtView in my layout file, when I changed it to android:text=" ? " it worked. I have no idea why this works, maybe it helps someone. It took me hours to find the issue.
Take a look here: https://reacttraining.com/react-router/core/api/Route/exact-bool
exact: bool
When true, will only match if the path matches the location.pathname
exactly.
**path** **location.pathname** **exact** **matches?**
/one /one/two true no
/one /one/two false yes
if you are in base:
(base) HP-Compaq-Elite-8300-CMT:~$
remove env_name by:
conda env remove -n env_name
if you are already in env_name environment :
(env_name) HP-Compaq-Elite-8300-CMT:~$
deactivate then remove by :
conda deactivate
conda env remove -n env_name
I know it's a late answer but I had the same problem and my solution was just adding implementation 'com.android.support:design:28.0.0
or any above support design libraries !!
As this post gets a bit of popularity I edited it a bit. Spring Boot 2.x.x changed default JDBC connection pool from Tomcat to faster and better HikariCP. Here comes incompatibility, because HikariCP uses different property of jdbc url. There are two ways how to handle it:
OPTION ONE
There is very good explanation and workaround in spring docs:
Also, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no url property (but does have a jdbcUrl property). In that case, you must rewrite your configuration as follows:
app.datasource.jdbc-url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
OPTION TWO
There is also how-to in the docs how to get it working from "both worlds". It would look like below. ConfigurationProperties bean would do "conversion" for jdbcUrl
from app.datasource.url
@Configuration
public class DatabaseConfig {
@Bean
@ConfigurationProperties("app.datasource")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@ConfigurationProperties("app.datasource")
public HikariDataSource dataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
}
I tried your code, you didn't assign/bind a value to your formControlName.
In HTML file:
<form [formGroup]="form">
<label>
<input type="radio" value="Male" formControlName="gender">
<span>male</span>
</label>
<label>
<input type="radio" value="Female" formControlName="gender">
<span>female</span>
</label>
</form>
In the TS file:
form: FormGroup;
constructor(fb: FormBuilder) {
this.name = 'Angular2'
this.form = fb.group({
gender: ['', Validators.required]
});
}
Make sure you use Reactive form properly: [formGroup]="form"
and you don't need the name attribute.
In my sample. words male
and female
in span tags are the values display along the radio button and Male
and Female
values are bind to formControlName
To make it shorter:
<form [formGroup]="form">
<input type="radio" value='Male' formControlName="gender" >Male
<input type="radio" value='Female' formControlName="gender">Female
</form>
Hope it helps:)
You need to set JDK 1.5 to your project and also all dependent project or jar file should also compiled with JDK 1.5
You can use Async - Await:
async function axiosTest() {
const response = await axios.get(url);
const data = await response.json();
}
file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
any_string = "Hello\nWorld"
file.write(any_string)
file.close()
Solve my problem using this line of code in my Startup.cs file.
Adding a transient service means that each time the service is requested, a new instance is created when you are working
with
Dependency injection
services.AddDbContext<Context>(options =>
options.UseSqlServer(_configuration.GetConnectionString("ContextConn")),
ServiceLifetime.Transient);
Whenever you try to show a Link
on a page thats outside the BrowserRouter
you will get that error.
This error message is essentially saying that any component that is not a child of our <Router>
cannot contain any React Router related components.
You need to migrate your component hierarchy to how you see it in the first answer above. For anyone else reviewing this post who may need to look at more examples.
Let's say you have a Header.js
component that looks like this:
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => {
return (
<div className="ui secondary pointing menu">
<Link to="/" className="item">
Streamy
</Link>
<div className="right menu">
<Link to="/" className="item">
All Streams
</Link>
</div>
</div>
);
};
export default Header;
And your App.js
file looks like this:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';
const App = () => {
return (
<div className="ui container">
<Header />
<BrowserRouter>
<div>
<Route path="/" exact component={StreamList} />
<Route path="/streams/new" exact component={StreamCreate} />
<Route path="/streams/edit" exact component={StreamEdit} />
<Route path="/streams/delete" exact component={StreamDelete} />
<Route path="/streams/show" exact component={StreamShow} />
</div>
</BrowserRouter>
</div>
);
};
export default App;
Notice that the Header.js
component is making use of the Link
tag from react-router-dom
but the componet was placed outside the <BrowserRouter>
, this will lead to the same error as the one experience by the OP. In this case, you can make the correction in one move:
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';
const App = () => {
return (
<div className="ui container">
<BrowserRouter>
<div>
<Header />
<Route path="/" exact component={StreamList} />
<Route path="/streams/new" exact component={StreamCreate} />
<Route path="/streams/edit" exact component={StreamEdit} />
<Route path="/streams/delete" exact component={StreamDelete} />
<Route path="/streams/show" exact component={StreamShow} />
</div>
</BrowserRouter>
</div>
);
};
export default App;
Please review carefully and ensure you have the <Header />
or whatever your component may be inside of not only the <BrowserRouter>
but also inside of the <div>
, otherwise you will also get the error that a Router may only have one child which is referring to the <div>
which is the child of <BrowserRouter>
. Everything else such as Route
and components must go within it in the hierarchy.
So now the <Header />
is a child of the <BrowserRouter>
within the <div>
tags and it can successfully make use of the Link
element.
To be more generic about the answer provided by @P Fuster. There can be error in your xml files.
I encountered the same error and was having error in the drawable where end tag was missing.
You should pass the event object when calling the function :
{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}
If you don't need to handle onClick event you can also type :
{<td><span onClick={(e) => this.toggle()}>Details</span></td>}
Now you can also add your parameters within the function.
1.On Child Widget : add parameter Function paramter
class ChildWidget extends StatefulWidget {
final Function() notifyParent;
ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}
2.On Parent Widget : create a Function for the child to callback
refresh() {
setState(() {});
}
3.On Parent Widget : pass parentFunction to Child Widget
new ChildWidget( notifyParent: refresh );
4.On Child Widget : call the Parent Function
widget.notifyParent();
If this isn't a good solution for any reason, please let me know. It worked fine for me.
What I did is to hide the Sidebar and then make appear the navbar with breakpoints
@media screen and (max-width: 771px) {
#fixed-sidebar {
display: none;
}
#navbar-superior {
display: block !important;
}
}
Adding to sagiv's answer, we should create the parent component in such a way that it can consist all children components rather than returning the child components in the way you were trying to return.
Try to intentiate the parent component and pass the props inside it so that all children can use it like below
const NewComponent = NewHOC(Movie);
Here NewHOC is the parent component and all its child are going to use movie as props.
But any way, you guyd6 have solved a problem for new react developers as this might be a problem that can come too and here is where they can find the solution for that.
You might forgetting to include.. StartUp.cs/Configure()
app.UseSwagger();
Check if you forgot to include, you error must be remove.
Assuming you don't want to eject and you just want to look at the config you will find them in /node_modules/react-scripts/config
webpack.config.dev.js. //used by `npm start`
webpack.config.prod.js //used by `npm run build`
Please add the JAVA_HOME in the System variable no in the user variable
You can tag your DOM element using #someTag
, then get it with @ViewChild('someTag')
.
See complete example:
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'app',
template: `
<div #myDiv>Some text</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement.innerHTML);
}
}
console.log
will print Some text.
After you start running the training loop, if you want to manually watch it from the terminal whether your program is utilizing the GPU resources and to what extent, then you can simply use watch
as in:
$ watch -n 2 nvidia-smi
This will continuously update the usage stats for every 2 seconds until you press ctrl+c
If you need more control on more GPU stats you might need, you can use more sophisticated version of nvidia-smi
with --query-gpu=...
. Below is a simple illustration of this:
$ watch -n 3 nvidia-smi --query-gpu=index,gpu_name,memory.total,memory.used,memory.free,temperature.gpu,pstate,utilization.gpu,utilization.memory --format=csv
which would output the stats something like:
Note: There should not be any space between the comma separated query names in --query-gpu=...
. Else those values will be ignored and no stats are returned.
Also, you can check whether your installation of PyTorch detects your CUDA installation correctly by doing:
In [13]: import torch
In [14]: torch.cuda.is_available()
Out[14]: True
True
status means that PyTorch is configured correctly and is using the GPU although you have to move/place the tensors with necessary statements in your code.
If you want to do this inside Python code, then look into this module:
https://github.com/jonsafari/nvidia-ml-py or in pypi here: https://pypi.python.org/pypi/nvidia-ml-py/
You're only exporting it in your NgModule, you need to import it too
@NgModule({
imports: [
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule,
]
exports: [
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule,
],
declarations: [
SearchComponent,
],
})export class MaterialModule {};
better yet
const modules = [
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule
];
@NgModule({
imports: [...modules],
exports: [...modules]
,
})export class MaterialModule {};
You're declaring component (SearchComponent) depending on Angular Material before all Angular dependency are imported
Like BrowserAnimationsModule
Try moving it to MaterialModule, or before it
in the manifest file set second activity parentActivityName as first activity and remove the screenOrientation parameter to the second activity. it means your first activity is the parent and decide to an orientation of your second activity.
<activity
android:name=".view.FirstActiviy"
android:screenOrientation="portrait"
android:theme="@style/AppTheme" />
<activity
android:name=".view.SecondActivity"
android:parentActivityName=".view.FirstActiviy"
android:theme="@style/AppTheme.Transparent" />
This problem is commonly related to compiler errors in the Java code. Sometimes Android Studio does not show these errors in the Project explorer
. However, when a problematic .java
file is opened, errors are shown. Try to resolve errors and rebuild the project.
I encountered a similar issue trying to use xlrd in jupyter notebook. I notice you are using a virtual environment and that was the key to my issue as well. I had xlrd installed in my venv, but I had not properly installed a kernel for that virtual environment in my notebook.
To get it to work, I created my virtual environment and activated it.
Then... pip install ipykernel
And then... ipython kernel install --user --name=myproject
Finally, start jupyter notebooks and when you create a new notebook, select the name you created (in this example, 'myproject')
Hope that helps.
You have to look to official ReactiveX documentation: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md.
This is a good article about piping in RxJS: https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44.
In short .pipe() allows chaining multiple pipeable operators.
Starting in version 5.5 RxJS has shipped "pipeable operators" and renamed some operators:
do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize
This is rather old question but this might be of some help for future reference. Delete node_modules folder and run npm install again. Worked for me.
The order of details provided with verbose flag are as
Less details.... More details
0 < 2 < 1
Default is 1
For production environment, 2 is recommended
One of the ways that you can run your spring-boot application from command line is as follows :
1) First go to your project directory in command line [where is your project located ?]
2) Then in the next step you have to create jar file for that, this can be done as
mvnw package
[for WINDOWS OS ] or ./mvnw package
[for MAC OS] , this will
create jar file for our application.
3) jar file is created in the target sub-directory
4)Now go to target sub directory as jar was created inside of it , i.e cd target
5) Now run the jar file in there.
Use command java -jar name.jar
[ name is the name of your created jar file.]
and there you go , you are done . Now you can run project in browser,
http://localhost:port_number
Fortunately, if you are using Angular 5.1+, you do not need to implement a hack anymore as native support has been added. You just need to set onSameUrlNavigation to 'reload' in the RouterModule options :
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
exports: [RouterModule],
})
More information can be found here: https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2
For others with the same problem on iOS with CocoaPods:
I tried all of the solutions above, without luck. I have some packages with native dependencies in my project, and some of those needed pod modules being installed. The problem was that React was specified in my Podfile, but the React pod didn't automatically get upgraded by using react-native-git-upgrade
.
The fix is to upgrade all installed pods, by running cd ios && pod install
.
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;
If you are getting this error only when you are generating signed Apk . Then the problem might be in one or more of the imported media file format. I have used an image directly from net to studio and was not able to generate sign apk, then found the error .
from Gradle >assembleRelease then got the error in console. see the error log in console image.
Unlike it's most popular commercial competitor, numpy pretty much from the outset is about "arbitrary-dimensional" arrays, that's why the core class is called ndarray
. You can check the dimensionality of a numpy array using the .ndim
property. The .shape
property is a tuple of length .ndim
containing the length of each dimensions. Currently, numpy can handle up to 32 dimensions:
a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32
If a numpy array happens to be 2d like your second example, then it's appropriate to think about it in terms of rows and columns. But a 1d array in numpy is truly 1d, no rows or columns.
If you want something like a row or column vector you can achieve this by creating a 2d array with one of its dimensions equal to 1.
a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T
The Component
is defined like so:
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
Meaning that the default type for the state (and props) is: {}
.
If you want your component to have value
in the state then you need to define it like this:
class App extends React.Component<{}, { value: string }> {
...
}
Or:
type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
...
}
Simple answer
If you want to match single character, put it inside those brackets [ ]
Examples
...and so on. You can check your regular expresion online on this site: https://regex101.com/
(updated based on comment)
Does IE11 displays any message relative to the blocked execution of your ActiveX ?
You should read this and this.
Use the following JS function to detect support of ActiveX :
function IsActiveXSupported() {
var isSupported = false;
if(window.ActiveXObject) {
return true;
}
if("ActiveXObject" in window) {
return true;
}
try {
var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
isSupported = true;
} catch (e) {
if (e.name === "TypeError" || e.name === "Error") {
isSupported = true;
}
}
return isSupported;
}
The following will produce, in the output directory,
But it does not contain all .NET Core runtime assemblies.
<PropertyGroup>
<Temp>$(SolutionDir)\packaging\</Temp>
</PropertyGroup>
<ItemGroup>
<BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
</ItemGroup>
<Target Name="GenerateNetcoreExe"
AfterTargets="Build"
Condition="'$(IsNestedBuild)' != 'true'">
<RemoveDir Directories="$(Temp)" />
<Exec
ConsoleToMSBuild="true"
Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
<Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
</Exec>
<Copy
SourceFiles="@(BootStrapFiles)"
DestinationFolder="$(OutputPath)"
/>
</Target>
I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole
First Option:
OPEN package.json and add "--port port-no" in "serve" section.
Just like below, I have done it.
{
"name": "app-name",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve --port 8090",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
}
Second Option: If You want through command prompt
npm run serve --port 8090
If it's a sorted array you could use a Binary search algorithm (O(log n)
). For example, extending the Array-class with this functionality:
class Array
def b_search(e, l = 0, u = length - 1)
return if lower_index > upper_index
midpoint_index = (lower_index + upper_index) / 2
return midpoint_index if self[midpoint_index] == value
if value < self[midpoint_index]
b_search(value, lower_index, upper_index - 1)
else
b_search(value, lower_index + 1, upper_index)
end
end
end
Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.
double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));
The nextInt()
method leaves the \n
(end line) symbol and is picked up immediately by nextLine()
, skipping over the next input. What you want to do is use nextLine()
for everything, and parse it later:
String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int
This is by far the easiest way to avoid problems--don't mix your "next" methods. Use only nextLine()
and then parse int
s or separate words afterwards.
Also, make sure you use only one Scanner
if your are only using one terminal for input. That could be another reason for the exception.
Last note: compare a String
with the .equals()
function, not the ==
operator.
if (playAgain == "yes"); // Causes problems
if (playAgain.equals("yes")); // Works every time
I had to use Stylesheet directory to work for me.
<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/image.png">
This will replace all ?
with '
:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
WHERE city LIKE '%?%'
If you need to update more than one column, you can either change city
each time you execute to a different column name, or list the columns like so:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'
This won't work if the list contains integers
And if the list contains non-string types (such as integers, floats, bools, None) then do:
my_string = ','.join(map(str, my_list))
If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:
PARAMETERS SomeParam Text(10);
SELECT Field FROM Table
WHERE OtherField=SomeParam
You can also say:
CREATE PROCEDURE ProcedureName
(Parameter1 datatype, Parameter2 datatype) AS
SQLStatement
From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs
Note that the procedure contains only one statement.
Install and setup mysql to connect from anywhere remotely DOES NOT WORK WITH mysql_secure_installation ! (https://dev.mysql.com/doc/refman/5.5/en/mysql-secure-installation.html)
sudo apt-get install mysql-server
[mysqld]
#### Unix socket settings (making localhost work)
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
#### TCP Socket settings (making all remote logins work)
port = 3306
bind-address = 0.0.0.0
mysql -u root -p
grant all privileges on *.* to ‘username’@‘%’ identified by ‘password’;
sudo ufw allow 3306
sudo service mysql restart
To store the third line into a variable, use below syntax:
variable=`echo "$1" | sed '3q;d' urfile`
To store the changed line into a variable, use below syntax:
variable=echo 'overflow' | sed -e "s/over/"OVER"/g"
output:OVERflow
If you are to replace a fixed string or some pattern, I would also like to add the bash builtin pattern string replacement variable substitution construct. Instead of describing it myself, I am quoting the section from the bash manual:
${parameter/pattern/string}
The pattern is expanded to produce a pattern just as in pathname expansion. parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with
/
, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with#
, it must match at the beginning of the expanded value of parameter. If pattern begins with%
, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the/
following pattern may be omitted. If parameter is@
or*
, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with@
or*
, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
According to http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/
[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
{
IntPtr ip = source.GetHbitmap();
BitmapSource bs = null;
try
{
bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(ip);
}
return bs;
}
It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.
image1.Source = YourUtilClass.loadBitmap(SomeBitmap);
I have not played with 3D yet, but I know a good place for ressources on 3D for HTML5.
http://www.html5rocks.com/en/gaming
And here is a tutorial on how to create your 3D models with the Three.js
Framework.
http://www.html5rocks.com/en/tutorials/three/intro/
This may help you. Good luck.
By calling method
public class a
{
void sum(int i,int k)
{
System.out.println("THe sum of the number="+(i+k));
}
}
class b
{
public static void main(String[] args)
{
a vc=new a();
vc.sum(10 , 20);
}
}
sudo nginx -t
should test all files and return errors and warnings locations
Depends on what you're doing.
For instance:
//bankers' rounding - midpoint goes to nearest even
GetIntPart(2.5) >> 2
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -6
or
//arithmetic rounding - midpoint goes away from zero
GetIntPart(2.5) >> 3
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -7
The default is always the former, which can be a surprise but makes very good sense.
Your explicit cast will do:
int intPart = (int)343564564.5
// intPart will be 343564564
int intPart = (int)343564565.5
// intPart will be 343564566
From the way you've worded the question it sounds like this isn't what you want - you want to floor it every time.
I would do:
Math.Floor(Math.Abs(number));
Also check the size of your decimal
- they can be quite big, so you may need to use a long
.
Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
And on the handler method:
private void WorkerDoWork(int value, string text) {
...
}
With question 3, this article states that RESTful Services are appropiate in this scenarios:
While SOAP is the way to go when:
In manually deleting a topic from a kafka cluster , you just might check this out https://github.com/darrenfu/bigdata/issues/6
A vital step missed a lot in most solution is in deleting the /config/topics/<topic_name>
in ZK.
This is good in the general case:
yourPath.Split(@"\/", StringSplitOptions.RemoveEmptyEntries)
There is no empty element in the returned array if the path itself ends in a (back)slash (e.g. "\foo\bar\"). However, you will have to be sure that yourPath
is really a directory and not a file. You can find out what it is and compensate if it is a file like this:
if(Directory.Exists(yourPath)) {
var entries = yourPath.Split(@"\/", StringSplitOptions.RemoveEmptyEntries);
}
else if(File.Exists(yourPath)) {
var entries = Path.GetDirectoryName(yourPath).Split(
@"\/", StringSplitOptions.RemoveEmptyEntries);
}
else {
// error handling
}
I believe this covers all bases without being too pedantic. It will return a string[]
that you can iterate over with foreach
to get each directory in turn.
If you want to use constants instead of the @"\/"
magic string, you need to use
var separators = new char[] {
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar
};
and then use separators
instead of @"\/"
in the code above. Personally, I find this too verbose and would most likely not do it.
JOIN t2 ON t1.id=t2.id AND t1.date=t2.date
iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// "e@uu$`a"
iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@uu$`a"
iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// PHP Notice: iconv(): Detected an illegal character
iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@u$`a"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', Transliterator::create('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC')->transliterate('é@ùµ$`à'))
// "e@uu$`a" -> same as PHP 7.2
We've just released arg.js, a project aimed at solving this problem once and for all. It's traditionally been so difficult but now you can do:
var querystring = Arg.url({name: "Mat", state: "CO"});
And reading works:
var name = Arg("name");
or getting the whole lot:
var params = Arg.all();
and if you care about the difference between ?query=true
and #hash=true
then you can use the Arg.query()
and Arg.hash()
methods.
The file .so is not a UNIX file extension for shared library.
It just happens to be a common one.
Check line 3b at ArnaudRecipes sharedlib page
Basically .dylib is the mac file extension used to indicate a shared lib.
@SuppressWarnings("unchecked")
Map<String,String[]> requestMapper=request.getParameterMap();
JsonObject jsonObject=new JsonObject();
for(String key:requestMapper.keySet()){
jsonObject.addProperty(key, requestMapper.get(key)[0]);
}
All params will be stored in jsonObject
.
for VS code and later versions Ctrl + P to open and then writing Whitespace, you can select the View: Toggle Render Whitespace
This how to make input password that has hint which not converted to * !!.
On XML :
android:inputType="textPassword"
android:gravity="center"
android:ellipsize="start"
android:hint="Input Password !."
thanks to : mango and rjrjr for the insight :D.
At my case change buildToolsVersion from "24" to "23.0.2", solve the problem.
192.168.0.101 - remote server
192.168.0.102 - local server
Remore server
CREATE USER 'backup_remote_2'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '3333333' REQUIRE SSL;
GRANT ALL PRIVILEGES ON *.* TO 'backup_remote_2'@'192.168.0.102';
FLUSH PRIVILEGES;
-
Local server
sudo /usr/local/mysql/bin/mysqldump \
--databases test_1 \
--host=192.168.0.101 \
--user=backup_remote_2 \
--password=3333333 \
--master-data \
--set-gtid-purged \
--events \
--triggers \
--routines \
--verbose \
--ssl-mode=REQUIRED \
--result-file=/home/db_1.sql
====================================
192.168.0.101 - remote server
192.168.0.102 - local server
Remore server
CREATE USER 'backup_remote'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '1111111' REQUIRE X509;
GRANT ALL PRIVILEGES ON *.* TO 'backup_remote'@'192.168.0.102';
FLUSH PRIVILEGES;
-
Local server
sudo /usr/local/mysql/bin/mysqldump \
--databases test_1 \
--host=192.168.0.101 \
--user=backup_remote \
--password=1111111 \
--events \
--triggers \
--routines \
--verbose \
--ssl-mode=VERIFY_CA \
--ssl-ca=/usr/local/mysql/data/ssl/ca.pem \
--ssl-cert=/usr/local/mysql/data/ssl/client-cert.pem \
--ssl-key=/usr/local/mysql/data/ssl/client-key.pem \
--result-file=/home/db_name.sql
On local server
/usr/local/mysql/data/ssl/
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 client-key.pem
Copy this files from remote server for (REQUIRE X509) or if SSL without (REQUIRE X509) do not copy
On remote server
/usr/local/mysql/data/
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 client-key.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 private_key.pem
-rw-r--r-- 1 mysql mysql 451 Apr 16 22:28 public_key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 server-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 server-key.pem
my.cnf
[mysqld]
# SSL
ssl_ca=/usr/local/mysql/data/ca.pem
ssl_cert=/usr/local/mysql/data/server-cert.pem
ssl_key=/usr/local/mysql/data/server-key.pem
Increase Password Security
https://dev.mysql.com/doc/refman/8.0/en/password-security-user.html
Using os.path.dirname
:
>>> os.path.dirname(r'C:\Program Files')
'C:\\'
>>> os.path.dirname('C:\\')
'C:\\'
>>>
Caveat: os.path.dirname()
gives different results depending on whether a trailing slash is included in the path. This may or may not be the semantics you want. Cf. @kender's answer using os.path.join(yourpath, os.pardir)
.
If your are referring to two worksheets please use this formula
=COUNTIF(Worksheet2!$A$1:$A$50,Worksheet1cellA1)
In case referring to to more than two worksheets please use this formula
=COUNTIF(Worksheet2!$A$1:$A$50,Worksheet1cellA1)+=COUNTIF
(Worksheet3!$A$1:$A$50,Worksheet1cellA1)+=
COUNTIF(Worksheet4!$A$1:$A$50,Worksheet1cellA1)
Another alternative is to use DATE()
function on the left hand operand as shown below
SELECT users.* FROM users WHERE DATE(created_at) BETWEEN '2011-12-01' AND '2011-12-06'
For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.
You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: data,
dataType: 'json', // ** ensure you add this line **
success: function(data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
Gem::Specification.map {|a| a.name}
However, if your app uses Bundler it will return only list of dependent local gems. To get all installed:
def all_installed_gems
Gem::Specification.all = nil
all = Gem::Specification.map{|a| a.name}
Gem::Specification.reset
all
end
Haven't tried it, but Elcomsoft released a product they claim is capable of decrypting backups, for forensics purposes. Maybe not as cool as engineering a solution yourself, but it might be faster.
What you can do is
RelationActiveEnum ae = Enum.valueOf(RelationActiveEnum.class,
RelationActiveEnum.ACTIVE.name();
or
RelationActiveEnum ae = RelationActiveEnum.valueOf(
RelationActiveEnum.ACTIVE.name();
or
// not recommended as the ordinal might not match the value
RelationActiveEnum ae = RelationActiveEnum.values()[
RelationActiveEnum.ACTIVE.value];
By if you want to lookup by a field of an enum you need to construct a collection such as a List, an array or a Map.
public enum RelationActiveEnum {
Invited(0),
Active(1),
Suspended(2);
private final int code;
private RelationActiveEnum(final int code) {
this.code = code;
}
private static final Map<Integer, RelationActiveEnum> BY_CODE_MAP = new LinkedHashMap<>();
static {
for (RelationActiveEnum rae : RelationActiveEnum.values()) {
BY_CODE_MAP.put(rae.code, rae);
}
}
public static RelationActiveEnum forCode(int code) {
return BY_CODE_MAP.get(code);
}
}
allows you to write
String name = RelationActiveEnum.forCode(RelationActiveEnum.ACTIVE.code).name();
If you already have the string, you can use this function:
bool isNumber( const string& s )
{
bool hitDecimal=0;
for( char c : s )
{
if( c=='.' && !hitDecimal ) // 2 '.' in string mean invalid
hitDecimal=1; // first hit here, we forgive and skip
else if( !isdigit( c ) )
return 0 ; // not ., not
}
return 1 ;
}
Another possible solution I came up with was:
re.sub(r'([uU]+(.)?\s)',' you ', text)
this in your callback function refers to the clicked element.
$(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
A class can be used several times, while an ID can only be used once, so you should use classes for items that you know you're going to use a lot. An example would be if you wanted to give all the paragraphs on your webpage the same styling, you would use classes.
Standards specify that any given ID name can only be referenced once within a page or document. Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.
Note: my answer is about really deleting the tables and other database objects; for deleting all data in the tables, i.e. truncating all tables, Endre Both has provided a similarily well-executed (direct execution) statement a month later.
For the cases where you can’t just DROP SCHEMA public CASCADE;
, DROP OWNED BY current_user;
or something, here’s a stand-alone SQL script I wrote, which is transaction-safe (i.e. you can put it between BEGIN;
and either ROLLBACK;
to just test it out or COMMIT;
to actually do the deed) and cleans up “all” database objects… well, all those used in the database our application uses or I could sensibly add, which is:
CHECK
, UNIQUE
)VIEW
s (normal or materialised)public
or DB-internal) schemata “we” own: the script is useful when run as “not a database superuser”; a superuser can drop all schemata (the really important ones are still explicitly excluded, though)Not dropped are (some deliberate; some only because I had no example in our DB):
public
schema (e.g. for extension-provided stuff in them)This is really useful for the cases when the dump you want to restore is of a different database schema version (e.g. with Debian dbconfig-common
, Flyway or Liquibase/DB-Manul) than the database you want to restore it into.
I’ve also got a version which deletes “everything except two tables and what belongs to them” (a sequence, tested manually, sorry, I know, boring) in case someone is interested; the diff is small. Contact me or check this repo if interested.
-- Copyright © 2019, 2020
-- mirabilos <[email protected]>
--
-- Provided that these terms and disclaimer and all copyright notices
-- are retained or reproduced in an accompanying document, permission
-- is granted to deal in this work without restriction, including un-
-- limited rights to use, publicly perform, distribute, sell, modify,
-- merge, give away, or sublicence.
--
-- This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
-- the utmost extent permitted by applicable law, neither express nor
-- implied; without malicious intent or gross negligence. In no event
-- may a licensor, author or contributor be held liable for indirect,
-- direct, other damage, loss, or other issues arising in any way out
-- of dealing in the work, even if advised of the possibility of such
-- damage or existence of a defect, except proven that it results out
-- of said person’s immediate fault when using the work as intended.
-- -
-- Drop everything from the PostgreSQL database.
DO $$
DECLARE
q TEXT;
r RECORD;
BEGIN
-- triggers
FOR r IN (SELECT pns.nspname, pc.relname, pt.tgname
FROM pg_catalog.pg_trigger pt, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pt.tgrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pt.tgisinternal=false
) LOOP
EXECUTE format('DROP TRIGGER %I ON %I.%I;',
r.tgname, r.nspname, r.relname);
END LOOP;
-- constraints #1: foreign key
FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pcon.contype='f'
) LOOP
EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
r.nspname, r.relname, r.conname);
END LOOP;
-- constraints #2: the rest
FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pcon.contype<>'f'
) LOOP
EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
r.nspname, r.relname, r.conname);
END LOOP;
-- indices
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='i'
) LOOP
EXECUTE format('DROP INDEX %I.%I;',
r.nspname, r.relname);
END LOOP;
-- normal and materialised views
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind IN ('v', 'm')
) LOOP
EXECUTE format('DROP VIEW %I.%I;',
r.nspname, r.relname);
END LOOP;
-- tables
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='r'
) LOOP
EXECUTE format('DROP TABLE %I.%I;',
r.nspname, r.relname);
END LOOP;
-- sequences
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='S'
) LOOP
EXECUTE format('DROP SEQUENCE %I.%I;',
r.nspname, r.relname);
END LOOP;
-- extensions (only if necessary; keep them normally)
FOR r IN (SELECT pns.nspname, pe.extname
FROM pg_catalog.pg_extension pe, pg_catalog.pg_namespace pns
WHERE pns.oid=pe.extnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
) LOOP
EXECUTE format('DROP EXTENSION %I;', r.extname);
END LOOP;
-- aggregate functions first (because they depend on other functions)
FOR r IN (SELECT pns.nspname, pp.proname, pp.oid
FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns, pg_catalog.pg_aggregate pagg
WHERE pns.oid=pp.pronamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pagg.aggfnoid=pp.oid
) LOOP
EXECUTE format('DROP AGGREGATE %I.%I(%s);',
r.nspname, r.proname,
pg_get_function_identity_arguments(r.oid));
END LOOP;
-- routines (functions, aggregate functions, procedures, window functions)
IF EXISTS (SELECT * FROM pg_catalog.pg_attribute
WHERE attrelid='pg_catalog.pg_proc'::regclass
AND attname='prokind' -- PostgreSQL 11+
) THEN
q := 'CASE pp.prokind
WHEN ''p'' THEN ''PROCEDURE''
WHEN ''a'' THEN ''AGGREGATE''
ELSE ''FUNCTION''
END';
ELSIF EXISTS (SELECT * FROM pg_catalog.pg_attribute
WHERE attrelid='pg_catalog.pg_proc'::regclass
AND attname='proisagg' -- PostgreSQL =10
) THEN
q := 'CASE pp.proisagg
WHEN true THEN ''AGGREGATE''
ELSE ''FUNCTION''
END';
ELSE
q := '''FUNCTION''';
END IF;
FOR r IN EXECUTE 'SELECT pns.nspname, pp.proname, pp.oid, ' || q || ' AS pt
FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns
WHERE pns.oid=pp.pronamespace
AND pns.nspname NOT IN (''information_schema'', ''pg_catalog'', ''pg_toast'')
' LOOP
EXECUTE format('DROP %s %I.%I(%s);', r.pt,
r.nspname, r.proname,
pg_get_function_identity_arguments(r.oid));
END LOOP;
-- non-default schemata we own; assume to be run by a not-superuser
FOR r IN (SELECT pns.nspname
FROM pg_catalog.pg_namespace pns, pg_catalog.pg_roles pr
WHERE pr.oid=pns.nspowner
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast', 'public')
AND pr.rolname=current_user
) LOOP
EXECUTE format('DROP SCHEMA %I;', r.nspname);
END LOOP;
-- voilà
RAISE NOTICE 'Database cleared!';
END; $$;
Tested, except later additions (extensions
contributed by Clément Prévost), on PostgreSQL 9.6 (jessie-backports
). Aggregate removal tested on 9.6 and 12.2, procedure removal tested on 12.2 as well. Bugfixes and further improvements welcome!
ES6
[...select.options].filter(option => option.selected).map(option => option.value)
Where select
is a reference to the <select>
element.
To break it down:
[...select.options]
takes the Array-like list of options and destructures it so that we can use Array.prototype methods on it (Edit: also consider using Array.from()
)filter(...)
reduces the options to only the ones that are selectedmap(...)
converts the raw <option>
elements into their respective valuesAnother interesting approach would be to use when
:
when(a) {
true -> b
false -> c
}
Can be quite handy in some more complex scenarios. And honestly, it's more readable for me than if ... else ...
You can use the action()
helper to generate an URL to your route:
<form method="post" action="{{ action('WelcomeController@log_in') }}" accept-charset="UTF-8">
Note that the Laravel 5 default installation already comes with views and controllers for the whole authentication process. Just go to /home
on a fresh install and you should get redirected to a login page.
Also make sure to read the Authentication section in the docs
The error you're getting now (TokenMismatchException
) is because Laravel has CSRF protection out of the box
To make use of it (and make the error go away) add a hidden field to your form:
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
Alternatively you can also disable CSRF protection by removing 'App\Http\Middleware\VerifyCsrfToken'
from the $middleware
array in app/Http/Kernel.php
when you are using POST method in HTML forms, you need to catch the data from req.body in the server side i.e. Node.js. and also add
var bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({extended: false}));
OR
use method='GET' in HTML and and catch the data by req.query in the server side i.e. Node.js
It looks like this question has a number of answers already, but I'll weigh in with mine since I haven't seen any that address the issue I had.
I had this error as well on a brand new github repository. It turns out the user I was pushing from did not have push access. For some reason, this results in an "ERROR: repository not found" error instead of some sort of access error.
Anyway, I hope this helps the poor soul who runs into the same issue.
This will also work
SELECT NAME
FROM GEO_LOCATION
WHERE MODIFY_ON BETWEEN SYSDATE() - INTERVAL 2 HOUR AND SYSDATE()
padde's solution is right, but risen up another problem i.e.
As said by Adam (the questioner) that it is showing empty popup. Here is the complete and working solution
<html>
<head>
<script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.0.5"></script>
<link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.0.5" media="screen" />
</head>
<body>
<a href="#divForm" id="btnForm">Load Form</a>
<div id="divForm" style="display:none">
<form action="tbd">
File: <input type="file" /><br /><br />
<input type="submit" />
</form>
</div>
<script type="text/javascript">
$(function() {
$("#btnForm").fancybox({
'onStart': function() { $("#divForm").css("display","block"); },
'onClosed': function() { $("#divForm").css("display","none"); }
});
});
</script>
</body>
</html>
In my case I didn't run this command
sudo apt-get install php7.4-fpm
All the answers above about reload()
or imp.reload()
are deprecated.
reload()
is no longer a builtin function in python 3 and imp.reload()
is marked deprecated (see help(imp)
).
It's better to use importlib.reload()
instead.
Most of the answers above search by space, not whitespace. @georg's answer is good. I have a slightly different version.
s.trim().split(/\s(.*)/).splice(0,2)
I'm not sure how to tell which is most efficient as the regexp in mine is a lot simpler, but it has the extra splace.
(@georg's for reference is s.split(/(?<=^\S+)\s/)
)
The question doesn't specify how to handle no whitespace or all whitespace, leading or trailing whitespace or an empty string, and our results differ subtly in those cases.
I'm writing this for a parser that needs to consume the next word, so I prefer my definition, though @georg's may be better for other use cases.
input. mine @georg
'aaa bbb' ['aaa','bbb'] ['aaa','bbb']
'aaa bbb ccc' ['aaa','bbb ccc'] ['aaa','bbb ccc']
'aaa ' [ 'aaa' ] [ 'aaa', '' ]
' ' [ '' ] [ ' ' ]
'' [''] ['']
' aaa' ['aaa'] [' aaa']
Out of all these factors,it can be concluded that concept Class is highly suitable to represent real world objects rather than "Structures".Largely because OOP concepts used in class are highly practical in explaining real world scenarios therefore easier to merge them to reality.For an example,default inheritance is public for structs but if we apply this rule for real world,it's ridiculous.But in a class default inheritance is private which is more realistic.
Anyways,what i need to justify is Class is a much broader,real world applicable concept whereas Structure is a primitive Concept with poor internal organization(Eventhough struct follows OOP concepts,they have a poor meaning)
Here is a concise way using lambdas and JDK 8 Supplier to fit everything in the outer try:
try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
PreparedStatement stmt = ((Supplier<PreparedStatement>)() -> {
try {
PreparedStatement s = con.prepareStatement("SELECT userid, name, features FROM users WHERE userid = ?");
s.setInt(1, userid);
return s;
} catch (SQLException e) { throw new RuntimeException(e); }
}).get();
ResultSet resultSet = stmt.executeQuery()) {
}
You should use the equals
method since this is implemented to perform the comparison you want. toString()
itself uses an iterator just like equals
but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString
is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).
Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString
and equals
behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.
See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
boolean equals(Object o)
Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.
Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap
which is used by classes such as HashMap
:
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* <p>This implementation first checks if the specified object is this map;
* if so it returns <tt>true</tt>. Then, it checks if the specified
* object is a map whose size is identical to the size of this map; if
* not, it returns <tt>false</tt>. If so, it iterates over this map's
* <tt>entrySet</tt> collection, and checks that the specified map
* contains each mapping that this map contains. If the specified map
* fails to contain such a mapping, <tt>false</tt> is returned. If the
* iteration completes, <tt>true</tt> is returned.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> m = (Map<K,V>) o;
if (m.size() != size())
return false;
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
toString
fails miserably when comparing a TreeMap
and HashMap
though equals
does compare contents correctly.
Code:
public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");
System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
+ map.toString().equals(map2.toString()));
System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}
Output:
Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}
Have you tried this?:
countif(rangethatyouhave, not(""))
I don't think you need to open the code editor, you can just do it in the spreadsheet itself.
With a recent nightly, you can do this:
let my_int = from_str::<int>(&*my_string);
What's happening here is that String
can now be dereferenced into a str
. However, the function wants an &str
, so we have to borrow again. For reference, I believe this particular pattern (&*
) is called "cross-borrowing".
Do you need a type attribute at all? If you're using HTML5, no. Otherwise, yes. HTML 4.01 and XHTML 1.0 specifies the type
attribute as required while HTML5 has it as optional, defaulting to text/javascript
. HTML5 is now widely implemented, so if you use the HTML5 doctype, <script>...</script>
is valid and a good choice.
As to what should go in the type attribute, the MIME type application/javascript
registered in 2006 is intended to replace text/javascript
and is supported by current versions of all the major browsers (including Internet Explorer 9). A quote from the relevant RFC:
This document thus defines text/javascript and text/ecmascript but marks them as "obsolete". Use of experimental and unregistered media types, as listed in part above, is discouraged. The media types,
* application/javascript * application/ecmascript
which are also defined in this document, are intended for common use and should be used instead.
However, IE up to and including version 8 doesn't execute script inside a <script>
element with a type
attribute of either application/javascript
or application/ecmascript
, so if you need to support old IE, you're stuck with text/javascript
.
File format
This tool parses .CRX version 2 format documented by Google. In general, .CRX file format consist of few parts:
Magic header
Version of file format
Public Key information and a package signature
Zipped contents of the extension source code
Magic header is a signature of the file telling that this file is Chrome Extension. Using this header the operating system can determine the actual type of the file (MIME type is application/x-chrome-extension), and how should it be treaten (is it executable? is it a text file?). Then the window system can show beautiful icon to the user.
In .CRX files the magic header has a constant value Cr24 or 0x43723234.
The version is provided by vendor. The version bytes are 0x02000000.
The next part of the file contains the length of the public key information and the length of a digital signature.
All .CRX packages distributed via Chrome WebStore should have public key information and digital signature in order to make possible for browser to check that the package has been transmitted without modifications and that no additions or replacements were made.
After all of the header stuff, typically ending up on 307'th byte, comes the code of extension, stored as zip-archive. So the remainder of the .crx file is the well-known .zip archive.
.crx file opened in the hex editor called HexFiend (on Mac) The header part of a .crx file selected on the picture above. Obviously, you can extract the remaining .zip archive "by hand" using any simple hex editor. In this example, we use handy HexFiend editor on Mac.
The CRX Extractor loads a file provided, checks a magic header, version and trims the file, so only .zip archive remains. Then it returns obtained .zip archive to user.
First of all, for initializing a container you cannot use a primitive type (i.e. int
; you can use int[]
but as you want just an array of integers, I see no use in that). Instead, you should use Integer
, as follows:
ArrayList<Integer> arl = new ArrayList<Integer>();
For adding elements, just use the add
function:
arl.add(1);
arl.add(22);
arl.add(-2);
Last, but not least, for printing the ArrayList
you may use the build-in functionality of toString()
:
System.out.println("Arraylist contains: " + arl.toString());
If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :
int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));
I suggest reading first on Java Containers, before starting to work with them.
Program to find the longest substring which is palindrome from a given string.
package source;
import java.util.ArrayList;
public class LongestPalindrome
{
//Check the given string is palindrome by
public static boolean isPalindrome (String s)
{
StringBuffer sb = new StringBuffer(s);
if(s.equalsIgnoreCase(sb.reverse().toString()))
return true;
else
return false;
}
public static void main(String[] args)
{
//String / word without space
String str = "MOMABCMOMOM"; // "mom" //abccbabcd
if(str.length() > 2 )
{
StringBuffer sb = new StringBuffer();
ArrayList<String> allPalindromeList = new ArrayList<>();
for(int i=0; i<str.length(); i++)
{
for(int j=i; j<str.length(); j++)
{
sb.append(str.charAt(j));
if( isPalindrome(sb.toString()) ) {
allPalindromeList.add(sb.toString());
}
}
//clear the stringBuffer
sb.delete(0, sb.length());
}
int maxSubStrLength = -1;
int indexMaxSubStr = -1;
int index = -1;
for (String subStr : allPalindromeList) {
++index;
if(maxSubStrLength < subStr.length()) {
maxSubStrLength = subStr.length();
indexMaxSubStr = index;
}
}
if(maxSubStrLength > 2)
System.out.println("Maximum Length Palindrome SubString is : "+allPalindromeList.get(indexMaxSubStr));
else
System.out.println("Not able to find a Palindrome who is three character in length!!");
}
}
}
Use
var x = 0.1*0.2;
x =Math.round(x*Math.pow(10,2))/Math.pow(10,2);
As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList
)
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country(string _name)
{
Cities = new List<City>();
Name = _name;
}
}
List<Country> countries = new List<Country> { new Country("UK"),
new Country("Australia"),
new Country("France") };
var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;
comboBox1.DataSource = bindingSource1.DataSource;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";
To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;
.
If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource
implements IBindingList
; one such structure is BindingList<T>
.
Tip: make sure that you are binding the DisplayMember
to a Property on the class and not a public field. If you class uses public string Name { get; set; }
it will work but if it uses public string Name;
it will not be able to access the value and instead will display the object type for each line in the combo box.
Here is my answer when you want to animate it and start fading it out after couple of seconds. I used opacity because first of all i didn't want to fade it out completely, second, it does not go back and force after many scrolls.
$(window).scroll(function () {
var elem = $('div');
setTimeout(function() {
elem.css({"opacity":"0.2","transition":"2s"});
},4000);
elem.css({"opacity":"1","transition":"1s"});
});
Marc Gravell's answer is very complete, but I thought I'd add something about this from the user's point of view, as well...
The main difference, from a user's perspective, is that, when you use IQueryable<T>
(with a provider that supports things correctly), you can save a lot of resources.
For example, if you're working against a remote database, with many ORM systems, you have the option of fetching data from a table in two ways, one which returns IEnumerable<T>
, and one which returns an IQueryable<T>
. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25.
If you do:
IEnumerable<Product> products = myORM.GetProducts();
var productsOver25 = products.Where(p => p.Cost >= 25.00);
What happens here, is the database loads all of the products, and passes them across the wire to your program. Your program then filters the data. In essence, the database does a SELECT * FROM Products
, and returns EVERY product to you.
With the right IQueryable<T>
provider, on the other hand, you can do:
IQueryable<Product> products = myORM.GetQueryableProducts();
var productsOver25 = products.Where(p => p.Cost >= 25.00);
The code looks the same, but the difference here is that the SQL executed will be SELECT * FROM Products WHERE Cost >= 25
.
From your POV as a developer, this looks the same. However, from a performance standpoint, you may only return 2 records across the network instead of 20,000....
All operational steps(finding java, parent dir, editing file,...) one solution
zFileProfile="/etc/profile"
zJavaHomePath=$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)
echo $zJavaHomePath
echo "export JAVA_HOME=\"${zJavaHomePath}\"" >> $zFileProfile
echo "export PATH=\$PATH:\$JAVA_HOME/bin" >> $zFileProfile
Result:
# tail -2 $zFileProfile
export JAVA_HOME="/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"
export PATH=$PATH:$JAVA_HOME/bin
Explanation:
1) Let's break the full command into pieces
$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)
2) Find java path from java command
# $(which java)
"/usr/bin/java"
3) Get relative path from symbolic path
# readlink -ze /usr/bin/java
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java"
4) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java
# readlink -ze /usr/bin/java | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin"
5) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/
# readlink -ze /usr/bin/java | xargs -0 dirname | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"
use this: data.peek() != '\0'
I've been searching for an hour until finaly this helped!
If none of them are working then check this.. say if you have x and y arrays of data along respective axis. Then check in which cell(jupyter) you have initialized x and y to empty. This is because , maybe you are appending data to x and y without re-initializing them. So plot has old data too. So check that..
If code elegance ranks higher than the performance hit of regex, then
'1234567'.match(/^(.*)(.{3})/).slice(1).join(',')
=> "1234,567"
There's a lot of room to further modify the regex to be more precise.
If join()
doesn't work then you might need to use map
with a closure, at which point the other answers here may be less bytes and line noise.
here is a better answer found through Git docs.
This shows what the heroku remote is:
$ git remote get-url heroku
Found it here: https://git-scm.com/docs/git-remote Also in that document is a set-url, if you need to change it.
I ended up following @vicenteherrera's approach, with some tweaks (that are possibly bootstrap 3 specific).
Basically; we can't break tr
s, or td
s because they're not block-level elements. So we embed div
s into each, and apply our page-break-*
rules against the div
. Secondly; we add some padding to the top of each of these divs, to compensate for any styling artifacts.
<style>
@media print {
/* avoid cutting tr's in half */
th div, td div {
margin-top:-8px;
padding-top:8px;
page-break-inside:avoid;
}
}
</style>
<script>
$(document).ready(function(){
// Wrap each tr and td's content within a div
// (todo: add logic so we only do this when printing)
$("table tbody th, table tbody td").wrapInner("<div></div>");
})
</script>
The margin and padding adjustments were necessary to offset some kind of jitter that was being introduced (by my guess - from bootstrap). I'm not sure that I'm presenting any new solution from the other answers to this question, but I figure maybe this will help someone.
The Installed JREs is used for what JREs to execute for your downstream Java projects and servers. As far as what JVM or JRE that is used to execute Eclipse process (workbench) itself that is controlled by your environment, history and eclipse.exe binary. So eclipse.exe itself decides what JRE Eclipse will execute itself with, not installed JREs preferences since those are not read until OSGi framework is up and running which is loaded after the JVM/JRE is picked.
So for new workspaces, Eclipse is going to use its currently executing JRE to populate the JRE prefs.
The best way I know how is to force eclipse.exe to use the JRE that you tell it via the -vm
switch. So in your eclipse.ini do this:
-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502
-vm
/path/to/exactly/what/jre/you/want/as/default/javaw.exe
...
var pdf = MyPdf.pdf;
window.open(pdf);
This will open the pdf document in a full window from JavaScript
A function to open windows would look like this:
function openPDF(pdf){
window.open(pdf);
return false;
}
You can also do it through the JavaScript:
(document.querySelector("form_selector") as HTMLFormElement).reset();
This is because your data sending column type is integer and your are sending a string value to it.
So, the following way worked for me. Try with this one.
$insertQuery = "INSERT INTO workorders VALUES (
null,
'$priority',
'$requestType',
'$purchaseOrder',
'$nte',
'$jobSiteNumber'
)";
Don't use 'null'
. use it as null
without single quotes.
My solution is to use these 2 mappings:
map <leader>n <Esc><Esc>0qq
map <leader>m q:'<,'>-1normal!@q<CR><Down>
How to use them:
V12j
<leader>n
<leader>m
To make another edit you don't need to make the selection again. Just press <leader>n
, make your edit and press <leader>m
to apply.
How this works:
<Esc><Esc>0qq
Exit the visual selection, go to the beginning of the line and start recording a macro.
q
Stop recording the macro.
:'<,'>-1normal!@q<CR>
From the start of the visual selection to the line before the end, play the macro on each line.
<Down>
Go back down to the last line.
You can also just map the same key but for different modes:
vmap <leader>m <Esc><Esc>0qq
nmap <leader>m q:'<,'>-1normal!@q<CR><Down>
Although this messes up your ability to make another edit. You'll have to re-select your lines.
REPLACE INTO
pros:
cons:
too slow.
auto-increment key will CHANGE(increase by 1) if there is entry matches unique key
or primary key
, because it deletes the old entry then insert new one.
INSERT IGNORE
pros:
cons:
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
some other errors/warnings will be ignored such as data conversion error.
INSERT ... ON DUPLICATE KEY UPDATE
pros:
cons:
looks relatively complex if you just want to insert not update.
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
unique key
or primary key
?As mentioned in the comment below by @toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode
config after version 5.1" if you are using innodb
as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.
I think this way is more simple:
User resultUser = users.stream()
.filter(user -> user.getId() > 0)
.findFirst().get();
http://docs.python.org/howto/unicode.html#the-unicode-type
str = unicode(str, errors='replace')
or
str = unicode(str, errors='ignore')
Note: This will strip out (ignore) the characters in question returning the string without them.
For me this is ideal case since I'm using it as protection against non-ASCII input which is not allowed by my application.
Alternatively: Use the open method from the codecs
module to read in the file:
import codecs
with codecs.open(file_name, 'r', encoding='utf-8',
errors='ignore') as fdata:
one elegant way to do this is to represent items in the list as string holding a dot separated list of parents, and finally a value:
server.port=90
server.hostname=localhost
client.serverport=90
client.database.port=1234
client.database.host=localhost
When assembling a tree, you would end up with something like:
server:
port: 90
hostname: localhost
client:
serverport=1234
database:
port: 1234
host: localhost
I have a configuration library that implements this override configuration (tree) from command line arguments (list). The algorithm to add a single item to the list to a tree is here.
in Ruby ...
i=true
while(i)
i=false
a=2
end
puts defined?(a) // returns true
//ICO , DI ,10 years back , this was they way:
public class AuditDAOImpl implements Audit{
//dependency
AuditDAO auditDAO = null;
//Control of the AuditDAO is with AuditDAOImpl because its creating the object
public AuditDAOImpl () {
this.auditDAO = new AuditDAO ();
}
}
Now with Spring 3,4 or latest its like below
public class AuditDAOImpl implements Audit{
//dependency
//Now control is shifted to Spring. Container find the object and provide it.
@Autowired
AuditDAO auditDAO = null;
}
Overall the control is inverted from old concept of coupled code to the frameworks like Spring which makes the object available. So that's IOC as far as I know and Dependency injection as you know when we inject the dependent object into another object using Constructor or setters . Inject basically means passing it as an argument. In spring we have XML & annotation based configuration where we define bean object and pass the dependent object with Constructor or setter injection style.
Using one line to convert the dates to preferred format:
nzd$date <- format(as.Date(nzd$date, format="%d/%m/%Y"),"%Y/%m/%d")
you have to name your checkboxes accordingly:
<input type="checkbox" name="check_list[]" value="…" />
you can then access all checked checkboxes with
// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
// do something
}
ps. make sure to properly escape your output (htmlspecialchars()
)
Worked for me in Kotlin,
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.
JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.
Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.
Minor variation on Geoff's answer.
New Data in Array:
Sub AddDataRow(tableName As String, NewData As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Iterate through the last row and populate it with the entries from values()
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
Next col
End Sub
New Data in Horizontal Range:
Sub AddDataRow(tableName As String, NewData As Range)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last table row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Copy NewData to new table record
Set lastRow = table.ListRows(table.ListRows.Count).Range
lastRow.Value = NewData.Value
End Sub
Your issue is that you have re-defined list
as a variable previously in your code. This means that when you do type(tmpDict[key])==list
if will return False
because they aren't equal.
That being said, you should instead use isinstance(tmpDict[key], list)
when testing the type of something, this won't avoid the problem of overwriting list
but is a more Pythonic way of checking the type.
you should not use swap to copy vectors, it would change the "original" vector.
pass the original as a parameter to the new instead.
An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.
If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.
A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to be shared by all, but avoids the problem described in #2.
The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.
Apache CXF is an example the pattern in #2.
you can try this way in Colab
!git clone https://github.com/UKPLab/sentence-transformers.git
!pip install -e /content/sentence-transformers
import sentence_transformers
If both repositories have same kind of files (like two Rails repositories for different projects), you can fetch data of the secondary repository to your current repository:
git fetch git://repository.url/repo.git master:branch_name
and then merge it to current repository:
git merge --allow-unrelated-histories branch_name
If your Git version is smaller than 2.9, remove --allow-unrelated-histories
.
After this, conflicts may occur. You can resolve them for example with git mergetool
. kdiff3
can be used solely with keyboard, so 5 conflict file takes when reading the code just few minutes.
Remember to finish the merge:
git commit
Depends on what you want to do. If you want to use the two arguments as input files, you can just pass them in and then use <>
to read their contents.
If they have a different meaning, you can use GetOpt::Std
and GetOpt::Long
to process them easily. GetOpt::Std
supports only single-character switches and GetOpt::Long
is much more flexible. From GetOpt::Long
:
use Getopt::Long;
my $data = "file.dat";
my $length = 24;
my $verbose;
$result = GetOptions ("length=i" => \$length, # numeric
"file=s" => \$data, # string
"verbose" => \$verbose); # flag
Alternatively, @ARGV
is a special variable that contains all the command line arguments. $ARGV[0]
is the first (ie. "string1"
in your case) and $ARGV[1]
is the second argument. You don't need a special module to access @ARGV
.
I had a similar problem.
When I entered
<activity android:name="MyActivity" android:screenOrientation="landscape"></activity>
In the manifest file this caused that activity to display in landscape. However when I returned to previous activities they displayed in lanscape even though they were set to portrait. However by adding
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
immediately after the OnCreate section of the target activity resolved the problem. So I now use both methods.
You can also try this way
<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
jquery
$('.select_continent').click(function () {
alert($(this).data('value'));
});
Good luck !!!!
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)
If you need to query on the list, then store it in a table.
If you always want the list, you could store it as a delimited list in a column. Even in this case, unless you have VERY specific reasons not to, store it in a lookup table.
you can also make it overflow: auto
and give a maximum fixed height and width that way, when the text or whatever is in there, overflows it'll show only the required scrollbar
Take a look at limits.h. You can find the specific values for your compiler. INT_MIN and INT_MAX will be of interest.
You can combine the columns without using macros. Type the following function in the formula bar:
=IF(ROW()<=COUNTA(A:A),INDEX(A:A,ROW()),IF(ROW()<=COUNTA(A:B),INDEX(B:B,ROW()-COUNTA(A:A)),IF(ROW()>COUNTA(A:C),"",INDEX(C:C,ROW()-COUNTA(A:B)))))
The statement uses 3 IF functions, because it needs to combine 3 columns:
React has few lifecycle methods which help in these situations, the lists including but not limited to getInitialState, getDefaultProps, componentWillMount, componentDidMount etc.
In your case and the cases which needs to interact with the DOM elements, you need to wait till the dom is ready, so use componentDidMount as below:
/** @jsx React.DOM */
var List = require('../list');
var ActionBar = require('../action-bar');
var BalanceBar = require('../balance-bar');
var Sidebar = require('../sidebar');
var AppBase = React.createClass({
componentDidMount: function() {
ReactDOM.findDOMNode(this).height = /* whatever HEIGHT */;
},
render: function () {
return (
<div className="wrapper">
<Sidebar />
<div className="inner-wrapper">
<ActionBar title="Title Here" />
<BalanceBar balance={balance} />
<div className="app-content">
<List items={items} />
</div>
</div>
</div>
);
}
});
module.exports = AppBase;
Also for more information about lifecycle in react you can have look the below link: https://facebook.github.io/react/docs/state-and-lifecycle.html
You could modify it simply like this
GradientDrawable bgShape = (GradientDrawable)btn.getBackground();
bgShape.setColor(Color.BLACK);
Well, by IP is faster.
Basically, when you call by server name, it is converted to original IP.
But it would be difficult to memorize an IP, for this reason the domain name was created.
Personally I use http://localhost
instead of http://127.0.0.1
or http://username
.
Assumption 1: You're attempting to convert a date to a timestamp, however since a date covers a 24 hour period, there isn't a single timestamp that represents that date. I'll assume that you want to represent the timestamp of that date at midnight (00:00:00.000).
Assumption 2: The date you present is not associated with a particular time zone, however you want to determine the offset from a particular time zone (UTC). Without knowing the time zone the date is in, it isn't possible to calculate a timestamp for a specific time zone. I'll assume that you want to treat the date as if it is in the local system time zone.
First, you can convert the date instance into a tuple representing the various time components using the timetuple()
member:
dtt = d.timetuple() # time.struct_time(tm_year=2011, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)
You can then convert that into a timestamp using time.mktime
:
ts = time.mktime(dtt) # 1293868800.0
You can verify this method by testing it with the epoch time itself (1970-01-01), in which case the function should return the timezone offset for the local time zone on that date:
d = datetime.date(1970,1,1)
dtt = d.timetuple() # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
ts = time.mktime(dtt) # 28800.0
28800.0
is 8 hours, which would be correct for the Pacific time zone (where I'm at).
SimpleDateFormat.format(...)
takes a Date as parameter and format Date to String. So you need have a look API carefully
A small change to your algorithm:
filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')
while 1:
lines = f.readlines()
if not lines:
break
line_iter= iter(lines) # here
for line in line_iter: # and here
print line
if (line[:5] == "anim "):
print 'next() '
ne = line_iter.next() # and here
print ' ne ',ne,'\n'
break
f.close()
However, using the pairwise
function from itertools
recipes:
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
you can change your loop into:
for line, next_line in pairwise(f): # iterate over the file directly
print line
if line.startswith("anim "):
print 'next() '
print ' ne ', next_line, '\n'
break
If you should remove all values from list a, which are present in list b.
def list_diff(a, b):
r = []
for i in a:
if i not in b:
r.append(i)
return r
list_diff([1,2,2], [1])
Result: [2,2]
or
def list_diff(a, b):
return [x for x in a if x not in b]
Here's one way:
CString str;
str.Format("%d", 5);
In your case, try _T("%d")
or L"%d"
rather than "%d"
In Python 3, print
became a function. This means that you need to include parenthesis now like mentioned below:
print("Hello World")
In your code you are assigning a native method to a property of custom object.
When you call support.animationFrame(function () {})
, it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window
.
So the correct usage here is support.animationFrame.call(window, function() {});
.
The same happens with alert too:
var myObj = {
myAlert : alert //copying native alert to an object
};
myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window
Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame: _raf ? _raf.bind(window) : null
};
You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.
It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1
E.g.:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM
Where mF_9.B5f-4.1JqM is your OAuth access token.
This won't show custom events like those your script might create if it's a jquery plugin. for example :
jQuery(function($){
var ThingName="Something";
$("body a").live('click', function(Event){
var $this = $(Event.target);
$this.trigger(ThingName + ":custom-event-one");
});
$.on(ThingName + ":custom-event-one", function(Event){
console.log(ThingName, "Fired Custom Event: 1", Event);
})
});
The Event Panel under Scripts in chrome developer tools will not show you "Something:custom-event-one"
You appear to be trying to mix query expression syntax and "normal" lambda expression syntax. You can either use:
IEnumerable<SelectListItem> stores =
from store in database.Stores
where store.CompanyID == curCompany.ID
select new SelectListItem { Value = store.Name, Text = store.ID};
ViewBag.storeSelector = stores;
Or:
IEnumerable<SelectListItem> stores = database.Stores
.Where(store => store.CompanyID == curCompany.ID)
.Select(s => new SelectListItem { Value = s.Name, Text = s.ID});
ViewBag.storeSelector = stores;
You can't mix the two like you're trying to.
Correct output:
'{"data":[{"id":"1","reason":"hello\\nworld"},{"id":"2","reason":"it\\nworks"}]}'
function json_entities( $data = null )
{
//stripslashes
return str_replace( '\n',"\\"."\\n",
htmlentities(
utf8_encode( json_encode( $data) ) ,
ENT_QUOTES | ENT_IGNORE, 'UTF-8'
)
);
}
The .values()
method will return you a result of type ValuesQuerySet
which is typically what you need in most cases.
But if you wish, you could turn ValuesQuerySet
into a native Python list using Python list comprehension as illustrated in the example below.
result = Blog.objects.values() # return ValuesQuerySet object
list_result = [entry for entry in result] # converts ValuesQuerySet into Python list
return list_result
I find the above helps if you are writing unit tests and need to assert that the expected return value of a function matches the actual return value, in which case both expected_result
and actual_result
must be of the same type (e.g. dictionary).
actual_result = some_function()
expected_result = {
# dictionary content here ...
}
assert expected_result == actual_result
I had this issue too, and I have <mat-select>
element in my template, when I import the MatSelectModule into Module, it works, it doesn't make science, but stil hope it can help you.
import { MatSelectModule } from '@angular/material/select';
imports: [
BrowserModule,
BrowserAnimationsModule,
MatSidenavModule,
MatButtonModule,
MatIconModule,
MatToolbarModule,
MatFormFieldModule,
MatProgressSpinnerModule,
MatInputModule,
MatCardModule,
MatSelectModule
],
<div class="example-container">
<mat-form-field>
<input matInput placeholder="Input">
</mat-form-field>
<mat-form-field>
<textarea matInput placeholder="Textarea"></textarea>
</mat-form-field>
<mat-form-field>
<mat-select placeholder="Select">
<mat-option value="option">Option</mat-option>
</mat-select>
</mat-form-field>
</div>
In case of MySQL
or SQLite
the correct keyword is IFNULL
(not ISNULL
).
SELECT iar.Description,
IFNULL(iai.Quantity,0) as Quantity,
IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail',
iar.Compliance
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'
Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0
Sounds like a good job for regular expressions.
Laravel validation rules support regular expressions. Both 4.X and 5.X versions are supporting it :
This might help too:
You can annotate your bean with jaxb annotations.
@XmlRootElement
public class MyJaxbBean {
public String name;
public int age;
public MyJaxbBean() {} // JAXB needs this
public MyJaxbBean(String name, int age) {
this.name = name;
this.age = age;
}
}
and then your method would look like this:
@GET @Produces("application/json")
public MyJaxbBean getMyBean() {
return new MyJaxbBean("Agamemnon", 32);
}
There is a chapter in the latest documentation that deals with this:
https://jersey.java.net/documentation/latest/user-guide.html#json
I had the same problem, the WebBrowser was using an old version of IE, with some googling I came across the following code that makes a change into registry and makes the WebBrowser to use the lastest IE version possible:
public enum BrowserEmulationVersion
{
Default = 0,
Version7 = 7000,
Version8 = 8000,
Version8Standards = 8888,
Version9 = 9000,
Version9Standards = 9999,
Version10 = 10000,
Version10Standards = 10001,
Version11 = 11000,
Version11Edge = 11001
}
public static class WBEmulator
{
private const string InternetExplorerRootKey = @"Software\Microsoft\Internet Explorer";
public static int GetInternetExplorerMajorVersion()
{
int result;
result = 0;
try
{
RegistryKey key;
key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey);
if (key != null)
{
object value;
value = key.GetValue("svcVersion", null) ?? key.GetValue("Version", null);
if (value != null)
{
string version;
int separator;
version = value.ToString();
separator = version.IndexOf('.');
if (separator != -1)
{
int.TryParse(version.Substring(0, separator), out result);
}
}
}
}
catch (SecurityException)
{
// The user does not have the permissions required to read from the registry key.
}
catch (UnauthorizedAccessException)
{
// The user does not have the necessary registry rights.
}
return result;
}
private const string BrowserEmulationKey = InternetExplorerRootKey + @"\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
public static BrowserEmulationVersion GetBrowserEmulationVersion()
{
BrowserEmulationVersion result;
result = BrowserEmulationVersion.Default;
try
{
RegistryKey key;
key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
if (key != null)
{
string programName;
object value;
programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
value = key.GetValue(programName, null);
if (value != null)
{
result = (BrowserEmulationVersion)Convert.ToInt32(value);
}
}
}
catch (SecurityException)
{
// The user does not have the permissions required to read from the registry key.
}
catch (UnauthorizedAccessException)
{
// The user does not have the necessary registry rights.
}
return result;
}
public static bool SetBrowserEmulationVersion(BrowserEmulationVersion browserEmulationVersion)
{
bool result;
result = false;
try
{
RegistryKey key;
key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
if (key != null)
{
string programName;
programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
if (browserEmulationVersion != BrowserEmulationVersion.Default)
{
// if it's a valid value, update or create the value
key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
}
else
{
// otherwise, remove the existing value
key.DeleteValue(programName, false);
}
result = true;
}
}
catch (SecurityException)
{
// The user does not have the permissions required to read from the registry key.
}
catch (UnauthorizedAccessException)
{
// The user does not have the necessary registry rights.
}
return result;
}
public static bool SetBrowserEmulationVersion()
{
int ieVersion;
BrowserEmulationVersion emulationCode;
ieVersion = GetInternetExplorerMajorVersion();
if (ieVersion >= 11)
{
emulationCode = BrowserEmulationVersion.Version11;
}
else
{
switch (ieVersion)
{
case 10:
emulationCode = BrowserEmulationVersion.Version10;
break;
case 9:
emulationCode = BrowserEmulationVersion.Version9;
break;
case 8:
emulationCode = BrowserEmulationVersion.Version8;
break;
default:
emulationCode = BrowserEmulationVersion.Version7;
break;
}
}
return SetBrowserEmulationVersion(emulationCode);
}
public static bool IsBrowserEmulationSet()
{
return GetBrowserEmulationVersion() != BrowserEmulationVersion.Default;
}
}
You just need to create a class and put this code in it, then run the following code when the program starts:
if (!WBEmulator.IsBrowserEmulationSet())
{
WBEmulator.SetBrowserEmulationVersion();
}
VB.NET:
Imports Microsoft.Win32
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Security
Imports System.Text
Imports System.Threading.Tasks
Public Enum BrowserEmulationVersion
[Default] = 0
Version7 = 7000
Version8 = 8000
Version8Standards = 8888
Version9 = 9000
Version9Standards = 9999
Version10 = 10000
Version10Standards = 10001
Version11 = 11000
Version11Edge = 11001
End Enum
Public Class WBEmulator
Private Const InternetExplorerRootKey As String = "Software\Microsoft\Internet Explorer"
Public Shared Function GetInternetExplorerMajorVersion() As Integer
Dim result As Integer
result = 0
Try
Dim key As RegistryKey
key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey)
If key IsNot Nothing Then
Dim value As Object = If(key.GetValue("svcVersion", Nothing), key.GetValue("Version", Nothing))
Dim Version As String
Dim separator As Integer
Version = value.ToString()
separator = Version.IndexOf(".")
If separator <> -1 Then
Integer.TryParse(Version.Substring(0, separator), result)
End If
End If
Catch ex As SecurityException
'The user does Not have the permissions required to read from the registry key.
Catch ex As UnauthorizedAccessException
'The user does Not have the necessary registry rights.
Catch
End Try
GetInternetExplorerMajorVersion = result
End Function
Private Const BrowserEmulationKey = InternetExplorerRootKey + "\Main\FeatureControl\FEATURE_BROWSER_EMULATION"
Public Shared Function GetBrowserEmulationVersion() As BrowserEmulationVersion
Dim result As BrowserEmulationVersion
result = BrowserEmulationVersion.Default
Try
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
If key IsNot Nothing Then
Dim programName As String
Dim value As Object
programName = Path.GetFileName(Environment.GetCommandLineArgs()(0))
value = key.GetValue(programName, Nothing)
If value IsNot Nothing Then
result = CType(Convert.ToInt32(value), BrowserEmulationVersion)
End If
End If
Catch ex As SecurityException
'The user does Not have the permissions required to read from the registry key.
Catch ex As UnauthorizedAccessException
'The user does Not have the necessary registry rights.
Catch
End Try
GetBrowserEmulationVersion = result
End Function
Public Shared Function SetBrowserEmulationVersion(BEVersion As BrowserEmulationVersion) As Boolean
Dim result As Boolean = False
Try
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
If key IsNot Nothing Then
Dim programName As String = Path.GetFileName(Environment.GetCommandLineArgs()(0))
If BEVersion <> BrowserEmulationVersion.Default Then
'if it's a valid value, update or create the value
key.SetValue(programName, CType(BEVersion, Integer), RegistryValueKind.DWord)
Else
'otherwise, remove the existing value
key.DeleteValue(programName, False)
End If
result = True
End If
Catch ex As SecurityException
' The user does Not have the permissions required to read from the registry key.
Catch ex As UnauthorizedAccessException
' The user does Not have the necessary registry rights.
End Try
SetBrowserEmulationVersion = result
End Function
Public Shared Function SetBrowserEmulationVersion() As Boolean
Dim ieVersion As Integer
Dim emulationCode As BrowserEmulationVersion
ieVersion = GetInternetExplorerMajorVersion()
If ieVersion >= 11 Then
emulationCode = BrowserEmulationVersion.Version11
Else
Select Case ieVersion
Case 10
emulationCode = BrowserEmulationVersion.Version10
Case 9
emulationCode = BrowserEmulationVersion.Version9
Case 8
emulationCode = BrowserEmulationVersion.Version8
Case Else
emulationCode = BrowserEmulationVersion.Version7
End Select
End If
SetBrowserEmulationVersion = SetBrowserEmulationVersion(emulationCode)
End Function
Public Shared Function IsBrowserEmulationSet() As Boolean
IsBrowserEmulationSet = GetBrowserEmulationVersion() <> BrowserEmulationVersion.Default
End Function
End Class
You may use it like:
If Not WBEmulator.IsBrowserEmulationSet() Then
WBEmulator.SetBrowserEmulationVersion()
End If
Settings (Ctrl+Alt+s)--> Apprarance-->Override default fonts by(not recommended):
then change Size to 16+.
It is possible
You just also need to apply the color to 'tbody' element as that's the table body that's been causing our trouble by peeking underneath.table, tbody, tr, th, td{
background-color: rgba(0, 0, 0, 0.0) !important;
}
Internally, SQL Server treats an inline table valued function much like it would a view and treats a multi-statement table valued function similar to how it would a stored procedure.
When an inline table-valued function is used as part of an outer query, the query processor expands the UDF definition and generates an execution plan that accesses the underlying objects, using the indexes on these objects.
For a multi-statement table valued function, an execution plan is created for the function itself and stored in the execution plan cache (once the function has been executed the first time). If multi-statement table valued functions are used as part of larger queries then the optimiser does not know what the function returns, and so makes some standard assumptions - in effect it assumes that the function will return a single row, and that the returns of the function will be accessed by using a table scan against a table with a single row.
Where multi-statement table valued functions can perform poorly is when they return a large number of rows and are joined against in outer queries. The performance issues are primarily down to the fact that the optimiser will produce a plan assuming that a single row is returned, which will not necessarily be the most appropriate plan.
As a general rule of thumb we have found that where possible inline table valued functions should be used in preference to multi-statement ones (when the UDF will be used as part of an outer query) due to these potential performance issues.
A web-application is an application that is hosted on the internet. It can have a front-end or user-interface on a web-site.
Hope that helps.
Java 7 and up supports the Path
class (in java.nio package).
You can use this class to convert a string-path to one that works for your current OS.
Using:
Paths.get("\\folder\\subfolder").toString()
on a Unix machine, will give you /folder/subfolder
. Also works the other way around.
https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
You have to use parseInt() to convert
For eg.
var z = parseInt(x) + parseInt(y);
use parseFloat() if you want to handle float value.
Are you providing write input to the console ?
Scanner reader = new Scanner(System.in);
num = reader.nextDouble();
This is return double if you just enter number like 456. In case you enter a string or character instead,it will throw java.util.InputMismatchException when it tries to do num = reader.nextDouble() .
tnslsnr
is up but database is down.
For oracle novice it is not obvious that database may be down while connections are accepted.
I had to start up database manually like that
su - oracle
export ORACLE_SID=XE
sqlplus sys as sysdba
And then in sql console
startup
In my case i failed to startup but got another error message and found the source of a problem - i had to change host name and then database auto startup was functional again.
public function testAction()
{
$filter_a = array('like'=>'a%');
$filter_b = array('like'=>'b%');
echo(
(string)
Mage::getModel('catalog/product')
->getCollection()
->addFieldToFilter('sku',array($filter_a,$filter_b))
->getSelect()
);
}
Result:
WHERE (((e.sku like 'a%') or (e.sku like 'b%')))
with open("input", "rb") as input:
with open("output", "wb") as output:
while True:
data = input.read(1024)
if data == "":
break
output.write(data)
The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.
You can do (pre-Java 8):
List<Enum> enumValues = Arrays.asList(Enum.values());
or
List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));
Using Java 8 features, you can map each constant to its name:
List<String> enumNames = Stream.of(Enum.values())
.map(Enum::name)
.collect(Collectors.toList());
function addValueInObject(value, object, key) {
var addMoreOptions = eval('{"' + key + '":' + value + '}');
if(addMoreOptions != null) {
var textObject = JSON.stringify(object);
textObject = textObject.substring(1,textObject.length-1);
var AddElement = JSON.stringify(addMoreOptions);
object = eval('{' + textObject +','+ AddElement.substring(1,AddElement.length-1) + '}');
}
return object;
}
addValueInObject('sdfasfas', yourObject, 'keyname');
OR:
var obj = {'key':'value'};
obj.key2 = 'value2';
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!
Example: To be placed in AssemblyInfo.cs
[assembly: InternalsVisibleTo("OtherAssembly")]
Alternatively you could use a loop, keep the row number (counter should be the row number) and stop the loop when you find the first "ProjTemp".
Then it should look something like this:
Sub find()
Dim i As Integer
Dim firstTime As Integer
Dim bNotFound As Boolean
i = 1
bNotFound = True
Do While bNotFound
If Cells(i, 2).Value = "ProjTemp" Then
firstTime = i
bNotFound = false
End If
i = i + 1
Loop
End Sub
There are some more interesting ones along with related info.
This work for me:
public static void main(String[] args) {
Properties props = new Properties();
props.load(new FileInputStream("src/log4j.properties"));
PropertyConfigurator.configure(props);
Spans are inline, divs are block elements. i.e. spans are only as wide as their respective content. You can align the span inside the surrounding container (if it's a block container), but you can't align the content.
Span is primarily used for formatting purposes. If you want to arrange or position the contents, use div, p or some other block element.
It seems like a Android Runtime bug. There seems to be finalizer that runs in its separate thread and calls finalize() method on objects if they are not in the current frame of the stacktrace. For example following code(created to verify this issue) ended with the crash.
Let's have some cursor that do something in finalize method(e.g. SqlCipher ones, do close() which locks to the database that is currently in use)
private static class MyCur extends MatrixCursor {
public MyCur(String[] columnNames) {
super(columnNames);
}
@Override
protected void finalize() {
super.finalize();
try {
for (int i = 0; i < 1000; i++)
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And we do some long running stuff having opened cursor:
for (int i = 0; i < 7; i++) {
new Thread(new Runnable() {
@Override
public void run() {
MyCur cur = null;
try {
cur = new MyCur(new String[]{});
longRun();
} finally {
cur.close();
}
}
private void longRun() {
try {
for (int i = 0; i < 1000; i++)
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
This causes following error:
FATAL EXCEPTION: FinalizerWatchdogDaemon
Process: la.la.land, PID: 29206
java.util.concurrent.TimeoutException: MyCur.finalize() timed out after 10 seconds
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:371)
at java.lang.Thread.sleep(Thread.java:313)
at MyCur.finalize(MessageList.java:1791)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:222)
at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:209)
at java.lang.Thread.run(Thread.java:762)
The production variant with SqlCipher is very similiar:
12-21 15:40:31.668: E/EH(32131): android.content.ContentResolver$CursorWrapperInner.finalize() timed out after 10 seconds_x000D_
12-21 15:40:31.668: E/EH(32131): java.util.concurrent.TimeoutException: android.content.ContentResolver$CursorWrapperInner.finalize() timed out after 10 seconds_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Object.wait(Native Method)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Thread.parkFor$(Thread.java:2128)_x000D_
12-21 15:40:31.668: E/EH(32131): at sun.misc.Unsafe.park(Unsafe.java:325)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.LockSupport.park(LockSupport.java:161)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:840)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:873)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1197)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.ReentrantLock$FairSync.lock(ReentrantLock.java:200)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:262)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteDatabase.lock(SourceFile:518)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteProgram.close(SourceFile:294)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteQuery.close(SourceFile:136)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteCursor.close(SourceFile:510)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.database.CursorWrapper.close(CursorWrapper.java:50)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.database.CursorWrapper.close(CursorWrapper.java:50)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.content.ContentResolver$CursorWrapperInner.close(ContentResolver.java:2746)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.content.ContentResolver$CursorWrapperInner.finalize(ContentResolver.java:2757)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:222)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:209)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Thread.run(Thread.java:762)
_x000D_
Resume: Close cursors ASAP. At least on Samsung S8 with Android 7 where the issue have been seen.
For those arriving around summer 2013, I believe some of this thread is outdated.
I followed this howto which recommends Vundle over Pathogen. After one days use I found installing plugins trivial.
The klen/python-mode plugin deserves special mention. It provides pyflakes and pylint amongst other features.
I have just started using Valloric/YouCompleteMe and I love it. It has C-lang auto-complete and python also works great thanks to jedi integration. It may well replace jedi-vim as per this discussion /davidhalter/jedi-vim/issues/119
Finally browsing the /carlhuda/janus plugins supplied is a good guide to useful scripts you might not know you are looking for such as NerdTree, vim-fugitive, syntastic, powerline, ack.vim, snipmate...
All the above '{}/{}' are found on github you can find them easily with Google.
If you have a valid dtd file for the xml then you can easily transform json to xml and xml to json using the eclipselink jar binary.
Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html
The article also has a sample project (including the supporting third party jars) as a zip file which can be downloaded for reference purpose.
There is a library for this BarCode PHP. You just need to include a few files:
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
You can generate many types of barcodes, namely 1D or 2D. Add the required library:
require_once('class/BCGcode39.barcode.php');
Generate the colours:
// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);
After you have added all the codes, you will get this way:
Example
Since several have asked for an example here is what I was able to do to get it done
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
require_once('class/BCGcode128.barcode.php');
header('Content-Type: image/png');
$color_white = new BCGColor(255, 255, 255);
$code = new BCGcode128();
$code->parse('HELLO');
$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
If you want to actually create the image file so you can save it then change
$drawing = new BCGDrawing('', $color_white);
to
$drawing = new BCGDrawing('image.png', $color_white);
Set the Format to Custom and then specify the format:
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";
or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)
Don't know about the picker for date and time together. Sounds like a custom control to me.
This is just an optimized code form of the accepted answer in case anyone wants to use this in production :
public static void byteArrayOps() throws IOException, ClassNotFoundException{
String str="123";
byte[] yourBytes = null;
// Convert to byte[]
try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);) {
out.writeObject(str);
out.flush();
yourBytes = bos.toByteArray();
} finally {
}
// convert back to Object
try(ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = new ObjectInputStream(bis);) {
Object o = in.readObject();
} finally {
}
}
If someone is still finding it hard, this simple thing worked for me:
On you main system let's say Hosting PC... Go to Control Panel > Windows Defender Firewall > Allow an app or feature through Windows Defender Firewall > Change settings > Find "Apache HTTP Server" > Check both the check-boxes (under Private & Public). See Screenshot
On any another system connected over a same network... Open browser > type: your hosting pc's IP adress followed by your project name in the url bar. Example: 192.168.72.111/example.com/
Hope it helps! Thanks.
>>> {k: v**3 for (k, v) in zip(string.ascii_lowercase, range(26))}
Python supports dict comprehensions, which allow you to express the creation of dictionaries at runtime using a similarly concise syntax.
A dictionary comprehension takes the form {key: value for (key, value) in iterable}. This syntax was introduced in Python 3 and backported as far as Python 2.7, so you should be able to use it regardless of which version of Python you have installed.
A canonical example is taking two lists and creating a dictionary where the item at each position in the first list becomes a key and the item at the corresponding position in the second list becomes the value.
The zip function used inside this comprehension returns an iterator of tuples, where each element in the tuple is taken from the same position in each of the input iterables. In the example above, the returned iterator contains the tuples (“a”, 1), (“b”, 2), etc.
Output:
{'i': 512, 'e': 64, 'o': 2744, 'h': 343, 'l': 1331, 's': 5832, 'b': 1, 'w': 10648, 'c': 8, 'x': 12167, 'y': 13824, 't': 6859, 'p': 3375, 'd': 27, 'j': 729, 'a': 0, 'z': 15625, 'f': 125, 'q': 4096, 'u': 8000, 'n': 2197, 'm': 1728, 'r': 4913, 'k': 1000, 'g': 216, 'v': 9261}
The id of the input seems is not WallSearch
. Maybe you're confusing that name
and id
. They are two different properties. name
is used to define the name by which the value is posted, while id
is the unique identification of the element inside the DOM.
Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value
property.
Just use axes.get_ylim()
, it is very similar to set_ylim
. From the docs:
get_ylim()
Get the y-axis range [bottom, top]
put this inside your Manifest like this in No fullscreen Mode
android:windowSoftInputMode="stateVisible|adjustPan"
in your manifest
<activity
android:windowSoftInputMode="stateVisible|adjustPan"
android:name="com.example.patronusgps.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
In addition to previous post you can have
<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />
Jsf 2.0
I've found it works this way too:
watch: {
"details.position"(newValue, oldValue) {
console.log("changes here")
}
},
data() {
return {
details: {
position: ""
}
}
}
Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.
WAITFOR DELAY 'HH:MM:SS'
I believe the maximum time this can wait for is 23 hours, 59 minutes and 59 seconds.
Here's a Scalar-valued function to show it's use; the below function will take an integer parameter of seconds, which it then translates into HH:MM:SS and executes it using the EXEC sp_executesql @sqlcode
command to query. Below function is for demonstration only, i know it's not fit for purpose really as a scalar-valued function! :-)
CREATE FUNCTION [dbo].[ufn_DelayFor_MaxTimeIs24Hours]
(
@sec int
)
RETURNS
nvarchar(4)
AS
BEGIN
declare @hours int = @sec / 60 / 60
declare @mins int = (@sec / 60) - (@hours * 60)
declare @secs int = (@sec - ((@hours * 60) * 60)) - (@mins * 60)
IF @hours > 23
BEGIN
select @hours = 23
select @mins = 59
select @secs = 59
-- 'maximum wait time is 23 hours, 59 minutes and 59 seconds.'
END
declare @sql nvarchar(24) = 'WAITFOR DELAY '+char(39)+cast(@hours as nvarchar(2))+':'+CAST(@mins as nvarchar(2))+':'+CAST(@secs as nvarchar(2))+char(39)
exec sp_executesql @sql
return ''
END
IF you wish to delay longer than 24 hours, I suggest you use a @Days parameter to go for a number of days and wrap the function executable inside a loop... e.g..
Declare @Days int = 5
Declare @CurrentDay int = 1
WHILE @CurrentDay <= @Days
BEGIN
--24 hours, function will run for 23 hours, 59 minutes, 59 seconds per run.
[ufn_DelayFor_MaxTimeIs24Hours] 86400
SELECT @CurrentDay = @CurrentDay + 1
END
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #
$('#myId').val()
should do it, failing that I would try:
$('#myId option:selected').val()
Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Nothing works and what mostly annoys me it's the fact that it works in the command line.
The simplest way is to get the width and height of an ImageView in onWindowFocusChanged method of the activity
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
height = mImageView.getHeight();
width = mImageView.getWidth();
}
Sometimes it is Skype or another application "Holding" on to port 80. Jusct close Skype
Is using System.Threading.Timer
mandatory?
If not, System.Timers.Timer
has handy Start()
and Stop()
methods (and an AutoReset
property you can set to false, so that the Stop()
is not needed and you simply call Start()
after executing).
<c:if test="${companies.size() > 0}">
</c:if>
This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt
instead of >
.
<c:if test="${companies.size() gt 0}">
</c:if>
If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length()
function then. From the documentation:
length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.
Put this at the top of JSP page to allow the fn
namespace:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Or if you're using JSPX or Facelets:
<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">
And use like this in your page:
<p>The length of the companies collection is: ${fn:length(companies)}</p>
So to test with length of a collection:
<c:if test="${fn:length(companies) gt 0}">
</c:if>
Alternatively, for this specific case you can also simply use the EL empty
operator:
<c:if test="${not empty companies}">
</c:if>
Try
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
I've got this, which is working in FF3, IE6 & 7. The methods in the on-demand loaded scripts aren't available until page load is complete, but this is still very useful.
//handle on-demand loading of javascripts
makescript = function(url){
var v = document.createElement('script');
v.src=url;
v.type='text/javascript';
//insertAfter. Get last <script> tag in DOM
d=document.getElementsByTagName('script')[(document.getElementsByTagName('script').length-1)];
d.parentNode.insertBefore( v, d.nextSibling );
}
I took the Ned Rockson's version and adjusted it to allow upwards scrolls as well.
var smoothScroll = function(elementId) {
var MIN_PIXELS_PER_STEP = 16;
var MAX_SCROLL_STEPS = 30;
var target = document.getElementById(elementId);
var scrollContainer = target;
do {
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop === 0);
var targetY = 0;
do {
if (target === scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
Math.abs(targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);
var isUp = targetY < scrollContainer.scrollTop;
var stepFunc = function() {
if (isUp) {
scrollContainer.scrollTop = Math.max(targetY, scrollContainer.scrollTop - pixelsPerStep);
if (scrollContainer.scrollTop <= targetY) {
return;
}
} else {
scrollContainer.scrollTop = Math.min(targetY, scrollContainer.scrollTop + pixelsPerStep);
if (scrollContainer.scrollTop >= targetY) {
return;
}
}
window.requestAnimationFrame(stepFunc);
};
window.requestAnimationFrame(stepFunc);
};
SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >
If the case is:
n=int(input())
Instead of -> for i in n: -> gives error- 'int' object is not iterable
Use -> for i in range(0,n): -> works fine..!
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
Just to add. If you right-click on an eclipse project and select Properties
, select the Java Build Path
link on the left. Then select the Source
Tab. You'll see a list of all the java source folders. You can even add your own. By default the {project}/src
folder is the classpath folder.
Currently you can use it, changing the order: (it seems to be a bug)
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_good);
toolbar.setTitle("Title");
toolbar.setSubtitle("Sub");
toolbar.setLogo(R.drawable.ic_launcher);
Promo graphic
The promo graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to submit an update for your Store Listing.
Requirements
- JPG or 24-bit PNG (no alpha)
- Dimensions: 180px by 120px
https://support.google.com/googleplay/android-developer/answer/1078870
REM kill all existing instance of chrome
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files
change chromeLocation path with yours.
save above as .bat file.
drag drop you file on the batch file you created. (chrome does give restore pages option though so if you have pages open just hit restore and it will work).
I had all my settings covered in the accepted answer. The problem I had was that I was trying to update the Entity Framework entity type "Task" like:
public IHttpActionResult Post(Task task)
What worked for me was to create my own entity "DTOTask" like:
public IHttpActionResult Post(DTOTask task)
Global Gzip in HttpModule
If you don't have access to the final IIS instance (shared hosting...) you can create a HttpModule that adds this code to every HttpApplication.Begin_Request event :
HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
Testing
Kudos, no solution is done without testing. I like to use the Firefox plugin "Liveheaders" it shows all the information about every http message between the browser and server, including compression, file size (which you could compare to the file size on the server).
Use the tag @import
@import url('http://fonts.googleapis.com/css?family=Kavoon');
0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
You may want to read this document in matplotlib
's documentation, titled:
An add-on to the previous answers since I came across this concern:
If you really want to insert something like 24-May-2005
to your DATE column, you could do something like this:
INSERT INTO someTable(Empid,Date_Joined)
VALUES
('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));
In the above query please note that if it's May
(ie: the month in letters) the format should be %M
.
NOTE: I tried this with the latest MySQL version 8.0 and it works!
i think this - including null value = 0
SELECT oi.id,
SUM(nvl(oi.quantity,0) * nvl(p.price,0)) AS total_qty
FROM ORDERITEM oi
JOIN PRODUCT p ON p.id = oi.productid
WHERE oi.orderid = @OrderId
GROUP BY oi.id
As the more recent MySQL documentation on view restrictions says:
Before MySQL 5.7.7, subqueries cannot be used in the FROM clause of a view.
This means, that choosing a MySQL v5.7.7 or newer or upgrading the existing MySQL instance to such a version, would remove this restriction on views completely.
However, if you have a current production MySQL version that is earlier than v5.7.7, then the removal of this restriction on views should only be one of the criteria being assessed while making a decision as to upgrade or not. Using the workaround techniques described in the other answers may be a more viable solution - at least on the shorter run.
You can also have several workspaces - so you can connect to one and have set "A" of projects - and then connect to a different set when ever you like.
You are using a forward declaration for the type MainWindowClass
. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)
So, you either want:
// forward declaration, details unknown
class A;
class B {
A *a; // pointer to A, ok
};
Or, if you can't use a pointer or reference....
// declaration of A
#include "A.h"
class B {
A a; // ok, declaration of A is known
};
At some point, the compiler needs to know the details of A
.
If you are only storing a pointer to A
then it doesn't need those details when you declare B
. It needs them at some point (whenever you actually dereference the pointer to A
), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A
.
// B.h
// header file
// forward declaration, details unknown
class A;
class B {
public:
void foo();
private:
A *a; // pointer to A, ok
};
// B.cpp
// implementation file
#include "B.h"
#include "A.h" // declaration of A
B::foo() {
// here we need to know the declaration of A
a->whatever();
}
If you like to keep it fixed width, for example 10 digits, do it like this
Key = i.ToString("0000000000");
Replace with as many digits as you like.
i = 123
will then result in Key = "0000000123"
.
In my case, updating com.android.tools.build:gradle
to last version and rebuild the project in online mode of Gradle was solved the problem.
Postgres allows:
UPDATE dummy
SET customer=subquery.customer,
address=subquery.address,
partn=subquery.partn
FROM (SELECT address_id, customer, address, partn
FROM /* big hairy SQL */ ...) AS subquery
WHERE dummy.address_id=subquery.address_id;
This syntax is not standard SQL, but it is much more convenient for this type of query than standard SQL. I believe Oracle (at least) accepts something similar.
As an alternative to James McNellis answer, I always try to use enumeration for the bool type instead of macros: typedef enum bool {false=0; true=1;} bool;
. It is safer b/c it lets the compiler do type checking and eliminates macro expansion races
Except when it is the operand of the sizeof
or unary &
operator, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T
" is converted ("decays") to an expression of type "pointer to T
", and the value of the expression is the address of the first element of the array.
If the declaration of the array being passed is
int S[4][4] = {...};
then when you write
rotateArr( S );
the expression S
has type "4-element array of 4-element array of int
"; since S
is not the operand of the sizeof
or unary &
operators, it will be converted to an expression of type "pointer to 4-element array of int
", or int (*)[4]
, and this pointer value is what actually gets passed to rotateArr
. So your function prototype needs to be one of the following:
T rotateArr( int (*arr)[4] )
or
T rotateArr( int arr[][4] )
or even
T rotateArr( int arr[4][4] )
In the context of a function parameter list, declarations of the form T a[N]
and T a[]
are interpreted as T *a
; all three declare a
as a pointer to T
.
You're probably wondering why I changed the return type from int
to T
. As written, you're trying to return a value of type "4-element array of 4-element array of int
"; unfortunately, you can't do that. C functions cannot return array types, nor can you assign array types. IOW, you can't write something like:
int a[N], b[N];
...
b = a; // not allowed
a = f(); // not allowed either
Functions can return pointers to arrays, but that's not what you want here. D
will cease to exist once the function returns, so any pointer you return will be invalid.
If you want to assign the results of the rotated array to a different array, then you'll have to pass the target array as a parameter to the function:
void rotateArr( int (*dst)[4], int (*src)[4] )
{
...
dst[i][n] = src[n][M - i + 1];
...
}
And call it as
int S[4][4] = {...};
int D[4][4];
rotateArr( D, S );
No you don't have to put credentials, You have to put headers on client side eg:
$http({
url: 'url of service',
method: "POST",
data: {test : name },
withCredentials: true,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
And and on server side you have to put headers to this is example for nodejs:
/**
* On all requests add headers
*/
app.all('*', function(req, res,next) {
/**
* Response settings
* @type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
Precision and scale are often misunderstood. In numeric(3,2) you want 3 digits overall, but 2 to the right of the decimal. If you want 15 => 15.00 so the leading 1 causes the overflow (since if you want 2 digits to the right of the decimal, there is only room on the left for one more digit). With 4,2 there is no problem because all 4 digits fit.
You can use UIAppearance once, at your application startup (before UI is loaded), to set it as default global settings:
// iOS 7:
[[UITableView appearance] setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
[[UITableView appearance] setSeparatorInset:UIEdgeInsetsZero];
[[UITableViewCell appearance] setSeparatorInset:UIEdgeInsetsZero];
// iOS 8:
if ([UITableView instancesRespondToSelector:@selector(setLayoutMargins:)]) {
[[UITableView appearance] setLayoutMargins:UIEdgeInsetsZero];
[[UITableViewCell appearance] setLayoutMargins:UIEdgeInsetsZero];
[[UITableViewCell appearance] setPreservesSuperviewLayoutMargins:NO];
}
This way, you keep your UIViewController's code clean and can always override it if you want.
You can easily create a timer functionality by using setInterval.Below is the code which you can use it to create the timer.
http://jsfiddle.net/ayyadurai/GXzhZ/1/
window.onload = function() {_x000D_
var minute = 5;_x000D_
var sec = 60;_x000D_
setInterval(function() {_x000D_
document.getElementById("timer").innerHTML = minute + " : " + sec;_x000D_
sec--;_x000D_
if (sec == 00) {_x000D_
minute --;_x000D_
sec = 60;_x000D_
if (minute == 0) {_x000D_
minute = 5;_x000D_
}_x000D_
}_x000D_
}, 1000);_x000D_
}
_x000D_
Registration closes in <span id="timer">05:00<span> minutes!
_x000D_
According to the CSS Flexible Box Layout Module, you can declare the a
element as a flex container (see figure) and use align-items
to vertically align text along the cross axis (which is perpendicular to the main axis).
All you need to do is:
display: flex;
align-items: center;
See this fiddle.
Using environment variable is sometimes more convenient when you do not control the build scripts / process.
For C includes use C_INCLUDE_PATH
.
For C++ includes use CPLUS_INCLUDE_PATH
.
See this link for other gcc environment variables.
# `pip install` will automatically run `gcc` using parameters
# specified in the `asyncpg` package (that I do not control)
C_INCLUDE_PATH=/home/scott/.pyenv/versions/3.7.9/include/python3.7m pip install asyncpg
set C_INCLUDE_PATH="C:\Users\Scott\.pyenv\versions\3.7.9\include\python3.7m"
pip install asyncpg
# clear the environment variable so it doesn't affect other builds
set C_INCLUDE_PATH=
Here's a more simple version of essentially the same file.
@echo off
break off
title C:\Windows\system32\cmd.exe
cls
:cmd
set /p cmd=C:\Enter Command:
%cmd%
echo.
goto cmd
As soon as you add a "WebApi Controller" under controllers folder, Visual Studio takes care of dependencies automatically;
Visual Studio has added the full set of dependencies for ASP.NET Web API 2 to project 'MyTestProject'.
The Global.asax.cs file in the project may require additional changes to enable ASP.NET Web API.
Add the following namespace references:
using System.Web.Http; using System.Web.Routing;
If the code does not already define an Application_Start method, add the following method:
protected void Application_Start() { }
Add the following lines to the beginning of the Application_Start method:
GlobalConfiguration.Configure(WebApiConfig.Register);
clang++ 3.5 even warns on it:
/tmp/a.C:3:7: warning: reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to
always evaluate to false [-Wtautological-undefined-compare]
if( & nullReference == 0 ) // null reference
^~~~~~~~~~~~~ ~
1 warning generated.
Nope, IDs have to be unique. You can use classes for that purpose
<div class="a" /><div class="a b" /><span class="a" />
div.a {font: ...;}
/* or just: */
.a {prop: value;}
If, like me, you've come to this topic via Razor components as you're learning Blazor, then you'll find you need to think a little more outside of the box to solve this problem. It's a bit of a minefield if (also like me) Blazor is your first forray into the MVC-type world, as the documentation isn't as helpful for such 'menial' tasks.
So, at the time of writing, you cannot achieve this using vanilla Blazor/Razor without embedding an MVC controller to handle the file download part an example of which is as below:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
[Route("api/[controller]")]
[ApiController]
public class FileHandlingController : ControllerBase
{
[HttpGet]
public FileContentResult Download(int attachmentId)
{
TaskAttachment taskFile = null;
if (attachmentId > 0)
{
// taskFile = <your code to get the file>
// which assumes it's an object with relevant properties as required below
if (taskFile != null)
{
var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileNameStar = taskFile.Filename
};
Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
}
}
return new FileContentResult(taskFile?.FileData, taskFile?.FileContentType);
}
}
Next, make sure your application startup (Startup.cs) is configured to correctly use MVC and has the following line present (add it if not):
services.AddMvc();
.. and then finally modify your component to link to the controller, for example (iterative based example using a custom class):
<tbody>
@foreach (var attachment in yourAttachments)
{
<tr>
<td><a href="api/[email protected]" target="_blank">@attachment.Filename</a> </td>
<td>@attachment.CreatedUser</td>
<td>@attachment.Created?.ToString("dd MMM yyyy")</td>
<td><ul><li class="oi oi-circle-x delete-attachment"></li></ul></td>
</tr>
}
</tbody>
Hopefully this helps anyone who struggled (like me!) to get an appropriate answer to this seemingly simple question in the realms of Blazor…!