Remove unwanted parts from strings in a column
How do I remove unwanted parts from strings in a column?
6 years after the original question was posted, pandas now has a good number of "vectorised" string functions that can succinctly perform these string manipulation operations.
This answer will explore some of these string functions, suggest faster alternatives, and go into a timings comparison at the end.
Specify the substring/pattern to match, and the substring to replace it with.
pd.__version__
# '0.24.1'
df
time result
1 09:00 +52A
2 10:00 +62B
3 11:00 +44a
4 12:00 +30b
5 13:00 -110a
df['result'] = df['result'].str.replace(r'\D', '')
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
If you need the result converted to an integer, you can use Series.astype
,
df['result'] = df['result'].str.replace(r'\D', '').astype(int)
df.dtypes
time object
result int64
dtype: object
If you don't want to modify df
in-place, use DataFrame.assign
:
df2 = df.assign(result=df['result'].str.replace(r'\D', ''))
df
# Unchanged
Useful for extracting the substring(s) you want to keep.
df['result'] = df['result'].str.extract(r'(\d+)', expand=False)
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
With extract
, it is necessary to specify at least one capture group. expand=False
will return a Series with the captured items from the first capture group.
Splitting works assuming all your strings follow this consistent structure.
# df['result'] = df['result'].str.split(r'\D').str[1]
df['result'] = df['result'].str.split(r'\D').str.get(1)
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
Do not recommend if you are looking for a general solution.
If you are satisfied with the succinct and readable str
accessor-based solutions above, you can stop here. However, if you are
interested in faster, more performant alternatives, keep reading.
Optimizing: List Comprehensions
In some circumstances, list comprehensions should be favoured over pandas string functions. The reason is because string functions are inherently hard to vectorize (in the true sense of the word), so most string and regex functions are only wrappers around loops with more overhead.
My write-up, Are for-loops in pandas really bad? When should I care?, goes into greater detail.
The str.replace
option can be re-written using re.sub
import re
# Pre-compile your regex pattern for more performance.
p = re.compile(r'\D')
df['result'] = [p.sub('', x) for x in df['result']]
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
The str.extract
example can be re-written using a list comprehension with re.search
,
p = re.compile(r'\d+')
df['result'] = [p.search(x)[0] for x in df['result']]
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
If NaNs or no-matches are a possibility, you will need to re-write the above to include some error checking. I do this using a function.
def try_extract(pattern, string):
try:
m = pattern.search(string)
return m.group(0)
except (TypeError, ValueError, AttributeError):
return np.nan
p = re.compile(r'\d+')
df['result'] = [try_extract(p, x) for x in df['result']]
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
We can also re-write @eumiro's and @MonkeyButter's answers using list comprehensions:
df['result'] = [x.lstrip('+-').rstrip('aAbBcC') for x in df['result']]
And,
df['result'] = [x[1:-1] for x in df['result']]
Same rules for handling NaNs, etc, apply.
Performance Comparison
Graphs generated using perfplot. Full code listing, for your reference. The relevant functions are listed below.
Some of these comparisons are unfair because they take advantage of the structure of OP's data, but take from it what you will. One thing to note is that every list comprehension function is either faster or comparable than its equivalent pandas variant.
Functions
def eumiro(df):
return df.assign(
result=df['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC')))
def coder375(df):
return df.assign(
result=df['result'].replace(r'\D', r'', regex=True))
def monkeybutter(df):
return df.assign(result=df['result'].map(lambda x: x[1:-1]))
def wes(df):
return df.assign(result=df['result'].str.lstrip('+-').str.rstrip('aAbBcC'))
def cs1(df):
return df.assign(result=df['result'].str.replace(r'\D', ''))
def cs2_ted(df):
# `str.extract` based solution, similar to @Ted Petrou's. so timing together.
return df.assign(result=df['result'].str.extract(r'(\d+)', expand=False))
def cs1_listcomp(df):
return df.assign(result=[p1.sub('', x) for x in df['result']])
def cs2_listcomp(df):
return df.assign(result=[p2.search(x)[0] for x in df['result']])
def cs_eumiro_listcomp(df):
return df.assign(
result=[x.lstrip('+-').rstrip('aAbBcC') for x in df['result']])
def cs_mb_listcomp(df):
return df.assign(result=[x[1:-1] for x in df['result']])
MVC Razor Hidden input and passing values
If you are using Razor, you cannot access the field directly, but you can manage its value.
The idea is that the first Microsoft approach drive the developers away from Web Development and make it easy for Desktop programmers (for example) to make web applications.
Meanwhile, the web developers, did not understand this tricky strange way of ASP.NET.
Actually this hidden input is rendered on client-side, and the ASP has no access to it (it never had). However, in time you will see its a piratical way and you may rely on it, when you get use with it. The web development differs from the Desktop or Mobile.
The model is your logical unit, and the hidden field (and the whole view page) is just a representative view of the data. So you can dedicate your work on the application or domain logic and the view simply just serves it to the consumer - which means you need no detailed access and "brainstorming" functionality in the view.
The controller actually does work you need for manage the hidden or general setup. The model serves specific logical unit properties and functionality and the view just renders it to the end user, simply said. Read more about MVC.
Model
public class MyClassModel
{
public int Id { get; set; }
public string Name { get; set; }
public string MyPropertyForHidden { get; set; }
}
This is the controller aciton
public ActionResult MyPageView()
{
MyClassModel model = new MyClassModel(); // Single entity, strongly-typed
// IList model = new List<MyClassModel>(); // or List, strongly-typed
// ViewBag.MyHiddenInputValue = "Something to pass"; // ...or using ViewBag
return View(model);
}
The view is below
//This will make a Model property of the View to be of MyClassModel
@model MyNamespace.Models.MyClassModel // strongly-typed view
// @model IList<MyNamespace.Models.MyClassModel> // list, strongly-typed view
// ... Some Other Code ...
@using(Html.BeginForm()) // Creates <form>
{
// Renders hidden field for your model property (strongly-typed)
// The field rendered to server your model property (Address, Phone, etc.)
Html.HiddenFor(model => Model.MyPropertyForHidden);
// For list you may use foreach on Model
// foreach(var item in Model) or foreach(MyClassModel item in Model)
}
// ... Some Other Code ...
The view with ViewBag:
// ... Some Other Code ...
@using(Html.BeginForm()) // Creates <form>
{
Html.Hidden(
"HiddenName",
ViewBag.MyHiddenInputValue,
new { @class = "hiddencss", maxlength = 255 /*, etc... */ }
);
}
// ... Some Other Code ...
We are using Html Helper to render the Hidden field or we could write it by hand - <input name=".." id=".." value="ViewBag.MyHiddenInputValue">
also.
The ViewBag is some sort of data carrier to the view. It does not restrict you with model - you can place whatever you like.
How to delete all instances of a character in a string in python?
>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'
Since your code would only replace the first instance, I assumed that's what you wanted. If you want to replace them all, leave off the 1
argument.
Since you cannot replace the character in the string itself, you have to reassign it back to the variable. (Essentially, you have to update the reference instead of modifying the string.)
Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time
You are definitely missing a small thing and that is you are not setting a default value:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
So the code would look like:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
Explanation: If you want to change the time zone, set the default time zone using TimeZone.setDefault()
Should I declare Jackson's ObjectMapper as a static field?
A trick I learned from this PR if you don't want to define it as a static final variable but want to save a bit of overhead and guarantee thread safe.
private static final ThreadLocal<ObjectMapper> om = new ThreadLocal<ObjectMapper>() {
@Override
protected ObjectMapper initialValue() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}
};
public static ObjectMapper getObjectMapper() {
return om.get();
}
credit to the author.
How to print the current time in a Batch-File?
You can use the command time /t
for the time and date /t
for the date, here is an example:
@echo off
time /t >%tmp%\time.tmp
date /t >%tmp%\date.tmp
set ttime=<%tmp%\time.tmp
set tdate=<%tmp%\date.tmp
del /f /q %tmp%\time.tmp
del /f /q %tmp%\date.tmp
echo Time: %ttime%
echo Date: %tdate%
pause >nul
You can also use the built in variables %time% and %date%, here is another example:
@echo off
echo Time: %time:~0,5%
echo Date: %date%
pause >nul
JQuery $.ajax() post - data in a java servlet
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
How to change the style of a DatePicker in android?
Create custom DatePickerDialog
style:
<style name="AppTheme.DatePickerDialog" parent="Theme.MaterialComponents.Light.Dialog">
<item name="android:colorAccent">@color/colorPrimary</item>
<item name="android:colorControlActivated">@color/colorPrimaryDark</item>
<item name="android:buttonBarPositiveButtonStyle">@style/AppTheme.Alert.Button.Positive</item>
<item name="android:buttonBarNegativeButtonStyle">@style/AppTheme.Alert.Button.Negative</item>
<item name="android:buttonBarNeutralButtonStyle">@style/AppTheme.Alert.Button.Neutral</item>
</style>
<style name="AppTheme.Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
<item name="android:textColor">@color/buttonPositive</item>
</style>
<style name="AppTheme.Alert.Button.Negative" parent="Widget.MaterialComponents.Button.TextButton">
<item name="android:textColor">@color/buttonNegative</item>
</style>
<style name="AppTheme.Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
<item name="android:textColor">@color/buttonNeutral</item>
</style>
Set custom datePickerDialogTheme
style in app theme:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="android:datePickerDialogTheme">@style/AppTheme.DatePickerDialog</item>
</style>
Set theme programmatically on initialization like this:
val datetime = DatePickerDialog(this, R.style.AppTheme_DatePickerDialog)
AngularJS dynamic routing
In the $routeProvider URI patters, you can specify variable parameters, like so: $routeProvider.when('/page/:pageNumber' ...
, and access it in your controller via $routeParams.
There is a good example at the end of the $route page: http://docs.angularjs.org/api/ng.$route
EDIT (for the edited question):
The routing system is unfortunately very limited - there is a lot of discussion on this topic, and some solutions have been proposed, namely via creating multiple named views, etc.. But right now, the ngView directive serves only ONE view per route, on a one-to-one basis. You can go about this in multiple ways - the simpler one would be to use the view's template as a loader, with a <ng-include src="myTemplateUrl"></ng-include>
tag in it ($scope.myTemplateUrl would be created in the controller).
I use a more complex (but cleaner, for larger and more complicated problems) solution, basically skipping the $route service altogether, that is detailed here:
http://www.bennadel.com/blog/2420-Mapping-AngularJS-Routes-Onto-URL-Parameters-And-Client-Side-Events.htm
AngularJS - Binding radio buttons to models with boolean values
I tried changing value="true"
to ng-value="true"
, and it seems to work.
<input type="radio" name="response2" data-ng-model="choice.isUserAnswer" ng-value="true" />
Also, to get both inputs to work in your example, you'd have to give different name to each input -- e.g. response
should become response1
and response2
.
check if command was successful in a batch file
I don't know if javaw will write to the %errorlevel% variable, but it might.
echo %errorlevel%
after you run it directly to see.
Other than that, you can pipe the output of javaw to a file, then use find
to see what the results were. Without knowing the output of it, I can't really help you with that.
Prevent double submission of forms in jQuery
Update in 2018: I just got some points for this old answer, and just wanted to add that the best solution would be to make the operation idempotent so that duplicate submissions are harmless.
Eg, if the form creates an order, put a unique ID in the form. The first time the server sees an order creation request with that id, it should create it and respond "success". Subsequent submissions should also respond "success" (in case the client didn't get the first response) but shouldn't change anything.
Duplicates should be detected via a uniqueness check in the database to prevent race conditions.
I think that your problem is this line:
$('input').attr('disabled','disabled');
You're disabling ALL the inputs, including, I'd guess, the ones whose data the form is supposed to submit.
To disable just the submit button(s), you could do this:
$('button[type=submit], input[type=submit]').prop('disabled',true);
However, I don't think IE will submit the form if even those buttons are disabled. I'd suggest a different approach.
A jQuery plugin to solve it
We just solved this problem with the following code. The trick here is using jQuery's data()
to mark the form as already submitted or not. That way, we don't have to mess with the submit buttons, which freaks IE out.
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
Use it like this:
$('form').preventDoubleSubmission();
If there are AJAX forms that should be allowed to submit multiple times per page load, you can give them a class indicating that, then exclude them from your selector like this:
$('form:not(.js-allow-double-submission)').preventDoubleSubmission();
Rails migration for change column
This is all assuming that the datatype of the column has an implicit conversion for any existing data. I've run into several situations where the existing data, let's say a String
can be implicitly converted into the new datatype, let's say Date
.
In this situation, it's helpful to know you can create migrations with data conversions. Personally, I like putting these in my model file, and then removing them after all database schemas have been migrated and are stable.
/app/models/table.rb
...
def string_to_date
update(new_date_field: date_field.to_date)
end
def date_to_string
update(old_date_field: date_field.to_s)
end
...
def up
# Add column to store converted data
add_column :table_name, :new_date_field, :date
# Update the all resources
Table.all.each(&:string_to_date)
# Remove old column
remove_column :table_name, :date_field
# Rename new column
rename_column :table_name, :new_date_field, :date_field
end
# Reversed steps does allow for migration rollback
def down
add_column :table_name, :old_date_field, :string
Table.all.each(&:date_to_string)
remove_column :table_name, :date_field
rename_column :table_name, :old_date_field, :date_field
end
CSS3 opacity gradient?
You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.
CSS:
p {
color: red;
-webkit-mask-image: -webkit-gradient(linear, left top, left bottom,
from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}
The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)
See a demo with a solid background, but you can change this to whatever you want.
DEMO
Notice also that all the usual image properties are available for mask-image
_x000D_
_x000D_
p {_x000D_
color: red;_x000D_
font-size: 30px;_x000D_
-webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
-webkit-mask-size: 100% 50%;_x000D_
-webkit-mask-repeat: no-repeat;_x000D_
-webkit-mask-position: left top, left bottom;_x000D_
}_x000D_
_x000D_
div {_x000D_
background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_
Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.
The idea is to use
mix-blend-mode: hard-light;
that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency
_x000D_
_x000D_
div {_x000D_
background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
color: red;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
width: 200px;_x000D_
mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
position: absolute;_x000D_
content: "";_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
background: linear-gradient(transparent, gray);_x000D_
pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_
Can promises have multiple arguments to onFulfilled?
Great question, and great answer by Benjamin, Kris, et al - many thanks!
I'm using this in a project and have created a module based on Benjamin Gruenwald's code. It's available on npmjs:
npm i -S promise-spread
Then in your code, do
require('promise-spread');
If you're using a library such as any-promise
var Promise = require('any-promise');
require('promise-spread')(Promise);
Maybe others find this useful, too!
Pods stuck in Terminating status
I'd not recommend force deleting pods unless container already exited.
- Verify kubelet logs to see what is causing the issue "journalctl -u kubelet"
- Verify docker logs: journalctl -u docker.service
- Check if pod's volume mount points still exist and if anyone holds lock on it.
- Verify if host is out of memory or disk
Abstract methods in Java
Abstract methods means there is no default implementation for it and an implementing class will provide the details.
Essentially, you would have
abstract class AbstractObject {
public abstract void method();
}
class ImplementingObject extends AbstractObject {
public void method() {
doSomething();
}
}
So, it's exactly as the error states: your abstract method can not have a body.
There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.
A very simple example would be shapes:
You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.
(This is taken from the site I linked above)
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
Setting up a cron job in Windows
There's pycron which I really as a Cron implementation for windows, but there's also the built in scheduler which should work just fine for what you need (Control Panel -> Scheduled Tasks -> Add Scheduled Task).
How do SETLOCAL and ENABLEDELAYEDEXPANSION work?
The ENABLEDELAYEDEXPANSION part is REQUIRED in certain programs that use delayed expansion, that is, that takes the value of variables that were modified inside IF or FOR commands by enclosing their names in exclamation-marks.
If you enable this expansion in a script that does not require it, the script behaves different only if it contains names enclosed in exclamation-marks !LIKE! !THESE!. Usually the name is just erased, but if a variable with the same name exist by chance, then the result is unpredictable and depends on the value of such variable and the place where it appears.
The SETLOCAL part is REQUIRED in just a few specialized (recursive) programs, but is commonly used when you want to be sure to not modify any existent variable with the same name by chance or if you want to automatically delete all the variables used in your program. However, because there is not a separate command to enable the delayed expansion, programs that require this must also include the SETLOCAL part.
Rotating a Vector in 3D Space
If you want to rotate a vector you should construct what is known as a rotation matrix.
Rotation in 2D
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
Rotation in 3D
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
Rotation not Revolution
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
Composition
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
Rotation around Arbitrary Vector
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
How to stop asynctask thread in android?
You can't just kill asynctask immediately. In order it to stop you should first cancel it:
task.cancel(true);
and than in asynctask's doInBackground() method check if it's already cancelled:
isCancelled()
and if it is, stop executing it manually.
Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail
I consider that should escape the last < to \x3C in string. When the browser sees , it considers this to be the end of the script block (since the HTML parser has no idea about JavaScript, it can't distinguish between something that just appears in a string, and something that's actually meant to end the script element). So appearing literally in JavaScript that's inside an HTML page will (in the best case) cause errors, and (in the worst case) be a huge security hole.
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-2.0.0.min.js">\x3C/script>')</script>
How to find current transaction level?
If you are talking about the current transaction nesting level, then you would use @@TRANCOUNT
.
If you are talking about transaction isolation level, use DBCC USEROPTIONS
and look for an option of isolation level. If it isn't set, it's read committed.
Is there any way to specify a suggested filename when using data: URI?
Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.
var exportFileName = "export-" + filename;
$('<a></a>', {
"download": exportFileName,
"href": "data:," + JSON.stringify(exportData, null,5),
"id": "exportDataID"
}).appendTo("body")[0].click().remove();
How to find NSDocumentDirectory in Swift?
Xcode 8.2.1 • Swift 3.0.2
let documentDirectoryURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
Xcode 7.1.1 • Swift 2.1
let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
"Could not get any response" response when using postman with subdomain
I just experienced this error. In my case, the path was TOO LONG. So url like that gave me this error in postman (fake example)
http://127.0.0.1:5000/api/batch/upload_import_deactivate_from_ready_folder
whereas
http://127.0.0.1:5000/api/batch/upld_impt_deac_ready_folder
worked fine.
Hope it helps someone who by accident read that far...
Pandas group-by and sum
df.groupby(['Fruit','Name'])['Number'].sum()
You can select different columns to sum numbers.
How can I connect to Android with ADB over TCP?
On my system it went like this:
On my Android device in my Linux shell, a simple "ifconfig" did not give me my IP address. I had to type:
ifconfig eth0
-or-
netcfg
to get my IP address. (I knew eth0 was configured because I saw it in my dmesg.) Then I did the :
setprop service.adb.tcp.port -1
stop adbd
start adbd
Then on my Win7 box (the one running Eclipse 3.7.1). I opened a command prompt to
\android-sdk\platform-tools>
without running as admin. Then I did a
adb connect 12.345.678.90
I never put a port. If I did a
adb tcpip 5555
it said it couldn't find the device then nothing appeared in my "adb devices" list. I.e. it only works if I DON'T do the tcpip command above.
I can do an "adb shell" and mess with my Android Device. But my Android Device does not appear in my Run->Run Configurations->Target tab right now. On the other hand, if I keep the Target Tab set to automatic. Then when I run my app via Run->Run it does run on my Android device even though my Android device is not even listed as one of my targets.
What's the difference between utf8_general_ci and utf8_unicode_ci?
For those people still arriving at this question in 2020 or later, there are newer options that may be better than both of these. For example, utf8mb4_0900_ai_ci
.
All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared.
_unicode_ci
and _general_ci
are two different sets of rules for sorting and comparing text according to the way we expect. Newer versions of MySQL introduce new sets of rules, too, such as _0900_ai_ci
for equivalent rules based on Unicode 9.0 - and with no equivalent _general_ci
variant. People reading this now should probably use one of these newer collations instead of either _unicode_ci
or _general_ci
. The description of those older collations below is provided for interest only.
MySQL is currently transitioning away from an older, flawed UTF-8 implementation. For now, you need to use utf8mb4
instead of utf8
for the character encoding part, to ensure you are getting the fixed version. The flawed version remains for backward compatibility, though it is being deprecated.
Key differences
utf8mb4_unicode_ci
is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.
utf8mb4_general_ci
is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.
On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today's computers.
Benefits of utf8mb4_unicode_ci
over utf8mb4_general_ci
utf8mb4_unicode_ci
, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call 'alphabetical order'.
As far as Latin (ie "European") languages go, there is not much difference between the Unicode sorting and the simplified utf8mb4_general_ci
sorting in MySQL, but there are still a few differences:
For examples, the Unicode collation sorts "ß" like "ss", and "Œ" like "OE" as people using those characters would normally want, whereas utf8mb4_general_ci
sorts them as single characters (presumably like "s" and "e" respectively).
Some Unicode characters are defined as ignorable, which means they shouldn't count toward the sort order and the comparison should move on to the next character instead. utf8mb4_unicode_ci
handles these properly.
In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8mb4_general_ci
sorting. The suitability of utf8mb4_general_ci
will depend heavily on the language used. For some languages, it'll be quite inadequate.
What should you use?
There is almost certainly no reason to use utf8mb4_general_ci
anymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.
In the past, some people recommended to use utf8mb4_general_ci
except when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.
There's an argument to be made that if speed is more important to you than accuracy, you may as well not do any sorting at all. It's trivial to make an algorithm faster if you do not need it to be accurate. So, utf8mb4_general_ci
is a compromise that's probably not needed for speed reasons and probably also not suitable for accuracy reasons.
One other thing I'll add is that even if you know your application only supports the English language, it may still need to deal with people's names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.
What the parts mean
Firstly, ci
is for case-insensitive sorting and comparison. This means it's suitable for textual data, and case is not important. The other types of collation are cs
(case-sensitive) for textual data where case is important, and bin
, for where the encoding needs to match, bit for bit, which is suitable for fields which are really encoded binary data (including, for example, Base64). Case-sensitive sorting leads to some weird results and case-sensitive comparison can result in duplicate values differing only in letter case, so case-sensitive collations are falling out of favor for textual data - if case is significant to you, then otherwise ignorable punctuation and so on is probably also significant, and a binary collation might be more appropriate.
Next, unicode
or general
refers to the specific sorting and comparison rules - in particular, the way text is normalized or compared. There are many different sets of rules for the utf8mb4 character encoding, with unicode
and general
being two that attempt to work well in all possible languages rather than one specific one. The differences between these two sets of rules are the subject of this answer. Note that unicode
uses rules from Unicode 4.0. Recent versions of MySQL add the rulesets unicode_520
using rules from Unicode 5.2, and 0900
(dropping the "unicode_" part) using rules from Unicode 9.0.
And lastly, utf8mb4
is of course the character encoding used internally. In this answer I'm talking only about Unicode based encodings.
How can I convert an HTML element to a canvas element?
Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:
rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>'
+ '<img src="local_img.png"/>', canvas);
Source code and a more extensive example is here.
Can I connect to SQL Server using Windows Authentication from Java EE webapp?
This actually works for me:
Per the README.SSO that comes with the jtdsd distribution:
In order for Single Sign On to work, jTDS must be able to load the native SPPI library ntlmauth.dll
. Place this DLL anywhere in the system path (defined by the PATH
system variable) and you're all set.
I placed it in my jre/bin folder
I configured a port dedicated the sql server instance (2302) to alleviate the need for an instance name - just something I do. lportal is my database name.
jdbc.default.url=jdbc:jtds:sqlserver://192.168.0.147:2302/lportal;useNTLMv2=true;domain=mydomain.local
How do I append text to a file?
How about:
echo "hello" >> <filename>
Using the >>
operator will append data at the end of the file, while using the >
will overwrite the contents of the file if already existing.
You could also use printf
in the same way:
printf "hello" >> <filename>
Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last >
all data in the file will be destroyed. You can change this behavior by setting the noclobber
variable in your .bashrc
:
set -o noclobber
Now when you try to do echo "hello" > file.txt
you will get a warning saying cannot overwrite existing file
.
To force writing to the file you must now use the special syntax:
echo "hello" >| <filename>
You should also know that by default echo
adds a trailing new-line character which can be suppressed by using the -n
flag:
echo -n "hello" >> <filename>
References
add column to mysql table if it does not exist
Another way to do this would be to ignore the error with a declare continue handler
:
delimiter ;;
create procedure foo ()
begin
declare continue handler for 1060 begin end;
alter table atable add subscriber_surname varchar(64);
end;;
call foo();;
I think its neater this way than with an exists
subquery. Especially if you have a lot of columns to add, and you want to run the script several times.
more info on continue handlers can be found at http://dev.mysql.com/doc/refman/5.0/en/declare-handler.html
How to set caret(cursor) position in contenteditable element (div)?
Based on Tim Down's answer, but it checks for the last known "good" text row. It places the cursor at the very end.
Furthermore, I could also recursively/iteratively check the last child of each consecutive last child to find the absolute last "good" text node in the DOM.
_x000D_
_x000D_
function onClickHandler() {_x000D_
setCaret(document.getElementById("editable"));_x000D_
}_x000D_
_x000D_
function setCaret(el) {_x000D_
let range = document.createRange(),_x000D_
sel = window.getSelection(),_x000D_
lastKnownIndex = -1;_x000D_
for (let i = 0; i < el.childNodes.length; i++) {_x000D_
if (isTextNodeAndContentNoEmpty(el.childNodes[i])) {_x000D_
lastKnownIndex = i;_x000D_
}_x000D_
}_x000D_
if (lastKnownIndex === -1) {_x000D_
throw new Error('Could not find valid text content');_x000D_
}_x000D_
let row = el.childNodes[lastKnownIndex],_x000D_
col = row.textContent.length;_x000D_
range.setStart(row, col);_x000D_
range.collapse(true);_x000D_
sel.removeAllRanges();_x000D_
sel.addRange(range);_x000D_
el.focus();_x000D_
}_x000D_
_x000D_
function isTextNodeAndContentNoEmpty(node) {_x000D_
return node.nodeType == Node.TEXT_NODE && node.textContent.trim().length > 0_x000D_
}
_x000D_
<div id="editable" contenteditable="true">_x000D_
text text text<br>text text text<br>text text text<br>_x000D_
</div>_x000D_
<button id="button" onclick="onClickHandler()">focus</button>
_x000D_
_x000D_
_x000D_
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
C++ Matrix Class
you could do it with a template, if the matrix size is known at compile-time :
template <int width, int height>
class Matrix{
double data[height][width];
//...member functions
};
PHP salt and hash SHA256 for login password
According to php.net the Salt option has been deprecated as of PHP 7.0.0, so you should use the salt that is generated by default and is far more simpler
Example for store the password:
$hashPassword = password_hash("password", PASSWORD_BCRYPT);
Example to verify the password:
$passwordCorrect = password_verify("password", $hashPassword);
How can I change a file's encoding with vim?
Just like your steps, setting fileencoding should work. However, I'd like to add one "set bomb" to help editor consider the file as UTF8.
$ vim file
:set bomb
:set fileencoding=utf-8
:wq
Return 0 if field is null in MySQL
None of the above answers were complete for me.
If your field is named field
, so the selector should be the following one:
IFNULL(`field`,0) AS field
For example in a SELECT query:
SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`
Hope this can help someone to not waste time.
Convert NaN to 0 in javascript
Something simpler and effective for anything :
function getNum(val) {
val = +val || 0
return val;
}
...which will convert a from any "falsey" value to 0
.
The "falsey" values are:
false
null
undefined
0
""
( empty string )
NaN
( Not a Number )
Restrict SQL Server Login access to only one database
this is to topup to what was selected as the correct answer. It has one missing step that when not done, the user will still be able to access the rest of the database.
First, do as @DineshDB suggested
1. Connect to your SQL server instance using management studio
2. Goto Security -> Logins -> (RIGHT CLICK) New Login
3. fill in user details
4. Under User Mapping, select the databases you want the user to be able to access and configure
the missing step is below:
5. Under user mapping, ensure that "sysadmin" is NOT CHECKED and select "db_owner" as the role for the new user.
And thats it.
What data type to use for money in Java?
You can use Money and Currency API (JSR 354). You can use this API in, provided you add appropriate dependencies to your project.
For Java 8, add the following reference implementation as a dependency to your pom.xml
:
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.0</version>
</dependency>
This dependency will transitively add javax.money:money-api
as a dependency.
You can then use the API:
package com.example.money;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
import java.util.Locale;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.MonetaryRounding;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import org.junit.Test;
public class MoneyTest {
@Test
public void testMoneyApi() {
MonetaryAmount eurAmount1 = Monetary.getDefaultAmountFactory().setNumber(1.1111).setCurrency("EUR").create();
MonetaryAmount eurAmount2 = Monetary.getDefaultAmountFactory().setNumber(1.1141).setCurrency("EUR").create();
MonetaryAmount eurAmount3 = eurAmount1.add(eurAmount2);
assertThat(eurAmount3.toString(), is("EUR 2.2252"));
MonetaryRounding defaultRounding = Monetary.getDefaultRounding();
MonetaryAmount eurAmount4 = eurAmount3.with(defaultRounding);
assertThat(eurAmount4.toString(), is("EUR 2.23"));
MonetaryAmountFormat germanFormat = MonetaryFormats.getAmountFormat(Locale.GERMAN);
assertThat(germanFormat.format(eurAmount4), is("EUR 2,23") );
}
}
How does internationalization work in JavaScript?
Mozilla recently released the awesome L20n or localization 2.0. In their own words L20n is
an open source, localization-specific scripting language used to process gender, plurals, conjugations, and most of the other quirky elements of natural language.
Their js implementation is on the github L20n repository.
How to use S_ISREG() and S_ISDIR() POSIX Macros?
[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);
int main(int argc, char *argv[]){
DIR *dip;
struct dirent *dit;
struct stat statbuf;
char currentPath[FILENAME_MAX];
int depth = 0; /*Used to correctly space output*/
/*Open Current Directory*/
if((dip = opendir(".")) == NULL)
return errno;
/*Store Current Working Directory in currentPath*/
if((getcwd(currentPath, FILENAME_MAX)) == NULL)
return errno;
/*Read all items in directory*/
while((dit = readdir(dip)) != NULL){
/*Skips . and ..*/
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
/*Correctly forms the path for stat and then resets it for rest of algorithm*/
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
if(stat(currentPath, &statbuf) == -1){
perror("stat");
return errno;
}
getcwd(currentPath, FILENAME_MAX);
/*Checks if current item is of the type file (type 8) and no command line arguments*/
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*If a command line argument is given, checks for filename match*/
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
if(strcmp(dit->d_name, argv[1]) == 0)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*Checks if current item is of the type directory (type 4)*/
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
closedir(dip);
return 0;
}
/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
if((dip = opendir(currentPath)) == NULL)
printf("Error: Failed to open Directory ==> %s\n", currentPath);
while((dit = readdir(dip)) != NULL){
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
stat(currentPath, &statbuf);
getcwd(currentPath, FILENAME_MAX);
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
if(strcmp(dit->d_name, argv[1]) == 0){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
}
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
/*Changing back here is necessary because of how stat is done*/
chdir("..");
closedir(dip);
}
void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
/*If two directories exist at the same level the path
is built wrong and needs to be corrected*/
if((chdir(currentPath)) == -1){
chdir("..");
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
for(i = 0; i < depth; i++)
printf (" ");
printf("%s (subdirectory)\n", dit->d_name);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
else{
for(i =0; i < depth; i++)
printf(" ");
printf("%s (subdirectory)\n", dit->d_name);
chdir(currentPath);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
}
How to install Flask on Windows?
heres a step by step procedure (assuming you've already installed python):
- first install chocolatey:
open terminal (Run as Administrator) and type in the command line:
C:/> @powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin
it will take some time to get chocolatey installed on your machine. sit back n relax...
now install pip. type in terminal
cinst easy.install pip
now type in terminal:
pip install flask
YOU'RE DONE !!!
Tested on Win 8.1 with Python 2.7
Multidimensional Lists in C#
It's old but thought I'd add my two cents...
Not sure if it will work but try using a KeyValuePair:
List<KeyValuePair<?, ?>> LinkList = new List<KeyValuePair<?, ?>>();
LinkList.Add(new KeyValuePair<?, ?>(Object, Object));
You'll end up with something like this:
LinkList[0] = <Object, Object>
LinkList[1] = <Object, Object>
LinkList[2] = <Object, Object>
and so on...
Angular 5 - Copy to clipboard
Solution 1: Copy any text
HTML
<button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>
.ts file
copyMessage(val: string){
const selBox = document.createElement('textarea');
selBox.style.position = 'fixed';
selBox.style.left = '0';
selBox.style.top = '0';
selBox.style.opacity = '0';
selBox.value = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
}
Solution 2: Copy from a TextBox
HTML
<input type="text" value="User input Text to copy" #userinput>
<button (click)="copyInputMessage(userinput)" value="click to copy" >Copy from Textbox</button>
.ts file
/* To copy Text from Textbox */
copyInputMessage(inputElement){
inputElement.select();
document.execCommand('copy');
inputElement.setSelectionRange(0, 0);
}
Demo Here
Solution 3: Import a 3rd party directive ngx-clipboard
<button class="btn btn-default" type="button" ngxClipboard [cbContent]="Text to be copied">copy</button>
Solution 4: Custom Directive
If you prefer using a custom directive, Check Dan Dohotaru's answer which is an elegant solution implemented using ClipboardEvent
.
Solution 5: Angular Material
Angular material 9 + users can utilize the built-in clipboard feature to copy text. There are a few more customization available such as limiting the number of attempts to copy data.
Get current URL/URI without some of $_GET variables
Something like this should work, if run in the controller:
$controller = $this;
$path = '/path/to/app/'
. $controller->module->getId() // only necessary if you're using modules
. '/' . $controller->getId()
. '/' . $controller->getAction()->getId()
. '/';
This assumes that you are using 'friendly' URLs in your app config.
Connection failed: SQLState: '01000' SQL Server Error: 10061
- Windows firewall blocks the sql server. Even if you open the 1433 port from exceptions, in the client machine it sets the connection point to dynamic port. Add also the sql server to the exceptions.
"C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe"
More info
- This page helped me to solve the problem. Especially
or if you feel brave, locate the alias in the registry and delete it
there.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo\
Is it possible to include one CSS file in another?
The "@import" rule could calls in multiple styles files. These files are called by the browser or User Agent when needed e.g. HTML tags call the CSS.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="EN" dir="ltr">
<head>
<title>Using @import</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
@import url("main.css");
</style>
</head>
<body>
</body>
</html>
CSS File "main.css" Contains The Following Syntax:
@import url("fineprint.css") print;
@import url("bluish.css") projection, tv;
@import 'custom.css';
@import url("chrome://communicator/skin/");
@import "common.css" screen, projection;
@import url('landscape.css') screen and (orientation:landscape);
To insert in style element use createTexNode don't use innerHTML but:
<script>
var style = document.createElement('style');
style.setAttribute("type", "text/css");
var textNode = document.createTextNode("
@import 'fineprint.css' print;
@import 'bluish.css' projection, tv;
@import 'custom.css';
@import 'chrome://communicator/skin/';
@import 'common.css' screen, projection;
@import 'landscape.css' screen and (orientation:landscape);
");
style.appendChild(textNode);
</script>
How can I find my php.ini on wordpress?
you can do it from the Cpanel:
1.- CPANEL
2.- Select PHP Version
3.- Swich to PHP options
4.- Edit:
max_execution_time 1800
max_input_time 64
max_input_vars 6000
memory_limit 512M
post_max_size 128M
upload_max_filesize 128M
Difference between string and StringBuilder in C#
A String (System.String) is a type defined inside the .NET framework. The String class is not mutable. This means that every time you do an action to an System.String instance, the .NET compiler create a new instance of the string. This operation is hidden to the developer.
A System.Text.StringBuilder is class that represents a mutable string. This class provides some useful methods that make the user able to manage the String wrapped by the StringBuilder. Notice that all the manipulations are made on the same StringBuilder instance.
Microsoft encourages the use of StringBuilder because it is more effective in terms of memory usage.
Can I map a hostname *and* a port with /etc/hosts?
If you really need to do this, use reverse proxy.
For example, with nginx as reverse proxy
server {
listen api.mydomain.com:80;
server_name api.mydomain.com;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
Convert PEM to PPK file format
If you have Linux machine just install puttygen in your system and use use below command to convert the key
pem to ppk use below command:
puttygen keyname -o keyname.ppk
Below command is use to convert ppk to pem not pem to ppk
puttygen filename.ppk -O private-openssh -o filename.pem
docker error: /var/run/docker.sock: no such file or directory
docker pull
will fail if docker service
is not running. Make sure it is running by
:~$ ps aux | grep docker
root 18745 1.7 0.9 284104 13976 ? Ssl 21:19 0:01 /usr/bin/docker -d
If it is not running, you can start it by
sudo service docker start
For Ubuntu 15 and above use
sudo systemctl start docker
cast or convert a float to nvarchar?
If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.
So instead of:
select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009
You would use:
select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890
In these examples the innermost cast(1234567890 as float)
is used in place of selecting a value from the appropriate column.
I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?
select cast(0100884555 as float)
100884555
Whoops! We just stored an incorrect phone number...
NSURLErrorDomain error codes description
IN SWIFT 3.
Here are the NSURLErrorDomain error codes description in a Swift 3 enum:
(copied from answer above and converted what i can).
enum NSURLError: Int {
case unknown = -1
case cancelled = -999
case badURL = -1000
case timedOut = -1001
case unsupportedURL = -1002
case cannotFindHost = -1003
case cannotConnectToHost = -1004
case connectionLost = -1005
case lookupFailed = -1006
case HTTPTooManyRedirects = -1007
case resourceUnavailable = -1008
case notConnectedToInternet = -1009
case redirectToNonExistentLocation = -1010
case badServerResponse = -1011
case userCancelledAuthentication = -1012
case userAuthenticationRequired = -1013
case zeroByteResource = -1014
case cannotDecodeRawData = -1015
case cannotDecodeContentData = -1016
case cannotParseResponse = -1017
//case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
case fileDoesNotExist = -1100
case fileIsDirectory = -1101
case noPermissionsToReadFile = -1102
//case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103
// SSL errors
case secureConnectionFailed = -1200
case serverCertificateHasBadDate = -1201
case serverCertificateUntrusted = -1202
case serverCertificateHasUnknownRoot = -1203
case serverCertificateNotYetValid = -1204
case clientCertificateRejected = -1205
case clientCertificateRequired = -1206
case cannotLoadFromNetwork = -2000
// Download and file I/O errors
case cannotCreateFile = -3000
case cannotOpenFile = -3001
case cannotCloseFile = -3002
case cannotWriteToFile = -3003
case cannotRemoveFile = -3004
case cannotMoveFile = -3005
case downloadDecodingFailedMidStream = -3006
case downloadDecodingFailedToComplete = -3007
/*
case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018
case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019
case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020
case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021
case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
*/
}
Direct link to URLError.Code
in the Swift github repository, which contains the up to date list of error codes being used (github link).
Unresolved external symbol on static class members
Static data members declarations in the class declaration are not definition of them.
To define them you should do this in the .CPP
file to avoid duplicated symbols.
The only data you can declare and define is integral static constants.
(Values of enums
can be used as constant values as well)
You might want to rewrite your code as:
class test {
public:
const static unsigned char X = 1;
const static unsigned char Y = 2;
...
test();
};
test::test() {
}
If you want to have ability to modify you static variables (in other words when it is inappropriate to declare them as const), you can separate you code between .H
and .CPP
in the following way:
.H :
class test {
public:
static unsigned char X;
static unsigned char Y;
...
test();
};
.CPP :
unsigned char test::X = 1;
unsigned char test::Y = 2;
test::test()
{
// constructor is empty.
// We don't initialize static data member here,
// because static data initialization will happen on every constructor call.
}
What are the differences between a program and an application?
Without more information about the question, the terms 'program' and 'application' are nearly synonymous.
As Saif has indicated, 'application' tends to be used more for non-system related programs. That being said, I don't think it's wrong to describe the operating system as an special application that provides an environment in which to run other applications.
How to extract the decimal part from a floating point number in C?
I think that using string is the correct way to go in this case, since you don't know a priori the number of digits in the decimal part. But, it won't work for all cases (e.g. 1.005), as mentioned before by @SingleNegationElimination. Here is my take on this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char s_value[60], s_integral[60], s_fractional[60];
int i, found = 0, count = 1, integral, fractional;
scanf("%s", s_value);
for (i = 0; s_value[i] != '\0'; i++)
{
if (!found)
{
if (s_value[i] == '.')
{
found = 1;
s_integral[i] = '\0';
continue;
}
s_integral[i] = s_value[i];
count++;
}
else
s_fractional[i - count] = s_value[i];
}
s_fractional[i - count] = '\0';
integral = atoi(s_integral);
fractional = atoi(s_fractional);
printf("value = %s, integral = %d, fractional = %d\n",
s_value, integral, fractional);
return 0;
}
HTML/CSS - Adding an Icon to a button
Here's what you can do using font-awesome library.
_x000D_
_x000D_
button.btn.add::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
_x000D_
_x000D_
Fiddle here.
SELECT COUNT in LINQ to SQL C#
Like that
var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();
or even easier
var purchCount = myBlaContext.purchases.Count()
How to add days to the current date?
SELECT DateAdd(5,day(getdate())
this is for adding 5 days to current days.
for eg:today date is 23/08/2018 it became 28/08/2018 by using the above query
How to set recurring schedule for xlsm file using Windows Task Scheduler
Three important steps - How to Task Schedule an excel.xls(m) file
simply:
- make sure the .vbs file is correct
- set the Action tab correctly in Task Scheduler
- don't turn on "Run whether user is logged on or not"
IN MORE DETAIL...
- Here is an example .vbs file:
`
' a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt to .vbs
'Write Excel.xls Sheet's full path here
strPath = "C:\RodsData.xlsm"
'Write the macro name - could try including module name
strMacro = "Update" ' "Sheet1.Macro2"
'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application")
objApp.Visible = True ' or False
'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath)
objApp.Run strMacro ' wbToRun.Name & "!" & strMacro
wbToRun.Save
wbToRun.Close
objApp.Quit
'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!", vbInformation
'
`
- In the Action tab (Task Scheduler):
set Program/script: = C:\Windows\System32\cscript.exe
set Add arguments (optional): = C:\MyVbsFile.vbs
- Finally, don't turn on "Run whether user is logged on or not".
That should work.
Let me know!
Rod Bowen
Check if a property exists in a class
Your method looks like this:
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
This adds an extension onto object
- the base class of everything. When you call this extension you're passing it a Type
:
var res = typeof(MyClass).HasProperty("Label");
Your method expects an instance of a class, not a Type
. Otherwise you're essentially doing
typeof(MyClass) - this gives an instanceof `System.Type`.
Then
type.GetType() - this gives `System.Type`
Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type`
As @PeterRitchie correctly points out, at this point your code is looking for property Label
on System.Type
. That property does not exist.
The solution is either
a) Provide an instance of MyClass to the extension:
var myInstance = new MyClass()
myInstance.HasProperty("Label")
b) Put the extension on System.Type
public static bool HasProperty(this Type obj, string propertyName)
{
return obj.GetProperty(propertyName) != null;
}
and
typeof(MyClass).HasProperty("Label");
How to check whether a int is not null or empty?
if your int variable is declared as a class level variable (instance variable) it would be defaulted to 0. But that does not indicate if the value sent from the client was 0 or a null. may be you could have a setter method which could be called to initialize/set the value sent by the client. then you can define your indicator value , may be a some negative value to indicate the null..
How to prevent going back to the previous activity?
This method is working fine
Intent intent = new Intent(Profile.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
adding text to an existing text element in javascript via DOM
remove .textContent
from var t = document.getElementById("p").textContent;
_x000D_
_x000D_
var t = document.getElementById("p");_x000D_
var y = document.createTextNode("This just got added");_x000D_
_x000D_
t.appendChild(y);
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_
What is an 'undeclared identifier' error and how do I fix it?
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. In C++ all names have to be declared before they are used. If you try to use the name of a such that hasn't been declared you will get an "undeclared identifier" compile-error.
According to the documentation, the declaration of printf()
is in cstdio
i.e. you have to include it, before using the function.
How to calculate a Mod b in Casio fx-991ES calculator
Here's how I usually do it. For example, to calculate 1717 mod 2
:
- Take
1717 / 2
. The answer is 858.5
- Now take 858 and multiply it by the mod (
2
) to get 1716
- Finally, subtract the original number (
1717
) minus the number you got from the previous step (1716
) -- 1717-1716=1
.
So 1717 mod 2
is 1
.
To sum this up all you have to do is multiply the numbers before the decimal point with the mod then subtract it from the original number.
What are forward declarations in C++?
Because C++ is parsed from the top down, the compiler needs to know about things before they are used. So, when you reference:
int add( int x, int y )
in the main function the compiler needs to know it exists. To prove this try moving it to below the main function and you'll get a compiler error.
So a 'Forward Declaration' is just what it says on the tin. It's declaring something in advance of its use.
Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.
How can I add a custom HTTP header to ajax request with js or jQuery?
You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
this.setRequestHeader('x-my-custom-header', 'some value');
this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;
Split text file into smaller multiple text file using command line
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET /a fcount=100
SET /a llimit=5000
SET /a lcount=%llimit%
FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\q25249516.txt") DO (
CALL :select
FOR /f "tokens=1*delims==" %%b IN ('set dfile') DO IF /i "%%b"=="dfile" >>"%%c" ECHO(%%a
)
GOTO :EOF
:select
SET /a lcount+=1
IF %lcount% lss %llimit% GOTO :EOF
SET /a lcount=0
SET /a fcount+=1
SET "dfile=%sourcedir%\file%fcount:~-2%.txt"
GOTO :EOF
Here's a native windows batch that should accomplish the task.
Now I'll not say that it'll be fast (less than 2 minutes for each 5Kline output file) or that it will be immune to batch character-sensitivites. Really depends on the characteristics of your target data.
I used a file named q25249516.txt
containing 100Klines of data for my testing.
Revised quicker version
REM
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET /a fcount=199
SET /a llimit=5000
SET /a lcount=%llimit%
FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\q25249516.txt") DO (
CALL :select
>>"%sourcedir%\file$$.txt" ECHO(%%a
)
SET /a lcount=%llimit%
:select
SET /a lcount+=1
IF %lcount% lss %llimit% GOTO :EOF
SET /a lcount=0
SET /a fcount+=1
MOVE /y "%sourcedir%\file$$.txt" "%sourcedir%\file%fcount:~-2%.txt" >NUL 2>nul
GOTO :EOF
Note that I used llimit
of 50000 for testing. Will overwrite the early file numbers if llimit
*100 is gearter than the number of lines in the file (cure by setting fcount
to 1999
and use ~3
in place of ~2
in file-renaming line.)
Python append() vs. + operator on lists, why do these give different results?
The method you're looking for is extend()
. From the Python documentation:
list.append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].
list.extend(L)
Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Case-Insensitive List Search
Below is the example of searching for a keyword in the whole list and remove that item:
public class Book
{
public int BookId { get; set; }
public DateTime CreatedDate { get; set; }
public string Text { get; set; }
public string Autor { get; set; }
public string Source { get; set; }
}
If you want to remove a book that contains some keyword in the Text property, you can create a list of keywords and remove it from list of books:
List<Book> listToSearch = new List<Book>()
{
new Book(){
BookId = 1,
CreatedDate = new DateTime(2014, 5, 27),
Text = " test voprivreda...",
Autor = "abc",
Source = "SSSS"
},
new Book(){
BookId = 2,
CreatedDate = new DateTime(2014, 5, 27),
Text = "here you go...",
Autor = "bcd",
Source = "SSSS"
}
};
var blackList = new List<string>()
{
"test", "b"
};
foreach (var itemtoremove in blackList)
{
listToSearch.RemoveAll(p => p.Source.ToLower().Contains(itemtoremove.ToLower()) || p.Source.ToLower().Contains(itemtoremove.ToLower()));
}
return listToSearch.ToList();
Testing if a site is vulnerable to Sql Injection
SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.
First rule of securing any script or page that attaches to a database instance is Do not trust user input.
Your example is attempting to end a misquoted string in an SQL statement. To understand this, you first need to understand SQL statements. In your example of adding a '
to a paramater, your 'injection' is hoping for the following type of statement:
SELECT username,password FROM users WHERE username='$username'
By appending a '
to that statement, you could then add additional SQL paramaters or queries.: ' OR username --
SELECT username,password FROM users WHERE username='' OR username -- '$username
That is an injection (one type of; Query Reshaping). The user input becomes an injected statement into the pre-written SQL statement.
Generally there are three types of SQL injection methods:
- Query Reshaping or redirection (above)
- Error message based (No such user/password)
- Blind Injections
Read up on SQL Injection, How to test for vulnerabilities, understanding and overcoming SQL injection, and this question (and related ones) on StackOverflow about avoiding injections.
Edit:
As far as TESTING your site for SQL injection, understand it gets A LOT more complex than just 'append a symbol'. If your site is critical, and you (or your company) can afford it, hire a professional pen tester. Failing that, this great exaxmple/proof can show you some common techniques one might use to perform an injection test. There is also SQLMap which can automate some tests for SQL Injection and database take over scenarios.
CORS: credentials mode is 'include'
If it helps, I was using centrifuge with my reactjs app,
and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:
if ('withCredentials' in xhr) {
xhr.withCredentials = true;
}
After I removed these three lines, the app worked fine, as expected.
Hope it helps!
How to write a comment in a Razor view?
Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.
Server side Comments:
Razor .cshtml
Like so:
@* Comment goes here *@
.aspx
For those looking for the older .aspx
view (and Asp.Net WebForms) server side comment syntax:
<%-- Comment goes here --%>
Client Side Comments
HTML Comment
<!-- Comment goes here -->
Javascript Comment
// One line Comment goes Here
/* Multiline comment
goes here */
As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).
How to use Spring Boot with MySQL database and JPA?
For Jpa based application: base package scan
@EnableJpaRepositories(basePackages = "repository")
You can try it once!!!
Project Structure
com
+- stack
+- app
| +- Application.java
+- controller
| +- EmployeeController.java
+- service
| +- EmployeeService.java
+- repository
| +- EmployeeRepository.java
+- model
| +- Employee.java
-pom.xml
dependencies:
mysql, lombok, data-jpa
application.properties
#Data source :
spring.datasource.url=jdbc:mysql://localhost:3306/employee?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.generate-ddl=true
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#Jpa/Hibernate :
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
Employee.java
@Entity
@Table (name = "employee")
@Getter
@Setter
public class Employee {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
@Column (name = "first_name")
private String firstName;
@Column (name = "last_name")
private String lastName;
@Column (name = "email")
private String email;
@Column (name = "phone_number")
private String phoneNumber;
@Column (name = "emp_desg")
private String desgination;
}
EmployeeRepository.java
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
EmployeeController.java
@RestController
public class EmployeeController {
@Autowired
private EmployeeService empService;
@GetMapping (value = "/employees")
public List<Employee> getAllEmployee(){
return empService.getAllEmployees();
}
@PostMapping (value = "/employee")
public ResponseEntity<Employee> addEmp(@RequestBody Employee emp, HttpServletRequest
request) throws URISyntaxException {
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(request.getRequestURI() + "/" + emp.getId()));
empService.saveEmployee(emp);
return new ResponseEntity<Employee>(emp, headers, HttpStatus.CREATED);
}
EmployeeService.java
public interface EmployeeService {
public List<Employee> getAllEmployees();
public Employee saveEmployee(Employee emp);
}
EmployeeServiceImpl.java
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository empRepository;
@Override
public List<Employee> getAllEmployees() {
return empRepository.findAll();
}
@Override
public Employee saveEmployee(Employee emp) {
return empRepository.save(emp);
}
}
EmployeeApplication.java
@SpringBootApplication
@EnableJpaRepositories(basePackages = "repository")
public class EmployeeApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeApplication.class, args);
}
}
How to specify test directory for mocha?
Here's one way, if you have subfolders in your test folder e.g.
/test
/test/server-test
/test/other-test
Then in linux you can use the find command to list all *.js files recursively and pass it to mocha:
mocha $(find test -name '*.js')
How to split strings into text and number?
I'm always the one to bring up findall() =)
>>> strings = ['foofo21', 'bar432', 'foobar12345']
>>> [re.findall(r'(\w+?)(\d+)', s)[0] for s in strings]
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
Note that I'm using a simpler (less to type) regex than most of the previous answers.
how to show progress bar(circle) in an activity having a listview before loading the listview with data
I used this one for list view loading may helpful.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp" >
<LinearLayout
android:id="@+id/progressbar_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Loading data..." />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#C0C0C0" />
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="1dip"
android:visibility="gone" />
</RelativeLayout>
and my MainActivity class is,
public class MainActivity extends Activity {
ListView listView;
LinearLayout layout;
List<String> stringValues;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
stringValues = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stringValues);
listView.setAdapter(adapter);
new Task().execute();
}
class Task extends AsyncTask<String, Integer, Boolean> {
@Override
protected void onPreExecute() {
layout.setVisibility(View.VISIBLE);
listView.setVisibility(View.GONE);
super.onPreExecute();
}
@Override
protected void onPostExecute(Boolean result) {
layout.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
@Override
protected Boolean doInBackground(String... params) {
stringValues.add("String 1");
stringValues.add("String 2");
stringValues.add("String 3");
stringValues.add("String 4");
stringValues.add("String 5");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
this activity display progress for 3sec then it will display listview, instead of adding data statically to stringValues list you can get data from server in doInBackground() and display it.
Using variables inside a bash heredoc
In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:
The format of here-documents is:
<<[-]word
here-document
delimiter
No parameter expansion, command substitution, arithmetic expansion, or
pathname expansion is performed on word. If any characters in word are
quoted, the delimiter is the result of quote removal on word, and the
lines in the here-document are not expanded. If word is unquoted, all
lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]
If you change your first example to use <<EOF
instead of << "EOF"
you'll find that it works.
In your second example, the shell invokes sudo
only with the parameter cat
, and the redirection applies to the output of sudo cat
as the original user. It'll work if you try:
sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT
Map implementation with duplicate keys
You are searching for a multimap, and indeed both commons-collections and Guava have several implementations for that. Multimaps allow for multiple keys by maintaining a collection of values per key, i.e. you can put a single object into the map, but you retrieve a collection.
If you can use Java 5, I would prefer Guava's Multimap
as it is generics-aware.
What is the correct way to read a serial port using .NET framework?
Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method
using System;
using System.IO.Ports;
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this
SerialPortProgram();
}
private static void SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Console.ReadLine();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
Or is you want to do it based on what you were trying to do , you can try this
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
{
serialPort.Dispose();
}
}
How to make script execution wait until jquery is loaded
I'm not super fond of the interval thingies. When I want to defer jquery, or anything actually, it usually goes something like this.
Start with:
<html>
<head>
<script>var $d=[];var $=(n)=>{$d.push(n)}</script>
</head>
Then:
<body>
<div id="thediv"></div>
<script>
$(function(){
$('#thediv').html('thecode');
});
</script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
Then finally:
<script>for(var f in $d){$d[f]();}</script>
</body>
<html>
Or the less mind-boggling version:
<script>var def=[];function defer(n){def.push(n)}</script>
<script>
defer(function(){
$('#thediv').html('thecode');
});
</script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>for(var f in def){def[f]();}</script>
And in the case of async you could execute the pushed functions on jquery onload.
<script async onload="for(var f in def){def[f]();}"
src="jquery.min.js" type="text/javascript"></script>
Alternatively:
function loadscript(src, callback){
var script = document.createElement('script');
script.src = src
script.async = true;
script.onload = callback;
document.body.appendChild(script);
};
loadscript("jquery.min", function(){for(var f in def){def[f]();}});
Error 405 (Method Not Allowed) Laravel 5
Your routes.php file needs to be setup correctly.
What I am assuming your current setup is like:
Route::post('/empresas/eliminar/{id}','CompanyController@companiesDelete');
or something. Define a route for the delete method instead.
Route::delete('/empresas/eliminar/{id}','CompanyController@companiesDelete');
Now if you are using a Route resource, the default route name to be used for the 'DELETE' method is .destroy. Define your delete logic in that function instead.
Excel formula to get cell color
Color is not data.
The Get.cell technique has flaws.
- It does not update as soon as the cell color changes, but only when
the cell (or the sheet) is recalculated.
- It does not have sufficient numbers for the millions of colors that are available in modern Excel. See the screenshot and notice how the different intensities of yellow or purple all have the same number.
That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.
Again: Color is not data.
If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.
Call another rest api from my server in Spring-Boot
Modern Spring 5+ answer using WebClient
instead of RestTemplate
.
Configure WebClient
for a specific web-service or resource as a bean (additional properties can be configured).
@Bean
public WebClient localApiClient() {
return WebClient.create("http://localhost:8080/api/v3");
}
Inject and use the bean from your service(s).
@Service
public class UserService {
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);
private final WebClient localApiClient;
@Autowired
public UserService(WebClient localApiClient) {
this.localApiClient = localApiClient;
}
public User getUser(long id) {
return localApiClient
.get()
.uri("/users/" + id)
.retrieve()
.bodyToMono(User.class)
.block(REQUEST_TIMEOUT);
}
}
How do I make a newline after a twitter bootstrap element?
Using br
elements is fine, and as long as you don't need a lot of space between elements, is actually a logical thing to do as anyone can read your code and understand what spacing logic you are using.
The alternative is to create a custom class for white space. In bootstrap 4 you can use
<div class="w-100"></div>
to make a blank row across the page, but this is no different to using the <br>
tag. The downside to creating a custom class for white space is that it can be a pain to read for others who view your code. A custom class would also apply the same amount of white space each time you used it, so if you wanted different amounts of white space on the same page, then you would need to create several white space classes.
In most cases, it is just easier to use <br>
or <div class="w-100"></div>
for the sake of ease and readability. it doesn't look pretty, but it works.
Commit history on remote repository
git
isn't a centralized scm like svn
so you have two options:
It may be annoying to implement for many different platforms (GitHub, GitLab, BitBucket, SourceForge, Launchpad, Gogs, ...) but fetching data is pretty slow (we talk about seconds) - no solution is perfect.
An example with fetching into a temporary directory:
git clone https://github.com/rust-lang/rust.git -b master --depth 3 --bare --filter=blob:none -q .
git log -n 3 --no-decorate --format=oneline
Alternatively:
git init --bare -q
git remote add -t master origin https://github.com/rust-lang/rust.git
git fetch --depth 3 --filter=blob:none -q
git log -n 3 --no-decorate --format=oneline origin/master
Both are optimized for performance by restricting to exactly 3 commits of one branch into a minimal local copy without file contents and preventing console outputs. Though opening a connection and calculating deltas during fetch takes some time.
An example with GitHub:
GET https://api.github.com/repos/rust-lang/rust/commits?sha=master&per_page=3
An example with GitLab:
GET https://gitlab.com/api/v4/projects/inkscape%2Finkscape/repository/commits?ref_name=master&per_page=3
Both are really fast but have different interfaces (like every platform).
Disclaimer: Rust and Inkscape were chosen because of their size and safety to stay, no advertisement
How can I add an image file into json object?
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button) findViewById(R.id.uploadButton);
messageText = (TextView) findViewById(R.id.messageText);
messageText.setText("Uploading file path :- '/mnt/sdcard/"
+ uploadFileName + "'");
/************* Php script path ****************/
upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";
uploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection connection = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
+ uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ uploadFilePath + "" + uploadFileName);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // Allow Inputs
connection.setDoOutput(true); // Allow Outputs
connection.setUseCaches(false); // Don't use a Cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
// dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
// + fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ URLEncoder.encode(fileName, "UTF-8") + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " http://www.androidexample.com/media/uploads/"
+ uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
PHP FILE
<?php
$target_path = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
How to use pagination on HTML tables?
For me, best and simplest way, Bootply
http://www.bootply.com/lxa0FF9yhw#
First include Bootstrap to your project
Then include javascript file in which you write this code:
$.fn.pageMe = function(opts){
var $this = this,
defaults = {
perPage: 7,
showPrevNext: false,
hidePageNumbers: false
},
settings = $.extend(defaults, opts);
var listElement = $this;
var perPage = settings.perPage;
var children = listElement.children();
var pager = $('.pager');
if (typeof settings.childSelector!="undefined") {
children = listElement.find(settings.childSelector);
}
if (typeof settings.pagerSelector!="undefined") {
pager = $(settings.pagerSelector);
}
var numItems = children.size();
var numPages = Math.ceil(numItems/perPage);
pager.data("curr",0);
if (settings.showPrevNext){
$('<li><a href="#" class="prev_link">«</a></li>').appendTo(pager);
}
var curr = 0;
while(numPages > curr && (settings.hidePageNumbers==false)){
$('<li><a href="#" class="page_link">'+(curr+1)+'</a></li>').appendTo(pager);
curr++;
}
if (settings.showPrevNext){
$('<li><a href="#" class="next_link">»</a></li>').appendTo(pager);
}
pager.find('.page_link:first').addClass('active');
pager.find('.prev_link').hide();
if (numPages<=1) {
pager.find('.next_link').hide();
}
pager.children().eq(1).addClass("active");
children.hide();
children.slice(0, perPage).show();
pager.find('li .page_link').click(function(){
var clickedPage = $(this).html().valueOf()-1;
goTo(clickedPage,perPage);
return false;
});
pager.find('li .prev_link').click(function(){
previous();
return false;
});
pager.find('li .next_link').click(function(){
next();
return false;
});
function previous(){
var goToPage = parseInt(pager.data("curr")) - 1;
goTo(goToPage);
}
function next(){
goToPage = parseInt(pager.data("curr")) + 1;
goTo(goToPage);
}
function goTo(page){
var startAt = page * perPage,
endOn = startAt + perPage;
children.css('display','none').slice(startAt, endOn).show();
if (page>=1) {
pager.find('.prev_link').show();
}
else {
pager.find('.prev_link').hide();
}
if (page<(numPages-1)) {
pager.find('.next_link').show();
}
else {
pager.find('.next_link').hide();
}
pager.data("curr",page);
pager.children().removeClass("active");
pager.children().eq(page+1).addClass("active");
}
};
You need to give an id to the tbody of your table and to add a 'div' after the table for the pagination
<table class="table" id="myTable">
<thead>
<tr>
<th>...</th>
</tr>
</thead>
<tbody id="myTableBody">
</tbody>
</table>
<div class="col-md-12 text-center">
<ul class="pagination pagination-lg pager" id="myPager"></ul>
</div>
When your table's data is loaded, just call this
$('#myTableBody').pageMe({pagerSelector:'#myPager',showPrevNext:true,hidePageNumbers:false,perPage:4});
where the 'perPage' value is to set how many elements per page you want to have.
gson throws MalformedJsonException
In the debugger you don't need to add back slashes, the input field understands the special chars.
In java code you need to escape the special chars
No visible cause for "Unexpected token ILLEGAL"
I had the same problem on my mac and found it was because the Mac was replacing the standard quotes with curly quotes which are illegal javascript characters.
To fix this I had to change the settings on my mac System Preferences=>Keyboard=>Text(tab) uncheck use smart quotes and dashes (default was checked).
Displaying a Table in Django from Database
The easiest way is to use a for loop template tag.
Given the view:
def MyView(request):
...
query_results = YourModel.objects.all()
...
#return a response to your template and add query_results to the context
You can add a snippet like this your template...
<table>
<tr>
<th>Field 1</th>
...
<th>Field N</th>
</tr>
{% for item in query_results %}
<tr>
<td>{{ item.field1 }}</td>
...
<td>{{ item.fieldN }}</td>
</tr>
{% endfor %}
</table>
This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.
How to install OpenSSL in windows 10?
Check openssl tool which is a collection of Openssl from the LibreSSL project and Cygwin libraries (2.5 MB). NB! We're the packager.
One liner to create a self signed certificate:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt
C# windows application Event: CLR20r3 on application start
I encountered the same problem when I built an application on a Windows 7 box that had previously been maintained on an XP machine.
The program ran fine when built for Debug, but failed with this error when built for Release. I found the answer on the project's Properties page. Go to the "Build" tab and try changing the Platform Target from "Any CPU" to "x86".
Best way to parse command line arguments in C#?
A very simple easy to use ad hoc class for command line parsing, that supports default arguments.
class CommandLineArgs
{
public static CommandLineArgs I
{
get
{
return m_instance;
}
}
public string argAsString( string argName )
{
if (m_args.ContainsKey(argName)) {
return m_args[argName];
}
else return "";
}
public long argAsLong(string argName)
{
if (m_args.ContainsKey(argName))
{
return Convert.ToInt64(m_args[argName]);
}
else return 0;
}
public double argAsDouble(string argName)
{
if (m_args.ContainsKey(argName))
{
return Convert.ToDouble(m_args[argName]);
}
else return 0;
}
public void parseArgs(string[] args, string defaultArgs )
{
m_args = new Dictionary<string, string>();
parseDefaults(defaultArgs );
foreach (string arg in args)
{
string[] words = arg.Split('=');
m_args[words[0]] = words[1];
}
}
private void parseDefaults(string defaultArgs )
{
if ( defaultArgs == "" ) return;
string[] args = defaultArgs.Split(';');
foreach (string arg in args)
{
string[] words = arg.Split('=');
m_args[words[0]] = words[1];
}
}
private Dictionary<string, string> m_args = null;
static readonly CommandLineArgs m_instance = new CommandLineArgs();
}
class Program
{
static void Main(string[] args)
{
CommandLineArgs.I.parseArgs(args, "myStringArg=defaultVal;someLong=12");
Console.WriteLine("Arg myStringArg : '{0}' ", CommandLineArgs.I.argAsString("myStringArg"));
Console.WriteLine("Arg someLong : '{0}' ", CommandLineArgs.I.argAsLong("someLong"));
}
}
Adding an identity to an existing column
There isn't one, sadly; the IDENTITY property belongs to the table rather than the column.
The easier way is to do it in the GUI, but if this isn't an option, you can go the long way around of copying the data, dropping the column, re-adding it with identity, and putting the data back.
See here for a blow-by-blow account.
Convert string to Time
string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);
string t = date.ToString("HH:mm:ss tt");
Best way to reverse a string
public string Reverse(string input)
{
char[] output = new char[input.Length];
int forwards = 0;
int backwards = input.Length - 1;
do
{
output[forwards] = input[backwards];
output[backwards] = input[forwards];
}while(++forwards <= --backwards);
return new String(output);
}
public string DotNetReverse(string input)
{
char[] toReverse = input.ToCharArray();
Array.Reverse(toReverse);
return new String(toReverse);
}
public string NaiveReverse(string input)
{
char[] outputArray = new char[input.Length];
for (int i = 0; i < input.Length; i++)
{
outputArray[i] = input[input.Length - 1 - i];
}
return new String(outputArray);
}
public string RecursiveReverse(string input)
{
return RecursiveReverseHelper(input, 0, input.Length - 1);
}
public string RecursiveReverseHelper(string input, int startIndex , int endIndex)
{
if (startIndex == endIndex)
{
return "" + input[startIndex];
}
if (endIndex - startIndex == 1)
{
return "" + input[endIndex] + input[startIndex];
}
return input[endIndex] + RecursiveReverseHelper(input, startIndex + 1, endIndex - 1) + input[startIndex];
}
void Main()
{
int[] sizes = new int[] { 10, 100, 1000, 10000 };
for(int sizeIndex = 0; sizeIndex < sizes.Length; sizeIndex++)
{
string holaMundo = "";
for(int i = 0; i < sizes[sizeIndex]; i+= 5)
{
holaMundo += "ABCDE";
}
string.Format("\n**** For size: {0} ****\n", sizes[sizeIndex]).Dump();
string odnuMaloh = DotNetReverse(holaMundo);
var stopWatch = Stopwatch.StartNew();
string result = NaiveReverse(holaMundo);
("Naive Ticks: " + stopWatch.ElapsedTicks).Dump();
stopWatch.Restart();
result = Reverse(holaMundo);
("Efficient linear Ticks: " + stopWatch.ElapsedTicks).Dump();
stopWatch.Restart();
result = RecursiveReverse(holaMundo);
("Recursive Ticks: " + stopWatch.ElapsedTicks).Dump();
stopWatch.Restart();
result = DotNetReverse(holaMundo);
("DotNet Reverse Ticks: " + stopWatch.ElapsedTicks).Dump();
}
}
Output
For size: 10
Naive Ticks: 1
Efficient linear Ticks: 0
Recursive Ticks: 2
DotNet Reverse Ticks: 1
For size: 100
Naive Ticks: 2
Efficient linear Ticks: 1
Recursive Ticks: 12
DotNet Reverse Ticks: 1
For size: 1000
Naive Ticks: 5
Efficient linear Ticks: 2
Recursive Ticks: 358
DotNet Reverse Ticks: 9
For size: 10000
Naive Ticks: 32
Efficient linear Ticks: 28
Recursive Ticks: 84808
DotNet Reverse Ticks: 33
Sql Server : How to use an aggregate function like MAX in a WHERE clause
The correct way to use max in the having clause is by performing a self join first:
select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)
The following is how you would join with a subquery:
select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
from table1 t1_max
where t1.id = t1_max.id)
Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
join #dataset d_max
on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c
Sub query version:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
from #dataset d_max
where d.id = d_max.id)
How to print a dictionary's key?
A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys()
method, which gives you a python list
of all the keys, and you have the iteritems()
method, which returns key-value pairs, so
for key, value in mydic.iteritems() :
print key, value
Python 3 version:
for key, value in mydic.items() :
print (key, value)
So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.
How to set default value to all keys of a dict object in python?
You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.
class cDefaultDict(dict):
# dictionary that returns zero for missing keys
# keys with zero values are not stored
def __missing__(self,key):
return 0
def __setitem__(self, key, value):
if value==0:
if key in self: # returns zero anyway, so no need to store it
del self[key]
else:
dict.__setitem__(self, key, value)
What is the difference between static_cast<> and C style casting?
C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime.
Also, c++ style casts can be searched for easily, whereas it's really hard to search for c style casts.
Another big benefit is that the 4 different C++ style casts express the intent of the programmer more clearly.
When writing C++ I'd pretty much always use the C++ ones over the the C style.
How to take the first N items from a generator or list?
Slicing a list
top5 = array[:5]
- To slice a list, there's a simple syntax:
array[start:stop:step]
- You can omit any parameter. These are all valid:
array[start:]
, array[:stop]
, array[::step]
Slicing a generator
import itertools
top5 = itertools.islice(my_list, 5) # grab the first five elements
You can't slice a generator directly in Python. itertools.islice()
will wrap an object in a new slicing generator using the syntax itertools.islice(generator, start, stop, step)
Remember, slicing a generator will exhaust it partially. If you want to keep the entire generator intact, perhaps turn it into a tuple or list first, like: result = tuple(generator)
Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here
You can just controll it with a boolean, so you only call unbind if bind has been made
public void doBindService()
{
if (!mIsBound)
{
bindService(new Intent(this, DMusic.class), Scon, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
}
public void doUnbindService()
{
if (mIsBound)
{
unbindService(Scon);
mIsBound = false;
}
}
If you only want to unbind it if it has been connected
public ServiceConnection Scon = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder)
{
mServ = ((DMusic.ServiceBinder) binder).getService();
mIsBound = true;
}
public void onServiceDisconnected(ComponentName name)
{
mServ = null;
}
};
Select subset of columns in data.table R
This seems an improvement:
> cols<-!(colnames(dt) %in% c("V1","V2","V3","V5"))
> new_dt<-subset(dt,,cols)
> cor(new_dt)
V4 V6 V7 V8 V9 V10
V4 1.0000000 0.14141578 -0.44466832 0.23697216 -0.1020074 0.48171747
V6 0.1414158 1.00000000 -0.21356218 -0.08510977 -0.1884202 -0.22242274
V7 -0.4446683 -0.21356218 1.00000000 -0.02050846 0.3209454 -0.15021528
V8 0.2369722 -0.08510977 -0.02050846 1.00000000 0.4627034 -0.07020571
V9 -0.1020074 -0.18842023 0.32094540 0.46270335 1.0000000 -0.19224973
V10 0.4817175 -0.22242274 -0.15021528 -0.07020571 -0.1922497 1.00000000
This one is not quite as easy to grasp but might have use for situations there there were a need to specify columns by a numeric vector:
subset(dt, , !grepl(paste0("V", c(1:3,5),collapse="|"),colnames(dt) ))
Set div height to fit to the browser using CSS
I do not think you need float.
_x000D_
_x000D_
html,_x000D_
body,_x000D_
.container {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.div1, .div2 {_x000D_
display: inline-block;_x000D_
margin: 0;_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
.div1 {_x000D_
width: 25%;_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
.div2 {_x000D_
width: 75%;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="div1"></div><!--_x000D_
--><div class="div2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
display: inline-block;
is used to display blocks as inline (just like spans but keeping the block effect)
Comments in the html is used because you have 75% + 25% = 100%. The space in-between the divs counts (so you have 75% + 1%? + 25% = 101%, meaning line break)
How can I make a list of lists in R?
You can easily make lists of lists
list1 <- list(a = 2, b = 3)
list2 <- list(c = "a", d = "b")
mylist <- list(list1, list2)
mylist is now a list that contains two lists. To access list1 you can use mylist[[1]]
. If you want to be able to something like mylist$list1
then you need to do somethingl like
mylist <- list(list1 = list1, list2 = list2)
# Now you can do the following
mylist$list1
Edit: To reply to your edit. Just use double bracket indexing
a <- list_all[[1]]
a[[1]]
#[1] 1
a[[2]]
#[1] 2
What does the Visual Studio "Any CPU" target mean?
I think most of the important stuff has been said, but I just thought I'd add one thing: If you compile as Any CPU and run on an x64 platform, then you won't be able to load 32-bit DLL files, because your application wasn't started in WoW64, but those DLL files need to run there.
If you compile as x86, then the x64 system will run your application in WoW64, and you'll be able to load 32-bit DLL files.
So I think you should choose "Any CPU" if your dependencies can run in either environment, but choose x86 if you have 32-bit dependencies. This article from Microsoft explains this a bit:
/CLRIMAGETYPE (Specify Type of CLR Image)
Incidentally, this other Microsoft documentation agrees that x86 is usually a more portable choice:
Choosing x86 is generally the safest configuration for an app package
since it will run on nearly every device. On some devices, an app
package with the x86 configuration won't run, such as the Xbox or some
IoT Core devices. However, for a PC, an x86 package is the safest
choice and has the largest reach for device deployment. A substantial
portion of Windows 10 devices continue to run the x86 version of
Windows.
How to insert a row between two rows in an existing excel with HSSF (Apache POI)
For people who are looking to insert a row between two rows in an existing excel with XSSF (Apache POI), there is already a method "copyRows" implemented in the XSSFSheet.
import org.apache.poi.ss.usermodel.CellCopyPolicy;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class App2 throws Exception{
public static void main(String[] args){
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("input.xlsx"));
XSSFSheet sheet = workbook.getSheet("Sheet1");
sheet.copyRows(0, 2, 3, new CellCopyPolicy());
FileOutputStream out = new FileOutputStream("output.xlsx");
workbook.write(out);
out.close();
}
}
jQuery multiple events to trigger the same function
If you attach the same event handler to several events, you often run into the issue of more than one of them firing at once (e.g. user presses tab after editing; keydown, change, and blur might all fire).
It sounds like what you actually want is something like this:
$('#ValidatedInput').keydown(function(evt) {
// If enter is pressed
if (evt.keyCode === 13) {
evt.preventDefault();
// If changes have been made to the input's value,
// blur() will result in a change event being fired.
this.blur();
}
});
$('#ValidatedInput').change(function(evt) {
var valueToValidate = this.value;
// Your validation callback/logic here.
});
Uploading Images to Server android
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
ABOVE CODE TO SELECT IMAGE FROM GALLERY
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String filePath = getPath(selectedImage);
String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
image_name_tv.setText(filePath);
try {
if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
//FINE
} else {
//NOT IN REQUIRED FORMAT
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaColumns.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
NOW POST THE DATA USING MULTIPART FORM DATA
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");
Multipart FORM DATA
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
File file = new File(filePath);
Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}
FINALLY POST DATA TO SERVER
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response
This is my case: it's run
Environment: AspNet Core 2.1
Controller:
public class MyController
{
// ...
[HttpPost]
public ViewResult Search([FromForm]MySearchModel searchModel)
{
// ...
return View("Index", viewmodel);
}
}
View:
<form method="post" asp-controller="MyController" asp-action="Search">
<input name="MySearchModelProperty" id="MySearchModelProperty" />
<input type="submit" value="Search" />
</form>
In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?
According to the HTML standard, the content model of the HTML element is:
A head element followed by a body
element.
You can either define the BODY element in the source code:
<html>
<body>
... web-page ...
</body>
</html>
or you can omit the BODY element:
<html>
... web-page ...
</html>
However, it is invalid to place the BODY element inside the web-page content (in-between other elements or text content), like so:
<html>
... content ...
<body>
... content ...
</body>
... content ...
</html>
Ignoring directories in Git repositories on Windows
If you want to maintain a folder and not the files inside it, just put a ".gitignore" file in the folder with "*" as the content. This file will make Git ignore all content from the repository. But .gitignore
will be included in your repository.
$ git add path/to/folder/.gitignore
If you add an empty folder, you receive this message (.gitignore is a hidden file)
The following paths are ignored by one of your .gitignore files:
path/to/folder/.gitignore
Use -f if you really want to add them.
fatal: no files added
So, use "-f" to force add:
$ git add path/to/folder/.gitignore -f
ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean
Case 1:
@SpringBootApplication
annotation missing in your spring boot starter class.
Case 2:
For non web application, disable web application type
in properties file:
In application.properties
:
spring.main.web-application-type=none
If you use application.yml
then add:
spring:
main:
web-application-type: none
For web applications, extends *SpringBootServletInitializer*
in main class.
@SpringBootApplication
public class YourAppliationName extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(YourAppliationName.class, args);
}
}
Case 3:
If you use spring-boot-starter-webflux
then also add spring-boot-starter-web
as dependency.
How can I backup a remote SQL Server database to a local drive?
I'm astonished that no-one has mentioned the scripted backup solution offered by Ola Hallengren which absolutely does allow you to backup a DB from a remote server to a UNC path on your network for free (I'm actually using it as I type to backup a DB from a dev server to which I have no remote access other than through SSMS to a share on my dev PC). This has been available since 2008 and works on SQL Server 2005 through to 2014.
You need to ensure that the share you set up has enough access: I tend to allow full read/write to the 'Everyone' AD group for the duration of the backup process because I'm too lazy to figure out anything more restrictive but that's personal choice.
It's well-used, well-documented and very flexible. I tend to put the procs and the logging table in their own little utility database and then fire it up. Provided everything is in your AD domain and not remote in the sense that it's out on a co-located server or something, this works very well.
Apologies for adding to a very old thread but I came across this when looking for something else and figured it was a worthwhile addition for anyone looking for this topic.
Jmeter - Run .jmx file through command line and get the summary report in a excel
This worked for me on mac os High sierra 10.13.6, java 8 64-bit, jmeter 4.0
$ jmeter -n --testfile /path/to/Test_Plan.jmx
Sample output:
Creating summariser <summary>
Created the tree successfully using ./src/test/jmeter/Test_Plan.jmx
Starting the test @ Fri Aug 24 17:18:18 PDT 2018 (1535156298333)
Waiting for possible Shutdown/StopTestNow/Heapdump message on port 4445
summary = 10 in 00:00:09 = 1.1/s Avg: 6666 Min: 1000 Max: 8950 Err:
0 (0.00%)
Tidying up ... @ Fri Aug 24 17:18:28 PDT 2018 (1535156308049)
... end of run
How to fire a button click event from JavaScript in ASP.NET
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
That solution works for me, but remember it wont work if your asp button has
Visible="False"
To hide button that should be triggered with that script you should hide it with <div hidden></div>
How to allow remote access to my WAMP server for Mobile(Android)
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
How to set timer in android?
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
CheckBox optSingleShot;
Button btnStart, btnCancel;
TextView textCounter;
Timer timer;
MyTimerTask myTimerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
optSingleShot = (CheckBox)findViewById(R.id.singleshot);
btnStart = (Button)findViewById(R.id.start);
btnCancel = (Button)findViewById(R.id.cancel);
textCounter = (TextView)findViewById(R.id.counter);
btnStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 5000);
}
}});
btnCancel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (timer!=null){
timer.cancel();
timer = null;
}
}
});
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(strDate);
}});
}
}
}
.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<CheckBox
android:id="@+id/singleshot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Single Shot"/>
Proper way to initialize C++ structs
In C++ classes/structs are identical (in terms of initialization).
A non POD struct may as well have a constructor so it can initialize members.
If your struct is a POD then you can use an initializer.
struct C
{
int x;
int y;
};
C c = {0}; // Zero initialize POD
Alternatively you can use the default constructor.
C c = C(); // Zero initialize using default constructor
C c{}; // Latest versions accept this syntax.
C* c = new C(); // Zero initialize a dynamically allocated object.
// Note the difference between the above and the initialize version of the constructor.
// Note: All above comments apply to POD structures.
C c; // members are random
C* c = new C; // members are random (more officially undefined).
I believe valgrind is complaining because that is how C++ used to work. (I am not exactly sure when C++ was upgraded with the zero initialization default construction). Your best bet is to add a constructor that initializes the object (structs are allowed constructors).
As a side note:
A lot of beginners try to value init:
C c(); // Unfortunately this is not a variable declaration.
C c{}; // This syntax was added to overcome this confusion.
// The correct way to do this is:
C c = C();
A quick search for the "Most Vexing Parse" will provide a better explanation than I can.
ImportError: No module named 'MySQL'
You need to use anaconda to manage python environment dependencies. MySQL connector can be installed using conda installer
conda install -c anaconda mysql-connector-python
How do I print bytes as hexadecimal?
Well you can convert one byte (unsigned char) at a time into a array like so
char buffer [17];
buffer[16] = 0;
for(j = 0; j < 8; j++)
sprintf(&buffer[2*j], "%02X", data[j]);
Can I send a ctrl-C (SIGINT) to an application on Windows?
void SendSIGINT( HANDLE hProcess )
{
DWORD pid = GetProcessId(hProcess);
FreeConsole();
if (AttachConsole(pid))
{
// Disable Ctrl-C handling for our program
SetConsoleCtrlHandler(NULL, true);
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); // SIGINT
//Re-enable Ctrl-C handling or any subsequently started
//programs will inherit the disabled state.
SetConsoleCtrlHandler(NULL, false);
WaitForSingleObject(hProcess, 10000);
}
}
How to make inline functions in C#
You can use Func which encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.
void Method()
{
Func<string,string> inlineFunction = source =>
{
// add your functionality here
return source ;
};
// call the inline function
inlineFunction("prefix");
}
How to deploy a Java Web Application (.war) on tomcat?
As others pointed out, the most straightforward way to deploy a WAR is to copy it to the webapps
of the Tomcat install. Another option would be to use the manager application if it is installed (this is not always the case), if it's properly configured (i.e. if you have the credentials of a user assigned to the appropriate group) and if it you can access it over an insecure network like Internet (but this is very unlikely and you didn't mention any VPN access). So this leaves you with the webapp
directory.
Now, if Tomcat is installed and running on bilgin.ath.cx
(as this is the machine where you uploaded the files), I noticed that Apache is listening to port 80
on that machien so I would bet that Tomcat is not directly exposed and that requests have to go through Apache. In that case, I think that deploying a new webapp and making it visible to the Internet will involve the edit of Apache configuration files (mod_jk
?, mod_proxy
?). You should either give us more details or discuss this with your hosting provider.
Update: As expected, the bilgin.ath.cx
is using Apache Tomcat + Apache HTTPD + mod_jk. The configuration usually involves two files: the worker.properties
file to configure the workers and the httpd.conf
for Apache. Now, without seeing the current configuration, it's not easy to give a definitive answer but, basically, you may have to add a JkMount
directive in Apache httpd.conf
for your new webapp1. Refer to the mod_jk documentation, it has a simple configuration example. Note that modifying httpd.conf
will require access to (obviously) and proper rights and that you'll have to restart Apache after the modifications.
1 I don't think you'll need to define a new worker if you are deploying to an already used Tomcat instance, especially if this sounds like Chinese for you :)
Use of "this" keyword in formal parameters for static methods in C#
I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).
Self Join to get employee manager name
CREATE VIEW AS
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName,
e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName
FROM tblEmployeeDetails e1
JOIN tblEmployeeDetails e2
ON e1.emp_mgr_id = e2.emp_id
EDIT:
Left Join will work if emp_mgr_id is null.
CREATE VIEW AS
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName,
e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName
FROM tblEmployeeDetails e1
LEFT JOIN tblEmployeeDetails e2
ON e1.emp_mgr_id = e2.emp_id
Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?
There are several ways to try to prevent line breaks, and the phrase “a newer construct” might refer to more than one way—that’s actually the most reasonable interpretation. They probably mostly think of the CSS declaration white-space:nowrap
and possibly the no-break space character. The different ways are not equivalent, far from that, both in theory and especially in practice, though in some given case, different ways might produce the same result.
There is probably nothing real to be gained by switching from the HTML attribute to the somewhat clumsier CSS way, and you would surely lose when style sheets are disabled. But even the nowrap
attribute does no work in all situations. In general, what works most widely is the nobr
markup, which has never made its way to any specifications but is alive and kicking: <td><nobr>...</nobr></td>
.
How to pass parameters to a partial view in ASP.NET MVC?
Here is another way to do it if you want to use ViewData:
@Html.Partial("~/PathToYourView.cshtml", null, new ViewDataDictionary { { "VariableName", "some value" } })
And to retrieve the passed in values:
@{
string valuePassedIn = this.ViewData.ContainsKey("VariableName") ? this.ViewData["VariableName"].ToString() : string.Empty;
}
Linux: is there a read or recv from socket with timeout?
You can use the setsockopt function to set a timeout on receive operations:
SO_RCVTIMEO
Sets the timeout value that specifies
the maximum amount of time an input
function waits until it completes. It
accepts a timeval structure with the
number of seconds and microseconds
specifying the limit on how long to
wait for an input operation to
complete. If a receive operation has
blocked for this much time without
receiving additional data, it shall
return with a partial count or errno
set to [EAGAIN] or [EWOULDBLOCK] if no
data is received. The default for this
option is zero, which indicates that a
receive operation shall not time out.
This option takes a timeval structure.
Note that not all implementations
allow this option to be set.
// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
Reportedly on Windows this should be done before calling bind
. I have verified by experiment that it can be done either before or after bind
on Linux and OS X.
Why do we need C Unions?
Here's an example of a union from my own codebase (from memory and paraphrased so it may not be exact). It was used to store language elements in an interpreter I built. For example, the following code:
set a to b times 7.
consists of the following language elements:
- symbol[set]
- variable[a]
- symbol[to]
- variable[b]
- symbol[times]
- constant[7]
- symbol[.]
Language elements were defines as '#define
' values thus:
#define ELEM_SYM_SET 0
#define ELEM_SYM_TO 1
#define ELEM_SYM_TIMES 2
#define ELEM_SYM_FULLSTOP 3
#define ELEM_VARIABLE 100
#define ELEM_CONSTANT 101
and the following structure was used to store each element:
typedef struct {
int typ;
union {
char *str;
int val;
}
} tElem;
then the size of each element was the size of the maximum union (4 bytes for the typ and 4 bytes for the union, though those are typical values, the actual sizes depend on the implementation).
In order to create a "set" element, you would use:
tElem e;
e.typ = ELEM_SYM_SET;
In order to create a "variable[b]" element, you would use:
tElem e;
e.typ = ELEM_VARIABLE;
e.str = strdup ("b"); // make sure you free this later
In order to create a "constant[7]" element, you would use:
tElem e;
e.typ = ELEM_CONSTANT;
e.val = 7;
and you could easily expand it to include floats (float flt
) or rationals (struct ratnl {int num; int denom;}
) and other types.
The basic premise is that the str
and val
are not contiguous in memory, they actually overlap, so it's a way of getting a different view on the same block of memory, illustrated here, where the structure is based at memory location 0x1010
and integers and pointers are both 4 bytes:
+-----------+
0x1010 | |
0x1011 | typ |
0x1012 | |
0x1013 | |
+-----+-----+
0x1014 | | |
0x1015 | str | val |
0x1016 | | |
0x1017 | | |
+-----+-----+
If it were just in a structure, it would look like this:
+-------+
0x1010 | |
0x1011 | typ |
0x1012 | |
0x1013 | |
+-------+
0x1014 | |
0x1015 | str |
0x1016 | |
0x1017 | |
+-------+
0x1018 | |
0x1019 | val |
0x101A | |
0x101B | |
+-------+
Ansible: get current target host's IP address
The following snippet will return the public ip of the remote machine and also default ip(i.e: LAN)
This will print ip's in quotes also to avoid confusion in using config files.
_x000D_
_x000D_
>> main.yml_x000D_
_x000D_
---_x000D_
- hosts: localhost_x000D_
tasks:_x000D_
- name: ipify_x000D_
ipify_facts:_x000D_
- debug: var=hostvars[inventory_hostname]['ipify_public_ip']_x000D_
- debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']_x000D_
- name: template_x000D_
template:_x000D_
src: debug.j2_x000D_
dest: /tmp/debug.ansible_x000D_
_x000D_
>> templates/debug.j2_x000D_
_x000D_
public_ip={{ hostvars[inventory_hostname]['ipify_public_ip'] }}_x000D_
public_ip_in_quotes="{{ hostvars[inventory_hostname]['ipify_public_ip'] }}"_x000D_
_x000D_
default_ipv4={{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}_x000D_
default_ipv4_in_quotes="{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"
_x000D_
_x000D_
_x000D_
How to find topmost view controller on iOS
Here is a Swift's implementation of an app with UINavigationController's as a root.
if let nav = UIApplication.sharedApplication().keyWindow?.rootViewController as? UINavigationController{
//get the current's navigation view controller
var vc = nav.topViewController
while vc?.presentedViewController != nil {
vc = vc?.presentedViewController
}
return vc
}
Single Result from Database by using mySQLi
If you assume just one result you could do this as in Edwin suggested by using specific users id.
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
Split string into array
Use the .split()
method. When specifying an empty string as the separator, the split()
method will return an array with one element per character.
entry = prompt("Enter your name")
entryArray = entry.split("");
Importing Excel spreadsheet data into another Excel spreadsheet containing VBA
This should get you started:
Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file,
then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook).
Here's a quick vba example of how that works:
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)
targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value
' Close customer workbook
customerWorkbook.Close
JavaScript Regular Expression Email Validation
Simple but powerful email validation for check email syntax :
var EmailId = document.getElementById('Email').value;
var emailfilter = /^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/;
if((EmailId != "") && (!(emailfilter.test(EmailId ) ) )) {
msg+= "Enter the valid email address!<br />";
}
Sending Arguments To Background Worker?
Check out the DoWorkEventArgs.Argument Property:
...
backgroundWorker1.RunWorkerAsync(yourInt);
...
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Do not access the form's BackgroundWorker reference directly.
// Instead, use the reference provided by the sender parameter.
BackgroundWorker bw = sender as BackgroundWorker;
// Extract the argument.
int arg = (int)e.Argument;
// Start the time-consuming operation.
e.Result = TimeConsumingOperation(bw, arg);
// If the operation was canceled by the user,
// set the DoWorkEventArgs.Cancel property to true.
if (bw.CancellationPending)
{
e.Cancel = true;
}
}
Flutter: Run method on Widget build complete
UPDATE: Flutter v1.8.4
Both mentioned codes are working now:
Working:
WidgetsBinding.instance
.addPostFrameCallback((_) => yourFunction(context));
Working
import 'package:flutter/scheduler.dart';
SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));
I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely
I just experienced this issue while using the Windows Subsystem for Linux (WSL2), so I will also share this solution.
My objective was to render the output from webpack both at wsl:3000
and localhost:3000
, thereby creating an alternate local endpoint.
As you might expect, this initially caused the "Invalid Host header" error to arise. Nothing seemed to help until I added the devServer config option shown below.
module.exports = {
//...
devServer: {
proxy: [
{
context: ['http://wsl:3000'],
target: 'http://localhost:3000',
},
],
},
}
This fixed the "bug" without introducing any security risks.
Reference: webpack DevServer docs