Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7
before start make sure of installation:
yum install -y xorg-x11-server-Xorg xorg-x11-xauth xorg-x11-apps
- start
xming
or cygwin
- make connection with X11 forwarding (in putty don't forget to set localhost:0.0 for X display location)
- edit sshd.cong and restart
cat /etc/ssh/sshd_config | grep X
X11Forwarding yes
X11DisplayOffset 10
AddressFamily inet
- Without the X11 forwarding, you are subjected to the X11 SECURITY and then you must:
authorize the remote server to make a connection with the local X Server using a method (for instance, the xhost command)
set the display environment variable to redirect the output to the X server of your local computer.
In this example:
192.168.2.223 is the IP of the server
192.168.2.2 is the IP of the local computer where the x server is installed. localhost can also be used.
blablaco@blablaco01 ~
$ xhost 192.168.2.223
192.168.2.223 being added to access control list
blablaco@blablaco01 ~
$ ssh -l root 192.168.2.223
[email protected] password:
Last login: Sat May 22 18:59:04 2010 from etcetc
[root@oel5u5 ~]# export DISPLAY=192.168.2.2:0.0
[root@oel5u5 ~]# echo $DISPLAY
192.168.2.2:0.0
[root@oel5u5 ~]# xclock&
Then the xclock application must launch.
Check it on putty or mobaxterm and don't check in remote desktop Manager software.
Be careful for user that sudo in.
Can you run GUI applications in a Docker container?
Yet another answer in case you already built the image:
invoke docker w/o sudo
(How to fix docker: Got permission denied issue)
share the same USER & home & passwd between host and container share
(tips: use user id instead of user name)
the dev folder for driver dependent libs to work well
plus X11 forward.
docker run --name=CONTAINER_NAME --network=host --privileged \
-v /dev:/dev \
-v `echo ~`:/home/${USER} \
-p 8080:80 \
--user=`id -u ${USER}` \
--env="DISPLAY" \
--volume="/etc/group:/etc/group:ro" \
--volume="/etc/passwd:/etc/passwd:ro" \
--volume="/etc/shadow:/etc/shadow:ro" \
--volume="/etc/sudoers.d:/etc/sudoers.d:ro" \
--volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
-it REPO:TAG /bin/bash
you may ask, whats the point to use docker if so many things are the same? well, one reason I can think of is to overcome the package depency hell (https://en.wikipedia.org/wiki/Dependency_hell).
So this type of usage is more suitable for developer I think.
how to add the missing RANDR extension
First off, Xvfb doesn't read configuration from xorg.conf. Xvfb is a variant of the KDrive X servers and like all members of that family gets its configuration from the command line.
It is true that XRandR and Xinerama are mutually exclusive, but in the case of Xvfb there's no Xinerama in the first place. You can enable the XRandR extension by starting Xvfb using at least the following command line options
Xvfb +extension RANDR [further options]
"No X11 DISPLAY variable" - what does it mean?
you must enable X11 forwarding in you PuTTy
to do so open PuTTy, go to Connection => SSH => Tunnels and check mark the Enable X11 forwarding
Also sudo to server and export the below variable here IP is your local machine's IP
export DISPLAY=10.75.75.75:0.0
How can I specify a display?
The way that X works is the same as the way any network program works. You have a server of some description (in this case, the X display server) which runs on a specific machine, and you have X clients (like firefox) that try to connect to that server to get their information displayed.
Often (on "home" machines), the client and server run on the same box and there's only one server, but X is powerful enough that this doesn't need to happen. It was built with the server/client separation built in from the start.
This allows you to do such wondrous things such as log on to your box (in text mode) halfway around the planet, tell it that the display server is the box you're currently on and, voila, the windows suddenly start appearing locally.
In order for a client to interact with a user, it needs to know how to find the server. There are a number of ways to do this. Many clients allow the -display
or --display
option to specify it:
xeyes -display paxbox1.paxco.com:0.0
Many will use the DISPLAY
environment variable if a display isn't specifically given. You can set this variable like any other:
DISPLAY=paxbox1.paxco.com:0.0; export DISPLAY # in .profile
export DISPLAY=paxbox1.paxco.com:0.0 # in your shell
DISPLAY=paxbox1.paxco.com:0.0 firefox & # for that command (shell permitting)
The first part of the DISPLAY
variable is just the address of the display server machine. It follows the same rule as any other IP address; it can be a resolvable DNS name (including localhost
) or a specific IP address (such as 192.168.10.55).
The second part is X-specific. It gives the X "display" (X server) number and screen number to use. The first (display number) generally refers to a group of devices containing one or more screens but with a single keyboard and mouse (i.e., one input stream). The screen number generally gives the specific screen within that group.
An example would be:
+----------------------------------------+
|paxbox1.paxco.com| |
+-----------------+ |
| |
| +----------+----+ +----------+----+ |
| |Display :0| | |Display :1| | |
| +----------+ | +----------+ | |
| | | | | |
| | +-----------+ | | | |
| | |Screen :0.0| | | | |
| | +-----------+ | | | |
| | +-----------+ | | | |
| | |Screen :0.1| | | | |
| | +-----------+ | | | |
| | +-----------+ | | +-----------+ | |
| | |Screen :0.2| | | |Screen :1.0| | |
| | +-----------+ | | +-----------+ | |
| | +-----------+ | | +-----------+ | |
| | |Screen :0.3| | | |Screen :1.1| | |
| | +-----------+ | | +-----------+ | |
| | +-----------+ | | +-----------+ | |
| | | Keyboard | | | | Keyboard | | |
| | +-----------+ | | +-----------+ | |
| | +-----------+ | | +-----------+ | |
| | | Mouse | | | | Mouse | | |
| | +-----------+ | | +-----------+ | |
| +---------------+ +---------------+ |
| |
+----------------------------------------+
Here you have a single machine (paxbox1.paxco.com
) with two display servers. The first has four screens and the second has two. The possibilities are then:
DISPLAY=paxbox1.paxco.com:0.0
DISPLAY=paxbox1.paxco.com:0.1
DISPLAY=paxbox1.paxco.com:0.2
DISPLAY=paxbox1.paxco.com:0.3
DISPLAY=paxbox1.paxco.com:1.0
DISPLAY=paxbox1.paxco.com:1.1
depending on where you want your actual windows to appear and which input devices you want to use.
How to check if X server is running?
The bash script solution:
if ! xset q &>/dev/null; then
echo "No X server at \$DISPLAY [$DISPLAY]" >&2
exit 1
fi
Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:
#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
echo "X server running"
exit 1
fi
You can change /usr/lib/Xorg for only Xorg or the proper command on your system.
Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms
Don't know if you resolved this problem, but I have just resolved the same issue from the other side.
It appears Selenium and Firefox have difficulty talking to each other - I suspect Firefox 'evolve' changes over a number of releases, so backward and forward compatibility are not always guaranteed, and incompatibility always seems to generate the same error.
My problem started when I moved from FF 15 to FF 16. Running on Ubuntu, this happens auto magically along with other upgrades but I believe this was the critical change.
The problem was resolved by moving from Selenium 2.24.1 to Selenium 2.25.0
As the selenium change is just download the jar file and run it instead of the old one,it's worth trying this as a quick and easy troubleshooter - if it doesn't help, just switch back. In your case, I'm not sure which version of Selenium to try, but I think 2.24 should work with FF 10.
Another issue I have found in the past is that Firefox would not run as root on Ubuntu. This happens if Selenium is running as a service, or possibly if it is fired up from a bash script or cron job. This may explain why it runs for you but not for Jenkins.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
How do I perform a GROUP BY on an aliased column in MS-SQL Server?
This is what I do.
SELECT FullName
FROM
(
SELECT LastName + ', ' + FirstName AS FullName
FROM customers
) as sub
GROUP BY FullName
This technique applies in a straightforward way to your "edit" scenario:
SELECT FullName
FROM
(
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS FullName
FROM customers
) as sub
GROUP BY FullName
How do I retrieve query parameters in Spring Boot?
Use @RequestParam
@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){
Item i = itemDao.findOne(itemid);
String itemName = i.getItemName();
String price = i.getPrice();
return i;
}
SQL update trigger only when column is modified
You want to do the following:
ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
ON [dbo].[SCHEDULE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF (UPDATE(QtyToRepair))
BEGIN
UPDATE SCHEDULE SET modified = GETDATE()
, ModifiedUser = SUSER_NAME()
, ModifiedHost = HOST_NAME()
FROM SCHEDULE S
INNER JOIN Inserted I ON S.OrderNo = I.OrderNo AND S.PartNumber = I.PartNumber
WHERE S.QtyToRepair <> I.QtyToRepair
END
END
Please note that this trigger will fire each time you update the column no matter if the value is the same or not.
how to prevent adding duplicate keys to a javascript array
Generally speaking, this is better accomplished with an object instead since JavaScript doesn't really have associative arrays:
var foo = { bar: 0 };
Then use in
to check for a key:
if ( !( 'bar' in foo ) ) {
foo['bar'] = 42;
}
As was rightly pointed out in the comments below, this method is useful only when your keys will be strings, or items that can be represented as strings (such as numbers).
What is an MDF file?
SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.
As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.
More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.
android: stretch image in imageview to fit screen
Give in the xml file of your layout android:scaleType="fitXY"
P.S : this applies to when the image is set with android:src="..."
rather than android:background="..."
as backgrounds are set by default to stretch and fit to the View.
How to convert a timezone aware string to datetime in Python without dateutil?
I'm new to Python, but found a way to convert
2017-05-27T07:20:18.000-04:00
to
2017-05-27T07:20:18
without downloading new utilities.
from datetime import datetime, timedelta
time_zone1 = int("2017-05-27T07:20:18.000-04:00"[-6:][:3])
>>returns -04
item_date = datetime.strptime("2017-05-27T07:20:18.000-04:00".replace(".000", "")[:-6], "%Y-%m-%dT%H:%M:%S") + timedelta(hours=-time_zone1)
I'm sure there are better ways to do this without slicing up the string so much, but this got the job done.
Make a div fill the height of the remaining screen space
It could be done purely by CSS
using vh
:
#page {
display:block;
width:100%;
height:95vh !important;
overflow:hidden;
}
#tdcontent {
float:left;
width:100%;
display:block;
}
#content {
float:left;
width:100%;
height:100%;
display:block;
overflow:scroll;
}
and the HTML
<div id="page">
<div id="tdcontent"></div>
<div id="content"></div>
</div>
I checked it, It works in all major browsers: Chrome
, IE
, and FireFox
CSS Always On Top
Ensure position
is on your element and set the z-index
to a value higher than the elements you want to cover.
element {
position: fixed;
z-index: 999;
}
div {
position: relative;
z-index: 99;
}
It will probably require some more work than that but it's a start since you didn't post any code.
What is “2's Complement”?
It is a clever means of encoding negative integers in such a way that approximately half of the combination of bits of a data type are reserved for negative integers, and the addition of most of the negative integers with their corresponding positive integers results in a carry overflow that leaves the result to be binary zero.
So, in 2's complement if one is 0x0001 then -1 is 0x1111, because that will result in a combined sum of 0x0000 (with an overflow of 1).
Angular 5 - Copy to clipboard
I think this is a much more cleaner solution when copying text:
copyToClipboard(item) {
document.addEventListener('copy', (e: ClipboardEvent) => {
e.clipboardData.setData('text/plain', (item));
e.preventDefault();
document.removeEventListener('copy', null);
});
document.execCommand('copy');
}
And then just call copyToClipboard on click event in html. (click)="copyToClipboard('texttocopy')"
C# how to change data in DataTable?
Try the SetField method:
table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);
This should get the job done and is a bit "cleaner" than using Rows[i][j].
C/C++ maximum stack size of program
Platform-dependent, toolchain-dependent, ulimit-dependent, parameter-dependent.... It is not at all specified, and there are many static and dynamic properties that can influence it.
Cannot add a project to a Tomcat server in Eclipse
You didn't create your project as "Dynamic Web Project", so Eclipse doesn't recognize it like a web project. Create a new "Dynamic Web Project" or go to Properties ? Projects Facets and check Dynamic Web Module.
Case Statement Equivalent in R
As of data.table v1.13.0 you can use the function fcase()
(fast-case) to do SQL-like CASE
operations (also similar to dplyr::case_when()
):
require(data.table)
dt <- data.table(name = c('cow','pig','eagle','pigeon','cow','eagle'))
dt[ , category := fcase(name %in% c('cow', 'pig'), 'mammal',
name %in% c('eagle', 'pigeon'), 'bird') ]
Why does modern Perl avoid UTF-8 by default?
You should enable the unicode strings feature, and this is the default if you use v5.14;
You should not really use unicode identifiers esp. for foreign code via utf8 as they are insecure in perl5, only cperl got that right. See e.g. http://perl11.org/blog/unicode-identifiers.html
Regarding utf8 for your filehandles/streams: You need decide by yourself the encoding of your external data. A library cannot know that, and since not even libc supports utf8, proper utf8 data is rare. There's more wtf8, the windows aberration of utf8 around.
BTW: Moose is not really "Modern Perl", they just hijacked the name. Moose is perfect Larry Wall-style postmodern perl mixed with Bjarne Stroustrup-style everything goes, with an eclectic aberration of proper perl6 syntax, e.g. using strings for variable names, horrible fields syntax, and a very immature naive implementation which is 10x slower than a proper implementation.
cperl and perl6 are the true modern perls, where form follows function, and the implementation is reduced and optimized.
Calling one method from another within same class in Python
To call the method, you need to qualify function with self.
. In addition to that, if you want to pass a filename, add a filename
parameter (or other name you want).
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
filename = srcpath[12:]
self.dropbox_fn(filename) # <----
def dropbox_fn(self, filename): # <-----
print('In dropbox_fn:', filename)
How to view .img files?
With *nix, usually, you don't need a software to view an .img file. You can use the loop device to mount it and then every file manager to navigate it. Here you can find how. Sometime you need to install some package to manage strange filesystem like squashfs.
How to stop event bubbling on checkbox click
As others have mentioned, try stopPropagation()
.
And there is a second handler to try: event.cancelBubble = true;
It's a IE specific handler, but it is supported in at least FF. Don't really know much about it, as I haven't used it myself, but it might be worth a shot, if all else fails.
difference between throw and throw new Exception()
throw
is for rethrowing a caught exception. This can be useful if you want to do something with the exception before passing it up the call chain.
Using throw
without any arguments preserves the call stack for debugging purposes.
What is the `zero` value for time.Time in Go?
You should use the Time.IsZero() function instead:
func (Time) IsZero
func (t Time) IsZero() bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
Import and insert sql.gz file into database with putty
Login into your server using a shell program like putty.
Type in the following command on the command line
zcat DB_File_Name.sql.gz | mysql -u username -p Target_DB_Name
where
DB_File_Name.sql.gz
= full path of the sql.gz file to be imported
username
= your mysql username
Target_DB_Name
= database name where you want to import the database
When you hit enter in the command line, it will prompt for password. Enter your MySQL password.
You are done!
Move an array element from one array position to another
It is stated in many places (adding custom functions into Array.prototype) playing with the Array prototype could be a bad idea, anyway I combined the best from various posts, I came with this, using modern Javascript:
Object.defineProperty(Array.prototype, 'immutableMove', {
enumerable: false,
value: function (old_index, new_index) {
var copy = Object.assign([], this)
if (new_index >= copy.length) {
var k = new_index - copy.length;
while ((k--) + 1) { copy.push(undefined); }
}
copy.splice(new_index, 0, copy.splice(old_index, 1)[0]);
return copy
}
});
//how to use it
myArray=[0, 1, 2, 3, 4];
myArray=myArray.immutableMove(2, 4);
console.log(myArray);
//result: 0, 1, 3, 4, 2
Hope can be useful to anyone
How to use std::sort to sort an array in C++
It is as simple as that ... C++ is providing you a function in STL (Standard Template Library) called sort
which runs 20% to 50% faster than the hand-coded quick-sort.
Here is the sample code for it's usage:
std::sort(arr, arr + size);
json call with C#
In your code you don't get the HttpResponse, so you won't see what the server side sends you back.
you need to get the Response similar to the way you get (make) the Request. So
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"method\": \"send\", " +
" \"params\": [ " +
" \"IPutAGuidHere\", " +
" \"[email protected]\", " +
" \"MyTenDigitNumberWasHere\", " +
" \"" + message + "\" " +
" ] " +
"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.
How to mock private method for testing using PowerMock?
A generic solution that will work with any testing framework (if your class is non-final
) is to manually create your own mock.
- Change your private method to protected.
- In your test class extend the class
- override the previously-private method to return whatever constant you want
This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.
To mock a private method directly, you'll need to use PowerMock as shown in the other answer.
Read response headers from API response - Angular 5 + TypeScript
You can get headers using below code
let main_headers = {}
this.http.post(url,
{email: this.username, password: this.password},
{'headers' : new HttpHeaders ({'Content-Type' : 'application/json'}), 'responseType': 'text', observe:'response'})
.subscribe(response => {
const keys = response.headers.keys();
let headers = keys.map(key => {
`${key}: ${response.headers.get(key)}`
main_headers[key] = response.headers.get(key)
}
);
});
later we can get the required header form the json object.
header_list['X-Token']
How is the default submit button on an HTML form determined?
If you submit the form via Javascript (i.e. formElement.submit()
or anything equivalent), then none of the submit buttons are considered successful and none of their values are included in the submitted data. (Note that if you submit the form by using submitElement.click()
then the submit that you had a reference to is considered active; this doesn't really fall under the remit of your question since here the submit button is unambiguous but I thought I'd include it for people who read the first part and wonder how to make a submit button successful via JS form submission. Of course, the form's onsubmit handlers will still fire this way whereas they wouldn't via form.submit()
so that's another kettle of fish...)
If the form is submitted by hitting Enter while in a non-textarea field, then it's actually down to the user agent to decide what it wants here. The specs don't say anything about submitting a form using the enter key while in a text entry field (if you tab to a button and activate it using space or whatever, then there's no problem as that specific submit button is unambiguously used). All it says is that a form must be submitted when a submit button is activated, it's not even a requirement that hitting enter in e.g. a text input will submit the form.
I believe that Internet Explorer chooses the submit button that appears first in the source; I have a feeling that Firefox and Opera choose the button with the lowest tabindex, falling back to the first defined if nothing else is defined. There's also some complications regarding whether the submits have a non-default value attribute IIRC.
The point to take away is that there is no defined standard for what happens here and it's entirely at the whim of the browser - so as far as possible in whatever you're doing, try to avoid relying on any particular behaviour. If you really must know, you can probably find out the behaviour of the various browser versions but when I investigated this a while back there were some quite convoluted conditions (which of course are subject to change with new browser versions) and I'd advise you to avoid it if possible!
JavaScript Promises - reject vs. throw
An example to try out. Just change isVersionThrow to false to use reject instead of throw.
_x000D_
_x000D_
const isVersionThrow = true_x000D_
_x000D_
class TestClass {_x000D_
async testFunction () {_x000D_
if (isVersionThrow) {_x000D_
console.log('Throw version')_x000D_
throw new Error('Fail!')_x000D_
} else {_x000D_
console.log('Reject version')_x000D_
return new Promise((resolve, reject) => {_x000D_
reject(new Error('Fail!'))_x000D_
})_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
const test = async () => {_x000D_
const test = new TestClass()_x000D_
try {_x000D_
var response = await test.testFunction()_x000D_
return response _x000D_
} catch (error) {_x000D_
console.log('ERROR RETURNED')_x000D_
throw error _x000D_
} _x000D_
}_x000D_
_x000D_
test()_x000D_
.then(result => {_x000D_
console.log('result: ' + result)_x000D_
})_x000D_
.catch(error => {_x000D_
console.log('error: ' + error)_x000D_
})
_x000D_
_x000D_
_x000D_
Automatically add all files in a folder to a target using CMake?
As of CMake 3.1+ the developers strongly discourage users from using file(GLOB
or file(GLOB_RECURSE
to collect lists of source files.
Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.
See the documentation here.
There are two goods answers ([1], [2]) here on SO detailing the reasons to manually list source files.
It is possible. E.g. with file(GLOB
:
cmake_minimum_required(VERSION 2.8)
file(GLOB helloworld_SRC
"*.h"
"*.cpp"
)
add_executable(helloworld ${helloworld_SRC})
Note that this requires manual re-running of cmake
if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.
As of CMake 3.12, you can pass the CONFIGURE_DEPENDS
flag to file(GLOB
to automatically check and reset the file lists any time the build is invoked. You would write:
cmake_minimum_required(VERSION 3.12)
file(GLOB helloworld_SRC CONFIGURE_DEPENDS "*.h" "*.cpp")
This at least lets you avoid manually re-running CMake every time a file is added.
Get filename from file pointer
You can get the path via fp.name
. Example:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basename
if you want only the file name:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
How do I call Objective-C code from Swift?
See Apple's guide to Using Swift with Cocoa and Objective-C. This guide covers how to use Objective-C and C code from Swift and vice versa and has recommendations for how to convert a project or mix and match Objective-C/C and Swift parts in an existing project.
The compiler automatically generates Swift syntax for calling C functions and Objective-C methods. As seen in the documentation, this Objective-C:
UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
turns into this Swift code:
let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)
Xcode also does this translation on the fly — you can use Open Quickly while editing a Swift file and type an Objective-C class name, and it'll take you to a Swift-ified version of the class header. (You can also get this by cmd-clicking on an API symbol in a Swift file.) And all the API reference documentation in the iOS 8 and OS X v10.10 (Yosemite) developer libraries is visible in both Objective-C and Swift forms (e.g. UIView
).
Using TortoiseSVN via the command line
By default TortoiseSVN always has a GUI (Graphical User Interface) associated with it. But on the installer (of version 1.7 and later) you can select the "command line client tools" option so you can call svn commands (like svn commit and svn update) from the command line.
Here's a screenshot of the "command line client tools" option in the installer, you need to make sure you select it:
Jenkins, specifying JAVA_HOME
openjdk-6
is a Java runtime, not a JDK (development kit which contains javac
, for example). Install openjdk-6-jdk
.
Maven also needs the JDK.
[EDIT] When the JDK is installed, use /usr/lib/jvm/java-6-openjdk
for JAVA_HOME
(i.e. without the jre
part).
Convert Text to Date?
Perhaps:
Sub dateCNV()
Dim N As Long, r As Range, s As String
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
Set r = Cells(i, "A")
s = r.Text
r.Clear
r.Value = DateSerial(Left(s, 4), Mid(s, 6, 2), Right(s, 2))
Next i
End Sub
This assumes that column A contains text values like 2013-12-25 with no header cell.
How to change the height of a div dynamically based on another div using css?
The simplest way to get equal height columns, without the ugly side effects that come along with absolute positioning, is to use the display: table
properties:
.div1 {
width:300px;
height: auto;
background-color: grey;
border:1px solid;
display: table;
}
.div2, .div3 {
display: table-cell;
}
.div2 {
width:150px;
height:auto;
background-color: #F4A460;
}
.div3 {
width:150px;
height:auto;
background-color: #FFFFE0;
}
http://jsfiddle.net/E4Zgj/21/
Now, if your goal is to have .div2
so that it is only as tall as it needs to be to contain its content while .div3
is at least as tall as .div2
but still able to expand if its content makes it taller than .div2
, then you need to use flexbox. Flexbox support isn't quite there yet (IE10, Opera, Chrome. Firefox follows an old spec, but is following the current spec soon).
.div1 {
width:300px;
height: auto;
background-color: grey;
border:1px solid;
display: flex;
align-items: flex-start;
}
.div2 {
width:150px;
background-color: #F4A460;
}
.div3 {
width:150px;
background-color: #FFFFE0;
align-self: stretch;
}
http://jsfiddle.net/E4Zgj/22/
Why did I get the compile error "Use of unassigned local variable"?
The following categories of variables are classified as initially unassigned:
- Instance variables of initially unassigned struct variables.
- Output parameters, including the this variable of struct instance constructors.
- Local variables , except those declared in a catch clause or a foreach statement.
The following categories of variables are classified as initially assigned:
- Static variables.
- Instance variables of class instances.
- Instance variables of initially assigned struct variables.
- Array elements.
- Value parameters.
- Reference parameters.
- Variables declared in a catch clause or a foreach statement.
How do I remove a single breakpoint with GDB?
You can list breakpoints with:
info break
This will list all breakpoints. Then a breakpoint can be deleted by its corresponding number:
del 3
For example:
(gdb) info b
Num Type Disp Enb Address What
3 breakpoint keep y 0x004018c3 in timeCorrect at my3.c:215
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
(gdb) del 3
(gdb) info b
Num Type Disp Enb Address What
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
How to change Elasticsearch max memory size
If you installed ES using the RPM/DEB packages as provided (as you seem to have), you can adjust this by editing the init script (/etc/init.d/elasticsearch on RHEL/CentOS
). If you have a look in the file you'll see a block with the following:
export ES_HEAP_SIZE
export ES_HEAP_NEWSIZE
export ES_DIRECT_SIZE
export ES_JAVA_OPTS
export JAVA_HOME
To adjust the size, simply change the ES_HEAP_SIZE
line to the following:
export ES_HEAP_SIZE=xM/xG
(where x is the number of MB/GB of RAM that you would like to allocate)
Example:
export ES_HEAP_SIZE=1G
Would allocate 1GB.
Once you have edited the script, save and exit, then restart the service. You can check if it has been correctly set by running the following:
ps aux | grep elasticsearch
And checking for the -Xms and -Xmx flags in the java process that returns:
/usr/bin/java -Xms1G -Xmx1G
Hope this helps :)
Git conflict markers
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
CLEAR SCREEN - Oracle SQL Developer shortcut?
Ctrl+Shift+D, but you have to put focus on the script output panel first...which you can do via the KB.
Run script.
Alt+PgDn - puts you in Script Output panel.
Ctrl+Shift+D - clears panel.
Alt+PgUp - puts you back in editor panel.
numpy matrix vector multiplication
Simplest solution
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Other Solutions
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
Rarer options for edge cases
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
Python Pandas replicate rows in dataframe
You can put df_try
inside a list and then do what you have in mind:
>>> df.append([df_try]*5,ignore_index=True)
Store Dept Date Weekly_Sales IsHoliday
0 1 1 2010-02-05 24924.50 False
1 1 1 2010-02-12 46039.49 True
2 1 1 2010-02-19 41595.55 False
3 1 1 2010-02-26 19403.54 False
4 1 1 2010-03-05 21827.90 False
5 1 1 2010-03-12 21043.39 False
6 1 1 2010-03-19 22136.64 False
7 1 1 2010-03-26 26229.21 False
8 1 1 2010-04-02 57258.43 False
9 1 1 2010-02-12 46039.49 True
10 1 1 2010-02-12 46039.49 True
11 1 1 2010-02-12 46039.49 True
12 1 1 2010-02-12 46039.49 True
13 1 1 2010-02-12 46039.49 True
There was no endpoint listening at (url) that could accept the message
I changed my website and app bindings to a new port and it worked for me. This error might occur because the port the website uses is not available. Hence sometimes the problem is solved by simply restarting the machine
-Edit-
Alternative (and easier) solution:reference
- Get PID of process which is using the port
CMD command-
netstat -aon | findstr 0.0:80
- Use the PID to get process name -
tasklist /FI "PID eq "
- Open task manager, find this process and stop it.
(Note- Make sure you do not stop Net.tcp services)
How to remove item from a python list in a loop?
hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:
x[:] = [value for value in x if len(value)==2]
However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n).
glglgl's answer suffers from O(n²) complexity, because list.remove
is O(n).
Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the del
keywork to remove by index:
to_remove = [i for i, val in enumerate(x) if len(val)==2]
for index in reversed(to_remove): # start at the end to avoid recomputing offsets
del x[index]
Now del x[i]
is also O(n) because you need to copy all elements after index i
(a list is a vector), so you'll need to test this against your data. Still this should be faster than using remove
because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases.
[edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of @Sven Marnach. It uses itertools.compress
which was introduced in python 2.7:
from itertools import compress
selectors = (len(s) == 2 for s in x)
for i, s in enumerate(compress(x, selectors)): # enumerate elements of length 2
x[i] = s # move found element to beginning of the list, without resizing
del x[i+1:] # trim the end of the list
How to know a Pod's own IP address from inside a container in the Pod?
Some clarifications (not really an answer)
In kubernetes, every pod gets assigned an IP address, and every container in the pod gets assigned that same IP address. Thus, as Alex Robinson stated in his answer, you can just use hostname -i
inside your container to get the pod IP address.
I tested with a pod running two dumb containers, and indeed hostname -i
was outputting the same IP address inside both containers. Furthermore, that IP was equivalent to the one obtained using kubectl describe pod
from outside, which validates the whole thing IMO.
However, PiersyP's answer seems more clean to me.
Sources
From kubernetes docs:
The applications in a pod all use the same network namespace (same IP and port space), and can thus “find” each other and communicate using localhost. Because of this, applications in a pod must coordinate their usage of ports. Each pod has an IP address in a flat shared networking space that has full communication with other physical computers and pods across the network.
Another piece from kubernetes docs:
Until now this document has talked about containers. In reality, Kubernetes applies IP addresses at the Pod scope - containers within a Pod share their network namespaces - including their IP address. This means that containers within a Pod can all reach each other’s ports on localhost.
Strip / trim all strings of a dataframe
You can use the apply
function of the Series
object:
>>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
>>> df[0][0]
' a '
>>> df[0] = df[0].apply(lambda x: x.strip())
>>> df[0][0]
'a'
Note the usage of strip
and not the regex
which is much faster
Another option - use the apply
function of the DataFrame object:
>>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
>>> df.apply(lambda x: x.apply(lambda y: y.strip() if type(y) == type('') else y), axis=0)
0 1
0 a 10
1 c 5
How to use GROUP_CONCAT in a CONCAT in MySQL
IF OBJECT_ID('master..test') is not null Drop table test
CREATE TABLE test (ID INTEGER, NAME VARCHAR (50), VALUE INTEGER );
INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);
select distinct NAME , LIST = Replace(Replace(Stuff((select ',', +Value from test where name = _a.name for xml path('')), 1,1,''),'<Value>', ''),'</Value>','') from test _a order by 1 desc
My table name is test , and for concatination I use the For XML Path('') syntax.
The stuff function inserts a string into another string. It deletes a specified length of characters
in the first string at the start position and then inserts the second string into the first string
at the start position.
STUFF functions looks like this : STUFF (character_expression , start , length ,character_expression )
character_expression
Is an expression of character data. character_expression can be a constant, variable, or column of either
character or binary data.
start
Is an integer value that specifies the location to start deletion and insertion. If start or length is negative,
a null string is returned. If start is longer than the first character_expression, a null string is returned.
start can be of type bigint.
length
Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression,
deletion occurs up to the last character in the last character_expression. length can be of type bigint.
When to use the !important property in CSS
Using !important
is generally not a good idea in the code itself, but it can be useful in various overrides.
I use Firefox and a dotjs plugin which essentially can run your own custom JS or CSS code on specified websites automatically.
Here's the code for it I use on Twitter that makes the tweet input field always stay on my screen no matter how far I scroll, and for the hyperlinks to always remain the same color.
a, a * {
color: rgb(34, 136, 85) !important;
}
.count-inner {
color: white !important;
}
.timeline-tweet-box {
z-index: 99 !important;
position: fixed !important;
left: 5% !important;
}
Since, thankfully, Twitter developers don't use !important
properties much, I can use it to guarantee that the specified styles will be definitely overridden, because without !important
they were not overridden sometimes. It really came in handy for me there.
How to display a date as iso 8601 format with PHP
Here is the good function for pre PHP 5:
I added GMT difference at the end, it's not hardcoded.
function iso8601($time=false) {
if ($time === false) $time = time();
$date = date('Y-m-d\TH:i:sO', $time);
return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
}
Reading file input from a multipart/form-data POST
Another way would be to use .Net parser for HttpRequest. To do that you need to use a bit of reflection and simple class for WorkerRequest.
First create class that derives from HttpWorkerRequest (for simplicity you can use SimpleWorkerRequest):
public class MyWorkerRequest : SimpleWorkerRequest
{
private readonly string _size;
private readonly Stream _data;
private string _contentType;
public MyWorkerRequest(Stream data, string size, string contentType)
: base("/app", @"c:\", "aa", "", null)
{
_size = size ?? data.Length.ToString(CultureInfo.InvariantCulture);
_data = data;
_contentType = contentType;
}
public override string GetKnownRequestHeader(int index)
{
switch (index)
{
case (int)HttpRequestHeader.ContentLength:
return _size;
case (int)HttpRequestHeader.ContentType:
return _contentType;
}
return base.GetKnownRequestHeader(index);
}
public override int ReadEntityBody(byte[] buffer, int offset, int size)
{
return _data.Read(buffer, offset, size);
}
public override int ReadEntityBody(byte[] buffer, int size)
{
return ReadEntityBody(buffer, 0, size);
}
}
Then wherever you have you message stream create and instance of this class. I'm doing it like that in WCF Service:
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
public string Upload(Stream data)
{
HttpWorkerRequest workerRequest =
new MyWorkerRequest(data,
WebOperationContext.Current.IncomingRequest.ContentLength.
ToString(CultureInfo.InvariantCulture),
WebOperationContext.Current.IncomingRequest.ContentType
);
And then create HttpRequest using activator and non public constructor
var r = (HttpRequest)Activator.CreateInstance(
typeof(HttpRequest),
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new object[]
{
workerRequest,
new HttpContext(workerRequest)
},
null);
var runtimeField = typeof (HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
if (runtimeField == null)
{
return;
}
var runtime = (HttpRuntime) runtimeField.GetValue(null);
if (runtime == null)
{
return;
}
var codeGenDirField = typeof(HttpRuntime).GetField("_codegenDir", BindingFlags.Instance | BindingFlags.NonPublic);
if (codeGenDirField == null)
{
return;
}
codeGenDirField.SetValue(runtime, @"C:\MultipartTemp");
After that in r.Files
you will have files from your stream.
How to fix System.NullReferenceException: Object reference not set to an instance of an object
If the problem is 100% here
EffectSelectorForm effectSelectorForm = new EffectSelectorForm(Effects);
There's only one possible explanation: property/variable "Effects" is not initialized properly... Debug your code to see what you pass to your objects.
EDIT after several hours
There were some problems:
MEF attribute [Import] didn't work as expected, so we replaced it for the time being with a manually populated List<>. While the collection was null, it was causing exceptions later in the code, when the method tried to get the type of the selected item and there was none.
several event handlers weren't wired up to control events
Some problems are still present, but I believe OP's original problem has been fixed. Other problems are not related to this one.
How to see if a directory exists or not in Perl?
Use -d
(full list of file tests)
if (-d "cgi-bin") {
# directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
# cgi-bin exists but is not a directory
}
else {
# nothing called cgi-bin exists
}
As a note, -e
doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f
.
How do you make an anchor link non-clickable or disabled?
Bootstrap provide us with .disabled
class. Please use it.
But .disabled
class only works when the 'a' tag already has class 'btn'. It doesn' t work on any old 'a' tag. The btn
class may not be appropriate in some context as it has style connotations. Under the covers, the .disabled
class sets pointer-events
to none
, so you can make CSS to do the same thing as Saroj Aryal and Vitrilo have sugested. (Thank you, Les Nightingill for this advice).
Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android
I ran into this problem with my new Nexus 4 and an APK built with Adobe AIR. I already had android:installLocation="preferExternal" in my manifest. I noticed I was also calling adb install
with the -s
option (Install package on the shared mass storage such as sdcard.) which seemed like overkill.
Removing the -s
flag from adb install
fixed the issue for me.
Android Camera : data intent returns null
Simple working camera app avoiding the null intent problem
- all changed code included in this reply; close to android tutorial
I've been spending plenty of time on this issue, so I decided to create an account and share my outcomes with you.
The official android tutorial "Taking Photos Simply" turned out to not quite hold what it promised.
The code provided there did not work on my device: a Samsung Galaxy S4 Mini GT-I9195 running android version 4.4.2 / KitKat / API Level 19.
I figured out that the main problem was the following line in the method invoked when capturing the photo (dispatchTakePictureIntent
in the tutorial):
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
It resulted in the intent subsequently catched by onActivityResult
being null.
To solve this problem, I pulled much inspiration out of earlier replies here and some helpful posts on github (mostly this one by deepwinter - big thanks to him; you might want to check out his reply on a closely related post as well).
Following these pleasant pieces of advice, I chose the strategy of deleting the mentioned putExtra
line and doing the corresponding thing of getting back the taken picture from the camera within the onActivityResult() method instead.
The decisive lines of code to get back the bitmap associated with the picture are:
Uri uri = intent.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
I created an exemplary app which just has the ability to take a picture, save it on the SD card and display it.
I think this might be helpful to people in the same situation as me when I stumbled on this issue, since the current help suggestions mostly refer to rather extensive github posts which do the thing in question but aren't too easy to oversee for newbies like me.
With respect to the file system Android Studio creates per default when creating a new project, I just had to change three files for my purpose:
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.simpleworkingcameraapp.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="takePicAndDisplayIt"
android:text="Take a pic and display it." />
<ImageView
android:id="@+id/image1"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
MainActivity.java :
package com.example.android.simpleworkingcameraapp;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private ImageView image;
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image1);
}
// copied from the android development pages; just added a Toast to show the storage location
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_LONG).show();
return image;
}
public void takePicAndDisplayIt(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
File file = null;
try {
file = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
}
}
@Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
if (requestCode == REQUEST_TAKE_PHOTO && resultcode == RESULT_OK) {
Uri uri = intent.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
}
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.simpleworkingcameraapp">
<!--only added paragraph-->
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- only crucial line to add; for me it still worked without the other lines in this paragraph -->
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Note that the solution I found for the problem also led to a simplification of the android manifest file: the changes suggested by the android tutorial in terms of adding a provider are no longer needed since I am not making use of any in my java code. Hence, only few standard lines -mostly regarding permissions- had to be added to the manifest file.
It might additionally be valuable to point out that Android Studio's autoimport may not be capable of handling java.text.SimpleDateFormat
and java.util.Date
. I had to import both of them manually.
Get the item doubleclick event of listview
The sender is of type ListView not ListViewItem.
private void listViewTriggers_MouseDoubleClick(object sender, MouseEventArgs e)
{
ListView triggerView = sender as ListView;
if (triggerView != null)
{
btnEditTrigger_Click(null, null);
}
}
Windows Bat file optional argument parsing
The selected answer works, but it could use some improvement.
- The options should probably be initialized to default values.
- It would be nice to preserve %0 as well as the required args %1 and %2.
- It becomes a pain to have an IF block for every option, especially as the number of options grows.
- It would be nice to have a simple and concise way to quickly define all options and defaults in one place.
- It would be good to support stand-alone options that serve as flags (no value following the option).
- We don't know if an arg is enclosed in quotes. Nor do we know if an arg value was passed using escaped characters. Better to access an arg using %~1 and enclose the assignment within quotes. Then the batch can rely on the absence of enclosing quotes, but special characters are still generally safe without escaping. (This is not bullet proof, but it handles most situations)
My solution relies on the creation of an OPTIONS variable that defines all of the options and their defaults. OPTIONS is also used to test whether a supplied option is valid. A tremendous amount of code is saved by simply storing the option values in variables named the same as the option. The amount of code is constant regardless of how many options are defined; only the OPTIONS definition has to change.
EDIT - Also, the :loop code must change if the number of mandatory positional arguments changes. For example, often times all arguments are named, in which case you want to parse arguments beginning at position 1 instead of 3. So within the :loop, all 3 become 1, and 4 becomes 2.
@echo off
setlocal enableDelayedExpansion
:: Define the option names along with default values, using a <space>
:: delimiter between options. I'm using some generic option names, but
:: normally each option would have a meaningful name.
::
:: Each option has the format -name:[default]
::
:: The option names are NOT case sensitive.
::
:: Options that have a default value expect the subsequent command line
:: argument to contain the value. If the option is not provided then the
:: option is set to the default. If the default contains spaces, contains
:: special characters, or starts with a colon, then it should be enclosed
:: within double quotes. The default can be undefined by specifying the
:: default as empty quotes "".
:: NOTE - defaults cannot contain * or ? with this solution.
::
:: Options that are specified without any default value are simply flags
:: that are either defined or undefined. All flags start out undefined by
:: default and become defined if the option is supplied.
::
:: The order of the definitions is not important.
::
set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"
:: Set the default option values
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
:: Validate and store the options, one at a time, using a loop.
:: Options start at arg 3 in this example. Each SHIFT is done starting at
:: the first option so required args are preserved.
::
if not "%~3"=="" (
set "test=!options:*%~3:=! "
if "!test!"=="!options! " (
rem No substitution was made so this is an invalid option.
rem Error handling goes here.
rem I will simply echo an error message.
echo Error: Invalid option %~3
) else if "!test:~0,1!"==" " (
rem Set the flag option using the option name.
rem The value doesn't matter, it just needs to be defined.
set "%~3=1"
) else (
rem Set the option value using the option as the name.
rem and the next arg as the value
set "%~3=%~4"
shift /3
)
shift /3
goto :loop
)
:: Now all supplied options are stored in variables whose names are the
:: option names. Missing options have the default value, or are undefined if
:: there is no default.
:: The required args are still available in %1 and %2 (and %0 is also preserved)
:: For this example I will simply echo all the option values,
:: assuming any variable starting with - is an option.
::
set -
:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!
There really isn't that much code. Most of the code above is comments. Here is the exact same code, without the comments.
@echo off
setlocal enableDelayedExpansion
set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
set "test=!options:*%~3:=! "
if "!test!"=="!options! " (
echo Error: Invalid option %~3
) else if "!test:~0,1!"==" " (
set "%~3=1"
) else (
set "%~3=%~4"
shift /3
)
shift /3
goto :loop
)
set -
:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!
This solution provides Unix style arguments within a Windows batch. This is not the norm for Windows - batch usually has the options preceding the required arguments and the options are prefixed with /
.
The techniques used in this solution are easily adapted for a Windows style of options.
- The parsing loop always looks for an option at
%1
, and it continues until arg 1 does not begin with /
- Note that SET assignments must be enclosed within quotes if the name begins with
/
.
SET /VAR=VALUE
fails
SET "/VAR=VALUE"
works. I am already doing this in my solution anyway.
- The standard Windows style precludes the possibility of the first required argument value starting with
/
. This limitation can be eliminated by employing an implicitly defined //
option that serves as a signal to exit the option parsing loop. Nothing would be stored for the //
"option".
Update 2015-12-28: Support for !
in option values
In the code above, each argument is expanded while delayed expansion is enabled, which means that !
are most likely stripped, or else something like !var!
is expanded. In addition, ^
can also be stripped if !
is present. The following small modification to the un-commented code removes the limitation such that !
and ^
are preserved in option values.
@echo off
setlocal enableDelayedExpansion
set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
set "test=!options:*%~3:=! "
if "!test!"=="!options! " (
echo Error: Invalid option %~3
) else if "!test:~0,1!"==" " (
set "%~3=1"
) else (
setlocal disableDelayedExpansion
set "val=%~4"
call :escapeVal
setlocal enableDelayedExpansion
for /f delims^=^ eol^= %%A in ("!val!") do endlocal&endlocal&set "%~3=%%A" !
shift /3
)
shift /3
goto :loop
)
goto :endArgs
:escapeVal
set "val=%val:^=^^%"
set "val=%val:!=^!%"
exit /b
:endArgs
set -
:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!
How to Parse JSON Array with Gson
you can get List value without using Type object.
EvalClassName[] evalClassName;
ArrayList<EvalClassName> list;
evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
list = new ArrayList<>(Arrays.asList(evalClassName));
I have tested it and it is working.
Do I cast the result of malloc?
No, you don't cast the result of malloc()
.
In general, you don't cast to or from void *
.
A typical reason given for not doing so is that failure to #include <stdlib.h>
could go unnoticed. This isn't an issue anymore for a long time now as C99 made implicit function declarations illegal, so if your compiler conforms to at least C99, you will get a diagnostic message.
But there's a much stronger reason not to introduce unnecessary pointer casts:
In C, a pointer cast is almost always an error. This is because of the following rule (§6.5 p7 in N1570, the latest draft for C11):
An object shall have its stored value accessed only by an lvalue expression that has one of
the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the
object,
— a type that is the signed or unsigned type corresponding to a qualified version of the
effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its
members (including, recursively, a member of a subaggregate or contained union), or
— a character type.
This is also known as the strict aliasing rule. So the following code is undefined behavior:
long x = 5;
double *p = (double *)&x;
double y = *p;
And, sometimes surprisingly, the following is as well:
struct foo { int x; };
struct bar { int x; int y; };
struct bar b = { 1, 2};
struct foo *p = (struct foo *)&b;
int z = p->x;
Sometimes, you do need to cast pointers, but given the strict aliasing rule, you have to be very careful with it. So, any occurrence of a pointer cast in your code is a place you have to double-check for its validity. Therefore, you never write an unnecessary pointer cast.
tl;dr
In a nutshell: Because in C, any occurrence of a pointer cast should raise a red flag for code requiring special attention, you should never write unnecessary pointer casts.
Side notes:
There are cases where you actually need a cast to void *
, e.g. if you want to print a pointer:
int x = 5;
printf("%p\n", (void *)&x);
The cast is necessary here, because printf()
is a variadic function, so implicit conversions don't work.
In C++, the situation is different. Casting pointer types is somewhat common (and correct) when dealing with objects of derived classes. Therefore, it makes sense that in C++, the conversion to and from void *
is not implicit. C++ has a whole set of different flavors of casting.
Disable a Maven plugin defined in a parent POM
The thread is old, but maybe someone is still interested.
The shortest form I found is further improvement on the example from ?lex and bmargulies. The execution tag will look like:
<execution>
<id>TheNameOfTheRelevantExecution</id>
<phase/>
</execution>
2 points I want to highlight:
- phase is set to nothing, which looks less hacky than 'none', though still a hack.
- id must be the same as execution you want to override. If you don't specify id for execution, Maven will do it implicitly (in a way not expected intuitively by you).
After posting found it is already in stackoverflow:
In a Maven multi-module project, how can I disable a plugin in one child?
Android setOnClickListener method - How does it work?
That what manual says about setOnClickListener
method is:
public void setOnClickListener (View.OnClickListener l)
Added in API level 1 Register a callback to be invoked when this view
is clicked. If this view is not clickable, it becomes clickable.
Parameters
l View.OnClickListener: The callback that will run
And normally you have to use it like this
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
Take a look at this lesson as well Building a Simple Calculator using Android Studio.
Creating a singleton in Python
- If one wants to have multiple number of instances of the same class, but only if the args or kwargs are different, one can use the third-party python package Handy Decorators (package
decorators
).
- Ex.
- If you have a class handling
serial
communication, and to create an instance you want to send the serial port as an argument, then with traditional approach won't work
- Using the above mentioned decorators, one can create multiple instances of the class if the args are different.
- For same args, the decorator will return the same instance which is already been created.
>>> from decorators import singleton
>>>
>>> @singleton
... class A:
... def __init__(self, *args, **kwargs):
... pass
...
>>>
>>> a = A(name='Siddhesh')
>>> b = A(name='Siddhesh', lname='Sathe')
>>> c = A(name='Siddhesh', lname='Sathe')
>>> a is b # has to be different
False
>>> b is c # has to be same
True
>>>
Server Error in '/' Application. ASP.NET
http://www.velocityreviews.com/forums/t123353-configuration-error.html
If you want to use inetpub/wwwroot/aspnet as your application, remove this
line :
Line 26:
and any other lines which define MachineToApplication beyond application
level
If you want to use d:\inetpub\wwwroot\aspnet\begin\chapter02\ as your
application,
create an IIS Application which points to
d:\inetpub\wwwroot\aspnet\begin\chapter02\
maybe you can refer link above.
For my application, my web.config store in d:\inetpub\wwwroot\aspnet\begin\chapter02\
and when i move the web.config to d:\inetpub\wwwroot\aspnet and the problem is solve.
Please check also does your application have two web.config file.
Check if process returns 0 with batch file
How to write a compound statement with
if?
You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.
if %ERRORLEVEL% == 0 (
echo ErrorLevel is zero
echo A second statement
) else if %ERRORLEVEL% == 1 (
echo ErrorLevel is one
echo A second statement
) else (
echo ErrorLevel is > 1
echo A second statement
)
Call to undefined function oci_connect()
I installed WAMPServer 2.5 (32-bit) and also encountered an oci_connect error. I also had Oracle 11g client (32-bit) installed. The common fix I read in other posts was to alter the php.ini file in your C:\wamp\bin\php\php5.5.12 directory, however this never worked for me. Maybe I misunderstood, but I found that if you alter the php.ini file in the C:\wamp\bin\apache\apache2.4.9 directory instead, you will get the results you want. The only thing I altered in the apache php.ini file was remove the semicolon to extension=php_oci8_11g.dll
in order to enable it. I then restarted all the services and it now works! I hope this works for you.
Return value from a VBScript function
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
SQL Server IF NOT EXISTS Usage?
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
Why do people hate SQL cursors so much?
The "overhead" with cursors is merely part of the API. Cursors are how parts of the RDBMS work under the hood. Often CREATE TABLE
and INSERT
have SELECT
statements, and the implementation is the obvious internal cursor implementation.
Using higher-level "set-based operators" bundles the cursor results into a single result set, meaning less API back-and-forth.
Cursors predate modern languages that provide first-class collections. Old C, COBOL, Fortran, etc., had to process rows one at a time because there was no notion of "collection" that could be used widely. Java, C#, Python, etc., have first-class list structures to contain result sets.
The Slow Issue
In some circles, the relational joins are a mystery, and folks will write nested cursors rather than a simple join. I've seen truly epic nested loop operations written out as lots and lots of cursors. Defeating an RDBMS optimization. And running really slowly.
Simple SQL rewrites to replace nested cursor loops with joins and a single, flat cursor loop can make programs run in 100th the time. [They thought I was the god of optimization. All I did was replace nested loops with joins. Still used cursors.]
This confusion often leads to an indictment of cursors. However, it isn't the cursor, it's the misuse of the cursor that's the problem.
The Size Issue
For really epic result sets (i.e., dumping a table to a file), cursors are essential. The set-based operations can't materialize really large result sets as a single collection in memory.
Alternatives
I try to use an ORM layer as much as possible. But that has two purposes. First, the cursors are managed by the ORM component. Second, the SQL is separated from the application into a configuration file. It's not that the cursors are bad. It's that coding all those opens, closes and fetches is not value-add programming.
PHP 5.4 Call-time pass-by-reference - Easy fix available?
PHP and references are somewhat unintuitive. If used appropriately references in the right places can provide large performance improvements or avoid very ugly workarounds and unusual code.
The following will produce an error:
function f(&$v){$v = true;}
f(&$v);
function f($v){$v = true;}
f(&$v);
None of these have to fail as they could follow the rules below but have no doubt been removed or disabled to prevent a lot of legacy confusion.
If they did work, both involve a redundant conversion to reference and the second also involves a redundant conversion back to a scoped contained variable.
The second one used to be possible allowing a reference to be passed to code that wasn't intended to work with references. This is extremely ugly for maintainability.
This will do nothing:
function f($v){$v = true;}
$r = &$v;
f($r);
More specifically, it turns the reference back into a normal variable as you have not asked for a reference.
This will work:
function f(&$v){$v = true;}
f($v);
This sees that you are passing a non-reference but want a reference so turns it into a reference.
What this means is that you can't pass a reference to a function where a reference is not explicitly asked for making it one of the few areas where PHP is strict on passing types or in this case more of a meta type.
If you need more dynamic behaviour this will work:
function f(&$v){$v = true;}
$v = array(false,false,false);
$r = &$v[1];
f($r);
Here it sees that you want a reference and already have a reference so leaves it alone. It may also chain the reference but I doubt this.
What is the difference between "INNER JOIN" and "OUTER JOIN"?
You use INNER JOIN
to return all rows from both tables where there is a match. i.e. In the resulting table all the rows and columns will have values.
In OUTER JOIN
the resulting table may have empty columns. Outer join may be either LEFT
or RIGHT
.
LEFT OUTER JOIN
returns all the rows from the first table, even if there are no matches in the second table.
RIGHT OUTER JOIN
returns all the rows from the second table, even if there are no matches in the first table.
What's the easy way to auto create non existing dir in ansible
copy module creates the directory if it's not there. In this case it created the resolved.conf.d directory
- name: put fallback_dns.conf in place
copy:
src: fallback_dns.conf
dest: /etc/systemd/resolved.conf.d/
mode: '0644'
owner: root
group: root
become: true
tags: testing
Move view with keyboard using Swift
@Boris's solution is VERY good but the view can sometimes be corrupted.
For the perfect alignment, use the below code
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)}
Functions:
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}}
And,
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y = 0
}
} }
How can I run MongoDB as a Windows service?
This is what worked for me:
sc.exe create MongoDB binPath= "d:\MongoDB\bin\mongod.exe --service --config=d:\MongoDB\bin\mongod.config" displayname= "MongoDB 2.6 Standard" start= "auto"
escaping the binPath was failing for me as described in the Mongo documentation
Failed:
sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe\" --service --config=\"C:\Program Files\MongoDB 2.6 Standard\mongod.cfg\"" DisplayName= "MongoDB 2.6 Standard" start= "auto"
How do I fix a Git detached head?
Realizing I had a detached head without knowing how I managed to get it (like three commits away), I also found out that trying to merge
, rebase
or cherry-pick
triggered hundreds of merge-conflicts, so I took a different approach:
(Assuming everything is committed (working tree is "clean"))
Save my commit messages: git log > /tmp/log
Save my working tree: mkdir /tmp/backup && cp -a all_my files_and_directories /tmp/backup
Revert to master
: git checkout master
Remove all the working files and directories: rm ...
Use the backup: cp -a /tmp/backup/. .
git add
and git commit
using messages from saved /tmp/log
, maybe repeating it with different sub-sets of files...
The disadvantage is that you loose your commit history if one file was changed multiple times since master
, but in the end I had a clean master
.
Most efficient way to find mode in numpy array
from collections import Counter
n = int(input())
data = sorted([int(i) for i in input().split()])
sorted(sorted(Counter(data).items()), key = lambda x: x[1], reverse = True)[0][0]
print(Mean)
The Counter(data)
counts the frequency and returns a defaultdict. sorted(Counter(data).items())
sorts using the keys, not the frequency. Finally, need to sorted the frequency using another sorted with key = lambda x: x[1]
. The reverse tells Python to sort the frequency from the largest to the smallest.
Multiple axis line chart in excel
An alternative is to normalize the data. Below are three sets of data with widely varying ranges. In the top chart you can see the variation in one series clearly, in another not so clearly, and the third not at all.
In the second range, I have adjusted the series names to include the data range, using this formula in cell C15 and copying it to D15:E15
=C2&" ("&MIN(C3:C9)&" to "&MAX(C3:C9)&")"
I have normalized the values in the data range using this formula in C15 and copying it to the entire range C16:E22
=100*(C3-MIN(C$3:C$9))/(MAX(C$3:C$9)-MIN(C$3:C$9))
In the second chart, you can see a pattern: all series have a low in January, rising to a high in March, and dropping to medium-low value in June or July.
You can modify the normalizing formula however you need:
=100*C3/MAX(C$3:C$9)
=C3/MAX(C$3:C$9)
=(C3-AVERAGE(C$3:C$9))/STDEV(C$3:C$9)
etc.
How to delete/remove nodes on Firebase
The problem is that you call remove
on the root of your Firebase:
ref = new Firebase("myfirebase.com")
ref.remove();
This will remove the entire Firebase through the API.
You'll typically want to remove specific child nodes under it though, which you do with:
ref.child(key).remove();
Copy multiple files in Python
If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*")
to get a list of all the filenames, loop over the list and use shutil.copy
to copy each file.
for filename in glob.glob(os.path.join(source_dir, '*.*')):
shutil.copy(filename, dest_dir)
How to restore the dump into your running mongodb
I have been through a lot of trouble so I came up with my own solution, I created this script, just set the path inside script and db name and run it, it will do the trick
#!/bin/bash
FILES= #absolute or relative path to dump directory
DB=`db` #db name
for file in $FILES
do
name=$(basename $file)
collection="${name%.*}"
echo `mongoimport --db "$DB" --file "$name" --collection "$collection"`
done
How to increment a number by 2 in a PHP For Loop
<?php
for ($n = 0; $n <= 7; $n++) {
echo '<p>'.($n + 1).'</p>';
echo '<p>'.($n * 2 + 1).'</p>';
}
?>
First paragraph:
1, 2, 3, 4, 5, 6, 7, 8
Second paragraph:
1, 3, 5, 7, 9, 11, 13, 15
How to filter a RecyclerView with a SearchView
I don't know why everyone is using 2 copies of the same list to solve this. This uses too much RAM...
Why not just hide the elements that are not found, and simply store their index in a Set
to be able to restore them later? That's much less RAM especially if your objects are quite large.
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.SampleViewHolders>{
private List<MyObject> myObjectsList; //holds the items of type MyObject
private Set<Integer> foundObjects; //holds the indices of the found items
public MyRecyclerViewAdapter(Context context, List<MyObject> myObjectsList)
{
this.myObjectsList = myObjectsList;
this.foundObjects = new HashSet<>();
//first, add all indices to the indices set
for(int i = 0; i < this.myObjectsList.size(); i++)
{
this.foundObjects.add(i);
}
}
@NonNull
@Override
public SampleViewHolders onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.my_layout_for_staggered_grid, null);
MyRecyclerViewAdapter.SampleViewHolders rcv = new MyRecyclerViewAdapter.SampleViewHolders(layoutView);
return rcv;
}
@Override
public void onBindViewHolder(@NonNull SampleViewHolders holder, int position)
{
//look for object in O(1) in the indices set
if(!foundObjects.contains(position))
{
//object not found => hide it.
holder.hideLayout();
return;
}
else
{
//object found => show it.
holder.showLayout();
}
//holder.imgImageView.setImageResource(...)
//holder.nameTextView.setText(...)
}
@Override
public int getItemCount() {
return myObjectsList.size();
}
public void findObject(String text)
{
//look for "text" in the objects list
for(int i = 0; i < myObjectsList.size(); i++)
{
//if it's empty text, we want all objects, so just add it to the set.
if(text.length() == 0)
{
foundObjects.add(i);
}
else
{
//otherwise check if it meets your search criteria and add it or remove it accordingly
if (myObjectsList.get(i).getName().toLowerCase().contains(text.toLowerCase()))
{
foundObjects.add(i);
}
else
{
foundObjects.remove(i);
}
}
}
notifyDataSetChanged();
}
public class SampleViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener
{
public ImageView imgImageView;
public TextView nameTextView;
private final CardView layout;
private final CardView.LayoutParams hiddenLayoutParams;
private final CardView.LayoutParams shownLayoutParams;
public SampleViewHolders(View itemView)
{
super(itemView);
itemView.setOnClickListener(this);
imgImageView = (ImageView) itemView.findViewById(R.id.some_image_view);
nameTextView = (TextView) itemView.findViewById(R.id.display_name_textview);
layout = itemView.findViewById(R.id.card_view); //card_view is the id of my androidx.cardview.widget.CardView in my xml layout
//prepare hidden layout params with height = 0, and visible layout params for later - see hideLayout() and showLayout()
hiddenLayoutParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
hiddenLayoutParams.height = 0;
shownLayoutParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public void onClick(View view)
{
//implement...
}
private void hideLayout() {
//hide the layout
layout.setLayoutParams(hiddenLayoutParams);
}
private void showLayout() {
//show the layout
layout.setLayoutParams(shownLayoutParams);
}
}
}
And I simply have an EditText
as my search box:
cardsSearchTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
myViewAdapter.findObject(editable.toString().toLowerCase());
}
});
Result:
Oracle: SQL query that returns rows with only numeric values
You can use the REGEXP_LIKE
function as:
SELECT X
FROM myTable
WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');
Sample run:
SQL> SELECT X FROM SO;
X
--------------------
12c
123
abc
a12
SQL> SELECT X FROM SO WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');
X
--------------------
123
SQL>
Android DialogFragment vs Dialog
Use DialogFragment over AlertDialog:
Since the introduction of API level 13:
the showDialog method from Activity is deprecated.
Invoking a dialog elsewhere in code is not advisable since you will have to manage the the dialog yourself (e.g. orientation change).
Difference DialogFragment - AlertDialog
Are they so much different? From Android reference regarding DialogFragment:
A DialogFragment is a fragment that displays a dialog window, floating on top of its
activity's window. This fragment contains a Dialog object, which it
displays as appropriate based on the fragment's state. Control of the
dialog (deciding when to show, hide, dismiss it) should be done
through the API here, not with direct calls on the dialog.
Other notes
- Fragments are a natural evolution in the Android framework due to the diversity of devices with different screen sizes.
- DialogFragments and Fragments are made available in the support library which makes the class usable in all current used versions of Android.
Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?
When you type "java -version", you see three version numbers - the java version (on mine, that's "1.6.0_07
"), the Java SE Runtime Environment version ("build 1.6.0_07-b06
"), and the HotSpot version (on mine, that's "build 10.0-b23, mixed mode"
). I suspect the "11.0" you are seeing is the HotSpot version.
Update: HotSpot is (or used to be, now they seem to use it to mean the whole VM) the just-in-time compiler that is built in to the Java Virtual Machine. God only knows why Sun gives it a separate version number.
Java: Clear the console
By combining all the given answers, this method should work on all environments:
public static void clearConsole() {
try {
if (System.getProperty("os.name").contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
else {
System.out.print("\033\143");
}
} catch (IOException | InterruptedException ex) {}
}
Finding the source code for built-in Python functions?
The iPython shell makes this easy: function?
will give you the documentation. function??
shows also the code. BUT this only works for pure python functions.
Then you can always download the source code for the (c)Python.
If you're interested in pythonic implementations of core functionality have a look at PyPy source.
What does file:///android_asset/www/index.html mean?
file:///
is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://
.
It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www
has a file called index.html
located in the assets
folder in the root of the project".
That is how assets are loaded at runtime, for example, a WebView
widget would know exactly where to load the embedded resource file by specifying the file:///
URI.
Consider the code example:
WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");
A very easy mistake to make here is this, some would infer it to as file:///android_assets
, notice the plural of assets in the URI and wonder why the embedded resource is not working!
Writing files in Node.js
You can of course make it a little more advanced. Non-blocking, writing bits and pieces, not writing the whole file at once:
var fs = require('fs');
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
stream.write("My first row\n");
stream.write("My second row\n");
stream.end();
});
How to trigger an event in input text after I stop typing/writing?
SOLUTION:
Here is the solution. Executing a function after the user has stopped typing for a specified amount of time:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Usage
$('input').keyup(function() {
delay(function(){
alert('Hi, func called');
}, 1000 );
});
header location not working in my php code
That is because you have an output:
?>
<?php
results in blank line output.
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
Combine all your PHP codes and make sure you don't have any spaces at the beginning of the file.
also after header('location: index.php');
add exit();
if you have any other scripts bellow.
Also move your redirect header after the last if
.
If there is content, then you can also redirect by injecting javascript:
<?php
echo "<script>window.location.href='target.php';</script>";
exit;
?>
jquery $(window).height() is returning the document height
I think your document must be having enough space in the window to display its contents. That means there is no need to scroll down to see any more part of the document. In that case, document height would be equal to the window height.
Using NotNull Annotation in method argument
I do this to create my own validation annotation and validator:
ValidCardType.java
(annotation to put on methods/fields)
@Constraint(validatedBy = {CardTypeValidator.class})
@Documented
@Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidCardType {
String message() default "Incorrect card type, should be among: \"MasterCard\" | \"Visa\"";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
And, the validator to trigger the check:
CardTypeValidator.java
:
public class CardTypeValidator implements ConstraintValidator<ValidCardType, String> {
private static final String[] ALL_CARD_TYPES = {"MasterCard", "Visa"};
@Override
public void initialize(ValidCardType status) {
}
public boolean isValid(String value, ConstraintValidatorContext context) {
return (Arrays.asList(ALL_CARD_TYPES).contains(value));
}
}
You can do something very similar to check @NotNull
.
Maintain the aspect ratio of a div with CSS
A simple way of maintaining the aspect ratio, using the canvas element.
Try resizing the div below to see it in action.
For me, this approach worked best, so I am sharing it with others so they can benefit from it as well.
_x000D_
_x000D_
.cont {
border: 5px solid blue;
position: relative;
width: 300px;
padding: 0;
margin: 5px;
resize: horizontal;
overflow: hidden;
}
.ratio {
width: 100%;
margin: 0;
display: block;
}
.content {
background-color: rgba(255, 0, 0, 0.5);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
margin: 0;
}
_x000D_
<div class="cont">
<canvas class="ratio" width="16" height="9"></canvas>
<div class="content">I am 16:9</div>
</div>
_x000D_
_x000D_
_x000D_
Also works with dynamic height!
_x000D_
_x000D_
.cont {
border: 5px solid blue;
position: relative;
height: 170px;
padding: 0;
margin: 5px;
resize: vertical;
overflow: hidden;
display: inline-block; /* so the div doesn't automatically expand to max width */
}
.ratio {
height: 100%;
margin: 0;
display: block;
}
.content {
background-color: rgba(255, 0, 0, 0.5);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
margin: 0;
}
_x000D_
<div class="cont">
<canvas class="ratio" width="16" height="9"></canvas>
<div class="content">I am 16:9</div>
</div>
_x000D_
_x000D_
_x000D_
How do I sort a Set to a List in Java?
Here's how you can do it with Java 8's Streams:
mySet.stream().sorted().collect(Collectors.toList());
or with a custom comparator:
mySet.stream().sorted(myComparator).collect(Collectors.toList());
Set timeout for ajax (jQuery)
use the full-featured .ajax
jQuery function.
compare with https://stackoverflow.com/a/3543713/1689451 for an example.
without testing, just merging your code with the referenced SO question:
target = $(this).attr('data-target');
$.ajax({
url: $(this).attr('href'),
type: "GET",
timeout: 2000,
success: function(response) { $(target).modal({
show: true
}); },
error: function(x, t, m) {
if(t==="timeout") {
alert("got timeout");
} else {
alert(t);
}
}
});?
ASP.NET Custom Validator Client side & Server Side validation not firing
Your CustomValidator
will only fire when the TextBox
isn't empty.
If you need to ensure that it's not empty then you'll need a RequiredFieldValidator
too.
Note: If the input control is empty,
no validation functions are called and
validation succeeds. Use a
RequiredFieldValidator control to
require the user to enter data in the
input control.
EDIT:
If your CustomValidator
specifies the ControlToValidate
attribute (and your original example does) then your validation functions will only be called when the control isn't empty.
If you don't specify ControlToValidate
then your validation functions will be called every time.
This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator
, you could omit the ControlToValidate
attribute from the CustomValidator
and setup your validation functions to do something like this:
Client Side code (Javascript):
function TextBoxDCountyClient(sender, args) {
var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
if (v == '') {
args.IsValid = false; // field is empty
}
else {
// do your other validation tests here...
}
}
Server side code (C#):
protected void TextBoxDTownCity_Validate(
object source, ServerValidateEventArgs args)
{
string v = TextBoxDTownCity.Text;
if (v == string.Empty)
{
args.IsValid = false; // field is empty
}
else
{
// do your other validation tests here...
}
}
Convert Uri to String and String to Uri
I am not sure if you got this resolved.
To follow up on "CommonsWare's" comment.
That is not a valid string representation of a Uri.
A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.
Change
Uri uri=Uri.parse("/external/images/media/470939");
to
Uri uri=Uri.parse("content://external/images/media/470939");
in my case
Uri uri = Uri.parse("content://media/external/images/media/6562");
MongoDB or CouchDB - fit for production?
We are currently using mongodb as an file storage service for our collaboration over LAN.
Also, projects like trello are using mongodb as their backend datastore.
I have used couchdb earlier, but not in production capacity.
Java System.out.print formatting
Something likes this
public void testPrintOut() {
int val1 = 8;
String val2 = "$951.23";
String val3 = "$215.92";
String val4 = "$198,301.22";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
val1 = 9;
val2 = "$950.19";
val3 = "$216.95";
val4 = "$198,084.26";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
}
VBA Go to last empty row
If you are certain that you only need column A, then you can use an End function in VBA to get that result.
If all the cells A1:A100 are filled, then to select the next empty cell use:
Range("A1").End(xlDown).Offset(1, 0).Select
Here, End(xlDown) is the equivalent of selecting A1 and pressing Ctrl + Down Arrow.
If there are blank cells in A1:A100, then you need to start at the bottom and work your way up. You can do this by combining the use of Rows.Count and End(xlUp), like so:
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
Going on even further, this can be generalized to selecting a range of cells, starting at a point of your choice (not just in column A). In the following code, assume you have values in cells C10:C100, with blank cells interspersed in between. You wish to select all the cells C10:C100, not knowing that the column ends at row 100, starting by manually selecting C10.
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlUp)).Select
The above line is perhaps one of the more important lines to know as a VBA programmer, as it allows you to dynamically select ranges based on very few criteria, and not be bothered with blank cells in the middle.
How can I process each letter of text using Javascript?
In today's JavaScript you can
Array.prototype.map.call('This is my string', (c) => c+c)
Obviously, c+c represents whatever you want to do with c.
This returns
["TT", "hh", "ii", "ss", " ", "ii", "ss", " ",
"mm", "yy", " ", "ss", "tt", "rr", "ii", "nn", "gg"]
Get HTML5 localStorage keys
I like to create an easily visible object out of it like this.
Object.keys(localStorage).reduce(function(obj, str) {
obj[str] = localStorage.getItem(str);
return obj
}, {});
I do a similar thing with cookies as well.
document.cookie.split(';').reduce(function(obj, str){
var s = str.split('=');
obj[s[0].trim()] = s[1];
return obj;
}, {});
Succeeded installing but could not start apache 2.4 on my windows 7 system
In my case, it was due to an IP address that Apache is listening to. Previously I have set it to 192.168.10.6 and recently Apache service is not running. I noticed that due to My laptop wifi changed recently and new IP is different. After fixing the wifi IP to laptop previous IP, Apache service is running again without any error.
Also if you don't want to change wifi IP then remove/comment that hardcode IP in httpd.conf file to resolve conflict.
Are "while(true)" loops so bad?
It's more of an aesthetics thing, much easier to read code where you explicitly know why the loop will stop right in the declaration of the loop.
What are good examples of genetic algorithms/genetic programming solutions?
There was an competition on codechef.com (great site by the way, monthly programming competitions) where one was supposed to solve an unsolveable sudoku (one should come as close as possible with as few wrong collumns/rows/etc as possible).
What I would do, was to first generate a perfect sudoku and then override the fields, that have been given. From this pretty good basis on I used genetic programming to improve my solution.
I couldn't think of a deterministic approach in this case, because the sudoku was 300x300 and search would've taken too long.
Convert binary to ASCII and vice versa
Convert binary to its equivalent character.
k=7
dec=0
new=[]
item=[x for x in input("Enter 8bit binary number with , seprator").split(",")]
for i in item:
for j in i:
if(j=="1"):
dec=2**k+dec
k=k-1
else:
k=k-1
new.append(dec)
dec=0
k=7
print(new)
for i in new:
print(chr(i),end="")
.NET: Simplest way to send POST with data and read response
Use WebRequest. From Scott Hanselman:
public static string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length); //Push it out there
os.Close ();
System.Net.WebResponse resp = req.GetResponse();
if (resp== null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
How to bind RadioButtons to an enum?
You can further simplify the accepted answer. Instead of typing out the enums as strings in xaml and doing more work in your converter than needed, you can explicitly pass in the enum value instead of a string representation, and as CrimsonX commented, errors get thrown at compile time rather than runtime:
ConverterParameter={x:Static local:YourEnumType.Enum1}
<StackPanel>
<StackPanel.Resources>
<local:ComparisonConverter x:Key="ComparisonConverter" />
</StackPanel.Resources>
<RadioButton IsChecked="{Binding Path=YourEnumProperty, Converter={StaticResource ComparisonConverter}, ConverterParameter={x:Static local:YourEnumType.Enum1}}" />
<RadioButton IsChecked="{Binding Path=YourEnumProperty, Converter={StaticResource ComparisonConverter}, ConverterParameter={x:Static local:YourEnumType.Enum2}}" />
</StackPanel>
Then simplify the converter:
public class ComparisonConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value?.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value?.Equals(true) == true ? parameter : Binding.DoNothing;
}
}
Edit (Dec 16 '10):
Thanks to anon for suggesting returning Binding.DoNothing rather than DependencyProperty.UnsetValue.
Note - Multiple groups of RadioButtons in same container (Feb 17 '11):
In xaml, if radio buttons share the same parent container, then selecting one will de-select all other's within that container (even if they are bound to a different property). So try to keep your RadioButton's that are bound to a common property grouped together in their own container like a stack panel. In cases where your related RadioButtons cannot share a single parent container, then set the GroupName property of each RadioButton to a common value to logically group them.
Edit (Apr 5 '11):
Simplified ConvertBack's if-else to use a Ternary Operator.
Note - Enum type nested in a class (Apr 28 '11):
If your enum type is nested in a class (rather than directly in the namespace), you might be able to use the '+' syntax to access the enum in XAML as stated in a (not marked) answer to the question
Unable to find enum type for static reference in WPF:
ConverterParameter={x:Static local:YourClass+YourNestedEnumType.Enum1}
Due to this Microsoft Connect Issue, however, the designer in VS2010 will no longer load stating "Type 'local:YourClass+YourNestedEnumType' was not found."
, but the project does compile and run successfully. Of course, you can avoid this issue if you are able to move your enum type to the namespace directly.
Edit (Jan 27 '12):
If using Enum flags, the converter would be as follows:
public class EnumToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((Enum)value).HasFlag((Enum)parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
}
Edit (May 7 '15):
In case of a Nullable Enum (that is
not asked in the question, but can be needed in some cases, e.g. ORM returning null from DB or whenever it might make sense that in the program logic the value is not provided), remember to add an initial null check in the Convert Method and return the appropriate bool value, that is typically false (if you don't want any radio button selected), like below:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) {
return false; // or return parameter.Equals(YourEnumType.SomeDefaultValue);
}
return value.Equals(parameter);
}
Note - NullReferenceException (Oct 10 '18):
Updated the example to remove the possibility of throwing a NullReferenceException.
IsChecked
is a nullable type so returning
Nullable<Boolean>
seems a reasonable solution.
Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?
I believe the intent was to rename System32, but so many applications hard-coded for that path, that it wasn't feasible to remove it.
SysWoW64 wasn't intended for the dlls of 64-bit systems, it's actually something like "Windows on Windows64", meaning the bits you need to run 32bit apps on a 64bit windows.
This article explains a bit:
"Windows x64 has a directory System32 that contains 64-bit DLLs (sic!). Thus native processes with a bitness of 64 find “their” DLLs where they expect them: in the System32 folder. A second directory, SysWOW64, contains the 32-bit DLLs. The file system redirector does the magic of hiding the real System32 directory for 32-bit processes and showing SysWOW64 under the name of System32."
Edit: If you're talking about an installer, you really should not hard-code the path to the system folder. Instead, let Windows take care of it for you based on whether or not your installer is running on the emulation layer.
Setting Windows PowerShell environment variables
All the answers suggesting a permanent change have the same problem: They break the path registry value.
SetEnvironmentVariable
turns the REG_EXPAND_SZ
value %SystemRoot%\system32
into a REG_SZ
value of C:\Windows\system32
.
Any other variables in the path are lost as well. Adding new ones using %myNewPath%
won't work any more.
Here's a script Set-PathVariable.ps1
that I use to address this problem:
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[parameter(Mandatory=$true)]
[string]$NewLocation)
Begin
{
#requires –runasadministrator
$regPath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
$hklm = [Microsoft.Win32.Registry]::LocalMachine
Function GetOldPath()
{
$regKey = $hklm.OpenSubKey($regPath, $FALSE)
$envpath = $regKey.GetValue("Path", "", [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
return $envPath
}
}
Process
{
# Win32API error codes
$ERROR_SUCCESS = 0
$ERROR_DUP_NAME = 34
$ERROR_INVALID_DATA = 13
$NewLocation = $NewLocation.Trim();
If ($NewLocation -eq "" -or $NewLocation -eq $null)
{
Exit $ERROR_INVALID_DATA
}
[string]$oldPath = GetOldPath
Write-Verbose "Old Path: $oldPath"
# Check whether the new location is already in the path
$parts = $oldPath.split(";")
If ($parts -contains $NewLocation)
{
Write-Warning "The new location is already in the path"
Exit $ERROR_DUP_NAME
}
# Build the new path, make sure we don't have double semicolons
$newPath = $oldPath + ";" + $NewLocation
$newPath = $newPath -replace ";;",""
if ($pscmdlet.ShouldProcess("%Path%", "Add $NewLocation")){
# Add to the current session
$env:path += ";$NewLocation"
# Save into registry
$regKey = $hklm.OpenSubKey($regPath, $True)
$regKey.SetValue("Path", $newPath, [Microsoft.Win32.RegistryValueKind]::ExpandString)
Write-Output "The operation completed successfully."
}
Exit $ERROR_SUCCESS
}
I explain the problem in more detail in a blog post.
convert json ipython notebook(.ipynb) to .py file
You definitely can achieve that with nbconvert using the following command:
jupyter nbconvert --to python while.ipynb
However, having used it personally I would advise against it for several reasons:
- It's one thing to be able to convert to simple Python code and another to have all the right abstractions, classes access and methods set up. If the whole point of you converting your notebook code to Python is getting to a state where your code and notebooks are maintainable for the long run, then nbconvert alone will not suffice. The only way to do that is by manually going through the codebase.
- Notebooks inherently promote writing code which is not maintainable (https://docs.google.com/presentation/d/1n2RlMdmv1p25Xy5thJUhkKGvjtV-dkAIsUXP-AL4ffI/edit#slide=id.g3d7fe085e7_0_21). Using nbconvert on top might just prove to be a bandaid. Specific examples of where it promotes not-so-maintainable code are imports might be sprayed throughout, hard coded paths are not in one simple place to view, class abstractions might not be present, etc.
- nbconvert still mixes execution code and library code.
- Comments are still not present (probably were not in the notebook).
- There is still a lack of unit tests etc.
So to summarize, there is not good way to out of the box convert python notebooks to maintainable, robust python modularized code, the only way is to manually do surgery.
Bootstrap 3 dropdown select
The dropdown list appearing like that depends on what your browser is, as it is not possible to style this away for some. It looks like yours is IE9, but would look quite different in Chrome.
You could look to use something like this:
http://silviomoreto.github.io/bootstrap-select/
Which will make your selectboxes more consistent cross browser.
How to insert TIMESTAMP into my MySQL table?
In addition to checking your table setup to confirm that the field is set to NOT NULL
with a default of CURRENT_TIMESTAMP
, you can insert date/time values from PHP by writing them in a string format compatible with MySQL.
$timestamp = date("Y-m-d H:i:s");
This will give you the current date and time in a string format that you can insert into MySQL.
MySQL dump by query
Combining much of above here is my real practical example, selecting records based on both meterid & timestamp. I have needed this command for years. Executes really quickly.
mysqldump -uuser -ppassword main_dbo trHourly --where="MeterID =5406 AND TIMESTAMP<'2014-10-13 05:00:00'" --no-create-info --skip-extended-insert | grep '^INSERT' > 5406.sql
Drag and drop elements from list into separate blocks
I wrote some test code to check JQueryUI drag/drop. The example shows how to drag an element from a container and drop it to another container.
Markup-
<div class="row">
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Panel 1</h1>
</div>
<div id="container1" class="panel-body box-container">
<div itemid="itm-1" class="btn btn-default box-item">Item 1</div>
<div itemid="itm-2" class="btn btn-default box-item">Item 2</div>
<div itemid="itm-3" class="btn btn-default box-item">Item 3</div>
<div itemid="itm-4" class="btn btn-default box-item">Item 4</div>
<div itemid="itm-5" class="btn btn-default box-item">Item 5</div>
</div>
</div>
</div>
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Panel 2</h1>
</div>
<div id="container2" class="panel-body box-container"></div>
</div>
</div>
</div>
JQuery codes-
$(document).ready(function() {
$('.box-item').draggable({
cursor: 'move',
helper: "clone"
});
$("#container1").droppable({
drop: function(event, ui) {
var itemid = $(event.originalEvent.toElement).attr("itemid");
$('.box-item').each(function() {
if ($(this).attr("itemid") === itemid) {
$(this).appendTo("#container1");
}
});
}
});
$("#container2").droppable({
drop: function(event, ui) {
var itemid = $(event.originalEvent.toElement).attr("itemid");
$('.box-item').each(function() {
if ($(this).attr("itemid") === itemid) {
$(this).appendTo("#container2");
}
});
}
});
});
CSS-
.box-container {
height: 200px;
}
.box-item {
width: 100%;
z-index: 1000
}
Check the plunker JQuery Drag Drop
How to deal with floating point number precision in JavaScript?
I'm finding BigNumber.js meets my needs.
A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.
It has good documentation and the author is very diligent responding to feedback.
The same author has 2 other similar libraries:
Big.js
A small, fast JavaScript library for arbitrary-precision decimal arithmetic. The little sister to bignumber.js.
and Decimal.js
An arbitrary-precision Decimal type for JavaScript.
Here's some code using BigNumber:
_x000D_
_x000D_
$(function(){_x000D_
_x000D_
_x000D_
var product = BigNumber(.1).times(.2); _x000D_
$('#product').text(product);_x000D_
_x000D_
var sum = BigNumber(.1).plus(.2); _x000D_
$('#sum').text(sum);_x000D_
_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- 1.4.1 is not the current version, but works for this example. -->_x000D_
<script src="http://cdn.bootcss.com/bignumber.js/1.4.1/bignumber.min.js"></script>_x000D_
_x000D_
.1 × .2 = <span id="product"></span><br>_x000D_
.1 + .2 = <span id="sum"></span><br>
_x000D_
_x000D_
_x000D_
How to replace text of a cell based on condition in excel
You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM
. Then simply type where it says TYPE
: what you want to say in QUOTES.
Example.. "OTHER"
What's the difference between an id and a class?
Classes are like categories. Many HTML elements can belong to a class, and an HTML element can have more than one class. Classes are used to apply general styles or styles that can be applied across multiple HTML elements.
IDs are identifiers. They're unique; no one else is allowed to have that same ID. IDs are used to apply unique styles to an HTML element.
I use IDs and classes in this fashion:
<div id="header">
<h1>I am a header!</h1>
<p>I am subtext for a header!</p>
</div>
<div id="content">
<div class="section">
<p>I am a section!</p>
</div>
<div class="section special">
<p>I am a section!</p>
</div>
<div class="section">
<p>I am a section!</p>
</div>
</div>
In this example, the header and content sections can be styled via #header and #content. Each section of the content can be applied a common style through #content .section. Just for kicks, I added a "special" class for the middle section. Suppose you wanted a particular section to have a special styling. This can be achieved with the .special class, yet the section still inherits the common styles from #content .section.
When I do JavaScript or CSS development, I typically use IDs to access/manipulate a very specific HTML element, and I use classes to access/apply styles to a broad range of elements.
Set style for TextView programmatically
You can create a generic style and re-use it on multiple textviews like the one below:
textView.setTextAppearance(this, R.style.MyTextStyle);
Edit: this refers to Context
How to scale a UIImageView proportionally?
Here is how you can scale it easily.
This works in 2.x with the Simulator and the iPhone.
UIImage *thumbnail = [originalImage _imageScaledToSize:CGSizeMake(40.0, 40.0) interpolationQuality:1];
Why does ENOENT mean "No such file or directory"?
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
How to get SQL from Hibernate Criteria API (*not* for logging)
This answer is based on user3715338's answer (with a small spelling error corrected) and mixed with Michael's answer for Hibernate 3.6 - based on the accepted answer from Brian Deterling. I then extended it (for PostgreSQL) with a couple more types replacing the questionmarks:
public static String toSql(Criteria criteria)
{
String sql = "";
Object[] parameters = null;
try
{
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
SessionImpl sessionImpl = (SessionImpl) criteriaImpl.getSession();
SessionFactoryImplementor factory = sessionImpl.getSessionFactory();
String[] implementors = factory.getImplementors(criteriaImpl.getEntityOrClassName());
OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister(implementors[0]);
LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers();
CriteriaLoader loader = new CriteriaLoader(persister, factory,
criteriaImpl, implementors[0].toString(), loadQueryInfluencers);
Field f = OuterJoinLoader.class.getDeclaredField("sql");
f.setAccessible(true);
sql = (String) f.get(loader);
Field fp = CriteriaLoader.class.getDeclaredField("translator");
fp.setAccessible(true);
CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
parameters = translator.getQueryParameters().getPositionalParameterValues();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
if (sql != null)
{
int fromPosition = sql.indexOf(" from ");
sql = "\nSELECT * " + sql.substring(fromPosition);
if (parameters != null && parameters.length > 0)
{
for (Object val : parameters)
{
String value = "%";
if (val instanceof Boolean)
{
value = ((Boolean) val) ? "1" : "0";
}
else if (val instanceof String)
{
value = "'" + val + "'";
}
else if (val instanceof Number)
{
value = val.toString();
}
else if (val instanceof Class)
{
value = "'" + ((Class) val).getCanonicalName() + "'";
}
else if (val instanceof Date)
{
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
value = "'" + sdf.format((Date) val) + "'";
}
else if (val instanceof Enum)
{
value = "" + ((Enum) val).ordinal();
}
else
{
value = val.toString();
}
sql = sql.replaceFirst("\\?", value);
}
}
}
return sql.replaceAll("left outer join", "\nleft outer join").replaceAll(
" and ", "\nand ").replaceAll(" on ", "\non ").replaceAll("<>",
"!=").replaceAll("<", " < ").replaceAll(">", " > ");
}
Working with a List of Lists in Java
Also this is an example of how to print List of List using advanced for loop:
public static void main(String[] args){
int[] a={1,3, 7, 8, 3, 9, 2, 4, 10};
List<List<Integer>> triplets;
triplets=sumOfThreeNaive(a, 13);
for (List<Integer> list : triplets){
for (int triplet: list){
System.out.print(triplet+" ");
}
System.out.println();
}
}
How to check if a file exists in Go?
The first thing to consider is that it is rare that you would only want to check whether or not a file exists. In most situations, you're trying to do something with the file if it exists. In Go, any time you try to perform some operation on a file that doesn't exist, the result should be a specific error (os.ErrNotExist
) and the best thing to do is check whether the return err
value (e.g. when calling a function like os.OpenFile(...)
) is os.ErrNotExist
.
The recommended way to do this used to be:
file, err := os.OpenFile(...)
if os.IsNotExist(err) {
// handle the case where the file doesn't exist
}
However, since the addition of errors.Is
in Go 1.13 (released in late 2019), the new recommendation is to use errors.Is
:
file, err := os.OpenFile(...)
if errors.Is(err, os.ErrNotExist) {
// handle the case where the file doesn't exist
}
It's usually best to avoid using os.Stat
to check for the existence of a file before you attempt to do something with it, because it will always be possible for the file to be renamed, deleted, etc. in the window of time before you do something with it.
However, if you're OK with this caveat and you really, truly just want to check whether a file exists without then proceeding to do something useful with it (as a contrived example, let's say that you're writing a pointless CLI tool that tells you whether or not a file exists and then exits ¯\_(?)_/¯
), then the recommended way to do it would be:
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
// file does not exist
} else {
// file exists
}
Facebook api: (#4) Application request limit reached
The Facebook API limit isn't really documented, but apparently it's something like: 600 calls per 600 seconds, per token & per IP. As the site is restricted, quoting the relevant part:
After some testing and discussion with the Facebook platform team, there is no official limit I'm aware of or can find in the documentation. However, I've found 600 calls per 600 seconds, per token & per IP to be about where they stop you. I've also seen some application based rate limiting but don't have any numbers.
As a general rule, one call per second should not get rate limited. On the surface this seems very restrictive but remember you can batch certain calls and use the subscription API to get changes.
As you can access the Graph API on the client side via the Javascript SDK; I think if you travel your request for photos from the client, you won't hit any application limit
as it's the user (each one with unique id) who's fetching data, not your application server (unique ID).
This may mean a huge refactor if everything you do go through a server. But it seems like the best solution if you have so many request (as it'll give a breath to your server).
Else, you can try batch
request, but I guess you're already going this way if you have big traffic.
If nothing of this works, according to the Facebook Platform Policy you should contact them.
If you exceed, or plan to exceed, any of the following thresholds please contact us as you may be subject to additional terms: (>5M MAU) or (>100M API calls per day) or (>50M impressions per day).
UIWebView open links in Safari
One quick comment to user306253's answer: caution with this, when you try to load something in the UIWebView yourself (i.e. even from the code), this method will prevent it to happened.
What you can do to prevent this (thanks Wade) is:
if (inType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
You might also want to handle the UIWebViewNavigationTypeFormSubmitted
and UIWebViewNavigationTypeFormResubmitted
types.