Alt + Shift + ? (Left Arrow)
or
Ctrl + E (Recent Files pop-up).
Also check:
Ctrl + Shift + E (the Recently Edited Files pop-up).
Mac users, replace Ctrl with ? (command) and Alt with ? (option).
Update In v12.0 it's Alt + Shift +? (Left Arrow) instead of Alt + Ctrl + ? (Left Arrow).
Update 2 In v14.1 (and possibly earlier) it's Ctrl + [
Update 3 In IntelliJ IDEA 2016.3 it's Ctrl + Alt + ? (Left Arrow)
Update 4 In IntelliJ IDEA 2018.3 it's Alt + Shift + ? (Left Arrow)
Update 5 In IntelliJ IDEA 2019.3 it's Ctrl + Alt + ? (Left Arrow)
If using scala, try priv
+ tab
You can find all the details here:
It's the old bug in Java on Mac that got triggered by the Java Agent being used by the IDE when starting the app. This message is harmless and is safe to ignore. Oracle developer's comment:
The message is benign, there is no negative impact from this problem since both copies of that class are identical (compiled from the exact same source). It is purely a cosmetic issue.
The problem is fixed in Java 9 and in Java 8 update 152.
If it annoys you or affects your apps in any way (it shouldn't), the workaround for IntelliJ IDEA is to disable idea_rt
launcher agent by adding idea.no.launcher=true
into idea.properties
(Help
| Edit Custom Properties...
). The workaround will take effect on the next restart of the IDE.
I don't recommend disabling IntelliJ IDEA launcher agent, though. It's used for such features as graceful shutdown (Exit button), thread dumps, workarounds a problem with too long command line exceeding OS limits, etc. Losing these features just for the sake of hiding the harmless message is probably not worth it, but it's up to you.
It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.
In 'Path Variables' create a variable for example ANALYTICS_VERSION
.
In a 'Run Configuration' under 'Environment Variables' add for example the following:
ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin
To answer the original question you would need to add an APP_HOME
environment variable to your run configuration which references the path variable:
APP_HOME=$APP_HOME$
For a new project select the home directory of the jdk
eg C:\Java\jdk1.7.0_99
or C:\Program Files\Java\jdk1.7.0_99
For an existing project.
1) You need to have a jdk
installed on the system.
for instance in
C:\Java\jdk1.7.0_99
2) go to project structure
under File
menu ctrl+alt+shift+S
3) SDKs
is located under Platform Settings
. Select it.
4) click the green +
up the top of the window.
5) select JDK
(I have to use keyboard to select it do not know why).
select the home directory for your jdk installation.
should be good to go.
If you do not want to destroy .idea, you can try :
I know this is not the OP's problem, but I ran into the same error with an entirely different basis, so I just wanted to drop it here in case anyone else has the same. This is Windows-specific, and I assume does not affect Linux users.
I had a LibreOffice doc file, call it final report.odt
. I later changed its case to Final Report.odt
. In Windows, this doesn't even count as a rename. final report.odt
, Final Report.odt
, FiNaL RePoRt.oDt
are all the same. In Linux, these are all distinct.
When I eventually went to git rm "Final Report.odt"
and got the "pathspec did not match any files" error. Only when I use the original casing at the time the file was added -- git rm "final report.odt"
-- did it work.
Lesson learned: to change the case I should have instead done:
git mv "final report.odt" temp.odt
git mv temp.odt "Final Report.odt"
Again, that wasn't the problem for the OP here; and wouldn't affect a Linux user, as his posts shows he clearly is. I'm just including it for others who may have this problem in Windows git and stumble onto this question.
Try Ctrl+Alt+U
Also check if the UML plugin is activated (settings -> plugin, settings can be opened by Ctrl+Alt+S
None of the solutions in Intellij is as elegant (or useful) as in Eclipse. What we need is feature request to the intellij so that we can add a hook (what actions to perform) when the IDE autosaves.
In Eclipse we can add "post-save" actions, such as organize imports and format the class. Yes you have to do a "save" or ctrl-s but the hook is very convenient.
You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.
In my experience, using a PYTHONPATH variable at all is usually the wrong approach, because it does not play nicely with VENV on windows. PYTHON on loading will prepare the path by prepending PYTHONPATH to the path, which can result in your carefully prepared Venv preferentially fetching global site packages.
Instead of using PYTHON path, include a pythonpath.pth file in the relevant site-packages directory (although beware custom pythons occasionally look for them in different locations, e.g. enthought looks in the same directory as python.exe for its .pth files) with each virtual environment. This will act like a PYTHONPATH only it will be specific to the python installation, so you can have a separate one for each python installation/environment. Pycharm integrates strongly with VENV if you just go to yse the VENV's python as your python installation.
See e.g. this SO question for more details on .pth files....
With Esc and Command + 1 you can navigate between project view and editor area - back and forward, in this way you can select the folder/location you need
With Control +Option + N you can trigger New file menu and select whatever you need, class, interface, file, etc. This works in editor as well in project view and it relates to the current selected location
// please consider that this is working with standard key mapping
For Android Studio 0.8.9: VCS --> Import into version contraol --> Share project on Github.
It doesn't give you option to share in a specific repository or at least I couldn't find (my limitation!).
You can add your github info here: File --> Settings --> Version COntraol --> Github.
For what its worth, in Pycharm it is: Right click on the root folder->Mark Directory as-> Sources Root
Having included a dependency on spring-boot-configuration-processor
in build.gradle
:
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor:2.4.1"
the only thing that worked for me, besides invalidating caches of IntelliJ and restarting, is
Reload All Gradle Projects
Clean
Build
Since I had to compile some source with 7 compatibility, because of some legacy system and ran into the same problem. I found out that in the gradle configuration there where two options set to java 8
sourceCompatibility = 1.8
targetCompatibility = 1.8
switching these to 1.7 solved the problem for me, keeping JAVA_HOME pointing to the installed JDK-7
sourceCompatibility = 1.7
targetCompatibility = 1.7
One way of doing this is to do add junit.jar to your $CLASSPATH
as an external dependency.
So to do that, go to project structure, and then add JUnit as one of the libraries as shown in the gif.
In the 'Choose Modules' prompt choose only the modules that you'd need JUnit for.
Install the GenerateSerialVersionUID plugin by Olivier Descout.
Go to: menu File ? Settings ? Plugins ? Browse repositories ? GenerateSerialVersionUID
Install the plugin and restart.
Now you can generate the id from menu Code ? Generate ? serialVersionUID` or the shortcut.
Parameters can be set on the fly also.
mvn test -DargLine="-Dsystem.test.property=test"
See http://www.cowtowncoder.com/blog/archives/2010/04/entry_385.html
SOLVED !!!
This is how I fixed the issue...
Tried again one of the answers in the thread which says 'If that does not work, Invalidate your caches (File > Invalidate caches) and restart.' Did that but again no luck.
Tried These options .. Go to Settings --> Maven --> Importing and made sure the following was selected
Import Maven projects automatically
Create IDEA modules for aggregator projects Keep source...
Exclude build dir...
Use Maven output...
Generated souces folders: "detect automatically"
Phase to be...: "process-resources"
Automatically download: "sources" & "documentation"
Use Maven3 to import
project VM options for importer: -Xmx512m
But again no success.
OK I found the problem, I was checking in the wrong place which is for the whole IDE's look and feel at File->Settings->Appearance
The correct place to change the editor appearance is through File->Settings->Editor->Colors &Fonts
and then choose the scheme there. The imported settings appear there :)
Note: The theme site seems to have moved.
If you are working on spring/mvn project you can use this command:
mvn package -DskipTests
The jar file will be saved on target directoy.
Seems like IntelliJ IDEA will import missed class automatically, and you can import them by hit Alt + Enter manually.
Project Structure->Modules->{Your Module}->Sources->{Click the folder named java in src/main}->click the blue button which img is a blue folder,then you should see the right box contains new item(Source Folders).All be done;
[For IntelliJ IDEA 2016.2]
I would like to expand upon part of Peter Gromov's answer with an up-to-date screenshot. Specifically this particular part:
You might also want to take a look at Settings | Compiler | Java Compiler | Per-module bytecode version.
I believe that (at least in 2016.2): checking out different commits in git
resets these to 1.5.
If all my pom.xml files are configured correctly and I still have issues with Maven in IntelliJ I do the following steps
P.S. I've spent hours to understand(step 3) that IntelliJ's java demon process that handles maven index update was doing something wrong and I simply need to make IntelliJ to start it from scratch. Problem was solved without even restarting IntelliJ itself.
My version of IntelliJ IDEA Ultimate (2016.3.4 Build 163) seems to support this. The trick is that you need to have enabled the Spring Data plugin.
You can also try my ubuntu repository: https://launchpad.net/~mmk2410/+archive/ubuntu/intellij-idea
To use it just run the following commands:
sudo apt-add-repository ppa:mmk2410/intellij-idea
sudo apt-get update
The community edition can then installed with
sudo apt-get install intellij-idea-community
and the ultimate edition with
sudo apt-get install intellij-idea-ultimate
you can try invalidating the cache and restarting intellij, in many cases it will help.
File -> Invalidate Caches/Restart
In my case I used below configuration at VM options in IntelliJ
, it was not picking the local configurations but after a restart of IntelliJ
it picked configuration details from IntelliJ
and service started running.
-Dspring.profiles.active=local
I had the same issue. I think it would be appropriate to check whether your class can be compiled or not. Click recompile (Ctrl+Shift+F9 by default). If its not working then you have to investigate why it isn't compiling.
In my case the code wasn't autocompiling because there were hidden errors with compilation (they weren't shown in logs anywhere and maven clean-install was working). The rootcause was incorrect Project Structure -> Modules configuration, so Intellij Idea wasn't able to build it according to this configuration.
This is my solution, it is very similar to the previous one:
<dependency>
<groupId>com.google.android</groupId>
<artifactId>support-v7</artifactId>
<scope>system</scope>
<systemPath>${android.home}/support/v7/appcompat/libs/android-support-v7-appcompat.jar</systemPath>
<version>19.0.1</version>
</dependency>
Where {android.home} is the root directory of the Android SDK and it uses systemPath instead of repository.
modules.xml with wrong content, I don't know what's matter with my IDEA.
If you are installing into local repository, there is no special index/cache update needed.
Make sure that:
You have installed the first artifact in your local repository properly. Simply copying the file to .m2
may not work as expected. Make sure you install it by mvn install
The dependency in 2nd project is setup correctly. Check on any typo in groupId/artifactId/version
, or unmatched artifact type/classifier
.
Try Ctrl+Mouse Wheel
which can be enabled under File > Settings... > Editor > General : Change font size (Zoom) with Ctrl+Mouse Wheel
in pyCharm,
file|
v-->settings|
v-->Version Control|
v-->Git
Here change SSH executable
from Built-in
into Native
then press apply
and close
As indicated here, JavaFX is no longer included in openjdk.
So check, if you have <Java SDK root>/jre/lib/ext/jfxrt.jar
on your classpath under Project Structure -> SDKs -> 1.x -> Classpath
? If not, that could be why. Try adding it and see if that fixes your issue, e.g. on Ubuntu, install then openjfx package with sudo apt-get install openjfx
.
Here is the complete procedure for IDEA IntelliJ 2019.3:
File > Project Structure
Under Project Settings > Modules
Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.
Apply changes.
For me, it was due to the project missing Gradle Libraries in its project structure.
Just add in build.gradle:
apply plugin: 'idea'
And then run:
$ gradle idea
After that gradle rebuilds dependencies libraries and the references are recognized!
Once I have followed all these steps, I start to receive error messages in all android classes calls like:
I revolved that including android.jar in the SDKs Platform Settings:
I had the problem not able to load jar file in libs folder in Android Studio.
If you have added JAR file in libs folder, then just open build.gradle
file and save it without editing anything else. If you have added this line
compile fileTree(dir: 'libs', include: ['*.jar'])
save it and clean the project .. In next build time Android Studio will load the JAR file.
Hope this helps.
Here is a link to the latest documentation as of today http://www.jetbrains.com/idea/webhelp/increasing-memory-heap.html
That's part of the syntax of the new lambda expressions, to be introduced in Java 8. There are a couple of online tutorials to get the hang of it, here's a link to one. Basically, the ->
separates the parameters (left-side) from the implementation (right side).
The general syntax for using lambda expressions is
(Parameters) -> { Body }
where the ->
separates parameters and lambda expression body.
The parameters are enclosed in parentheses which is the same way as for methods and the lambda expression body is a block of code enclosed in braces.
Many answers regarding Maven are right but you don't have to configure the plugin directly.
Like described on the wiki page of the Apache Maven Compiler Plugin you can just set the 2 properties used by the plugin.
<project>
[...]
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
[...]
</project>
In my case, just changingTarget JVM Version like this: File > Setting > Kotlin Compiler > Target JVM Version > 1.8 did not help. However, it does resolved compile time error. But failed at runtime.
I also had to add following in app build.gradle file to make it work.
android {
// Other code here...
kotlinOptions {
jvmTarget = "1.8"
}
}
Add:
build.gradle
in your root project folder, and use plugin for example:
apply plugin: 'idea'
//and standard one
apply plugin: 'java'
and with this fire from command line:
gradle cleanIdea
and after that:
gradle idea
After that everything should work
Inside your .idea folder, change workspace.xml file
Add
<property name="dynamic.classpath" value="true" />
to
<component name="PropertiesComponent">
.
.
.
</component>
Example
<component name="PropertiesComponent">
<property name="project.structure.last.edited" value="Project" />
<property name="project.structure.proportion" value="0.0" />
<property name="project.structure.side.proportion" value="0.0" />
<property name="settings.editor.selected.configurable" value="preferences.pluginManager" />
<property name="dynamic.classpath" value="true" />
</component>
If you don't see one, feel free to add it yourself
<component name="PropertiesComponent">
<property name="dynamic.classpath" value="true" />
</component>
This is where my gradle home is (Arch Linux):
/usr/share/java/gradle/
I tried out all the steps mentioned in here https://stackoverflow.com/a/26009627/2058104, but the 4th point has now changed. You need to go to Preferences -> Build, Execution, Deployment -> Compiler -> Java Compiler
In there, as shown in below figure, you need to change the "Target bytecode version". Although, I changed it to 8 (since I needed to downgrade to Java 8), it was giving the same error, over and over. Therefore, try to remove the existing entry (in this table) and add it again. This worked for me.
On the other hand, clean the project and try to run again.
Goto Help -> Find Action (Short Cut for this is Cntl + Shift + A) and type Optimize imports (Short cut for this is Cntl + Alt + O)
Make sure you have a jdk setup. To do this, create a new project and then go to file -> project structure. From there you can add a new jdk. Once that is setup, go back to your gradle project and you should have a jdk to select in the 'Gradle JVM' field.
I think this post by Rex St John is very useful for unit testing with android studio.
(source: rexstjohn.com)
right click on the "SRC folder", select "Mark directory as:, select "Resource Root".
Then Edit the run configuration. select Run, run, edit configuration, with the plus button add an application configuration, give it a name (could be any name), and in the main class write down the full name of the main java class for example, com.example.java.MaxValues.
you might also need to check file, project structure, project settings-project, give it a folder for the compiler output, preferably a separate folder, under the java folder,
If you are using java 7 then make sure you have Tomcat 7
brew install tomcat@7
and update run configuration to Tomcat 7
Tomcat 9 is working with java 8
If you are using Lombok, make sure you have enabled annotation processing.
You can try -Xbootclasspath/a:path option of java application launcher. By description it specifies "a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path."
I needed to enable the JUnit plugin, after I linked my project with the jar files.
To enable the JUnit plugin, go to File->Settings, type "JUnit" in the search bar, and under "Plugins," check "JUnit.
vikingsteve's advice above will probably get the libraries linked right. Otherwise, open File->Project Structure, go to Libraries, hit the plus, and then browse to
C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 14.1.1\lib\
and add these jar files:
hamcrest-core-1.3.jar
junit-4.11.jar
junit.jar
If you are coming from Eclipse: http://tanu.wordpress.com/2010/09/24/moving-from-eclipse-to-intellij-idea/
General documentation and shortcuts are on Intellij's site http://www.jetbrains.com/idea/documentation/index.jsp
Tried everything in this thread and nothing worked for me in IntelliJ 2020.2. This answer did the trick, but I had to set the correct path to the JDK and choose it in Gradle settings after that (as showed in figures bellow):
After that, the option "Reload All Gradle Projects" downloaded all dependencies as expected.
Cheers.
Change debug port of your server configured in the Intelli J.
Or you can do the following shortcut :
MAC : Shift + Command + A (Enter Action menu pops up)
And write : Optimize Imports
I had a similar error and in my case the fix was removing the '-' character from project name. Instead of my-app
, I used MyApp
Add .idea
and *.iml
to .gitignore
, you don't need those files to successfully import and compile the project.
On my IntelliJ U on Mac I need to point with cursor on some method, variable etc. and press [cntrl] or [cmd] key. Then click on the link inside popup window which appeared to see JavaDocs
Unfortunately all above didn't work for me. After having lots of trials, What worked for me in Android Studio:
do a 'move' on the package to a new package name you want.(right click on package and select Refactor -> Move) If Refactor -> Move didn't work for you, then create a package with the name you want and move manually in the existing package to the new one, and then delete the old empty package.
Change package name in manifest (manually)
The easiest way is to execute the following command from the command line (see Upgrading the Gradle Wrapper in documentation):
./gradlew wrapper --gradle-version 5.5
Moreover, you can use --distribution-type
parameter with either bin
or all
value to choose a distribution type. Use all
distribution type to avoid a hint from IntelliJ IDEA or Android Studio that will offer you to download Gradle with sources:
./gradlew wrapper --gradle-version 5.5 --distribution-type all
Or you can create a custom wrapper
task
task wrapper(type: Wrapper) {
gradleVersion = '5.5'
}
and run ./gradlew wrapper
.
The problem was that the wrong hamcrest.Matcher
, not hamcrest.MatcherAssert
, class was being used. That was being pulled in from a junit-4.8 dependency one of my dependencies was specifying.
To see what dependencies (and versions) are included from what source while testing, run:
mvn dependency:tree -Dscope=test
Press Ctrl+Shift+A to find actions, and input "reimport", you will find the "Reimport All Maven Projects".
On a Mac, use ?+?+A instead.
In your IntelliJ idea find tools.jar replace it with tools.jar from yout JDK8
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
IntelliJ IDEA Plugins / GenerateSerialVersionUID https://plugins.jetbrains.com/plugin/?idea&id=185
very nice, very easy to install. you can install that from plugins menu, select install from disk, select the jar file you unpacked in the lib folder. restart, control + ins, and it pops up to generate serial UID from menu. love it. :-)
Since you give us very little details, most likely what you did, which is an incredibly easy mistake to make, is that instead of heading to
Build Path > Configure Build Path > Projects
and adding your additional project folder from there, instead you went to
Build Path > Configure Build Path > Libraries
and added your project folder from there instead.
This is most definitely the case if your code is all correct, but upon automatically reorganizing imports via the ctrl+space
shortcut , instead of your import statements referring to com.your.additionalproject, your references all point to bin.com.your.additionalproject.
Note the bin. Meaning that you -are- indirectly referring to your class by treating your other project folder structure as a library, making your IDE doing all the wokr of finding the exactly binary class you're referring to.
To correct this, remove the folder from the Libraries, and instead add it under the Projects tab, and reorganize your imports. Your project should work fine.
The issue that JavaFX is no longer part of JDK 11. The following solution works using IntelliJ (haven't tried it with NetBeans):
Add JavaFX Global Library as a dependency:
Settings -> Project Structure -> Module. In module go to the Dependencies tab, and click the add "+" sign -> Library -> Java-> choose JavaFX from the list and click Add Selected, then Apply settings.
Right click source file (src) in your JavaFX project, and create a new module-info.java file. Inside the file write the following code :
module YourProjectName {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens sample;
}
These 2 steps will solve all your issues with JavaFX, I assure you.
Reference : There's a You Tube tutorial made by The Learn Programming channel, will explain all the details above in just 5 minutes. I also recommend watching it to solve your problem: https://www.youtube.com/watch?v=WtOgoomDewo
For intellij 13,
Simply change the Project language level itself to 8.0
with following navigation.
File
|
|
---------Project Structure -> Project tab
|
|________Project language level
I also had to update Modules lang level
when there was no maven plugin for java compiler
.
File
|
|
---------Project Structure -> Modules tab
|
|________ language level
But this Module lang level
would automatically be fixed if there's already a maven plugin
for it,
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
After changes everything looks good
The problem appears to be that despite listing your dependencies in the pom.xml, IntelliJ IDEA does not rebuild those dependencies when you run your project.
What worked for me is this:
Go to 'Run' -> 'Edit Configurations...', find your application, make sure the "Before launch:" section is expanded, click the green plus sign, and select "Build Project".
Actually there are 3 places where gradle.properties
can be placed:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradlemyProject2
in your case)myProject
)Gradle looks for gradle.properties
in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).
You can find more details about it in gradle documentation here.
A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.
Search for [^\x00-\x7F]
and check the box for Regex.
The result will look like this (in dark mode):
I had the same issue on androidStudio 3.2
and clonning the project worked for me
the "problem view" mentioned in previous answers was helpful, but i saw it didn't catch all the errors in project. After running application, it began populating other classes that had issues but didn't appear at first in that problems view.
Example I have a class Test:
Then. Go to config to run class Test:
Step 1: Add Application
Step 2:
You can input arguments in the Program Arguments textbox.
Use Ctrl + Shift + F combination for Windows and Linux to search everywhere, it shows preview also.
Use Ctrl + F combination for Windows and Linux to search in current file.
Use Shift + Shift (Double Tap Shift) combination for Windows and Linux to search Project File of Project.
This solution worked for me Android Studio 3.3.2.
If M2_HOME
is configured to point to the Maven home directory then:
File -> Settings
Maven
Runner
Insert in the field VM Options
the following string:
Dmaven.multiModuleProjectDirectory=$M2_HOME
Click Apply
and OK
check, if this works for you.
File -> Settings -> (type appe in search box) and select Appearance -> Select Intellij from dropdown option of Theme on the right (under UI Options).
Hope this helps someone.
For me, it wasn't just getting the javadoc window to open, but also getting the complete javadoc to present. You may still get a sparse javadoc that is based solely on the method signature if you are importing libraries from a Maven repository and do not tell Idea to include the javadocs in the download. Be sure to tick the "JavaDocs" option in the "Download Library From Maven Repository" dialog, which can be found under Project Structure -> Projtect Settings -> Libraries.
I am using Lubuntu, I ended up finding it in :
/usr/share/gradle
When using JetBrains IDE's with Git, "stashing and unstashing actions are supported in addition to shelving and unshelving. These features have much in common; the major difference is in the way patches are generated and applied. Shelve can operate with either individual files or bunch of files, while Stash can only operate with a whole bunch of changed files at once. Here are some more details on the differences between them."
Press F4 at the project root and select the the root source pressing the source button. It resolved my problem!
for(; ;){
makeGoodCode();
}
To clear your gradle cache in android studio:
gradlew clean
Since it is hard to find good themes for IntelliJ IDEA, I've created this site: https://github.com/sdvoynikov/color-themes (note: site archived to GitHub repo) where there is a large collection of themes. There are 270 themes for now and the site is growing.
P.S.: Help me and other people — do not forget to upvote when you download themes from this site!
While maintaining the proper .gitignore
file is helpful, I found this alternate approach is way cleaner and easier to use.
my_project
and inside that git clone my_real_project
the actual project repo.my_project
and mark my_project/my_real_project
as the VCS root. my_project/.idea
wouldn't pollute your git repo because it happily lives outside the git repo which is what you want. This way your .gitignore
files stays clean as well. This approach works better due to the below reasons.
1 - .gitignore
file stays clean and we don't have to insert lines related to JetBrains products, that file is better used for binaries and libraries and autogen contents.
2 - Intellij keeps updating their projects and the files inside .idea
keep changing every significant release from JB. What this means is we have to keep updating our .gitignore
accordingly which is not an ideal use of time.
3 - Intellij has the flawed pattern here, most editors Atom, VS Code, Eclipse... nobody stores their IDE contents right inside project root. JB shouldn't be an exception either. It's the onus of Jetbrains to keep those files tracked outside project root. They have to refrain from polluting VCS root. This approach does just that. The .idea
folder is kept outside the PROJECT_ROOT
Hope this helps.
On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.
EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .
Shortcut Alt+Enter shows intention actions where you can choose "Add Javadoc".
In my case, there was a misstype in AndroidManifest.xml as shown below. Removing "o" letter above application tag solved. Apparently, Android Studio doesn't detect type errors in AndroidMainfest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
o
<application android:name=".AppName"
android:allowBackup="false"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Light.NoTitleBar">
Alternatively via Project Settings:
Depending on how your build is set up, this may be the way to go.
If you imported your maven project in IntelliJ and there are errors because of maven imports not getting resolved, it maybe because of the custom maven settings.xml you may be using. I tried overriding it in the Intellij default maven settings but it did not help. Finally I had to keep it in ~/.m2/settings.xml and then IntelliJ finally honored it.
Use /usr/libexec/java_home
; I found these alias and function to be pretty useful in my ~/.profile
:
alias java_ls='/usr/libexec/java_home -V 2>&1 | cut -s -d , -f 1 | cut -c 5-'
function java_use() {
export JAVA_HOME=$(/usr/libexec/java_home -v $1)
java -version
}
The latter strings shouldn't start with a slash. If they start with a slash, then they're considered an "absolute path" and everything before them is discarded.
Quoting the Python docs for os.path.join
:
If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
Note on Windows, the behaviour in relation to drive letters, which seems to have changed compared to earlier Python versions:
On Windows, the drive letter is not reset when an absolute path component (e.g.,
r'\foo'
) is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive,os.path.join("c:", "foo")
represents a path relative to the current directory on driveC:
(c:foo
), notc:\foo
.
Following the currently top voted answer, I've found using a dataset / data attribute works well.
//Javascript
const input1 = document.querySelector("#input1");
input1.value = "0.00";
input1.dataset.value = input1.value;
//dataset.value will set "data-value" on the input1 HTML element
//and will be used by CSS targetting the dataset attribute
document.querySelectorAll("input").forEach((input) => {
input.addEventListener("input", function() {
this.dataset.value = this.value;
console.log(this);
})
})
_x000D_
/*CSS*/
input[data-value="0.00"] {
color: red;
}
_x000D_
<!--HTML-->
<div>
<p>Input1 is programmatically set by JavaScript:</p>
<label for="input1">Input 1:</label>
<input id="input1" value="undefined" data-value="undefined">
</div>
<br>
<div>
<p>Try typing 0.00 inside input2:</p>
<label for="input2">Input 2:</label>
<input id="input2" value="undefined" data-value="undefined">
</div>
_x000D_
hopefully this will save images form your webcam
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
VideoCapture cap(0);
Mat save_img;
cap >> save_img;
char Esc = 0;
while (Esc != 27 && cap.isOpened()) {
bool Frame = cap.read(save_img);
if (!Frame || save_img.empty()) {
cout << "error: frame not read from webcam\n";
break;
}
namedWindow("save_img", CV_WINDOW_NORMAL);
imshow("imgOriginal", save_img);
Esc = waitKey(1);
}
imwrite("test.jpg",save_img);
}
Preface
Much of the information in this answer has been gathered based on experiments run on a Vista machine. Unless explicitly stated otherwise, I have not confirmed whether the information applies to other Windows versions.
FINDSTR output
The documentation never bothers to explain the output of FINDSTR. It alludes to the fact that matching lines are printed, but nothing more.
The format of matching line output is as follows:
filename:lineNumber:lineOffset:text
where
fileName: = The name of the file containing the matching line. The file name is not printed if the request was explicitly for a single file, or if searching piped input or redirected input. When printed, the fileName will always include any path information provided. Additional path information will be added if the /S
option is used. The printed path is always relative to the provided path, or relative to the current directory if none provided.
Note - The filename prefix can be avoided when searching multiple files by using the non-standard (and poorly documented) wildcards <
and >
. The exact rules for how these wildcards work can be found here. Finally, you can look at this example of how the non-standard wildcards work with FINDSTR.
lineNumber: = The line number of the matching line represented as a decimal value with 1 representing the 1st line of the input. Only printed if /N
option is specified.
lineOffset: = The decimal byte offset of the start of the matching line, with 0 representing the 1st character of the 1st line. Only printed if /O
option is specified. This is not the offset of the match within the line. It is the number of bytes from the beginning of the file to the beginning of the line.
text = The binary representation of the matching line, including any <CR> and/or <LF>. Nothing is left out of the binary output, such that this example that matches all lines will produce an exact binary copy of the original file.
FINDSTR "^" FILE >FILE_COPY
The /A option sets the color of the fileName:, lineNumber:, and lineOffset: output only. The text of the matching line is always output with the current console color. The /A option only has effect when output is displayed directly to the console. The /A option has no effect if the output is redirected to a file or piped. See the 2018-08-18 edit in Aacini's answer for a description of the buggy behavior when output is redirected to CON.
Most control characters and many extended ASCII characters display as dots on XP
FINDSTR on XP displays most non-printable control characters from matching lines as dots (periods) on the screen. The following control characters are exceptions; they display as themselves: 0x09 Tab, 0x0A LineFeed, 0x0B Vertical Tab, 0x0C Form Feed, 0x0D Carriage Return.
XP FINDSTR also converts a number of extended ASCII characters to dots as well. The extended ASCII characters that display as dots on XP are the same as those that are transformed when supplied on the command line. See the "Character limits for command line parameters - Extended ASCII transformation" section, later in this post
Control characters and extended ASCII are not converted to dots on XP if the output is piped, redirected to a file, or within a FOR IN() clause.
Vista and Windows 7 always display all characters as themselves, never as dots.
Return Codes (ERRORLEVEL)
/A:xx
option/L
and /R
both specified/A:
, /F:
, /C:
, /D:
, or /G:
/F:file
or /G:file
not foundSource of data to search (Updated based on tests with Windows 7)
Findstr can search data from only one of the following sources:
filenames specified as arguments and/or using the /F:file
option.
stdin via redirection findstr "searchString" <file
data stream from a pipe type file | findstr "searchString"
Arguments/options take precedence over redirection, which takes precedence over piped data.
File name arguments and /F:file
may be combined. Multiple file name arguments may be used. If multiple /F:file
options are specified, then only the last one is used. Wild cards are allowed in filename arguments, but not within the file pointed to by /F:file
.
Source of search strings (Updated based on tests with Windows 7)
The /G:file
and /C:string
options may be combined. Multiple /C:string
options may be specified. If multiple /G:file
options are specified, then only the last one is used. If either /G:file
or /C:string
is used, then all non-option arguments are assumed to be files to search. If neither /G:file
nor /C:string
is used, then the first non-option argument is treated as a space delimited list of search terms.
File names must not be quoted within the file when using the /F:FILE
option.
File names may contain spaces and other special characters. Most commands require that such file names are quoted. But the FINDSTR /F:files.txt
option requires that filenames within files.txt must NOT be quoted. The file will not be found if the name is quoted.
BUG - Short 8.3 filenames can break the /D
and /S
options
As with all Windows commands, FINDSTR will attempt to match both the long name and the short 8.3 name when looking for files to search. Assume the current folder contains the following non-empty files:
b1.txt
b.txt2
c.txt
The following command will successfully find all 3 files:
findstr /m "^" *.txt
b.txt2
matches because the corresponding short name B9F64~1.TXT
matches. This is consistent with the behavior of all other Windows commands.
But a bug with the /D
and /S
options causes the following commands to only find b1.txt
findstr /m /d:. "^" *.txt
findstr /m /s "^" *.txt
The bug prevents b.txt2
from being found, as well as all file names that sort after b.txt2
within the same directory. Additional files that sort before, like a.txt
, are found. Additional files that sort later, like d.txt
, are missed once the bug has been triggered.
Each directory searched is treated independently. For example, the /S
option would successfully begin searching in a child folder after failing to find files in the parent, but once the bug causes a short file name to be missed in the child, then all subsequent files in that child folder would also be missed.
The commands work bug free if the same file names are created on a machine that has NTFS 8.3 name generation disabled. Of course b.txt2
would not be found, but c.txt
would be found properly.
Not all short names trigger the bug. All instances of bugged behavior I have seen involve an extension that is longer than 3 characters with a short 8.3 name that begins the same as a normal name that does not require an 8.3 name.
The bug has been confirmed on XP, Vista, and Windows 7.
Non-Printable characters and the /P
option
The /P
option causes FINDSTR to skip any file that contains any of the following decimal byte codes:
0-7, 14-25, 27-31.
Put another way, the /P
option will only skip files that contain non-printable control characters. Control characters are codes less than or equal to 31 (0x1F). FINDSTR treats the following control characters as printable:
8 0x08 backspace
9 0x09 horizontal tab
10 0x0A line feed
11 0x0B vertical tab
12 0x0C form feed
13 0x0D carriage return
26 0x1A substitute (end of text)
All other control characters are treated as non-printable, the presence of which causes the /P
option to skip the file.
Piped and Redirected input may have <CR><LF>
appended
If the input is piped in and the last character of the stream is not <LF>
, then FINDSTR will automatically append <CR><LF>
to the input. This has been confirmed on XP, Vista and Windows 7. (I used to think that the Windows pipe was responsible for modifying the input, but I have since discovered that FINDSTR is actually doing the modification.)
The same is true for redirected input on Vista. If the last character of a file used as redirected input is not <LF>
, then FINDSTR will automatically append <CR><LF>
to the input. However, XP and Windows 7 do not alter redirected input.
FINDSTR hangs on XP and Windows 7 if redirected input does not end with <LF>
This is a nasty "feature" on XP and Windows 7. If the last character of a file used as redirected input does not end with <LF>
, then FINDSTR will hang indefinitely once it reaches the end of the redirected file.
Last line of Piped data may be ignored if it consists of a single character
If the input is piped in and the last line consists of a single character that is not followed by <LF>
, then FINDSTR completely ignores the last line.
Example - The first command with a single character and no <LF>
fails to match, but the second command with 2 characters works fine, as does the third command that has one character with terminating newline.
> set /p "=x" <nul | findstr "^"
> set /p "=xx" <nul | findstr "^"
xx
> echo x| findstr "^"
x
Reported by DosTips user Sponge Belly at new findstr bug. Confirmed on XP, Windows 7 and Windows 8. Haven't heard about Vista yet. (I no longer have Vista to test).
Option syntax
Option letters are not case sensitive, so /i
and /I
are equivalent.
Options can be prefixed with either /
or -
Options may be concatenated after a single /
or -
. However, the concatenated option list may contain at most one multicharacter option such as OFF or F:, and the multi-character option must be the last option in the list.
The following are all equivalent ways of expressing a case insensitive regex search for any line that contains both "hello" and "goodbye" in any order
/i /r /c:"hello.*goodbye" /c:"goodbye.*hello"
-i -r -c:"hello.*goodbye" /c:"goodbye.*hello"
/irc:"hello.*goodbye" /c:"goodbye.*hello"
Options may also be quoted. So /i
, -i
, "/i"
and "-i"
are all equivalent. Likewise, /c:string
, "/c":string
, "/c:"string
and "/c:string"
are all equivalent.
If a search string begins with a /
or -
literal, then the /C
or /G
option must be used. Thanks to Stephan for reporting this in a comment (since deleted).
Search String length limits
On Vista the maximum allowed length for a single search string is 511 bytes. If any search string exceeds 511 then the result is a FINDSTR: Search string too long.
error with ERRORLEVEL 2.
When doing a regular expression search, the maximum search string length is 254. A regular expression with length between 255 and 511 will result in a FINDSTR: Out of memory
error with ERRORLEVEL 2. A regular expression length >511 results in the FINDSTR: Search string too long.
error.
On Windows XP the search string length is apparently shorter. Findstr error: "Search string too long": How to extract and match substring in "for" loop? The XP limit is 127 bytes for both literal and regex searches.
Line Length limits
Files specified as a command line argument or via the /F:FILE option have no known line length limit. Searches were successfully run against a 128MB file that did not contain a single <LF>.
Piped data and Redirected input is limited to 8191 bytes per line. This limit is a "feature" of FINDSTR. It is not inherent to pipes or redirection. FINDSTR using redirected stdin or piped input will never match any line that is >=8k bytes. Lines >= 8k generate an error message to stderr, but ERRORLEVEL is still 0 if the search string is found in at least one line of at least one file.
Default type of search: Literal vs Regular Expression
/C:"string"
- The default is /L literal. Explicitly combining the /L option with /C:"string" certainly works but is redundant.
"string argument"
- The default depends on the content of the very first search string. (Remember that <space> is used to delimit search strings.) If the first search string is a valid regular expression that contains at least one un-escaped meta-character, then all search strings are treated as regular expressions. Otherwise all search strings are treated as literals. For example, "51.4 200"
will be treated as two regular expressions because the first string contains an un-escaped dot, whereas "200 51.4"
will be treated as two literals because the first string does not contain any meta-characters.
/G:file
- The default depends on the content of the first non-empty line in the file. If the first search string is a valid regular expression that contains at least one un-escaped meta-character, then all search strings are treated as regular expressions. Otherwise all search strings are treated as literals.
Recommendation - Always explicitly specify /L
literal option or /R
regular expression option when using "string argument"
or /G:file
.
BUG - Specifying multiple literal search strings can give unreliable results
The following simple FINDSTR example fails to find a match, even though it should.
echo ffffaaa|findstr /l "ffffaaa faffaffddd"
This bug has been confirmed on Windows Server 2003, Windows XP, Vista, and Windows 7.
Based on experiments, FINDSTR may fail if all of the following conditions are met:
/I
option)In every failure I have seen, it is always one of the shorter search strings that fails.
For more info see Why doesn't this FINDSTR example with multiple literal search strings find a match?
Quotes and backslahses within command line arguments
Note - User MC ND's comments reflect the actual horrifically complicated rules for this section. There are 3 distinct parsing phases involved:
- First cmd.exe may require some quotes to be escaped as ^" (really nothing to do with FINDSTR)
- Next FINDSTR uses the pre 2008 MS C/C++ argument parser, which has special rules for " and \
- After the argument parser finishes, FINDSTR additionally treats \ followed by an alpha-numeric character as literal, but \ followed by non-alpha-numeric character as an escape character
The remainder of this highlighted section is not 100% correct. It can serve as a guide for many situations, but the above rules are required for total understanding.
Escaping Quote within command line search strings
Quotes within command line search strings must be escaped with backslash like\"
. This is true for both literal and regex search strings. This information has been confirmed on XP, Vista, and Windows 7.Note: The quote may also need to be escaped for the CMD.EXE parser, but this has nothing to do with FINDSTR. For example, to search for a single quote you could use:
FINDSTR \^" file && echo found || echo not found
Escaping Backslash within command line literal search strings
Backslash in a literal search string can normally be represented as\
or as\\
. They are typically equivalent. (There may be unusual cases in Vista where the backslash must always be escaped, but I no longer have a Vista machine to test).But there are some special cases:
When searching for consecutive backslashes, all but the last must be escaped. The last backslash may optionally be escaped.
\\
can be coded as\\\
or\\\\
\\\
can be coded as\\\\\
or\\\\\\
Searching for one or more backslashes before a quote is bizarre. Logic would suggest that the quote must be escaped, and each of the leading backslashes would need to be escaped, but this does not work! Instead, each of the leading backslashes must be double escaped, and the quote is escaped normally:
\"
must be coded as\\\\\"
\\"
must be coded as\\\\\\\\\"
As previously noted, one or more escaped quotes may also require escaping with
^
for the CMD parserThe info in this section has been confirmed on XP and Windows 7.
Escaping Backslash within command line regex search strings
Vista only: Backslash in a regex must be either double escaped like
\\\\
, or else single escaped within a character class set like[\\]
XP and Windows 7: Backslash in a regex can always be represented as
[\\]
. It can normally be represented as\\
. But this never works if the backslash precedes an escaped quote.One or more backslashes before an escaped quote must either be double escaped, or else coded as
[\\]
\"
may be coded as\\\\\"
or[\\]\"
\\"
may be coded as\\\\\\\\\"
or[\\][\\]\"
or\\[\\]\"
Escaping Quote and Backslash within /G:FILE literal search strings
Standalone quotes and backslashes within a literal search string file specified by /G:file need not be escaped, but they can be.
"
and \"
are equivalent.
\
and \\
are equivalent.
If the intent is to find \\, then at least the leading backslash must be escaped. Both \\\
and \\\\
work.
If the intent is to find ", then at least the leading backslash must be escaped. Both \\"
and \\\"
work.
Escaping Quote and Backslash within /G:FILE regex search strings
This is the one case where the escape sequences work as expected based on the documentation. Quote is not a regex metacharacter, so it need not be escaped (but can be). Backslash is a regex metacharacter, so it must be escaped.
Character limits for command line parameters - Extended ASCII transformation
The null character (0x00) cannot appear in any string on the command line. Any other single byte character can appear in the string (0x01 - 0xFF). However, FINDSTR converts many extended ASCII characters it finds within command line parameters into other characters. This has a major impact in two ways:
Many extended ASCII characters will not match themselves if used as a search string on the command line. This limitation is the same for literal and regex searches. If a search string must contain extended ASCII, then the /G:FILE
option should be used instead.
FINDSTR may fail to find a file if the name contains extended ASCII characters and the file name is specified on the command line. If a file to be searched contains extended ASCII in the name, then the /F:FILE
option should be used instead.
Here is a complete list of extended ASCII character transformations that FINDSTR performs on command line strings. Each character is represented as the decimal byte code value. The first code represents the character as supplied on the command line, and the second code represents the character it is transformed into. Note - this list was compiled on a U.S machine. I do not know what impact other languages may have on this list.
158 treated as 080 199 treated as 221 226 treated as 071
169 treated as 170 200 treated as 043 227 treated as 112
176 treated as 221 201 treated as 043 228 treated as 083
177 treated as 221 202 treated as 045 229 treated as 115
178 treated as 221 203 treated as 045 231 treated as 116
179 treated as 221 204 treated as 221 232 treated as 070
180 treated as 221 205 treated as 045 233 treated as 084
181 treated as 221 206 treated as 043 234 treated as 079
182 treated as 221 207 treated as 045 235 treated as 100
183 treated as 043 208 treated as 045 236 treated as 056
184 treated as 043 209 treated as 045 237 treated as 102
185 treated as 221 210 treated as 045 238 treated as 101
186 treated as 221 211 treated as 043 239 treated as 110
187 treated as 043 212 treated as 043 240 treated as 061
188 treated as 043 213 treated as 043 242 treated as 061
189 treated as 043 214 treated as 043 243 treated as 061
190 treated as 043 215 treated as 043 244 treated as 040
191 treated as 043 216 treated as 043 245 treated as 041
192 treated as 043 217 treated as 043 247 treated as 126
193 treated as 045 218 treated as 043 249 treated as 250
194 treated as 045 219 treated as 221 251 treated as 118
195 treated as 043 220 treated as 095 252 treated as 110
196 treated as 045 222 treated as 221 254 treated as 221
197 treated as 043 223 treated as 095
198 treated as 221 224 treated as 097
Any character >0 not in the list above is treated as itself, including <CR>
and <LF>
. The easiest way to include odd characters like <CR>
and <LF>
is to get them into an environment variable and use delayed expansion within the command line argument.
Character limits for strings found in files specified by /G:FILE and /F:FILE options
The nul (0x00) character can appear in the file, but it functions like the C string terminator. Any characters after a nul character are treated as a different string as if they were on another line.
The <CR>
and <LF>
characters are treated as line terminators that terminate a string, and are not included in the string.
All other single byte characters are included perfectly within a string.
Searching Unicode files
FINDSTR cannot properly search most Unicode (UTF-16, UTF-16LE, UTF-16BE, UTF-32) because it cannot search for nul bytes and Unicode typically contains many nul bytes.
However, the TYPE command converts UTF-16LE with BOM to a single byte character set, so a command like the following will work with UTF-16LE with BOM.
type unicode.txt|findstr "search"
Note that Unicode code points that are not supported by your active code page will be converted to ?
characters.
It is possible to search UTF-8 as long as your search string contains only ASCII. However, the console output of any multi-byte UTF-8 characters will not be correct. But if you redirect the output to a file, then the result will be correctly encoded UTF-8. Note that if the UTF-8 file contains a BOM, then the BOM will be considered as part of the first line, which could throw off a search that matches the beginning of a line.
It is possible to search multi-byte UTF-8 characters if you put your search string in a UTF-8 encoded search file (without BOM), and use the /G option.
End Of Line
FINDSTR breaks lines immediately after every <LF>. The presence or absence of <CR> has no impact on line breaks.
Searching across line breaks
As expected, the .
regex metacharacter will not match <CR> or <LF>. But it is possible to search across a line break using a command line search string. Both the <CR> and <LF> characters must be matched explicitly. If a multi-line match is found, only the 1st line of the match is printed. FINDSTR then doubles back to the 2nd line in the source and begins the search all over again - sort of a "look ahead" type feature.
Assume TEXT.TXT has these contents (could be Unix or Windows style)
A
A
A
B
A
A
Then this script
@echo off
setlocal
::Define LF variable containing a linefeed (0x0A)
set LF=^
::Above 2 blank lines are critical - do not remove
::Define CR variable containing a carriage return (0x0D)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
setlocal enableDelayedExpansion
::regex "!CR!*!LF!" will match both Unix and Windows style End-Of-Line
findstr /n /r /c:"A!CR!*!LF!A" TEST.TXT
gives these results
1:A
2:A
5:A
Searching across line breaks using the /G:FILE option is imprecise because the only way to match <CR> or <LF> is via a regex character class range expression that sandwiches the EOL characters.
[<TAB>-<0x0B>]
matches <LF>, but it also matches <TAB> and <0x0B>
[<0x0C>-!]
matches <CR>, but it also matches <0x0C> and !
Note - the above are symbolic representations of the regex byte stream since I can't graphically represent the characters.
By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.
So just set it to:
<style name="AppTheme" parent="android:Theme.Holo" />
I assume you are using integers to represent your year, month, and day? If you want to remain consistent, use the Date methods.
Calendar cal = new Calendar();
int currentYear, currentMonth, currentDay;
currentYear = cal.get(Calendar.YEAR);
currentMonth = cal.get(Calendar.MONTH);
currentDay = cal.get(Calendar.DAY_OF_WEEK);
if(startYear < currentYear)
{
message = message + "Start Date is Before Today" + "\n";
}
else if(startMonth < currentMonth && startYear <= currentYear)
{
message = message + "Start Date is Before Today" + "\n";
}
else if(startDay < currentDay && startMonth <= currentMonth && startYear <= currentYear)
{
message = message + "Start Date is Before Today" + "\n";
}
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
a = 5
makes the variable name a
to refer to the integer 5. Later, a = "hello"
makes the variable name a
to refer to a string containing "hello". Static typed languages would have you declare int a
and then a = 5
, but assigning a = "hello"
would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a
refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.a = "5"
(the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5
to get "hello5"
.Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node. In the image description screenshot, the XPath text() function will only locate Success in DOM Example 2. It will not find success in DOM Example 1 because it's located between the tags.
In addition, the text() function will not find success in DOM Example 3 because success does not have a direct relationship to the element . Here's a video demo explaining the difference between text() and dot (.) https://youtu.be/oi2Q7-0ZIBg
pd.options.display
This answer is a variation of the prior answer by lucidyan. It makes the code more readable by avoiding the use of set_option
.
After importing pandas, as an alternative to using the context manager, set such options for displaying large dataframes:
def set_pandas_display_options() -> None:
"""Set pandas display options."""
# Ref: https://stackoverflow.com/a/52432757/
display = pd.options.display
display.max_columns = 1000
display.max_rows = 1000
display.max_colwidth = 199
display.width = None
# display.precision = 2 # set as needed
set_pandas_display_options()
After this, you can use either display(df)
or just df
if using a notebook, otherwise print(df)
.
to_string
Pandas 0.25.3 does have DataFrame.to_string
and Series.to_string
methods which accept formatting options.
to_markdown
If what you need is markdown output, Pandas 1.0.0 has DataFrame.to_markdown
and Series.to_markdown
methods.
to_html
If what you need is HTML output, Pandas 0.25.3 does have a DataFrame.to_html
method but not a Series.to_html
. Note that a Series
can be converted to a DataFrame
.
just put all apache comons jar and file upload jar in lib folder of tomcat
Java implementation contains utilities classes java.util.Arrays and java.util.Collections both of them contains static factory methods, examples of it and how to use :
Arrays.asList("1","2","3")
Collections.synchronizedList(..), Collections.emptyList(), Collections.unmodifiableList(...)
(Only some examples, could check javadocs for mor methods examples https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html)
Also java.lang.String class have such static factory methods:
String.format(...), String.valueOf(..), String.copyValueOf(...)
object.setForeground(Color.green);
*any colour you wish *object being declared earlier
To get the last element of an array, use:
$lastElement = array_slice($array, -1)[0];
Benchmark
I iterated 1,000 times, grabbing the last element of small and large arrays that contained 100 and 50,000 elements, respectively.
Method: $array[count($array)-1];
Small array (s): 0.000319957733154
Large array (s): 0.000526905059814
Note: Fastest! count() must access an internal length property.
Note: This method only works if the array is naturally-keyed (0, 1, 2, ...).
Method: array_slice($array, -1)[0];
Small array (s): 0.00145292282104
Large array (s): 0.499367952347
Method: array_pop((array_slice($array, -1, 1)));
Small array (s): 0.00162816047668
Large array (s): 0.513121843338
Method: end($array);
Small array (s): 0.0028350353241
Large array (s): 4.81077480316
Note: Slowest...
I used PHP Version 5.5.32.
On your storyboard page, go to File Inspector and uncheck 'Use Size Classes'. This should shrink your view controller to regular IPhone size you were familiar with. Note that using 'size classes' will let you design your project across many devices. Once you uncheck this the Xcode will give you a warning dialogue as follows. This should be self-explainatory.
"Disabling size classes will limit this document to storing data for a single device family. The data for the size class best representing the targeted device will be retained, and all other data will be removed. In addition, segues will be converted to their non-adaptive equivalents."
I have issue with itextsharp and itextsharp.xmlworker dlls for exception-from-hresult-0x80131040 so I have removed those both dlls from references and downloaded new dlls directly from nuget packages, which resolved my issue.
May be this method can be useful to resolved the issue to other people.
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
This is also working, avoiding to call for an element id but calling it using as an array element.
The following code is based on the fact that an array, named as the radiobuttons group, is composed by radiobuttons elements in the same order as they where declared in the html document:
if(!document.yourformname.yourradioname[0].checked
&& !document.yourformname.yourradioname[1].checked){
alert('is this working for all?');
return false;
}
Here my example. Supper simple
$(document).ready(function() {_x000D_
_x000D_
var textarea = $("#my_textarea");_x000D_
_x000D_
textarea.keydown(function(event) {_x000D_
_x000D_
var numbOfchars = textarea.val();_x000D_
var len = numbOfchars.length;_x000D_
$(".chars-counter").text(len);_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="my_textarea" class="uk-textarea" rows="5" name="text"></textarea>_x000D_
<h1 class="chars-counter">0</h1>
_x000D_
public static void Main()
{
int a,b=0;
int []arr={1, 2, 2, 3, 3, 4, 5, 6, 5, 7, 7, 7, 100, 8, 1};
for(int i=arr.Length-1 ; i>-1 ; i--)
{
a = arr[i];
if(a > b)
{
b=a;
}
}
Console.WriteLine(b);
}
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text);
}
If this is where you're getting the null pointer exception, there was no view found for the id that you passed into findViewById()
, and the actual exception is thrown when you try to call a function setText()
on null
. You should post your XML for R.layout.activity_main
, as it's hard to tell where things went wrong just by looking at your code.
More reading on null pointers: What is a NullPointerException, and how do I fix it?
CSS for that td: white-space: nowrap;
should solve it.
Put the assets folder in the main/src/assets
path.
inside onstart command put START_STICKY
... This service won't kill unless it is doing too much task and kernel wants to kill it for it...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Long story short, EOF
marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline.
A lot of confusion comes from how cat
actually works it seems.
You can use cat
with >>
or >
as follows:
$ cat >> temp.txt
line 1
line 2
While cat
can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
Heredoc allows to define your entire input as if you are not working with stdin
but typing in a separate text editor. This is what Wikipedia article means by:
it is a section of a source code file that is treated as if it were a separate file.
You can use 'required' http://jsbin.com/atefuq/1/edit
<form action="login.php" method="post">
<label>Login Name:</label>
<input required type="text" name="email" id="log" />
<label>Password:</label>
<input required type="password" name="password" id="pwd" />
<input required type="submit" name="submit" value="Login" />
</form>
simply add android:indeterminateTint="@color/colorPrimary"
to your progressBar
Example:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminateTint="@color/colorPrimary"/>
in case of progressBarStyleHorizontal change android:progressTint="@color/colorPrimary"
Example:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progress="50"
android:progressTint="@color/colorPrimary" />
var x = $(this).attr("name");
$("#" + x).hide();
With latest git you may use --patch
option
git stash push --patch # since 2.14.6
git stash save --patch # for older git versions
And git will ask you for each change in your files to add or not into stash.
You just answer y
or n
UPD
Alias for DOUBLE STASH:
git config --global alias.stash-staged '!bash -c "git stash --keep-index; git stash push -m "staged" --keep-index; git stash pop stash@{1}"'
Now you can stage your files and then run git stash-staged
.
As result your staged files will be saved into stash.
If you do not want to keep staged files and want move them into stash. Then you can add another alias and run git move-staged
:
git config --global alias.move-staged '!bash -c "git stash-staged;git commit -m "temp"; git stash; git reset --hard HEAD^; git stash pop"'
There is no explicit Clone
button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.
First create an image from an existing EC2 instance.
Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.
Then, you need to create a new instance and use that image as the AMI.
If you are popping it in the DOM then try wrapping it in
<pre>
<code>{JSON.stringify(REPLACE_WITH_OBJECT, null, 4)}</code>
</pre>
makes a little easier to visually parse.
When you get an Error:
ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running?
The Solution would be:
First, try verifying Docker Service is Up and Running as expected on your remote/local machine:sudo service docker status
if Not - run sudo service docker start
or sudo systemctl start docker
(depends on some linux versions, see Docker get started instructions).
Second, start docker as sudo sudo docker-compose up
There are plenty of answers on SO and good posts on the web about mocking. One place that you might want to start looking is the post by Martin Fowler Mocks Aren't Stubs where he discusses a lot of the ideas of mocking.
In one paragraph - Mocking is one particlar technique to allow testing of a unit of code with out being reliant upon dependencies. In general, what differentiates mocking from other methods is that mock objects used to replace code dependencies will allow expectations to be set - a mock object will know how it is meant to be called by your code and how to respond.
Your original question mentioned TypeMock, so I've left my answer to that below:
TypeMock is the name of a commercial mocking framework.
It offers all the features of the free mocking frameworks like RhinoMocks and Moq, plus some more powerful options.
Whether or not you need TypeMock is highly debatable - you can do most mocking you would ever want with free mocking libraries, and many argue that the abilities offered by TypeMock will often lead you away from well encapsulated design.
As another answer stated 'TypeMocking' is not actually a defined concept, but could be taken to mean the type of mocking that TypeMock offers, using the CLR profiler to intercept .Net calls at runtime, giving much greater ability to fake objects (not requirements such as needing interfaces or virtual methods).
If the script is short and is meant to be embedded inside your script and you are running under bash
shell and also bash
shell is available on the remote side, you may use declare
to transfer local context to remote. Define variables and functions containing the state that will be transferred to the remote. Define a function that will be executed on the remote side. Then inside a here document read by bash -s
you can use declare -p
to transfer the variable values and use declare -f
to transfer function definitions to the remote.
Because declare
takes care of the quoting and will be parsed by the remote bash
, the variables are properly quoted and functions are properly transferred. You may just write the script locally, usually I do one long function with the work I need to do on the remote side. The context has to be hand-picked, but the following method is "good enough" for any short scripts and is safe - should properly handle all corner cases.
somevar="spaces or other special characters"
somevar2="!@#$%^"
another_func() {
mkdir -p "$1"
}
work() {
another_func "$somevar"
touch "$somevar"/"$somevar2"
}
ssh user@server 'bash -s' <<EOT
$(declare -p somevar somevar2) # transfer variables values
$(declare -f work another_func) # transfer function definitions
work # call the function
EOT
I am currently creating plugins for a retail software brand, which are actually .net class libraries. As a requirement, each plugin needs to be configured using a config file. After a bit of research and testing, I compiled the following class. It does the job flawlessly. Note that I haven't implemented local exception handling in my case because, I catch exceptions at a higher level.
Some tweaking maybe needed to get the decimal point right, in case of decimals and doubles, but it works fine for my CultureInfo...
static class Settings
{
static UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
static Configuration myDllConfig = ConfigurationManager.OpenExeConfiguration(uri.Path);
static AppSettingsSection AppSettings = (AppSettingsSection)myDllConfig.GetSection("appSettings");
static NumberFormatInfo nfi = new NumberFormatInfo()
{
NumberGroupSeparator = "",
CurrencyDecimalSeparator = "."
};
public static T Setting<T>(string name)
{
return (T)Convert.ChangeType(AppSettings.Settings[name].Value, typeof(T), nfi);
}
}
App.Config file sample
<add key="Enabled" value="true" />
<add key="ExportPath" value="c:\" />
<add key="Seconds" value="25" />
<add key="Ratio" value="0.14" />
Usage:
somebooleanvar = Settings.Setting<bool>("Enabled");
somestringlvar = Settings.Setting<string>("ExportPath");
someintvar = Settings.Setting<int>("Seconds");
somedoublevar = Settings.Setting<double>("Ratio");
Credits to Shadow Wizard & MattC
Yes you use this
<a href="#google"></a>
<div id="google"></div>
But this does not create a smooth scroll just so you know.
You can also add in your CSS
html {
scroll-behavior: smooth;
}
If you're more used to using ax
objects to do your plotting, you might find the ax.xaxis.label.set_size()
easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:
import matplotlib.pyplot as plt
# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)
# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium') # relative to plt.rcParams['font.size']
# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()
I don't know of a similar way to set the suptitle size after it's created.
Under the "Goto" menu, Control + M is Jump to Matching Bracket. Works for parentheses as well.
The way that I resolved this issue was to register the COM
via regsvr32
.
ensure that the COM you are invoking is registered.
My application was using xceedcry.dll
and I was not registering it. Once I registered it, the application worked fine.
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
@Column(columnDefinition="tinyint(1) default 1")
I just tested the issue. It works just fine. Thanks for the hint.
About the comments:
@Column(name="price")
private double price = 0.0;
This one doesn't set the default column value in the database (of course).
Here is my version. It's based on the answer by @Offirmo. I made it Dash-compatible and fixed the following testcase failure:
./compute-relative.sh "/a/b/c/de/f/g" "/a/b/c/def/g/"
--> "../..f/g/"
Now:
CT_FindRelativePath "/a/b/c/de/f/g" "/a/b/c/def/g/"
--> "../../../def/g/"
See the code:
# both $1 and $2 are absolute paths beginning with /
# returns relative path to $2/$target from $1/$source
CT_FindRelativePath()
{
local insource=$1
local intarget=$2
# Ensure both source and target end with /
# This simplifies the inner loop.
#echo "insource : \"$insource\""
#echo "intarget : \"$intarget\""
case "$insource" in
*/) ;;
*) source="$insource"/ ;;
esac
case "$intarget" in
*/) ;;
*) target="$intarget"/ ;;
esac
#echo "source : \"$source\""
#echo "target : \"$target\""
local common_part=$source # for now
local result=""
#echo "common_part is now : \"$common_part\""
#echo "result is now : \"$result\""
#echo "target#common_part : \"${target#$common_part}\""
while [ "${target#$common_part}" = "${target}" -a "${common_part}" != "//" ]; do
# no match, means that candidate common part is not correct
# go up one level (reduce common part)
common_part=$(dirname "$common_part")/
# and record that we went back
if [ -z "${result}" ]; then
result="../"
else
result="../$result"
fi
#echo "(w) common_part is now : \"$common_part\""
#echo "(w) result is now : \"$result\""
#echo "(w) target#common_part : \"${target#$common_part}\""
done
#echo "(f) common_part is : \"$common_part\""
if [ "${common_part}" = "//" ]; then
# special case for root (no common path)
common_part="/"
fi
# since we now have identified the common part,
# compute the non-common part
forward_part="${target#$common_part}"
#echo "forward_part = \"$forward_part\""
if [ -n "${result}" -a -n "${forward_part}" ]; then
#echo "(simple concat)"
result="$result$forward_part"
elif [ -n "${forward_part}" ]; then
result="$forward_part"
fi
#echo "result = \"$result\""
# if a / was added to target and result ends in / then remove it now.
if [ "$intarget" != "$target" ]; then
case "$result" in
*/) result=$(echo "$result" | awk '{ string=substr($0, 1, length($0)-1); print string; }' ) ;;
esac
fi
echo $result
return 0
}
You may use str.isdigit()
and str.isalpha()
to check whether given string is positive integer and alphabet respectively.
Sample Results:
# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
str.isdigit()
returns False
if the string is a negative number or a float number. For example:
# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False
If you want to also check for the negative integers and float
, then you may write a custom function to check for it as:
def is_number(n):
try:
float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True
Sample Run:
>>> is_number('123') # positive integer number
True
>>> is_number('123.4') # positive float number
True
>>> is_number('-123') # negative integer number
True
>>> is_number('-123.4') # negative `float` number
True
>>> is_number('abc') # `False` for "some random" string
False
The above functions will return True
for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
>>> is_number('NaN')
True
In order to check whether the number is "NaN", you may use math.isnan()
as:
>>> import math
>>> nan_num = float('nan')
>>> math.isnan(nan_num)
True
Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==
. Python returns False
when nan
float is compared with itself. For example:
# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False
Hence, above function is_number
can be updated to return False
for "NaN"
as:
def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('Nan') # not a number "Nan" string
False
>>> is_number('nan') # not a number string "nan" with all lower cased
False
>>> is_number('123') # positive integer
True
>>> is_number('-123') # negative integer
True
>>> is_number('-1.12') # negative `float`
True
>>> is_number('abc') # "some random" string
False
The above function will still return you False
for the complex numbers. If you want your is_number
function to treat complex numbers as valid number, then you need to type cast your passed string to complex()
instead of float()
. Then your is_number
function will look like:
def is_number(n):
is_number = True
try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('1+2j') # Valid
True # : complex number
>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number
>>> is_number('123') # Valid
True # : positive integer
>>> is_number('-123') # Valid
True # : negative integer
>>> is_number('abc') # Invalid
False # : some random string, not a valid number
>>> is_number('nan') # Invalid
False # : not a number "nan" string
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number
function which fits your requirement.
Have a better one based on @hypo 's answer
public class GrowLabel : Label {
private bool mGrowing;
public GrowLabel() {
this.AutoSize = false;
}
private void resizeLabel() {
if (mGrowing)
return;
try {
mGrowing = true;
int width = this.Parent == null ? this.Width : this.Parent.Width;
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height + Padding.Bottom + Padding.Top;
} finally {
mGrowing = false;
}
}
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
resizeLabel();
}
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
resizeLabel();
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
resizeLabel();
}
}
int width = this.Parent == null ? this.Width : this.Parent.Width;
this allows you to use auto-grow label when docked to a parent, e.g. a panel.
this.Height = sz.Height + Padding.Bottom + Padding.Top;
here we take care of padding for top and bottom.
Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n
and you use \n
.
Exceding the maximum value of a long doesnt throw an exception, instead it cicles back. If you do this:
Long.MAX_VALUE + 1
you will notice that the result is the equivalent to Long.MIN_VALUE.
From here: java number exceeds long.max_value - how to detect?
I'm using this function based on @Murph answer. It searches inside the current directory and lists the full path:
function findit
{
$filename = $args[0];
gci -recurse -filter "*${filename}*" -file -ErrorAction SilentlyContinue | foreach-object {
$place_path = $_.directory
echo "${place_path}\${_}"
}
}
Example usage: findit myfile
I haven't seen this anywhere, either, but my instinct would be that this means that the IF
prevented the whole statement from executing.
Try to run the statement with a database where the IF
passes.
Also check if there are any triggers involved which might change the result.
[EDIT] When the standard says that this function should never return -1
, that doesn't enforce this. Java doesn't have pre and post conditions. A JDBC driver could return a random number and there was no way to stop it.
If it's important to know why this happens, run the statement against different database until you have tried all execution paths (i.e. one where the IF
returns false
and one where it returns true
).
If it's not that important, mark it off as a "clever trick" by a Microsoft engineer and remember how much you liked it when you feel like being clever yourself next time.
No validate will do the job.
<form action="whatever" method="post" novalidate>
Have you tried the following?:
textbox1.text = System.DateTime.Today.ToString("MM/dd/yy");
Be aware that 2 digit years could be bad in the future...
promise
represents a value that is not yet known deferred
represents work that is not yet finishedA promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.
Reference
Have a look at:
JPA query language
: The Java Persistence Query Language JPA Criteria API
: Using the Criteria API to Create QueriesIn general Shift + Tab works for any environment.
Change the PATH variable to include the bin directory of your PostgreSQL installation.
then add new path their....[for example]
C:\Program Files\PostgreSQL\12\bin
After that click OK
Open CMD/Command Prompt. Type this to open psql
psql -U username database_name
For Example psql -U postgres test
Now, you will be prompted to give Password for the User. (It will be hidden as a security measure).
Then you are good to go.
I resolve this error by below step :
1 : first of all write this code in terminal :
...$ which python3
/usr/bin/python3
2 : Then :
"python.pythonPath": "/users/bin/python",
done.
I was having a problem getting my ASP.NET 5.0/MVC 6 app to serve static binary file types or browse virtual directories. It looks like this is now done in Configure() at startup. See http://docs.asp.net/en/latest/fundamentals/static-files.html for a quick primer.
If you don't want something bloated like jQuery UI, try my custom animations: https://github.com/yckart/jquery-custom-animations
For you, blindLeftToggle
and blindRightToggle
is the appropriate choice.
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
import numpy as np
import PIL
def convert_image(image_file):
image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
original_width, original_height = image.size
np_image = np.array(image)
new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3))
# create 3D array
for each_channel in range(3):
new_image[:,:,each_channel] = np_image[:,:,each_channel]
# only copy first 3 channels.
# flushing
np_image = []
return new_image
There are more technical explanations for your question, but if you want a way to think about margin and padding, this analogy might help.
Imagine block elements as picture frames hanging on a wall:
With this in mind, a good rule of thumb is to use margin when you want to space an element in relationship to other elements on the wall, and padding when you're adjusting the appearance of the element itself. Margin won't change the size of the element, but padding will make the element bigger1.
1 You can alter this behavior with the box-sizing
attribute.
As a complement to other answers note that you can also put the lang
attribute on various HTML tags inside a page.
For example to give a hint to the spellchecker that the input text should be in english:
<input ... spellcheck="true" lang="en"> ...
See: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang
There are a few things wrong here:
First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".
.unix()
returns Unix Time in whole seconds, but the default moment
constructor accepts a timestamp in milliseconds. You should instead use .valueOf()
to return milliseconds. Note that calling .unix()*1000
would also work, but it would result in a loss of precision.
You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:
moment("10/15/2014 9:00", "M/D/YYYY H:mm")
.calendar()
has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format()
function instead. Again, you may want to pass a format specifier.
To answer your questions in comments, No - you don't need to call .local()
or .utc()
.
Putting it all together:
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);
On my machine, in the US Pacific time zone, it results in:
Values are: ts = 1413388800000, s = 10/15/2014 9:00
Since the input value is interpreted in terms of local time, you will get a different value for ts
if you are in a different time zone.
Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix()
to return the timestamp in whole seconds, and moment.unix(ts)
to parse it back to a moment.
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);
With the Underscore.js library:
var hash = {
foo: 1,
bar: 2
};
(_.invert(hash))[1]; // => 'foo'
You can do it with CSS:
<iframe style="position: absolute; height: 100%; border: none"></iframe>
Be aware that this will by default place it in the upper-left corner of the page, but I guess that is what you want to achieve. You can position with the left
,right
, top
and bottom
CSS properties.
I had the similar issue - could not figure out what was the reason, but I fixed it using following code. Somehow it could not focus only the blank inputs:
$('input').click(function () {
var val = $(this).val();
if (val == "") {
this.select();
}
});
The -HideTableHeaders
parameter unfortunately still causes the empty lines to be printed (and table headers appearently are still considered for column width). The only way I know that could reliably work here would be to format the output yourself:
| % { '{0,10} {1,20} {2,20}' -f $_.Operation,$_.AttributeName,$_.AttributeValue }
select so.name, text
from sysobjects so, syscomments sc
where type = 'TR'
and so.id = sc.id
and text like '%YourTableName%'
This way you can list out all the triggers associated with the given table.
When an attribute value contains a placeholder (see format below), the manifest merger will swap this placeholder value with an injected value. Injected values are specified in the build.gradle. The syntax for placeholder values is ${name} since @ is reserved for links. After the last file merging occurred, and before the resulting merged android manifest file is written out, all values with a placeholder will be swapped with injected values. A build breakage will be generated if a variable name is unknown.
from http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger#TOC-Build-error
-XX:PermSize
specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize
.
Open the sql file and comment out the line that tries to create the existing database.
Declare your progress dialog:
ProgressDialog progress;
When you're ready to start the progress dialog:
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
and to make it go away when you're done:
progress.dismiss();
Here's a little thread example for you:
// Note: declare ProgressDialog progress as a field in your class.
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new Thread(new Runnable() {
@Override
public void run()
{
// do the thing that takes a long time
runOnUiThread(new Runnable() {
@Override
public void run()
{
progress.dismiss();
}
});
}
}).start();
I had the same error message. But the cause and solution are slightly different. When I ran "ng -v" it showed different versions for angular-cli (1.0.0-beta.28.3) and @angular/cli (1.0.0-beta.31). I re-ran:
npm install -g @angular/cli
Now both show a version of 1.0.0-beta.31. The error message is gone and "ng serve" now works. (Yes - it was @angular/cli that I re-installed and the angular-cli version was updated.)
You could have switch
construct "handle" ranges by using it in conjunction with a List
of your bounds.
List<int> bounds = new List<int>() {int.MinValue, 0, 4, 9, 17, 20, int.MaxValue };
switch (bounds.IndexOf(bounds.Last(x => x < j)))
{
case 0: // <=0
break;
case 1: // >= 1 and <=4
break;
case 2: // >= 5 and <=9
break;
case 3: // >= 10 and <=17
break;
case 4: // >= 18 and <=20
break;
case 5: // >20
break;
}
With this approach ranges can have different spans.
Failed to delete C:\EclipseProjects\myGoogleAppEngine\target\myGoogleAppEngine-0.0.1-SNAPSHOT\WEB-INF\lib\spring-webmvc-3.1.0.RELEASE.jar
Because of the path C:\EclipseProjects
i guess you have eclipse running on that project. If you application runs, you cannot clean the output, because it may be in use.
Stop the application and maybe eclipse and try again.
read
reads until it finds a newline character or the end of file, and returns a non-zero exit code if it encounters an end-of-file. So it's quite possible for it to both read a line and return a non-zero exit code.
Consequently, the following code is not safe if the input might not be terminated by a newline:
while read LINE; do
# do something with LINE
done
because the body of the while
won't be executed on the last line.
Technically speaking, a file not terminated with a newline is not a text file, and text tools may fail in odd ways on such a file. However, I'm always reluctant to fall back on that explanation.
One way to solve the problem is to test if what was read is non-empty (-n
):
while read -r LINE || [[ -n $LINE ]]; do
# do something with LINE
done
Other solutions include using mapfile
to read the file into an array, piping the file through some utility which is guaranteed to terminate the last line properly (grep .
, for example, if you don't want to deal with blank lines), or doing the iterative processing with a tool like awk
(which is usually my preference).
Note that -r
is almost certainly needed in the read
builtin; it causes read
to not reinterpret \
-sequences in the input.
Figured it out. Used this instead.
$('.div_class').load('http://en.wikipedia.org/wiki/Cross-origin_resource_sharing #toctitle');
Example:
iptables -A INPUT -j LOG --log-prefix "INPUT:DROP:" --log-level 6
iptables -A INPUT -j DROP
Log Exampe:
Feb 19 14:18:06 servername kernel: INPUT:DROP:IN=eth1 OUT= MAC=aa:bb:cc:dd:ee:ff:11:22:33:44:55:66:77:88 SRC=x.x.x.x DST=x.x.x.x LEN=48 TOS=0x00 PREC=0x00 TTL=117 ID=x PROTO=TCP SPT=x DPT=x WINDOW=x RES=0x00 SYN URGP=0
Other options:
LOG
Turn on kernel logging of matching packets. When this option
is set for a rule, the Linux kernel will print some
information on all matching packets
(like most IP header fields) via the kernel log (where it can
be read with dmesg or syslogd(8)). This is a "non-terminating
target", i.e. rule traversal
continues at the next rule. So if you want to LOG the packets
you refuse, use two separate rules with the same matching
criteria, first using target LOG
then DROP (or REJECT).
--log-level level
Level of logging (numeric or see syslog.conf(5)).
--log-prefix prefix
Prefix log messages with the specified prefix; up to 29
letters long, and useful for distinguishing messages in
the logs.
--log-tcp-sequence
Log TCP sequence numbers. This is a security risk if the
log is readable by users.
--log-tcp-options
Log options from the TCP packet header.
--log-ip-options
Log options from the IP packet header.
--log-uid
Log the userid of the process which generated the packet.
For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess
object, from which you can easily obtain the output as well as return code. Since you are only interested in the output, you can write a utility wrapper like this.
from subprocess import PIPE, run
def out(command):
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
return result.stdout
my_output = out("echo hello world")
# Or
my_output = out(["echo", "hello world"])
I believe the main (only?) different is inheritance:
class T < S
end
p T.k
=> 23
S.k = 24
p T.k
=> 24
p T.s
=> nil
Class variables are shared by all "class instances" (i.e. subclasses), whereas class instance variables are specific to only that class. But if you never intend to extend your class, the difference is purely academic.
Here is how I would do it, (however I would use an external style sheet for this project and all others. just makes things easier to work with. Also this example is with html5.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.container {
display:inline-block;
}
</style>
</head>
<body>
<div class="container">
<figure>
<img src="http://placehold.it/350x150" height="200" width="200">
<figcaption>This is image 1</figcaption>
</figure>
<figure>
<img class="middle-img" src="http://placehold.it/350x150"/ height="200" width="200">
<figcaption>This is image 2</figcaption>
</figure>
<figure>
<img src="http://placehold.it/350x150" height="200" width="200">
<figcaption>This is image 3</figcaption>
</figure>
</div>
</body>
</html>
Try this:
location / {
root /path/to/root;
expires 30d;
access_log off;
}
location ~* ^.*\.php$ {
if (!-f $request_filename) {
return 404;
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php
should be forwared to Apache if only a corresponding .php
file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.
Days
ClassUsing the Days
class with the withTimeAtStartOfDay
method should work:
Days.daysBetween(start.withTimeAtStartOfDay() , end.withTimeAtStartOfDay() ).getDays()
I tested the following procedure under macOS Mojave 10.14.6 (18G3020).
Launch Automator. Create a document of type “Quick Action”:
(In older versions of macOS, use the “Service” template.)
In the new Automator document, add a “Run AppleScript” action. (You can type “run applescript” into the search field at the top of the action list to find it.) Here's the AppleScript to paste into the action:
on run {input, parameters}
tell application "Terminal"
if it is running then
do script ""
end if
activate
end tell
end run
Set the “Workflow receives” popup to “no input”. It should look like this overall:
Save the document with the name “New Terminal”. Then go to the Automator menu (or the app menu in any running application) and open the Services submenu. You should now see the “New Terminal” quick action:
If you click the “New Terminal” menu item, you'll get a dialog box:
Click OK to allow the action to run. You'll see this dialog once in each application that's frontmost when you use the action. In other words, the first time you use the action while Finder is frontmost, you'll see the dialog. And the first time you use the action while Safari is frontmost, you'll see the dialog. And so on.
After you click OK in the dialog, Terminal should open a new window.
To assign a keyboard shortcut to the quick action, choose the “Services Preferences…” item from the Services menu. (Or launch System Preferences, choose the Keyboard pane, then choose the Shortcuts tab, then choose Services from the left-hand list.) Scroll to the bottom of the right-hand list and find the New Terminal service. Click it and you should see an “Add Shortcut” button:
Click the button and press your preferred keyboard shortcut. Then, scratch your head, because (when I tried it) the Add Shortcut button reappears. But click the button again and you should see your shortcut:
Now you should be able to press your keyboard shortcut in most circumstances to get a new terminal window.
IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment
Will do the job as Buttle Butkus suggested.
I came across this post
by Minko Gechev which clearly explains the major differences.
For setting value in hidden field do in the following way:
@Html.HiddenFor(model => model.title,
new { id= "natureOfVisitField", Value = @Model.title})
It will work
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.
I'm disappointed Microsoft didn't offer a neat, fast and easy solution like Ruby are doing with the
clone()
method.
Except that does not create a deep copy, it creates a shallow copy.
With deep copying, you have to be always careful, what exactly do you want to copy. Some examples of possible issues are:
Book
has an Author
and Author
has a list of his Book
s.Stream
that writes to a file.Window
.Now, there are basically two ways how to clone something:
Clone()
method in each class that you need cloned. (There is also ICloneable
interface, but you should not use that; using a custom ICloneable<T>
interface as Trevor suggested is okay.) If you know that all you need is to create a shallow copy of each field of this class, you could use MemberwiseClone()
to implement it. As an alternative, you could create a “copy constructor”: public Book(Book original)
.MemoryStream
and then deserialize them back. This requires you to mark each class as [Serializable]
and it can also be configured what exactly (and how) should be serialized. But this is more of a “quick and dirty” solution, and will most likely also be less performant.If the present data is not important for you, you can just take down your original migration using:
rake db:migrate:down VERSION='YOUR MIGRATION FILE VERSION HERE'
Without the quotes, then make changes in the original migration and run the up migration again by:
rake db:migrate
XMLSpectrum formats XML, supports attribute indentation and also does syntax-highlighting for XML and any embedded XPath expressions:
XMLSpectrum is an open source project, coded in XSLT 2.0 - so you can run this server-side with a processor such as Saxon-HE (recommended) or client-side using Saxon-CE.
XMLSpectrum is not yet optimised to run in the browser - hence the recommendation to run this server-side.
On Linux, Unix, Git Bash, or Cygwin, try:
rm -f .git/index.lock
On Windows Command Prompt, try:
del .git\index.lock
For Windows:
From a PowerShell console opened as administrator, try
rm -Force ./.git/index.lock
If that does not work, you must kill all git.exe processes
taskkill /F /IM git.exe
SUCCESS: The process "git.exe" with PID 20448 has been terminated.
SUCCESS: The process "git.exe" with PID 11312 has been terminated.
SUCCESS: The process "git.exe" with PID 23868 has been terminated.
SUCCESS: The process "git.exe" with PID 27496 has been terminated.
SUCCESS: The process "git.exe" with PID 33480 has been terminated.
SUCCESS: The process "git.exe" with PID 28036 has been terminated. \
rm -Force ./.git/index.lock
Apart of larsmans answer (who is indeed correct), the exception in a call to a get() method, so the code you have posted is not the one that is causing the error.
If your repo is of HTTPS repo, git config -e give this command in the git bash. Update the username and password by opening in insert mode, change the password or username give :x and Cntrl+z keys it will save and exit
So, From then while you pull / push the code to the repository it will not ask for password.
I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.
The code below was simplyfied.
List<SelectListItem> items = new List<SelectListItem>();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("Texto", "1");
dictionary.Add("Foto", "2");
dictionary.Add("Vídeo", "3");
foreach (KeyValuePair<string, string> pair in objBLL.GetTiposPost())
{
items.Add(new SelectListItem() { Text = pair.Key, Value = pair.Value, Selected = false });
}
ViewBag.TiposPost = new SelectList(items, "Value", "Text");
In the View, I used a foreach to build a radiobutton.
<div class="form-group">
<div class="col-sm-10">
@foreach (var item in (SelectList)ViewBag.TiposPost)
{
@Html.RadioButtonFor(model => model.IDTipoPost, item.Value, false)
<label class="control-label">@item.Text</label>
}
</div>
</div>
Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.
Hope it's useful!
None of the above worked for me. what worked for me is to go to File -> Invalidate Caches / Restart
You are on the right track about hostvars
.
This magic variable is used to access information about other hosts.
hostvars
is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1']
, hostvars['test2-1']
, etc.
ansible_ssh_host
is deprecated in favor of ansible_host
since 2.0.
So you should first remove "_ssh" from inventory hosts arguments (i.e. to become "ansible_user", "ansible_host", and "ansible_port"), then in your role call it with:
{{ hostvars['your_host_group'].ansible_host }}
I actually wrote a patch to do this a few months ago (after someone asked about it in #angularjs on freenode).
It probably won't be merged, but it's very similar to ngClass: https://github.com/angular/angular.js/pull/4269
Whether it gets merged or not, the existing ng-attr-* stuff is probably suitable for your needs (as others have mentioned), although it might be a bit clunkier than the more ngClass-style functionality that you're suggesting.
There is another way. There is a program called PowerRun which allows for elevated cmd to be run. Even with TrustedInstaller rights. It allows for both console and GUI commands.
To show a simple star rating in round figure just use this code
public static String getIntToStar(int starCount) {
String fillStar = "\u2605";
String blankStar = "\u2606";
String star = "";
for (int i = 0; i < starCount; i++) {
star = star.concat(" " + fillStar);
}
for (int j = (5 - starCount); j > 0; j--) {
star = star.concat(" " + blankStar);
}
return star;
}
And use it like this
button.setText(getIntToStar(4));
I have been having the same issue and tried everything written here but it was still giving me the same error. Turned out to be NULL value in the column which I was trying to convert.
Removing the NULL value solved my issue.
Cheers, Ahmed
You can use jQuery.is()
function along with :disabled
selector:
$("#savematerial").is(":disabled")
Click anywhere in chrome window and type thisisunsafe
(instead of badidea
previously) in chrome.
This passphrase may change in future. This is the source
According to that line, type window.atob('dGhpc2lzdW5zYWZl')
to your browser console and it will give you the actual passphrase.
This time the passphrase is thisisunsafe
.
This takes into account blank characters other than space and I think it's faster than using re
module:
url = "_".join( title.split() )
declare @puvodni nvarchar(20)
set @puvodni = N'abc1d8e8ttr987avc'
WHILE PATINDEX('%[^0-9]%', @puvodni) > 0 SET @puvodni = REPLACE(@puvodni, SUBSTRING(@puvodni, PATINDEX('%[^0-9]%', @puvodni), 1), '' )
SELECT @puvodni
This is a well-known old question, but I'd like to share some more insights about modern programming language research and design.
Traditionally (in the sense of structured programming) and informally, a procedure is a reusable structural construct to have "input" and to do something programmable. When something is needed to be done within a procedure, you can provide (actual) arguments to the procedure in a procedure call coded in the source code (usually in a kind of an expression), and the actions coded in the procedures body (provided in the definition of the procedure) will be executed with the substitution of the arguments into the (formal) parameters used in the body.
A function is more than a procedure because return values can also be specified as the "output" in the body. Function calls are more or less same to procedure calls, except that you can also use the result of the function call, syntactically (usually as a subexpression of some other expression).
Traditionally, procedure calls (rather than function calls) are used to indicate that no output must be interested, and there must be side effects to avoid the call being no-ops, hence emphasizing the imperative programming paradigm. Many traditional programming languages like Pascal provide both "procedures" and "functions" to distinguish this intentional difference of styles.
(To be clear, the "input" and "output" mentioned above are simplified notions based on the syntactic properties of functions. Many languages additionally support passing arguments to parameters by reference/sharing, to allow users transporting information encoded in arguments during the calls. Such parameter may even be just called as "in/out parameter". This feature is based on the nature of the objects being passed in the calls, which is orthogonal to the properties of the feature of procedure/function.)
However, if the result of a function call is not needed, it can be just (at least logically) ignored, and function definitions/function calls should be consistent to procedure definitions/procedure calls in this way. ALGOL-like languages like C, C++ and Java, all provide the feature of "function" in this fashion: by encoding the result type void
as a special case of functions looking like traditional procedures, there is no need to provide the feature of "procedures" separately. This prevents some bloat in the language design.
Since SICP is mentioned, it is also worth noting that in the Scheme language specified by RnRS, a procedure may or may not have to return the result of the computation. This is the union of the traditional "function" (returning the result) and "procedure" (returning nothing), essentially same to the "function" concept of many ALGOL-like languages (and actually sharing even more guarantees like applicative evaluations of the operands before the call). However, old-fashion differences still occur even in normative documents like SRFI-96.
I don't know much about the exact reasons behind the divergence, but as I have experienced, it seems that language designers will be happier without specification bloat nowadays. That is, "procedure" as a standalone feature is unnecessary. Techniques like void
type is already sufficient to mark the use where side effects should be emphasized. This is also more natural to users having experiences on C-like languages, which are popular more than a few decades. Moreover, it avoids the embarrassment in cases like RnRS where "procedures" are actually "functions" in the broader sense.
In theory, a function can be specified with a specified unit type as the type of the function call result to indicate that result is special. This distinguishes the traditional procedures (where the result of a call is uninterested) from others. There are different styles in the design of a language:
#inert
) also works.void
type in ALGOL-like languages is exactly an example of this technique. ISO C11's _Noreturn
is a similar but more subtle one in this kind.As the traditional concept derived from math, there are tons of black magic most people do not bother to know. Strictly speaking, you won't be likely get the whole things clear as per your math books. CS books might not provide much help, either.
With concerning of programming languages, there are several caveats:
{{{}}, {}}
...) besides some limited contexts.As of API 24, sending a file://
URI to another app will throw a FileUriExposedException. Instead, use FileProvider to send a content://
URI:
public File getFile(Context context, String fileName) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
File storageDir = context.getExternalFilesDir(null);
return new File(storageDir, fileName);
}
public Uri getFileUri(Context context, String fileName) {
File file = getFile(context, fileName);
return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
}
You must also define the FileProvider in your manifest:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Example file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="name" path="path" />
</paths>
Replace "name" and "path" as appropriate.
To give the PDF viewer access to the file, you also have to add the FLAG_GRANT_READ_URI_PERMISSION
flag to the intent:
private void displayPdf(String fileName) {
Uri uri = getFileUri(this, fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
// FLAG_GRANT_READ_URI_PERMISSION is needed on API 24+ so the activity opening the file can read it
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getPackageManager()) == null) {
// Show an error
} else {
startActivity(intent);
}
}
See the FileProvider documentation for more details.
This should work:
$(document).ready(function() {
$("someTableSelector").find("tr:gt(0)").remove();
});
To avoid using integer values to identify the VideoCapture
properties, one can use, e.g., cv2.cv.CV_CAP_PROP_FPS
in OpenCV 2.4 and cv2.CAP_PROP_FPS
in OpenCV 3.0. (See also Stefan's comment below.)
Here a utility function that works for both OpenCV 2.4 and 3.0:
# returns OpenCV VideoCapture property id given, e.g., "FPS"
def capPropId(prop):
return getattr(cv2 if OPCV3 else cv2.cv,
("" if OPCV3 else "CV_") + "CAP_PROP_" + prop)
OPCV3
is set earlier in my utilities code like this:
from pkg_resources import parse_version
OPCV3 = parse_version(cv2.__version__) >= parse_version('3')
You can use
if errorlevel 1 echo Unsuccessful
in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.
Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.
I believe it adds them there for consistency... they're only required when you have a space or special character in the column name, but it's cleaner to just include them all the time when the IDE generates SQL.
I found these two links very helpful while I was trying to learn socket.io:
Here's a table to help find the required flags for different permission combinations.
+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ ¦ ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦ files ¦ ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦ ¦ Propagation ¦ none ¦ none ¦ none ¦ none ¦ InheritOnly ¦ InheritOnly ¦ InheritOnly ¦ ¦ Inheritance ¦ none ¦ Container|Object ¦ Container ¦ Object ¦ Container|Object ¦ Container ¦ Object ¦ +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
So, as David said, you'll want
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit PropagationFlags.None
For Windows 7 and up, scheduled tasks are not run by cmd.exe
, but rather by MMC
(Microsoft Management Console). %SystemRoot%\Tasks
should work on any other Windows version though.
Based on your comment, moddify this:
$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV
to:
$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV
More about selectors: https://api.jquery.com/category/selectors/
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
Calculate row means on a subset of columns:
Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled 'Means':
data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))
ID Means
1 A 3.666667
2 B 4.333333
3 C 3.333333
4 D 4.666667
5 E 4.333333
If you use PHP 7.4 or later you can also do it using arrow function so it looks cleaner:
Post::with(['user' => fn ($query) => $query->select('id','username')])->get();
I had the same question but figured it out finally. What you most likely need to do is run the following two git commands (replacing hash with the git commit revision number):
git checkout <hash>
git push -f HEAD:master
Unfortunately, the offered solution doesn't work in Safari 10+, since Apple has decided to ignore user-scalable=no
. This thread has more details and some JS hacks: disable viewport zooming iOS 10+ safari?
If you installed as admin ( and meant for all users )
C:\ProgramData\Anaconda3\Scripts\anaconda.exe
If you install as a normal user
C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe
Function xrand() As Long
Dim r1 As Long = Now.Day & Now.Month & Now.Year & Now.Hour & Now.Minute & Now.Second & Now.Millisecond
Dim RAND As Long = Math.Max(r1, r1 * 2)
Return RAND
End Function
[BBOYSE] This its the best way, from scratch :P
For me above solutions didn't work then I tried
map.setCenter(new google.maps.LatLng(lat, lng));
and it worked as expected.
The way to check for null is to check for it:
DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");
You can use and
and or
in the Select
statement.
thanks for answer @Cristian i was getting error
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
i solved this using
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
-----
-----
}
To rotate, you can use key frames and a transform.
div {
margin: 20px;
width: 100px;
height: 100px;
background: #f00;
-webkit-animation-name: spin;
-webkit-animation-duration: 40000ms;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-moz-animation-name: spin;
-moz-animation-duration: 40000ms;
-moz-animation-iteration-count: infinite;
-moz-animation-timing-function: linear;
-ms-animation-name: spin;
-ms-animation-duration: 40000ms;
-ms-animation-iteration-count: infinite;
-ms-animation-timing-function: linear;
}
@-webkit-keyframes spin {
from {
-webkit-transform:rotate(0deg);
}
to {
-webkit-transform:rotate(360deg);
}
}
If you just need some views not to use CSRF, you can use @csrf_exempt
:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
You can find more examples and other scenarios in the Django documentation:
Here's a quick ruby script that corrals up the impact per user against a given log query.
For example, for rubinius:
Brian Ford: 4410668
Evan Phoenix: 1906343
Ryan Davis: 855674
Shane Becker: 242904
Alexander Kellett: 167600
Eric Hodel: 132986
Dirkjan Bussink: 113756
...
the script:
#!/usr/bin/env ruby
impact = Hash.new(0)
IO.popen("git log --pretty=format:\"%an\" --shortstat #{ARGV.join(' ')}") do |f|
prev_line = ''
while line = f.gets
changes = /(\d+) insertions.*(\d+) deletions/.match(line)
if changes
impact[prev_line] += changes[1].to_i + changes[2].to_i
end
prev_line = line # Names are on a line of their own, just before the stats
end
end
impact.sort_by { |a,i| -i }.each do |author, impact|
puts "#{author.strip}: #{impact}"
end
As mentioned by others Android Toasts can either be LENGTH_LONG or LENGTH_SHORT. There is no way around this, nor should you follow any of the 'hacks' posted.
The purpose of Toasts are to display "non-essential" information and due to their lingering effect, messages may be put far out of context if their duration exceeds a certain threshold. If stock Toasts were modified so that they can display longer than LENGTH_LONG the message would linger on the screen until the application's process is terminated as toast views are added to the WindowManager and not a ViewGroup in your app. I would assume this is why it is hard coded.
If you absolutely need to show a toast style message longer than three and a half seconds I recommend building a view that gets attached to the Activity's content, that way it will disappear when the user exits the application. My SuperToasts library deals with this issue and many others, feel free to use it! You would most likely be interested in using SuperActivityToasts
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
<a onclick="return false;" href="http://foo.com">I want to ignore my parent's onclick event.</a>
Change:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
To:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
The groupId
of net.sourceforge
was incorrect. The correct value is net.sourceforge.ant4x
.
Making column not null and adding default can also be done in the SSMS GUI.
UPDATE myTable SET myColumn = 0
I have had similar issue on a Xamarin Project. It is maybe rare case but in case anyone else is having the issue. my project structure was like below
Extending @RobBednark's solution to a specific Windows + PuTTY scenario, you can do so:
Generate SSH key pair with PuTTYgen (following Manually generating your SSH key in Windows), saving it to a PPK file;
With the context menu in Windows Explorer, choose Edit with PuTTYgen. It will prompt for a password.
If you type the wrong password, it will just prompt again.
Note, if you like to type, use the following command on a folder that contains the PPK file: puttygen private-key.ppk -y
.
is.element()
makes for more readable code, and is identical to %in%
v <- c('a','b','c','e')
is.element('b', v)
'b' %in% v
## both return TRUE
is.element('f', v)
'f' %in% v
## both return FALSE
subv <- c('a', 'f')
subv %in% v
## returns a vector TRUE FALSE
is.element(subv, v)
## returns a vector TRUE FALSE
You don't need any extra dependencies for this! Depending on whether you need to optimize for performance or not, there are two good solutions:
URL.hostname
for readabilityIn the Babel era, the cleanest and easiest solution is to use URL.hostname
.
const getHostname = (url) => {
// use URL constructor and return hostname
return new URL(url).hostname;
}
// tests
console.log(getHostname("https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/"));
console.log(getHostname("https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname"));
_x000D_
URL.hostname
is part of the URL API, supported by all major browsers except IE (caniuse). Use a URL polyfill if you need to support legacy browsers.
Using this solution will also give you access to other URL properties and methods. This will be useful if you also want to extract the URL's pathname or query string params, for example.
URL.hostname
is faster than using the anchor solution or parseUri. However it's still much slower than gilly3's regex:
const getHostnameFromRegex = (url) => {
// run against regex
const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
// extract hostname (will be null if no match is found)
return matches && matches[1];
}
// tests
console.log(getHostnameFromRegex("https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/"));
console.log(getHostnameFromRegex("https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname"));
_x000D_
Test it yourself on this jsPerf
If you need to process a very large number of URLs (where performance would be a factor), use RegEx. Otherwise, use URL.hostname
.
OK. This is the "most elegant" solution I could come up with on the fly:
boolean allTrue = !Arrays.toString(myArray).contains("f");
Hope that helps!
If Short.TryParse(editTransactionRow.pay_id, New Short) Then editTransactionRow.pay_id.ToString()
I prefer the following over the other answers. It matches only the first letter of each word and capitalises it. Simpler code, easier to read and less bytes. It preserves existing capital letters to prevent distorting acronyms. However you can always call toLowerCase()
on your string first.
function title(str) {
return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
You can add this to your string prototype which will allow you to 'my string'.toTitle()
as follows:
String.prototype.toTitle = function() {
return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
Example:
String.prototype.toTitle = function() {_x000D_
return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });_x000D_
}_x000D_
_x000D_
console.log('all lower case ->','all lower case'.toTitle());_x000D_
console.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());_x000D_
console.log("I'm a little teapot ->","I'm a little teapot".toTitle());
_x000D_
Just to expand on and improve some of the above answers:
First, I'll check the mkdir man page for GNU Coreutils 8.26 -- it gives us this information about the option '-m' and '-p' (can also be given as --mode=MODE and --parents, respectively):
...set[s] file mode (as in chmod), not a=rwx - umask
...no error if existing, make parent directories as needed
The statements are vague and unclear in my opinion. But basically, it says that you can make the directory with permissions specified by "chmod numeric notation" (octals) or you can go "the other way" and use a/your umask.
Side note: I say "the other way" since the umask value is actually exactly what it sounds like -- a mask, hiding/removing permissions rather than "granting" them as with chmod's numeric octal notation.
You can execute the shell-builtin command umask
to see what your 3-digit umask is; for me, it's 022
. This means that when I execute mkdir yodirectory
in a given folder (say, mahome) and stat
it, I'll get some output resembling this:
755 richard:richard /mahome/yodirectory
# permissions user:group what I just made (yodirectory),
# (owner,group,others--in that order) where I made it (i.e. in mahome)
#
Now, to add just a tiny bit more about those octal permissions. When you make a directory, "your system" take your default directory perms' [which applies for new directories (its value should 777)] and slaps on yo(u)mask, effectively hiding some of those perms'. My umask is 022--now if we "subtract" 022 from 777 (technically subtracting is an oversimplification and not always correct - we are actually turning off perms or masking them)...we get 755 as stated (or "statted") earlier.
We can omit the '0' in front of the 3-digit octal (so they don't have to be 4 digits) since in our case we didn't want (or rather didn't mention) any sticky bits, setuids or setgids (you might want to look into those, btw, they might be useful since you are going 777). So in other words, 0777 implies (or is equivalent to) 777 (but 777 isn't necessarily equivalent to 0777--since 777 only specifies the permissions, not the setuids, setgids, etc.)
Now, to apply this to your question in a broader sense--you have (already) got a few options. All the answers above work (at least according to my coreutils). But you may (or are pretty likely to) run into problems with the above solutions when you want to create subdirectories (nested directories) with 777 permissions all at once. Specifically, if I do the following in mahome with a umask of 022:
mkdir -m 777 -p yodirectory/yostuff/mastuffinyostuff
# OR (you can swap 777 for 0777 if you so desire, outcome will be the same)
install -d -m 777 -p yodirectory/yostuff/mastuffinyostuff
I will get perms 755
for both yodirectory
and yostuff
, with only 777
perms for mastuffinyostuff
. So it appears that the umask
is all that's slapped on yodirectory
and yostuff
...to get around this we can use a subshell:
( umask 000 && mkdir -p yodirectory/yostuff/mastuffinyostuff )
and that's it. 777 perms for yostuff, mastuffinyostuff, and yodirectory.
In our case we were getting UnmarshalException because a wrong Java package was specified in the following. The issue was resolved once the right package was in place:
@Bean
public Unmarshaller tmsUnmarshaller() {
final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller
.setPackagesToScan("java.package.to.generated.java.classes.for.xsd");
return jaxb2Marshaller;
}
If it is something that you reference but never mutate, then use const
:
declare const bootbox;
I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:
const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))
#collect
is actually an alias for #map
. That means the two methods can be used interchangeably, and effect the same behavior.
There is a better solution to this answer that is more Angular based.
Save your string in a variable in the .ts file
MyStrings = ["one","two","three"]
In the html file use *ngFor.
<div class="one" *ngFor="let string of MyStrings; let i = index">
<div class="two">{{string}}</div>
</div>
if you want to dynamically insert the div element, just push more strings into the MyStrings array
myFunction(nextString){
this.MyString.push(nextString)
}
this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.
OK, answering to my own question.
Steps to connect LocalDB to Visual Studio Server Explorer
SqlLocalDB.exe start v11.0
SqlLocalDB.exe info v11.0
(localdb)\v11.0
. If it didn't work, use the Instance pipe name that you copied earlier. You can also use this to connect with SQL Management Studio.Read textarea value and code-char conversion:
function keys(e) {
msg.innerHTML = `last key: ${String.fromCharCode(e.keyCode)}`
if(e.key == 'Enter') {
console.log('send: ', mycon.value);
mycon.value='';
e.preventDefault();
}
}
_x000D_
Push enter to 'send'<br>
<textarea id='mycon' onkeydown="keys(event)"></textarea>
<div id="msg"></div>
_x000D_
And below nice Quake like console on div-s only :)
document.addEventListener('keyup', keys);
let conShow = false
function keys(e) {
if (e.code == 'Backquote') {
conShow = !conShow;
mycon.classList.toggle("showcon");
} else {
if (conShow) {
if (e.code == "Enter") {
conTextOld.innerHTML+= '<br>' + conText.innerHTML;
let command=conText.innerHTML.replace(/ /g,' ');
conText.innerHTML='';
console.log('Send to server:', command);
}
else if (e.code == "Backspace") {
conText.innerHTML = conText.innerText.slice(0, -1);
} else if (e.code == "Space") {
conText.innerHTML = conText.innerText + ' '
} else {
conText.innerHTML = conText.innerText + e.key;
}
}
}
}
_x000D_
body {
margin: 0
}
.con {
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: flex-start;
width: 100%;
height: 90px;
background: rgba(255, 0, 0, 0.4);
position: fixed;
top: -90px;
transition: top 0.5s ease-out 0.2s;
font-family: monospace;
}
.showcon {
top: 0px;
}
.conTextOld {
color: white;
}
.line {
display: flex;
flex-direction: row;
}
.conText{ color: yellow; }
.carret {
height: 20px;
width: 10px;
background: red;
margin-left: 1px;
}
.start { color: red; margin-right: 2px}
_x000D_
Click here and Press tilde ` (and Enter for "send")
<div id="mycon" class="con">
<div id='conTextOld' class='conTextOld'>Hello!</div>
<div class="line">
<div class='start'> > </div>
<div id='conText' class="conText"></div>
<div class='carret'></div>
</div>
</div>
_x000D_
if (select == "") {
alert("Please select a selection");
return false;
That should work for you. It just did for me.
Though this may be late, but it will be helpful to someone else.From my experience and research I have come to know and accept decimal(19, 6).That is when working with php and mysql. when working with large amount of money and exchange rate
This should do it:
<style>
body {
background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>
As mentioned above markdown itself leaves you hanging on this. However, depending on the implementation there are some workarounds:
At least one version of MD considers <div>
to be a block level tag but <DIV>
is just text. All broswers however are case insensitive. This allows you to keep the syntax simplicity of MD, at the cost of adding div container tags.
So the following is a workaround:
<DIV class=foo>
Paragraphs here inherit class foo from above.
</div>
The downside of this is that the output code has <p>
tags wrapping the <div>
lines (both of them, the first because it's not and the second because it doesn't match. No browser fusses about this that I've found, but the code won't validate. MD tends to put in spare <p>
tags anyway.
Several versions of markdown implement the convention <tag markdown="1">
in which case MD will do the normal processing inside the tag. The above example becomes:
<div markdown="1" class=foo>
Paragraphs here inherit class foo from above.
</div>
The current version of Fletcher's MultiMarkdown allows attributes to follow the link if using referenced links.
Unlike the CMD.EXE CHDIR
or CD
command, the PowerShell Set-Location
cmdlet will change drive and directory, both. Get-Help Set-Location -Full
will get you more detailed information on Set-Location
, but the basic usage would be
PS C:\> Set-Location -Path Q:\MyDir
PS Q:\MyDir>
By default in PowerShell, CD
and CHDIR
are alias for Set-Location
.
(Asad reminded me in the comments that if the path contains spaces, it must be enclosed in quotes.)
Please use below solution it has taken my lots of time to fix.
Enjoy your time :)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
>
<ScrollView
android:id="@+id/mainScroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:fillViewport="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
>
</android.support.constraint.ConstraintLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
_x000D_
Use Exactly like this u will definitely find your solution...
maybe this new Chrome extension helps:
ActiveX for Chrome https://chrome.google.com/extensions/detail/lgllffgicojgllpmdbemgglaponefajn/
The document.location
is an object that contains properties for the current location.
The href
property is one of these properties, containing the complete URL, i.e. all the other properties put together.
Some browsers allow you to assign an URL to the location
object and acts as if you assigned it to the href
property. Some other browsers are more picky, and requires you to use the href
property. Thus, to make the code work in all browsers, you have to use the href
property.
Both the window
and document
objects has a location
object. You can set the URL using either window.location.href
or document.location.href
. However, logically the document.location
object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href
when you want to set the URL.
How about print (x, y)
at once.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
plt.grid()
plt.show()
The
compile 'com.google.zxing:core:2.3.0'
unfortunately didn't work for me.
This is what worked for me:
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.0.1@aar'
compile 'com.google.zxing:core:3.2.0'
}
Please find the link here: https://github.com/journeyapps/zxing-android-embedded
One of the reasons for me getting an error was the file name make sure the file name is Dockerfile So i figured it out, hope it might help someone.
There is a plugin to check if an element is focused: http://plugins.jquery.com/project/focused
$('input').each(function(){
if ($(this) == $.focused()) {
$(this).addClass('focused');
}
})
If you just want the two branches 'email' and 'staging' to be the same, you can tag the 'email' branch, then reset the 'email' branch to the 'staging' one:
$ git checkout email
$ git tag old-email-branch
$ git reset --hard staging
You can also rebase the 'staging' branch on the 'email' branch. But the result will contains the modification of the two branches.
It seems things have changed around a bit in the latest version of react router. You can now access history via the context. this.context.history.push('/path')
Also see the replies to the this github issue: https://github.com/ReactTraining/react-router/issues/4059
Lets start with some data:
from pyspark.mllib.linalg import SparseVector
from pyspark.sql import Row
df1 = sqlContext.createDataFrame([
Row(a=107831, f=SparseVector(
5, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0})),
Row(a=125231, f=SparseVector(
5, {0: 0.0, 1: 0.0, 2: 0.0047, 3: 0.0, 4: 0.0043})),
])
df2 = sqlContext.createDataFrame([
Row(a=107831, f=SparseVector(
5, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0})),
Row(a=107831, f=SparseVector(
5, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0})),
])
There are a few ways you can approach this problem. First of all you can unambiguously reference child table columns using parent columns:
df1.join(df2, df1['a'] == df2['a']).select(df1['f']).show(2)
## +--------------------+
## | f|
## +--------------------+
## |(5,[0,1,2,3,4],[0...|
## |(5,[0,1,2,3,4],[0...|
## +--------------------+
You can also use table aliases:
from pyspark.sql.functions import col
df1_a = df1.alias("df1_a")
df2_a = df2.alias("df2_a")
df1_a.join(df2_a, col('df1_a.a') == col('df2_a.a')).select('df1_a.f').show(2)
## +--------------------+
## | f|
## +--------------------+
## |(5,[0,1,2,3,4],[0...|
## |(5,[0,1,2,3,4],[0...|
## +--------------------+
Finally you can programmatically rename columns:
df1_r = df1.select(*(col(x).alias(x + '_df1') for x in df1.columns))
df2_r = df2.select(*(col(x).alias(x + '_df2') for x in df2.columns))
df1_r.join(df2_r, col('a_df1') == col('a_df2')).select(col('f_df1')).show(2)
## +--------------------+
## | f_df1|
## +--------------------+
## |(5,[0,1,2,3,4],[0...|
## |(5,[0,1,2,3,4],[0...|
## +--------------------+
After checking the XHTML DTD I discovered that a <TD>-element is allowed to contain block elements like headings, lists and also <DIV>-elements. Thus, using a <DIV>-element inside a <TD>-element does not violate the XHTML standard. I'm pretty sure that other modern variations of HTML have an equivalent content model for the <TD>-element.
Here are the relevant DTD rules:
<!ELEMENT td %Flow;>
<!-- %Flow; mixes block and inline and is used for list items etc. -->
<!ENTITY %Flow "(#PCDATA | %block; | form | %inline; | %misc;>
<!ENTITY %block "p | %heading; | div | %lists; | %blocktext; | fieldset | table">
Why not try using the following:
$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');
You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.
However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.
IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:
overflow: auto;
overflow-y: hidden;
You may also need to add for IE8:
-ms-overflow-y: hidden;
as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)
On the other hand it's entirely possible IE8 will have fixed the bug anyway.
new Guid(string)
You could also look at using a TypeConverter
.
python setup.py install
You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install
EDIT- thanks to kwatford (see first comment)
To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.
The docs say:
Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:
More details can be found here: http://docs.python.org/2.7/install/index.html
In short, if you have multiple routes defined for your app's routing, enclosed with Switch
component like this;
<Switch>
<Route exact path="/" component={Home} />
<Route path="/detail" component={Detail} />
<Route exact path="/functions" component={Functions} />
<Route path="/functions/:functionName" component={FunctionDetails} />
</Switch>
Then you have to put exact
keyword to the Route which it's path is also included by another Route's path. For example home path /
is included in all paths so it needs to have exact
keyword to differentiate it from other paths which start with /
. The reason is also similar to /functions
path. If you want to use another route path like /functions-detail
or /functions/open-door
which includes /functions
in it then you need to use exact
for the /functions
route.
This function basically generates unique random API key's and in case if it doesn't then pop-up dialog box with error message appears
In View Page:
<div class="form-group required">
<label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
<div class="col-sm-6">
<input type="text" class="apivalue" id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />
<button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
</div>
</div>
<script>
$(document).ready(function(){
$('.changeKey1').click(function(){
debugger;
$.ajax({
url :"index.php?route=account/apiaccess/regenerate",
type :'POST',
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function(data){
var result = data.sync_id.toUpperCase();
if(result){
$('#api_text').val(result);
}
debugger;
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
});
</script>
From Controller:
public function regenerate(){
$json = array();
$api_key = substr(md5(rand(0,100).microtime()), 0, 12);
$json['sync_id'] = $api_key;
$json['message'] = 'Successfully API Generated';
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
First of all you have to fetch the remote repository:
git fetch remoteName
Than you can create the new branch and set it up to track the remote branch you want:
git checkout -b newLocalBranch remoteName/remoteBranch
You can also use "git branch --track" instead of "git checkout -b" as max specified.
git branch --track newLocalBranch remoteName/remoteBranch
The 'is' test will test for identity using the builtin 'id()' function which essentially returns the memory address of the object and therefore isn't overloadable.
However in the case of testing the equality of a class you probably want to be a little bit more strict about your tests and only compare the data attributes in your class:
import types
class ComparesNicely(object):
def __eq__(self, other):
for key, value in self.__dict__.iteritems():
if (isinstance(value, types.FunctionType) or
key.startswith("__")):
continue
if key not in other.__dict__:
return False
if other.__dict__[key] != value:
return False
return True
This code will only compare non function data members of your class as well as skipping anything private which is generally what you want. In the case of Plain Old Python Objects I have a base class which implements __init__, __str__, __repr__ and __eq__ so my POPO objects don't carry the burden of all that extra (and in most cases identical) logic.
I think one way is first to check whether your file exists and if it exists to exclude the folder from copy:
<target name="excludeLocales">
<property name="de-DE.file" value="${basedir}/locale/de-DE/incompelte.flag"/>
<available property="de-DE.file.exists" file="${de-DE.file}" />
<copy todir="C:/temp/">
<fileset dir="${basedir}/locale">
<exclude name="de-DE/**" if="${de-DE.file.exists}"/>
<include name="xy/**"/>
</fileset>
</copy>
</target>
This should work also for the other languages.
Hope this helps : Declared a variable , in case of any changes need to be made thats only once .
declare @line varchar(100)
set @line ='[email protected]'
select SUBSTRING(@line ,(charindex('-',@line)+1), CHARINDEX('@',@line)-charindex('-',@line)-1)
a simpler way search downloads in the start menu and click on downloads in the search results to see where it will take you the drive will be highlighted in the explorer.
You can use:
@Html.EditorFor(x => x.Created, new { htmlAttributes = new { @class = "date" } })
(At least with ASP.NET MVC 5, but I do not know how that was with ASP.NET MVC 3.)
var myEle = document.getElementById("myElement");
if(myEle){
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value
Try following code it works for me:
public async void TaskSearchOnTaskList (SearchModel searchModel)
{
try
{
List<EventsTasksModel> taskSearchList = await Task.Run(
() => MakeasyncSearchRequest(searchModel),
cancelTaskSearchToken.Token);
if (cancelTaskSearchToken.IsCancellationRequested
|| string.IsNullOrEmpty(rid_agendaview_search_eventsbox.Text))
{
return;
}
if (taskSearchList == null || taskSearchList[0].result == Constants.ZERO)
{
RunOnUiThread(() => {
textViewNoMembers.Visibility = ViewStates.Visible;
taskListView.Visibility = ViewStates.Gone;
});
taskSearchRecureList = null;
return;
}
else
{
taskSearchRecureList = TaskFooterServiceLayer
.GetRecurringEvent(taskSearchList);
this.SetOnAdapter(taskSearchRecureList);
}
}
catch (Exception ex)
{
Console.WriteLine("ActivityTaskFooter -> TaskSearchOnTaskList:" + ex.Message);
}
}
var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
i have resolved same issue
"This action could not be completed. Try Again (-22421)"
using following steps...
issue
”This action could not be completed. Try Again (-22421)”
has been Resolved in Xcode 9. Now, we can upload app through Xcode Organizer also.
If you were trying to do what I imagine you were trying to do, then you only have to treat scope like a regular JS object.
This is what I use for an API success response for JSON data array...
function(data){
$scope.subjects = [];
$.each(data, function(i,subject){
//Store array of data types
$scope.subjects.push(subject.name);
//Split data in to arrays
$scope[subject.name] = subject.data;
});
}
Now {{subjects}} will return an array of data subject names, and in my example there would be a scope attribute for {{jobs}}, {{customers}}, {{staff}}, etc. from $scope.jobs, $scope.customers, $scope.staff
if($('#user_inp').length > 0 && $('#user_inp').val() != '')
{
$('#user_inp').css({"font-size":"18px"});
$('#user_line').css({"background-color":"#4cae4c","transition":"0.5s","height":"2px"});
$('#username').css({"color":"#4cae4c","transition":"0.5s","font-size":"18px"});
}
The GuidToBinary routine posted by KCD should be tweaked to account for the bit layout of the timestamp in the GUID string. If the string represents a version 1 UUID, like those returned by the uuid() mysql routine, then the time components are embedded in letters 1-G, excluding the D.
12345678-9ABC-DEFG-HIJK-LMNOPQRSTUVW
12345678 = least significant 4 bytes of the timestamp in big endian order
9ABC = middle 2 timestamp bytes in big endian
D = 1 to signify a version 1 UUID
EFG = most significant 12 bits of the timestamp in big endian
When you convert to binary, the best order for indexing would be: EFG9ABC12345678D + the rest.
You don't want to swap 12345678 to 78563412 because big endian already yields the best binary index byte order. However, you do want the most significant bytes moved in front of the lower bytes. Hence, EFG go first, followed by the middle bits and lower bits. Generate a dozen or so UUIDs with uuid() over the course of a minute and you should see how this order yields the correct rank.
select uuid(), 0
union
select uuid(), sleep(.001)
union
select uuid(), sleep(.010)
union
select uuid(), sleep(.100)
union
select uuid(), sleep(1)
union
select uuid(), sleep(10)
union
select uuid(), 0;
/* output */
6eec5eb6-9755-11e4-b981-feb7b39d48d6
6eec5f10-9755-11e4-b981-feb7b39d48d6
6eec8ddc-9755-11e4-b981-feb7b39d48d6
6eee30d0-9755-11e4-b981-feb7b39d48d6
6efda038-9755-11e4-b981-feb7b39d48d6
6f9641bf-9755-11e4-b981-feb7b39d48d6
758c3e3e-9755-11e4-b981-feb7b39d48d6
The first two UUIDs were generated closest in time. They only vary in the last 3 nibbles of the first block. These are the least significant bits of the timestamp, which means we want to push them to the right when we convert this to an indexable byte array. As a counter example, the last ID is the most current, but the KCD's swapping algorithm would put it before the 3rd ID (3e before dc, last bytes from the first block).
The correct order for indexing would be:
1e497556eec5eb6...
1e497556eec5f10...
1e497556eec8ddc...
1e497556eee30d0...
1e497556efda038...
1e497556f9641bf...
1e49755758c3e3e...
See this article for supporting information: http://mysql.rjweb.org/doc.php/uuid
*** note that I don't split the version nibble from the high 12 bits of the timestamp. This is the D nibble from your example. I just throw it in front. So my binary sequence ends up being DEFG9ABC and so on. This implies that all my indexed UUIDs start with the same nibble. The article does the same thing.
How about this?
select DATEPART(MM,'january 01 2011') -- returns 1
select DATEPART(MM,'march 01 2011') -- returns 3
select DATEPART(MM,'august 01 2011') -- returns 8
As mentionned in comments, this is the updated solution in favor of Icon object with documentation.
Use Icon object
var icon = {
url: "../res/sit_marron.png", // url
scaledSize: new google.maps.Size(50, 50), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
posicion = new google.maps.LatLng(latitud,longitud)
marker = new google.maps.Marker({
position: posicion,
map: map,
icon: icon
});
Router:-
...
.when('/enquiry/:page', {
template: '<div ng-include src="templateUrl" onload="onLoad()"></div>',
controller: 'enquiryCtrl'
})
...
Controller:-
...
// template onload event
$scope.onLoad = function() {
console.log('onLoad()');
f_tcalInit(); // or other onload stuff
}
// initialize
$scope.templateUrl = 'ci_index.php/adminctrl/enquiry/'+$routeParams.page;
...
I believe it is a weakness in angularjs that $routeParams is NOT visible inside the router. A tiny enhancement would make a world of difference during implementation.
This would be a good example of something that's trivial to do with tables and hard (if not impossible, at least in a cross-browser sense) to do with CSS.
If both the columns were fixed width, this would be easy.
If one of the columns was fixed width, this would be slightly harder but entirely doable.
With both columns variable width, IMHO you need to just use a two-column table.
In my case it was caused by a wrong Content-Type
in the HTTP POST. Setting it to text/xml
solved the problem.
Use CDATA in the below way for formatting your text
<resources>
<string name="app_name">DemoShareActionButton</string>
<string name="intro_message">
<b>
<![CDATA[ This sample shows you how a provide a context-sensitive ShareActionProvider.
]]>
</b>
</string>
Just add any tag you want before the <![CDATA[
and you will get your proper output.
Another nice little method is to include the current directory in your load path with
$:.unshift('.')
You could push it onto the $: ($LOAD_PATH) array but unshift will force it to load your current working directory before the rest of the load path.
Once you've added your current directory in your load path you don't need to keep specifying
require './tokenizer'
and can just go back to using
require 'tokenizer'
From PHP 5.2 on you can use modify with a DateTime object:
http://php.net/manual/en/datetime.modify.php
$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->modify('+1 day');
$Date2 = $date->format('Y-m-d');
Be careful when adding months... (and to a lesser extent, years)
I have same problem and i found solution which is given below with full datepicker using simple HTML,Javascript and CSS. In this code i prepare formate like dd/mm/yyyy but you can work any.
HTML Code:
<body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>
CSS Code:
#dt{text-indent: -500px;height:25px; width:200px;}
Javascript Code :
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}
Output:
Basing off from Bohemian's answer for Kotlin:
Use replace()
instead of replaceAll()
.
Arrays.toString(MyEnum.values()).replace(Regex("^.|.$"), "").split(", ").toTypedArray()
Side note: Convert to .toTypedArray()
for use in AlertDialog
's setSingleChoiceItems
, for example.
normaly is better image store in public folder (because it has write permission already that you can use when I upload images to it)
public
upload_media
photos
image.png
$image = public_path() . '/upload_media/photos/image.png'; // destination path
view PHP
<img src="<?= $image ?>">
View blade
<img src="{{ $image }}">
var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();
See the google.maps.LatLng docs and google.maps.Marker getPosition()
.
Note that Boolean
will only work were you have using System;
(which is usually, but not necessarily, included) (unless you write it out as System.Boolean
). bool
does not need using System;
Although Array.forEach is not asynchronous, you can get asynchronous "end result". Example below:
function delayFunction(x) {
return new Promise(
(resolve) => setTimeout(() => resolve(x), 1000)
);
}
[1, 2, 3].forEach(async(x) => {
console.log(x);
console.log(await delayFunction(x));
});
_x000D_
another solution using logging module:
import logging
import sys
log = logging.getLogger('stdxxx')
class StreamLogger(object):
def __init__(self, stream, prefix=''):
self.stream = stream
self.prefix = prefix
self.data = ''
def write(self, data):
self.stream.write(data)
self.stream.flush()
self.data += data
tmp = str(self.data)
if '\x0a' in tmp or '\x0d' in tmp:
tmp = tmp.rstrip('\x0a\x0d')
log.info('%s%s' % (self.prefix, tmp))
self.data = ''
logging.basicConfig(level=logging.INFO,
filename='text.log',
filemode='a')
sys.stdout = StreamLogger(sys.stdout, '[stdout] ')
print 'test for stdout'
You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.
This is the Known limitation in MySQLWorkbench (you can't edit table w/o PK):
Method 1: (method not working in somecases)
right-click on a table within the Object Browser and choose the Edit Table Data option from there.
Method 2:
I would rather suggest you to add Primary Key Instead:
ALTER TABLE `your_table_name` ADD PRIMARY KEY (`column_name`);
and you might want to remove the existing rows first:
Truncate table your_table_name
For these cases it would be better to use Apache Commons StringUtils#equals, it already handles null strings. Code sample:
public boolean compare(String s1, String s2) {
return StringUtils.equals(s1, s2);
}
If you dont want to add the library, just copy the source code of the StringUtils#equals
method and apply it when you need it.