How to delete a module in Android Studio
In Android studio v1.0.2
Method 1
Go to project structure, File -> Project Structure...
, as the following picture show, click -
icon to remove the module.
Method 2
Edit the file settings.gradle
and remove the entry you are going to delete. e.g. edit the file from include ':app', ':apple'
to include ':app'
.
That will work in most of the situation, however finally you have to delete the module from disk manually if you don't need it anymore.
Developing C# on Linux
Mono is a runtime environment that can run .NET applications and that works on both Windows and Linux. It includes a C# compiler.
As an IDE, you could use MonoDevelop, and I suppose there's something available for Eclipse, too.
Note that WinForms support on Mono is there, but somewhat lacking. Generally, Mono developers seem to prefer different GUI toolkits such as Gtk#.
Which @NotNull Java annotation should I use?
Unfortunately, JSR 308
will not add more values than this project local Not Null suggestion here
Java 8
will not come with a single default annotation or its own Checker
framework.
Similar to Find-bugs or JSR 305
, this JSR is poorly maintained by a small bunch of mostly academic teams.
No commercial power behind it, thus JSR 308
launches EDR 3
(Early Draft Review at JCP
) NOW, while Java 8
is supposed to ship in less than 6 months:-O
Similar to 310
btw. but unlike 308 Oracle
has taken charge of that now away from its founders to minimize harm it'll do to the Java Platform.
Every project, vendor and academic class like the ones behind the Checker Framework
and JSR 308
will create its own proprietary checker annotation.
Making source code incompatible for years to come, until a few popular compromises could be found and maybe added to Java 9
or 10
, or via frameworks like Apache Commons
or Google Guava
;-)
What is the best alternative IDE to Visual Studio
I still like Source Insight a lot, but I'm hesitant to recommend it anymore as I'm not sure anybody's still maintaining it. They released a very minor update back in March but haven't had a major release in years. And there seems to be no web community presence. It's a shame because I still like its auto-completion-friendly file open and symbol browsing panels (as well as syntax formatting) better than anything else I've ever used.
What Ruby IDE do you prefer?
In last 3 months, I have tried RadRails, Netbeans and RubyMine and finally settled on RubyMine not so much for features but for responsiveness and stability reasons.
In terms of features, RubyMine has slightly better code completion
, debugging
and code navigation
, but only ruby beginners(like myself) need them most. Relying on code completion and code navigation is anti-ruby/rails
, as ruby/rails names are supposed to be natural and each line of code needs to be in its convention determined location.
Unresolved reference issue in PyCharm
Install via PyCharm (works with Community Edition). Open up Settings > Project > Project Interpreter
then click the green + icon in the screenshot below. In the 2nd dialogue that opens, enter the package name and click the 'Install Package' button.
What IDE to use for Python?
Results
Spreadsheet version
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
Submit edits to the spreadsheet
Things possible in IntelliJ that aren't possible in Eclipse?
A few other things:
- propagate parameters/exceptions when
changing method signature, very
handy for updating methods deep
inside the call stack
- SQL code validation in the strings passed as arguments to jdbc calls
(and the whole newly bundled
language injection stuff)
- implemented in/overwritten in icons for interfaces & classes (and their methods) and
the smart implementation navigation
(Ctrl+Alt+Click or Ctrl+Alt+B)
- linking between the EJB 2.1 interfaces and bean classes
(including refactoring support); old
one, but still immensely valuable
when working on older projects
How do I enable the column selection mode in Eclipse?
A different approach:
The vrapper plugin emulates vim
inside the Eclipse editor. One of its features is visual block
mode which works fine inside Eclipse.
It is by default mapped to Ctrl-V
which interferes with the paste command in Eclipse. You can either remap the visual block
mode to a different shortcut, or remap the paste
command to a different key. I chose the latter: remapped the paste
command to Ctrl-Shift-V
to match my terminal's behavior.
QtCreator: No valid kits found
I had a similar problems after installing Qt in Windows.
This could be because only the Qt creator was installed and not any of the Qt libraries during initial installation. When installing from scratch use the online installer and select the following to install:
For starting, select at least one version of Qt libs (ex Qt 5.15.1) and the c++ compiler of choice (ex MinGW 8.1.0 64-bit).
Select Developer and Designer Tools. I kept the selected defaults.
Note: The choice of the Qt libs and Tools can also be changed post initial installation using MaintenanceTool.exe under Qt installation dir C:\Qt
. See here.
How do I run a Python program?
Python itself comes with an editor that you can access from the IDLE File > New File menu option.
Write the code in that file, save it as [filename].py and then (in that same file editor window) press F5 to execute the code you created in the IDLE Shell window.
Note: it's just been the easiest and most straightforward way for me so far.
How do I autoindent in Netbeans?
I have netbeans 6.9.1 open right now and ALT+SHIFT+F indents only the lines you have selected.
If no lines are selected then it will indent the whole document you are in.
1 possibly unintended behavior is that if you have selected ONLY 1 line, it must be selected completely, otherwise it does nothing. But you don't have to completely select the last line of a group nor the first.
I expected it to indent only one line by just selecting the first couple of chars but didn't work, yea i know i am lazy as hell...
PHPDoc type hinting for array of objects?
In the PhpStorm IDE from JetBrains, you can use /** @var SomeObj[] */
, e.g.:
/**
* @return SomeObj[]
*/
function getSomeObjects() {...}
The phpdoc documentation recommends this method:
specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array.
Example: @return int[]
JUnit Eclipse Plugin?
You might want to try out Quick JUnit: https://marketplace.eclipse.org/content/quick-junit
The plugin is stable and it allows switching between production and test code. I am currently using Eclipse Mars 4.5 and the plugin is supported for this release as well as for the following:
Luna (4.4), Kepler (4.3), Juno (4.2, 3.8), Previous to Juno (<=4.1)
How to jump back to NERDTree from file in tab?
Ctrl-ww
This will move between open windows (so you could hop between the NERDTree window, the file you are editing and the help window, for example... just hold down Ctrl and press w twice).
Difference between WebStorm and PHPStorm
Essentially, PHPStorm = WebStorm + PHP, SQL and more.
BUT (and this is a very important "but") because it is capable of parsing so much more, it quite often fails to parse Node.js dependencies, as they (probably) conflict with some other syntax it is capable of parsing.
The most notable example of that would be Mongoose model definition, where WebStorm easily recognizes mongoose.model method, whereas PHPStorm marks it as unresolved as soon as you connect Node.js plugin.
Surprisingly, it manages to resolve the method if you turn the plugin off, but leave the core modules connected, but then it cannot be used for debugging. And this happens to quite a few methods out there.
All this goes for PHPStorm 8.0.1, maybe in later releases this annoying bug would be fixed.
How do I run Python code from Sublime Text 2?
Edit %APPDATA%\Sublime Text 2\Python\Python.sublime-build
Change content to:
{
"cmd": ["C:\\python27\\python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
change the "c:\python27" part to any version of python you have in your system.
How do I "Add Existing Item" an entire directory structure in Visual Studio?
You can change your project XML to add existing subfolders and structures automatically into your project like "node_modules" from NPM:
This is for older MSBuild / Visual Studio versions
<ItemGroup>
<Item Include="$([System.IO.Directory]::GetFiles("$(MSBuildProjectDirectory)\node_modules","*",SearchOption.AllDirectories))"></Item>
</ItemGroup>
For the current MSBuild / Visual Studio versions:
Just put it in the nodes of the xml:
<Project>
</Project>
In this case just change $(MSBuildProjectDirectory)\node_modules to your folder name.
Importing project into Netbeans
File >> New Project >> Java Project With Existing Source>Next >> Project Name(add a name for your project) >> Next>>Add Folder >> select your existing project source code from your Directory>>Next >> Finish
Java Project With Existing Source
How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)
For those who want to use simpleUML in Android Studio and having issues in running SimpleUML.
First download simpleUML jar from here https://plugins.jetbrains.com/plugin/4946-simpleumlce
Now follow the below steps.
Step 1:
Click on File and go to Settings (File ? Settings)
Step 2
Select Plugins from Left Panel and click Install plugin from disk
Step 3:
Locate the SimpleUML jar file and select it.
Step 4:
Now Restart Android Studio (File ? Invalidate Caches/Restart ? Just Restart)
Step 5:
After you restart Right Click the Package name and Select New Diagram or Add to simpleUML Diagram ? New Diagram.
Step 6:
Set a file name and create UML file. I created with name NewDiagram
Step 7:
Now Right Click the Package name and Select the file you created. In my case it was NewDiagram
Step 8:
All files are stacked on top of one another. You can just drag and drop them and set a hierarchy.
Like this below, you can drag these classes
Bash script plugin for Eclipse?
ShellEd is a good plugin for Eclipse.
This link helped me to install it: http://mattnorris.me/blog/install-eclipse-shelled-plugin/
Steps:
Download ShellEd: http://sourceforge.net/projects/shelled/files/latest/download - The file is a zipped archive named something like net.sourceforge.shelled-site-2.0.x.zip.
Then click Help > Install New Software...
- Click Add... in the upper right.
- Click Archive...
- Navigate to where you saved the zipped archive net.sourceforge.shelled-site-2.0.x.zip and select it.
- Click OK. (Don't worry about the optional Name field. Eclipse will name it automatically.)
- Select the new Shell Script checkbox.
- Click Next.
- Click Next again.
- Select "I accept the terms of the license agreement."
- Click Finish.
- Restart Eclipse.
Why should I use an IDE?
I prefer an IDE because it permits me to integrate editing/compiling/debugging, with a 1-click jump from error to line generating the error. Further, it permits multiple panes of information with OS-standard interfaces displaying the information. In short, it gives the user a mouse-based input interface with a modern output interface instead of relying on 1970s technology and interfaces for my help.
There are more sophisticated users and uses for an IDE, I don't claim to use them or to know them all. When I have need, I will learn them.
How to configure Eclipse build path to use Maven dependencies?
I met this issue too. When I add dependencies in the pom.xml
, I checked in the local folder /Users/xyz/.m2/
and the jars are already downloaded there, but cann't added the the buildpath of the eclipse.
My eclipse Version: Mars.2 Release (4.5.2)
right click project > Maven > Enable Workspace Resolution
And this solved my issue.
Eclipse: Frustration with Java 1.7 (unbound library)
To set JDK you can watch this video : how to set JDK
. Then when you'll have JDK:
- Right click on build path and select "Build Path"
- Choose "Configure Build Path"
- Click on "JRE System Library [JavaSE-1.7] (unbound)"
- Edit it
- Choose "Alternate JRE"
- Click on "Installed JREs.." button
- Press Add
- Choose to add "Standard VM"
- Choose JRE Home directory - usually it is locates in "C:\Program Files\Java\jre7" directory
- Press "Finish"
- Re-check newly appeared "Jre7": Verify that now when you edit "JRE System Library [JavaSE-1.7]" "Alternate JRE" is chosen for jre7.
Can Android Studio be used to run standard Java projects?
Easy way to run a java program in Android Studio would be,
Create a java Class says "Test.java"
in Android Studio.
Write your code eg, a Hello World
program to test.
Right-click on the Java class and:
- select the option
Run 'Test.main()'
or
- press CTRL + SHIFT + F10 (on windows) or control + R (on Mac)
There you have your Java code running below.
Does Notepad++ show all hidden characters?
For non-printing characters, you can do the following:
- if you could identify the character, where cursor takes 2 arrow keys
to move, just select that character.
- do Ctrl-F
- now you can count or
replace or even mark all such characters
How to ignore a particular directory or file for tslint?
Starting from tslint v5.8.0
you can set an exclude
property under your linterOptions
key in your tslint.json
file:
{
"extends": "tslint:latest",
"linterOptions": {
"exclude": [
"bin",
"**/__test__",
"lib/*generated.js"
]
}
}
More information on this here.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)
In Sublime3 (Windows):
Some users may get an inverted screen using the Ctrl+Alt+? in windows. To Solve this go to
Preferences->Key Bindings-User
And add these two lines at the end of the file just before closing brackets:
{ "keys": ["ctrl+alt+pageup"], "command": "select_lines", "args": {"forward": false} },
{ "keys": ["ctrl+alt+pagedown"], "command": "select_lines", "args": {"forward": true} }
Or use your own keys.
How to clear gradle cache?
In android studio open View > Tool Windows > Terminal and execute the following commands
On Windows:
gradlew cleanBuildCache
On Mac or Linux:
./gradlew cleanBuildCache
if you want to disable the cache from your project add this into the gradle build properties
(Warning: this may slow your PC performance if there is no cache than same time will consume after every time during the run app)
android.enableBuildCache=false
Any good, visual HTML5 Editor or IDE?
Cloud 9 IDE. Storage is cloud+local, it offers autocompletion, it provides explicit support for node.js development, offers real-time collaboration, and you get bash into the deal with all its most popular tools (gcc included). All without having to open anything other than your browser.
I think that's Pretty Awesome.
EDIT Q3 2013 I would also suggest JetBrains WebStorm. It has autocompletion and solid refactoring features for HTML5, CSS3, JS. And it is very responsive.
Is there a way to collapse all code blocks in Eclipse?
There is a hotkey, mapped by default to Ctrl+Shift+NUM_KEYPAD_DIVIDE.
You can change it to something else via Window -> Preferences, search for "Keys", then for "Collapse All".
To open all code blocks the shortcut is Ctrl+Shift+NUM_KEYPAD_MULTIPLY.
In the Eclipse extension PyDev, close all code blocks is
Ctrl + 9
To open all blocks, is Ctrl + 0
Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?
SDK represents to software development kit, and IDE represents to integrated development environment. The IDE is the software or the program is used to write, compile, run, and debug such as Xcode. The SDK is the underlying engine of the IDE, includes all the platform's libraries an app needs to access. It's more basic than an IDE because it doesn't usually have graphical tools.
How to clear the cache in NetBeans
The path of the cache directory is listed in the About window (menu Help/About). Close NetBeans, then delete (or rename) the directory. NetBeans will rebuild its cache when it starts up.
Tips for using Vim as a Java IDE?
I know this is quite a few years later but here are some interesting plugins. I have not tried either of these yet so YMMV.
https://github.com/mikelue/vim-maven-plugin
https://github.com/vim-scripts/maven-ide
EDIT: Oh an BTW, i've tried eclim off and on, but the reason I like vim is its lightness. Executing eclipse even on headless mode is just too much mental lifting for me.
EDIT2: I've been using playframework lately and this will probably work with maven builds too:
For compiling, you can configure VIM's make to run maven or in my
case, run a build script, tee that to a file.
autocmd Filetype java setl makeprg=play_compile
autocmd Filetype java setl efm=%A\ %#[error]\ %f:%l:\ %m,%-Z\ %#[error]\ %p^,%-C%.%#
"play_compile" is just a compile script. It uses SBT so Maven should work just fine here. Even direct javac will work. This way, you can use VIM"s quickfix buffer (:cnext, :clist: cprev, etc).
For jumping around the classes, I use ctrl-p. Its beautiful.
Use it. Faster than eclipse in jumping around files.
For jumping around methods, I use tagsearch with exuberant c-tags.
Jump into method declarations by using ctrl-]. Go back using
Ctrl-o. Doesnt work as good as eclipse, but it works good enough.
I use supertab for code completion. Javacomplete is pretty slow, so I stick with omni-complete. Again, not as accurate as eclipse, but its fast and works good enough for me.
How to see JavaDoc in IntelliJ IDEA?
There is nice feature which shows quick documentation when your mouse is over element.
IntelliJ 14
Editor / General -> Show quick documentation on mouse move
Older versions
Add the following line to idea.properties file:
auto.show.quick.doc=true
Which is the best IDE for Python For Windows
Python is dynamic language so the IDE can do only so much in terms of code intelligence and syntax checking but I personally recommend Komode IDE, it's pretty slick on OS/X and Windows. I've experienced high cpu use with Linux but not sure if it's caused by my VirtualBox environment.
You can also try Eclipse with PyDev plugin. It's heavier so performance might become a problem though.
C++ IDE for Macs
Another (albeit non-free) option is to install VMware Fusion or Parallels Desktop on the Mac and run Windows with Visual Studio in a VM.
This works really pretty well. The downsides are:
- it'll cost money for the virtual machine software and Windows (the school may have some academic licensing that may help here)
- the Mac needs to be an x86 Mac with a fair bit of memory
The upside is that you and the student don't need to hassle with differences in the IDE that may not be accounted for in your instruction materials.
How do I completely rename an Xcode project (i.e. inclusive of folders)?
XCode 11.0+.
It's really simple now. Just go to Project Navigator
left panel of the XCode window.
Press Enter
to make it active for rename, just like you change the folder name.
Just change the new name here, and XCode will ask you for renaming other pieces of stuff.
.
Tap on Rename
here and you are done.
If you are confused about your root folder name that why it's not changed, well it's just a folder. just renamed it with a new name.
Eclipse/Java code completion not working
I also face this issue but it is resolved in different way.
Steps that I follow may be helpful for others.
- Right click on project (the one you are working on)
- Go to Properties > Java Build Path > JRE System Library
- Click Edit... on the right
- Choose the JRE 7
Learning Ruby on Rails
My steps was:
* Agile development with Rails (book)
* Railscasts - very useful, always learn something new.
* And of course the RoR API
Which Android IDE is better - Android Studio or Eclipse?
Both are equally good. With Android Studio you have ADT tools integrated, and with eclipse you need to integrate them manually. With Android Studio, it feels like a tool designed from the outset with Android development in mind.
Go ahead, they have same features.
Seeking useful Eclipse Java code templates
list_methods - generates the methods for add, removing, counting, and contains for a list
public void add${listname}(${listtype} toAdd){
get${listname}s().add(toAdd);
}
public void remove${listname}(${listtype} toRemove){
get${listname}s().remove(toRemove);
}
public ${listtype} get${listname}(int index){
return get${listname}s().get(index);
}
public int get${listname}Count(){
return get${listname}s().size();
}
public boolean contains${listname}(${listtype} toFind){
return get${listname}s().contains(toFind);
}
${cursor}
id - inserts the annotations, imports, field, and getter for simple JPA @Id
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public Long getId(){
return id;
}
${cursor}
${:import (javax.persistence.GenerationType,javax.persistence.GeneratedValue,javax.persistence.Id)}
Pandas conditional creation of a series/dataframe column
One liner with .apply()
method is following:
df['color'] = df['Set'].apply(lambda set_: 'green' if set_=='Z' else 'red')
After that, df
data frame looks like this:
>>> print(df)
Type Set color
0 A Z green
1 B Z green
2 B X red
3 C Y red
How to grep Git commit diffs or contents for a certain word?
If you want to find all commits where commit message contains given word, use
$ git log --grep=word
If you want to find all commits where "word" was added or removed in the file contents (to be more exact: where number of occurences of "word" changed), i.e. search the commit contents, use so called 'pickaxe' search with
$ git log -Sword
In modern git there is also
$ git log -Gword
to look for differences whose added or removed line matches "word" (also commit contents).
Note that -G
by default accepts a regex, while -S
accepts a string, but can be modified to accept regexes using the --pickaxe-regex
.
To illustrate the difference between -S<regex> --pickaxe-regex
and -G<regex>
, consider a commit with the following diff in the same file:
+ return !regexec(regexp, two->ptr, 1, ®match, 0);
...
- hit = !regexec(regexp, mf2.ptr, 1, ®match, 0);
While git log -G"regexec\(regexp"
will show this commit, git log -S"regexec\(regexp" --pickaxe-regex
will not (because the number of occurrences of that string did not change).
With Git 2.25.1 (Feb. 2020), the documentation is clarified around those regexes.
See commit 9299f84 (06 Feb 2020) by Martin Ågren (``).
(Merged by Junio C Hamano -- gitster
-- in commit 0d11410, 12 Feb 2020)
diff-options.txt
: avoid "regex" overload in example
Reported-by: Adam Dinwoodie
Signed-off-by: Martin Ågren
Reviewed-by: Taylor Blau
When we exemplify the difference between -G
and -S
(using --pickaxe-regex
), we do so using an example diff and git diff
invocation involving "regexec", "regexp", "regmatch", ...
The example is correct, but we can make it easier to untangle by avoiding writing "regex.*" unless it's really needed to make our point.
Use some made-up, non-regexy words instead.
The git diff
documentation now includes:
To illustrate the difference between -S<regex> --pickaxe-regex
and
-G<regex>
, consider a commit with the following diff in the same
file:
+ return frotz(nitfol, two->ptr, 1, 0);
...
- hit = frotz(nitfol, mf2.ptr, 1, 0);
While git log -G"frotz\(nitfol"
will show this commit, git log
-S"frotz\(nitfol" --pickaxe-regex
will not (because the number of
occurrences of that string did not change).
Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?
CLOCK_REALTIME
represents the machine's best-guess as to the current wall-clock, time-of-day time. As Ignacio and MarkR say, this means that CLOCK_REALTIME
can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.
CLOCK_MONOTONIC
represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn't affected by changes in the system time-of-day clock.
If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, CLOCK_MONOTONIC
is the best option.
Note that on Linux, CLOCK_MONOTONIC
does not measure time spent in suspend, although by the POSIX definition it should. You can use the Linux-specific CLOCK_BOOTTIME
for a monotonic clock that keeps running during suspend.
Directory.GetFiles of certain extension
I would have done using just single line like
List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(file => new string[] { ".jpg", ".gif", ".png" }
.Contains(Path.GetExtension(file)))
.ToList();
how to use python2.7 pip instead of default pip
There should be a binary called "pip2.7" installed at some location included within your $PATH variable.
You can find that out by typing
which pip2.7
This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py
Now, you should be all set, and
which pip2.7
should return the correct output.
Android 6.0 Marshmallow. Cannot write to SD Card
Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21.
Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1
Code:-
If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
return;
}`
` @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_RC) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted start reading
} else {
Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
}
}
}
}
Get an OutputStream into a String
Here's what I ended up doing:
Obj.writeToStream(toWrite, os);
try {
String out = new String(os.toByteArray(), "UTF-8");
assertTrue(out.contains("testString"));
} catch (UnsupportedEncondingException e) {
fail("Caught exception: " + e.getMessage());
}
Where os is a ByteArrayOutputStream
.
LIKE operator in LINQ
In native LINQ you may use combination of Contains/StartsWith/EndsWith
or RegExp.
In LINQ2SQL use method SqlMethods.Like()
from i in db.myTable
where SqlMethods.Like(i.field, "tra%ata")
select i
add Assembly: System.Data.Linq (in System.Data.Linq.dll) to use this feature.
Heap vs Binary Search Tree (BST)
Insert all n elements from an array to BST takes O(n logn). n elemnts in an array can be inserted to a heap in O(n) time. Which gives heap a definite advantage
How can I backup a Docker-container with its data-volumes?
If you have a case as simple as mine was you can do the following:
- Create a Dockerfile that extends the base image of your container
- I assume that your volumes are mapped to your filesystem, so you can just add those files/folders to your image using
ADD folder destination
- Done!
For example, assuming you have the data from the volumes on your home directory, for example at /home/mydata
you can run the following:
DOCKERFILE=/home/dockerfile.bk-myimage
docker build --rm --no-cache -t $IMAGENAME:$TAG -f $DOCKERFILE /home/pirate
Where your DOCKERFILE points to a file like this:
FROM user/myimage
MAINTAINER Danielo Rodríguez Rivero <[email protected]>
WORKDIR /opt/data
ADD mydata .
The rest of the stuff is inherited from the base image. You can now push that image to docker cloud and your users will have the data available directly on their containers
Count number of occurrences of a pattern in a file (even on same line)
Try this:
grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c
Sample:
grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
6 SMTP connect from unknown [188.190.118.90]
54 SMTP connect from unknown [62.193.131.114]
3 SMTP connect from unknown [91.222.51.253]
Go back button in a page
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
std::string formatting like sprintf
Based on the answer provided by Erik Aronesty:
std::string string_format(const std::string &fmt, ...) {
std::vector<char> str(100,'\0');
va_list ap;
while (1) {
va_start(ap, fmt);
auto n = vsnprintf(str.data(), str.size(), fmt.c_str(), ap);
va_end(ap);
if ((n > -1) && (size_t(n) < str.size())) {
return str.data();
}
if (n > -1)
str.resize( n + 1 );
else
str.resize( str.size() * 2);
}
return str.data();
}
This avoids the need to cast away const
from the result of .c_str()
which was in the original answer.
How to handle configuration in Go
The JSON format worked for me quite well. The
standard library offers methods to write the data structure indented, so it is quite
readable.
See also this golang-nuts thread.
The benefits of JSON are that it is fairly simple to parse and human readable/editable
while offering semantics for lists and mappings (which can become quite handy), which
is not the case with many ini-type config parsers.
Example usage:
conf.json:
{
"Users": ["UserA","UserB"],
"Groups": ["GroupA"]
}
Program to read the configuration
import (
"encoding/json"
"os"
"fmt"
)
type Configuration struct {
Users []string
Groups []string
}
file, _ := os.Open("conf.json")
defer file.Close()
decoder := json.NewDecoder(file)
configuration := Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(configuration.Users) // output: [UserA, UserB]
How to clear https proxy setting of NPM?
execute npm config list
it will list down all proxy values.. in my case proxy value was fetched form global npmrc file, removed it and was able to complete npm install on my windows machine
Processing $http response in service
I've read http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/
[AngularJS allows us to streamline our controller logic by placing a promise directly on the scope, rather than manually handing the resolved value in a success callback.]
so simply and handy :)
var app = angular.module('myApp', []);
app.factory('Data', function($http,$q) {
return {
getData : function(){
var deferred = $q.defer();
var promise = $http.get('./largeLoad').success(function (response) {
deferred.resolve(response);
});
// Return the promise to the controller
return deferred.promise;
}
}
});
app.controller('FetchCtrl',function($scope,Data){
$scope.items = Data.getData();
});
Hope this help
How to search JSON tree with jQuery
I have kind of similar condition plus my Search Query not limited to particular Object property ( like "John" Search query should be matched with first_name and also with last_name property ). After spending some hours I got this function from Google's Angular project. They have taken care of every possible cases.
/* Seach in Object */
var comparator = function(obj, text) {
if (obj && text && typeof obj === 'object' && typeof text === 'object') {
for (var objKey in obj) {
if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
comparator(obj[objKey], text[objKey])) {
return true;
}
}
return false;
}
text = ('' + text).toLowerCase();
return ('' + obj).toLowerCase().indexOf(text) > -1;
};
var search = function(obj, text) {
if (typeof text == 'string' && text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return comparator(obj, text);
case "object":
switch (typeof text) {
case "object":
return comparator(obj, text);
default:
for (var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
break;
}
return false;
case "array":
for (var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
Javascript switch vs. if...else if...else
Other than syntax, a switch can be implemented using a tree which makes it O(log n)
, while a if/else has to be implemented with an O(n)
procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?
How to Retrieve value from JTextField in Java Swing?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Swingtest extends JFrame implements ActionListener
{
JTextField txtdata;
JButton calbtn = new JButton("Calculate");
public Swingtest()
{
JPanel myPanel = new JPanel();
add(myPanel);
myPanel.setLayout(new GridLayout(3, 2));
myPanel.add(calbtn);
calbtn.addActionListener(this);
txtdata = new JTextField();
myPanel.add(txtdata);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == calbtn) {
String data = txtdata.getText(); //perform your operation
System.out.println(data);
}
}
public static void main(String args[])
{
Swingtest g = new Swingtest();
g.setLocation(10, 10);
g.setSize(300, 300);
g.setVisible(true);
}
}
now its working
linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'
Recently,I also encountered this problem. That's because I used qt(x64
) in vs win32
. If you want to use qt application x64
, you could choose vs x64
--as the above. If you want to use win32
and perhaps you haven't,you need to download qt(32bit
),then correctly set your enviroment, such as the lib
directory, etc.(note: maybe you are is old set in x64(other version)
, if you convert your win32 or x64 into another, Additional Dependencies
includes the old directory!)
How can I execute PHP code from the command line?
If you're going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It's a lot more fun.
Anyway, the php
command offers two switches to execute code from the command line:
-r <code> Run PHP <code> without using script tags <?..?>
-R <code> Run PHP <code> for every input line
You can use php
's -r switch as such:
php -r 'echo function_exists("foo") ? "yes" : "no";'
The above PHP command above should output no
and returns 0
as you can see:
>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
no
>>> echo $? # print the return value of the previous command
0
Another funny switch is php -a:
-a Run as interactive shell
It's sort of lame compared to phpsh, but if you don't want to install the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on, then use -a as such:
>>> php -a
Interactive shell
php > echo function_exists("foo") ? "yes" : "no";
no
php >
If it doesn't work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:
php -i | grep 'API'
You should see:
Server API => Command Line Interface
If you don't, this means that maybe another command will provides the CLI SAPI. Try php-cli; maybe it's a package or a command available in your OS.
If you do see that your php
command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code
to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.
Another couple of examples, just to make sure it works on my boxes:
>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
no
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'
yes
Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files, e.g., /etc/php/cli/php.ini
vs. /etc/php/cgi/php.ini
vs. /etc/php/apache/php.ini
on a Gentoo Linux box. Find out which ini file is used with php -i | grep ini
.
Why is it string.join(list) instead of list.join(string)?
Because the join()
method is in the string class, instead of the list class?
I agree it looks funny.
See http://www.faqs.org/docs/diveintopython/odbchelper_join.html:
Historical note. When I first learned
Python, I expected join to be a method
of a list, which would take the
delimiter as an argument. Lots of
people feel the same way, and there’s
a story behind the join method. Prior
to Python 1.6, strings didn’t have all
these useful methods. There was a
separate string module which contained
all the string functions; each
function took a string as its first
argument. The functions were deemed
important enough to put onto the
strings themselves, which made sense
for functions like lower, upper, and
split. But many hard-core Python
programmers objected to the new join
method, arguing that it should be a
method of the list instead, or that it
shouldn’t move at all but simply stay
a part of the old string module (which
still has lots of useful stuff in it).
I use the new join method exclusively,
but you will see code written either
way, and if it really bothers you, you
can use the old string.join function
instead.
--- Mark Pilgrim, Dive into Python
How do I read an attribute on a class at runtime?
A simplified version of Darin Dimitrov's first solution:
public string GetDomainName<T>()
{
var dnAttribute = typeof(T).GetCustomAttribute<DomainNameAttribute>(true);
if (dnAttribute != null)
{
return dnAttribute.Name;
}
return null;
}
Why can a function modify some arguments as perceived by the caller, but not others?
My general understanding is that any object variable (such as a list or a dict, among others) can be modified through its functions. What I believe you are not able to do is reassign the parameter - i.e., assign it by reference within a callable function.
That is consistent with many other languages.
Run the following short script to see how it works:
def func1(x, l1):
x = 5
l1.append("nonsense")
y = 10
list1 = ["meaning"]
func1(y, list1)
print(y)
print(list1)
Conversion failed when converting from a character string to uniqueidentifier
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
difference between width auto and width 100 percent
When we say
width:auto;
width will never exceed the total width of parent element. Maximum width is it's parent width. Even if we add border, padding and margin, content of element itself will become smaller in order to give space for border, padding and margin. In case if space required for border + padding + margin is greater than total width of parent element then width of content will become zero.
When we say
width:100%;
width of content of element will become 100% of parent element and from now if we add border, padding or margin then it will cause child element to exceed parent element's width and it will starts overflowing out of parent element.
How to sort a Ruby Hash by number value?
That's not the behavior I'm seeing:
irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]
Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?
Getting the current Fragment instance in the viewpager
To get current fragment - get position in ViewPager at public void onPageSelected(final int position), and then
public PlaceholderFragment getFragmentByPosition(Integer pos){
for(Fragment f:getChildFragmentManager().getFragments()){
if(f.getId()==R.viewpager && f.getArguments().getInt("SECTNUM") - 1 == pos) {
return (PlaceholderFragment) f;
}
}
return null;
}
SECTNUM - position argument assigned in public static PlaceholderFragment newInstance(int sectionNumber); of Fragment
getChildFragmentManager() or getFragmentManager() - depends on how created SectionsPagerAdapter
Why doesn't TFS get latest get the latest?
just want to add TFS MSBuild does not support special characters on folders i.e. "@"
i had experienced in the past where one of our project folders named as External@Project1
we created a TFS Build definition to run a custom msbuild file then the workspace folder is not getting any contents at the External@Project1 folder during workspace get latest. It seems that tfs get is failing but does not show any error.
after some trial and error and renaming the folder to _Project1. voila we got files on the the folder (_Project1).
How to use OrderBy with findAll in Spring Data
Yes you can sort using query method in Spring Data.
Ex:ascending order or descending order by using the value of the id field.
Code:
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public findAllByOrderByIdAsc();
}
alternative solution:
@Repository
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
@Override
public List<Student> findAll() {
return studentDao.findAll(orderByIdAsc());
}
private Sort orderByIdAsc() {
return new Sort(Sort.Direction.ASC, "id")
.and(new Sort(Sort.Direction.ASC, "name"));
}
}
Spring Data Sorting: Sorting
Angular JS update input field after change
Create a directive and put a watch on it.
app.directive("myApp", function(){
link:function(scope){
function:getTotal(){
..do your maths here
}
scope.$watch('one', getTotals());
scope.$watch('two', getTotals());
}
})
Entity Framework 5 Updating a Record
public interface IRepository
{
void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class;
}
public class Repository : DbContext, IRepository
{
public void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class
{
Set<T>().Attach(obj);
propertiesToUpdate.ToList().ForEach(p => Entry(obj).Property(p).IsModified = true);
SaveChanges();
}
}
How to delete all rows from all tables in a SQL Server database?
I had to delete all the rows and did it with the next script:
DECLARE @Nombre NVARCHAR(MAX);
DECLARE curso CURSOR FAST_FORWARD
FOR
Select Object_name(object_id) AS Nombre from sys.objects where type = 'U'
OPEN curso
FETCH NEXT FROM curso INTO @Nombre
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
DECLARE @statement NVARCHAR(200);
SET @statement = 'DELETE FROM ' + @Nombre;
print @statement
execute sp_executesql @statement;
END
FETCH NEXT FROM curso INTO @Nombre
END
CLOSE curso
DEALLOCATE curso
Hope this helps!
Is an HTTPS query string secure?
Yes. The entire text of an HTTPS session is secured by SSL. That includes the query and the headers. In that respect, a POST and a GET would be exactly the same.
As to the security of your method, there's no real way to say without proper inspection.
Android button background color
Why not just use setBackgroundColor(getResources().getColor(R.color.holo_light_green))
?
Edit: If you want to have something which looks more like an Android button you are going to want to create a gradient and set it as the background. For an example of this, you can check out this question.
How can you find out which process is listening on a TCP or UDP port on Windows?
netstat -ao
and netstat -ab
tell you the application, but if you're not a system administrator you'll get "The requested operation requires elevation".
It's not ideal, but if you use Sysinternals' Process Explorer you can go to specific processes' properties and look at the TCP tab to see if they're using the port you're interested in. It is a bit of a needle and haystack thing, but maybe it'll help someone...
Interfaces — What's the point?
Examples above don't make much sense. You could accomplish all above examples using classes (abstract class if you want it to behave only as a contract):
public abstract class Food {
public abstract void Prepare();
}
public class Pizza : Food {
public override void Prepare() { /* Prepare pizza */ }
}
public class Burger : Food {
public override void Prepare() { /* Prepare Burger */ }
}
You get the same behavior as with interface. You can create a List<Food>
and iterate that w/o knowing what class sits on top.
More adequate example would be multiple inheritance:
public abstract class MenuItem {
public string Name { get; set; }
public abstract void BringToTable();
}
// Notice Soda only inherits from MenuItem
public class Soda : MenuItem {
public override void BringToTable() { /* Bring soda to table */ }
}
// All food needs to be cooked (real food) so we add this
// feature to all food menu items
public interface IFood {
void Cook();
}
public class Pizza : MenuItem, IFood {
public override void BringToTable() { /* Bring pizza to table */ }
public void Cook() { /* Cook Pizza */ }
}
public class Burger : MenuItem, IFood {
public override void BringToTable() { /* Bring burger to table */ }
public void Cook() { /* Cook Burger */ }
}
Then you can use all of them as MenuItem
and don't care about how they handle each method call.
public class Waiter {
public void TakeOrder(IEnumerable<MenuItem> order)
{
// Cook first
// (all except soda because soda is not IFood)
foreach (var food in order.OfType<IFood>())
food.Cook();
// Bring them all to the table
// (everything, including soda, pizza and burger because they're all menu items)
foreach (var menuItem in order)
menuItem.BringToTable();
}
}
Automatically start a Windows Service on install
Despite following the accepted answer exactly, I was still unable to get the service to start-- I was instead given a failure message during installation stating that the service that was just installed could not be started, as it did not exist, despite using this.serviceInstaller.ServiceName
rather than a literal...
I eventually found an alternative solution that makes use of the command line:
private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e) {
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C sc start " + this.serviceInstaller.ServiceName;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
}
Return multiple values to a method caller
Just use in OOP manner a class like this:
class div
{
public int remainder;
public int quotient(int dividend, int divisor)
{
remainder = ...;
return ...;
}
}
The function member returns the quotient which most callers are primarily interested in. Additionally it stores the remainder as a data member, which is easily accessible by the caller afterwards.
This way you can have many additional "return values", very useful if you implement database or networking calls, where lots of error messages may be needed but only in case an error occurs.
I entered this solution also in the C++ question that OP is referring to.
fcntl substitute on Windows
The fcntl module is just used for locking the pinning file, so assuming you don't try multiple access, this can be an acceptable workaround. Place this module in your sys.path
, and it should just work as the official fcntl module.
Try using this module for development/testing purposes only in windows.
def fcntl(fd, op, arg=0):
return 0
def ioctl(fd, op, arg=0, mutable_flag=True):
if mutable_flag:
return 0
else:
return ""
def flock(fd, op):
return
def lockf(fd, operation, length=0, start=0, whence=0):
return
Javascript reduce() on Object
Since it hasnt really been confirmed in an answer yet, Underscore's reduce
also works for this.
_.reduce({
a: {value:1},
b: {value:2},
c: {value:3}
}, function(prev, current){
//prev is either first object or total value
var total = prev.value || prev
return total + current.value
})
Note, _.reduce
will return the only value (object or otherwise) if the list object only has one item, without calling iterator function.
_.reduce({
a: {value:1}
}, function(prev, current){
//not called
})
//returns {value: 1} instead of 1
Using Linq to get the last N elements of a collection?
Note: I missed your question title which said Using Linq, so my answer does not in fact use Linq.
If you want to avoid caching a non-lazy copy of the entire collection, you could write a simple method that does it using a linked list.
The following method will add each value it finds in the original collection into a linked list, and trim the linked list down to the number of items required. Since it keeps the linked list trimmed to this number of items the entire time through iterating through the collection, it will only keep a copy of at most N items from the original collection.
It does not require you to know the number of items in the original collection, nor iterate over it more than once.
Usage:
IEnumerable<int> sequence = Enumerable.Range(1, 10000);
IEnumerable<int> last10 = sequence.TakeLast(10);
...
Extension method:
public static class Extensions
{
public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> collection,
int n)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (n < 0)
throw new ArgumentOutOfRangeException(nameof(n), $"{nameof(n)} must be 0 or greater");
LinkedList<T> temp = new LinkedList<T>();
foreach (var value in collection)
{
temp.AddLast(value);
if (temp.Count > n)
temp.RemoveFirst();
}
return temp;
}
}
Sum values from an array of key-value pairs in JavaScript
You could use the Array.reduce
method:
_x000D_
_x000D_
const myData = [_x000D_
['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],_x000D_
['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], _x000D_
['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], _x000D_
['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]_x000D_
];_x000D_
const sum = myData_x000D_
.map( v => v[1] ) _x000D_
.reduce( (sum, current) => sum + current, 0 );_x000D_
_x000D_
console.log(sum);
_x000D_
_x000D_
_x000D_
See MDN
Which is the fastest algorithm to find prime numbers?
Rabin-Miller is a standard probabilistic primality test. (you run it K times and the input number is either definitely composite, or it is probably prime with probability of error 4-K. (a few hundred iterations and it's almost certainly telling you the truth)
There is a non-probabilistic (deterministic) variant of Rabin Miller.
The Great Internet Mersenne Prime Search (GIMPS) which has found the world's record for largest proven prime (274,207,281 - 1 as of June 2017), uses several algorithms, but these are primes in special forms. However the GIMPS page above does include some general deterministic primality tests. They appear to indicate that which algorithm is "fastest" depends upon the size of the number to be tested. If your number fits in 64 bits then you probably shouldn't use a method intended to work on primes of several million digits.
Filtering lists using LINQ
This LINQ below will generate the SQL for a left outer join and then take all of the results that don't find a match in your exclusion list.
List<Person> filteredResults =from p in people
join e in exclusions on p.compositeKey equals e.compositeKey into temp
from t in temp.DefaultIfEmpty()
where t.compositeKey == null
select p
let me know if it works!
What is the difference between g++ and gcc?
I was testing gcc and g++ in a linux system. By using MAKEFILE, I can define the compliler used by "GNU make". I tested with the so called "dynamic memory" locating feature of "C plus plus" by :
int main(){
int * myptr = new int;
* myptr = 1;
printf("myptr[0] is %i\n",*myptr);
return 0;
}
Only g++ can successfully compile on my computer while gcc will report error
undefined reference to `operator new(unsigned long)'
So my own conclusion is gcc does not fully support "C plus plus". It seems that choosing g++ for C++ source files is a better option.
What is Domain Driven Design?
I believe the following pdf will give you the bigger picture. Domain Driven Design by Eric Evans
NOTE: Think of a project you can work on, apply the little things you understood and see best practices. It will help you to grow your ability to the micro service architecture design approach too.
Android: how to refresh ListView contents?
In my understanding, if you want to refresh ListView immediately when data has changed, you should call notifyDataSetChanged()
in RunOnUiThread()
.
private void updateData() {
List<Data> newData = getYourNewData();
mAdapter.setList(yourNewList);
runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
Detect Android phone via Javascript / jQuery
I think Michal's answer is the best, but we can take it a step further and dynamically load an Android CSS as per the original question:
var isAndroid = /(android)/i.test(navigator.userAgent);
if (isAndroid) {
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", "/css/android.css");
document.body.appendChild(css);
}
Is it necessary to write HEAD, BODY and HTML tags?
It's true that the HTML specs permit certain tags to be omitted in certain cases, but generally doing so is unwise.
It has two effects - it makes the spec more complex, which in turn makes it harder for browser authors to write correct implementations (as demonstrated by IE getting it wrong).
This makes the likelihood of browser errors in these parts of the spec high. As a website author you can avoid the issue by including these tags - so while the spec doesn't say you have to, doing so reduces the chance of things going wrong, which is good engineering practice.
What's more, the latest HTML 5.1 WG spec currently says (bear in mind it's a work in progress and may yet change).
A body element's start tag may be omitted if the element is empty, or
if the first thing inside the body element is not a space character or
a comment, except if the first thing inside the body element is a
meta, link, script, style, or template element.
http://www.w3.org/html/wg/drafts/html/master/sections.html#the-body-element
This is a little subtle. You can omit body and head, and the browser will then infer where those elements should be inserted. This carries the risk of not being explicit, which could cause confusion.
So this
<html>
<h1>hello</h1>
<script ... >
...
results in the script element being a child of the body element, but this
<html>
<script ... >
<h1>hello</h1>
would result in the script tag being a child of the head element.
You could be explicit by doing this
<html>
<body>
<script ... >
<h1>hello</h1>
and then whichever you have first, the script or the h1, they will both, predictably appear in the body element. These are things which are easy to overlook while refactoring and debugging code. (say for example, you have JS which is looking for the 1st script element in the body - in the second snippet it would stop working).
As a general rule, being explicit about things is always better than leaving things open to interpretation. In this regard XHTML is better because it forces you to be completely explicit about your element structure in your code, which makes it simpler, and therefore less prone to misinterpretation.
So yes, you can omit them and be technically valid, but it is generally unwise to do so.
Print JSON parsed object?
Most debugger consoles support displaying objects directly. Just use
console.log(obj);
Depending on your debugger this most likely will display the object in the console as a collapsed tree. You can open the tree and inspect the object.
finding first day of the month in python
First day of next month:
from datetime import datetime
class SomeClassName(models.Model):
if datetime.now().month == 12:
new_start_month = 1
else:
new_start_month = datetime.now().month + 1
Then we replace the month and the day
start_date = models.DateField(default=datetime.today().replace(month=new_start_month, day=1, hour=0, minute=0, second=0, microsecond=0))
How to modify existing, unpushed commit messages?
On this question there are a lot of answers, but none of them explains in super detail how to change older commit messages using Vim. I was stuck trying to do this myself, so here I'll write down in detail how I did this especially for people who have no experience in Vim!
I wanted to change my five latest commits that I already pushed to the server. This is quite 'dangerous' because if someone else already pulled from this, you can mess things up by changing the commit messages. However, when you’re working on your own little branch and are sure no one pulled it you can change it like this:
Let's say you want to change your five latest commits, and then you type this in the terminal:
git rebase -i HEAD~5
*Where 5 is the number of commit messages you want to change (so if you want to change the 10th to last commit, you type in 10).
This command will get you into Vim there you can ‘edit’ your commit history. You’ll see your last five commits at the top like this:
pick <commit hash> commit message
Instead of pick
you need to write reword
. You can do this in Vim by typing in i
. That makes you go in to insert mode. (You see that you’re in insert mode by the word INSERT at the bottom.) For the commits you want to change, type in reword
instead of pick
.
Then you need to save and quit this screen. You do that by first going in to ‘command-mode’ by pressing the Escbutton (you can check that you’re in command-mode if the word INSERT at the bottom has disappeared). Then you can type in a command by typing :
. The command to save and quit is wq
. So if you type in :wq
you’re on the right track.
Then Vim will go over every commit message you want to reword, and here you can actually change the commit messages. You’ll do this by going into insert mode, changing the commit message, going into the command-mode, and save and quit. Do this five times and you’re out of Vim!
Then, if you already pushed your wrong commits, you need to git push --force
to overwrite them. Remember that git push --force
is quite a dangerous thing to do, so make sure that no one pulled from the server since you pushed your wrong commits!
Now you have changed your commit messages!
(As you see, I'm not that experienced in Vim, so if I used the wrong 'lingo' to explain what's happening, feel free to correct me!)
How do I sort arrays using vbscript?
Disconnected recordsets can be useful.
Const adVarChar = 200 'the SQL datatype is varchar
'Create a disconnected recordset
Set rs = CreateObject("ADODB.RECORDSET")
rs.Fields.append "SortField", adVarChar, 25
rs.CursorType = adOpenStatic
rs.Open
rs.AddNew "SortField", "Some data"
rs.Update
rs.AddNew "SortField", "All data"
rs.Update
rs.Sort = "SortField"
rs.MoveFirst
Do Until rs.EOF
strList=strList & vbCrLf & rs.Fields("SortField")
rs.MoveNext
Loop
MsgBox strList
How to find the maximum value in an array?
Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.
int max = array.get(0);
for (int i = 1; i < array.length; i++) {
if (array.get(i) > max) {
max = array.get(i);
}
}
Getting the HTTP Referrer in ASP.NET
Since Google takes you to this post when searching for C# Web API Referrer
here's the deal: Web API
uses a different type of Request
from normal MVC Request
called HttpRequestMessage
which does not include UrlReferrer
. Since a normal Web API
request does not include this information, if you really need it, you must have your clients go out of their way to include it. Although you could make this be part of your API Object
, a better way is to use Headers
.
First, you can extend HttpRequestMessage
to provide a UrlReferrer()
method:
public static string UrlReferrer(this HttpRequestMessage request)
{
return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}
Then your clients need to set the Referrer Header
to their API Request
:
// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);
And now the Web API Request
includes the referrer data which you can access like this from your Web API
:
Request.UrlReferrer();
System.Runtime.InteropServices.COMException (0x800A03EC)
For all of those, who still experiencing this problem, I just spent 2 days tracking down the bloody thing.
I was getting the same error when there was no rows in dataset.
Seems obvious, but error message is very obscure, hence 2 days.
Chrome sendrequest error: TypeError: Converting circular structure to JSON
As per the JSON docs at Mozilla, JSON.Stringify
has a second parameter censor
which can be used to filter/ignore children items while parsing the tree. However, perhaps you can avoid the circular references.
In Node.js we cannot. So we can do something like this:
function censor(censor) {
var i = 0;
return function(key, value) {
if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value)
return '[Circular]';
if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
return '[Unknown]';
++i; // so we know we aren't using the original object anymore
return value;
}
}
var b = {foo: {bar: null}};
b.foo.bar = b;
console.log("Censoring: ", b);
console.log("Result: ", JSON.stringify(b, censor(b)));
The result:
Censoring: { foo: { bar: [Circular] } }
Result: {"foo":{"bar":"[Circular]"}}
Unfortunately there seems to be a maximum of 30 iterations before it automatically assumes it's circular. Otherwise, this should work. I even used areEquivalent
from here, but JSON.Stringify
still throws the exception after 30 iterations. Still, it's good enough to get a decent representation of the object at a top level, if you really need it. Perhaps somebody can improve upon this though? In Node.js for an HTTP request object, I'm getting:
{
"limit": null,
"size": 0,
"chunks": [],
"writable": true,
"readable": false,
"_events": {
"pipe": [null, null],
"error": [null]
},
"before": [null],
"after": [],
"response": {
"output": [],
"outputEncodings": [],
"writable": true,
"_last": false,
"chunkedEncoding": false,
"shouldKeepAlive": true,
"useChunkedEncodingByDefault": true,
"_hasBody": true,
"_trailer": "",
"finished": false,
"socket": {
"_handle": {
"writeQueueSize": 0,
"socket": "[Unknown]",
"onread": "[Unknown]"
},
"_pendingWriteReqs": "[Unknown]",
"_flags": "[Unknown]",
"_connectQueueSize": "[Unknown]",
"destroyed": "[Unknown]",
"bytesRead": "[Unknown]",
"bytesWritten": "[Unknown]",
"allowHalfOpen": "[Unknown]",
"writable": "[Unknown]",
"readable": "[Unknown]",
"server": "[Unknown]",
"ondrain": "[Unknown]",
"_idleTimeout": "[Unknown]",
"_idleNext": "[Unknown]",
"_idlePrev": "[Unknown]",
"_idleStart": "[Unknown]",
"_events": "[Unknown]",
"ondata": "[Unknown]",
"onend": "[Unknown]",
"_httpMessage": "[Unknown]"
},
"connection": "[Unknown]",
"_events": "[Unknown]",
"_headers": "[Unknown]",
"_headerNames": "[Unknown]",
"_pipeCount": "[Unknown]"
},
"headers": "[Unknown]",
"target": "[Unknown]",
"_pipeCount": "[Unknown]",
"method": "[Unknown]",
"url": "[Unknown]",
"query": "[Unknown]",
"ended": "[Unknown]"
}
I created a small Node.js module to do this here: https://github.com/ericmuyser/stringy Feel free to improve/contribute!
Are all Spring Framework Java Configuration injection examples buggy?
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
Visual Studio 2015 installer hangs during install?
Alright so after hours of googling and failed attempts at solving this including many of the suggestions above, I found a solution I tried on a whim and worked for me.
Attempt to install the program, then, when it gets "stuck", cancel it, but don't uninstall.
Then, go to the control panel, go to programs, go and attempt to uninstall it, select "Repair" instead of Uninstall.
"Repairing" Visual Studio appears to have completely worked and was very quick, under 5 minutes and everything seems to work fine.
What is a web service endpoint?
Simply put, an endpoint is one end of a communication channel. When an API interacts with another system, the touch-points of this communication are considered endpoints. For APIs, an endpoint can include a URL of a server or service. Each endpoint is the location from which APIs can access the resources they need to carry out their function.
APIs work using ‘requests’ and ‘responses.’ When an API requests information from a web application or web server, it will receive a response. The place that APIs send requests and where the resource lives, is called an endpoint.
Reference:
https://smartbear.com/learn/performance-monitoring/api-endpoints/
Auto increment primary key in SQL Server Management Studio 2012
If the table is already populated it is not possible to change a column to IDENTITY column or convert it to non IDENTITY column. You would need to export all the data out then you can change column type to IDENTITY or vice versa and then import data back.
I know it is painful process but I believe there is no alternative except for using sequence as mentioned in this post.
RegExp in TypeScript
In typescript, the declaration is something like this:
const regex : RegExp = /.+\*.+/;
using RegExp constructor:
const regex = new RegExp('.+\\*.+');
What does it mean to inflate a view from an xml file?
A layman definition for inflation might be to convert the XML code to Java code. Just a way to understand, e.g., if we have a tag in XML, OS has to create a corresponding Java object in memory, so inflatter reads the XMLtags, and creates the corresponding objects in Java.
Android: View.setID(int id) programmatically - how to avoid ID conflicts?
public String TAG() {
return this.getClass().getSimpleName();
}
private AtomicInteger lastFldId = null;
public int generateViewId(){
if(lastFldId == null) {
int maxFld = 0;
String fldName = "";
Field[] flds = R.id.class.getDeclaredFields();
R.id inst = new R.id();
for (int i = 0; i < flds.length; i++) {
Field fld = flds[i];
try {
int value = fld.getInt(inst);
if (value > maxFld) {
maxFld = value;
fldName = fld.getName();
}
} catch (IllegalAccessException e) {
Log.e(TAG(), "error getting value for \'"+ fld.getName() + "\' " + e.toString());
}
}
Log.d(TAG(), "maxId="+maxFld +" name="+fldName);
lastFldId = new AtomicInteger(maxFld);
}
return lastFldId.addAndGet(1);
}
What is the difference between Amazon SNS and Amazon SQS?
You can see SNS as a traditional topic which you can have multiple Subscribers. You can have heterogeneous subscribers for one given SNS topic, including Lambda and SQS, for example. You can also send SMS messages or even e-mails out of the box using SNS. One thing to consider in SNS is only one message (notification) is received at once, so you cannot take advantage from batching.
SQS, on the other hand, is nothing but a queue, where you store messages and subscribe one consumer (yes, you can have N consumers to one SQS queue, but it would get messy very quickly and way harder to manage considering all consumers would need to read the message at least once, so one is better off with SNS combined with SQS for this use case, where SNS would push notifications to N SQS queues and every queue would have one subscriber, only) to process these messages. As of Jun 28, 2018, AWS Supports Lambda Triggers for SQS, meaning you don't have to poll for messages any more.
Furthermore, you can configure a DLQ on your source SQS queue to send messages to in case of failure. In case of success, messages are automatically deleted (this is another great improvement), so you don't have to worry about the already processed messages being read again in case you forgot to delete them manually. I suggest taking a look at Lambda Retry Behaviour to better understand how it works.
One great benefit of using SQS is that it enables batch processing. Each batch can contain up to 10 messages, so if 100 messages arrive at once in your SQS queue, then 10 Lambda functions will spin up (considering the default auto-scaling behaviour for Lambda) and they'll process these 100 messages (keep in mind this is the happy path as in practice, a few more Lambda functions could spin up reading less than the 10 messages in the batch, but you get the idea). If you posted these same 100 messages to SNS, however, 100 Lambda functions would spin up, unnecessarily increasing costs and using up your Lambda concurrency.
However, if you are still running traditional servers (like EC2 instances), you will still need to poll for messages and manage them manually.
You also have FIFO SQS queues, which guarantee the delivery order of the messages. SQS FIFO is also supported as an event source for Lambda as of November 2019
Even though there's some overlap in their use cases, both SQS and SNS have their own spotlight.
Use SNS if:
- multiple subscribers is a requirement
- sending SMS/E-mail out of the box is handy
Use SQS if:
- only one subscriber is needed
- batching is important
Pass arguments to Constructor in VBA
Why not this way:
- In a class module »myClass« use
Public Sub Init(myArguments)
instead of Private Sub Class_Initialize()
- Instancing:
Dim myInstance As New myClass: myInstance.Init myArguments
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.
This is a kind of test failure.@SpringBootApplication annotation contains these configurations.
1) @Configuration
2) @ComponentScan
3) @EnableAutoConfiguration
@EnableAutoConfiguration is the reason for this error. This will try to automatically configure application according to dependencies in your pom.xml
As a example when you have spring-data-jpa dependency in pom it will try to add configuration to application by looking at application.properties file for data source. So you need add data source to solve that.
For MySQL :
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost/lahiru
spring.datasource.username=root
spring.datasource.password=
Or
You could hide this by skipping testing.
mvn install -DskipTests
For more details.
COUNT DISTINCT with CONDITIONS
Try the following statement:
select distinct A.[Tag],
count(A.[Tag]) as TAG_COUNT,
(SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
from [TagTbl] AS A GROUP BY A.[Tag]
The first field will be the tag the second will be the whole count the third will be the positive ones count.
Android: Clear Activity Stack
This decision works fine:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
But new activity launch long and you see white screen some time. If this is critical then use this workaround:
public class BaseActivity extends AppCompatActivity {
private static final String ACTION_FINISH = "action_finish";
private BroadcastReceiver finisBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(finisBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
}, new IntentFilter(ACTION_FINISH));
}
public void clearBackStack() {
sendBroadcast(new Intent(ACTION_FINISH));
}
@Override
protected void onDestroy() {
unregisterReceiver(finisBroadcastReceiver);
super.onDestroy();
}
}
How use it:
public class ActivityA extends BaseActivity {
// Click any button
public void startActivityB() {
startActivity(new Intent(this, ActivityB.class));
clearBackStack();
}
}
Disadvantage: all activities that must be closed on the stack must extends BaseActivity
How do I get Maven to use the correct repositories?
Basically, all Maven is telling you is that certain dependencies in your project are not available in the central maven repository. The default is to look in your local .m2 folder (local repository), and then any configured repositories in your POM, and then the central maven repository. Look at the repositories section of the Maven reference.
The problem is that the project that was checked in didn't configure the POM in such a way that all the dependencies could be found and the project could be built from scratch.
Error: [$injector:unpr] Unknown provider: $routeProvider
It looks like you forgot to include the ngRoute module in your dependency for myApp.
In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.
'use strict';
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
How can I view the allocation unit size of a NTFS partition in Vista?
The simple GUI way, as provided by J Y in a previous answer:
- Create a small file (not empty)
- Right-click, choose Properties
- Check "Size on disk" (in tab General), double-check that your file size is less than half that so that it is certainly using a single allocation unit.
This works well and reminds you of the significance of allocation unit size. But it does have a caveat: as seen in comments to previous answer, Windows will sometimes show "Size on disk" as 0 for a very small file. In my testing, NTFS filesystems with allocation unit size 4096 bytes required the file to be 800 bytes to consistently avoid this issue. On FAT32 file systems this issue seems nonexistent, even a single byte file will work - just not empty.
CSS: fixed to bottom and centered
Based on the comment from @Michael:
There is a better way to do this. Simply create the body with
position:relative and a padding the size of the footer + the space
between content and footer you want. Then just make a footer div with
an absolute and bottom:0.
I went digging for the explanation and it boils down to this:
- By default, absolute position of bottom:0px sets it to the bottom of the window...not the bottom of the page.
- Relative positioning an element resets the scope of its children's absolute position...so by setting the body to relative positioning, the absolute position of bottom:0px now truly reflects the bottom of the page.
More details at http://css-tricks.com/absolute-positioning-inside-relative-positioning/
How to autosize a textarea using Prototype?
Internet Explorer, Safari, Chrome and Opera users need to remember to explicidly set the line-height value in CSS. I do a stylesheet that sets the initial properites for all text boxes as follows.
<style>
TEXTAREA { line-height: 14px; font-size: 12px; font-family: arial }
</style>
Changing every value in a hash in Ruby
A bit more readable one, map
it to an array of single-element hashes and reduce
that with merge
the_hash.map{ |key,value| {key => "%#{value}%"} }.reduce(:merge)
Getting Image from API in Angular 4/5+?
You should set responseType: ResponseContentType.Blob
in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.
Here is an working example:
Create image.service.ts
and put following code:
Angular 4:
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}
Angular 5+:
getImage(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, { responseType: 'blob' });
}
Important: Since Angular 5+ you should use the new HttpClient
.
The new HttpClient
returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'
. Read more about that here.
Now you need to create some function in your image.component.ts
to get image and show it in html.
For creating an image from Blob you need to use JavaScript's FileReader
.
Here is function which creates new FileReader
and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:
imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
Now you should use your created ImageService
to get image from api. You should to subscribe to data and give this data to createImageFromBlob
-function. Here is an example function:
getImageFromService() {
this.isImageLoading = true;
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
});
}
Now you can use your imageToShow
-variable in HTML template like this:
<img [src]="imageToShow"
alt="Place image title"
*ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
<img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>
I hope this description is clear to understand and you can use it in your project.
See the working example for Angular 5+ here.
IPC performance: Named Pipe vs Socket
Named pipes and sockets are not functionally equivalent; sockets provide more features (they are bidirectional, for a start).
We cannot tell you which will perform better, but I strongly suspect it doesn't matter.
Unix domain sockets will do pretty much what tcp sockets will, but only on the local machine and with (perhaps a bit) lower overhead.
If a Unix socket isn't fast enough and you're transferring a lot of data, consider using shared memory between your client and server (which is a LOT more complicated to set up).
Unix and NT both have "Named pipes" but they are totally different in feature set.
Java Singleton and Synchronization
Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:
Draconian synchronization:
private static YourObject instance;
public static synchronized YourObject getInstance() {
if (instance == null) {
instance = new YourObject();
}
return instance;
}
This solution requires that every thread be synchronized when in reality only the first few need to be.
Double check synchronization:
private static final Object lock = new Object();
private static volatile YourObject instance;
public static YourObject getInstance() {
YourObject r = instance;
if (r == null) {
synchronized (lock) { // While we were waiting for the lock, another
r = instance; // thread may have instantiated the object.
if (r == null) {
r = new YourObject();
instance = r;
}
}
}
return r;
}
This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.
Initialization on Demand:
private static class InstanceHolder {
private static final YourObject instance = new YourObject();
}
public static YourObject getInstance() {
return InstanceHolder.instance;
}
This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance
is called, InstanceHolder
will be loaded and instance
will be created, and since this is controlled by ClassLoader
s, no additional synchronization is necessary.
Why is this printing 'None' in the output?
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
Convert JsonNode into POJO
String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);
If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)
mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);
Java Error: illegal start of expression
Remove the public
keyword from int[] locations={1,2,3};
. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.
If your goal is to use this reference in many a method, you might want to move the declaration outside the method.
C++ convert string to hexadecimal and vice versa
Simplest example using the Standard Library.
#include <iostream>
using namespace std;
int main()
{
char c = 'n';
cout << "HEX " << hex << (int)c << endl; // output in hexadecimal
cout << "ASC" << c << endl; // output in ascii
return 0;
}
To check the output, codepad returns: 6e
and an online ascii-to-hexadecimal conversion tool yields 6e as well. So it works.
You can also do this:
template<class T> std::string toHexString(const T& value, int width) {
std::ostringstream oss;
oss << hex;
if (width > 0) {
oss << setw(width) << setfill('0');
}
oss << value;
return oss.str();
}
How to extract numbers from string in c?
Make a state machine that operates on one basic principle: is the current character a number.
- When transitioning from non-digit to digit, you initialize your current_number := number.
- when transitioning from digit to digit, you "shift" the new digit in:
current_number := current_number * 10 + number;
- when transitioning from digit to non-digit, you output the current_number
- when from non-digit to non-digit, you do nothing.
Optimizations are possible.
Python equivalent for HashMap
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
Why do this() and super() have to be the first statement in a constructor?
Simply because this is the inheritance philosophy. And according to the Java language specification, this is how the constructor's body is defined:
ConstructorBody:
{ ExplicitConstructorInvocationopt BlockStatementsopt }
The first statement of a constructor body may be either
- an explicit invocation of another constructor of the same class (by using the keyword "this"); or
- an explicit invocation of the direct superclass (by using the keyword "super")
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments. And so on.. there will be a whole chain of constructors called all the way back to the constructor of Object; "All Classes in the Java platform are Descendants of Object". This thing is called "Constructor Chaining".
Now why is this?
And the reason why Java defined the ConstructorBody in this way, is that they needed to maintain the hierarchy of the object. Remember the definition of the inheritance; It's extending a class. With that being said, you cannot extend something that doesn't exist. The base (the superclass) needs to be created first, then you can derive it (the subclass). That's why they called them Parent and Child classes; you can't have a child without a parent.
On a technical level, a subclass inherits all the members (fields, methods, nested classes) from its parent. And since Constructors are NOT members (They don't belong to objects. They are responsible of creating objects) so they are NOT inherited by subclasses, but they can be invoked. And since at the time of object creation only ONE constructor is executed. So how do we guarantee the creation of the superclass when you create the subclass object? Thus the concept of "constructor chaining"; so we have the ability to invoke other constructors (i.e. super) from within the current constructor. And Java required this invocation to be the FIRST line in the subclass constructor to maintain the hierarchy and guarantee it. They assume that if you don't explicitly create the parent object FIRST (like if you forgot about it), they will do it implicitly for you.
This check is done during compilation. But I'm not sure what would happen on runtime, what kind of runtime error we would get, IF Java doesn't throw a compile-error when we explicitly try to execute a base constructor from within a subclass's constructor in the middle of its body and not from the very first line ...
Error 5 : Access Denied when starting windows service
One of the causes for this error is insufficient permissions (Authenticated Users) in your local folder.
To give permission for 'Authenticated Users'
Open the security tab in properties of your folder, Edit and Add 'Authenticated Users' group and Apply changes.
Once this was done I was able to run services even through network service account (before this I was only able to run with Local system account).
ROW_NUMBER() in MySQL
Important: Please consider upgrading to MySQL 8+ and use the defined and documented ROW_NUMBER() function, and ditch old hacks tied to a feature limited ancient version of MySQL
Now here's one of those hacks:
The answers here that use in-query variables mostly/all seem to ignore the fact that the documentation says (paraphrase):
Don't rely on items in the SELECT list being evaluated in order from top to bottom. Don't assign variables in one SELECT item and use them in another one
As such, there's a risk they will churn out the wrong answer, because they typically do a
select
(row number variable that uses partition variable),
(assign partition variable)
If these are ever evaluated bottom up, the row number will stop working (no partitions)
So we need to use something with a guaranteed order of execution. Enter CASE WHEN:
SELECT
t.*,
@r := CASE
WHEN col = @prevcol THEN @r + 1
WHEN (@prevcol := col) = null THEN null
ELSE 1 END AS rn
FROM
t,
(SELECT @r := 0, @prevcol := null) x
ORDER BY col
As outline ld, order of assignment of prevcol is important - prevcol has to be compared to the current row's value before we assign it a value from the current row (otherwise it would be the current rows col value, not the previous row's col value).
Here's how this fits together:
The first WHEN is evaluated. If this row's col is the same as the previous row's col then @r is incremented and returned from the CASE. This return led values is stored in @r. It's a feature of MySQL that assignment returns the new value of what is assigned into @r into the result rows.
For the first row on the result set, @prevcol is null (it is initialised to null in the subquery) so this predicate is false. This first predicate also returns false every time col changes (current row is different to previous row). This causes the second WHEN to be evaluated.
The second WHEN predicate is always false, and it exists purely to assign a new value to @prevcol. Because this row's col is different to the previous row's col (we know this because if it were the same, the first WHEN would have been used), we have to assign the new value to keep it for testing next time. Because the assignment is made and then the result of the assignment is compared with null, and anything equated with null is false, this predicate is always false. But at least evaluating it did its job of keeping the value of col from this row, so it can be evaluated against the next row's col value
Because the second WHEN is false, it means in situations where the column we are partitioning by (col) has changed, it is the ELSE that gives a new value for @r, restarting the numbering from 1
We this get to a situation where this:
SELECT
t.*,
ROW_NUMBER() OVER(PARTITION BY pcol1, pcol2, ... pcolX ORDER BY ocol1, ocol2, ... ocolX) rn
FROM
t
Has the general form:
SELECT
t.*,
@r := CASE
WHEN col1 = @pcol1 AND col2 = @pcol2 AND ... AND colX = @pcolX THEN @r + 1
WHEN (@pcol1 := pcol1) = null OR (@pcol2 := col2) = null OR ... OR (@pcolX := colX) = null THEN null
ELSE 1
END AS rn
FROM
t,
(SELECT @r := 0, @pcol1 := null, @pcol2 := null, ..., @pcolX := null) x
ORDER BY pcol1, pcol2, ..., pcolX, ocol1, ocol2, ..., ocolX
Footnotes:
The p in pcol means "partition", the o in ocol means "order" - in the general form I dropped the "prev" from the variable name to reduce visual clutter
The brackets around (@pcolX := colX) = null
are important. Without them you'll assign null to @pcolX and things stop working
It's a compromise that the result set has to be ordered by the partition columns too, for the previous column compare to work out. You can't thus have your rownumber ordered according to one column but your result set ordered to another You might be able to resolve this with subqueries but I believe the docs also state that subquery ordering may be ignored unless LIMIT is used and this could impact performance
I haven't delved into it beyond testing that the method works, but if there is a risk that the predicates in the second WHEN will be optimised away (anything compared to null is null/false so why bother running the assignment) and not executed, it also stops. This doesn't seem to happen in my experience but I'll gladly accept comments and propose solution if it could reasonably occur
It may be wise to cast the nulls that create @pcolX to the actual types of your columns, in the subquery that creates the @pcolX variables, viz: select @pcol1 := CAST(null as INT), @pcol2 := CAST(null as DATE)
How to create a GUID / UUID
Don't use Math.random in anycase since it generated a non-cryptographic source of random numbers
Solution below using crypto.getRandomValues
function uuidv4() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
// tslint:disable-next-line: no-bitwise
const r =
(window.crypto.getRandomValues(new Uint32Array(1))[0] *
Math.pow(2, -32) * 16) |
0;
// tslint:disable-next-line: no-bitwise
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
This link helps your to understand the Insecure Randomness thrown by Fortify Scanner
hibernate - get id after save object
Let's say your primary key is an Integer and the object you save is "ticket", then you can get it like this. When you save the object, a Serializable id is always returned
Integer id = (Integer)session.save(ticket);
How to set a default value with Html.TextBoxFor?
It turns out that if you don't specify the Model to the View method within your controller, it doesn't create a object for you with the default values.
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Loads default values
Instructor i = new Instructor();
return View("Create", i);
}
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Does not load default values from instructor
return View("Create");
}
printf formatting (%d versus %u)
The difference is simple: they cause different warning messages to be emitted when compiling:
1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("memory address = %d\n", &a); // prints "memory add=-12"
^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("memory address = %u\n", &a); // prints "memory add=65456"
^
If you pass your pointer as a void*
and use %p
as the conversion specifier, then you get no error message:
#include <stdio.h>
int main()
{
int a = 5;
// check the memory address
printf("memory address = %d\n", &a); /* wrong */
printf("memory address = %u\n", &a); /* wrong */
printf("memory address = %p\n", (void*)&a); /* right */
}
How to Sort a List<T> by a property in the object
Based on GenericTypeTea's Comparer :
we can obtain more flexibility by adding sorting flags :
public class MyOrderingClass : IComparer<Order> {
public int Compare(Order x, Order y) {
int compareDate = x.Date.CompareTo(y.Date);
if (compareDate == 0) {
int compareOrderId = x.OrderID.CompareTo(y.OrderID);
if (OrderIdDescending) {
compareOrderId = -compareOrderId;
}
return compareOrderId;
}
if (DateDescending) {
compareDate = -compareDate;
}
return compareDate;
}
public bool DateDescending { get; set; }
public bool OrderIdDescending { get; set; }
}
In this scenario, you must instantiate it as MyOrderingClass explicitly( rather then IComparer )
in order to set its sorting properties :
MyOrderingClass comparer = new MyOrderingClass();
comparer.DateDescending = ...;
comparer.OrderIdDescending = ...;
orderList.Sort(comparer);
How to detect installed version of MS-Office?
Why not check HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\[office.exe]
, where [office.exe]
stands for particular office product exe-filename, e.g. winword.exe
, excel.exe
etc.
There you get path to executable and check version of that file.
How to check version of the file: in C++ / in C#
Any criticism towards such approach?
Why is the parent div height zero when it has floated children
I'm not sure this is a right way but I solved it by adding display: inline-block;
to the wrapper div.
#wrapper{
display: inline-block;
/*border: 1px black solid;*/
width: 75%;
min-width: 800px;
}
.content{
text-align: justify;
float: right;
width: 90%;
}
.lbar{
text-align: justify;
float: left;
width: 10%;
}
How to use fetch in typescript
Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.
That being said, the following works...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then((res: Actor) => {
// res is now an Actor
});
I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...
callBack: (response: any) => void
But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then(res => {
if (callback) {
callback(res); // Client receives the response as desired type.
}
});
So that a client can call it with a callback like...
(response: IApigeeResponse) => {
// Process response as an IApigeeResponse
}
How to suspend/resume a process in Windows?
Without any external tool you can simply accomplish this on Windows 7 or 8, by opening up the Resource monitor and on the CPU or Overview tab right clicking on the process and selecting Suspend Process.
The Resource monitor can be started from the Performance tab of the Task manager.
HTTP error 403 in Python 3 Web Scraping
Based on the previous answer,
from urllib.request import Request, urlopen
#specify url
url = 'https://xyz/xyz'
req = Request(url, headers={'User-Agent': 'XYZ/3.0'})
response = urlopen(req, timeout=20).read()
This worked for me by extending the timeout.
Google Android USB Driver and ADB
Locate the following file
C:\Users\
[your name]\.android\adb_usb.ini
And make the following changes:
# ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
# USE 'android update adb' TO GENERATE.
# 1 USB VENDOR ID PER LINE.
0x2207
I added 0x2207
to the file. This number is part of the hardware id, which can be found under the device's hardware information.
Mine was:
USB\VID_2207&PID_0010&MI_01
(I tried executing android update adb
, but it did nothing.)
Checking if a variable is initialized
Variable that is not defined will cause compilation error.
What you're asking is about checking if it is initialized. But initialization is just a value, that you should choose and assign in the constructor.
For example:
class MyClass
{
MyClass() : mCharacter('0'), mDecimal(-1.0){};
void SomeMethod();
char mCharacter;
double mDecimal;
};
void MyClass::SomeMethod()
{
if ( mCharacter != '0')
{
// touched after the constructor
// do something with mCharacter.
}
if ( mDecimal != -1.0 )
{
// touched after the constructor
// define mDecimal.
}
}
You should initialize to a default value that will mean something in the context of your logic, of course.
Getting Google+ profile picture url with user_id
If you want to show the profile picture for the currently logged in user, you do not even need to know the {user_id}. Simply using https://plus.google.com/s2/photos/profile/me
will be enough.
Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?
When you establish a connection for a transaction, you acquire a lock before performing the transaction. If not able to acquire the lock, then you try for sometime. If lock is still not obtainable, then lock wait time exceeded error is thrown. Why you will not able to acquire a lock is that you are not closing the connection. So, when you are trying to get a lock second time, you will not be able to acquire the lock as your previous connection is still unclosed and holding the lock.
Solution: close the connection or setAutoCommit(true)
(according to your design) to release the lock.
Count specific character occurrences in a string
I suggest you to do it like this:
String.Replace("e", "").Count
String.Replace("t", "").Count
You can also use .Split("e").Count - 1
or .Split("t").Count - 1
respectively, but it gives wrong values if you, for instance have an e or a t at the beginning of the String
.
Locate the nginx.conf file my nginx is actually using
which nginx
will give you the path of the nginx being used
EDIT (2017-Jan-18)
Thanks to Will Palmer's comment on this answer, I have added the following...
If you've installed nginx via a package manager such as HomeBrew...
which nginx
may not give you the EXACT path to the nginx being used. You can however find it using
realpath $(which nginx)
and as mentioned by @Daniel Li
you can get configuration of nginx via his method
alternatively you can use this:
nginx -V
Where can I set path to make.exe on Windows?
The path is in the registry but usually you edit through this interface:
- Go to
Control Panel
-> System
-> System settings
-> Environment Variables
.
- Scroll down in system variables until you find
PATH
.
- Click edit and change accordingly.
- BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e.
c:\path;c:\path2
- Launch a new console for the settings to take effect.
How to refresh an access form
No, it is like I want to run Form_Load
of Form A,if it is possible
-- Varun Mahajan
The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:
Form B:
Sub RunFormALoad()
Forms!FormA.ToDoOnLoad
End Sub
Form A:
Public Sub Form_Load()
ToDoOnLoad
End Sub
Sub ToDoOnLoad()
txtText = "Hi"
End Sub
Ignoring directories in Git repositories on Windows
When everything else fails try editing the file
/.git/info/exclude
and adding the directories you want to the end of the file, like this:
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~
assets/
compiled/
I added the folders "assets" and "compiled" to the list of files and directories to ignore.
Add Favicon to Website
Simply put a file named favicon.ico
in the webroot.
If you want to know more, please start reading:
How to get an object's properties in JavaScript / jQuery?
Scanning object for first intance of a determinated prop:
var obj = {a:'Saludos',
b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
d:'Hasta luego'
}
function scan (element,list){
var res;
if (typeof(list) != 'undefined'){
if (typeof(list) == 'object'){
for(key in list){
if (typeof(res) == 'undefined'){
res = (key == element)?list[key]:scan(element,list[key]);
}
});
}
}
return res;
}
console.log(scan('a',obj));
Returning Arrays in Java
Of course the method numbers()
returns an array, it's just that you're doing nothing with it. Try this in main()
:
int[] array = numbers(); // obtain the array
System.out.println(Arrays.toString(array)); // now print it
That will show the array in the console.
Make anchor link go some pixels above where it's linked to
This is also a good solution. Make a div above the destination div
like this and link the a to this div;
<div class="destination" id="link"></div> /**Needs to be above the destination**/
.destination {
position:absolute;
z-index:-1;
left:0;
margin-top:-100px;/* height of nav*/
}
Change Name of Import in Java, or import two classes with the same name
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
Why do we need the "finally" clause in Python?
You can use finally
to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception. (Or if you don't catch that specific exception.)
myfile = open("test.txt", "w")
try:
myfile.write("the Answer is: ")
myfile.write(42) # raises TypeError, which will be propagated to caller
finally:
myfile.close() # will be executed before TypeError is propagated
In this example you'd be better off using the with
statement, but this kind of structure can be used for other kinds of resources.
A few years later, I wrote a blog post about an abuse of finally
that readers may find amusing.
Return zero if no record is found
I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the SELECT 0
would be SELECT 0 FROM DUAL
)
SELECT SUM(sub.value)
FROM
(
SELECT SUM(columnA) as value FROM my_table
WHERE columnB = 1
UNION
SELECT 0 as value
) sub
Maybe this would work for postgresql too?
What is the simplest and most robust way to get the user's current location on Android?
After searching for best implementation how to get best precise user location I managed to combine all the best methods and come up with following class:
/**
* Retrieve accurate location from GPS or network services.
*
*
* Class usage example:
*
* public void onCreate(Bundle savedInstanceState) {
* ...
* my_location = new MyLocation();
* my_location.init(main.this, locationResult);
* }
*
*
* public LocationResult locationResult = new LocationResult(){
* @Override
* public void gotLocation(final Location location){
* // do something
* location.getLongitude();
* location.getLatitude();
* }
* };
*/
class MyLocation{
/**
* If GPS is enabled.
* Use minimal connected satellites count.
*/
private static final int min_gps_sat_count = 5;
/**
* Iteration step time.
*/
private static final int iteration_timeout_step = 500;
LocationResult locationResult;
private Location bestLocation = null;
private Handler handler = new Handler();
private LocationManager myLocationManager;
public Context context;
private boolean gps_enabled = false;
private int counts = 0;
private int sat_count = 0;
private Runnable showTime = new Runnable() {
public void run() {
boolean stop = false;
counts++;
System.println("counts=" + counts);
//if timeout (1 min) exceeded, stop tying
if(counts > 120){
stop = true;
}
//update last best location
bestLocation = getLocation(context);
//if location is not ready or don`t exists, try again
if(bestLocation == null && gps_enabled){
System.println("BestLocation not ready, continue to wait");
handler.postDelayed(this, iteration_timeout_step);
}else{
//if best location is known, calculate if we need to continue to look for better location
//if gps is enabled and min satellites count has not been connected or min check count is smaller then 4 (2 sec)
if(stop == false && !needToStop()){
System.println("Connected " + sat_count + " sattelites. continue waiting..");
handler.postDelayed(this, iteration_timeout_step);
}else{
System.println("#########################################");
System.println("BestLocation finded return result to main. sat_count=" + sat_count);
System.println("#########################################");
// removing all updates and listeners
myLocationManager.removeUpdates(gpsLocationListener);
myLocationManager.removeUpdates(networkLocationListener);
myLocationManager.removeGpsStatusListener(gpsStatusListener);
sat_count = 0;
// send best location to locationResult
locationResult.gotLocation(bestLocation);
}
}
}
};
/**
* Determine if continue to try to find best location
*/
private Boolean needToStop(){
if(!gps_enabled){
return true;
}
else if(counts <= 4){
return false;
}
if(sat_count < min_gps_sat_count){
//if 20-25 sec and 3 satellites found then stop
if(counts >= 40 && sat_count >= 3){
return true;
}
return false;
}
}
return true;
}
/**
* Best location abstract result class
*/
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
/**
* Initialize starting values and starting best location listeners
*
* @param Context ctx
* @param LocationResult result
*/
public void init(Context ctx, LocationResult result){
context = ctx;
locationResult = result;
myLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = (Boolean) myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
bestLocation = null;
counts = 0;
// turning on location updates
myLocationManager.requestLocationUpdates("network", 0, 0, networkLocationListener);
myLocationManager.requestLocationUpdates("gps", 0, 0, gpsLocationListener);
myLocationManager.addGpsStatusListener(gpsStatusListener);
// starting best location finder loop
handler.postDelayed(showTime, iteration_timeout_step);
}
/**
* GpsStatus listener. OnChainged counts connected satellites count.
*/
public final GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {
public void onGpsStatusChanged(int event) {
if(event == GpsStatus.GPS_EVENT_SATELLITE_STATUS){
try {
// Check number of satellites in list to determine fix state
GpsStatus status = myLocationManager.getGpsStatus(null);
Iterable<GpsSatellite>satellites = status.getSatellites();
sat_count = 0;
Iterator<GpsSatellite>satI = satellites.iterator();
while(satI.hasNext()) {
GpsSatellite satellite = satI.next();
System.println("Satellite: snr=" + satellite.getSnr() + ", elevation=" + satellite.getElevation());
sat_count++;
}
} catch (Exception e) {
e.printStackTrace();
sat_count = min_gps_sat_count + 1;
}
System.println("#### sat_count = " + sat_count);
}
}
};
/**
* Gps location listener.
*/
public final LocationListener gpsLocationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location){
}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status, Bundle extras){}
};
/**
* Network location listener.
*/
public final LocationListener networkLocationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location){
}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status, Bundle extras){}
};
/**
* Returns best location using LocationManager.getBestProvider()
*
* @param context
* @return Location|null
*/
public static Location getLocation(Context context){
System.println("getLocation()");
// fetch last known location and update it
try {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
String strLocationProvider = lm.getBestProvider(criteria, true);
System.println("strLocationProvider=" + strLocationProvider);
Location location = lm.getLastKnownLocation(strLocationProvider);
if(location != null){
return location;
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
This class tries to connect to min_gps_sat_count
satellites if GPS is enabled. Else returns LocationManager.getBestProvider()
location. Check the code!
How to set default values in Rails?
In Ruby on Rails v3.2.8, using the after_initialize
ActiveRecord callback, you can call a method in your model that will assign the default values for a new object.
after_initialize callback is triggered for each object that is found and instantiated by a finder, with after_initialize being triggered after new objects are instantiated as well
(see ActiveRecord Callbacks).
So, IMO it should look something like:
class Foo < ActiveRecord::Base
after_initialize :assign_defaults_on_new_Foo
...
attr_accessible :bar
...
private
def assign_defaults_on_new_Foo
# required to check an attribute for existence to weed out existing records
self.bar = default_value unless self.attribute_whose_presence_has_been_validated
end
end
Foo.bar = default_value
for this instance unless the instance contains an attribute_whose_presence_has_been_validated
previously on save/update. The default_value
will then be used in conjunction with your view to render the form using the default_value
for the bar
attribute.
At best this is hacky...
EDIT - use 'new_record?' to check if instantiating from a new call
Instead of checking an attribute value, use the new_record?
built-in method with rails. So, the above example should look like:
class Foo < ActiveRecord::Base
after_initialize :assign_defaults_on_new_Foo, if: 'new_record?'
...
attr_accessible :bar
...
private
def assign_defaults_on_new_Foo
self.bar = default_value
end
end
This is much cleaner. Ah, the magic of Rails - it's smarter than me.
Python: For each list element apply a function across the list
If working with Python =2.6 (including 3.x), you can:
from __future__ import division
import operator, itertools
def getmin(alist):
return min(
(operator.div(*pair), pair)
for pair in itertools.product(alist, repeat=2)
)[1]
getmin([1, 2, 3, 4, 5])
EDIT: Now that I think of it and if I remember my mathematics correctly, this should also give the answer assuming that all numbers are non-negative:
def getmin(alist):
return min(alist), max(alist)
ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()
If you use an absolute path such as ("/index.jsp"
), there is no difference.
If you use relative path, you must use HttpServletRequest.getRequestDispatcher()
. ServletContext.getRequestDispatcher()
doesn't allow it.
For example, if you receive your request on http://example.com/myapp/subdir
,
RequestDispatcher dispatcher =
request.getRequestDispatcher("index.jsp");
dispatcher.forward( request, response );
Will forward the request to the page http://example.com/myapp/subdir/index.jsp
.
In any case, you can't forward request to a resource outside of the context.
Understanding INADDR_ANY for socket programming
INADDR_ANY
instructs listening socket to bind to all available interfaces. It's the same as trying to bind to inet_addr("0.0.0.0")
.
For completeness I'll also mention that there is also IN6ADDR_ANY_INIT for IPv6 and it's the same as trying to bind to ::
address for IPv6 socket.
#include <netinet/in.h>
struct in6_addr addr = IN6ADDR_ANY_INIT;
Also, note that when you bind IPv6 socket to to IN6ADDR_ANY_INIT
your socket will bind to all IPv6 interfaces, and should be able to accept connections from IPv4 clients as well (though IPv6-mapped addresses).
UIAlertView first deprecated IOS 9
-(void)showAlert{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"
message:"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
[self showAlert];
// calling Method
How to define static constant in a class in swift
If I understand your question correctly, you are asking how you can create class level constants (static - in C++ parlance) such that you don't a) replicate the overhead in every instance, and b have to recompute what is otherwise constant.
The language has evolved - as every reader knows, but as I test this in Xcode 6.3.1, the solution is:
import Swift
class MyClass {
static let testStr = "test"
static let testStrLen = count(testStr)
init() {
println("There are \(MyClass.testStrLen) characters in \(MyClass.testStr)")
}
}
let a = MyClass()
// -> There are 4 characters in test
I don't know if the static is strictly necessary as the compiler surely only adds only one entry per const variable into the static section of the binary, but it does affect syntax and access. By using static, you can refer to it even when you don't have an instance: MyClass.testStrLen
.
How do I reflect over the members of dynamic object?
There are several scenarios to consider.
First of all, you need to check the type of your object. You can simply call GetType() for this.
If the type does not implement IDynamicMetaObjectProvider, then you can use reflection same as for any other object. Something like:
var propertyInfo = test.GetType().GetProperties();
However, for IDynamicMetaObjectProvider implementations, the simple reflection doesn't work. Basically, you need to know more about this object. If it is ExpandoObject (which is one of the IDynamicMetaObjectProvider implementations), you can use the answer provided by itowlson. ExpandoObject stores its properties in a dictionary and you can simply cast your dynamic object to a dictionary.
If it's DynamicObject (another IDynamicMetaObjectProvider implementation), then you need to use whatever methods this DynamicObject exposes. DynamicObject isn't required to actually "store" its list of properties anywhere. For example, it might do something like this (I'm reusing an example from my blog post):
public class SampleObject : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = binder.Name;
return true;
}
}
In this case, whenever you try to access a property (with any given name), the object simply returns the name of the property as a string.
dynamic obj = new SampleObject();
Console.WriteLine(obj.SampleProperty);
//Prints "SampleProperty".
So, you don't have anything to reflect over - this object doesn't have any properties, and at the same time all valid property names will work.
I'd say for IDynamicMetaObjectProvider implementations, you need to filter on known implementations where you can get a list of properties, such as ExpandoObject, and ignore (or throw an exception) for the rest.
receiving json and deserializing as List of object at spring mvc controller
Here is the code that works for me. The key is that you need a wrapper class.
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
A PersonWrapper class
public class PersonWrapper {
private List<Person> persons;
/**
* @return the persons
*/
public List<Person> getPersons() {
return persons;
}
/**
* @param persons the persons to set
*/
public void setPersons(List<Person> persons) {
this.persons = persons;
}
}
My Controller methods
@RequestMapping(value="person", method=RequestMethod.POST,consumes="application/json",produces="application/json")
@ResponseBody
public List<String> savePerson(@RequestBody PersonWrapper wrapper) {
List<String> response = new ArrayList<String>();
for (Person person: wrapper.getPersons()){
personService.save(person);
response.add("Saved person: " + person.toString());
}
return response;
}
The request sent is json in POST
{"persons":[{"name":"shail1","age":"2"},{"name":"shail2","age":"3"}]}
And the response is
["Saved person: Person [name=shail1, age=2]","Saved person: Person [name=shail2, age=3]"]
Pointer arithmetic for void pointer in C
Compiler knows by type cast. Given a void *x
:
x+1
adds one byte to x
, pointer goes to byte x+1
(int*)x+1
adds sizeof(int)
bytes, pointer goes to byte x + sizeof(int)
(float*)x+1
addres sizeof(float)
bytes,
etc.
Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)
Undefined Symbols for architecture x86_64: Compiling problems
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
iPhone UILabel text soft shadow
To keep things up to date: Creating the shadow in Swift is as easy as that:
Import the QuartzCore Framework
import QuartzCore
And set the shadow attributes to your label
titleLabel.shadowColor = UIColor.blackColor()
titleLabel.shadowOffset = CGSizeMake(0.0, 0.0)
titleLabel.layer.shadowRadius = 5.0
titleLabel.layer.shadowOpacity = 0.8
titleLabel.layer.masksToBounds = false
titleLabel.layer.shouldRasterize = true
How to hide a div from code (c#)
Try this. Your markup:
<div id="MyId" runat="server">some content</div>
.. and in aspx.cs file:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["someSessionVal"].ToString() == "some value")
{
MyId.Visible = true;
}
else
{
MyId.Visible = false;
}
}
SQL: How To Select Earliest Row
In this case a relatively simple GROUP BY
can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER()
:
Runnable example (Wofkflow20 error in original data corrected)
;WITH partitioned AS (
SELECT company
,workflow
,date
,other_columns
,ROW_NUMBER() OVER(PARTITION BY company, workflow
ORDER BY date) AS seq
FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1
ASP.NET Core Web API exception handling
By adding your own "Exception Handling Middleware", makes it hard to reuse some good built-in logic of Exception Handler like send an "RFC 7807-compliant payload to the client" when an error happens.
What I made was to extend built-in Exception handler outside of the Startup.cs
class to handle custom exceptions or override the behavior of existing ones. For example, an ArgumentException and convert into BadRequest without changing the default behavior of other exceptions:
on the Startup.cs
add:
app.UseExceptionHandler("/error");
and extend ErrorController.cs with something like this:
using System;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
namespace Api.Controllers
{
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
[AllowAnonymous]
public class ErrorController : ControllerBase
{
[Route("/error")]
public IActionResult Error(
[FromServices] IWebHostEnvironment webHostEnvironment)
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exceptionType = context.Error.GetType();
if (exceptionType == typeof(ArgumentException)
|| exceptionType == typeof(ArgumentNullException)
|| exceptionType == typeof(ArgumentOutOfRangeException))
{
if (webHostEnvironment.IsDevelopment())
{
return ValidationProblem(
context.Error.StackTrace,
title: context.Error.Message);
}
return ValidationProblem(context.Error.Message);
}
if (exceptionType == typeof(NotFoundException))
{
return NotFound(context.Error.Message);
}
if (webHostEnvironment.IsDevelopment())
{
return Problem(
context.Error.StackTrace,
title: context.Error.Message
);
}
return Problem();
}
}
}
Note that:
NotFoundException
is a custom exception and all you need to do is throw new NotFoundException(null);
or throw new ArgumentException("Invalid argument.");
- You should not serve sensitive error information to clients. Serving errors is a security risk.
Where can I download Eclipse Android bundle?
The Android Developer pages still state how you can download and use the ADT plugin for Eclipse:
- Start Eclipse, then select Help > Install New Software.
- Click Add, in the top-right corner.
- In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:
https://dl-ssl.google.com/android/eclipse/
- Click OK.
- In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
- In the next window, you'll see a list of the tools to be downloaded. Click Next.
- Read and accept the license agreements, then click Finish.
If you get a security warning saying that the authenticity or validity of the software can't be established, click OK
- When the installation completes, restart Eclipse.
Links for the Eclipse ADT Bundle (found using Archive.org's WayBackMachine)
I don't know how future-proof these links are. They all worked on February 27th, 2017.
Update (2015-06-29): Google will end development and official support for ADT in Eclipse at the end of this year and recommends switching to Android Studio.
Best way to determine user's locale within browser
There's a difference between the user's preferred languages and the system/browser locale.
A user can configure preferred languages in the browser, and these will be used for navigator.language(s)
, and used when requesting resources from a server, to request content according to a list of language priorities.
However, the browser locale will decide how to render number, date, time and currency. This setting is likely the highest ranking language, but there is no guarantee. On Mac and Linux, the locale is decided by the system regardless of the user language preferences. On Windows is can be elected among the languages in the preferred list on Chrome.
By using Intl (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl), developers can override/set the locale to use to render these things, but there are elements that cannot be overridden, such as the <input type="date">
format.
To properly extract this language, the only way I've found is:
(new Intl.NumberFormat()).resolvedOptions().locale
(Intl.NumberFormat().resolvedOptions().locale
also seems to work)
This will create a new NumberFormat instance for the default locale and then reading back the locale of those resolved options.
calculate the mean for each column of a matrix in R
You can use colMeans
:
### Sample data
set.seed(1)
m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))
### Your error
mean(m)
# [1] NA
# Warning message:
# In mean.default(m) : argument is not numeric or logical: returning NA
### The result using `colMeans`
colMeans(m)
# X1 X2 X3 X4
# 47.0 64.4 44.8 67.8
Adding IN clause List to a JPA Query
public List<DealInfo> getDealInfos(List<String> dealIds) {
String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
query.setParameter("inclList", dealIds);
return query.getResultList();
}
Works for me with JPA 2, Jboss 7.0.2
Jquery post, response in new window
If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:
Example:
<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
<input type="hidden" name="packing_slip" value="35592" />
<input type="hidden" name="reference" value="0018439" />
<input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>
Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.
Get safe area inset top and bottom heights
Swift 4
if let window = UIApplication.shared.windows.first {
let topPadding = window.safeAreaInsets.top
let bottomPadding = window.safeAreaInsets.bottom
}
Use from class
class fitToTopInsetConstraint: NSLayoutConstraint {
override func awakeFromNib() {
if let window = UIApplication.shared.windows.first {
let topPadding = window.safeAreaInsets.top
self.constant += topPadding
}
}
}
class fitToBottomInsetConstraint: NSLayoutConstraint {
override func awakeFromNib() {
if let window = UIApplication.shared.windows.first {
let bottomPadding = window.safeAreaInsets.bottom
self.constant += bottomPadding
}
}
}
You will see safe area padding when you build your application.
Get loop counter/index using for…of syntax in JavaScript
For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.
Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).
loop over an Array:
var a = [];
for (var i=0; i<a.length; i++) {
i // is the index
a[i] // is the item
}
loop over an Object:
var o = {};
for (var prop in o) {
prop // is the property name
o[prop] // is the property value - the item
}