(rewritten 2015-07-28)
The default behavior of Eclipse when compiling code with errors in it, is to generate byte code throwing the exception you see, allowing the program to be run. This is possible as Eclipse uses its own built-in compiler, instead of javac
from the JDK which Apache Maven uses, and which fails the compilation completely for errors. If you use Eclipse on a Maven project which you are also working with using the command line mvn
command, this may happen.
The cure is to fix the errors and recompile, before running again.
The setting is marked with a red box in this screendump:
<input type="phone" numbers-only >
You can use this way if you want only numbers :)
here is the the demo click
TRY THIS
SELECT E.ename,E.empno,ISNULL(E.ename,'NO MANAGER') AS MANAGER FROM emp e
INNER JOIN emp M
ON M.empno=E.empno
Instaed of subquery use self join
I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.
Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.
Here is an attempt at this with your data:
import matplotlib.pyplot as plt
# ... define 2D array hist as you did
plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case
Two steps, for example,
package main
import (
"fmt"
"strings"
)
func main() {
s := strings.Split("127.0.0.1:5432", ":")
ip, port := s[0], s[1]
fmt.Println(ip, port)
}
Output:
127.0.0.1 5432
One step, for example,
package main
import (
"fmt"
"net"
)
func main() {
host, port, err := net.SplitHostPort("127.0.0.1:5432")
fmt.Println(host, port, err)
}
Output:
127.0.0.1 5432 <nil>
Another option is to use Descendant selectors
HTML:
<div class="social">
<p class="first">burrito</p>
<p class="last">chimichanga</p>
</div>
Reference first one in CSS: .social .first { color: blue; }
Reference last one in CSS: .social .last { color: green; }
Jsfiddle: https://jsfiddle.net/covbtpaq/153/
Use import scala.collection.mutable.MutableList or similar if you really need mutation.
import scala.collection.mutable.MutableList
val x = MutableList(1, 2, 3, 4, 5)
x += 6 // MutableList(1, 2, 3, 4, 5, 6)
x ++= MutableList(7, 8, 9) // MutableList(1, 2, 3, 4, 5, 6, 7, 8, 9)
by splitting with newlines.
for line in wallop_of_a_string_with_many_lines.split('\n'):
#do_something..
if you iterate over a string, you are iterating char by char in that string, not by line.
>>>string = 'abc'
>>>for line in string:
print line
a
b
c
If you see this error when you are loading custom SQL data for initialization, another way to avoid this is:
Instead of writing:
INSERT INTO book (id, name, price) VALUES (1 , 'Alchemist' , 10),
Remove the id
(primary key) from initial data
INSERT INTO book (name, price) VALUES ('Alchemist' , 10),
This keeps the Postgres sequence in sync !
Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.
Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.
Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.
I could see a situation like this making a detectable difference:
inline int aplusb_pow2(int a, int b) {
return (a + b)*(a + b) ;
}
for(int a = 0; a < 900000; ++a)
for(int b = 0; b < 900000; ++b)
aplusb_pow2(a, b);
That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with stdin
(they are usually line buffered). You can, however use a library for that:
conio available with Windows compilers. Use the _getch()
function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include <conio.h>
and use it. See conio.h
at Wikipedia. It lists getch()
, which is declared deprecated in Visual C++.
curses available for Linux. Compatible curses implementations are available for Windows too. It has also a getch()
function. (try man getch
to view its manpage). See Curses at Wikipedia.
I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into man stty
). Curses would handle that for you in a portable manner, if I'm not mistaken.
GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL
. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.
To remove the .html extension from your urls, you can use the following code in root/htaccess :
RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]
NOTE: If you want to remove any other extension, for example to remove the .php extension, just replace the html everywhere with php in the code above.
There is no special git ignore
command.
Edit a .gitignore
file located in the appropriate place within the working copy. You should then add this .gitignore
and commit it. Everyone who clones that repo will than have those files ignored.
Note that only file names starting with /
will be relative to the directory .gitignore
resides in. Everything else will match files in whatever subdirectory.
You can also edit .git/info/exclude
to ignore specific files just in that one working copy. The .git/info/exclude
file will not be committed, and will thus only apply locally in this one working copy.
You can also set up a global file with patterns to ignore with git config --global core.excludesfile
. This will locally apply to all git working copies on the same user's account.
Run git help gitignore
and read the text for the details.
How do time zones factor in this analysis. Does a card expire in New York before California? Does it depend on the billing or shipping addresses?
You have a problem with a png file maybe, look here :
1 more Caused by: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details at com.android.builder.png.AaptProcess$NotifierProcessOutput.handleOutput(AaptProcess.java:454)
It can be corrupted image or jpeg image with png extension
Try to change like this ..
firstStr = "<?xml version" 'my file always starts like this
Do until objInputFile.AtEndOfStream
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))
tmpStr = objInputFile.ReadLine
If InStr(tmpStr, substrToFind) <= 0 Then
If Instr(tmpStr, firstStr) > 0 Then
text = tmpStr 'to avoid the first empty line
Else
text = text & vbCrLf & tmpStr
End If
Else
text = text & vbCrLf & strToAdd & vbCrLf & tmpStr
End If
index = index + 1
Loop
//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;
prefsEditor = myPrefs.edit();
//strVersionName->Any value to be stored
prefsEditor.putString("STOREDVALUE", strVersionName);
prefsEditor.commit();
//Get Preferenece
SharedPreferences myPrefs;
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String StoredValue=myPrefs.getString("STOREDVALUE", "");
Try this..
You just want to set the field separator as .
using the -F
option and print the first field:
$ echo aaa0.bbb.ccc | awk -F'.' '{print $1}'
aaa0
Same thing but using cut:
$ echo aaa0.bbb.ccc | cut -d'.' -f1
aaa0
Or with sed
:
$ echo aaa0.bbb.ccc | sed 's/[.].*//'
aaa0
Even grep
:
$ echo aaa0.bbb.ccc | grep -o '^[^.]*'
aaa0
For URL query parameters, use request.args
.
search = request.args.get("search")
page = request.args.get("page")
For posted form input, use request.form
.
email = request.form.get('email')
password = request.form.get('password')
For JSON posted with content type application/json
, use request.get_json()
.
data = request.get_json()
In Windows inorder to set
Step 1 : Right Click on MyComputer and click on properties .
Step 2 : Click on Advanced tab
Step 3: Click on Environment Variables
Step 4: Create a new class path for JAVA_HOME
Step 5: Enter the Variable name as JAVA_HOME and the value to your jdk bin path ie c:\Programfiles\Java\jdk-1.6\bin and
NOTE Make sure u start with .;
in the Value so that it doesn't corrupt the other environment variables which is already set.
Step 6 : Follow the Above step and edit the Path in System Variables add the following ;c:\Programfiles\Java\jdk-1.6\bin
in the value column.
Step 7 :Your are done setting up your environment variables for your Java , In order to test it go to command prompt and type
java
who will get a list of help doc
In order make sure whether compiler is setup Type in cmd
javac
who will get a list related to javac
Hope this Helps !
In my case there was a corrupted character in one of the named params ("-StorageAccountName" for cmdlet "Get-AzureStorageKey") which showed as perfectly normal in my editor (SublimeText) but Windows Powershell couldn't parse it.
To get to the bottom of it, I moved the offending lines from the error message into another .ps1 file, ran that, and the error now showed a botched character at the beginning of my "-StorageAccountName" parameter.
Deleting the character (again which looks normal in the actual editor) and re-typing it fixes this issue.
in your case you just need to
git diff HEAD^ HEAD^2
or just hash for you commit:
git diff 0e1329e55^ 0e1329e55^2
.help will show you all the options. Do .exit in this case
You seem to have the quote marks ("
) embedded in your string at the start and the end. These are not needed and are illegal characters in a path. How are you initializing the string with the path?
This can be seen from the debugger visualizer, as the string starts with "\"
and ends with \""
, it shows that the quotes are part of the string, when they shouldn't be.
You can do two thing - a regular escaped string (using \
) or a verbatim string literal (that starts with a @
):
string str = "C:\\Program Files (x86)\\test software\\myapp\\demo.exe";
Or:
string verbatim = @"C:\Program Files (x86)\test software\myapp\demo.exe";
Another thing to note is that if you want a absolute element to be confined to a parent element then you need to set the parent element's position to relative. That will keep the child element contained within the parent element and it won't be "relative" to the entire window.
I wrote a blog post that gives a simple example that creates the following affect:
That has a green div that is absolutely positioned to the bottom of the parent yellow div.
1 http://blog.troygrosfield.com/2013/02/11/working-with-css-positions-creating-a-simple-progress-bar/
I found a special case that causes symlinks to appear to fail:
I did a standard enterprise install of mongodb but changed the /var/lib/mongodb to a symlink as I wanted to use an XFS filesystem for my database folder and a third filesystem for the log folder.
$sudo systemctl start mongod (fails with a message no permission to write to mongodb.log).. but it succceded if I started with the same configuration file:
.. as the owner of the external drives (ziggy) I was able to start $mongod --config /etc/mongodb.conf --fork
I eventually discovered that .. the symlinks pointed to a different filesystem and the mongodb (user) did not have permission to browse the folder that the symlink referred. Both the symlinks and the folders the symlinks referred had expansive rights to the mongod user so it made no sense?
/var/log/mongodb was changed (from the std ent install) to a symlink AND I had checked before:
$ ll /var/log/mongodb lrwxrwxrwx 1 mongodb mongodb 38 Oct 28 21:58 /var/log/mongodb -> /media/ziggy/XFS_DB/mongodb/log/
$ ll -d /media/ziggy/Ext4DataBase/mongodb/log drwxrwxrwx 2 mongodb mongodb 4096 Nov 1 12:05 /media/ashley/XFS_DB/mongodb/log/
.. But so it seemed to make no sense.. of course user mongodb had rwx access to the link, the folder and to the file mongodb.log .. but it couldnt find it via the symlink because the BASE folder of the media couldnt be searched by mongodb.
SO.. I EVENTUALLY DID THIS: $ ll /media/ziggy/ . . drwx------ 5 ziggy ziggy 4096 Oct 28 21:49 XFS_DB/
and found the offending missing x permissions..
$chmod a+x /media/ziggy/XFS_DB solved the problem
Seems stupid in hindsight but no searches turned up anything useful.
You can use from the pd.to_numeric(s)
If you'd like to send the data to a view pass the following in.
server.get('/usersList', function(req, res) {
User.find({}, function(err, users) {
res.render('/usersList', {users: users});
});
});
Inside your view you can loop through the data using the variable users
You are looking for the OS native module for Node.js:
v4: https://nodejs.org/dist/latest-v4.x/docs/api/os.html#os_os_platform
or v5 : https://nodejs.org/dist/latest-v5.x/docs/api/os.html#os_os_platform
os.platform()
Returns the operating system platform. Possible values are 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of process.platform.
SELECT * from Employees where [Employee ID] = ALL (SELECT MAX([Employee ID]) from Employees)
Open up a command prompt then type...
netstat -a
Try this:
#wrapper {
text-align: center;
}
#wrapper iframe {
display: inline-block;
}
I was able to get all I needed from the dir
built in plus getattr
.
# Works on pretty much everything, but be mindful that
# you get lists of strings back
print dir(myproject)
print dir(myproject.mymodule)
print dir(myproject.mymodule.myfile)
print dir(myproject.mymodule.myfile.myclass)
# But, the string names can be resolved with getattr, (as seen below)
Though, it does come out looking like a hairball:
def list_supported_platforms():
"""
List supported platforms (to match sys.platform)
@Retirms:
list str: platform names
"""
return list(itertools.chain(
*list(
# Get the class's constant
getattr(
# Get the module's first class, which we wrote
getattr(
# Get the module
getattr(platforms, item),
dir(
getattr(platforms, item)
)[0]
),
'SYS_PLATFORMS'
)
# For each include in platforms/__init__.py
for item in dir(platforms)
# Ignore magic, ourselves (index.py) and a base class.
if not item.startswith('__') and item not in ['index', 'base']
)
))
When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.
sudo netstat -lpn |grep :'3000'
3000 is port i was looking for, After first command you will have Process ID for that port
kill -9 1192
in my case 1192 was process Id of process running on 3000 PORT use -9 for Force kill the process
If you are having a small script that you need to run (I simply needed to copy a file), I found it much easier to call the commands on the PHP script by calling
exec("sudo cp /tmp/testfile1 /var/www/html/testfile2");
and enabling such transaction by editing (or rather adding) a permitting line to the sudoers by first calling sudo visudo
and adding the following line to the very end of it
www-data ALL=(ALL) NOPASSWD:/bin/cp /tmp/testfile1 /var/www/html/testfile2
All I wanted to do was to copy a file and I have been having problems with doing so because of the root password problem, and as you mentioned I did NOT want to expose the system to have no password for all root transactions.
This will return the first 200 characters of words:
preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, 201));
import time
now = time.time()
future = now + 10
while time.time() < future:
# do stuff
pass
Alternatively, if you've already got your loop:
while True:
if time.time() > future:
break
# do other stuff
This method works well with pygame, since it pretty much requires you to have a big main loop.
Write code in this manner ...
<canvas id="canvas" width="640" height="480"></canvas>
<script>
var Grid = function(width, height) {
...
this.draw = function() {
var canvas = document.getElementById("canvas");
if(canvas.getContext) {
var context = canvas.getContext("2d");
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
if(isLive(i, j)) {
context.fillStyle = "lightblue";
}
else {
context.fillStyle = "yellowgreen";
}
context.fillRect(i*15, j*15, 14, 14);
}
}
}
}
}
First write canvas tag and then write script tag. And write script tag in body.
alter table Employee alter column salary numeric(22,5)
#!/bin/sh
#Find the Process ID for syncapp running instance
PID=`ps -ef | grep syncapp 'awk {print $2}'`
if [[ -z "$PID" ]] then
---> Kill -9 PID
fi
Not sure if this helps, but 'kill' is not spelled correctly. It's capitalized.
Try 'kill' instead.
The Python approach to "main" is almost unique to the language(*).
The semantics are a bit subtle. The __name__
identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__
is set to "__main__"
(the literal string: __main__
).
This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:
#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
pass
def some_function(*args,**kwargs):
pass
if __name__ == '__main__':
print("This only executes when %s is executed rather than imported" % __file__)
Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.
It's important to understand that all of the code above the if __name__
line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print
statement before the if __name__
line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).
I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.
Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__"
to isolate a block of code which calls a suite of unit tests that apply to this module.
(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).
Summary: if __name__ == '__main__':
has two primary use cases:
It's fairly common to def main(*args)
and have if __name__ == '__main__':
simply call main(*sys.argv[1:])
if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module()
and calling test_module()
in your if __name__ == '__main__:'
suite.
if __file__ == $0
).I had the error:
An invalid form control with name='telefono' is not focusable.
This was happening because I was not using the required field correctly, which enabled and disabled when clicking on a checkbok. The solution was to remove the required
attribute whenever the checkbok was not marked and mark it as required when the checkbox was marked.
var telefono = document.getElementById("telefono");
telefono.removeAttribute("required");
The official way to detect .NET 3.0 is described here
http://msdn.microsoft.com/en-us/library/aa480198.aspx
Flawed, because it requires the caller to have registry access permissions.
MSDN also mentions a technique for detecting .NET 3.5 by checking the User Agent string:
http://msdn.microsoft.com/en-us/library/bb909885.aspx
I think Microsoft should have done a better job than this.
Try this solution.
$mainModelData = mainModel::where('column', $value)
->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
->orderBy('relation_table.title', 'ASC')
->with(['relationModal' => function ($q) {
$q->where('column', 'value');
}])->get();
Example:
$user = User::where('city', 'kullu')
->join('salaries', 'users.id', '=', 'salaries.user_id')
->orderBy('salaries.amount', 'ASC')
->with(['salaries' => function ($q) {
$q->where('amount', '>', '500000');
}])->get();
You can change the column name in join()
as per your database structure.
Change the code to:
public abstract class clsAbstractTable {
protected String TAG;
public abstract void init();
}
public class clsContactGroups extends clsAbstractTable {
public String doSomething() {
return TAG + "<something else>";
}
}
That way, all of the classes who inherit this class will have this variable. You can do 200 subclasses and still each one of them will have this variable.
Side note: do not use CAPS as variable name; common wisdom is that all caps identifiers refer to constants, i.e. non-changeable pieces of data.
We can change the item by value, here is the trick:
radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
This will not work alert(new Date('2010-11-29'));
safari have some weird/strict way of processing date format alert(new Date(String('2010-11-29')));
try like this.
(Or)
Using Moment js will solve the issue though, After ios 14 the safari gets even weird
Try this alert(moment(String("2015-12-31 00:00:00")));
Moment JS
You can try df.column_name = df.column_name.astype(float)
. As for the NaN
values, you need to specify how they should be converted, but you can use the .fillna
method to do it.
Example:
In [12]: df
Out[12]:
a b
0 0.1 0.2
1 NaN 0.3
2 0.4 0.5
In [13]: df.a.values
Out[13]: array(['0.1', nan, '0.4'], dtype=object)
In [14]: df.a = df.a.astype(float).fillna(0.0)
In [15]: df
Out[15]:
a b
0 0.1 0.2
1 0.0 0.3
2 0.4 0.5
In [16]: df.a.values
Out[16]: array([ 0.1, 0. , 0.4])
Another hints for Unexpected token
errors.
There are two major differences between javascript objects and json:
Correct JSON
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
}
Error JSON 1
{
'english': 'bag',
'kana': 'kaban',
'kanji': 'K'
}
Error JSON 2
{
english: "bag",
kana: "kaban",
kanji: "K"
}
Remark
This is not a direct answer for that question. But it's an answer for Unexpected token
errors. So it may be help others who stumple upon that question.
Always use static in .c
files unless you need to reference the object from a different .c
module.
Never use static in .h
files, because you will create a different object every time it is included.
select (floor(((DATE2-DATE1)*24*60*60)/3600)|| ' : ' ||floor((((DATE2-DATE1)*24*60*60) -floor(((DATE2-DATE1)*24*60*60)/3600)*3600)/60)|| ' ' ) as time_difference from TABLE1
You can check a checkbox checked condition using JavaScript in different ways. You can see below.
First method -
$('.myCheckbox').prop('checked', true);
Second method -
$('.myCheckbox').attr('checked', true);
Third method (for check condition if checkbox is checked or not) - $('.myCheckbox').is(':checked')
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the activity. After researching the problem on Stack Overflow, I adopted the following solution:
volatile boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.
With java 1.8 stream can be used ,
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
List<String> list = Arrays.asList("Bill","Bob","Steve").
String str = list.stream().collect(Collectors.joining(" and "));
Use this solution
<!--[if lt IE 9]>
<script src="js/css3-mediaqueries.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap-ie7.css" />
<![endif]-->
This string <script src="js/css3-mediaqueries.js"></script>
enable mediaqueries.
This string <link rel="stylesheet" type="text/css" href="css/bootstrap-ie7.css" />
enable bootstrap fonts.
Tested on Bootstrap 3.3.5
Link to download mediaqieries.js. Link to download bootstrap-ie7.css
I use this class for Audio play. If your audio location is raw folder.
Call method for play:
new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
.getDetail().get(0).getAudio(),"raw", getPackageName()));
AudioPlayer.java class:
public class AudioPlayer {
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
// mothod for raw folder (R.raw.fileName)
public void play(Context context, int rid){
stop();
mMediaPlayer = MediaPlayer.create(context, rid);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
// mothod for other folder
public void play(Context context, String name) {
stop();
//mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
}
It seems working :
HTML :
<input type='text' id="pointspossible"/>
<input type='text' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>
JavaScript :
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = parseInt($('#pointspossible').val());
var pEarned = parseInt($('#pointsgiven').val());
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned/pPos) * 100).toFixed(3);
}
$('#pointsperc').val(perc);
}
});
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
Based on antoinepairet's comment/example:
Using uib-collapse
attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="collapse navbar-collapse" uib-collapse="navCollapsed">
<ul class="nav navbar-nav">
...
</ul>
</div>
</nav>
I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:
The only variation from the official bootstrap example is the addition of ng-
attributes noted by comments, below:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- note the ng-class here -->
<div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">
<ul class="nav navbar-nav">
...
Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)
This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!
Floating point numbers are represented in scientific notation as a number of only seven significant digits multiplied by a larger number that represents the place of the decimal place. More information about it on Wikipedia:
its work for me SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.format(new Date));
I agree that Google's Gson
is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple
:
// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;
@Test
public void json2Object() {
// given
String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
+ "\"address\" : \"some address\","
+ "\"someobject\" : {\"field\" : \"value\"}}";
// when
JSONObject object = (JSONObject) JSONValue.parse(jsonString);
// then
@SuppressWarnings("unchecked")
Set<String> keySet = object.keySet();
for (String key : keySet) {
Object value = object.get(key);
System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
.getSimpleName());
}
assertThat(object.get("age").toString(), is("20"));
}
Pros and cons of Gson
and json-simple
is pretty much like pros and cons of user-defined Java Object and Map
. The object you define is clear for all fields (name and type), but less flexible than Map
.
Use:
function console_log($data) {
$bt = debug_backtrace();
$caller = array_shift($bt);
if (is_array($data))
$dataPart = implode(',', $data);
else
$dataPart = $data;
$toSplit = $caller['file'])) . ':' .
$caller['line'] . ' => ' . $dataPart
error_log(end(split('/', $toSplit));
}
I ran into a similar need. I wanted something that will give me easy transformation from/to JSON that is coming from a REST api call to/from specific class definition. The solutions that I've found were insufficient or meant to rewrite my classes' code and adding annotations or similars.
I wanted something like GSON is used in Java to serialize/deserialize classes to/from JSON objects.
Combined with a later need, that the converter will function in JS as well, I ended writing my own package.
It has though, a little bit of overhead. But when started it is very convenient in adding and editing.
You initialize the module with :
Then in your code, you use the initialized module like :
const convertedNewClassesArray : MyClass[] = this.converter.convert<MyClass>(jsonObjArray, 'MyClass');
const convertedNewClass : MyClass = this.converter.convertOneObject<MyClass>(jsonObj, 'MyClass');
or , to JSON :
const jsonObject = this.converter.convertToJson(myClassInstance);
Use this link to the npm package and also a detailed explanation to how to work with the module: json-class-converter
Also wrapped it for
Angular use in :
angular-json-class-converter
If you use Spring Boot, you can configure Jackson globally as follows:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
public class JacksonObjectMapperConfiguration implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.visibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
jacksonObjectMapperBuilder.visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
jacksonObjectMapperBuilder.visibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY);
}
}
I had the same issue. And I was able to solve it by using a formatter.
file_name = "abc.txt"
new_string = "I am a new string."
opened_file = open(file_name, 'a')
opened_file.write("%r\n" %new_string)
opened_file.close()
I hope this helps.
Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:
Using ImageLocation property of the PictureBox like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "../SamuderaJayaMotor.png";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
Using an image from the web like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.
If you really want a vba solution you can loop through a range like this:
Sub Check()
Dim dat As Variant
Dim rng As Range
Dim i As Long
Set rng = Range("A1:A100")
dat = rng
For i = LBound(dat, 1) To UBound(dat, 1)
If dat(i, 1) <> "" Then
rng(i, 2).Value = "My Text"
End If
Next
End Sub
*EDIT*
Instead of using varients you can just loop through the range like this:
Sub Check()
Dim rng As Range
Dim i As Long
'Set the range in column A you want to loop through
Set rng = Range("A1:A100")
For Each cell In rng
'test if cell is empty
If cell.Value <> "" Then
'write to adjacent cell
cell.Offset(0, 1).Value = "My Text"
End If
Next
End Sub
Dim row As DataRow
For Each row In dtDataTable.Rows
Dim strDetail As String
strDetail = row("Detail")
Console.WriteLine("Processing Detail {0}", strDetail)
Next row
The PyMsgBox module does exactly this. It has message box functions that follow the naming conventions of JavaScript: alert(), confirm(), prompt() and password() (which is prompt() but uses * when you type). These function calls block until the user clicks an OK/Cancel button. It's a cross-platform, pure Python module with no dependencies outside of tkinter.
Install with: pip install PyMsgBox
Sample usage:
import pymsgbox
pymsgbox.alert('This is an alert!', 'Title')
response = pymsgbox.prompt('What is your name?')
Full documentation at http://pymsgbox.readthedocs.org/en/latest/
No valid Kits found The problem occurs because qt-creator don't know the versions of your qt, your compiler or your debugger. First off, let's solve the Qt versions. It may normally solve the others too ;).
You try to create a new project, run select a kit and then there is no kit available in the list.
Follow the steps:
Yes I ...
Hope it's help ;)
To Write
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\listfile.txt",2,true)
objFileToWrite.WriteLine(data)
objFileToWrite.Close
Set objFileToWrite = Nothing
OpenTextFile parameters:
<filename>, IOMode (1=Read,2=write,8=Append), Create (true,false), Format (-2=System Default,-1=Unicode,0=ASCII)
To Read the entire file
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\listfile.txt",1)
strFileText = objFileToRead.ReadAll()
objFileToRead.Close
Set objFileToRead = Nothing
To Read line by line
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\listfile.txt",1)
Dim strLine
do while not objFileToRead.AtEndOfStream
strLine = objFileToRead.ReadLine()
'Do something with the line
loop
objFileToRead.Close
Set objFileToRead = Nothing
If you want the latest Beta, it will not be in the AppStore. Instead you have to login to https://developer.apple.com and download from there.
(Copy/paste of an answer I provided elsewhere)
Falling through switch
-case
s can be achieved by having no code in a case
(see case 0
), or using the special goto case
(see case 1
) or goto default
(see case 2
) forms:
switch (/*...*/) {
case 0: // shares the exact same code as case 1
case 1:
// do something
goto case 2;
case 2:
// do something else
goto default;
default:
// do something entirely different
break;
}
arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:
You could add an "imported" library target, instead of a link-directory. Something like:
# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )
And then link as if this library was built by your project:
TARGET_LINK_LIBRARIES(GLBall mylib)
Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.
I do not know if this will solve your problem with "updated versions of libs".
You can use the SharedPreferences to identify if it is the "First time" the app is launched. Just use a Boolean variable ("my_first_time") and change its value to false when your task for "first time" is over.
This is my code to catch the first time you open the app:
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
Log.d("Comments", "First time");
// first time task
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}
In addition to previous post you can have
<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />
Jsf 2.0
Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.
And the verification can be easily made with the following script contained in the blog post before:
DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)
Use CSS: overflow:
.thumb {
width:230px;
height:230px;
overflow:hidden
}
There are two ways to specify label for element:
So, the proper way to find element's label is
var $element = $( ... )
var $label = $("label[for='"+$element.attr('id')+"']")
if ($label.length == 0) {
$label = $element.closest('label')
}
if ($label.length == 0) {
// label wasn't found
} else {
// label was found
}
given:
public enum BonusType { MONTHLY(0), YEARLY(1), ONE_OFF(2) }
BonusType bonus = YEARLY;
System.out.println(bonus.Ordinal() + ":" + bonus)
Output: 1:YEARLY
Or you can use JQuery - just add your input field to the class "phone" and put this in your script section:
$(".phone").keyup(function () {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
There is no error message but you can see that the phone number is not correctly formatted until you have entered all ten digits.
Are you looking to do something like this http://jsfiddle.net/robert/xhHkG/
$('#transactionType').attr({
'multiple': true,
'size' : 10
});
Put that in a $(function() {...})
or some other onload
Reread your question, you're not really looking for a multiple select... but a dropdown box that allows you to select multiple. Yeah, probably best to use a plugin for that or write it from the ground up, it's not a "quick answer" type deal though.
Lumia phones give wrong screen.width (at least on emulator).
So maybe Math.min(window.innerWidth || Infinity, screen.width)
will work on all devices?
Or something crazier:
for (var i = 100; !window.matchMedia('(max-device-width: ' + i + 'px)').matches; i++) {}
var deviceWidth = i;
The git blame
command is used to know who/which commit is responsible for the latest changes made to a file. The author/commit of each line can also been seen.
git blame filename
(commits responsible for changes for all lines in code)
git blame filename -L 0,10
(commits responsible for changes from line "0" to line "10")
There are many other options for blame, but generally these could help.
SELECT ROW_NUMBER() OVER (ORDER BY ColumnName1) As SrNo, ColumnName1, ColumnName2 FROM TableName
The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.
Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.
>>>
is unsigned-shift; it'll insert 0. >>
is signed, and will extend the sign bit.
The shift operators include left shift
<<
, signed right shift>>
, and unsigned right shift>>>
.The value of
n>>s
isn
right-shifteds
bit positions with sign-extension.The value of
n>>>s
isn
right-shifteds
bit positions with zero-extension.
System.out.println(Integer.toBinaryString(-1));
// prints "11111111111111111111111111111111"
System.out.println(Integer.toBinaryString(-1 >> 16));
// prints "11111111111111111111111111111111"
System.out.println(Integer.toBinaryString(-1 >>> 16));
// prints "1111111111111111"
To make things more clear adding positive counterpart
System.out.println(Integer.toBinaryString(121));
// prints "1111001"
System.out.println(Integer.toBinaryString(121 >> 1));
// prints "111100"
System.out.println(Integer.toBinaryString(121 >>> 1));
// prints "111100"
Since it is positive both signed and unsigned shifts will add 0 to left most bit.
1 >>> 32 == 1
I face with the same issue. I deleted the local repository and relaunched the ID. It worked fine .
That is not an error; the make command in unix works based on the timestamps. I.e let's say if you have made certain changes to factorial.cpp
and compile using make
then make shows
the information that only the cc -o factorial.cpp
command is executed. Next time if you execute the same command i.e make
without making any changes to any file with .cpp
extension the compiler says that the output file is up to date. The compiler gives this information until we make certain changes to any file.cpp
.
The advantage of the makefile
is that it reduces the recompiling time by compiling the only files that are modified and by using the object (.o
) files of the unmodified files directly.
Craiglist is pretty stingy with their data , they even go out of their way to block scraping. If you use ruby here is a gem I wrote to help scrape craiglist data you can search through multiple cities , calculate average price ect...
Use cmp
command. This will either exit cleanly if they are binary equal, or it will print out where the first difference occurs and exit.
Like the answer of @memical.
However I found some improvements. You can use the jQuery height()
function. But be aware of padding-top and padding-bottom pixels. Otherwise your textarea will grow too fast.
$(document).ready(function() {
$textarea = $("#my-textarea");
// There is some diff between scrollheight and height:
// padding-top and padding-bottom
var diff = $textarea.prop("scrollHeight") - $textarea.height();
$textarea.live("keyup", function() {
var height = $textarea.prop("scrollHeight") - diff;
$textarea.height(height);
});
});
You can use this code
var stringDate = "2005-07-08T00:00:00+0000";
var dTimezone = new Date();
var offset = dTimezone.getTimezoneOffset() / 60;
var date = new Date(Date.parse(stringDate));
date.setHours(date.getHours() + offset);
If you are looking for a scripted solution:
.vsix
files (see example below)unzip
the binary into ~/.vscode/extensions/
: you need to modify unzipped directory name, remove one file and move/rename another one.For API start by looking at following example, and for hints how to modify request head to https://github.com/Microsoft/vscode/blob/master/src/vs/platform/extensionManagement/common/extensionGalleryService.ts.
POST https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=5.1-preview HTTP/1.1
content-type: application/json
{
"filters": [
{
"criteria": [
{
"filterType": 8,
"value": "Microsoft.VisualStudio.Code",
},
{
"filterType": 7,
"value": "ms-python.python",
}
],
"pageNumber": 1,
"pageSize": 10,
"sortBy": 0,
"sortOrder": 0,
}
],
"assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"],
"flags": 514,
}
Explanations to the above example:
"filterType": 8
- FilterType.Target
more FilterTypes"filterType": 7
- FilterType.ExtensionName
more FilterTypes"flags": 514
- 0x2 | 0x200
- Flags.IncludeFiles | Flags.IncludeLatestVersionOnly
- more Flags
python -c "print(0x2|0x200)"
"assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"]
- to get only link to .vsix
file more AssetTypesYou can use google map Obtaining User Location here!
After obtaining your location(longitude and latitude), you can use google place api
This code can help you get your location easily but not the best way.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
To expand on @cybersnoopy 's suggestion here
if you had a .proto file with a message like so:
message Request {
oneof option {
int64 option_value = 1;
}
}
You can make use of the case options provided (java generated code):
So we can now write some code as follows:
Request.OptionCase optionCase = request.getOptionCase();
OptionCase optionNotSet = OPTION_NOT_SET;
if (optionNotSet.equals(optionCase)){
// value not set
} else {
// value set
}
As you already hinted in your question, your code creates all promises synchronously. Instead they should only be created at the time the preceding one resolves.
Secondly, each promise that is created with new Promise
needs to be resolved with a call to resolve
(or reject
). This should be done when the timer expires. That will trigger any then
callback you would have on that promise. And such a then
callback (or await
) is a necessity in order to implement the chain.
With those ingredients, there are several ways to perform this asynchronous chaining:
With a for
loop that starts with an immediately resolving promise
With Array#reduce
that starts with an immediately resolving promise
With a function that passes itself as resolution callback
With ECMAScript2017's async
/ await
syntax
With ECMAScript2020's for await...of
syntax
See a snippet and comments for each of these options below.
for
You can use a for
loop, but you must make sure it doesn't execute new Promise
synchronously. Instead you create an initial immediately resolving promise, and then chain new promises as the previous ones resolve:
for (let i = 0, p = Promise.resolve(); i < 10; i++) {
p = p.then(_ => new Promise(resolve =>
setTimeout(function () {
console.log(i);
resolve();
}, Math.random() * 1000)
));
}
_x000D_
reduce
This is just a more functional approach to the previous strategy. You create an array with the same length as the chain you want to execute, and start out with an immediately resolving promise:
[...Array(10)].reduce( (p, _, i) =>
p.then(_ => new Promise(resolve =>
setTimeout(function () {
console.log(i);
resolve();
}, Math.random() * 1000)
))
, Promise.resolve() );
_x000D_
This is probably more useful when you actually have an array with data to be used in the promises.
Here we create a function and call it immediately. It creates the first promise synchronously. When it resolves, the function is called again:
(function loop(i) {
if (i < 10) new Promise((resolve, reject) => {
setTimeout( () => {
console.log(i);
resolve();
}, Math.random() * 1000);
}).then(loop.bind(null, i+1));
})(0);
_x000D_
This creates a function named loop
, and at the very end of the code you can see it gets called immediately with argument 0. This is the counter, and the i argument. The function will create a new promise if that counter is still below 10, otherwise the chaining stops.
The call to resolve()
will trigger the then
callback which will call the function again. loop.bind(null, i+1)
is just a different way of saying _ => loop(i+1)
.
async
/await
Modern JS engines support this syntax:
(async function loop() {
for (let i = 0; i < 10; i++) {
await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
console.log(i);
}
})();
_x000D_
It may look strange, as it seems like the new Promise()
calls are executed synchronously, but in reality the async
function returns when it executes the first await
. Every time an awaited promise resolves, the function's running context is restored, and proceeds after the await
, until it encounters the next one, and so it continues until the loop finishes.
As it may be a common thing to return a promise based on a timeout, you could create a separate function for generating such a promise. This is called promisifying a function, in this case setTimeout
. It may improve the readability of the code:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
(async function loop() {
for (let i = 0; i < 10; i++) {
await delay(Math.random() * 1000);
console.log(i);
}
})();
_x000D_
for await...of
With EcmaScript 2020, the for await...of
found its way to modern JavaScript engines. Although it does not really reduce code in this case, it allows to isolate the definition of the random interval chain from the actual iteration of it:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function * randomDelays(count ,max) {
for (let i = 0; i < count; i++) yield delay(Math.random() * max).then(() => i);
}
(async function loop() {
for await (let i of randomDelays(10, 1000)) console.log(i);
})();
_x000D_
Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
Becomes:
printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");
With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:
any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)
How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.
It's torture. Instead of including a generic conf file, they make you hit return 9000 times to generate one.
Sort a list of integers descending
class Program
{
private class SortIntDescending : IComparer<int>
{
int IComparer<int>.Compare(int a, int b) //implement Compare
{
if (a > b)
return -1; //normally greater than = 1
if (a < b)
return 1; // normally smaller than = -1
else
return 0; // equal
}
}
static List<int> intlist = new List<int>(); // make a list
static void Main(string[] args)
{
intlist.Add(5); //fill the list with 5 ints
intlist.Add(3);
intlist.Add(5);
intlist.Add(15);
intlist.Add(7);
Console.WriteLine("Unsorted list :");
Printlist(intlist);
Console.WriteLine();
// intlist.Sort(); uses the default Comparer, which is ascending
intlist.Sort(new SortIntDescending()); //sort descending
Console.WriteLine("Sorted descending list :");
Printlist(intlist);
Console.ReadKey(); //wait for keydown
}
static void Printlist(List<int> L)
{
foreach (int i in L) //print on the console
{
Console.WriteLine(i);
}
}
}
Based on docker documentation: https://docs.docker.com/compose/compose-file/#/command
I simply put
hostname: <string>
in my docker-compose file.
E.g.:
[...]
lb01:
hostname: at-lb01
image: at-client-base:v1
[...]
and container lb01 picks up at-lb01
as hostname.
If you look in the service details, you can see that the command to start the service is something like:
"C:\Program Files\MongoDB\bin\mongod" --config C:\Program Files\MongoDB\mongod.cfg --service
The MongoDB team forgot to add the "
around the --config
option. So just edit the registry to correct it and it will work.
Download and run the following script to recursively convert hard tabs to soft tabs in plain text files.
Execute the script from inside the folder which contains the plain text files.
#!/bin/bash
find . -type f -and -not -path './.git/*' -exec grep -Iq . {} \; -and -print | while read -r file; do {
echo "Converting... "$file"";
data=$(expand --initial -t 4 "$file");
rm "$file";
echo "$data" > "$file";
}; done;
Yes, you can do this quite easily. Click on your project in the project explorer or Navigator, go to the Search menu at the top, click File..., input your search string, and make sure that 'Selected Resources' or 'Enclosing Projects' is selected, then hit search. The alternative way to open the window is with Ctrl-H. This may depend on your keyboard accelerator configuration.
More details: http://www.ehow.com/how_4742705_file-eclipse.html and http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html
(source: avajava.com)
You can write your own Extension method for type String :-
public static string NonBlankValueOf(this string source)
{
return (string.IsNullOrEmpty(source)) ? "0" : source;
}
Now you can use it like with any string type
FooTextBox.Text = strFoo.NonBlankValueOf();
You can think of an iframe as an embedded browser window that you can put on an HTML page to show another URL inside it. This URL can be totally distinct from your web site/app.
You can put an iframe in any HTML page, so you could put one inside a contentplaceholder in a webform that has a Masterpage and it will appear with whatever URL you load into it (via Javascript, or C# if you turn your iframe into a server-side control (runat='server'
) on the final HTML page that your webform produces when requested.
And you can load a URL into your iframe that is a .aspx
page.
But - iframes have nothing to do with the ASP.net mechanism. They are HTML elements that can be made to run server-side, but they are essentially 'dumb' and unmanaged/unconnected to the ASP.Net mechanisms - don't confuse a Contentplaceholder with an iframe.
Incidentally, the use of iframes is still contentious - do you really need to use one? Can you afford the negative trade-offs associated with them e.g. lack of navigation history ...?
You just need to remove the LocationListener
from LocationManager
manager.removeUpdates(listener);
If your form does not have any id, but it has a class name like theForm, you can use the below statement to submit it:
document.getElementsByClassName("theForm")[0].submit();
This has been answered by a lot of people, but I feel like the simplest solution has been left out.
SQL SERVER (I believe its 2012+) has implicit string equivalents for DATETIME2 as shown here
Look at the section on "Supported string literal formats for datetime2"
To answer the OPs question explicitly:
DECLARE @myVar NCHAR(32)
DECLARE @myDt DATETIME2
SELECT @myVar = @GETDATE()
SELECT @myDt = @myVar
PRINT(@myVar)
PRINT(@myDt)
output:
Jan 23 2019 12:24PM
2019-01-23 12:24:00.0000000
Note:
The first variable (myVar
) is actually holding the value '2019-01-23 12:24:00.0000000'
as well. It just gets formatted to Jan 23 2019 12:24PM
due to default formatting set for SQL SERVER that gets called on when you use PRINT
. Don't get tripped up here by that, the actual string in (myVer)
= '2019-01-23 12:24:00.0000000'
A bit long winded but it works for me: try this::
=SUM(IF(OR(ISBLANK(AU2), NOT(ISERR(YEAR(AU2)))),0,1)
+IF(OR(ISBLANK(AV2), NOT(ISERR(YEAR(AV2)))),0,1))
first part of if will allow cell to be blank or if there is something in the cell it tries to convert to a year, if there is an error or there is something other than a date result = 1, do the same for each cell and sum the result
You get this message in the logs, because you do something that is not allowed in the current state of your MediaPlayer instance.
Therefore you should always register an error handler to catch those things (as @tidbeck suggested).
At first, I advice you to take a look at the documentation for the MediaPlayer
class and get an understanding of what that with states means. See: http://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram
Your mistake here could well be one of the common ones, the others wrote here, but in general, I would take a look at the documentation of what methods are valid to call in what state: http://developer.android.com/reference/android/media/MediaPlayer.html#Valid_and_Invalid_States
In my example it was the method mediaPlayer.CurrentPosition
, that I called while the media player was in a state, where it was not allowed to call this property.
More specifically:
Server Manager
(on task bar and start menu)Roles and Features
" section.Add Role or Feature
" from Tasks drop downAdd Role or Feature Wizard
" dialog, click down to "Features
" in list of pages on the left.".Net 3.5"
or ".Net 4.5"
, depending on what you have installed. (you can go back up to "roles
" screen to add if you don't have.WCF Services
", check the box for "HTTP-Activation
". You can also add non-http types if you know you need them (tcp, named pipes, etc)."Install"
Button.Use traits as base classes. Then use them in a parent class. Extend it .
trait business{
function sell(){
}
function buy(){
}
function collectMoney(){
}
}
trait human{
function think(){
}
function speak(){
}
}
class BusinessPerson{
use business;
use human;
// If you have more traits bring more
}
class BusinessWoman extends BusinessPerson{
function getPregnant(){
}
}
$bw = new BusinessWoman();
$bw ->speak();
$bw->getPregnant();
See now business woman logically inherited business and human both;
You can explicitly export it to the global scope with global.FOO = 5
. Then you simply need to require the file, and not even save your return value.
But really, you shouldn't do that. Keeping things properly encapsulated is a good thing. You have the right idea already, so keep doing what you're doing.
I mistankly put a space after the - so instead of -m I had - m Just something to look for.
<section>
marks up a section, <div>
marks up a generic block with no associated semantics.
Another solution using recursion:
def subsets(nums: List[int]) -> List[List[int]]:
n = len(nums)
output = [[]]
for num in nums:
output += [curr + [num] for curr in output]
return output
Starting from empty subset in output list. At each step we take a new integer into consideration and generates new subsets from the existing ones.
XSD files are used to validate that XML files conform to a certain format.
In that respect they are similar to DTDs that existed before them.
The main difference between XSD and DTD is that XSD is written in XML and is considered easier to read and understand.
Here are a few ways to create a list with N of continuous natural numbers starting from 1.
1 range:
def numbers(n):
return range(1, n+1);
2 List Comprehensions:
def numbers(n):
return [i for i in range(1, n+1)]
You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!
You could try using the third-party tool called NirCmd. It is a genuine, free command line utility. If or when you have it, use this code in a batch file:
title Open Word
nircmd win hide title "Open Word"
start "C:\Program" "Files" "(x86)\Microsoft" "Office\Office12\WINWORD.exe
nircmd wait 20
nircmd win min foreground
exit
This program, in order, changes its title, hides itself according to its title, starts Word, waits 20 milliseconds as a buffer for Word to settle, minimizes Word by assuming it is now the top window, and then exits itself. This program should work as intended as long as their are no key presses or clicks in that ~50 millisecond time window, which shouldn't be hard.
As for installing nircmd on your computer, use this link, and click "Download NirCmd" at the bottom of the page. Save the .zip folder to a normal directory (like "My Documents"), extract it, and copy "nircmd.exe" to %systemroot%\system32, and there you go. Now you have nircmd included with your command line utilities.
Another alternative is that you are allowed to have multiple classes in a tag. Consider:
<div class="button big">This is a big button</div>
<div class="button small">This is a small button</div>
And the CSS:
.button {
/* all your common button styles */
}
.big {
height: 60px;
width: 100px;
}
.small {
height: 40px;
width: 70px;
}
and so on.
I'd go with COUNT(1)
. It is faster than COUNT(*)
because COUNT(*)
tests to see if at least one column in that row is != NULL. You don't need that, especially because you already have a condition in place (the WHERE
clause). COUNT(1)
instead tests the validity of 1
, which is always valid and takes a lot less time to test.
Are you sure that all the lines have at least 2 columns? Can you try something like, just to check?:
sc.textFile("file.csv") \
.map(lambda line: line.split(",")) \
.filter(lambda line: len(line)>1) \
.map(lambda line: (line[0],line[1])) \
.collect()
Alternatively, you could print the culprit (if any):
sc.textFile("file.csv") \
.map(lambda line: line.split(",")) \
.filter(lambda line: len(line)<=1) \
.collect()
My guess is that you don't really want to GROUP BY
some_product.
The answer to: "Is there a way to GROUP BY
a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY
a column alias.
The SELECT
clause, where column aliases are assigned, is not processed until after the GROUP BY
clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.
Inline view:
select ...
from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... ) T
group by some_product ...
CTE:
with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... )
select ...
from T
group by some_product ...
When you call startActivity
on the last activity you could always use
Intent.FLAG_ACTIVITY_CLEAR_TOP
as a flag on that intent.
Read more about the flag here.
you need to wrap your text inside div and float it left while wrapper div should have height, and I've also added line height for vertical alignment
<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray;height:30px;">
<div style="float:left;line-height:30px;">Contact Details</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>
</div>
also js fiddle here =) http://jsfiddle.net/xQgSm/
You might read up on FILESTREAM. Here is some info from the docs that should help you decide:
If the following conditions are true, you should consider using FILESTREAM:
- Objects that are being stored are, on average, larger than 1 MB.
- Fast read access is important.
- You are developing applications that use a middle tier for application logic.
For smaller objects, storing varbinary(max) BLOBs in the database often provides better streaming performance.
page-break-inside: avoid;
does not seem to always work. It seems to take into account the height and positioning of container elements.
For example, inline-block
elements that are taller than the page will get clipped.
I was able to restore working page-break-inside: avoid;
functionality by identifying a container element with display: inline-block
and adding:
@media print {
.container { display: block; } /* this is key */
div, p, ..etc { page-break-inside: avoid; }
}
Hope this helps folks who complain that "page-break-inside does not work".
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
Visual Studio 2017 / 2019
For anyone looking for an answer for a newer version of Visual Studio, install the Editor Guidelines plugin, then right-click in the editor and select this:
Clarifying it. Model:
public class ContactUsModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public HttpPostedFileBase attachment { get; set; }
Post Action
public virtual ActionResult ContactUs(ContactUsModel Model)
{
if (Model.attachment.HasFile())
{
//save the file
//Send it as an attachment
Attachment messageAttachment = new Attachment(Model.attachment.InputStream, Model.attachment.FileName);
}
}
Finally the Extension method for checking the hasFile
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AtlanticCMS.Web.Common
{
public static class ExtensionMethods
{
public static bool HasFile(this HttpPostedFileBase file)
{
return file != null && file.ContentLength > 0;
}
}
}
Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...
id = cursor.lastrowid
...should work too, and it's per-connection based obviously.
Following code block shows how to calculate the difference in number of days between two dates using MomentJS.
var now = moment(new Date()); //todays date
var end = moment("2015-12-1"); // another date
var duration = moment.duration(now.diff(end));
var days = duration.asDays();
console.log(days)
You can do something like req.param('tagId')
try this, work for me
Put the two options, colorAccent
and android:colorAccent
<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
....
<item name="android:dialogTheme">@style/AppTheme.DialogTheme</item>
<item name="android:datePickerDialogTheme">@style/Dialog.Theme</item>
</style>
<style name="AppTheme.DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<!-- Put the two options, colorAccent and android:colorAccent. -->
<item name="colorAccent">@color/colorPrimary</item>
<item name="android:colorPrimary">@color/colorPrimary</item>
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="android:colorAccent">@color/colorPrimary</item>
</style>
import java.io.File;
import java.io.PrintWriter;
public class Testing
{
public static void main(String[] args)
{
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
}
}
Today things have changed a little.
Now we avoid use ProgressDialog to show spinning progress:
If you want to put in your app a spinning progress you should use an Activity indicators:
http://developer.android.com/design/building-blocks/progress.html#activity
Yes, just open the "Source" Tab in the dev-tools and navigate to the script you want to change . Make your adjustments directly in the dev tools window and then hit ctrl+s to save the script - know the new js will be used until you refresh the whole page.
Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.
In python 3 you can easily convert a byte string into a list of integers (0..255) by
>>> list(b'y\xcc\xa6\xbb')
[121, 204, 166, 187]
Unordered lists are often created with the intent of using them as a menu, but an li
list item is text. Because the list li
item is text, the mouse pointer will not be an arrow, but an "I cursor". Users are accustomed to seeing a pointing finger for a mouse pointer when something is clickable. Using an anchor tag a
inside of the li
tag causes the mouse pointer to change to a pointing finger. The pointing finger is a lot better for using the list as a menu.
<ul id="menu">
<li><a href="#">Menu Item 1</a></li>
<li><a href="#">Menu Item 2</a></li>
<li><a href="#">Menu Item 3</a></li>
<li><a href="#">Menu Item 4</a></li>
</ul>
If the list is being used for a menu, and doesn't need a link, then a URL doesn't need to be designated. But the problem is that if you leave out the href
attribute, text in the <a>
tag is seen as text, and therefore the mouse pointer is back to an I-cursor. The I-cursor might make the user think that the menu item is not clickable. Therefore, you still need an href
, but you don't need a link to anywhere.
You could use lots of div
or p
tags for a menu list, but the mouse pointer would be an I-cursor for them also.
You could use lots of buttons stacked on top of each other for a menu list, but the list seems to be preferable. And that's probably why the href="#"
that points to nowhere is used in anchor tags inside of list tags.
You can set the pointer style in CSS, so that is another option. The href="#"
to nowhere might just be the lazy way to set some styling.
You need to remember that IQueryable queries are not actually executed against the data store until you enumerate them.
using (var dataContext = new dataContext())
{
This line of code doesn't actually do anything other than build the SQL statement
users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);
.Any() is an operation that enumerates the IQueryable, so the SQL is sent to the data source (through dataContext), and then the .Any() operations is executed against it
if(users.Any() == false)
{
return null;
}
}
Your "problem" line is reusing the sql built above, and then doing an additional operation (.Select()), which just adds to the query. If you left it here, no exception, except your problem line
return users.Select(x => x.ToInfo()).ToList(); // this line is the problem
calls .ToList(), which enumerates the IQueryable, which causes the SQL to be sent to the datasource through the dataContext that was used in the original LINQ query. Since this dataContext has been disposed, it is no longer valid, and .ToList() throws an exception.
That is the "why it doesn't work". The fix is to move this line of code inside the scope of your dataContext.
How to use it properly is another question with a few arguably correct answers that depend on your application (Forms vs. ASP.net vs. MVC, etc.). The pattern that this implements is the Unit of Work pattern. There is almost no cost to creating a new context object, so the general rule is to create one, do your work, and then dispose of it. In web apps, some people will create a Context per request.
I believe it is because cell.getCellStyle
initially returns the default cell style which you then change.
Create styles like this and apply them to cells:
cellStyle = (XSSFCellStyle) cell.getSheet().getWorkbook().createCellStyle();
Although as the previous poster noted try and create styles and reuse them.
There is also some utility class in the XSSF library that will avoid the code I have provided and automatically try and reuse styles. Can't remember the class 0ff hand.
One possible solution in pure javascript:
for (var x = 0; x < str.length; x++)
{
var c = str.charAt(x);
alert(c);
}
First of all, both cases calls a constructor. If you write
Example *example = new Example();
then you are creating an object, call the constructor and retrieve a pointer to it.
If you write
Example example;
The only difference is that you are getting the object and not a pointer to it. The constructor called in this case is the same as above, the default (no argument) constructor.
As for the singleton question, you must simple invoke your static method by writing:
Example *e = Singleton::getExample();
The user-agent
should be specified as a field in the header.
Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent
.
The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:
import requests
url = 'SOME URL'
headers = {
'User-Agent': 'My User Agent 1.0',
'From': '[email protected]' # This is another valid field
}
response = requests.get(url, headers=headers)
Older versions of requests
clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.
import requests
url = 'SOME URL'
# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()
# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
{
'User-Agent': 'My User Agent 1.0',
}
)
response = requests.get(url, headers=headers)
Here is an alternative approach that I used to detect the text blocks:
Below is the code written in python with pyopencv, it should easy to port to C++.
import cv2
image = cv2.imread("card.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours
# for each contour found, draw a rectangle around it on original image
for contour in contours:
# get rectangle bounding contour
[x,y,w,h] = cv2.boundingRect(contour)
# discard areas that are too large
if h>300 and w>300:
continue
# discard areas that are too small
if h<40 or w<40:
continue
# draw rectangle around contour on original image
cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)
# write original image with added contours to disk
cv2.imwrite("contoured.jpg", image)
The original image is the first image in your post.
After preprocessing (grayscale, threshold and dilate - so after step 3) the image looked like this:
Below is the resulted image ("contoured.jpg" in the last line); the final bounding boxes for the objects in the image look like this:
You can see the text block on the left is detected as a separate block, delimited from its surroundings.
Using the same script with the same parameters (except for thresholding type that was changed for the second image like described below), here are the results for the other 2 cards:
The parameters (threshold value, dilation parameters) were optimized for this image and this task (finding text blocks) and can be adjusted, if needed, for other cards images or other types of objects to be found.
For thresholding (step 2), I used a black threshold. For images where text is lighter than the background, such as the second image in your post, a white threshold should be used, so replace thesholding type with cv2.THRESH_BINARY
). For the second image I also used a slightly higher value for the threshold (180). Varying the parameters for the threshold value and the number of iterations for dilation will result in different degrees of sensitivity in delimiting objects in the image.
Finding other object types:
For example, decreasing the dilation to 5 iterations in the first image gives us a more fine delimitation of objects in the image, roughly finding all words in the image (rather than text blocks):
Knowing the rough size of a word, here I discarded areas that were too small (below 20 pixels width or height) or too large (above 100 pixels width or height) to ignore objects that are unlikely to be words, to get the results in the above image.
You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.
public class ImageButton extends Parent {
private static final Image NORMAL_IMAGE = ...;
private static final Image PRESSED_IMAGE = ...;
private final ImageView iv;
public ImageButton() {
this.iv = new ImageView(NORMAL_IMAGE);
this.getChildren().add(this.iv);
this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(PRESSED_IMAGE);
}
});
// TODO other event handlers like mouse up
}
}
The object you're saving should have a correct Id
after propagating changes into database.
Check out this post
According to it
No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.
AWT 1 . AWT occupies more memory space 2 . AWT is platform dependent 3 . AWT require javax.awt package
swings 1 . Swing occupies less memory space 2 . Swing component is platform independent 3 . Swing requires javax.swing package
I'd like to make some changes: In C, you can use the built in qsort command:
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
// an easy expression for comparing
return (int_a > int_b) - (int_a < int_b);
}
qsort( a, 6, sizeof(int), compare )
just use:
window.location.href = "http://siwei.me"
Don't use vue-router, otherwise you will be redirected to "http://yoursite.com/#!/http://siwei.me"
my environment: node 6.2.1, vue 1.0.21, Ubuntu.
You can use any of these in your scenario since they write to the default streams (output and error). If you were piping output to another commandlet you would want to use Write-Output, which will eventually terminate in Write-Host.
This article describes the different output options: PowerShell O is for Output
In my case (php 5.6
, Ubuntu 14.04
) the following command worked for me:
sudo apt-get install php5.6-gd
According to php version we need to change the php5.x-gd
The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable
.
So for that, here is what I did, when I came across the same problem.
string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };
foreach (string ColName in ColumnsToBeDeleted)
{
if (dt.Columns.Contains(ColName))
dt.Columns.Remove(ColName);
}
In this example, to force a re-render, just change the variable machine
const [selected, setSelected] = useState(machine)
useEffect(() => {
setSelected(machine)
}, [machine])
Try to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.
The Externalizable interface was not actually provided to optimize the serialization process performance! but to provide means of implementing your own custom processing and offer complete control over the format and contents of the stream for an object and its super types!
Examples of this is the implementation of AMF (ActionScript Message Format) remoting to transfer native action script objects over the network.
The difference is ternary operator
return condition ? someData : Promise.reject(new Error('not OK'))
return condition ? someData : throw new Error('not OK')
Python's sets (and dictionaries) will iterate and print out in some order, but exactly what that order will be is arbitrary, and not guaranteed to remain the same after additions and removals.
Here's an example of a set changing order after a lot of values are added and then removed:
>>> s = set([1,6,8])
>>> print(s)
{8, 1, 6}
>>> s.update(range(10,100000))
>>> for v in range(10, 100000):
s.remove(v)
>>> print(s)
{1, 6, 8}
This is implementation dependent though, and so you should not rely upon it.
For Angular 2
<input [(ngModel)]='email' [required]='!phone' />
<input [(ngModel)]='phone' [required]='!email' />
In case some heroku users stumble here and like me want to copy some data from staging database to the production database or vice versa here's how you do it very conveniently (N.B. I hope there's no typos in there, can't check it atm., I'll try confirm the validity of the code asap):
to_app="The name of the app you want to migrate data to"
from_app="The name of the app you want to migrate data from"
collection="the collection you want to copy"
mongohq_url=`heroku config:get --app "$to_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
to_token=${parts[0]}; to_url=${parts[1]}; to_db=${parts[2]}
mongohq_url=`heroku config:get --app "$from_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
from_token=${parts[0]}; from_url=${parts[1]}; from_db=${parts[2]}
mongodump -h "$from_url" -u heroku -d "$from_db" -p"$from_token" -c "$collection" -o col_dump
mongorestore -h "$prod_url" -u heroku -d "$to_app" -p"$to_token" --dir col_dump/"$col_dump"/$collection".bson -c "$collection"
This message can mean many things clearly.
In my case it was compiling using multiple threads. One thread needed a dependency that another thread hadn't finished making, causing an error.
Not all builds are threadsafe, so consider a slow build with one thread if your build passes other tests such as the ones listed above.
Exception object also contains original response e.response
, that could be useful if need to see error body in response from the server. For example:
try:
r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
r.raise_for_status()
except requests.exceptions.HTTPError as e:
print (e.response.text)
WebDriver driver = new FirefoxDriver();
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
This method removes the extra call ( String.ValueOf() ) to convert unicode to string.
Suppose STUDENTID contains some characters or numbers that you already know i.e. 'searchstring' then below query will work for you.
You could try this:
select * from STUDENTS where CHARINDEX('searchstring',STUDENTID)>0
I think this one is the fastest and easiest one.
You can also override the deployment repository on the command line:
-Darguments=-DaltDeploymentRepository=myreposid::default::http://my/url/releases
That's the Unicode Replacement Character, \uFFFD. (info)
Something like this should work:
String strImport = "For some reason my ?double quotes? were lost.";
strImport = strImport.replaceAll("\uFFFD", "\"");
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
To solve this issue the first thing you need to do is to get the last version of composer :
curl -sS https://getcomposer.org/installer | php
I recommend you to move the composer.phar file to a global “bin” directoy, in my case (OS X) the path is:
mv composer.phar /usr/local/bin/composer.phar
than you need to create an alias file for an easy access
alias composer='/usr/local/bin/composer.phar'
If everything is ok, now it is time to verify our Composer version:
composer --version
Let's make composer great again.
A lot of functions return None if there are no appropriate results. For example, an SQLAlchemy query's .first()
method returns None if there were no rows in the result. Suppose you were selecting a value that might return 0 and need to know whether it's actually 0 or whether the query had no results at all.
A common idiom is to give a function or method's optional argument the default value of None, and then to test that value being None to see if it was specified. For example:
def spam(eggs=None):
if eggs is None:
eggs = retrievefromconfigfile()
compare that to:
def spam(eggs=None):
if not eggs:
eggs = retrievefromconfigfile()
In the latter, what happens if you call spam(0)
or spam([])
? The function would (incorrectly) detect that you hadn't passed in a value for eggs
and would compute a default value for you. That's probably not what you want.
Or imagine a method like "return the list of transactions for a given account". If the account does not exist, it might return None. This is different than returning an empty list (which would mean "this account exists but has not recorded transactions).
Finally, back to database stuff. There's a big difference between NULL and an empty string. An empty string typically says "there's a value here, and that value is nothing at all". NULL says "this value hasn't been entered."
In each of those cases, you'd want to use if A is None
. You're checking for a specific value - None - not just "any value that happens to cast to False".
if exists (
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = '<table_name>'
and COLUMN_NAME = '<column_name>'
) begin
print 'Column you have specified exists'
end else begin
print 'Column does not exist'
end
h = fspecial('average', n);
filter2(h, img);
See doc fspecial
:
h = fspecial('average', n)
returns an averaging filter. n
is a 1-by-2 vector specifying the number of rows and columns in h
.
I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.
head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt
If you don't want to rest of the lines from the file, just skip the tail part.
This is extreme, but I built a dynamic, database-driven filter using a 2 column database table named FILE_TYPES, with field names EXTENSION and DOCTYPE:
---------------------------------
| EXTENSION | DOCTYPE |
---------------------------------
| .doc | Document |
| .docx | Document |
| .pdf | Document |
| ... | ... |
| .bmp | Image |
| .jpg | Image |
| ... | ... |
---------------------------------
Obviously I had many different types and extensions, but I'm simplifying it for this example. Here is my function:
private static string GetUploadFilter()
{
// Desired format:
// "Document files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf|"
// "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|"
string filter = String.Empty;
string nameFilter = String.Empty;
string extFilter = String.Empty;
// Used to get extensions
DataTable dt = new DataTable();
dt = DataLayer.Get_DataTable("SELECT * FROM FILE_TYPES ORDER BY EXTENSION");
// Used to cycle through doctype groupings ("Images", "Documents", etc.)
DataTable dtDocTypes = new DataTable();
dtDocTypes = DataLayer.Get_DataTable("SELECT DISTINCT DOCTYPE FROM FILE_TYPES ORDER BY DOCTYPE");
// For each doctype grouping...
foreach (DataRow drDocType in dtDocTypes.Rows)
{
nameFilter = drDocType["DOCTYPE"].ToString() + " files (";
// ... add its associated extensions
foreach (DataRow dr in dt.Rows)
{
if (dr["DOCTYPE"].ToString() == drDocType["DOCTYPE"].ToString())
{
nameFilter += "*" + dr["EXTENSION"].ToString() + ", ";
extFilter += "*" + dr["EXTENSION"].ToString() + ";";
}
}
// Remove endings put in place in case there was another to add, and end them with pipe characters:
nameFilter = nameFilter.TrimEnd(' ').TrimEnd(',');
nameFilter += ")|";
extFilter = extFilter.TrimEnd(';');
extFilter += "|";
// Add the name and its extensions to our main filter
filter += nameFilter + extFilter;
extFilter = ""; // clear it for next round; nameFilter will be reset to the next DOCTYPE on next pass
}
filter = filter.TrimEnd('|');
return filter;
}
private void UploadFile(string fileType, object sender)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
string filter = GetUploadFilter();
dlg.Filter = filter;
if (dlg.ShowDialog().Value == true)
{
string fileName = dlg.FileName;
System.IO.FileStream fs = System.IO.File.OpenRead(fileName);
byte[] array = new byte[fs.Length];
// This will give you just the filename
fileName = fileName.Split('\\')[fileName.Split('\\').Length - 1];
...
Should yield a filter that looks like this:
Use the command line.
touch /var/www/project1/html/phpinfo.php && echo '<?php phpinfo(); ?>' >> /var/www/project1/html/phpinfo.php && firefox --url localhost/project1/phpinfo.php
Something like that? Idk!
I came across this error when tried to start 32-bit build of Eclipse under 64-bit linux. The problem was solved after installing ia32-libs package.
exec does not execute a command in your shell
try
Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
You can use swift.quicktype.io for converting JSON
to either struct
or class
. Even you can mention version of swift to genrate code.
Example JSON:
{
"message": "Hello, World!"
}
Generated code:
import Foundation
typealias Sample = OtherSample
struct OtherSample: Codable {
let message: String
}
// Serialization extensions
extension OtherSample {
static func from(json: String, using encoding: String.Encoding = .utf8) -> OtherSample? {
guard let data = json.data(using: encoding) else { return nil }
return OtherSample.from(data: data)
}
static func from(data: Data) -> OtherSample? {
let decoder = JSONDecoder()
return try? decoder.decode(OtherSample.self, from: data)
}
var jsonData: Data? {
let encoder = JSONEncoder()
return try? encoder.encode(self)
}
var jsonString: String? {
guard let data = self.jsonData else { return nil }
return String(data: data, encoding: .utf8)
}
}
extension OtherSample {
enum CodingKeys: String, CodingKey {
case message
}
}
This might help:
<input type="number" step="1" pattern="\d+" />
step
is for convenience (and could be set to another integer), but pattern
does some actual enforcing.
Note that since pattern
matches the whole expression, it wasn't necessary to express it as ^\d+$
.
Even with this outwardly tight regular expression, Chrome and Firefox's implementations, interestingly allow for e
here (presumably for scientific notation) as well as -
for negative numbers, and Chrome also allows for .
whereas Firefox is tighter in rejecting unless the .
is followed by 0's only. (Firefox marks the field as red upon the input losing focus whereas Chrome doesn't let you input disallowed values in the first place.)
Since, as observed by others, one should always validate on the server (or on the client too, if using the value locally on the client or wishing to prevent the user from a roundtrip to the server).
If you don't prefer the sticky bottom effect i would put it in viewDidLoad()
https://stackoverflow.com/a/38176479/4127670
The correct syntax for the above statement is:
if (defined?(var)).nil? # will now return true or false
print "var is not defined\n".color(:red)
else
print "var is defined\n".color(:green)
end
substituting (var
) with your variable. This syntax will return a true/false value for evaluation in the if statement.
for Python we can use itertools and import both permutations and combinations to solve your problem
from itertools import product, permutations
A = ([1,2,3])
print (list(permutations(sorted(A),2)))
chmod +x gradlew
Just run the above comment. that's all enjoy your coding...
As explained here, seems the foreign key constraint has to be dropped by constraint name and not the index name.
The syntax is:
ALTER TABLE footable DROP FOREIGN KEY fooconstraint;
For Mapping Composite primary key using Entity framework we can use two approaches.
1) By Overriding the OnModelCreating() Method
For ex: I have the model class named VehicleFeature as shown below.
public class VehicleFeature
{
public int VehicleId { get; set; }
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
The Code in my DBContext would be like ,
public class VegaDbContext : DbContext
{
public DbSet<Make> Makes{get;set;}
public DbSet<Feature> Features{get;set;}
public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)
{
}
// we override the OnModelCreating method here.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
}
}
2) By Data Annotations.
public class VehicleFeature
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int VehicleId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
Please refer the below links for the more information.
1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx
Although the order does not matter as the dictionary is hashmap. It depends on the order how it is pushed in:
s = 'abbc'
a = 'cbab'
def load_dict(s):
dict_tmp = {}
for ch in s:
if ch in dict_tmp.keys():
dict_tmp[ch]+=1
else:
dict_tmp[ch] = 1
return dict_tmp
dict_a = load_dict(a)
dict_s = load_dict(s)
print('for string %s, the keys are %s'%(s, dict_s.keys()))
print('for string %s, the keys are %s'%(a, dict_a.keys()))
output:
for string abbc, the keys are dict_keys(['a', 'b', 'c'])
for string cbab, the keys are dict_keys(['c', 'b', 'a'])
If you project is at /home/forge/laravel-project/
You can properly execute your artisan like this
php /home/forge/laravel-project/artisan ...
From Angsuman Chakraborty (archived) :
/** Get the current line number.
* @return int - Current line number.
*/
public static int getLineNumber() {
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
You can use scala.math.BigDecimal
:
BigDecimal(1.23456789).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble
There are a number of other rounding modes, which unfortunately aren't very well documented at present (although their Java equivalents are).
How about one of the many wikis?
Kenny: I've used FlexWiki & ScrewTurn (abandoned).
someone else with RepPower to edit my post added this.
Wikipedia is powered by MediaWiki.
Here's a pretty ggplot2 solution:
library(ggplot2)
library(scales) # makes pretty labels on the x-axis
breaks=c(0,1,2,3,4,5,25)
ggplot(mydata,aes(x = V3)) +
geom_histogram(breaks = log10(breaks)) +
scale_x_log10(
breaks = breaks,
labels = scales::trans_format("log10", scales::math_format(10^.x))
)
Note that to set the breaks in geom_histogram, they had to be transformed to work with scale_x_log10