Why doesn't java.io.File have a close method?
The javadoc of the File
class describes the class as:
An abstract representation of file and directory pathnames.
File
is only a representation of a pathname, with a few methods concerning the filesystem (like exists()
) and directory handling but actual streaming input and output is done elsewhere. Streams can be opened and closed, files cannot.
(My personal opinion is that it's rather unfortunate that Sun then went on to create RandomAccessFile
, causing much confusion with its inconsistent naming.)
Can MySQL convert a stored UTC time to local timezone?
I am not sure what math can be done on a DATETIME data type, but if you are using PHP, I strongly recommend using the integer-based timestamps. Basically, you can store a 4-byte integer in the database using PHP's time() function. This makes doing math on it much more straightforward.
MS Access: how to compact current database in VBA
I did this many years back on 2003 or possibly 97, yikes!
If I recall you need to use one of the subcommands above tied to a timer. You cannot operate on the db with any connections or forms open.
So you do something about closing all forms, and kick off the timer as the last running method. (which will in turn call the compact operation once everything closes)
If you haven't figured this out I could dig through my archives and pull it up.
How do I copy an object in Java?
public class MyClass implements Cloneable {
private boolean myField= false;
// and other fields or objects
public MyClass (){}
@Override
public MyClass clone() throws CloneNotSupportedException {
try
{
MyClass clonedMyClass = (MyClass)super.clone();
// if you have custom object, then you need create a new one in here
return clonedMyClass ;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return new MyClass();
}
}
}
and in your code:
MyClass myClass = new MyClass();
// do some work with this object
MyClass clonedMyClass = myClass.clone();
Xcode swift am/pm time to 24 hour format
Here is code for other way around
For Swift 3
func amAppend(str:String) -> String{
var temp = str
var strArr = str.characters.split{$0 == ":"}.map(String.init)
var hour = Int(strArr[0])!
var min = Int(strArr[1])!
if(hour > 12){
temp = temp + "PM"
}
else{
temp = temp + "AM"
}
return temp
}
jQuery: how to change title of document during .ready()?
I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document.
The correct way to do this is on the server side.
In your layout, there at some point will be some code which puts the text in the div. Make this code also set some instance variable such as @page_title
, and then in your outer layout have it do <%= @page_title || 'Default Title' %>
How to query a CLOB column in Oracle
I did run into another condition with HugeClob in my Oracle database. The dbms_lob.substr
only allowed a value of 4000 in the function, ex:
dbms_lob.substr(column,4000,1)
so for my HughClob which was larger, I had to use two calls in select
:
select dbms_lob.substr(column,4000,1) part1,
dbms_lob.substr(column,4000,4001) part2 from .....
I was calling from a Java app so I simply concatenated part1 and part2 and sent as a email.
Passing parameters to a Bash function
Drop the parentheses and commas:
myBackupFunction ".." "..." "xx"
And the function should look like this:
function myBackupFunction() {
# Here $1 is the first parameter, $2 the second, etc.
}
What is the => assignment in C# in a property signature
What you're looking at is an expression-bodied member not a lambda expression.
When the compiler encounters an expression-bodied property member, it essentially converts it to a getter like this:
public int MaxHealth
{
get
{
return Memory[Address].IsValid ? Memory[Address].Read<int>(Offs.Life.MaxHp) : 0;
}
}
(You can verify this for yourself by pumping the code into a tool called TryRoslyn.)
Expression-bodied members - like most C# 6 features - are just syntactic sugar. This means that they don’t provide functionality that couldn't otherwise be achieved through existing features. Instead, these new features allow a more expressive and succinct syntax to be used
As you can see, expression-bodied members have a handful of shortcuts that make property members more compact:
- There is no need to use a
return
statement because the compiler can infer that you want to return the result of the expression
- There is no need to create a statement block because the body is only one expression
- There is no need to use the
get
keyword because it is implied by the use of the expression-bodied member syntax.
I have made the final point bold because it is relevant to your actual question, which I will answer now.
The difference between...
// expression-bodied member property
public int MaxHealth => x ? y:z;
And...
// field with field initializer
public int MaxHealth = x ? y:z;
Is the same as the difference between...
public int MaxHealth
{
get
{
return x ? y:z;
}
}
And...
public int MaxHealth = x ? y:z;
Which - if you understand properties - should be obvious.
Just to be clear, though: the first listing is a property with a getter under the hood that will be called each time you access it. The second listing is is a field with a field initializer, whose expression is only evaluated once, when the type is instantiated.
This difference in syntax is actually quite subtle and can lead to a "gotcha" which is described by Bill Wagner in a post entitled "A C# 6 gotcha: Initialization vs. Expression Bodied Members".
While expression-bodied members are lambda expression-like, they are not lambda expressions. The fundamental difference is that a lambda expression results in either a delegate instance or an expression tree. Expression-bodied members are just a directive to the compiler to generate a property behind the scenes. The similarity (more or less) starts and end with the arrow (=>
).
I'll also add that expression-bodied members are not limited to property members. They work on all these members:
- Properties
- Indexers
- Methods
- Operators
Added in C# 7.0
However, they do not work on these members:
- Nested Types
- Events
- Fields
Comments in .gitignore?
Do git help gitignore
You will get the help page with following line:
A line starting with # serves as a comment.
Optimal way to DELETE specified rows from Oracle
I have tried this code and It's working fine in my case.
DELETE FROM NG_USR_0_CLIENT_GRID_NEW WHERE rowid IN
( SELECT rowid FROM
(
SELECT wi_name, relationship, ROW_NUMBER() OVER (ORDER BY rowid DESC) RN
FROM NG_USR_0_CLIENT_GRID_NEW
WHERE wi_name = 'NB-0000001385-Process'
)
WHERE RN=2
);
Input type DateTime - Value format?
For what it's worth, with iOS7 dropping support for datetime
you need to use datetime-local
which doesn't accept timezone portion (which makes sense).
Doesn't work (iOS anyway):
<input type="datetime-local" value="2000-01-01T00:00:00+05:00" />
Works:
<input type="datetime-local" value="2000-01-01T00:00:00" />
PHP for value (windows safe):
strftime('%Y-%m-%dT%H:%M:%S', strtotime($my_datetime_input))
Convert integer into its character equivalent, where 0 => a, 1 => b, etc
Assuming you want uppercase case letters:
function numberToLetter(num){
var alf={
'0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G'
};
if(num.length== 1) return alf[num] || ' ';
return num.split('').map(numberToLetter);
}
Example:
numberToLetter('023') is ["A", "C", "D"]
numberToLetter('5') is "F"
How can I tell if a DOM element is visible in the current viewport?
I tried Dan's answer. However, the algebra used to determine the bounds means that the element must be both = the viewport size and completely inside the viewport to get true
, easily leading to false negatives. If you want to determine whether an element is in the viewport at all, ryanve's answer is close, but the element being tested should overlap the viewport, so try this:
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return rect.bottom > 0 &&
rect.right > 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ &&
rect.top < (window.innerHeight || document.documentElement.clientHeight) /* or $(window).height() */;
}
ssh-copy-id no identities found error
FWIW, the -i option was a red herring for me. ssh-copy-id will use ~/.ssh/id_rsa.pub by default.
What was keeping it from working for me was the permissions on the ~ directory, the ~/.ssh directory, and the ~/.ssh/authorized_keys file on the remote computer.
All three need to be set with chmod 755 ~ ~/.ssh ~/.ssh/authorized_keys
, then ssh-copy-id your-remote-server.com
will work.
How do I embed PHP code in JavaScript?
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js
files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php
(or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var
in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode()
also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
After submitting a POST form open a new window showing the result
If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");
// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
How to create relationships in MySQL
If the tables are innodb you can create it like this:
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id ),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;
You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look here for more info.
CMD what does /im (taskkill)?
im
is "image process name"
example /f /im notepad.exe
is specified to kill image process name (program) notepad.exe
Set folder for classpath
If you are using Java 6 or higher you can use wildcards of this form:
java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp
If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:
java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp
There is nothing like lib\*\*
or lib\**
wildcard for the kind of job you want to be done.
Angular2 change detection: ngOnChanges not firing for nested object
I stumbled upon the same need. And I read a lot on this so, here is my copper on the subject.
If you want your change detection on push, then you would have it when you change a value of an object inside right ? And you also would have it if somehow, you remove objects.
As already said, use of changeDetectionStrategy.onPush
Say you have this component you made, with changeDetectionStrategy.onPush:
<component [collection]="myCollection"></component>
Then you'd push an item and trigger the change detection :
myCollection.push(anItem);
refresh();
or you'd remove an item and trigger the change detection :
myCollection.splice(0,1);
refresh();
or you'd change an attrbibute value for an item and trigger the change detection :
myCollection[5].attribute = 'new value';
refresh();
Content of refresh :
refresh() : void {
this.myCollection = this.myCollection.slice();
}
The slice method returns the exact same Array, and the [ = ] sign make a new reference to it, triggering the change detection every time you need it. Easy and readable :)
Regards,
How to ignore whitespace in a regular expression subject string?
This approach can be used to automate this
(the following exemplary solution is in python, although obviously it can be ported to any language):
you can strip the whitespace beforehand AND save the positions of non-whitespace characters so you can use them later to find out the matched string boundary positions in the original string like the following:
def regex_search_ignore_space(regex, string):
no_spaces = ''
char_positions = []
for pos, char in enumerate(string):
if re.match(r'\S', char): # upper \S matches non-whitespace chars
no_spaces += char
char_positions.append(pos)
match = re.search(regex, no_spaces)
if not match:
return match
# match.start() and match.end() are indices of start and end
# of the found string in the spaceless string
# (as we have searched in it).
start = char_positions[match.start()] # in the original string
end = char_positions[match.end()] # in the original string
matched_string = string[start:end] # see
# the match WITH spaces is returned.
return matched_string
with_spaces = 'a li on and a cat'
print(regex_search_ignore_space('lion', with_spaces))
# prints 'li on'
If you want to go further you can construct the match object and return it instead, so the use of this helper will be more handy.
And the performance of this function can of course also be optimized, this example is just to show the path to a solution.
Assign static IP to Docker container
I stumbled upon this problem during attempt to dockerise Avahi which needs to be aware of its public IP to function properly. Assigning static IP to the container is tricky due to lack of support for static IP assignment in Docker.
This article describes technique how to assign static IP to the container on Debian:
Docker service should be started with DOCKER_OPTS="--bridge=br0 --ip-masq=false --iptables=false"
. I assume that br0
bridge is already configured.
Container should be started with --cap-add=NET_ADMIN --net=bridge
Inside container pre-up ip addr flush dev eth0
in /etc/network/interfaces
can be used to dismiss IP address assigned by Docker as in following example:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
pre-up ip addr flush dev eth0
address 192.168.0.249
netmask 255.255.255.0
gateway 192.168.0.1
- Container's entry script should begin with
/etc/init.d/networking start
. Also entry script needs to edit or populate /etc/hosts
file in order to remove references to Docker-assigned IP.
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();
Android basically works on two thread types namely UI thread and background thread. According to android documentation -
Do not access the Android UI toolkit from outside the UI thread to fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:
Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
Now there are various methods to solve this problem. I will explain it by code sample
runOnUiThread
new Thread()
{
public void run()
{
myactivity.this.runOnUiThread(new runnable()
{
public void run()
{
//Do your UI operations like dialog opening or Toast here
}
});
}
}.start();
LOOPER
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
AsyncTask
AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.
public void onClick(View v) {
new CustomTask().execute((Void[])null);
}
private class CustomTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... param) {
//Do some work
return null;
}
protected void onPostExecute(Void param) {
//Print Toast or open dialog
}
}
Handler
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.
Message msg = new Message();
new Thread()
{
public void run()
{
msg.arg1=1;
handler.sendMessage(msg);
}
}.start();
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if(msg.arg1==1)
{
//Print Toast or open dialog
}
return false;
}
});
What is FCM token in Firebase?
They deprecated getToken() method in the below release notes. Instead, we have to use getInstanceId.
https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId
Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
task.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult authResult) {
// Task completed successfully
// ...
String fcmToken = authResult.getToken();
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
}
});
To handle success and failure in the same listener, attach an OnCompleteListener:
task.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (task.isSuccessful()) {
// Task completed successfully
InstanceIdResult authResult = task.getResult();
String fcmToken = authResult.getToken();
} else {
// Task failed with an exception
Exception exception = task.getException();
}
}
});
Also, the FirebaseInstanceIdService Class is deprecated and they came up with onNewToken method in FireBaseMessagingService as replacement for onTokenRefresh,
you can refer to the release notes here,
https://firebase.google.com/support/release-notes/android
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Use this code logic to send the info to your server.
//sendRegistrationToServer(s);
}
Count words in a string method?
create variable count, state. initialize variables
if space is present keep count as it is else increase count.
for eg:
if (string.charAt(i) == ' ' ) {
state = 0;
} else if (state == 0) {
state = 1;
count += 1;
Favicon: .ico or .png / correct tags?
I know this is an old question.
Here's another option - attending to different platform requirements - Source
<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='72x72' href='/icon.72.png'> <!-- iPad -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->
This is the broadest approach I have found so far.
Ultimately the decision depends on your own needs. Ask yourself, who is your target audience?
UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.
How to call a method function from another class?
You need a reference to the class that contains the method you want to call. Let's say we have two classes, A and B. B has a method you want to call from A. Class A would look like this:
public class A
{
B b; // A reference to B
b = new B(); // Creating object of class B
b.doSomething(); // Calling a method contained in class B from class A
}
B, which contains the doSomething() method would look like this:
public class B
{
public void doSomething()
{
System.out.println("Look, I'm doing something in class B!");
}
}
Interfaces with static fields in java for sharing 'constants'
I do not have enough reputation to give a comment to Pleerock, therefor do I have to create an answer. I am sorry for that, but he put some good effort in it and I would like to answer him.
Pleerock, you created the perfect example to show why those constants should be independent from interfaces and independent from inheritance. For the client of the application is it not important that there is a technical difference between those implementation of cars. They are the same for the client, just cars. So, the client wants to look at them from that perspective, which is an interface like I_Somecar. Throughout the application will the client use only one perspective and not different ones for each different car brand.
If a client wants to compare cars prior to buying he can have a method like this:
public List<Decision> compareCars(List<I_Somecar> pCars);
An interface is a contract about behaviour and shows different objects from one perspective. The way you design it, will every car brand have its own line of inheritance. Although it is in reality quite correct, because cars can be that different that it can be like comparing completely different type of objects, in the end there is choice between different cars. And that is the perspective of the interface all brands have to share. The choice of constants should not make this impossible. Please, consider the answer of Zarkonnen.
Child element click event trigger the parent click event
The stopPropagation()
method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
You can use the method event.isPropagationStopped()
to know whether this method was ever called (on that event object).
Syntax:
Here is the simple syntax to use this method:
event.stopPropagation()
Example:
$("div").click(function(event) {
alert("This is : " + $(this).prop('id'));
// Comment the following to see the difference
event.stopPropagation();
});?
Can I write native iPhone apps using Python?
I think it was not possible earlier but I recently heard about PyMob, which seems interesting because the apps are written in Python and the final outputs are native source codes in various platforms (Obj-C for iOS, Java for Android etc). This is certainly quite unique. This webpage explains it in more detail.
I haven't given it a shot yet, but will take a look soon.
Maven2: Best practice for Enterprise Project (EAR file)
I've been searching high and low for an end-to-end example of a complete maven-based ear-packaged application and finally stumbled upon this. The instructions say to select option 2 when running through the CLI but for your purposes, use option 1.
Remove all special characters from a string in R?
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
How to put comments in Django templates
As answer by Miles, {% comment %}...{% endcomment %}
is used for multi-line comments, but you can also comment out text on the same line like this:
{# some text #}
Functions that return a function
When you return b
, it is just a reference to function b, but not being executed at this time.
When you return b()
, you're executing the function and returning its value.
Try alert
ing typeof(s)
in your examples. Snippet b will give you 'function'. What will snippet a give you?
How to stop/terminate a python script from running?
You can also do it if you use the exit()
function in your code. More ideally, you can do sys.exit()
. sys.exit()
which might terminate Python even if you are running things in parallel through the multiprocessing
package.
Note: In order to use the sys.exit()
, you must import it: import sys
How to get the timezone offset in GMT(Like GMT+7:00) from android device?
This might give you an idea on how to implement it to your liking:
Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
int mGMTOffset = mTimeZone.getRawOffset();
System.out.printf("GMT offset is %s hours", TimeUnit.HOURS.convert(mGMTOffset, TimeUnit.MILLISECONDS));
(TimeUnit is "java.util.concurrent.TimeUnit")
How to get client IP address using jQuery
A simple AJAX call to your server, and then the serverside logic to get the ip address should do the trick.
$.getJSON('getip.php', function(data){
alert('Your ip is: ' + data.ip);
});
Then in php you might do:
<?php
/* getip.php */
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
print json_encode(array('ip' => $ip));
Built in Python hash() function
At a guess, AppEngine is using a 64-bit implementation of Python (-5768830964305142685 won't fit in 32 bits) and your implementation of Python is 32 bits. You can't rely on object hashes being meaningfully comparable between different implementations.
node.js execute system command synchronously
Node.js (since version 0.12 - so for a while) supports execSync
:
child_process.execSync(command[, options])
You can now directly do this:
const execSync = require('child_process').execSync;
code = execSync('node -v');
and it'll do what you expect. (Defaults to pipe the i/o results to the parent process). Note that you can also spawnSync
now.
How to add new column to an dataframe (to the front not end)?
Use cbind
e.g.
df <- data.frame(b = runif(6), c = rnorm(6))
cbind(a = 0, df)
giving:
> cbind(a = 0, df)
a b c
1 0 0.5437436 -0.1374967
2 0 0.5634469 -1.0777253
3 0 0.9018029 -0.8749269
4 0 0.1649184 -0.4720979
5 0 0.6992595 0.6219001
6 0 0.6907937 -1.7416569
Having services in React application
I am in the same boot like you. In the case you mention, I would implement the input validation UI component as a React component.
I agree the implementation of the validation logic itself should (must) not be coupled. Therefore I would put it into a separate JS module.
That is, for logic that should not be coupled use a JS module/class in separate file, and use require/import to de-couple the component from the "service".
This allows for dependency injection and unit testing of the two independently.
Java Embedded Databases Comparison
Either
- HSQLDB - Used by OpenOffice, tested and stable. It's easy to use. If you want to edit your db-data, you can just open the file and edit the insert statements.
or
- H2 - Said to be faster (by the developer, who originally designed hsqldb, too)
Which one you use is up to you, depending how much performance and how much stability you need.
The developer of H2 has put up a nice performance evaluation:
http://www.h2database.com/html/performance.html
How to get the Enum Index value in C#
You can directly cast it:
enum MyMonthEnum { January = 1, February, March, April, May, June, July, August, September, October, November, December };
public static string GetMyMonthName(int MonthIndex)
{
MyMonthEnum MonthName = (MyMonthEnum)MonthIndex;
return MonthName.ToString();
}
For Example:
string MySelectedMonthName=GetMyMonthName(8);
//then MySelectedMonthName value will be August.
#pragma once vs include guards?
I just wanted to add to this discussion that I am just compiling on VS and GCC, and used to use include guards. I have now switched to #pragma once
, and the only reason for me is not performance or portability or standard as I don't really care what is standard as long as VS and GCC support it, and that is that:
#pragma once
reduces possibilities for bugs.
It is all too easy to copy and paste a header file to another header file, modify it to suit ones needs, and forget to change the name of the include guard. Once both are included, it takes you a while to track down the error, as the error messages aren't necessarily clear.
Quoting backslashes in Python string literals
Use a raw string:
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
Note that although it looks wrong, it's actually right. There is only one backslash in the string foo
.
This happens because when you just type foo
at the prompt, python displays the result of __repr__()
on the string. This leads to the following (notice only one backslash and no quotes around the print
ed string):
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:
>>> foo = r'baz \'
File "<stdin>", line 1
foo = r'baz \'
^
SyntaxError: EOL while scanning single-quoted string
Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:
>>> foo = 'baz \\'
>>> print(foo)
baz \
However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath()
function:
myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)
This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.
Recursion or Iteration?
Stack overflow will only occur if you're programming in a language that doesn't have in built memory management.... Otherwise, make sure you have something in your function (or a function call, STDLbs, etc). Without recursion it would simply not be possible to have things like... Google or SQL, or any place one must efficiently sort through large data structures (classes) or databases.
Recursion is the way to go if you want to iterate through files, pretty sure that's how 'find * | ?grep *' works. Kinda dual recursion, especially with the pipe (but don't do a bunch of syscalls like so many like to do if it's anything you're going to put out there for others to use).
Higher level languages and even clang/cpp may implement it the same in the background.
Should I use SVN or Git?
I have used SVN for a long time, but whenever I used Git, I felt that Git is much powerful, lightweight, and although a little bit of learning curve involved but is better than SVN.
What I have noted is that each SVN project, as it grows, becomes a very big size project unless it is exported. Where as, GIT project (along with Git data) is very light weight in size.
In SVN, I've dealt with developers from novice to experts, and the novices and intermediates seem to introduce File conflicts if they copy one folder from another SVN project in order to re-use it. Whereas, I think in Git, you just copy the folder and it works, because Git doesn't introduce .git folders in all its subfolders (as SVN does).
After dealing alot with SVN since long time, I'm finally thinking to move my developers and me to Git, since it is easy to collaborate and merge work, as well as one great advantage is that a local copy's changes can be committed as much desired, and then finally pushed to the branch on server in one go, unlike SVN (where we have to commit the changes from time to time in the repository on server).
Anyone who can help me decide if I should really go with Git?
CSS3 Transition not working
HTML:
<div class="foo">
/* whatever is required */
</div>
CSS:
.foo {
top: 0;
transition: top ease 0.5s;
}
.foo:hover{
top: -10px;
}
This is just a basic transition to ease the div tag up by 10px when it is hovered on.
The transition property's values can be edited along with the class.hover properties to determine how the transition works.
Lodash - difference between .extend() / .assign() and .merge()
Here's how extend
/assign
works: For each property in source, copy its value as-is to destination. if property values themselves are objects, there is no recursive traversal of their properties. Entire object would be taken from source and set in to destination.
Here's how merge
works: For each property in source, check if that property is object itself. If it is then go down recursively and try to map child object properties from source to destination. So essentially we merge object hierarchy from source to destination. While for extend
/assign
, it's simple one level copy of properties from source to destination.
Here's simple JSBin that would make this crystal clear:
http://jsbin.com/uXaqIMa/2/edit?js,console
Here's more elaborate version that includes array in the example as well:
http://jsbin.com/uXaqIMa/1/edit?js,console
How to find third or n?? maximum salary from salary table?
To query the nth highest bonus
, say n=10
, using AdventureWorks2012, Try Following code
USE AdventureWorks2012;
GO
SELECT * FROM Sales.SalesPerson;
GO
DECLARE @grade INT;
SET @grade = 10;
SELECT MIN(Bonus)
FROM (SELECT TOP (@grade) Bonus FROM (SELECT DISTINCT(Bonus) FROM Sales.SalesPerson) AS a ORDER BY Bonus DESC) AS g
In SQL how to compare date values?
Uh, WHERE mydate<='2008-11-25'
is the way to do it. That should work.
Do you get an error message? Are you using an ancient version of MySQL?
Edit: The following works fine for me on MySQL 5.x
create temporary table foo(d datetime);
insert into foo(d) VALUES ('2000-01-01');
insert into foo(d) VALUES ('2001-01-01');
select * from foo where d <= '2000-06-01';
Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?
Because pypy is not 100% compatible, takes 8 gigs of ram to compile, is a moving target, and highly experimental, where cpython is stable, the default target for module builders for 2 decades (including c extensions that don't work on pypy), and already widely deployed.
Pypy will likely never be the reference implementation, but it is a good tool to have.
How to center cards in bootstrap 4?
You can also use Bootstrap 4 flex classes
Like: .align-item-center
and .justify-content-center
We can use these classes identically for all device view.
Like: .align-item-sm-center, .align-item-md-center, .justify-content-xl-center, .justify-content-lg-center, .justify-content-xs-center
.text-center class is used to align text in center.
How to convert any Object to String?
I am try to convert Object type variable into string using this line of code
try this to convert object value to string:
Java Code
Object dataobject=value;
//convert object into String
String convert= String.valueOf(dataobject);
mean() warning: argument is not numeric or logical: returning NA
If you just want to know the mean, you can use
summary(results)
It will give you more information than expected.
ex) Mininum value, 1st Qu., Median, Mean, 3rd Qu. Maxinum value, number of NAs.
Furthermore, If you want to get mean values of each column, you can simply use the method below.
mean(results$columnName, na.rm = TRUE)
That will return mean value. (you have to change 'columnName' to your variable name
How best to read a File into List<string>
//this is only good in .NET 4
//read your file:
List<string> ReadFile = File.ReadAllLines(@"C:\TEMP\FILE.TXT").ToList();
//manipulate data here
foreach(string line in ReadFile)
{
//do something here
}
//write back to your file:
File.WriteAllLines(@"C:\TEMP\FILE2.TXT", ReadFile);
How to merge multiple dicts with same key or different key?
This function merges two dicts even if the keys in the two dictionaries are different:
def combine_dict(d1, d2):
combined = {}
for k in set(d1.keys()) | set(d2.keys()):
combined[k] = tuple(d[k] for d in [d1, d2] if k in d)
return combined
Example:
d1 = {
'a': 1,
'b': 2,
}
d2` = {
'b': 'boat',
'c': 'car',
}
combine_dict(d1, d2)
# Returns: {
# 'a': (1,),
# 'b': (2, 'boat'),
# 'c': ('car',)
# }
How do I search for files in Visual Studio Code?
Win: CTRL+P or CTRL+E
Mac: CMD+P or CMD+E
Don't want to remember another shortcut?
Open the Command Palette:
- Menu: View -> Command Palette
- Windows Shortcut: Ctrl+Shift+P
and hit backspace to delete ">" character and then begin typing to search for files via filename. :)
Spring: How to get parameters from POST body?
You can get param from request.
@ResponseBody
public ResponseEntity<Boolean> saveData(HttpServletRequest request,
HttpServletResponse response, Model model){
String jsonString = request.getParameter("json");
}
pandas dataframe groupby datetime month
Slightly alternative solution to @jpp's but outputting a YearMonth
string:
df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))
res = df.groupby('YearMonth')['Values'].sum()
null vs empty string in Oracle
In oracle an empty varchar2 and null are treated the same, and your observations show that.
when you write:
select * from table where a = '';
its the same as writing
select * from table where a = null;
and not a is null
which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)
select count(*) from select
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
C# Connecting Through Proxy
Automatic proxy detection is a process by which a Web proxy server is identified by the
system and used to send requests on behalf of the client. This feature is also known as
Web Proxy Auto-Discovery (WPAD). When automatic proxy detection is enabled, the system
attempts to locate a proxy configuration script that is responsible for returning the set of proxies that can be used for the request.
http://msdn.microsoft.com/en-us/library/fze2ytx2.aspx
PermGen elimination in JDK 8
The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace.The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError
: PermGen error.
The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace. Read More>>
How to get CRON to call in the correct PATHs
You should put full paths in your crontab
. That's the safest option.
If you don't want to do that you can put a wrapper script around your programs, and set the PATH in there.
e.g.
01 01 * * * command
becomes:
01 01 * * * /full/path/to/command
Also anything called from cron
should be be very careful about the programs it runs, and probably set its own choice for the PATH
variable.
EDIT:
If you don't know where the command is that you want execute which <command>
from your shell and it'll tell you the path.
EDIT2:
So once your program is running, the first thing it should do is set PATH
and any other required variable (e.g. LD_LIBRARY_PATH
) to the values that are required for the script to run.
Basically instead of thinking how to modify the cron environment to make it more suitable for your program/script - make your script handle the environment it's given, by setting an appropriate one when it starts.
pandas dataframe convert column type to string or categorical
With pandas >= 1.0 there is now a dedicated string datatype:
1) You can convert your column to this pandas string datatype using .astype('string'):
df['zipcode'] = df['zipcode'].astype('string')
2) This is different from using str
which sets the pandas object datatype:
df['zipcode'] = df['zipcode'].astype(str)
3) For changing into categorical datatype use:
df['zipcode'] = df['zipcode'].astype('category')
You can see this difference in datatypes when you look at the info of the dataframe:
df = pd.DataFrame({
'zipcode_str': [90210, 90211] ,
'zipcode_string': [90210, 90211],
'zipcode_category': [90210, 90211],
})
df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')
df.info()
# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 zipcode_str 2 non-null object
1 zipcode_string 2 non-null string
2 zipcode_category 2 non-null category
dtypes: category(1), object(1), string(1)
From the docs:
The 'string' extension type solves several issues with object-dtype
NumPy arrays:
You can accidentally store a mixture of strings and non-strings in an
object dtype array. A StringArray can only store strings.
object dtype breaks dtype-specific operations like
DataFrame.select_dtypes(). There isn’t a clear way to select just text
while excluding non-text, but still object-dtype columns.
When reading code, the contents of an object dtype array is less clear
than string.
More info on working with the new string datatype can be found here:
https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html
Getting the screen resolution using PHP
You can't do it with pure PHP. You must do it with JavaScript. There are several articles written on how to do this.
Essentially, you can set a cookie or you can even do some Ajax to send the info to a PHP script. If you use jQuery, you can do it something like this:
jquery:
$(function() {
$.post('some_script.php', { width: screen.width, height:screen.height }, function(json) {
if(json.outcome == 'success') {
// do something with the knowledge possibly?
} else {
alert('Unable to let PHP know what the screen resolution is!');
}
},'json');
});
PHP (some_script.php)
<?php
// For instance, you can do something like this:
if(isset($_POST['width']) && isset($_POST['height'])) {
$_SESSION['screen_width'] = $_POST['width'];
$_SESSION['screen_height'] = $_POST['height'];
echo json_encode(array('outcome'=>'success'));
} else {
echo json_encode(array('outcome'=>'error','error'=>"Couldn't save dimension info"));
}
?>
All that is really basic but it should get you somewhere. Normally screen resolution is not what you really want though. You may be more interested in the size of the actual browser's view port since that is actually where the page is rendered...
Regex for checking if a string is strictly alphanumeric
See the documentation of Pattern.
Assuming US-ASCII alphabet (a-z, A-Z), you could use \p{Alnum}
.
A regex to check that a line contains only such characters is "^[\\p{Alnum}]*$"
.
That also matches empty string. To exclude empty string: "^[\\p{Alnum}]+$"
.
read file from assets
The Scanner class may simplify this.
StringBuilder sb=new StringBuilder();
Scanner scanner=null;
try {
scanner=new Scanner(getAssets().open("text.txt"));
while(scanner.hasNextLine()){
sb.append(scanner.nextLine());
sb.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(scanner!=null){try{scanner.close();}catch (Exception e){}}
}
mTextView.setText(sb.toString());
IBOutlet and IBAction
You need to use IBOutlet and IBAction if you are using interface builder (hence the IB prefix) for your GUI components. IBOutlet is needed to associate properties in your application with components in IB, and IBAction is used to allow your methods to be associated with actions in IB.
For example, suppose you define a button and label in IB. To dynamically change the value of the label by pushing the button, you will define an action and property in your app similar to:
UILabel IBOutlet *myLabel;
- (IBAction)pushme:(id)sender;
Then in IB you would connect myLabel with the label and connect the pushme method with the button. You need IBAction and IBOutlet for these connections to exist in IB.
How to remove empty lines with or without whitespace in Python
Try list comprehension and string.strip()
:
>>> mystr = "L1\nL2\n\nL3\nL4\n \n\nL5"
>>> mystr.split('\n')
['L1', 'L2', '', 'L3', 'L4', ' ', '', 'L5']
>>> [line for line in mystr.split('\n') if line.strip() != '']
['L1', 'L2', 'L3', 'L4', 'L5']
How to access the local Django webserver from outside world
For AWS users.
I had to use the following steps to get there.
1) Ensure that pip and django are installed at the sudo level
- sudo apt-get install python-pip
- sudo pip install django
2) Ensure that security group in-bound rules includ http on port 80 for 0.0.0.0/0
- configured through AWS console
3) Add Public IP and DNS to ALLOWED_HOSTS
- ALLOWED_HOSTS is a list object that you can find in settings.py
- ALLOWED_HOSTS = ["75.254.65.19","ec2-54-528-27-21.compute-1.amazonaws.com"]
4) Launch development server with sudo on port 80
- sudo python manage.py runserver 0:80
Site now available at either of the following (no need for :80 as that is default for http):
- [Public DNS] i.e. ec2-54-528-27-21.compute-1.amazonaws.com
- [Public IP] i.e 75.254.65.19
XSLT counting elements with a given value
Your xpath is just a little off:
count(//Property/long[text()=$parPropId])
Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId]
than the text() xpath, though you could make a case for the latter on readability grounds.
What can I say, I'm a bit tired today :)
What is the difference between printf() and puts() in C?
int puts(const char *s);
puts() writes the string s and a trailing newline to stdout.
int printf(const char *format, ...);
The function printf() writes output to stdout, under the control of a format string that specifies how subsequent arguments are converted for output.
I'll use this opportunity to ask you to read the documentation.
Regular expression to stop at first match
import regex
text = 'ask her to call Mary back when she comes back'
p = r'(?i)(?s)call(.*?)back'
for match in regex.finditer(p, str(text)):
print (match.group(1))
Output:
Mary
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
How to properly stop the Thread in Java?
Typically, a thread is terminated when it's interrupted. So, why not use the native boolean? Try isInterrupted():
Thread t = new Thread(new Runnable(){
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
// do stuff
}
}});
t.start();
// Sleep a second, and then interrupt
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
t.interrupt();
ref- How can I kill a thread? without using stop();
Is it safe to clean docker/overlay2/
I found this worked best for me:
docker image prune --all
By default Docker will not remove named images, even if they are unused. This command will remove unused images.
Note each layer in an image is a folder inside the /usr/lib/docker/overlay2/
folder.
How to switch text case in visual studio code
Quoted from this post:
The question is about how to make CTRL+SHIFT+U work in Visual Studio
Code. Here is how to do it. (Version 1.8.1 or above). You can also choose a different key combination.
File-> Preferences -> Keyboard Shortcuts.
An editor will appear with keybindings.json
file. Place the following
JSON in there and save.
[
{
"key": "ctrl+shift+u",
"command": "editor.action.transformToUppercase",
"when": "editorTextFocus"
},
{
"key": "ctrl+shift+l",
"command": "editor.action.transformToLowercase",
"when": "editorTextFocus"
}
]
Now CTRL+SHIFT+U will capitalise selected text, even if multi line. In
the same way, CTRL+SHIFT+L will make selected text lowercase.
These commands are built into VS Code, and no extensions are required
to make them work.
How do I mock a static method that returns void with PowerMock?
You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources
will throw the exception :
// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception
Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.
By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.
Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.
Hope that helps.
Regards
How to Parse a JSON Object In Android
JSONArray jsonArray = new JSONArray(yourJsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj1 = jsonArray.getJSONObject(i);
JSONArray results = patient.getJSONArray("results");
String indexForPhone = patientProfile.getJSONObject(0).getString("indexForPhone"));
}
Change to JSONArray, then convert to JSONObject.
Remove Server Response Header IIS7
I had researched this and the URLRewrite method works well. Can't seem to find the change scripted anywhere well. I wrote this compatible with PowerShell v2 and above and tested it on IIS 7.5.
# Add Allowed Server Variable
Add-WebConfiguration /system.webServer/rewrite/allowedServerVariables -atIndex 0 -value @{name="RESPONSE_SERVER"}
# Rule Name
$ruleName = "Remove Server Response Header"
# Add outbound IIS Rewrite Rule
Add-WebConfigurationProperty -pspath "iis:\" -filter "system.webServer/rewrite/outboundrules" -name "." -value @{name=$ruleName; stopProcessing='False'}
#Set Properties of newly created outbound rule
Set-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST" -filter "system.webServer/rewrite/outboundRules/rule[@name='$ruleName']/match" -name "serverVariable" -value "RESPONSE_SERVER"
Set-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST" -filter "system.webServer/rewrite/outboundRules/rule[@name='$ruleName']/match" -name "pattern" -value ".*"
Set-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST" -filter "system.webServer/rewrite/outboundRules/rule[@name='$ruleName']/action" -name "type" -value "Rewrite"
Difference between Xms and Xmx and XX:MaxPermSize
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
References:
How is the java memory pool divided?
What is perm space?
Java (JVM) Memory Model – Memory Management in Java
Java 7 SE Command Line Options
Java 7 HotSpot VM Options
How should I escape commas and speech marks in CSV files so they work in Excel?
We eventually found the answer to this.
Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...
Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."
... fixed the problem. Hope this helps someone!
Reading e-mails from Outlook with Python through MAPI
I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)
class CheckMailer:
def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
self.f = FileWriter(filename)
self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
self.inbox = self.outlook.Folders(folderindex)
def check(self):
#===============================================================================
# for i in xrange(1,100): #Uncomment this section if index 3 does not work for you
# try:
# self.inbox = self.outlook.Folders(i) # "6" refers to the index of inbox for Default User Mailbox
# print "%i %s" % (i,self.inbox) # "3" refers to the index of inbox for Another user's mailbox
# except:
# print "%i does not work"%i
#===============================================================================
self.f.pl(time.strftime("%H:%M:%S"))
tot = 0
messages = self.inbox.Items
message = messages.GetFirst()
while message:
self.f.pl (message.Subject)
message = messages.GetNext()
tot += 1
self.f.pl("Total Messages found: %i" % tot)
self.f.pl("-" * 80)
self.f.flush()
if __name__ == "__main__":
mail = CheckMailer()
for i in xrange(320): # this is 10.6 hours approximately
mail.check()
time.sleep(120.00)
For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because
trying to pipe UTF8 to a file in windows did not work.
class FileWriter(object):
'''
convenient file wrapper for writing to files
'''
def __init__(self, filename):
'''
Constructor
'''
self.file = open(filename, "w")
def pl(self, a_string):
str_uni = a_string.encode('utf-8')
self.file.write(str_uni)
self.file.write("\n")
def flush(self):
self.file.flush()
Hashmap with Streams in Java 8 Streams to collect value of Map
If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst
:
Optional<List> o = id1.entrySet()
.stream()
.filter( e -> e.getKey() == 1)
.map(Map.Entry::getValue)
.findFirst();
In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :
List<List> list = id1.entrySet()
.stream()
.filter(.. some predicate...)
.map(Map.Entry::getValue)
.collect(Collectors.toList());
How to implement an STL-style iterator and avoid common pitfalls?
http://www.cplusplus.com/reference/std/iterator/ has a handy chart that details the specs of § 24.2.2 of the C++11 standard. Basically, the iterators have tags that describe the valid operations, and the tags have a hierarchy. Below is purely symbolic, these classes don't actually exist as such.
iterator {
iterator(const iterator&);
~iterator();
iterator& operator=(const iterator&);
iterator& operator++(); //prefix increment
reference operator*() const;
friend void swap(iterator& lhs, iterator& rhs); //C++11 I think
};
input_iterator : public virtual iterator {
iterator operator++(int); //postfix increment
value_type operator*() const;
pointer operator->() const;
friend bool operator==(const iterator&, const iterator&);
friend bool operator!=(const iterator&, const iterator&);
};
//once an input iterator has been dereferenced, it is
//undefined to dereference one before that.
output_iterator : public virtual iterator {
reference operator*() const;
iterator operator++(int); //postfix increment
};
//dereferences may only be on the left side of an assignment
//once an output iterator has been dereferenced, it is
//undefined to dereference one before that.
forward_iterator : input_iterator, output_iterator {
forward_iterator();
};
//multiple passes allowed
bidirectional_iterator : forward_iterator {
iterator& operator--(); //prefix decrement
iterator operator--(int); //postfix decrement
};
random_access_iterator : bidirectional_iterator {
friend bool operator<(const iterator&, const iterator&);
friend bool operator>(const iterator&, const iterator&);
friend bool operator<=(const iterator&, const iterator&);
friend bool operator>=(const iterator&, const iterator&);
iterator& operator+=(size_type);
friend iterator operator+(const iterator&, size_type);
friend iterator operator+(size_type, const iterator&);
iterator& operator-=(size_type);
friend iterator operator-(const iterator&, size_type);
friend difference_type operator-(iterator, iterator);
reference operator[](size_type) const;
};
contiguous_iterator : random_access_iterator { //C++17
}; //elements are stored contiguously in memory.
You can either specialize std::iterator_traits<youriterator>
, or put the same typedefs in the iterator itself, or inherit from std::iterator
(which has these typedefs). I prefer the second option, to avoid changing things in the std
namespace, and for readability, but most people inherit from std::iterator
.
struct std::iterator_traits<youriterator> {
typedef ???? difference_type; //almost always ptrdiff_t
typedef ???? value_type; //almost always T
typedef ???? reference; //almost always T& or const T&
typedef ???? pointer; //almost always T* or const T*
typedef ???? iterator_category; //usually std::forward_iterator_tag or similar
};
Note the iterator_category should be one of std::input_iterator_tag
, std::output_iterator_tag
, std::forward_iterator_tag
, std::bidirectional_iterator_tag
, or std::random_access_iterator_tag
, depending on which requirements your iterator satisfies. Depending on your iterator, you may choose to specialize std::next
, std::prev
, std::advance
, and std::distance
as well, but this is rarely needed. In extremely rare cases you may wish to specialize std::begin
and std::end
.
Your container should probably also have a const_iterator
, which is a (possibly mutable) iterator to constant data that is similar to your iterator
except it should be implicitly constructable from a iterator
and users should be unable to modify the data. It is common for its internal pointer to be a pointer to non-constant data, and have iterator
inherit from const_iterator
so as to minimize code duplication.
My post at Writing your own STL Container has a more complete container/iterator prototype.
Bind event to right mouse click
Is contextmenu
an event?
I would use onmousedown
or onclick
then grab the MouseEvent
's button property to determine which button was pressed (0 = left, 1 = middle, 2 = right).
Set initially selected item in Select list in Angular2
The easiest way to solve this problem in Angular is to do:
In Template:
<select [ngModel]="selectedObjectIndex">
<option [value]="i" *ngFor="let object of objects; let i = index;">{{object.name}}</option>
</select>
In your class:
this.selectedObjectIndex = 1/0/your number wich item should be selected
Auto Increment after delete in MySQL
What you are trying to do is very dangerous. Think about this carefully. There is a very good reason for the default behaviour of auto increment.
Consider this:
A record is deleted in one table that has a relationship with another table. The corresponding record in the second table cannot be deleted for auditing reasons. This record becomes orphaned from the first table. If a new record is inserted into the first table, and a sequential primary key is used, this record is now linked to the orphan. Obviously, this is bad. By using an auto incremented PK, an id that has never been used before is always guaranteed. This means that orphans remain orphans, which is correct.
install cx_oracle for python
Thanks Burhan Khalid. Your advice to make a a soft link make my installation finally work.
To recap:
You need both the basic version and the SDK version of instant client
You need to set both LD_LIBRARY_PATH and ORACLE_HOME
- You need to create a soft link (ln -s libclntsh.so.12.1 libclntsh.so in my case)
None of this is documented anywhere, which is quite unbelievable and quite frustrating. I spent over 3 hours yesterday with failed builds because I didn't know to create a soft link.
How to create string with multiple spaces in JavaScript
With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:
let a = `something something`;
and to make multiline strings just press enter to create a new line, with no special characters:
let a = `something
something`;
The results are exactly the same as you write in the string.
WaitAll vs WhenAll
Task.WaitAll
blocks the current thread until everything has completed.
Task.WhenAll
returns a task which represents the action of waiting until everything has completed.
That means that from an async method, you can use:
await Task.WhenAll(tasks);
... which means your method will continue when everything's completed, but you won't tie up a thread to just hang around until that time.
Multi column forms with fieldsets
I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.
<div class="form-group">
<div class="col-sm-12">
<label for="user_login">Username</label>
<input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
</div>
</div>
Check out this demo.
Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.
<form action="#" method="post" class="form-horizontal">
Check out this demo.
When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.
How can I compile and run c# program without using visual studio?
Another option is an interesting open source project called ScriptCS. It uses some crafty techniques to allow you a development experience outside of Visual Studio while still being able to leverage NuGet to manage your dependencies. It's free, very easy to install using Chocolatey. You can check it out here http://scriptcs.net.
Another cool feature it has is the REPL from the command line. Which allows you to do stuff like this:
C:\> scriptcs
scriptcs (ctrl-c or blank to exit)
> var message = "Hello, world!";
> Console.WriteLine(message);
Hello, world!
>
C:\>
You can create C# utility "scripts" which can be anything from small system tasks, to unit tests, to full on Web APIs. In the latest release I believe they're also allowing for hosting the runtime in your own apps.
Check out it development on the GitHub page too https://github.com/scriptcs/scriptcs
How to display custom view in ActionBar?
There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .
The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.
Here're the themes:
styles.xml
<style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowShowWallpaper">true</item>
</style>
<style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
</style>
<style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
<item name="android:displayOptions">showCustom</item>
<item name="android:background">#88000000</item>
</style>
value-v19/styles.xml
<style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
<style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:
getSupportActionBar().setDisplayShowCustomEnabled(true);
How to get the size of a string in Python?
Python 3:
user225312's answer is correct:
A. To count number of characters in str
object, you can use len()
function:
>>> print(len('please anwser my question'))
25
B. To get memory size in bytes allocated to store str
object, you can use sys.getsizeof()
function
>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50
Python 2:
It gets complicated for Python 2.
A. The len()
function in Python 2 returns count of bytes allocated to store encoded characters in a str
object.
Sometimes it will be equal to character count:
>>> print(len('abc'))
3
But sometimes, it won't:
>>> print(len('???')) # String contains Cyrillic symbols
6
That's because str
can use variable-length encoding internally. So, to count characters in str
you should know which encoding your str
object is using. Then you can convert it to unicode
object and get character count:
>>> print(len('???'.decode('utf8'))) #String contains Cyrillic symbols
3
B. The sys.getsizeof()
function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object
>>> print(getsizeof('???'))
27
>>> print(getsizeof('???'.decode('utf8')))
32
What is (x & 1) and (x >>= 1)?
In addition to the answer of "dasblinkenlight" I think an example could help. I will only use 8 bits for a better understanding.
x & 1
produces a value that is either 1
or 0
, depending on the least
significant bit of x
: if the last bit is 1
, the result of x & 1
is 1
;
otherwise, it is 0
. This is a bitwise AND operation.
This is because 1
will be represented in bits as 00000001
. Only the last bit is set to 1
. Let's assume x
is 185
which will be represented in bits as 10111001
. If you apply a bitwise AND operation on x
with 1
this will be the result:
00000001
10111001
--------
00000001
The first seven bits of the operation result will be 0
after the operation and will carry no information in this case (see Logical AND operation). Because whatever the first seven bits of the operand x
were before, after the operation they will be 0
. But the last bit of the operand 1
is 1
and it will reveal if the last bit of operand x
was 0
or 1
. So in this example the result of the bitwise AND operation will be 1
because our last bit of x
is 1
. If the last bit would have been 0
, then the result would have been also 0
, indicating that the last bit of operand x
is 0
:
00000001
10111000
--------
00000000
x >>= 1
means "set x
to itself shifted by one bit to the right". The
expression evaluates to the new value of x
after the shift
Let's pick the example from above. For x >>= 1
this would be:
10111001
--------
01011100
And for left shift x <<= 1
it would be:
10111001
--------
01110010
Please pay attention to the note of user "dasblinkenlight" in regard to shifts.
Best way to "negate" an instanceof
ok just my two cents, use a is string method:
public static boolean isString(Object thing) {
return thing instanceof String;
}
public void someMethod(Object thing){
if (!isString(thing)) {
return null;
}
log.debug("my thing is valid");
}
Array to Hash Ruby
Enumerator
includes Enumerable
. Since 2.1
, Enumerable
also has a method #to_h
. That's why, we can write :-
a = ["item 1", "item 2", "item 3", "item 4"]
a.each_slice(2).to_h
# => {"item 1"=>"item 2", "item 3"=>"item 4"}
Because #each_slice
without block gives us Enumerator
, and as per the above explanation, we can call the #to_h
method on the Enumerator
object.
The simplest way to resize an UIImage?
This improvement to Paul's code will give you a sharp high res image on an iPhone with a retina display. Otherwise when scaling down it's blurry.
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
if ([[UIScreen mainScreen] scale] == 2.0) {
UIGraphicsBeginImageContextWithOptions(newSize, YES, 2.0);
} else {
UIGraphicsBeginImageContext(newSize);
}
} else {
UIGraphicsBeginImageContext(newSize);
}
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
How to insert text with single quotation sql server 2005
INSERT INTO Table1 (Column1) VALUES ('John''s')
Or you can use a stored procedure and pass the parameter as -
usp_Proc1 @Column1 = 'John''s'
If you are using an INSERT query and not a stored procedure, you'll have to escape the quote with two quotes, else its OK if you don't do it.
How to read all of Inputstream in Server Socket JAVA
The problem you have is related to TCP streaming nature.
The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.
You need to implement a loop in which you read until the whole message was received.
Let me provide an example with DataInputStream
instead of BufferedinputStream
. Something very simple to give you just an example.
Let's suppose you know beforehand the server is to send 100 Bytes of data.
In client you need to write:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
while(!end)
{
int bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == 100)
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.
The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:
- 1 Byte indicating type (For example, it could also be 2 or whatever).
- 1 Byte (or whatever) for length of message
- N Bytes for the value (N is indicated in length).
So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.
This is just a suggestion of a possible protocol. You could also get rid of "Type".
So it would be something like:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
int bytesToRead = messageByte[1];
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == bytesToRead )
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.
import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
class Test
{
public static void main(String[] args)
{
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
Socket clientSocket;
ServerSocket server;
server = new ServerSocket(30501, 100);
clientSocket = server.accept();
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);
int bytesToRead = byteBuffer.getShort();
System.out.println("About to read " + bytesToRead + " octets");
//The following code shows in detail how to read from a TCP socket
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length() == bytesToRead )
{
end = true;
}
}
//All the code in the loop can be replaced by these two lines
//in.readFully(messageByte, 0, bytesToRead);
//dataString = new String(messageByte, 0, bytesToRead);
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Can't compare naive and aware datetime.now() <= challenge.datetime_end
So the way I would solve this problem is to make sure the two datetimes are in the right timezone.
I can see that you are using datetime.now()
which will return the systems current time, with no tzinfo set.
tzinfo is the information attached to a datetime to let it know what timezone it is in. If you are using naive datetime you need to be consistent through out your system. I would highly recommend only using datetime.utcnow()
seeing as somewhere your are creating datetime that have tzinfo associated with them, what you need to do is make sure those are localized (has tzinfo associated) to the correct timezone.
Take a look at Delorean, it makes dealing with this sort of thing much easier.
How to add headers to OkHttp request interceptor?
package com.example.network.interceptors;
import androidx.annotation.NonNull;
import java.io.IOException;
import java.util.Map;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class RequestHeadersNetworkInterceptor implements Interceptor {
private final Map<String, String> headers;
public RequestHeadersNetworkInterceptor(@NonNull Map<String, String> headers) {
this.headers = headers;
}
@NonNull
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
for (Map.Entry<String, String> header : headers.entrySet()) {
if (header.getKey() == null || header.getKey().trim().isEmpty()) {
continue;
}
if (header.getValue() == null || header.getValue().trim().isEmpty()) {
builder.removeHeader(header.getKey());
} else {
builder.header(header.getKey(), header.getValue());
}
}
return chain.proceed(builder.build());
}
}
Example of usage:
httpClientBuilder.networkInterceptors().add(new RequestHeadersNetworkInterceptor(new HashMap<String, String>()
{
{
put("User-Agent", getUserAgent());
put("Accept", "application/json");
}
}));
How to update column with null value
If you want to set null value using update query set column value to NULL (without quotes)
update tablename set columnname = NULL
However, if you are directly editing field value inside mysql workbench then use (Esc + del) keystroke to insert null value into selected column
Insert data into table with result from another select query
Below is an example of such a query:
INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));
Embedding a media player in a website using HTML
<html>
<head>
<H1>
Automatically play music files on your website when a page loads
</H1>
</head>
<body>
<embed src="YourMusic.mp3" autostart="true" loop="true" width="2" height="0">
</embed>
</body>
</html>
Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers
It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin
to *
, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
Make sure that you haven't already used header
in another file, or you will get a nasty error. See the docs for more.
How to create an on/off switch with Javascript/CSS?
You can achieve this using HTML and CSS and convert a checkbox into a HTML Switch.
HTML
<div class="switch">
<input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-round" type="checkbox">
<label for="cmn-toggle-1"></label>
</div>
CSS
input.cmn-toggle-round + label {
padding: 2px;
width: 100px;
height: 30px;
background-color: #dddddd;
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-ms-border-radius: 30px;
-o-border-radius: 30px;
border-radius: 30px;
}
input.cmn-toggle-round + label:before, input.cmn-toggle-round + label:after {
display: block;
position: absolute;
top: 1px;
left: 1px;
bottom: 1px;
content: "";
}
input.cmn-toggle-round + label:before {
right: 1px;
background-color: #f1f1f1;
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-ms-border-radius: 30px;
-o-border-radius: 30px;
border-radius: 30px;
-webkit-transition: background 0.4s;
-moz-transition: background 0.4s;
-o-transition: background 0.4s;
transition: background 0.4s;
}
input.cmn-toggle-round + label:after {
width: 40px;
background-color: #fff;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
-ms-border-radius: 100%;
-o-border-radius: 100%;
border-radius: 100%;
-webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
-webkit-transition: margin 0.4s;
-moz-transition: margin 0.4s;
-o-transition: margin 0.4s;
transition: margin 0.4s;
}
input.cmn-toggle-round:checked + label:before {
background-color: #8ce196;
}
input.cmn-toggle-round:checked + label:after {
margin-left: 60px;
}
.cmn-toggle {
position: absolute;
margin-left: -9999px;
visibility: hidden;
}
.cmn-toggle + label {
display: block;
position: relative;
cursor: pointer;
outline: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
DEMO
Cancel split window in Vim
The command :hide will hide the currently focused window. I think this is the functionality you are looking for.
In order to navigate between windows type Ctrl+w followed by a navigation key (h,j,k,l, or arrow keys)
For more information run :help window
and :help hide
in vim.
What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion
1. Solution
Open Sublime Text console ? paste in opened field:
sublime.packages_path()
? Enter. You get result in console output.
2. Relevance
This answer is relevant for April 2018. In the future, the data of this answer may be obsolete.
3. Not recommended
I'm not recommended @osiris answer. Arguments:
- In new versions of Sublime Text and/or operating systems (e.g. Sublime Text 4, macOS 14) paths may be changed.
- It doesn't take portable Sublime Text on Windows. In portable Sublime Text on Windows another path of
Packages
folder.
- It less simple.
4. Additional link
Open a selected file (image, pdf, ...) programmatically from my Android Application?
Download source code from here (https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/)
activity_main.xml:
<?xml version=”1.0" encoding=”utf-8"?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:id=”@+id/activity_main”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”#efefef”>
<ListView
android:layout_width=”match_parent”
android:id=”@+id/lv_pdf”
android:divider=”#efefef”
android:layout_marginLeft=”10dp”
android:layout_marginRight=”10dp”
android:layout_marginTop=”10dp”
android:layout_marginBottom=”10dp”
android:dividerHeight=”5dp”
android:layout_height=”wrap_content”>
</ListView>
</RelativeLayout>
MainActivity.java:
package com.pdffilefromsdcard;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);
Log.e(“Position”, i + “”);
}
});
}
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
} else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {
}
}
if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
} else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();
}
}
}
}
activity_pdf.xml:
<?xml version=”1.0" encoding=”utf-8"?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:background=”#ffffff”
android:layout_height=”match_parent”
android:orientation=”vertical”>
<com.github.barteksc.pdfviewer.PDFView
android:id=”@+id/pdfView”
android:layout_margin=”10dp”
android:layout_width=”match_parent”
android:layout_height=”match_parent” />
</LinearLayout>
PdfActivity.java:
package com.pdffilefromsdcard;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.io.File;
import java.util.List;
public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}
Thanks!
Update .NET web service to use TLS 1.2
Add the following code before you instantiate your web service client:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Or for backward compatibility with TLS 1.1 and prior:
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
Static variables in JavaScript
Window level vars are sorta like statics in the sense that you can use direct reference and these are available to all parts of your app
Javascript: Extend a Function
Another option could be:
var initial = function() {
console.log( 'initial function!' );
}
var iWantToExecuteThisOneToo = function () {
console.log( 'the other function that i wanted to execute!' );
}
function extendFunction( oldOne, newOne ) {
return (function() {
oldOne();
newOne();
})();
}
var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );
Image resizing in React Native
{ flex: 1, height: undefined, width: undefined, resizeMode: 'contain' }
If you are using these attributes in your style prop in the <Image />
and the image is disappeared.
Put your image into a <View>
tag. Like this:
<View
style={{
width: '100%',
height: '30%'
}}
>
<Image
source={require('../logo.png')}
style={{
flex: 1,
height: undefined,
width: undefined,
resizeMode: 'contain'
}}
resizeMode={'cover'}
/>
</View>
Give your view the width and height you want.
gcc: undefined reference to
Are you mixing C and C++? One issue that can occur is that the declarations in the .h
file for a .c
file need to be surrounded by:
#if defined(__cplusplus)
extern "C" { // Make sure we have C-declarations in C++ programs
#endif
and:
#if defined(__cplusplus)
}
#endif
Note: if unable / unwilling to modify the .h
file(s) in question, you can surround their inclusion with extern "C"
:
extern "C" {
#include <abc.h>
} //extern
Query based on multiple where clauses in Firebase
var ref = new Firebase('https://your.firebaseio.com/');
Query query = ref.orderByChild('genre').equalTo('comedy');
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
Movie movie = dataSnapshot.getValue(Movie.class);
if (movie.getLead().equals('Jack Nicholson')) {
console.log(movieSnapshot.getKey());
}
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds
nothing new but still want to share my method:
+(NSString*) getDateStringFromSrcFormat:(NSString *) srcFormat destFormat:(NSString *)
destFormat scrString:(NSString *) srcString
{
NSString *dateString = srcString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[dateFormatter setDateFormat:@"MM-dd-yyyy"];
[dateFormatter setDateFormat:srcFormat];
NSDate *date = [dateFormatter dateFromString:dateString];
// Convert date object into desired format
//[dateFormatter setDateFormat:@"yyyy-MM-dd"];
[dateFormatter setDateFormat:destFormat];
NSString *newDateString = [dateFormatter stringFromDate:date];
return newDateString;
}
Basic authentication with fetch?
NODE USERS (REACT,EXPRESS) FOLLOW THESE STEPS
npm install base-64 --save
import { encode } from "base-64";
const response = await fetch(URL, {
method: 'post',
headers: new Headers({
'Authorization': 'Basic ' + encode(username + ":" + password),
'Content-Type': 'application/json'
}),
body: JSON.stringify({
"PassengerMobile": "xxxxxxxxxxxx",
"Password": "xxxxxxx"
})
});
const posts = await response.json();
Don't forget to define this whole function as async
I want to execute shell commands from Maven's pom.xml
Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>pip</executable>
<arguments><argument>install</argument></arguments>
<workingDirectory>${project.build.directory}/Demo</workingDirectory>
</configuration>
How do I express "if value is not empty" in the VBA language?
It depends on what you want to test:
- for a string, you can use
If strName = vbNullString
or IF strName = ""
or Len(strName) = 0
(last one being supposedly faster)
- for an object, you can use
If myObject is Nothing
- for a recordset field, you could use
If isnull(rs!myField)
- for an Excel cell, you could use
If range("B3") = ""
or IsEmpty(myRange)
Extended discussion available here (for Access, but most of it works for Excel as well).
Oracle: is there a tool to trace queries, like Profiler for sql server?
Oracle, along with other databases, analyzes a given query to create an execution plan. This plan is the most efficient way of retrieving the data.
Oracle provides the 'explain plan
' statement which analyzes the query but doesn't run it, instead populating a special table that you can query (the plan table).
The syntax (simple version, there are other options such as to mark the rows in the plan table with a special ID, or use a different plan table) is:
explain plan for <sql query>
The analysis of that data is left for another question, or your further research.
ORA-00918: column ambiguously defined in SELECT *
You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:
SELECT DISTINCT
coaches.id,
people.*,
users.*,
coaches.*
FROM "COACHES"
INNER JOIN people ON people.id = coaches.person_id
INNER JOIN users ON coaches.person_id = users.person_id
LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
rownum <= 25
It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.
Cannot find Dumpbin.exe
You probably need to open a command prompt with the PATH set up properly. Look for an icon in the start menu that says something like "Visual C++ 2005 Command Prompt". You should be able to run dumpbin (and all the other command line tools) from there.
How to Add Date Picker To VBA UserForm
Just throw some light in to some issues related to this control.
Date picker is not a standard control that comes with office package. So developers encountered issues like missing date picker controls when application deployed in some other machiens/versions of office. In order to use it you have to activate the reference to the .dll, .ocx file that contains it.
In the event of a missing date picker, you have to replace MSCOMCT2.OCX file in System or System32 directory and register it properly. Try this link to do the proper replacement of the file.
In the VBA editor menu bar-> select tools-> references and then find the date picker reference and check it.
If you need the file, download MSCOMCT2.OCX from here.
Iterating over arrays in Python 3
When you loop in an array like you did, your for variable(in this example i
) is current element of your array.
For example if your ar
is [1,5,10]
, the i
value in each iteration is 1
, 5
, and 10
.
And because your array length is 3, the maximum index you can use is 2. so when i = 5
you get IndexError
.
You should change your code into something like this:
for i in ar:
theSum = theSum + i
Or if you want to use indexes, you should create a range from 0 ro array length - 1
.
for i in range(len(ar)):
theSum = theSum + ar[i]
Import an existing git project into GitLab?
You create an empty project in gitlab then on your local terminal follow one of these:
Push an existing folder
cd existing_folder
git init
git remote add origin [email protected]:GITLABUSERNAME/YOURGITPROJECTNAME.git
git add .
git commit -m "Initial commit"
git push -u origin master
Push an existing Git repository
cd existing_repo
git remote rename origin old-origin
git remote add origin [email protected]:GITLABUSERNAME/YOURGITPROJECTNAME.git
git push -u origin --all
git push -u origin --tags
A completely free agile software process tool
Trello.com Trello is free for unlimited users. Period.
You almost definitely don't need "Sub-cards". Use the checklists instead, or if you REALLY need sub-cards, don't have a parent sub-card. Just name the tickets something like "Epic - Story A" or "Story - task Z" or whatever.
Another idea is to create two boards (did I mention you can have unlimited boards for free too?). One for your epics and one for your stories. Call one your product management board and the other your sprint board, or whatever you like.
I'm not sure what you need different roles for - but, people aren't crazy - they know their job. As a startup if you already have problems getting people to not do crazy things (Where you need to restrict their permissions) you have much much bigger issues.
The point is that you need a SMALL tool to help you track stuff. Not a super rigid tool that makes you work in a super specific way. As a new (I assume?) startup, you should let your process grow into a tool. Don't beef up your process to fit a tool.
How to close form
new WindowSettings();
You just closed a brand new instance of the form that wasn't visible in the first place.
You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.
How can I see function arguments in IPython Notebook Server 3?
Try Shift-Tab-Tab
a bigger documentation appears, than with Shift-Tab
. It's the same but you can scroll down.
Shift-Tab-Tab-Tab
and the tooltip will linger for 10 seconds while you type.
Shift-Tab-Tab-Tab-Tab
and the docstring appears in the pager (small part at the bottom of the window) and stays there.
What is middleware exactly?
Lets say your company makes 4 different products, your client has another 3 different products from another 3 different companies.
Someday the client thought, why don't we integrate all our systems into one huge system. Ten minutes later their IT department said that will take 2 years.
You (the wise developer) said, why don't we just integrate all the different systems and make them work together in a homogeneous environment? The client manager staring at you... You continued, we will use a Middleware, we will study the Inputs/Outputs of all different systems, the resources they use and then choose an appropriate Middleware framework.
Still explaining to the non tech manager
With Middleware framework in the middle, the first system will produce X stuff, the system Y and Z would consume those outputs and so on.
How can I access iframe elements with Javascript?
If you have the HTML
<form name="formname" .... id="form-first">
<iframe id="one" src="iframe2.html">
</iframe>
</form>
and JavaScript
function iframeRef( frameRef ) {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument
}
var inside = iframeRef( document.getElementById('one') )
inside
is now a reference to the document, so you can do getElementsByTagName('textarea')
and whatever you like, depending on what's inside the iframe src.
Count table rows
Because nobody mentioned it:
show table status;
lists all tables along with some additional information, including estimated rows for each table. This is what phpMyAdmin is using for its database page.
This information is available in MySQL 4, probably in MySQL 3.23 too - long time prior information schema database.
UPDATE:
Because there was down-vote, I want to clarify that the number shown is estimated for InnoDB and TokuDB and it is absolutely correct for MyISAM and Aria (Maria) storage engines.
Per the documentation:
The number of rows. Some storage engines, such as MyISAM, store the
exact count. For other storage engines, such as InnoDB, this value is
an approximation, and may vary from the actual value by as much as 40%
to 50%. In such cases, use SELECT COUNT(*) to obtain an accurate
count.
This also is fastest way to see the row count on MySQL, because query like:
select count(*) from table;
Doing full table scan what could be very expensive operation that might take hours on large high load server. It also increase disk I/O.
The same operation might block the table for inserts and updates - this happen only on exotic storage engines.
InnoDB and TokuDB are OK with table lock, but need full table scan.
Set HTTP header for one request
There's a headers parameter in the config object you pass to $http
for per-call headers:
$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
Or with the shortcut method:
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
The list of the valid parameters is available in the $http service documentation.
Do while loop in SQL Server 2008
You can also use an exit variable if you want your code to be a bit more readable:
DECLARE @Flag int = 0
DECLARE @Done bit = 0
WHILE @Done = 0 BEGIN
SET @Flag = @Flag + 1
PRINT @Flag
IF @Flag >= 5 SET @Done = 1
END
This would probably be more relevant when you have a more complicated loop and are trying to keep track of the logic. As stated loops are expensive so try and use other methods if you can.
Insert all data of a datagridview to database at once
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ID_Proof;Integrated Security=True");
SqlCommand cmd = new SqlCommand("INSERT INTO Restaurant (Customer_Name,Quantity,Price,Category,Subcategory,Item,Room_No,Tax,Service_Charge,Service_Tax,Order_Time) values (@customer,@quantity,@price,@category,@subcategory,@item,@roomno,@tax,@servicecharge,@sertax,@ordertime)", con);
cmd.Parameters.AddWithValue("@customer",dataGridView2.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("@quantity",dataGridView2.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("@price",dataGridView2.Rows[i].Cells[2].Value);
cmd.Parameters.AddWithValue("@category",dataGridView2.Rows[i].Cells[3].Value);
cmd.Parameters.AddWithValue("@subcategory",dataGridView2.Rows[i].Cells[4].Value);
cmd.Parameters.AddWithValue("@item",dataGridView2.Rows[i].Cells[5].Value);
cmd.Parameters.AddWithValue("@roomno",dataGridView2.Rows[i].Cells[6].Value);
cmd.Parameters.AddWithValue("@tax",dataGridView2.Rows[i].Cells[7].Value);
cmd.Parameters.AddWithValue("@servicecharge",dataGridView2.Rows[i].Cells[8].Value);
cmd.Parameters.AddWithValue("@sertax",dataGridView2.Rows[i].Cells[9].Value);
cmd.Parameters.AddWithValue("@ordertime",dataGridView2.Rows[i].Cells[10].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Added successfully!");
Examples for string find in Python
Honestly, this is the sort of situation where I just open up Python on the command line and start messing around:
>>> x = "Dana Larose is playing with find()"
>>> x.find("Dana")
0
>>> x.find("ana")
1
>>> x.find("La")
5
>>> x.find("La", 6)
-1
Python's interpreter makes this sort of experimentation easy. (Same goes for other languages with a similar interpreter)
How to convert integer timestamp to Python datetime
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
AngularJS + JQuery : How to get dynamic content working in angularjs
Addition to @jwize's answer
Because angular.element(document).injector()
was giving error injector is not defined
So, I have created function that you can run after AJAX call or when DOM is changed using jQuery.
function compileAngularElement( elSelector) {
var elSelector = (typeof elSelector == 'string') ? elSelector : null ;
// The new element to be added
if (elSelector != null ) {
var $div = $( elSelector );
// The parent of the new element
var $target = $("[ng-app]");
angular.element($target).injector().invoke(['$compile', function ($compile) {
var $scope = angular.element($target).scope();
$compile($div)($scope);
// Finally, refresh the watch expressions in the new element
$scope.$apply();
}]);
}
}
use it by passing just new element's selector.
like this
compileAngularElement( '.user' ) ;
putting a php variable in a HTML form value
You can do it like this,
<input type="text" name="name" value="<?php echo $name;?>" />
But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.
<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />