What are carriage return, linefeed, and form feed?
As a supplement,
1, Carriage return: It's a printer terminology meaning changing the print location to the beginning of current line. In computer world, it means return to the beginning of current line in most cases but stands for new line rarely.
2, Line feed: It's a printer terminology meaning advancing the paper one line. So Carriage return and Line feed are used together to start to print at the beginning of a new line. In computer world, it generally has the same meaning as newline.
3, Form feed: It's a printer terminology, I like the explanation in this thread.
If you were programming for a 1980s-style printer, it would eject the
paper and start a new page. You are virtually certain to never need
it.
http://en.wikipedia.org/wiki/Form_feed
It's almost obsolete and you can refer to Escape sequence \f - form feed - what exactly is it? for detailed explanation.
Note, we can use CR or LF or CRLF to stand for newline in some platforms but newline can't be stood by them in some other platforms. Refer to wiki Newline for details.
LF: Multics, Unix and Unix-like systems (Linux, OS X, FreeBSD, AIX,
Xenix, etc.), BeOS, Amiga, RISC OS, and others
CR: Commodore 8-bit machines, Acorn BBC, ZX Spectrum, TRS-80, Apple
II family, Oberon, the classic Mac OS up to version 9, MIT Lisp
Machine and OS-9
RS: QNX pre-POSIX implementation
0x9B: Atari 8-bit machines using ATASCII variant of ASCII (155 in
decimal)
CR+LF: Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10,
RT-11, CP/M, MP/M, Atari TOS, OS/2, Symbian OS, Palm OS, Amstrad CPC,
and most other early non-Unix and non-IBM OSes
LF+CR: Acorn BBC and RISC OS spooled text output.
Display alert message and redirect after click on accept
Combining CodeIgniter and JavaScript:
//for using the base_url() function
$this->load->helper('url');
echo "<script type='javascript/text'>";
echo "alert('There are no fields to generate a report');"
echo "window.location.href = '" . base_url() . "admin/ahm/panel';"
echo "</script>";
Note: The redirect()
function automatically includes the base_url
path that is why it wasn't required there.
Setting the zoom level for a MKMapView
Based on quentinadam's answer
Swift 5.1
// size refers to the width/height of your tile images, by default is 256.0
// Seems to get better results using round()
// frame.width is the width of the MKMapView
let zoom = round(log2(360 * Double(frame.width) / size / region.span.longitudeDelta))
How to reference a method in javadoc?
you can use @see
to do that:
sample:
interface View {
/**
* @return true: have read contact and call log permissions, else otherwise
* @see #requestReadContactAndCallLogPermissions()
*/
boolean haveReadContactAndCallLogPermissions();
/**
* if not have permissions, request to user for allow
* @see #haveReadContactAndCallLogPermissions()
*/
void requestReadContactAndCallLogPermissions();
}
How to reset Django admin password?
In case you do not know the usernames as created here. You can get the users as described by @FallenAngel above.
python manage.py shell
from django.contrib.auth.models import User
usrs = User.objects.filter(is_superuser=True)
#identify the user
your_user = usrs.filter(username="yourusername")[0]
#youruser = usrs.get(username="yourusername")
#then set the password
However in the event that you created your independent user model. A simple case is when you want to use email as a username instead of the default user name. In which case your user model lives somewhere such as your_accounts_app.models then the above solution wont work.
In this case you can instead use the get_user_model method
from django.contrib.auth import get_user_model
super_users = get_user_model().objects.filter(is_superuser=True)
#proceed to get identify your user
# and set their user password
Constructor of an abstract class in C#
There are two following important features that prevent to inherit Abstract class
Abstract class must have an abstract method otherwise it is not a abstract class
Abstract class must be inherited by derived class,So if a class inherited by other class than what is use of to create object of that class
conversion from string to json object android
Here is the code, and you can decide which
(synchronized)StringBuffer or
faster StringBuilder to use.
Benchmark shows StringBuilder is Faster.
public class Main {
int times = 777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
sb.append("");
getJSONFromStringBuffer(String stringJSON);
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
getJSONFromStringBUilder(String stringJSON);
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
}
Any shortcut to initialize all array elements to zero?
You can create a new empty array with your existing array size, and you can assign back them to your array. This may faster than other.
Snipet:
package com.array.zero;
public class ArrayZero {
public static void main(String[] args) {
// Your array with data
int[] yourArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//Creating same sized array with 0
int[] tempArray = new int[yourArray.length];
Assigning temp array to replace values by zero [0]
yourArray = tempArray;
//testing the array size and value to be zero
for (int item : yourArray) {
System.out.println(item);
}
}
}
Result :
0
0
0
0
0
0
0
0
0
Why am I getting tree conflicts in Subversion?
What's happening here is the following: You create a new file on your trunk, then you merge it into your branch. In the merge commit this file will be created in your branch also.
When you merge your branch back into the trunk, SVN tries to do the same again: It sees that a file was created in your branch, and tries to create it in your trunk in the merge commit, but it already exists! This creates a tree conflict.
The way to avoid this, is to do a special merge, a reintegration. You can achieve this with the --reintegrate
switch.
You can read about this in the documentation:
http://svnbook.red-bean.com/en/1.7/svn.branchmerge.basicmerging.html#svn.branchemerge.basicmerging.reintegrate
When merging your branch back to the trunk, however, the underlying
mathematics are quite different. Your feature branch is now a mishmash
of both duplicated trunk changes and private branch changes, so
there's no simple contiguous range of revisions to copy over. By
specifying the --reintegrate option, you're asking Subversion to
carefully replicate only those changes unique to your branch. (And in
fact, it does this by comparing the latest trunk tree with the latest
branch tree: the resulting difference is exactly your branch changes!)
After reintegrating a branch it is highly advisable to remove it, otherwise you will keep getting treeconflicts whenever you merge in the other direction: from the trunk to your branch. (For exactly the same reason as described before.)
There is a way around this too, but I never tried it. You can read it in this post: Subversion branch reintegration in v1.6
How to get the current plugin directory in WordPress?
To get the plugin directory you can use the Wordpress function plugin_basename($file)
. So you would use is as follows to extract the folder and filename of the plugin:
$plugin_directory = plugin_basename(__FILE__);
You can combine this with the URL or the server path of the plugin directory. Therefor you can use the constants WP_PLUGIN_URL
to get the plugin directory url or WP_PLUGIN_DIR
to get the server path. But as Mark Jaquith mentioned in a comment below this only works if the plugins resides in the Wordpress plugin directory.
Read more about it in the Wordpress codex.
Group by multiple field names in java 8
The groupingBy
method has the first parameter is Function<T,K>
where:
@param <T>
the type of the input elements
@param <K>
the type of the keys
If we replace lambda with the anonymous class in your code, we can see some kind of that:
people.stream().collect(Collectors.groupingBy(new Function<Person, int>() {
@Override
public int apply(Person person) {
return person.getAge();
}
}));
Just now change output parameter<K>
. In this case, for example, I used a pair class from org.apache.commons.lang3.tuple for grouping by name and age, but you may create your own class for filtering groups as you need.
people.stream().collect(Collectors.groupingBy(new Function<Person, Pair<Integer, String>>() {
@Override
public YourFilter apply(Person person) {
return Pair.of(person.getAge(), person.getName());
}
}));
Finally, after replacing with lambda back, code looks like that:
Map<Pair<Integer,String>, List<Person>> peopleByAgeAndName = people.collect(Collectors.groupingBy(p -> Pair.of(person.getAge(), person.getName()), Collectors.mapping((Person p) -> p, toList())));
String was not recognized as a valid DateTime " format dd/MM/yyyy"
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
Deserialize from string instead TextReader
static T DeserializeXml<T>(string sourceXML) where T : class
{
var serializer = new XmlSerializer(typeof(T));
T result = null;
using (TextReader reader = new StringReader(sourceXML))
{
result = (T) serializer.Deserialize(reader);
}
return result;
}
Unix command to check the filesize
ls -l --block-size=M
will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB.
If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.
Or
ls -lah
-h
When used with the -l option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to three or less using base 2 for sizes.
man ls
http://unixhelp.ed.ac.uk/CGI/man-cgi?ls
When do we need curly braces around shell variables?
In this particular example, it makes no difference. However, the {}
in ${}
are useful if you want to expand the variable foo
in the string
"${foo}bar"
since "$foobar"
would instead expand the variable identified by foobar
.
Curly braces are also unconditionally required when:
- expanding array elements, as in
${array[42]}
- using parameter expansion operations, as in
${filename%.*}
(remove extension)
- expanding positional parameters beyond 9:
"$8 $9 ${10} ${11}"
Doing this everywhere, instead of just in potentially ambiguous cases, can be considered good programming practice. This is both for consistency and to avoid surprises like $foo_$bar.jpg
, where it's not visually obvious that the underscore becomes part of the variable name.
MySQL GROUP BY two columns
Using Concat on the group by will work
SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30
What is the difference between Java RMI and RPC?
RPC is an old protocol based on C.It can invoke a remote procedure and make it look like a local call.RPC handles the complexities of passing that remote invocation to the server and getting the result to client.
Java RMI also achieves the same thing but slightly differently.It uses references to remote objects.So, what it does is that it sends a reference to the remote object alongwith the name of the method to invoke.It is better because it results in cleaner code in case of large programs and also distribution of objects over the network enables multiple clients to invoke methods in the server instead of establishing each connection individually.
How to create a hash or dictionary object in JavaScript
You want to create an Object, not an Array.
Like so,
var Map = {};
Map['key1'] = 'value1';
Map['key2'] = 'value2';
You can check if the key exists in multiple ways:
Map.hasOwnProperty(key);
Map[key] != undefined // For illustration // Edit, remove null check
if (key in Map) ...
How do I enable EF migrations for multiple contexts to separate databases?
The 2nd call to Enable-Migrations is failing because the Configuration.cs file already exists. If you rename that class and file, you should be able to run that 2nd Enable-Migrations, which will create another Configuration.cs.
You will then need to specify which configuration you want to use when updating the databases.
Update-Database -ConfigurationTypeName MyRenamedConfiguration
Android: How to rotate a bitmap on a center point
You can use something like following:
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
RectF rectF = new RectF(0, 0, source.getWidth(), source.getHeight());
matrix.mapRect(rectF);
Bitmap targetBitmap = Bitmap.createBitmap(rectF.width(), rectF.height(), config);
Canvas canvas = new Canvas(targetBitmap);
canvas.drawBitmap(source, matrix, new Paint());
Checking if a key exists in a JS object
var obj = {
"key1" : "k1",
"key2" : "k2",
"key3" : "k3"
};
if ("key1" in obj)
console.log("has key1 in obj");
=========================================================================
To access a child key of another key
var obj = {
"key1": "k1",
"key2": "k2",
"key3": "k3",
"key4": {
"keyF": "kf"
}
};
if ("keyF" in obj.key4)
console.log("has keyF in obj");
Sending an HTTP POST request on iOS
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
This method fills html forms inside Google Forms. Hope it helps someone using Swift.
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
Why is "except: pass" a bad programming practice?
In general, you can classify any error/exception in one of three categories:
Fatal: Not your fault, you cannot prevent them, you cannot recover from them. You should certainly not ignore them and continue, and leave your program in an unknown state. Just let the error terminate your program, there is nothing you can do.
Boneheaded: Your own fault, most likely due to an oversight, bug or programming error. You should fix the bug. Again, you should most certainly not ignore and continue.
Exogenous: You can expect these errors in exceptional situations, such as file not found or connection terminated. You should explicitly handle these errors, and only these.
In all cases except: pass
will only leave your program in an unknown state, where it can cause more damage.
Populating VBA dynamic arrays
I see many (all) posts above relying on LBound
/UBound
calls upon yet potentially uninitialized VBA dynamic array, what causes application's inevitable death ...
Erratic code:
Dim x As Long
Dim arr1() As SomeType
...
x = UBound(arr1) 'crashes
Correct code:
Dim x As Long
Dim arr1() As SomeType
...
ReDim Preserve arr1(0 To 0)
...
x = UBound(arr1)
... i.e. any code where Dim arr1()
is followed immediatelly by LBound(arr1)
/UBound(arr1)
calls without ReDim arr1(...)
in between, crashes. The roundabout is to employ an On Error Resume Next
and check the Err.Number
right after the LBound(arr1)
/UBound(arr1)
call - it should be 0 if the array is initialized, otherwise non-zero. As there is some VBA built-in misbehavior, the further check of array's limits is needed. Detailed explanation may everybody read at Chip Pearson's website (which should be celebrated as a Mankind Treasure Of VBA Wisdom ...)
Heh, that's my first post, believe it is legible.
How to list imported modules?
import sys
sys.modules.keys()
An approximation of getting all imports for the current module only would be to inspect globals()
for modules:
import types
def imports():
for name, val in globals().items():
if isinstance(val, types.ModuleType):
yield val.__name__
This won't return local imports, or non-module imports like from x import y
. Note that this returns val.__name__
so you get the original module name if you used import module as alias
; yield name instead if you want the alias.
Writing to a new file if it doesn't exist, and appending to a file if it does
Notice that if the file's parent folder doesn't exist you'll get the same error:
IOError: [Errno 2] No such file or directory:
Below is another solution which handles this case:
(*) I used sys.stdout
and print
instead of f.write
just to show another use case
# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print_to_log_file(folder_path, "Some File" ,"Some Content")
Where the internal print_to_log_file
just take care of the file level:
# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):
#1) Save a reference to the original standard output
original_stdout = sys.stdout
#2) Choose the mode
write_append_mode = 'a' #Append mode
file_path = folder_path + file_name
if (if not os.path.exists(file_path) ):
write_append_mode = 'w' # Write mode
#3) Perform action on file
with open(file_path, write_append_mode) as f:
sys.stdout = f # Change the standard output to the file we created.
print(file_path, content_to_write)
sys.stdout = original_stdout # Reset the standard output to its original value
Consider the following states:
'w' --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a' --> Append to file
'a+' --> Append to file, Create it if doesn't exist
In your case I would use a different approach and just use 'a'
and 'a+'
.
How can I load storyboard programmatically from class?
In your storyboard go to the Attributes inspector and set the view controller's Identifier. You can then present that view controller using the following code.
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myViewController"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];
Add support library to Android Studio project
You can simply download the library which you want to include and copy it to libs folder of your project. Then select that file (in my case it was android-support-v4 library) right click on it and select "Add as Library"
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Remove legend ggplot 2.2
If your chart uses both fill
and color
aesthetics, you can remove the legend with:
+ guides(fill=FALSE, color=FALSE)
Do you use source control for your database items?
We version and source control everything surrounding our databases:
- DDL (create and alters)
- DML (reference data, codes, etc.)
- Data Model changes (using ERwin or ER/Studio)
- Database configuration changes (permissions, security objects, general config changes)
We do all this with automated jobs using Change Manager and some custom scripts. We have Change Manager monitoring these changes and notifying when they are done.
Cannot construct instance of - Jackson
You need to use a concrete class and not an Abstract class while deserializing.
if the Abstract class has several implementations then, in that case, you can use it as below-
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = Bike.class, name = "bike"),
@Type(value = Auto.class, name = "auto"),
@Type(value = Car.class, name = "car")
})
public abstract class Vehicle {
// fields, constructors, getters, setters
}
MYSQL import data from csv using LOAD DATA INFILE
let suppose you are using xampp and phpmyadmin
you have file name 'ratings.txt' table name 'ratings' and database name 'movies'
if your xampp is installed in "C:\xampp\"
copy your "ratings.txt" file in "C:\xampp\mysql\data\movies" folder
LOAD DATA INFILE 'ratings.txt' INTO TABLE ratings FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES;
Hope this can help you to omit your error if you are doing this on localhost
getch and arrow codes
Try this...
I am in Windows 7 with Code::Blocks
while (true)
{
char input;
input = getch();
switch(input)
{
case -32: //This value is returned by all arrow key. So, we don't want to do something.
break;
case 72:
printf("up");
break;
case 75:
printf("left");
break;
case 77:
printf("right");
break;
case 80:
printf("down");
break;
default:
printf("INVALID INPUT!");
break;
}
}
How to convert a JSON string to a Map<String, String> with Jackson JSON
[Update Sept 2020] Although my original answer here, from many years ago, seems to be helpful and is still getting upvotes, I now use the GSON library from Google, which I find to be more intuitive.
I've got the following code:
public void testJackson() throws IOException {
ObjectMapper mapper = new ObjectMapper();
File from = new File("albumnList.txt");
TypeReference<HashMap<String,Object>> typeRef
= new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> o = mapper.readValue(from, typeRef);
System.out.println("Got " + o);
}
It's reading from a file, but mapper.readValue()
will also accept an InputStream
and you can obtain an InputStream
from a string by using the following:
new ByteArrayInputStream(astring.getBytes("UTF-8"));
There's a bit more explanation about the mapper on my blog.
Regex for Mobile Number Validation
This regex is very short and sweet for working.
/^([+]\d{2})?\d{10}$/
Ex: +910123456789 or 0123456789
-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length
This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.
if you want to add the space between than you can use the
[ ]
here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex
/^([+]\d{2}[ ])?\d{10}$/
Ex: +91 0123456789
Thanks ask any question if you have.
Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()
If you look at the source code, you will see, they are calling ThreadPoolExecutor. internally and setting their properties. You can create your one to have a better control of your requirement.
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
Member '<method>' cannot be accessed with an instance reference
YourClassName.YourStaticFieldName
For your static field would look like:
public class StaticExample
{
public static double Pi = 3.14;
}
From another class, you can access the staic field as follows:
class Program
{
static void Main(string[] args)
{
double radius = 6;
double areaOfCircle = 0;
areaOfCircle = StaticExample.Pi * radius * radius;
Console.WriteLine("Area = "+areaOfCircle);
Console.ReadKey();
}
}
Executing JavaScript after X seconds
I believe you are looking for the setTimeout function.
To make your code a little neater, define a separate function for onclick in a <script>
block:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
onclick="myClick();"
Removing MySQL 5.7 Completely
First of all, do a backup of your needed databases with mysqldump
Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).
In total, do this:
sudo service mysql stop #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql
All above commands in single line (just copy and paste):
sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql
How to deep merge instead of shallow merge?
Since this issue is still active, here's another approach:
- ES6/2015
- Immutable (does not modify original objects)
- Handles arrays (concatenates them)
_x000D_
_x000D_
/**_x000D_
* Performs a deep merge of objects and returns new object. Does not modify_x000D_
* objects (immutable) and merges arrays via concatenation._x000D_
*_x000D_
* @param {...object} objects - Objects to merge_x000D_
* @returns {object} New object with merged key/values_x000D_
*/_x000D_
function mergeDeep(...objects) {_x000D_
const isObject = obj => obj && typeof obj === 'object';_x000D_
_x000D_
return objects.reduce((prev, obj) => {_x000D_
Object.keys(obj).forEach(key => {_x000D_
const pVal = prev[key];_x000D_
const oVal = obj[key];_x000D_
_x000D_
if (Array.isArray(pVal) && Array.isArray(oVal)) {_x000D_
prev[key] = pVal.concat(...oVal);_x000D_
}_x000D_
else if (isObject(pVal) && isObject(oVal)) {_x000D_
prev[key] = mergeDeep(pVal, oVal);_x000D_
}_x000D_
else {_x000D_
prev[key] = oVal;_x000D_
}_x000D_
});_x000D_
_x000D_
return prev;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
// Test objects_x000D_
const obj1 = {_x000D_
a: 1,_x000D_
b: 1, _x000D_
c: { x: 1, y: 1 },_x000D_
d: [ 1, 1 ]_x000D_
}_x000D_
const obj2 = {_x000D_
b: 2, _x000D_
c: { y: 2, z: 2 },_x000D_
d: [ 2, 2 ],_x000D_
e: 2_x000D_
}_x000D_
const obj3 = mergeDeep(obj1, obj2);_x000D_
_x000D_
// Out_x000D_
console.log(obj3);
_x000D_
_x000D_
_x000D_
Less aggressive compilation with CSS3 calc
Less no longer evaluates expression inside calc
by default since v3.00
.
Original answer (Less v1.x...2.x
):
Do this:
body { width: calc(~"100% - 250px - 1.5em"); }
In Less 1.4.0 we will have a strictMaths
option which requires all Less calculations to be within brackets, so the calc
will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.
Xcode 6 iPhone Simulator Application Support location
Open finder>Library>Developer>CoreSimulator>Devices
Then Change Arrangement icon from finder select Date Added
Select your app >data>Container>data>Applications>
choose your app >Documents>Here is your db file
In my case:
/Users/pluto/Library/Developer/CoreSimulator/Devices/A75107D2-A535-415A-865D-978B2555370B/data/Containers/Data/Application/265A12BC-FF5B-4235-B5EF-6022B83754B4/Documents/dboPhotoBucket.sqlite
Otherwise do this :
NSLog(@"app dir: %@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
- It will print the full path to data folder.
Swift:
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
println("App Path: \(dirPaths)")
SQL "IF", "BEGIN", "END", "END IF"?
You could also rewrite the code to remove the nested 'If' statement completely.
INSERT INTO @Classes
SELECT XXXXXX
FROM XXXX
Where @Term = 3
---- **always** "fall thru" to here, no matter what @Term is equal to - always do
---- the following INSERT for all elementary schools
INSERT INTO @Classes
SELECT XXXXXXXX
FROM XXXXXX (more code)
android studio 0.4.2: Gradle project sync failed error
Today I ran into the same error, however, i was using Android Studio 1.0.2. What i did tot fix the problem was that i started a project with minimum SDK 4.4 (API 19) so when i checked the version i noticed that at File->ProjectStructure->app i found Android 5 as a compile SDK Version. I changed that back to 4.4.
GZIPInputStream reading line by line
BufferedReader in = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"))));
String content;
while ((content = in.readLine()) != null)
System.out.println(content);
How to ignore files/directories in TFS for avoiding them to go to central source repository?
For TFS 2013:
Start in VisualStudio-Team Explorer, in the PendingChanges Dialog undo the Changes whith the state [add], which should be ignored.
Visual Studio will detect the Add(s) again. Click On "Detected: x add(s)"-in Excluded Changes
In the opened "Promote Cadidate Changes"-Dialog You can easy exclude Files and Folders with the Contextmenu. Options are:
- Ignore this item
- Ignore by extension
- Ignore by file name
- Ignore by ffolder (yes ffolder, TFS 2013 Update 4/Visual Studio 2013 Premium Update 4)
Don't forget to Check In the changed .tfignore-File.
For VS 2015/2017:
The same procedure:
In the "Excluded Changes Tab" in TeamExplorer\Pending Changes
click on Detected: xxx add(s)
The "Promote Candidate Changes" Dialog opens, and on the entries you can Right-Click for the Contextmenu. Typo is fixed now :-)
Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2
The following code uses both data.table
and fastmatch
for increased speed.
library("data.table")
library("fastmatch")
a1 <- setDT(data.frame(a = 1:5, b=letters[1:5]))
a2 <- setDT(data.frame(a = 1:3, b=letters[1:3]))
compare_rows <- a1$a %fin% a2$a
# the %fin% function comes from the `fastmatch` package
added_rows <- a1[which(compare_rows == FALSE)]
added_rows
# a b
# 1: 4 d
# 2: 5 e
At least one JAR was scanned for TLDs yet contained no TLDs
If one wants to have the conf\logging.properties
read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\
folder and then add the lines :
-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
to the VM arguments of the launch configuration one is using.
This may have taken a restart or two (or not) but finally I saw in the console in bright red :
FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc
I still don't know when exactly this FINE
warning appears - does not appear immediately on tomcat launch EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".
Bonus: To make the warning go away add in catalina.properties
:
# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar
module.exports vs. export default in Node.js and ES6
You need to configure babel correctly in your project to use export default and export const foo
npm install --save-dev @babel/plugin-proposal-export-default-from
then add below configration in .babelrc
"plugins": [
"@babel/plugin-proposal-export-default-from"
]
How to get the current time in milliseconds in C Programming
quick answer
#include<stdio.h>
#include<time.h>
int main()
{
clock_t t1, t2;
t1 = clock();
int i;
for(i = 0; i < 1000000; i++)
{
int x = 90;
}
t2 = clock();
float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;
printf("%f",diff);
return 0;
}
jQuery autoComplete view all on click?
In order to show all items / simulate combobox behavior, you should first ensure you have set the minLength option to 0 (default is 1). Then you can bind the click event to perform a search with the empty string.
$('inputSelector').autocomplete({ minLength: 0 });
$('inputSelector').click(function() { $(this).autocomplete("search", ""); });
how do I strip white space when grabbing text with jQuery?
Use the replace
function in js:
var emailAdd = $(this).text().replace(/ /g,'');
That will remove all the spaces
If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :
var emailAdd = $.trim($(this).text());
ValueError: shape mismatch: objects cannot be broadcast to a single shape
This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n
and the output of np.add.reduce()
are both scalars, this implies that the problem lies with xm
and ym
, the two of which are simply your x
and y
inputs minus their respective means.
Based on this, my guess is that your x
and y
inputs have different shapes from one another, making them incompatible for element-wise multiplication.
** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.
Install IPA with iTunes 11
I always use the iPhone configuration utility for this. Allows much more control and is faster - you don't have to sync the whole device.
adb doesn't show nexus 5 device
I had a similar problem with my Nexus 4(Android version 4.4.2), it wasn't listed in adb devices.
Make sure USB debugging is enabled from device, and do the following on your PC:
Update Android SDK (Google USB Driver)
From PC Control Panel, System -> Device manager -> Right click Nexus 4 -> Update driver.
Set android-sdk-folder\extras\google\usb_driver as path to search, include subfolders checked.
If windows tells you that the driver is up to date, just uninstall the driver (right click on nexu4 -> uninstall driver) and start from step 2 again.
After that, open a cmd and type adb kill-server and then a adb devices, now it will include your device.
https://developer.android.com/studio/run/oem-usb.html
what is trailing whitespace and how can I handle this?
Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.
In your posted question, there is one extra space after try:
, and there are 12 extra spaces after pass
:
>>> post_text = '''\
... if self.tagname and self.tagname2 in list1:
... try:
... question = soup.find("div", "post-text")
... title = soup.find("a", "question-hyperlink")
... self.list2.append(str(title)+str(question)+url)
... current += 1
... except AttributeError:
... pass
... logging.info("%s questions passed, %s questions \
... collected" % (count, current))
... count += 1
... return self.list2
... '''
>>> for line in post_text.splitlines():
... if line.rstrip() != line:
... print(repr(line))
...
' try: '
' pass '
See where the strings end? There are spaces before the lines (indentation), but also spaces after.
Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.
Overlapping Views in Android
Also, take a look at FrameLayout
, that's how the Camera's Gallery application implements the Zoom buttons overlay.
Extracting time from POSIXct
Many solutions have been provided, but I have not seen this one, which uses package chron:
hours = times(strftime(times, format="%T"))
plot(val~hours)
(sorry, I am not entitled to post an image, you'll have to plot it yourself)
Resolving IP Address from hostname with PowerShell
If you know part of the subnet (i.e. 10.3 in this example), then this will grab any addresses that are in the given subnet:
PS C:\> [System.Net.Dns]::GetHostAddresses("MyPC") | foreach { $_.IPAddressToString | findstr "10.3."}
Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?
This is a very simple solution, but it works for me:
_x000D_
_x000D_
<!--TEXT-AREA-->_x000D_
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>_x000D_
_x000D_
<!--JAVASCRIPT-->_x000D_
<script type="text/javascript">_x000D_
function setHeight(fieldId){_x000D_
document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';_x000D_
}_x000D_
setHeight('textBox1');_x000D_
</script>
_x000D_
_x000D_
_x000D_
Convert double to float in Java
Use dataType casting. For example:
// converting from double to float:
double someValue;
// cast someValue to float!
float newValue = (float)someValue;
Cheers!
Note:
Integers are whole numbers, e.g. 10, 400, or -5.
Floating point numbers (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
Doubles are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).
Create two-dimensional arrays and access sub-arrays in Ruby
x.transpose[6][3..8]
or x[3..8].map {|r| r [6]}
would give what you want.
Example:
a = [ [1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[21, 22, 23, 24, 25]
]
#a[1..2][2] -> [8,13]
puts a.transpose[2][1..2].inspect # [8,13]
puts a[1..2].map {|r| r[2]}.inspect # [8,13]
How to compile a 64-bit application using Visual C++ 2010 Express?
I found an important step to add to this - after you've installed the SDK, go to your project properties and change Configuration Properties->General->Platform Toolset from v100 or whatever it is to Windows7.1SDK. This changes $(WindowsSdkDir) to the proper place and seemed to solve some other difficulties I was encountering as well.
C# version of java's synchronized keyword?
First - most classes will never need to be thread-safe. Use YAGNI: only apply thread-safety when you know you actually are going to use it (and test it).
For the method-level stuff, there is [MethodImpl]
:
[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}
This can also be used on accessors (properties and events):
private int i;
public int SomeProperty
{
[MethodImpl(MethodImplOptions.Synchronized)]
get { return i; }
[MethodImpl(MethodImplOptions.Synchronized)]
set { i = value; }
}
Note that field-like events are synchronized by default, while auto-implemented properties are not:
public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized
Personally, I don't like the implementation of MethodImpl
as it locks this
or typeof(Foo)
- which is against best practice. The preferred option is to use your own locks:
private readonly object syncLock = new object();
public void SomeMethod() {
lock(syncLock) { /* code */ }
}
Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a lock(this)
/ lock(Type)
- however, in more recent compilers it uses Interlocked
updates - so thread-safe without the nasty parts.
This allows more granular usage, and allows use of Monitor.Wait
/Monitor.Pulse
etc to communicate between threads.
A related blog entry (later revisited).
Android emulator-5554 offline
I finally solved this problem,
I had to go to the Developer options from the Settings in the Emulator,
then scrolled down a little, turned on the USB debugging. Instantly my device was recognized online, and I no longer faced that issue. I tried restarting android studio and emulator, killing adb process, but those did not work.
Access key value from Web.config in Razor View-MVC3 ASP.NET
Here's a real world example with the use of non-minified versus minified assets in your layout.
Web.Config
<appSettings>
<add key="Environment" value="Dev" />
</appSettings>
Razor Template - use that var above like this:
@if (System.Configuration.ConfigurationManager.AppSettings["Environment"] == "Dev")
{
<link type="text/css" rel="stylesheet" href="@Url.Content("~/Content/styles/theme.css" )">
}else{
<link type="text/css" rel="stylesheet" href="@Url.Content("~/Content/styles/blue_theme.min.css" )">
}
How can I delete a query string parameter in JavaScript?
Modern browsers provide URLSearchParams
interface to work with search params. Which has delete
method that removes param by name.
_x000D_
_x000D_
if (typeof URLSearchParams !== 'undefined') {_x000D_
const params = new URLSearchParams('param1=1¶m2=2¶m3=3')_x000D_
_x000D_
console.log(params.toString())_x000D_
_x000D_
params.delete('param2')_x000D_
_x000D_
console.log(params.toString())_x000D_
_x000D_
} else {_x000D_
console.log(`Your browser ${navigator.appVersion} does not support URLSearchParams`)_x000D_
}
_x000D_
_x000D_
_x000D_
Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
How to use componentWillMount() in React Hooks?
useComponentWillMount hook
export const useComponentWillMount = (func) => {
const willMount = useRef(true)
if (willMount.current) func()
willMount.current = false
}
// or
export const useComponentWillMount = (func) => {
useMemo(func, [])
}
Discussion
In class components componentWillMount is considered legacy (source 1, source2). However, this shouldn't apply to functional components and a hook based solution. Class component componentWillMount is deprecated since it might run more than once, and there is an alternative - using the constructor. Those considerations aren't relevant for a functional component.
My experience is that such a hook could be a saver when timing/sequence is critical. I'm interested to know what is your use case - comments are welcome.
useComponentDidMount hook
Alternatively, use componentDidMount hook.
const useComponentDidMount = func => useEffect(func, []);
It will run only once, after component has mounted(initial render to the dom).
Demo
const Component = (props) => {
useComponentWillMount(() => console.log("Runs only once before component mounts"));
useComponentDidMount(() => console.log("Runs only once after component mounts"));
...
return (
<div>{...}</div>
);
}
Full Demo
writing to existing workbook using xlwt
You need xlutils.copy
. Try something like this:
from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')
Keep in mind you can't overwrite cells by default as noted in this question.
Using Node.JS, how do I read a JSON file into (server) memory?
function parseIt(){
return new Promise(function(res){
try{
var fs = require('fs');
const dirPath = 'K:\\merge-xml-junit\\xml-results\\master.json';
fs.readFile(dirPath,'utf8',function(err,data){
if(err) throw err;
res(data);
})}
catch(err){
res(err);
}
});
}
async function test(){
jsonData = await parseIt();
var parsedJSON = JSON.parse(jsonData);
var testSuite = parsedJSON['testsuites']['testsuite'];
console.log(testSuite);
}
test();
How to remove/ignore :hover css style on touch devices
If Your issue is when you touch/tap on android and whole div covered by blue transparent color! Then you need to just change the
CURSOR : POINTER;
to
CURSOR : DEFAULT;
use mediaQuery to hide in mobile phone/Tablet.
This works for me.
Setting the value of checkbox to true or false with jQuery
Try this:
HTML:
<input type="checkbox" value="FALSE" />
jQ:
$("input[type='checkbox']").on('change', function(){
$(this).val(this.checked ? "TRUE" : "FALSE");
})
jsfiddle
Please bear in mind that unchecked checkbox will not be submitted in regular form, and you should use hidden filed in order to do it.
Table Naming Dilemma: Singular vs. Plural Names
I personaly prefer to use plural names to represent a set, it just "sounds" better to my relational mind.
At this exact moment i am using singular names to define a data model for my company, because most of the people at work feel more confortable with it.
Sometimes you just have to make life easier to everyone instead of imposing your personal preferences.
(that's how i ended up in this thread, to get a confirmation on what should be the "best practice" for naming tables)
After reading all the arguing in this thread, i reached one conclusion:
I like my pancakes with honey, no matter what everybody's favorite flavour is. But if i am cooking for other people, i will try to serve them something they like.
What is the difference between C++ and Visual C++?
C++ is a language and Visual C++ is a compiler for that language. Certainly, it (and every other compiler) introduces tiny modifications to the language, but the language recognized is mainly the same.
Checking cin input stream produces an integer
I prefer to use <limits>
to check for an int
until it is passed.
#include <iostream>
#include <limits> //std::numeric_limits
using std::cout, std::endl, std::cin;
int main() {
int num;
while(!(cin >> num)){ //check the Input format for integer the right way
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid input. Reenter the number: ";
};
cout << "output= " << num << endl;
return 0;
}
Javascript event handler with parameters
this
inside of doThings
is the window object. Try this instead:
var doThings = function (element) {
var eventHandler = function(ev, func){
if (element[ev] == undefined) {
return;
}
element[ev] = function(e){
func(e, element);
}
};
return {
eventHandler: eventHandler
};
};
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
Floating divs in Bootstrap layout
From all I have read you cannot do exactly what you want without javascript.
If you float left before text
<div style="float:left;">widget</div> here is some CONTENT, etc.
Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content
here is some CONTENT, etc. <div style="float:left;">widget</div>
Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:
here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>
In your question you are using bootstrap which just adds row-fluid::after { content: ""}
which resolves the border/background issue.
Moving your content up will give you the one line wrap :
http://jsfiddle.net/jJNPY/34/
<div class="container-fluid">
<div class="row-fluid">
<div class="offset1 span8 pull-right">
... Widget 1...
</div>
.... a lot of content ....
<div class="span8" style="margin-left: 0;">
... Widget 2...
</div>
</div>
</div><!--/.fluid-container-->
What is the difference between HTTP_HOST and SERVER_NAME in PHP?
Assuming one has a simple setup (CentOS 7, Apache 2.4.x, and PHP 5.6.20) and only one website (not assuming virtual hosting) ...
In the PHP sense, $_SERVER['SERVER_NAME']
is an element PHP registers in the $_SERVER
superglobal based on your Apache configuration (**ServerName**
directive with UseCanonicalName On
) in httpd.conf (be it from an included virtual host configuration file, whatever, etc ...). HTTP_HOST is derived from the HTTP host
header. Treat this as user input. Filter and validate before using.
Here is an example of where I use $_SERVER['SERVER_NAME']
as the basis for a comparison. The following method is from a concrete child class I made named ServerValidator
(child of Validator
). ServerValidator
checks six or seven elements in $_SERVER before using them.
In determining if the HTTP request is POST, I use this method.
public function isPOST()
{
return (($this->requestMethod === 'POST') && // Ignore
$this->hasTokenTimeLeft() && // Ignore
$this->hasSameGETandPOSTIdentities() && // Ingore
($this->httpHost === filter_input(INPUT_SERVER, 'SERVER_NAME')));
}
By the time this method is called, all filtering and validating of relevant $_SERVER elements would have occurred (and relevant properties set).
The line ...
($this->httpHost === filter_input(INPUT_SERVER, 'SERVER_NAME')
... checks that the $_SERVER['HTTP_HOST']
value (ultimately derived from the requested host
HTTP header) matches $_SERVER['SERVER_NAME']
.
Now, I am using superglobal speak to explain my example, but that is just because some people are unfamiliar with INPUT_GET
, INPUT_POST
, and INPUT_SERVER
in regards to filter_input_array()
.
The bottom line is, I do not handle POST requests on my server unless all four conditions are met. Hence, in terms of POST requests, failure to provide an HTTP host
header (presence tested for earlier) spells doom for strict HTTP 1.0 browsers. Moreover, the requested host must match the value for ServerName
in the httpd.conf, and, by extention, the value for $_SERVER('SERVER_NAME')
in the $_SERVER
superglobal. Again, I would be using INPUT_SERVER
with the PHP filter functions, but you catch my drift.
Keep in mind that Apache frequently uses ServerName
in standard redirects (such as leaving the trailing slash off a URL: Example, http://www.example.com becoming http://www.example.com/), even if you are not using URL rewriting.
I use $_SERVER['SERVER_NAME']
as the standard, not $_SERVER['HTTP_HOST']
. There is a lot of back and forth on this issue. $_SERVER['HTTP_HOST']
could be empty, so this should not be the basis for creating code conventions such as my public method above. But, just because both may be set does not guarantee they will be equal. Testing is the best way to know for sure (bearing in mind Apache version and PHP version).
Nested attributes unpermitted parameters
From the docs
To whitelist an entire hash of parameters, the permit! method can be used
params.require(:log_entry).permit!
Nested attributes are in the form of a hash. In my app, I have a Question.rb model accept nested attributes for an Answer.rb model (where the user creates answer choices for a question he creates). In the questions_controller, I do this
def question_params
params.require(:question).permit!
end
Everything in the question hash is permitted, including the nested answer attributes. This also works if the nested attributes are in the form of an array.
Having said that, I wonder if there's a security concern with this approach because it basically permits anything that's inside the hash without specifying exactly what it is, which seems contrary to the purpose of strong parameters.
How to redirect output to a file and stdout
You can do that for your entire script by using something like that at the beginning of your script :
#!/usr/bin/env bash
test x$1 = x$'\x00' && shift || { set -o pipefail ; ( exec 2>&1 ; $0 $'\x00' "$@" ) | tee mylogfile ; exit $? ; }
# do whaetever you want
This redirect both stderr and stdout outputs to the file called mylogfile
and let everything goes to stdout at the same time.
It is used some stupid tricks :
- use
exec
without command to setup redirections,
- use
tee
to duplicates outputs,
- restart the script with the wanted redirections,
- use a special first parameter (a simple
NUL
character specified by the $'string'
special bash notation) to specify that the script is restarted (no equivalent parameter may be used by your original work),
- try to preserve the original exit status when restarting the script using the
pipefail
option.
Ugly but useful for me in certain situations.
How to add a new line in textarea element?
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Fiddle showing that it works: http://jsfiddle.net/trott/5vu28/.
If you really want this to be on a single line in the source file, you could insert the HTML character references for a line feed and a carriage return as shown in the answer from @Bakudan:
_x000D_
_x000D_
<textarea cols='60' rows='8'>This is my statement one. This is my statement2</textarea>
_x000D_
_x000D_
_x000D_
Pointers in Python?
This is a python pointer (different of c/c++)
>>> a = lambda : print('Hello')
>>> a
<function <lambda> at 0x0000018D192B9DC0>
>>> id(a) == int(0x0000018D192B9DC0)
True
>>> from ctypes import cast, py_object
>>> cast(id(a), py_object).value == cast(int(0x0000018D192B9DC0), py_object).value
True
>>> cast(id(a), py_object).value
<function <lambda> at 0x0000018D192B9DC0>
>>> cast(id(a), py_object).value()
Hello
Copy mysql database from remote server to local computer
Better yet use a oneliner:
Dump remoteDB to localDB:
mysqldump -uroot -pMypsw -h remoteHost remoteDB | mysql -u root -pMypsw localDB
Dump localDB to remoteDB:
mysqldump -uroot -pmyPsw localDB | mysql -uroot -pMypsw -h remoteHost remoteDB
blur() vs. onblur()
Contrary to what pointy says, the blur()
method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Javascript test</title>
<script type="text/javascript" language="javascript">
window.onload = function()
{
var field = document.getElementById("field");
var link = document.getElementById("link");
var output = document.getElementById("output");
field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
link.onmouseover = function() { field.blur(); };
};
</script>
</head>
<body>
<form name="MyForm">
<input type="text" name="field" id="field" />
<a href="javascript:void(0);" id="link">Blur field on hover</a>
<div id="output"></div>
</form>
</body>
</html>
Note that I used link.onmouseover
instead of link.onclick
, because otherwise the click itself would have removed the focus.
How do I set cell value to Date and apply default Excel date format?
To set to default Excel type Date (defaulted to OS level locale /-> i.e. xlsx will look different when opened by a German or British person/ and flagged with an asterisk if you choose it in Excel's cell format chooser) you should:
CellStyle cellStyle = xssfWorkbook.createCellStyle();
cellStyle.setDataFormat((short)14);
cell.setCellStyle(cellStyle);
I did it with xlsx and it worked fine.
How do I hide anchor text without hiding the anchor?
You can put an image into ::before pseudoelement and set the same dimensions for as is the image + add overflow:hidden, like:
li a::before{
content:url('img');
width:20px;
height:10px
}
a {
overflow:hidden;
width:20px;
height:10px
}
Load local images in React.js
Instead of use img src="", try to create a div and set background-image as the image you want.
Right now it's working for me.
example:
App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div>
<div className="myImage"> </div>
</div>
);
}
}
export default App;
App.css
.myImage {
width: 60px;
height: 60px;
background-image: url("./icons/add-circle.png");
background-repeat: no-repeat;
background-size: 100%;
}
How to get records randomly from the oracle database?
Here's how to pick a random sample out of each group:
SELECT GROUPING_COLUMN,
MIN (COLUMN_NAME) KEEP (DENSE_RANK FIRST ORDER BY DBMS_RANDOM.VALUE)
AS RANDOM_SAMPLE
FROM TABLE_NAME
GROUP BY GROUPING_COLUMN
ORDER BY GROUPING_COLUMN;
I'm not sure how efficient it is, but if you have a lot of categories and sub-categories, this seems to do the job nicely.
Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv
My environment:
Since none of the previous answers worked for me, I downloaded OpenCV 3.0 from http://opencv.org/downloads.html and followed the installation manual. I used the following cmake
command:
$ ~/Programs/opencv-3.0.0$ cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local -D PYTHON3_EXECUTABLE=/usr/bin/python3.5 -D PYTHON_INCLUDE_DIR=/usr/include/python3.5 -D PYTHON_INCLUDE_DIR2=/usr/include/x86_64-linux-gnu/python3.5m -D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so -D PYTHON3_NUMPY_INCLUDE_DIRS=/usr/lib/python3/dist-packages/numpy/core/include/ -D PYTHON3_PACKAGES_PATH=/usr/lib/python3/dist-packages ..
Each step of the tutorial is important. Particularly, don't forget to call sudo make install
.
Android Camera : data intent returns null
Kotlin code that works for me:
private fun takePhotoFromCamera() {
val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA)
}
And get Result :
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
val photo: Bitmap? = MediaStore.Images.Media.getBitmap(this.contentResolver, Uri.parse( data!!.dataString) )
// Do something here : set image to an ImageView or save it ..
imgV_pic.imageBitmap = photo
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i(TAG, "Camera , RESULT_CANCELED ")
}
}
}
and don't forget to declare request code:
companion object {
const val PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA = 300
}
Restarting cron after changing crontab file?
No.
From the cron man page:
...cron will then examine the modification time on all crontabs
and reload those which have changed. Thus cron need not be restarted
whenever a crontab file is modified
But if you just want to make sure its done anyway,
sudo service cron reload
or
/etc/init.d/cron reload
How to delete specific columns with VBA?
You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.
I think what you were looking for in your Range was this:
Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete
Just change the column letters to match your needs.
How to insert DECIMAL into MySQL database
Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00
. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.
In SQL, is UPDATE always faster than DELETE+INSERT?
The question of speed is irrelevant without a specific speed problem.
If you are writing SQL code to make a change to an existing row, you UPDATE it. Anything else is incorrect.
If you're going to break the rules of how code should work, then you'd better have a damn good, quantified reason for it, and not a vague idea of "This way is faster", when you don't have any idea what "faster" is.
Java compile error: "reached end of file while parsing }"
You need to enclose your class in {
and }
. A few extra pointers: According to the Java coding conventions, you should
- Put your
{
on the same line as the method declaration:
- Name your classes using CamelCase (with initial capital letter)
- Name your methods using camelCase (with small initial letter)
Here's how I would write it:
public class ModMyMod extends BaseMod {
public String version() {
return "1.2_02";
}
public void addRecipes(CraftingManager recipes) {
recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
"#", Character.valueOf('#'), Block.dirt
});
}
}
Get all files modified in last 30 days in a directory
A couple of issues
- You're not limiting it to files, so when it finds a matching directory it will list every file within it.
- You can't use
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
.
+30
is older
than 30 days, -30
would be modified in last 30 days.
-exec
really isn't needed, you could list everything with various -printf
options.
Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
Equivalent of LIMIT for DB2
Developed this method:
You NEED a table that has an unique value that can be ordered.
If you want rows 10,000 to 25,000 and your Table has 40,000 rows, first you need to get the starting point and total rows:
int start = 40000 - 10000;
int total = 25000 - 10000;
And then pass these by code to the query:
SELECT * FROM
(SELECT * FROM schema.mytable
ORDER BY userId DESC fetch first {start} rows only ) AS mini
ORDER BY mini.userId ASC fetch first {total} rows only
List of remotes for a Git repository?
If you only need the names of the remote repositories (and not any of the other data), a simple git remote
is enough.
$ git remote
iqandreas
octopress
origin
Java generics - ArrayList initialization
You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.
ArrayList<? extends Object>
is an ArrayList whose type parameter is known to be Object
or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>
.
That is, you can put an ArrayList<String>
into a variable declared with ArrayList<?>
. That's why a1.add(3)
is a compile time error. a1
's declared type permits a1
to be an ArrayList<String>
, to which no Integer
can be added.
Clearly, an ArrayList<?>
is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:
It is a compile-time error if any of
the type arguments used in a class
instance creation expression are
wildcard type arguments
ArrayList<ArrayList<?>>
in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?>
only contains but is not a wildcard type, the above rule does not apply.
Use of String.Format in JavaScript?
//Add "format" method to the string class
//supports: "Welcome {0}. You are the first person named {0}".format("David");
// and "First Name:{} Last name:{}".format("David","Wazy");
// and "Value:{} size:{0} shape:{1} weight:{}".format(value, size, shape, weight)
String.prototype.format = function () {
var content = this;
for (var i = 0; i < arguments.length; i++) {
var target = '{' + i + '}';
content=content.split(target).join(String(arguments[i]))
content = content.replace("{}", String(arguments[i]));
}
return content;
}
alert("I {} this is what {2} want and {} works for {2}!".format("hope","it","you"))
You can mix and match using positional and "named" replacement locations using this function.
How to use jQuery in AngularJS
The best option is create a directive and wrap the slider features there.
The secret is use $timeout, the jquery code will be called only when DOM is ready.
angular.module('app')
.directive('my-slider',
['$timeout', function($timeout) {
return {
restrict:'E',
scope: true,
template: '<div id="{{ id }}"></div>',
link: function($scope) {
$scope.id = String(Math.random()).substr(2, 8);
$timeout(function() {
angular.element('#'+$scope.id).slider();
});
}
};
}]
);
Regex to get string between curly braces
/\{([^}]+)\}/
/ - delimiter
\{ - opening literal brace escaped because it is a special character used for quantifiers eg {2,3}
( - start capturing
[^}] - character class consisting of
^ - not
} - a closing brace (no escaping necessary because special characters in a character class are different)
+ - one or more of the character class
) - end capturing
\} - the closing literal brace
/ - delimiter
How can I check if a string is null or empty in PowerShell?
Another way to accomplish this in a pure PowerShell way would be to do something like this:
("" -eq ("{0}" -f $val).Trim())
This evaluates successfully for null, empty string, and whitespace. I'm formatting the passed value into an empty string to handle null (otherwise a null will cause an error when the Trim is called). Then just evaluate equality with an empty string. I think I still prefer the IsNullOrWhiteSpace, but if you're looking for another way to do it, this will work.
$val = null
("" -eq ("{0}" -f $val).Trim())
>True
$val = " "
("" -eq ("{0}" -f $val).Trim())
>True
$val = ""
("" -eq ("{0}" -f $val).Trim())
>True
$val = "not null or empty or whitespace"
("" -eq ("{0}" -f $val).Trim())
>False
In a fit of boredom, I played with this some and made it shorter (albeit more cryptic):
!!(("$val").Trim())
or
!(("$val").Trim())
depending on what you're trying to do.
installing python packages without internet and using source code as .tar.gz and .whl
This is how I handle this case:
On the machine where I have access to Internet:
mkdir keystone-deps
pip download python-keystoneclient -d "/home/aviuser/keystone-deps"
tar cvfz keystone-deps.tgz keystone-deps
Then move the tar file to the destination machine that does not have Internet access and perform the following:
tar xvfz keystone-deps.tgz
cd keystone-deps
pip install python_keystoneclient-2.3.1-py2.py3-none-any.whl -f ./ --no-index
You may need to add --no-deps to the command as follows:
pip install python_keystoneclient-2.3.1-py2.py3-none-any.whl -f ./ --no-index --no-deps
How to draw vertical lines on a given plot in matplotlib
If someone wants to add a legend
and/or colors
to some vertical lines, then use this:
import matplotlib.pyplot as plt
# x coordinates for the lines
xcoords = [0.1, 0.3, 0.5]
# colors for the lines
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()
Results:
How can I mix LaTeX in with Markdown?
Hey, this might not be the most ideal solution, but it works for me. I ended up creating a Python-Markdown LaTeX extension.
https://github.com/justinvh/Markdown-LaTeX
It adds support for inline math and text expressions using a $math$ and %text% syntax. The extension is a preprocessor that will use latex/dvipng to generate pngs for the respective equations/text and then base64 encode the data to inline the images directly, rather than have external images.
The data is then put in a simple-delimited cache file that encodes the expression to the base64 representation. This limits the number of times latex actually has to be run.
Here is an example:
%Hello, world!% This is regular text, but this: $y = mx + b$ is not.
The output:
$ markdown -x latex test.markdown
<p><img class='latex-inline math-false' alt='Hello, world!' id='Helloworld' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFwAAAAQBAMAAABpWwV8AAAAMFBMVEX///8iIiK6urpUVFTu7u6YmJgQEBDc3NxERESqqqqIiIgyMjJ2dnZmZmbMzMwAAAAbX03YAAAAAXRSTlMAQObYZgAAAVpJREFUKM9jYICDOgb2BwzYAVji8AQg8fb/PZ79u4AMvv0Mrz/gUA6W8F7AmcLAsJuBYT7Y1PcMfLiUgyWYF/B8Z2DYAVReABKrZ2DHpZwdopzrA0nKOeHKj66CKOcKPQJWwJo2NVFhfwCQyymhYwCUYD0avIApgYFh2927/QUcE3gDwMpvMhRCDJzNMIPhKZg7UW8DUOIMg9sCPgGo6e8ZODeAlAP9xLEArNy/IIwhAMx9D3IM+3cgi70BqnxZaNQFkHJWAQbeBrByjgURExaAuc9AyjnB5hjAlEO9ygVXzrplpskEMPchQvkBmGMcGApgjjkAVs7yhyWVAcwFK2f/AlJeAI0m5gMsEK+aMhQ6aDuA1DcDIZirBg7IOwxlB5g2QBJBF8OZVUz95hqfC3hOXWGYrwBSHskwk4EByGXab8QAlOBaGizFKYAtUlgUGEgBTCSpZnDCLQUA+y6MXeYnPDgAAAAASUVORK5CYII='> This is regular text, but this: <img class='latex-inline math-true' alt='y = mx + b' id='ymxb' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFIAAAAOBAMAAABOTlYkAAAAMFBMVEX///9ERETu7u4yMjK6urp2dnZUVFSIiIjMzMwQEBDc3NwiIiJmZmaYmJiqqqoAAADS00rKAAAAAXRSTlMAQObYZgAAAOtJREFUKM9jYCAACsCk4wYGgiABTLInEKuS+QGxKvkVGBj47jBwI8tcffI84e45BoZ7GVcLECo9751iWLeSoRPITBQEggMMDBy9sxj2MDgz8DIE8yCpPMxwjWFBGUMMkpFcbAEMvxjKGLgYxIE8NkHBiYIyQMY+hmoGhi0Mdsi2czawbGCQBTJ+ILvzE0MaA9MHIIWwnWE9A+sBpk8LGDgmMCnAVXJNYPgCJHhRQvUiA/cDXoECZx4DXoSZTBtYgaaEPw5AVnkOGBRc5xTcbsReQrL9+nWwyxbgC88DcJZ+QygDcYD1+QPiFAIAtLA8KPZOGFEAAAAASUVORK5CYII='> is not.</p>
As you can see it is a verbose output, but that really isn't an issue since you're already using Markdown :)
What is the difference between a URI, a URL and a URN?
Identity = Name with Location
Every URL(Uniform Resource Locator) is a URI(Uniform Resource Identifier), abstractly speaking, but every URI is not a URL. There is another subcategory of URI is URN (Uniform Resource Name), which is a named resource but do not specify how to locate them, like mailto, news, ISBN is URIs. Source
URN:
- URN Format :
urn:[namespace identifier]:[namespace specific string]
- urn: and : stand for themselves.
- Examples:
- urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66
- urn:ISSN:0167-6423
- urn:isbn:096139210x
- Amazon Resource Names (ARNs) is a uniquely identify AWS resources.
- ARN Format :
arn:partition:service:region:account-id:resource
URL:
- URL Format :
[scheme]://[Domain][Port]/[path]?[queryString]#[fragmentId]
- :,//,? and # stand for themselves.
- schemes are https,ftp,gopher,mailto,news,telnet,file,man,info,whatis,ldap...
- Examples:
Analogy:
To reach a person: Driving(protocol others SMS, email, phone), Address(hostname other phone-number, emailid) and person name(object name with a relative path).
bash script use cut command at variable and store result at another variable
The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.
#!/bin/bash -vx
##config file with ip addresses like 10.10.10.1:80
file=config.txt
while read line ; do
##this line is not correct, should strip :port and store to ip var
ip=$( echo "$line" |cut -d\: -f1 )
ping $ip
done < ${file}
You could write your top line as
for line in $(cat $file) ; do ...
(but not recommended).
You needed command substitution $( ... )
to get the value assigned to $ip
reading lines from a file is usually considered more efficient with the while read line ... done < ${file}
pattern.
I hope this helps.
How to Upload Image file in Retrofit 2
Retrofit 2.0 solution
@Multipart
@POST(APIUtils.UPDATE_PROFILE_IMAGE_URL)
public Call<CommonResponse> requestUpdateImage(@PartMap Map<String, RequestBody> map);
and
Map<String, RequestBody> params = new HashMap<>();
params.put("newProfilePicture" + "\"; filename=\"" + FilenameUtils.getName(file.getAbsolutePath()), RequestBody.create(MediaType.parse("image/jpg"), file));
Call<CommonResponse> call = request.requestUpdateImage(params);
you can use
image/jpg
image/png
image/gif
What is the difference between "Class.forName()" and "Class.forName().newInstance()"?
No matter how many times you call Class.forName() method, Only once the static block gets executed not multiple time:
package forNameMethodDemo;
public class MainClass {
public static void main(String[] args) throws Exception {
Class.forName("forNameMethodDemo.DemoClass");
Class.forName("forNameMethodDemo.DemoClass");
Class.forName("forNameMethodDemo.DemoClass");
DemoClass demoClass = (DemoClass)Class.forName("forNameMethodDemo.DemoClass").newInstance();
}
}
public class DemoClass {
static {
System.out.println("in Static block");
}
{
System.out.println("in Instance block");
}
}
output will be:
in Static block
in Instance block
This in Static block
statement is printed only once not three times.
What is the difference between <jsp:include page = ... > and <%@ include file = ... >?
In one reusable piece of code I use the directive <%@include file="reuse.html"%>
and in the second I use the standard action <jsp:include page="reuse.html" />
.
Let the code in the reusable file be:
<html>
<head>
<title>reusable</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<img src="candle.gif" height="100" width="50"/> <br />
<p><b>As the candle burns,so do I</b></p>
</body>
After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet
of the two JSP files, you will see the difference.
Here is what you will see when you use the directive:
out.write("<html>\r\n");
out.write(" <head>\r\n");
out.write(" <title>reusable</title>\r\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write(" </head>\r\n");
out.write(" <body>\r\n");
out.write(" <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write(" <p><b>As the candle burns,so do I</b></p>\r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
And this is what you will see for the used standard action in the second JSP file :
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);
So now you know that the include directive inserts the source of reuse.html
at translation time, but the action tag inserts the response of reuse.html
at runtime.
If you think about it, there is an extra performance hit with every action tag (<jsp:include>
). It means you can guarantee you will always have the latest content, but it increases performance cost.
CSS3 Transition not working
Transition is more like an animation.
div.sicon a {
background:-moz-radial-gradient(left, #ffffff 24%, #cba334 88%);
transition: background 0.5s linear;
-moz-transition: background 0.5s linear; /* Firefox 4 */
-webkit-transition: background 0.5s linear; /* Safari and Chrome */
-o-transition: background 0.5s linear; /* Opera */
-ms-transition: background 0.5s linear; /* Explorer 10 */
}
So you need to invoke that animation with an action.
div.sicon a:hover {
background:-moz-radial-gradient(left, #cba334 24%, #ffffff 88%);
}
Also check for browser support and if you still have some problem with whatever you're trying to do! Check css-overrides in your stylesheet and also check out for behavior: ***.htc
css hacks.. there may be something overriding your transition!
You should check this out: http://www.w3schools.com/css/css3_transitions.asp
How to enable Bootstrap tooltip on disabled button?
Simply add the disabled class to the button instead of the disabled attribute to make it visibly disabled instead.
<button class="btn disabled" rel="tooltip" data-title="Dieser Link führt zu Google">button disabled</button>
Note: this button only appears to be disabled, but it still triggers events, and you just have to be mindful of that.
Convert Python program to C/C++ code?
If the C variant needs x hours less, then I'd invest that time in letting the algorithms run longer/again
"invest" isn't the right word here.
Build a working implementation in Python. You'll finish this long before you'd finish a C version.
Measure performance with the Python profiler. Fix any problems you find. Change data structures and algorithms as necessary to really do this properly. You'll finish this long before you finish the first version in C.
If it's still too slow, manually translate the well-designed and carefully constructed Python into C.
Because of the way hindsight works, doing the second version from existing Python (with existing unit tests, and with existing profiling data) will still be faster than trying to do the C code from scratch.
This quote is important.
Thompson's Rule for First-Time Telescope Makers
It is faster to make a four-inch mirror and then a six-inch mirror than to make a six-inch mirror.
Bill McKeenan
Wang Institute
How to prevent errno 32 broken pipe?
It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.
For example, if your sendall
always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).
In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.
Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.
Change MySQL root password in phpMyAdmin
0) go to phpmyadmin don't select any db
1) Click "Privileges". You'll see all the users on MySQL's privilege tables.
2) Check the user "root" whose Host value is localhost, and click the "Edit Privileges" icon.
3) In the "Change password" field, click "Password" and enter a new password.
4) Retype the password to confirm. Then click "Go" to apply the settings.
How to use ES6 Fat Arrow to .filter() an array of objects
As simple as you can use const adults = family.filter(({ age }) => age > 18 );
_x000D_
_x000D_
const family =[{"name":"Jack", "age": 26},_x000D_
{"name":"Jill", "age": 22},_x000D_
{"name":"James", "age": 5 },_x000D_
{"name":"Jenny", "age": 2 }];_x000D_
_x000D_
const adults = family.filter(({ age }) => age > 18 );_x000D_
_x000D_
console.log(adults)
_x000D_
_x000D_
_x000D_
What does "to stub" mean in programming?
This phrase is almost certainly an analogy with a phase in house construction — "stubbing out" plumbing. During construction, while the walls are still open, the rough plumbing is put in. This is necessary for the construction to continue. Then, when everything around it is ready enough, one comes back and adds faucets and toilets and the actual end-product stuff. (See for example How to Install a Plumbing Stub-Out.)
When you "stub out" a function in programming, you build enough of it to work around (for testing or for writing other code). Then, you come back later and replace it with the full implementation.
Calculate time difference in Windows batch file
Fixed Gynnad's leading 0
Issue. I fixed it with the two Lines
SET STARTTIME=%STARTTIME: =0%
SET ENDTIME=%ENDTIME: =0%
Full Script ( CalculateTime.cmd
):
@ECHO OFF
:: F U N C T I O N S
:__START_TIME_MEASURE
SET STARTTIME=%TIME%
SET STARTTIME=%STARTTIME: =0%
EXIT /B 0
:__STOP_TIME_MEASURE
SET ENDTIME=%TIME%
SET ENDTIME=%ENDTIME: =0%
SET /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + (1%STARTTIME:~3,2%-100)*6000 + (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
SET /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + (1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)
SET /A DURATION=%ENDTIME%-%STARTTIME%
IF %DURATION% == 0 SET TIMEDIFF=00:00:00,00 && EXIT /B 0
IF %ENDTIME% LSS %STARTTIME% SET /A DURATION=%STARTTIME%-%ENDTIME%
SET /A DURATIONH=%DURATION% / 360000
SET /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
SET /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
SET /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - %DURATIONS%*100)
IF %DURATIONH% LSS 10 SET DURATIONH=0%DURATIONH%
IF %DURATIONM% LSS 10 SET DURATIONM=0%DURATIONM%
IF %DURATIONS% LSS 10 SET DURATIONS=0%DURATIONS%
IF %DURATIONHS% LSS 10 SET DURATIONHS=0%DURATIONHS%
SET TIMEDIFF=%DURATIONH%:%DURATIONM%:%DURATIONS%,%DURATIONHS%
EXIT /B 0
:: U S A G E
:: Start Measuring
CALL :__START_TIME_MEASURE
:: Print Message on Screen without Linefeed
ECHO|SET /P=Execute Job...
:: Some Time pending Jobs here
:: '> NUL 2>&1' Dont show any Messages or Errors on Screen
MyJob.exe > NUL 2>&1
:: Stop Measuring
CALL :__STOP_TIME_MEASURE
:: Finish the Message 'Execute Job...' and print measured Time
ECHO [Done] (%TIMEDIFF%)
:: Possible Result
:: Execute Job... [Done] (00:02:12,31)
:: Between 'Execute Job... ' and '[Done] (00:02:12,31)' the Job will be executed
Simple 3x3 matrix inverse code (C++)
//Title: Matrix Header File
//Writer: Say OL
//This is a beginner code not an expert one
//No responsibilty for any errors
//Use for your own risk
using namespace std;
int row,col,Row,Col;
double Coefficient;
//Input Matrix
void Input(double Matrix[9][9],int Row,int Col)
{
for(row=1;row<=Row;row++)
for(col=1;col<=Col;col++)
{
cout<<"e["<<row<<"]["<<col<<"]=";
cin>>Matrix[row][col];
}
}
//Output Matrix
void Output(double Matrix[9][9],int Row,int Col)
{
for(row=1;row<=Row;row++)
{
for(col=1;col<=Col;col++)
cout<<Matrix[row][col]<<"\t";
cout<<endl;
}
}
//Copy Pointer to Matrix
void CopyPointer(double (*Pointer)[9],double Matrix[9][9],int Row,int Col)
{
for(row=1;row<=Row;row++)
for(col=1;col<=Col;col++)
Matrix[row][col]=Pointer[row][col];
}
//Copy Matrix to Matrix
void CopyMatrix(double MatrixInput[9][9],double MatrixTarget[9][9],int Row,int Col)
{
for(row=1;row<=Row;row++)
for(col=1;col<=Col;col++)
MatrixTarget[row][col]=MatrixInput[row][col];
}
//Transpose of Matrix
double MatrixTran[9][9];
double (*(Transpose)(double MatrixInput[9][9],int Row,int Col))[9]
{
for(row=1;row<=Row;row++)
for(col=1;col<=Col;col++)
MatrixTran[col][row]=MatrixInput[row][col];
return MatrixTran;
}
//Matrix Addition
double MatrixAdd[9][9];
double (*(Addition)(double MatrixA[9][9],double MatrixB[9][9],int Row,int Col))[9]
{
for(row=1;row<=Row;row++)
for(col=1;col<=Col;col++)
MatrixAdd[row][col]=MatrixA[row][col]+MatrixB[row][col];
return MatrixAdd;
}
//Matrix Subtraction
double MatrixSub[9][9];
double (*(Subtraction)(double MatrixA[9][9],double MatrixB[9][9],int Row,int Col))[9]
{
for(row=1;row<=Row;row++)
for(col=1;col<=Col;col++)
MatrixSub[row][col]=MatrixA[row][col]-MatrixB[row][col];
return MatrixSub;
}
//Matrix Multiplication
int mRow,nCol,pCol,kcol;
double MatrixMult[9][9];
double (*(Multiplication)(double MatrixA[9][9],double MatrixB[9][9],int mRow,int nCol,int pCol))[9]
{
for(row=1;row<=mRow;row++)
for(col=1;col<=pCol;col++)
{
MatrixMult[row][col]=0.0;
for(kcol=1;kcol<=nCol;kcol++)
MatrixMult[row][col]+=MatrixA[row][kcol]*MatrixB[kcol][col];
}
return MatrixMult;
}
//Interchange Two Rows
double RowTemp[9][9];
double MatrixInter[9][9];
double (*(InterchangeRow)(double MatrixInput[9][9],int Row,int Col,int iRow,int jRow))[9]
{
CopyMatrix(MatrixInput,MatrixInter,Row,Col);
for(col=1;col<=Col;col++)
{
RowTemp[iRow][col]=MatrixInter[iRow][col];
MatrixInter[iRow][col]=MatrixInter[jRow][col];
MatrixInter[jRow][col]=RowTemp[iRow][col];
}
return MatrixInter;
}
//Pivote Downward
double MatrixDown[9][9];
double (*(PivoteDown)(double MatrixInput[9][9],int Row,int Col,int tRow,int tCol))[9]
{
CopyMatrix(MatrixInput,MatrixDown,Row,Col);
Coefficient=MatrixDown[tRow][tCol];
if(Coefficient!=1.0)
for(col=1;col<=Col;col++)
MatrixDown[tRow][col]/=Coefficient;
if(tRow<Row)
for(row=tRow+1;row<=Row;row++)
{
Coefficient=MatrixDown[row][tCol];
for(col=1;col<=Col;col++)
MatrixDown[row][col]-=Coefficient*MatrixDown[tRow][col];
}
return MatrixDown;
}
//Pivote Upward
double MatrixUp[9][9];
double (*(PivoteUp)(double MatrixInput[9][9],int Row,int Col,int tRow,int tCol))[9]
{
CopyMatrix(MatrixInput,MatrixUp,Row,Col);
Coefficient=MatrixUp[tRow][tCol];
if(Coefficient!=1.0)
for(col=1;col<=Col;col++)
MatrixUp[tRow][col]/=Coefficient;
if(tRow>1)
for(row=tRow-1;row>=1;row--)
{
Coefficient=MatrixUp[row][tCol];
for(col=1;col<=Col;col++)
MatrixUp[row][col]-=Coefficient*MatrixUp[tRow][col];
}
return MatrixUp;
}
//Pivote in Determinant
double MatrixPiv[9][9];
double (*(Pivote)(double MatrixInput[9][9],int Dim,int pTarget))[9]
{
CopyMatrix(MatrixInput,MatrixPiv,Dim,Dim);
for(row=pTarget+1;row<=Dim;row++)
{
Coefficient=MatrixPiv[row][pTarget]/MatrixPiv[pTarget][pTarget];
for(col=1;col<=Dim;col++)
{
MatrixPiv[row][col]-=Coefficient*MatrixPiv[pTarget][col];
}
}
return MatrixPiv;
}
//Determinant of Square Matrix
int dCounter,dRow;
double Det;
double MatrixDet[9][9];
double Determinant(double MatrixInput[9][9],int Dim)
{
CopyMatrix(MatrixInput,MatrixDet,Dim,Dim);
Det=1.0;
if(Dim>1)
{
for(dRow=1;dRow<Dim;dRow++)
{
dCounter=dRow;
while((MatrixDet[dRow][dRow]==0.0)&(dCounter<=Dim))
{
dCounter++;
Det*=-1.0;
CopyPointer(InterchangeRow(MatrixDet,Dim,Dim,dRow,dCounter),MatrixDet,Dim,Dim);
}
if(MatrixDet[dRow][dRow]==0)
{
Det=0.0;
break;
}
else
{
Det*=MatrixDet[dRow][dRow];
CopyPointer(Pivote(MatrixDet,Dim,dRow),MatrixDet,Dim,Dim);
}
}
Det*=MatrixDet[Dim][Dim];
}
else Det=MatrixDet[1][1];
return Det;
}
//Matrix Identity
double MatrixIdent[9][9];
double (*(Identity)(int Dim))[9]
{
for(row=1;row<=Dim;row++)
for(col=1;col<=Dim;col++)
if(row==col)
MatrixIdent[row][col]=1.0;
else
MatrixIdent[row][col]=0.0;
return MatrixIdent;
}
//Join Matrix to be Augmented Matrix
double MatrixJoin[9][9];
double (*(JoinMatrix)(double MatrixA[9][9],double MatrixB[9][9],int Row,int ColA,int ColB))[9]
{
Col=ColA+ColB;
for(row=1;row<=Row;row++)
for(col=1;col<=Col;col++)
if(col<=ColA)
MatrixJoin[row][col]=MatrixA[row][col];
else
MatrixJoin[row][col]=MatrixB[row][col-ColA];
return MatrixJoin;
}
//Inverse of Matrix
double (*Pointer)[9];
double IdentMatrix[9][9];
int Counter;
double MatrixAug[9][9];
double MatrixInv[9][9];
double (*(Inverse)(double MatrixInput[9][9],int Dim))[9]
{
Row=Dim;
Col=Dim+Dim;
Pointer=Identity(Dim);
CopyPointer(Pointer,IdentMatrix,Dim,Dim);
Pointer=JoinMatrix(MatrixInput,IdentMatrix,Dim,Dim,Dim);
CopyPointer(Pointer,MatrixAug,Row,Col);
for(Counter=1;Counter<=Dim;Counter++)
{
Pointer=PivoteDown(MatrixAug,Row,Col,Counter,Counter);
CopyPointer(Pointer,MatrixAug,Row,Col);
}
for(Counter=Dim;Counter>1;Counter--)
{
Pointer=PivoteUp(MatrixAug,Row,Col,Counter,Counter);
CopyPointer(Pointer,MatrixAug,Row,Col);
}
for(row=1;row<=Dim;row++)
for(col=1;col<=Dim;col++)
MatrixInv[row][col]=MatrixAug[row][col+Dim];
return MatrixInv;
}
//Gauss-Jordan Elemination
double MatrixGJ[9][9];
double VectorGJ[9][9];
double (*(GaussJordan)(double MatrixInput[9][9],double VectorInput[9][9],int Dim))[9]
{
Row=Dim;
Col=Dim+1;
Pointer=JoinMatrix(MatrixInput,VectorInput,Dim,Dim,1);
CopyPointer(Pointer,MatrixGJ,Row,Col);
for(Counter=1;Counter<=Dim;Counter++)
{
Pointer=PivoteDown(MatrixGJ,Row,Col,Counter,Counter);
CopyPointer(Pointer,MatrixGJ,Row,Col);
}
for(Counter=Dim;Counter>1;Counter--)
{
Pointer=PivoteUp(MatrixGJ,Row,Col,Counter,Counter);
CopyPointer(Pointer,MatrixGJ,Row,Col);
}
for(row=1;row<=Dim;row++)
for(col=1;col<=1;col++)
VectorGJ[row][col]=MatrixGJ[row][col+Dim];
return VectorGJ;
}
//Generalized Gauss-Jordan Elemination
double MatrixGGJ[9][9];
double VectorGGJ[9][9];
double (*(GeneralizedGaussJordan)(double MatrixInput[9][9],double VectorInput[9][9],int Dim,int vCol))[9]
{
Row=Dim;
Col=Dim+vCol;
Pointer=JoinMatrix(MatrixInput,VectorInput,Dim,Dim,vCol);
CopyPointer(Pointer,MatrixGGJ,Row,Col);
for(Counter=1;Counter<=Dim;Counter++)
{
Pointer=PivoteDown(MatrixGGJ,Row,Col,Counter,Counter);
CopyPointer(Pointer,MatrixGGJ,Row,Col);
}
for(Counter=Dim;Counter>1;Counter--)
{
Pointer=PivoteUp(MatrixGGJ,Row,Col,Counter,Counter);
CopyPointer(Pointer,MatrixGGJ,Row,Col);
}
for(row=1;row<=Row;row++)
for(col=1;col<=vCol;col++)
VectorGGJ[row][col]=MatrixGGJ[row][col+Dim];
return VectorGGJ;
}
//Matrix Sparse, Three Diagonal Non-Zero Elements
double MatrixSpa[9][9];
double (*(Sparse)(int Dimension,double FirstElement,double SecondElement,double ThirdElement))[9]
{
MatrixSpa[1][1]=SecondElement;
MatrixSpa[1][2]=ThirdElement;
MatrixSpa[Dimension][Dimension-1]=FirstElement;
MatrixSpa[Dimension][Dimension]=SecondElement;
for(int Counter=2;Counter<Dimension;Counter++)
{
MatrixSpa[Counter][Counter-1]=FirstElement;
MatrixSpa[Counter][Counter]=SecondElement;
MatrixSpa[Counter][Counter+1]=ThirdElement;
}
return MatrixSpa;
}
Copy and save the above code as Matrix.h then try the following code:
#include<iostream>
#include<conio.h>
#include"Matrix.h"
int Dim;
double Matrix[9][9];
int main()
{
cout<<"Enter your matrix dimension: ";
cin>>Dim;
Input(Matrix,Dim,Dim);
cout<<"Your matrix:"<<endl;
Output(Matrix,Dim,Dim);
cout<<"The inverse:"<<endl;
Output(Inverse(Matrix,Dim),Dim,Dim);
getch();
}
How do I detect the Python version at runtime?
Just in case you want to see all of the gory details in human readable form, you can use:
import platform;
print(platform.sys.version);
Output for my system:
3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0]
Something very detailed but machine parsable would be to get the version_info
object from platform.sys
, instead, and then use its properties to take a predetermined course of action. For example:
import platform;
print(platform.sys.version_info)
Output on my system:
sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)
How to find the minimum value of a column in R?
Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str()
.
min(as.numeric(data[,2]))
Is there a default password to connect to vagrant when using `homestead ssh` for the first time?
I've a same problem. After move machine from restore of Time Machine, on another host. There problem it's that ssh key for vagrant it's not your key, it's a key on Homestead directory.
Solution for me:
- Use vagrant / vagrant for access ti VM of Homestead
- vagrant ssh-config for see config of ssh
run on terminal
vagrant ssh-config
Host default
HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile "/Users/MYUSER/.vagrant.d/insecure_private_key"
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes
Create a new pair of SSH keys
ssh-keygen -f /Users/MYUSER/.vagrant.d/insecure_private_key
Copy content of public key
cat /Users/MYUSER/.vagrant.d/insecure_private_key.pub
On other shell in Homestead VM Machine copy into authorized_keys
vagrant@homestad:~$ echo 'CONTENT_PASTE_OF_PRIVATE_KEY' >> ~/.ssh/authorized_keys
Now can access with vagrant ssh
How can change width of dropdown list?
The dropdown width itself cannot be set. It's width depend on the option-values. See also here ( jsfiddle.net/LgS3C/ )
How the select box looks like is also depending on your browser.
You can build your own control or use Select2
https://select2.org
VBA: activating/selecting a worksheet/row/cell
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
Memcached vs. Redis?
Use Redis if
You require selectively deleting/expiring items in the cache. (You need this)
You require the ability to query keys of a particular type. eq. 'blog1:posts:*', 'blog2:categories:xyz:posts:*'. oh yeah! this is very important. Use this to invalidate certain types of cached items selectively. You can also use this to invalidate fragment cache, page cache, only AR objects of a given type, etc.
Persistence (You will need this too, unless you are okay with your cache having to warm up after every restart. Very essential for objects that seldom change)
Use memcached if
- Memcached gives you headached!
- umm... clustering? meh. if you gonna go that far, use Varnish and Redis for caching fragments and AR Objects.
From my experience I've had much better stability with Redis than Memcached
Accessing elements by type in javascript
In plain-old JavaScript you can do this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'text') {
alert(inputs[i].value);
}
}
In jQuery, you would just do:
// select all inputs of type 'text' on the page
$("input:text")
// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();
How to ignore conflicts in rpm installs
The --force
option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.
If you tell rpm
to install all RPMs from some directory, then it does exactly this. rpm
will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.
You can remove the old RPM and rpm
will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.
If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm
to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i
(zypper in
can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.
I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles
. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify
command. It will complain for the new package if the old one has overwritten some files.
Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?
Automatically start a Windows Service on install
Despite following the accepted answer exactly, I was still unable to get the service to start-- I was instead given a failure message during installation stating that the service that was just installed could not be started, as it did not exist, despite using this.serviceInstaller.ServiceName
rather than a literal...
I eventually found an alternative solution that makes use of the command line:
private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e) {
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C sc start " + this.serviceInstaller.ServiceName;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
}
Increase days to php current Date()
The simplest way to add x no. of days..
echo date('Y-m-d',strtotime('+1 day')); //+1 day from today
OR from specified date...
echo date('Y-m-d',strtotime('+1 day', strtotime('2007-02-28')));
Convert Word doc, docx and Excel xls, xlsx to PDF with PHP
Step 1. Install "Apache_OpenOffice_4.1.2" in your system
Step 2. Download "unoconv" library from github or any where else.
-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory
-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder
-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf
-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.
If pdf not created than last step is
Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop
Create sample .php file and put below code and run on wamp or xampp server
$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);
This code working for me in windows-8 operating system
how to get curl to output only http response body (json) and no other headers etc
I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.
From the curl man page:
-s, --silent
Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.
Below the examples:
curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"
Using custom headers
curl -s -H "Accept: application/json" "http://host:8080/some/resource")
Using POST method with a header
curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'
You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:
curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"
Get enum values as List of String in Java 8
You can do (pre-Java 8):
List<Enum> enumValues = Arrays.asList(Enum.values());
or
List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));
Using Java 8 features, you can map each constant to its name:
List<String> enumNames = Stream.of(Enum.values())
.map(Enum::name)
.collect(Collectors.toList());
Order by descending date - month, day and year
I'm guessing EventDate
is a char or varchar and not a date otherwise your order by clause would be fine.
You can use CONVERT to change the values to a date and sort by that
SELECT *
FROM
vw_view
ORDER BY
CONVERT(DateTime, EventDate,101) DESC
The problem with that is, as Sparky points out in the comments, if EventDate has a value that can't be converted to a date the query won't execute.
This means you should either exclude the bad rows or let the bad rows go to the bottom of the results
To exclude the bad rows just add WHERE IsDate(EventDate) = 1
To let let the bad dates go to the bottom you need to use CASE
e.g.
ORDER BY
CASE
WHEN IsDate(EventDate) = 1 THEN CONVERT(DateTime, EventDate,101)
ELSE null
END DESC
jQuery: get data attribute
Change IDs and data attributes as you wish!
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
CORS - How do 'preflight' an httprequest?
During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.
For example, suppose the browser makes a request with the following headers:
Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header
Your server should then respond with the following headers:
Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header
Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.
Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/
extract part of a string using bash/cut/split
Using a single Awk:
... | awk -F '[/:]' '{print $5}'
That is, using as field separator either /
or :
, the username is always in field 5.
To store it in a variable:
username=$(... | awk -F '[/:]' '{print $5}')
A more flexible implementation with sed
that doesn't require username to be field 5:
... | sed -e s/:.*// -e s?.*/??
That is, delete everything from :
and beyond, and then delete everything up until the last /
. sed
is probably faster too than awk
, so this alternative is definitely better.