Send multiple checkbox data to PHP via jQuery ajax()
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;
How to set a selected option of a dropdown list control using angular JS
I hope I understand your question, but the ng-model
directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant
. This means that changing item.selectedVariant
in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant
has a value of 0
, that item should get selected.
If variants
is an array of objects, item.selectedVariant
must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
How does Go update third-party packages?
go get
will install the package in the first directory listed at GOPATH
(an environment variable which might contain a colon separated list of directories). You can use go get -u
to update existing packages.
You can also use go get -u all
to update all packages in your GOPATH
For larger projects, it might be reasonable to create different GOPATHs for each project, so that updating a library in project A wont cause issues in project B.
Type go help gopath
to find out more about the GOPATH
environment variable.
How to split a string in Java
I looked at all the answers and noticed that all are either 3rd party-licenced or regex-based.
Here is a good dumb implementation I use:
/**
* Separates a string into pieces using
* case-sensitive-non-regex-char-separators.
* <p>
* <code>separate("12-34", '-') = "12", "34"</code><br>
* <code>separate("a-b-", '-') = "a", "b", ""</code>
* <p>
* When the separator is the first character in the string, the first result is
* an empty string. When the separator is the last character in the string the
* last element will be an empty string. One separator after another in the
* string will create an empty.
* <p>
* If no separators are set the source is returned.
* <p>
* This method is very fast, but it does not focus on memory-efficiency. The memory
* consumption is approximately double the size of the string. This method is
* thread-safe but not synchronized.
*
* @param source The string to split, never <code>null</code>.
* @param separator The character to use as splitting.
* @return The mutable array of pieces.
* @throws NullPointerException When the source or separators are <code>null</code>.
*/
public final static String[] separate(String source, char... separator) throws NullPointerException {
String[] resultArray = {};
boolean multiSeparators = separator.length > 1;
if (!multiSeparators) {
if (separator.length == 0) {
return new String[] { source };
}
}
int charIndex = source.length();
int lastSeparator = source.length();
while (charIndex-- > -1) {
if (charIndex < 0 || (multiSeparators ? Arrays.binarySearch(separator, source.charAt(charIndex)) >= 0 : source.charAt(charIndex) == separator[0])) {
String piece = source.substring(charIndex + 1, lastSeparator);
lastSeparator = charIndex;
String[] tmp = new String[resultArray.length + 1];
System.arraycopy(resultArray, 0, tmp, 1, resultArray.length);
tmp[0] = piece;
resultArray = tmp;
}
}
return resultArray;
}
mongoError: Topology was destroyed
I alse had the same error. Finally, I found that I have some error on my code. I use load balance for two nodejs server, but I just update the code of one server.
I change my mongod server from standalone to replication
, but I forget to do the corresponding update for the connection string, so I met this error.
standalone connection string:
mongodb://server-1:27017/mydb
replication connection string:
mongodb://server-1:27017,server-2:27017,server-3:27017/mydb?replicaSet=myReplSet
details here:[mongo doc for connection string]
Solving Quadratic Equation
How about accepting complex roots as solutions?
import math
# User inserting the values of a, b and c
a = float(input("Insert coefficient a: "))
b = float(input("Insert coefficient b: "))
c = float(input("Insert coefficient c: "))
discriminant = b**2 - 4 * a * c
if discriminant >= 0:
x_1=(-b+math.sqrt(discriminant))/2*a
x_2=(-b-math.sqrt(discriminant))/2*a
else:
x_1= complex((-b/(2*a)),math.sqrt(-discriminant)/(2*a))
x_2= complex((-b/(2*a)),-math.sqrt(-discriminant)/(2*a))
if discriminant > 0:
print("The function has two distinct real roots: ", x_1, " and ", x_2)
elif discriminant == 0:
print("The function has one double root: ", x_1)
else:
print("The function has two complex (conjugate) roots: ", x_1, " and ", x_2)
What does %>% mean in R
Use ?'%*%'
to get the documentation.
%*%
is matrix multiplication. For matrix multiplication, you need an m x n
matrix times an n x p
matrix.
What do $? $0 $1 $2 mean in shell script?
They are called the Positional Parameters.
3.4.1 Positional Parameters
A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.
Should I use alias or alias_method?
A point in favor of alias
instead of alias_method
is that its semantic is recognized by rdoc, leading to neat cross references in the generated documentation, while rdoc completely ignore alias_method
.
What are Covering Indexes and Covered Queries in SQL Server?
When I simply recalled that a Clustered Index consists of a key-ordered non-heap list of ALL the columns in the defined table, the lights went on for me. The word "cluster", then, refers to the fact that there is a "cluster" of all the columns, like a cluster of fish in that "hot spot". If there is no index covering the column containing the sought value (the right side of the equation), then the execution plan uses a Clustered Index Seek into the Clustered Index's representation of the requested column because it does not find the requested column in any other "covering" index. The missing will cause a Clustered Index Seek operator in the proposed Execution Plan, where the sought value is within a column inside the ordered list represented by the Clustered Index.
So, one solution is to create a non-clustered index that has the column containing the requested value inside the index. In this way, there is no need to reference the Clustered Index, and the Optimizer should be able to hook that index in the Execution Plan with no hint. If, however, there is a Predicate naming the single column clustering key and an argument to a scalar value on the clustering key, the Clustered Index Seek Operator will still be used, even if there is already a covering index on a second column in the table without an index.
css3 text-shadow in IE9
I tried out the filters referenced above and strongly disliked the effect it created. I also didn't want to use any plugins since they'd slow down loading time for what seems like such a basic effect.
In my case I was looking for a text shadow with a 0px blur, which means the shadow is an exact replica of the text but just offset and behind. This effect can be easily recreated with jquery.
<script>
var shadowText = $(".ie9 .normalText").html();
$(".ie9 .normalText").before('<div class="shadow">' + shadowText + '</div>');
</script>
<style>
.ie9 .shadow { position: relative; top: 2px; left: -3px; }
</style>
This will create an identical effect to the css3 text-shadow below.
text-shadow: -3px 2px 0px rgba(0, 0, 0, 1.0);
here's a working example (see the large white text over the main banner image) http://www.cb.restaurantconnectinc.com/
How can I convert spaces to tabs in Vim or Linux?
Simple Python Script:
import os
SOURCE_ROOT = "ROOT DIRECTORY - WILL CONVERT ALL UNDERNEATH"
for root, dirs, files in os.walk(SOURCE_ROOT):
for f in files:
fpath = os.path.join(root,f)
assert os.path.exists(fpath)
data = open(fpath, "r").read()
data = data.replace(" ", "\t")
outfile = open(fpath, "w")
outfile.write(data)
outfile.close()
Python Pandas User Warning: Sorting because non-concatenation axis is not aligned
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
What is /dev/null 2>&1?
Edit /etc/conf.apf
. Set DEVEL_MODE="0"
. DEVEL_MODE
set to 1
will add a cron job to stop apf after 5 minutes.
Android: ScrollView force to bottom
Sometimes scrollView.post doesn't work
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
BUT if you use scrollView.postDelayed, it will definitely work
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
},1000);
JPA Criteria API - How to add JOIN clause (as general sentence as possible)
Maybe the following extract from the Chapter 23 - Using the Criteria API to Create Queries of the Java EE 6 tutorial will throw some light (actually, I suggest reading the whole Chapter 23):
For queries that navigate to related
entity classes, the query must define
a join to the related entity by
calling one of the From.join
methods
on the query root object, or another
join
object. The join methods are
similar to the JOIN
keyword in JPQL.
The target of the join uses the
Metamodel class of type
EntityType<T>
to specify the
persistent field or property of the
joined entity.
The join methods return an object of
type Join<X, Y>
, where X
is the
source entity and Y
is the target of
the join.
Example 23-10 Joining a Query
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(Pet_.owners);
Joins can be chained together to
navigate to related entities of the
target entity without having to create
a Join<X, Y>
instance for each join.
Example 23-11 Chaining Joins Together
in a Query
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);
EntityType<Owner> Owner_ = m.entity(Owner.class);
Root<Pet> pet = cq.from(Pet.class);
Join<Owner, Address> address = cq.join(Pet_.owners).join(Owner_.addresses);
That being said, I have some additional remarks:
First, the following line in your code:
Root entity_ = cq.from(this.baseClass);
Makes me think that you somehow missed the Static Metamodel Classes part. Metamodel classes such as Pet_
in the quoted example are used to describe the meta information of a persistent class. They are typically generated using an annotation processor (canonical metamodel classes) or can be written by the developer (non-canonical metamodel). But your syntax looks weird, I think you are trying to mimic something that you missed.
Second, I really think you should forget this assay_id
foreign key, you're on the wrong path here. You really need to start to think object and association, not tables and columns.
Third, I'm not really sure to understand what you mean exactly by adding a JOIN clause as generical as possible and what your object model looks like, since you didn't provide it (see previous point). It's thus just impossible to answer your question more precisely.
To sum up, I think you need to read a bit more about JPA 2.0 Criteria and Metamodel API and I warmly recommend the resources below as a starting point.
See also
Related question
How to connect mySQL database using C++
Found here:
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
minimum double value in C/C++
The original question concerns infinity.
So, why not use
#define Infinity ((double)(42 / 0.0))
according to the IEEE definition?
You can negate that of course.
Quickest way to clear all sheet contents VBA
Technically, and from Comintern's accepted workaround,
I believe you actually want to Delete all the Cells in the Sheet. Which removes Formatting (See footnote for exceptions), etc. as well as the Cells Contents.
I.e. Sheets("Zeroes").Cells.Delete
Combined also with UsedRange, ScreenUpdating and Calculation skipping it should be nearly intantaneous:
Sub DeleteCells ()
Application.Calculation = XlManual
Application.ScreenUpdating = False
Sheets("Zeroes").UsedRange.Delete
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
End Sub
Or if you prefer to respect the Calculation State Excel is currently in:
Sub DeleteCells ()
Dim SaveCalcState
SaveCalcState = Application.Calculation
Application.Calculation = XlManual
Application.ScreenUpdating = False
Sheets("Zeroes").UsedRange.Delete
Application.ScreenUpdating = True
Application.Calculation = SaveCalcState
End Sub
Footnote: If formatting was applied for an Entire Column, then it is not deleted.
This includes Font Colour, Fill Colour and Borders, the Format Category (like General, Date, Text, Etc.) and perhaps other properties too, but
Conditional formatting IS deleted, as is Entire Row formatting.
(Entire Column formatting is quite useful if you are importing raw data repeatedly to a sheet as it will conform to the Formats originally applied if a simple Paste-Values-Only type import is done.)
How to check if command line tools is installed
To check if command line tools are installed run:
xcode-select --version
// if installed you will see the below with the version found in your system
// xcode-select version 1234.
If command line tools are not installed run:
xcode-select --install
Rotate a div using javascript
To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.
To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.
var rotated = false;
document.getElementById('button').onclick = function() {
var div = document.getElementById('div'),
deg = rotated ? 0 : 66;
div.style.webkitTransform = 'rotate('+deg+'deg)';
div.style.mozTransform = 'rotate('+deg+'deg)';
div.style.msTransform = 'rotate('+deg+'deg)';
div.style.oTransform = 'rotate('+deg+'deg)';
div.style.transform = 'rotate('+deg+'deg)';
rotated = !rotated;
}
_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_
To add some animation to the rotation all we have to do is add CSS transitions
div {
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_
Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript
document.getElementById('button').onclick = function() {
document.getElementById('div').classList.toggle('rotated');
}
_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
-webkit-transform : rotate(66deg); _x000D_
-moz-transform : rotate(66deg); _x000D_
-ms-transform : rotate(66deg); _x000D_
-o-transform : rotate(66deg); _x000D_
transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_
How to force maven update?
It's important to add that the main difference of running mvn
with -U and without -U is that -U
will override your local SNAPSHOT jars with remote SNAPSHOT jars.
Local SNAPSHOT jars created from local mvn install
in cases where you have other modules of your proj that generate jars.
sed edit file in place
The following works fine on my mac
sed -i.bak 's/foo/bar/g' sample
We are replacing foo with bar in sample file. Backup of original file will be saved in sample.bak
For editing inline without backup, use the following command
sed -i'' 's/foo/bar/g' sample
How to unit test abstract classes: extend with stubs?
If your abstract class contains concrete functionality that has business value, then I will usually test it directly by creating a test double that stubs out the abstract data, or by using a mocking framework to do this for me. Which one I choose depends a lot on whether I need to write test-specific implementations of the abstract methods or not.
The most common scenario in which I need to do this is when I'm using the Template Method pattern, such as when I'm building some sort of extensible framework that will be used by a 3rd party. In this case, the abstract class is what defines the algorithm that I want to test, so it makes more sense to test the abstract base than a specific implementation.
However, I think it's important that these tests should focus on the concrete implementations of real business logic only; you shouldn't unit test implementation details of the abstract class because you'll end up with brittle tests.
Deleting a file in VBA
Here's a tip: are you re-using the file name, or planning to do something that requires the deletion immediately?
No?
You can get VBA to fire the command DEL "C:\TEMP\scratchpad.txt" /F from the command prompt asynchronously using VBA.Shell:
Shell "DEL " & chr(34) & strPath & chr(34) & " /F ", vbHide
Note the double-quotes (ASCII character 34) around the filename: I'm assuming that you've got a network path, or a long file name containing spaces.
If it's a big file, or it's on a slow network connection, fire-and-forget is the way to go.
Of course, you never get to see if this worked or not; but you resume your VBA immediately, and there are times when this is better than waiting for the network.
How to get bean using application context in spring boot
You can use ServiceLocatorFactoryBean. First you need to create an interface for your class
public interface YourClassFactory {
YourClass getClassByName(String name);
}
Then you have to create a config file for ServiceLocatorBean
@Configuration
@Component
public class ServiceLocatorFactoryBeanConfig {
@Bean
public ServiceLocatorFactoryBean serviceLocatorBean(){
ServiceLocatorFactoryBean bean = new ServiceLocatorFactoryBean();
bean.setServiceLocatorInterface(YourClassFactory.class);
return bean;
}
}
Now you can find your class by name like that
@Autowired
private YourClassfactory factory;
YourClass getYourClass(String name){
return factory.getClassByName(name);
}
How can I get the browser's scrollbar sizes?
Here's the more concise and easy to read solution based on offset width difference:
function getScrollbarWidth(): number {
// Creating invisible container
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.overflow = 'scroll'; // forcing scrollbar to appear
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
document.body.appendChild(outer);
// Creating inner element and placing it in the container
const inner = document.createElement('div');
outer.appendChild(inner);
// Calculating difference between container's full width and the child width
const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);
// Removing temporary elements from the DOM
outer.parentNode.removeChild(outer);
return scrollbarWidth;
}
See the JSFiddle.
HTML table needs spacing between columns, not rows
This can be achieved by putting padding between the columns using CSS. You can either add padding to the left of all columns except the first, or add padding to the right of all columns except the last. You should avoid adding padding to the right of the last column or to the left of the first as this will insert redundant white space. You should also avoid being too prescriptive with classes to specify which columns should have the additional padding as this will make maintenance harder if you later add a new column.
The 'lobotomised owl selector' allows you to select all siblings, regardless of if they are a th
, td
or something else.
_x000D_
_x000D_
tr > * + * {
padding-left: 4em;
}
_x000D_
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
_x000D_
_x000D_
_x000D_
Odd behavior when Java converts int to byte?
Two's complement Equation:
In Java, byte
(N=8) and int
(N=32) are represented by the 2s-complement shown above.
From the equation, a7 is negative for byte
but positive for int
.
coef: a7 a6 a5 a4 a3 a2 a1 a0
Binary: 1 0 0 0 0 1 0 0
----------------------------------------------
int: 128 + 0 + 0 + 0 + 0 + 4 + 0 + 0 = 132
byte: -128 + 0 + 0 + 0 + 0 + 4 + 0 + 0 = -124
Operator overloading ==, !=, Equals
In fact, this is a "how to" subject. So, here is the reference implementation:
public class BOX
{
double height, length, breadth;
public static bool operator == (BOX b1, BOX b2)
{
if ((object)b1 == null)
return (object)b2 == null;
return b1.Equals(b2);
}
public static bool operator != (BOX b1, BOX b2)
{
return !(b1 == b2);
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
var b2 = (BOX)obj;
return (length == b2.length && breadth == b2.breadth && height == b2.height);
}
public override int GetHashCode()
{
return height.GetHashCode() ^ length.GetHashCode() ^ breadth.GetHashCode();
}
}
REF: https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx#Examples
UPDATE: the cast to (object)
in the operator ==
implementation is important, otherwise, it would re-execute the operator == overload, leading to a stackoverflow. Credits to @grek40.
This (object)
cast trick is from Microsoft String
== implementaiton.
SRC: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs#L643
installing vmware tools: location of GCC binary?
Found the answer. What I did was was first
sudo apt-get install aptitude
sudo aptitude install libglib2.0-0
sudo aptitude install gcc-4.7 make linux-headers-`uname -r` -y
and tried it but it didn't work so I continued and did
sudo apt-get install build-essential
sudo apt-get install gcc-4.7 linux-headers-`uname -r`
after doing these two steps and trying again, it worked.
How to add number of days in postgresql datetime
This will give you the deadline :
select id,
title,
created_at + interval '1' day * claim_window as deadline
from projects
Alternatively the function make_interval
can be used:
select id,
title,
created_at + make_interval(days => claim_window) as deadline
from projects
To get all projects where the deadline is over, use:
select *
from (
select id,
created_at + interval '1' day * claim_window as deadline
from projects
) t
where localtimestamp at time zone 'UTC' > deadline
Can we define min-margin and max-margin, max-padding and min-padding in css?
@vigilante_stark's answer worked for me. It can be used to set a minimum "approximately" fixed margin in pixels. But in a responsive layout, when the width of the page is increasing margin can be increased by a percentage according to the given percentage as well.
I used it as follows
example-class{
margin: 0 calc(20px + 5%) 0 0;
}
How to create a bash script to check the SSH connection?
You can check this with the return-value ssh gives you:
$ ssh -q user@downhost exit
$ echo $?
255
$ ssh -q user@uphost exit
$ echo $?
0
EDIT: Another approach would be to use nmap (you won't need to have keys or login-stuff):
$ a=`nmap uphost -PN -p ssh | grep open`
$ b=`nmap downhost -PN -p ssh | grep open`
$ echo $a
22/tcp open ssh
$ echo $b
(empty string)
But you'll have to grep the message (nmap does not use the return-value to show if a port was filtered, closed or open).
EDIT2:
If you're interested in the actual state of the ssh-port, you can substitute grep open
with egrep 'open|closed|filtered'
:
$ nmap host -PN -p ssh | egrep 'open|closed|filtered'
Just to be complete.
Why do we use Base64?
What does it mean "media that are designed to deal with textual data"?
Back in the day when ASCII ruled the world dealing with non-ASCII values was a headache. People jumped through all sorts of hoops to get these transferred over the wire without losing out information.
error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup
Your tried to turn that source file into an executable, which obviously isn't possible, because the mandatory entry point, the main
function, isn't defined. Add a file main.cpp and define a main function. If you're working on the commandline (which I doubt), you can add /c
to only compile and not link. This will produce an object file only, which needs to be linked into either a static or shared lib or an application (in which case you'll need an oject file with main defined).
_WinMain
is Microsoft's name for main
when linking.
Also: you're not running the code yet, you are compiling (and linking) it. C++ is not an interpreted language.
When is a C++ destructor called?
Whenever you use "new", that is, attach an address to a pointer, or to say, you claim space on the heap, you need to "delete" it.
1.yes, when you delete something, the destructor is called.
2.When the destructor of the linked list is called, it's objects' destructor is called. But if they are pointers, you need to delete them manually.
3.when the space is claimed by "new".
Printing Even and Odd using two Threads in Java
public class EvenOddex {
public static class print {
int n;
boolean isOdd = false;
synchronized public void printEven(int n) {
while (isOdd) {
try {
wait();
} catch (InterruptedException ex) {
Logger.getLogger(EvenOddex.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.print(Thread.currentThread().getName() + n + "\n");
isOdd = true;
notify();
}
synchronized public void printOdd(int n) {
while (!isOdd) {
try {
wait();
} catch (InterruptedException ex) {
Logger.getLogger(EvenOddex.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.print(Thread.currentThread().getName() + n + "\n");
isOdd = false;
notify();
}
}
public static class even extends Thread {
print po;
even(print po) {
this.po = po;
new Thread(this, "Even").start();
}
@Override
public void run() {
for (int j = 0; j < 10; j++) {
if ((j % 2) == 0) {
po.printEven(j);
}
}
}
}
public static class odd extends Thread {
print po;
odd(print po) {
this.po = po;
new Thread(this, "Odd").start();
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if ((i % 2) != 0) {
po.printOdd(i);
}
}
}
}
public static void main(String args[]) {
print po = new print();
new even(po);
new odd(po);
}
}
How to get thread id of a pthread in linux c program?
pthread_self()
function will give the thread id of current thread.
pthread_t pthread_self(void);
The pthread_self()
function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use pthread_getthreadid_np()
to return an integral identifier for the thread.
NOTE:
pthread_id_np_t tid;
tid = pthread_getthreadid_np();
is significantly faster than these calls, but provides the same behavior.
pthread_id_np_t tid;
pthread_t self;
self = pthread_self();
pthread_getunique_np(&self, &tid);
How to sort an array in Bash
try this:
echo ${array[@]} | awk 'BEGIN{RS=" ";} {print $1}' | sort
Output will be:
3
5
a
b
c
f
Problem solved.
Public class is inaccessible due to its protection level
This error is a result of the protection level of ClassB
's constructor, not ClassB
itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal
by default. Declaring the constructor public
will fix this problem:
public ClassB() { }
* One could also say that constructors have no name, only a type; this does not change the essence of the problem.
How do I include image files in Django templates?
In development
In your app folder create folder name 'static' and save your picture in that folder.
To use picture use:
<html>
<head>
{% load staticfiles %} <!-- Prepare django to load static files -->
</head>
<body>
<img src={% static "image.jpg" %}>
</body>
</html>
In production:
Everything same like in development, just add couple more parameters for Django:
add in settings.py
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
(this will prepare folder where static files from all apps will be stored)
be sure your app is in INSTALLED_APPS = ['myapp',]
in terminall run command python manage.py collectstatic (this will make copy of static files from all apps included in INSTALLED_APPS to global static folder - STATIC_ROOT folder )
Thats all what Django need, after this you need to make some web server side setup to make premissions for use static folder. E.g. in apache2 in configuration file httpd.conf (for windows) or sites-enabled/000-default.conf. (under site virtual host part for linux) add:
Alias \static "path_to_your_project\static"
Require all granted
And that's all
How do I use the JAVA_OPTS environment variable?
JAVA_OPTS
is the standard environment variable that some servers and other java apps append to the call that executes the java
command.
For example in tomcat if you define JAVA_OPTS='-Xmx1024m'
, the startup script will execute java org.apache.tomcat.Servert -Xmx1024m
If you are running in Linux/OSX, you can set the JAVA_OPTS, right before you call the startup script by doing
JAVA_OPTS='-Djava.awt.headless=true'
This will only last as long as the console is open.
To make it more permanent you can add it to your ~/.profile or ~/.bashrc file.
Concatenate a NumPy array to another NumPy array
Sven said it all, just be very cautious because of automatic type adjustments when append is called.
In [2]: import numpy as np
In [3]: a = np.array([1,2,3])
In [4]: b = np.array([1.,2.,3.])
In [5]: c = np.array(['a','b','c'])
In [6]: np.append(a,b)
Out[6]: array([ 1., 2., 3., 1., 2., 3.])
In [7]: a.dtype
Out[7]: dtype('int64')
In [8]: np.append(a,c)
Out[8]:
array(['1', '2', '3', 'a', 'b', 'c'],
dtype='|S1')
As you see based on the contents the dtype went from int64 to float32, and then to S1
JavaScript naming conventions
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. eg:
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? Would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // since I recognize the 'the' convention, I know it's static
})
How to use \n new line in VB msgbox() ...?
These are the character sequences to create a new line:
vbCr
is the carriage return (return to line beginning),
vbLf
is the line feed (go to next line)
vbCrLf
is the carriage return / line feed (similar to pressing Enter)
I prefer vbNewLine
as it is system independent (vbCrLf
may not be a true new line on some systems)
Encrypt and decrypt a String in java
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}
Here's an example that uses the class:
try {
// Generate a temporary key. In practice, you would save this key.
// See also Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt("Don't tell anybody!");
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}
Is there an XSLT name-of element?
<xsl:for-each select="person">
<xsl:for-each select="*">
<xsl:value-of select="local-name()"/> : <xsl:value-of select="."/>
</xsl:for-each>
</xsl:for-each>
Writing Unicode text to a text file?
The file opened by codecs.open
is a file that takes unicode
data, encodes it in iso-8859-1
and writes it to the file. However, what you try to write isn't unicode
; you take unicode
and encode it in iso-8859-1
yourself. That's what the unicode.encode
method does, and the result of encoding a unicode string is a bytestring (a str
type.)
You should either use normal open()
and encode the unicode yourself, or (usually a better idea) use codecs.open()
and not encode the data yourself.
How to INNER JOIN 3 tables using CodeIgniter
For executing pure SQL statements (I Don't Know About the FRAMEWORK- CodeIGNITER!!!)
you can use SUB QUERY!
The Syntax Would be as follows
SELECT t1.id
FROM example t1 INNER JOIN
(select id from (example2 t1
join example3 t2
on t1
.id
= t2
.id
)) as t2 ON t1.id = t2.id;
Hope you Get My Point!
How to randomize (shuffle) a JavaScript array?
Randomize array
var arr = ['apple','cat','Adam','123','Zorro','petunia'];
var n = arr.length; var tempArr = [];
for ( var i = 0; i < n-1; i++ ) {
// The following line removes one random element from arr
// and pushes it onto tempArr
tempArr.push(arr.splice(Math.floor(Math.random()*arr.length),1)[0]);
}
// Push the remaining item onto tempArr
tempArr.push(arr[0]);
arr=tempArr;
Iterate through Nested JavaScript Objects
Here is a concise breadth-first iterative solution, which I prefer to recursion:
const findCar = function(car) {
const carSearch = [cars];
while(carSearch.length) {
let item = carSearch.shift();
if (item.label === car) return true;
carSearch.push(...item.subs);
}
return false;
}
How to create a temporary directory/folder in Java?
I like the multiple attempts at creating a unique name but even this solution does not rule out a race condition. Another process can slip in after the test for exists()
and the if(newTempDir.mkdirs())
method invocation. I have no idea how to completely make this safe without resorting to native code, which I presume is what's buried inside File.createTempFile()
.
How to align 3 divs (left/center/right) inside another div?
There are several tricks available for aligning the elements.
01. Using Table Trick
_x000D_
_x000D_
.container{_x000D_
display:table;_x000D_
}_x000D_
_x000D_
.left{_x000D_
background:green;_x000D_
display:table-cell;_x000D_
width:33.33vw;_x000D_
}_x000D_
_x000D_
.center{_x000D_
background:gold;_x000D_
display:table-cell;_x000D_
width:33.33vw;_x000D_
}_x000D_
_x000D_
.right{_x000D_
background:gray;_x000D_
display:table-cell;_x000D_
width:33.33vw;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left">_x000D_
Left_x000D_
</div>_x000D_
<div class="center">_x000D_
Center_x000D_
</div>_x000D_
<div class="right">_x000D_
Right_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
02. Using Flex Trick
_x000D_
_x000D_
.container{_x000D_
display:flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.left{_x000D_
background:green;_x000D_
width:33.33vw;_x000D_
}_x000D_
_x000D_
.center{_x000D_
background:gold;_x000D_
width:33.33vw;_x000D_
}_x000D_
_x000D_
.right{_x000D_
background:gray;_x000D_
width:33.33vw;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left">_x000D_
Left_x000D_
</div>_x000D_
<div class="center">_x000D_
Center_x000D_
</div>_x000D_
<div class="right">_x000D_
Right_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
03. Using Float Trick
_x000D_
_x000D_
.left{_x000D_
background:green;_x000D_
width:100px;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
.center{_x000D_
background:gold;_x000D_
width:100px;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
.right{_x000D_
background:gray;_x000D_
width:100px;_x000D_
float:left;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left">_x000D_
Left_x000D_
</div>_x000D_
<div class="center">_x000D_
Center_x000D_
</div>_x000D_
<div class="right">_x000D_
Right_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Initializing a two dimensional std::vector
Let's say you want to initialize 2D vector, m*n, with initial value to be 0
we could do this
#include<iostream>
int main(){
int m = 2, n = 5;
vector<vector<int>> vec(m, vector<int> (n, 0));
return 0;
}
String method cannot be found in a main class method
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
Insert json file into mongodb
Use below command while importing JSON file
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs --file example2.json
How do I round a double to two decimal places in Java?
Are you working with money? Creating a String
and then converting it back is pretty loopy.
Use BigDecimal
. This has been discussed quite extensively. You should have a Money
class and the amount should be a BigDecimal
.
Even if you're not working with money, consider BigDecimal
.
How to echo out table rows from the db (php)
$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
echo "<tr>";
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
Create dynamic variable name
C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickTest
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> names = new Dictionary<string,int>();
for (int i = 0; i < 10; i++)
{
names.Add(String.Format("name{0}", i.ToString()), i);
}
var xx1 = names["name1"];
var xx2 = names["name2"];
var xx3 = names["name3"];
}
}
}
HTML form do some "action" when hit submit button
Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems
Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:
For this example you will need to create two pages. On the first page
we will create a simple HTML form to collect some data. Here is an
example:
<html>
<head>
<title>Test Page</title>
</head>
<body>
<h2>Data Collection</h2><p>
<form action="process.php" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="Name"/></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="Age"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
This page will
send the Name and Age data to the page process.php. Now lets create process.php to use
the data from the HTML form we made:
<?php
print "Your name is ". $Name;
print "<br />";
print "You are ". $Age . " years old";
print "<br />"; $old = 25 + $Age;
print "In 25 years you will be " . $old . " years old";
?>
As you
may be aware, if you leave out the method="post" part of the form, the
URL with show the data. For example if your name is Bill Jones and you
are 35 years old, our process.php page will display as
http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want,
you can manually change the URL in this way and the output will change
accordingly.
Additional JavaScript Example
This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.
Note: document.getElementById("fname").value
gets the object with the ID
tag that equals fname
and then pulls it's value
- which in this case is the text in the First Name textbox.
<html>
<head>
<script type="text/javascript">
function ExampleJS(){
var jFirst = document.getElementById("fname").value;
var jLast = document.getElementById("lname").value;
alert("Your name is: " + jFirst + " " + jLast);
}
</script>
</head>
<body>
<FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">
First name: <input type="text" id="fname" name="firstname" /><br />
Last name: <input type="text" id="lname" name="lastname" /><br />
<input name="Submit" type="submit" value="Update" />
</FORM>
</body>
</html>
Foreach loop in java for a custom object list
You can fix your example with the iterator pattern by changing the parametrization of the class:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
or much simpler way:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Room room : rooms) {
System.out.println(room);
}
BATCH file asks for file or folder
The real trick is: Use a Backslash at the end of the target path where to copy the file. The /Y is for overwriting existing files, if you want no warnings.
Example:
xcopy /Y "C:\file\from\here.txt" "C:\file\to\here\"
How to check if a process is running via a batch script
Under Windows you can use Windows Management Instrumentation (WMI) to ensure that no apps with the specified command line is launched, for example:
wmic process where (name="nmake.exe") get commandline | findstr /i /c:"/f load.mak" /c:"/f build.mak" > NUL && (echo THE BUILD HAS BEEN STARTED ALREADY! > %ALREADY_STARTED% & exit /b 1)
Can local storage ever be considered secure?
As an exploration of this topic, I have a presentation titled "Securing TodoMVC Using the Web Cryptography API" (video, code).
It uses the Web Cryptography API to store the todo list encrypted in localStorage by password protecting the application and using a password derived key for encryption. If you forget or lose the password, there is no recovery. (Disclaimer - it was a POC and not intended for production use.)
As the other answers state, this is still susceptible to XSS or malware installed on the client computer. However, any sensitive data would also be in memory when the data is stored on the server and the application is in use. I suggest that offline support may be the compelling use case.
In the end, encrypting localStorage probably only protects the data from attackers that have read only access to the system or its backups. It adds a small amount of defense in depth for OWASP Top 10 item A6-Sensitive Data Exposure, and allows you to answer "Is any of this data stored in clear text long term?" correctly.
Installing cmake with home-brew
Download the latest CMake Mac binary distribution here: https://cmake.org/download/
(current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
How to rollback just one step using rake db:migrate
try {
$result=DB::table('users')->whereExists(function ($Query){
$Query->where('id','<','14162756');
$Query->whereBetween('password',[14162756,48384486]);
$Query->whereIn('id',[3,8,12]);
});
}catch (\Exception $error){
Log::error($error);
DB::rollBack(1);
return redirect()->route('bye');
}
Enable CORS in fetch api
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
Default session timeout for Apache Tomcat applications
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
How can I replace newlines using PowerShell?
A CRLF is two characters, of course, the CR and the LF. However, `n
consists of both. For example:
PS C:\> $x = "Hello
>> World"
PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>
I think you're running into problems with the `r
. I was able to remove the `r
from your example, use only `n
, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.
What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
- Composer dump-autoload won’t download a thing.
- It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php).
- Ideal for when you have a new class inside your project.
- autoload_classmap.php also includes the providers in config/app.php
php artisan dump-autoload
- It will call Composer with the optimize flag
- It will 'recompile' loads of files creating the huge bootstrap/compiled.php
How to backup MySQL database in PHP?
Based on the good solution that provided by tazo todua, I've made some of changes since mysql_connect
has deprecated and not supported in new php version. I've used mysqli_connect
instead and increased the performance of inserting values to the database:
<?php
/**
* Updated: Mohammad M. AlBanna
* Website: MBanna.info
*/
//MySQL server and database
$dbhost = 'localhost';
$dbuser = 'my_user';
$dbpass = 'my_pwd';
$dbname = 'database_name';
$tables = '*';
//Call the core function
backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables);
//Core function
function backup_tables($host, $user, $pass, $dbname, $tables = '*') {
$link = mysqli_connect($host,$user,$pass, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($link, "SET NAMES 'utf8'");
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysqli_query($link, 'SHOW TABLES');
while($row = mysqli_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = '';
//cycle through
foreach($tables as $table)
{
$result = mysqli_query($link, 'SELECT * FROM '.$table);
$num_fields = mysqli_num_fields($result);
$num_rows = mysqli_num_rows($result);
$return.= 'DROP TABLE IF EXISTS '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
$counter = 1;
//Over tables
for ($i = 0; $i < $num_fields; $i++)
{ //Over rows
while($row = mysqli_fetch_row($result))
{
if($counter == 1){
$return.= 'INSERT INTO '.$table.' VALUES(';
} else{
$return.= '(';
}
//Over fields
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
if($num_rows == $counter){
$return.= ");\n";
} else{
$return.= "),\n";
}
++$counter;
}
}
$return.="\n\n\n";
}
//save file
$fileName = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
$handle = fopen($fileName,'w+');
fwrite($handle,$return);
if(fclose($handle)){
echo "Done, the file name is: ".$fileName;
exit;
}
}
Does SVG support embedding of bitmap images?
Yes, you can reference any image from the image
element. And you can use data URIs to make the SVG self-contained. An example:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
...
<image
width="100" height="100"
xlink:href="data:image/png;base64,IMAGE_DATA"
/>
...
</svg>
The svg
element attribute xmlns:xlink
declares xlink
as a namespace prefix and says where the definition is. That then allows the SVG reader to know what xlink:href
means.
The IMAGE_DATA
is where you'd add the image data as base64-encoded text. Vector graphics editors that support SVG usually have an option for saving with images embedded. Otherwise there are plenty of tools around for encoding a byte stream to and from base64.
Here's a full example from the SVG testsuite.
Merge data frames based on rownames in R
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
How to get the public IP address of a user in C#
On MVC 5 you can use this:
string cIpAddress = Request.UserHostAddress; //Gets the client ip address
or
string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address
Recursive file search using PowerShell
When searching folders where you might get an error based on security (e.g. C:\Users
), use the following command:
Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force
T-SQL string replace in Update
update YourTable
set YourColumn = replace(YourColumn, '@domain2', '@domain1')
where charindex('@domain2', YourColumn) <> 0
Javascript form validation with password confirming
Just add onsubmit
event handler for your form:
<form action="insert.php" onsubmit="return myFunction()" method="post">
Remove onclick
from button
and make it input
with type submit
<input type="submit" value="Submit">
And add boolean return statements to your function:
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var ok = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
return false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
How to use the CSV MIME-type?
You are not specifying a language or framework, but the following header is used for file downloads:
"Content-Disposition: attachment; filename=abc.csv"
Index was out of range. Must be non-negative and less than the size of the collection parameter name:index
what this means ? is there any problem in my code
It means that you are accessing a location or index which is not present in collection.
To find this, Make sure your Gridview has 5 columns as you are using it's 5th column by this line
dataGridView1.Columns[4].Name = "Amount";
Here is the image which shows the elements of an array. So if your gridview has less column then the (index + 1)
by which you are accessing it, then this exception arises.
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize
in case some one still get this kind of message. Its happen because you add JVM argument when running maven project. Because it is related with maven you can check your pom.xml
file on your project.
find this line <argLine>...</argLine>
, on my project I also have argument below
<argLine>-Xmx1024m -XX:MaxPermSize=512m -XX:+TieredCompilation -XX:TieredStopAtLevel=1</argLine>
you should replace MaxPermSize
argument as -Xms123m -Xmx123m
, since MaxPermSize
is already deprecated and wont take any effect on your JVM config :
<argLine>-Xms512m -Xmx512m -XX:+TieredCompilation -XX:TieredStopAtLevel=1</argLine>
How do I implement JQuery.noConflict() ?
It allows for you to give the jQuery variable a different name, and still use it:
<script type="text/javascript">
$jq = $.noConflict();
// Code that uses other library's $ can follow here.
//use $jq for all calls to jQuery:
$jq.ajax(...)
$jq('selector')
</script>
How does one get started with procedural generation?
Procedural content generation is now all written for the GPU, so you'll need to know a shader language. That means GLSL or HLSL. These are languages tied to OpenGL and DirectX respectively.
While my personal preference is for Dx11 / HLSL due to speed, an easier learning curve and Frank D Luna, OpenGL is supported on more platforms.
You should also check out WebGL if you want to jump right into writing shaders without having to spend the (considerable) time it takes to setup an OpenGL / DirectX game engine.
Procedural content starts with noise.
So you'll need to learn about Perlin noise (and its successor Simplex noise).
Shadertoy is a superb reference for learning about shader programming. I would recommend you come to it once you've given shader coding a go yourself, as the code there is not for the mathematically squeamish, but that is how procedural content is done.
Shadertoy was created by a procedural genius, Inigo Quilez, a product of the demo scene who works at Pixar. He has some youtube videos (great example) of live coding sessions and I can also recommend these.
How to save data in an android app
Quick answer:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Boolean Music;
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//restore preferences
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
Music = settings.getBoolean("key", true);
}
@Override
public void onClick() {
//save music setup to system
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("key", Music);
editor.apply();
}
}
How to tell whether a point is to the right or left side of a line
A(x1,y1) B(x2,y2) a line segment with length L=sqrt( (y2-y1)^2 + (x2-x1)^2 )
and a point M(x,y)
making a transformation of coordinates in order to be the point A the new start and B a point of the new X axis
we have the new coordinates of the point M
which are
newX = ((x-x1)(x2-x1)+(y-y1)(y2-y1)) / L
from (x-x1)*cos(t)+(y-y1)*sin(t) where cos(t)=(x2-x1)/L, sin(t)=(y2-y1)/L
newY = ((y-y1)(x2-x1)-(x-x1)(y2-y1)) / L
from (y-y1)*cos(t)-(x-x1)*sin(t)
because "left" is the side of axis X where the Y is positive, if the newY (which is the distance of M from AB) is positive, then it is on the left side of AB (the new X axis)
You may omit the division by L (allways positive), if you only want the sign
403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied
I had the same problem. It turned out that I didn't specify a default page and I didn't have any page that is named after the default page convention (default.html, defult.aspx etc). As a result, ASP.NET doesn't allow the user to browse the directory (not a problem in Visual Studio built-in web server that allows you to view the directory) and shows the error message. To fix it, I added one default page in Web.Config and it worked.
<system.webServer>
<defaultDocument>
<files>
<add value="myDefault.aspx"/>
</files>
</defaultDocument>
</system.webServer>
Embedding VLC plugin on HTML page
I found this:
<embed type="application/x-vlc-plugin"
pluginspage="http://www.videolan.org"version="VideoLAN.VLCPlugin.2" width="100%"
height="100%" id="vlc" loop="yes"autoplay="yes" target="http://10.1.2.201:8000/"></embed>
I don't see that in your code anywhere.... I think that's all you need and the target would be the location of your video...
and here is more info on the vlc plugin:
http://wiki.videolan.org/Documentation%3aWebPlugin#Input_object
Another thing to check is that the address for the video file is correct....
How to compare strings in C conditional preprocessor-directives
You can't do that if USER is defined as a quoted string.
But you can do that if USER is just JACK or QUEEN or Joker or whatever.
There are two tricks to use:
- Token-splicing, where you combine an identifier with another identifier by just concatenating their characters. This allows you to compare against JACK without having to
#define JACK
to something
- variadic macro expansion, which allows you to handle macros with variable numbers of arguments. This allows you to expand specific identifiers into varying numbers of commas, which will become your string comparison.
So let's start out with:
#define JACK_QUEEN_OTHER(u) EXPANSION1(ReSeRvEd_, u, 1, 2, 3)
Now, if I write JACK_QUEEN_OTHER(USER)
, and USER is JACK, the preprocessor
turns that into EXPANSION1(ReSeRvEd_, JACK, 1, 2, 3)
Step two is concatenation:
#define EXPANSION1(a, b, c, d, e) EXPANSION2(a##b, c, d, e)
Now JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(ReSeRvEd_JACK, 1, 2, 3)
This gives the opportunity to add a number of commas according to whether or not a string matches:
#define ReSeRvEd_JACK x,x,x
#define ReSeRvEd_QUEEN x,x
If USER is JACK, JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(x,x,x, 1, 2, 3)
If USER is QUEEN, JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(x,x, 1, 2, 3)
If USER is other, JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(ReSeRvEd_other, 1, 2, 3)
At this point, something critical has happened: the fourth argument to the EXPANSION2 macro is either 1, 2, or 3, depending on whether the original argument passed was jack, queen, or anything else. So all we have to do is pick it out. For long-winded reasons, we'll need two macros for the last step; they'll be EXPANSION2 and EXPANSION3, even though one seems unnecessary.
Putting it all together, we have these 6 macros:
#define JACK_QUEEN_OTHER(u) EXPANSION1(ReSeRvEd_, u, 1, 2, 3)
#define EXPANSION1(a, b, c, d, e) EXPANSION2(a##b, c, d, e)
#define EXPANSION2(a, b, c, d, ...) EXPANSION3(a, b, c, d)
#define EXPANSION3(a, b, c, d, ...) d
#define ReSeRvEd_JACK x,x,x
#define ReSeRvEd_QUEEN x,x
And you might use them like this:
int main() {
#if JACK_QUEEN_OTHER(USER) == 1
printf("Hello, Jack!\n");
#endif
#if JACK_QUEEN_OTHER(USER) == 2
printf("Hello, Queen!\n");
#endif
#if JACK_QUEEN_OTHER(USER) == 3
printf("Hello, who are you?\n");
#endif
}
Obligatory godbolt link: https://godbolt.org/z/8WGa19
MSVC Update: You have to parenthesize slightly differently to make things also work in MSVC. The EXPANSION* macros look like this:
#define EXPANSION1(a, b, c, d, e) EXPANSION2((a##b, c, d, e))
#define EXPANSION2(x) EXPANSION3 x
#define EXPANSION3(a, b, c, d, ...) d
Obligatory: https://godbolt.org/z/96Y8a1
Node.js fs.readdir recursive directory search
This is how I use the nodejs fs.readdir function to recursively search a directory.
const fs = require('fs');
const mime = require('mime-types');
const readdirRecursivePromise = path => {
return new Promise((resolve, reject) => {
fs.readdir(path, (err, directoriesPaths) => {
if (err) {
reject(err);
} else {
if (directoriesPaths.indexOf('.DS_Store') != -1) {
directoriesPaths.splice(directoriesPaths.indexOf('.DS_Store'), 1);
}
directoriesPaths.forEach((e, i) => {
directoriesPaths[i] = statPromise(`${path}/${e}`);
});
Promise.all(directoriesPaths).then(out => {
resolve(out);
}).catch(err => {
reject(err);
});
}
});
});
};
const statPromise = path => {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stats) => {
if (err) {
reject(err);
} else {
if (stats.isDirectory()) {
readdirRecursivePromise(path).then(out => {
resolve(out);
}).catch(err => {
reject(err);
});
} else if (stats.isFile()) {
resolve({
'path': path,
'type': mime.lookup(path)
});
} else {
reject(`Error parsing path: ${path}`);
}
}
});
});
};
const flatten = (arr, result = []) => {
for (let i = 0, length = arr.length; i < length; i++) {
const value = arr[i];
if (Array.isArray(value)) {
flatten(value, result);
} else {
result.push(value);
}
}
return result;
};
Let's say you have a path called '/database' in your node projects root. Once this promise is resolved, it should spit out an array of every file under '/database'.
readdirRecursivePromise('database').then(out => {
console.log(flatten(out));
}).catch(err => {
console.log(err);
});
How to change the scrollbar color using css
Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.
So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.
Solution:
By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution
See This Demo
Split a string into array in Perl
You already have multiple answers to your question, but I would like to add another minor one here that might help to add something.
To view data structures in Perl you can use Data::Dumper
. To print a string you can use say
, which adds a newline character "\n"
after every call instead of adding it explicitly.
I usually use \s
which matches a whitespace character. If you add +
it matches one or more whitespace characters. You can read more about it here perlre
.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use feature 'say';
my $line = "file1.gz file2.gz file3.gz";
my @abc = split /\s+/, $line;
print Dumper \@abc;
say for @abc;
Set content of HTML <span> with Javascript
The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).
The way I would actually do it is to use jQuery's .text()
.
What is the difference between bool and Boolean types in C#
bool is a primitive type, meaning that the value (true/false in this case) is stored directly in the variable. Boolean is an object. A variable of type Boolean stores a reference to a Boolean object. The only real difference is storage. An object will always take up more memory than a primitive type, but in reality, changing all your Boolean values to bool isn't going to have any noticeable impact on memory usage.
I was wrong; that's how it works in java with boolean and Boolean. In C#, bool and Boolean are both reference types. Both of them store their value directly in the variable, both of them cannot be null, and both of them require a "convertTO" method to store their values in another type (such as int). It only matters which one you use if you need to call a static function defined within the Boolean class.
How to add a footer to the UITableView?
I know that this is a pretty old question but I've just met same issue. I don't know exactly why but it seems that tableFooterView can be only an instance of UIView (not "kind of" but "is member")... So in my case I've created new UIView object (for example wrapperView) and add my custom subview to it... In your case, chamge your code from:
CGRect footerRect = CGRectMake(0, 0, 320, 40);
UILabel *tableFooter = [[UILabel alloc] initWithFrame:footerRect];
tableFooter.textColor = [UIColor blueColor];
tableFooter.backgroundColor = [self.theTable backgroundColor];
tableFooter.opaque = YES;
tableFooter.font = [UIFont boldSystemFontOfSize:15];
tableFooter.text = @"test";
self.theTable.tableFooterView = tableFooter;
[tableFooter release];
to:
CGRect footerRect = CGRectMake(0, 0, 320, 40);
UIView *wrapperView = [[UIView alloc] initWithFrame:footerRect];
UILabel *tableFooter = [[UILabel alloc] initWithFrame:footerRect];
tableFooter.textColor = [UIColor blueColor];
tableFooter.backgroundColor = [self.theTable backgroundColor];
tableFooter.opaque = YES;
tableFooter.font = [UIFont boldSystemFontOfSize:15];
tableFooter.text = @"test";
[wrapperView addSubview:tableFooter];
self.theTable.tableFooterView = wrapperView;
[wrapperView release];
[tableFooter release];
Hope it helps. It works for me.
How to persist a property of type List<String> in JPA?
Here is the solution for storing a Set using @Converter and StringTokenizer. A bit more checks against @jonck-van-der-kogel solution.
In your Entity class:
@Convert(converter = StringSetConverter.class)
@Column
private Set<String> washSaleTickers;
StringSetConverter:
package com.model.domain.converters;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
@Converter
public class StringSetConverter implements AttributeConverter<Set<String>, String> {
private final String GROUP_DELIMITER = "=IWILLNEVERHAPPEN=";
@Override
public String convertToDatabaseColumn(Set<String> stringList) {
if (stringList == null) {
return new String();
}
return String.join(GROUP_DELIMITER, stringList);
}
@Override
public Set<String> convertToEntityAttribute(String string) {
Set<String> resultingSet = new HashSet<>();
StringTokenizer st = new StringTokenizer(string, GROUP_DELIMITER);
while (st.hasMoreTokens())
resultingSet.add(st.nextToken());
return resultingSet;
}
}
load and execute order of scripts
After testing many options I've found that the following simple solution is loading the dynamically loaded scripts in the order in which they are added in all modern browsers
loadScripts(sources) {
sources.forEach(src => {
var script = document.createElement('script');
script.src = src;
script.async = false; //<-- the important part
document.body.appendChild( script ); //<-- make sure to append to body instead of head
});
}
loadScripts(['/scr/script1.js','src/script2.js'])
What are the differences between Deferred, Promise and Future in JavaScript?
A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
The deferred.promise()
method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, state and promise), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).
If target is provided, deferred.promise()
will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.
If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via deferred.promise() so other code can register callbacks or inspect the current state.
Simply we can say that a Promise represents a value that is not yet known where as a Deferred represents work that is not yet finished.
Is optimisation level -O3 dangerous in g++?
Yes, O3 is buggier. I'm a compiler developer and I've identified clear and obvious gcc bugs caused by O3 generating buggy SIMD assembly instructions when building my own software. From what I've seen, most production software ships with O2 which means O3 will get less attention wrt testing and bug fixes.
Think of it this way: O3 adds more transformations on top of O2, which adds more transformations on top of O1. Statistically speaking, more transformations means more bugs. That's true for any compiler.
Enable SQL Server Broker taking too long
Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:
USE master ;
GO
ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO
Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.
If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:
SELECT
name, database_id, is_broker_enabled
FROM sys.databases
Reading file contents on the client-side in javascript in various browsers
Edited to add information about the File API
Since I originally wrote this answer, the File API has been proposed as a standard and implemented in most browsers (as of IE 10, which added support for FileReader
API described here, though not yet the File
API). The API is a bit more complicated than the older Mozilla API, as it is designed to support asynchronous reading of files, better support for binary files and decoding of different text encodings. There is some documentation available on the Mozilla Developer Network as well as various examples online. You would use it as follows:
var file = document.getElementById("fileForUpload").files[0];
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
document.getElementById("fileContents").innerHTML = evt.target.result;
}
reader.onerror = function (evt) {
document.getElementById("fileContents").innerHTML = "error reading file";
}
}
Original answer
There does not appear to be a way to do this in WebKit (thus, Safari and Chrome). The only keys that a File object has are fileName
and fileSize
. According to the commit message for the File and FileList support, these are inspired by Mozilla's File object, but they appear to support only a subset of the features.
If you would like to change this, you could always send a patch to the WebKit project. Another possibility would be to propose the Mozilla API for inclusion in HTML 5; the WHATWG mailing list is probably the best place to do that. If you do that, then it is much more likely that there will be a cross-browser way to do this, at least in a couple years time. Of course, submitting either a patch or a proposal for inclusion to HTML 5 does mean some work defending the idea, but the fact that Firefox already implements it gives you something to start with.
Java HTTPS client certificate authentication
Finally managed to solve all the issues, so I'll answer my own question. These are the settings/files I've used to manage to get my particular problem(s) solved;
The client's keystore is a PKCS#12 format file containing
- The client's public certificate (in this instance signed by a self-signed CA)
- The client's private key
To generate it I used OpenSSL's pkcs12
command, for example;
openssl pkcs12 -export -in client.crt -inkey client.key -out client.p12 -name "Whatever"
Tip: make sure you get the latest OpenSSL, not version 0.9.8h because that seems to suffer from a bug which doesn't allow you to properly generate PKCS#12 files.
This PKCS#12 file will be used by the Java client to present the client certificate to the server when the server has explicitly requested the client to authenticate. See the Wikipedia article on TLS for an overview of how the protocol for client certificate authentication actually works (also explains why we need the client's private key here).
The client's truststore is a straight forward JKS format file containing the root or intermediate CA certificates. These CA certificates will determine which endpoints you will be allowed to communicate with, in this case it will allow your client to connect to whichever server presents a certificate which was signed by one of the truststore's CA's.
To generate it you can use the standard Java keytool, for example;
keytool -genkey -dname "cn=CLIENT" -alias truststorekey -keyalg RSA -keystore ./client-truststore.jks -keypass whatever -storepass whatever
keytool -import -keystore ./client-truststore.jks -file myca.crt -alias myca
Using this truststore, your client will try to do a complete SSL handshake with all servers who present a certificate signed by the CA identified by myca.crt
.
The files above are strictly for the client only. When you want to set-up a server as well, the server needs its own key- and truststore files. A great walk-through for setting up a fully working example for both a Java client and server (using Tomcat) can be found on this website.
Issues/Remarks/Tips
- Client certificate authentication can only be enforced by the server.
- (Important!) When the server requests a client certificate (as part of the TLS handshake), it will also provide a list of trusted CA's as part of the certificate request. When the client certificate you wish to present for authentication is not signed by one of these CA's, it won't be presented at all (in my opinion, this is weird behaviour, but I'm sure there's a reason for it). This was the main cause of my issues, as the other party had not configured their server properly to accept my self-signed client certificate and we assumed that the problem was at my end for not properly providing the client certificate in the request.
- Get Wireshark. It has great SSL/HTTPS packet analysis and will be a tremendous help debugging and finding the problem. It's similar to
-Djavax.net.debug=ssl
but is more structured and (arguably) easier to interpret if you're uncomfortable with the Java SSL debug output.
It's perfectly possible to use the Apache httpclient library. If you want to use httpclient, just replace the destination URL with the HTTPS equivalent and add the following JVM arguments (which are the same for any other client, regardless of the library you want to use to send/receive data over HTTP/HTTPS):
-Djavax.net.debug=ssl
-Djavax.net.ssl.keyStoreType=pkcs12
-Djavax.net.ssl.keyStore=client.p12
-Djavax.net.ssl.keyStorePassword=whatever
-Djavax.net.ssl.trustStoreType=jks
-Djavax.net.ssl.trustStore=client-truststore.jks
-Djavax.net.ssl.trustStorePassword=whatever
jQuery - Get Width of Element when Not Visible (Display: None)
Before take the width make the parent display show ,then take the width and finally make the parent display hide. Just like following
$('#parent').show();
var tableWidth = $('#parent').children('table').outerWidth();
$('#parent').hide();
if (tableWidth > $('#parent').width())
{
$('#parent').width() = tableWidth;
}
How can I install a package with go get?
First, we need GOPATH
The $GOPATH
is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT
directory where Go is installed.
export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin
We used ~/gocode
path in our computer to store the source of our application and its dependencies. The GOPATH
directory will also store the binaries of their packages.
Then check Go env
You system must have $GOPATH
and $GOROOT
, below is my Env:
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Now, you run download go package:
go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]
Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.
if variable contains
If you have a lot of these to check you might want to store a list of the mappings and just loop over that, instead of having a bunch of if/else statements. Something like:
var CODE_TO_LOCATION = {
'ST1': 'stoke central',
'ST2': 'stoke north',
// ...
};
function getLocation(text) {
for (var code in CODE_TO_LOCATION) {
if (text.indexOf(code) != -1) {
return CODE_TO_LOCATION[code];
}
}
return null;
}
This way you can easily add more code/location mappings. And if you want to handle more than one location you could just build up an array of locations in the function instead of just returning the first one you find.
Android Studio does not show layout preview
Fast Forward to 2018 and we are still having this issue!
When I had this issue with Android Studio Canary 3.2
today, this is what I did:
I went to
File -> Settings -> Plugins
On the plugins list, I disabled Android Support
by unchecking it.
Then, I selected Apply and then, OK.
After this I restarted Android Studio
.
On restart, I repeated the process:
File -> Settings -> Plugins
But this time, on the plugins list, I enabled Android Support
by checking it.
Then I restarted.
When Android Studio
came on, I allowed Gradle
do its thing, then I did:
File -> Sync Project with Gradle Files
When this was done, I reopened my xml files or refreshed them anyhow possible
and everything was fine.
Yeah long route, but on a day when I have to deliver at work? It sure works!
TLDR: Just disable and re-enable Android Support and you will be fine
Parse json string to find and element (key / value)
Use a JSON parser, like JSON.NET
string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Git - remote: Repository not found
Check if the url s.source is correct.
Example for me
// fail Project>>t<<est
s.source = { :git => '.../Projecttest-iOS', :tag => s.version.to_s }
// success Project>>T<<est
s.source = { :git => '.../ProjectTest-iOS', :tag => s.version.to_s }
merge two object arrays with Angular 2 and TypeScript?
I think that you should use rather the following:
data => {
this.results = this.results.concat(data.results);
this._next = data.next;
},
From the concat
doc:
The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.
How to get json response using system.net.webrequest in c#?
Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.
For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept
property to "application/json".
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
Stacking DIVs on top of each other?
You can now use CSS Grid to fix this.
<div class="outer">
<div class="top"> </div>
<div class="below"> </div>
</div>
And the css for this:
.outer {
display: grid;
grid-template: 1fr / 1fr;
place-items: center;
}
.outer > * {
grid-column: 1 / 1;
grid-row: 1 / 1;
}
.outer .below {
z-index: 2;
}
.outer .top {
z-index: 1;
}
How to validate a date?
I just do a remake of RobG solution
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;
if (isLeap) {
daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]
Effective swapping of elements of an array in Java
first of all you shouldn't write for (int k = 0; k **<** data.length **- 1**; k++)
because the < is until the k is smaller the length -1 and then the loop will run until the last position in the array and won't get the last place in the array;
so you can fix it by two ways:
1: for (int k = 0; k <= data.length - 1; k++)
2: for (int k = 0; k < data.length; k++)
and then it will work fine!!!
and to swap you can use: to keep one of the int's in another place and then to replace
int x = data[k]
data[k] = data[data.length - 1]
data[data.length - 1] = x;
because you don't want to lose one of the int's!!
JSLint says "missing radix parameter"
You can turn off this rule if you wish to skip that test.
Insert:
radix: false
Under the "rules
" property in the tslint.json
file.
It's not recommended to do that if you don't understand this exception.
List of <p:ajax> events
You can search for "Ajax Behavior Events" in PrimeFaces User's Guide, and you will find plenty of them for all supported components. That's also what PrimeFaces lead Optimus Prime suggest to do in this related question at the PrimeFaces forum <p:ajax>
event list?
There is no onblur
event, that's the HTML attribute name, but there is a blur
event. It's just without the "on" prefix like as the HTML attribute name. You can also look at all "on*" attributes of the tag documentation of the component in question to see which are all available, e.g. <p:inputText>
.
DB2 Timestamp select statement
@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000
If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:
...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'
or
...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06'
AND usagetime < '2012-09-03 08:03:07'
Multithreading in Bash
You can run several copies of your script in parallel, each copy for different input data, e.g. to process all *.cfg files on 4 cores:
ls *.cfg | xargs -P 4 -n 1 read_cfg.sh
The read_cfg.sh script takes just one parameters (as enforced by -n)
How can I get a resource "Folder" from inside my jar File?
Below code gets .yaml files from a custom resource directory.
ClassLoader classLoader = this.getClass().getClassLoader();
URI uri = classLoader.getResource(directoryPath).toURI();
if("jar".equalsIgnoreCase(uri.getScheme())){
Pattern pattern = Pattern.compile("^.+" +"/classes/" + directoryPath + "/.+.yaml$");
log.debug("pattern {} ", pattern.pattern());
ApplicationHome home = new ApplicationHome(SomeApplication.class);
JarFile file = new JarFile(home.getSource());
Enumeration<JarEntry> jarEntries = file.entries() ;
while(jarEntries.hasMoreElements()){
JarEntry entry = jarEntries.nextElement();
Matcher matcher = pattern.matcher(entry.getName());
if(matcher.find()){
InputStream in =
file.getInputStream(entry);
//work on the stream
}
}
}else{
//When Spring boot application executed through Non-Jar strategy like through IDE or as a War.
String path = uri.getPath();
File[] files = new File(path).listFiles();
for(File file: files){
if(file != null){
try {
InputStream is = new FileInputStream(file);
//work on stream
} catch (Exception e) {
log.error("Exception while parsing file yaml file {} : {} " , file.getAbsolutePath(), e.getMessage());
}
}else{
log.warn("File Object is null while parsing yaml file");
}
}
}
Subscript out of range error in this Excel VBA script
This looks a little better than your previous version but get rid of that .Activate on that line and see if you still get that error.
Dim sh1 As Worksheet
set sh1 = Workbooks.Add(filenum(lngPosition) & ".csv")
Creates a worksheet object. Not until you create that object do you want to start working with it. Once you have that object you can do the following:
sh1.Range("A69").Paste
sh1.Range("A69").Select
The sh1. explicitely tells Excel which object you are saying to work with... otherwise if you start selecting other worksheets while this code is running you could wind up pasting data to the wrong place.
How to read a large file line by line?
Best way to read large file, line by line is to use python enumerate function
with open(file_name, "rU") as read_file:
for i, row in enumerate(read_file, 1):
#do something
#i in line of that line
#row containts all data of that line
MySQL my.ini location
You can find the my.ini file in windows at this location-
C:\ProgramData\MySQL\MySQL Server 5.6
the ProgramData folder is a hidden folder, so make the according setting to see that folder.
And open my.ini file as an administrator to edit and then save that.
Why extend the Android Application class?
Best use of application class.
Example: Suppose you need to restart your alarm manager on boot completed.
public class BaseJuiceApplication extends Application implements BootListener {
public static BaseJuiceApplication instance = null;
public static Context getInstance() {
if (null == instance) {
instance = new BaseJuiceApplication();
}
return instance;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onBootCompleted(Context context, Intent intent) {
new PushService().scheduleService(getInstance());
//startToNotify(context);
}
"unrecognized import path" with go get
Because GFW forbidden you to access golang.org !
And when i use the proxy , it can work well.
you can look at the information using command
go get -v -u golang.org/x/oauth2
Output to the same line overwriting previous output?
Here's code for Python 3.x:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')
The end=
keyword is what does the work here -- by default, print()
ends in a newline (\n
) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, there's no need to import the sys
module for this sort of simple usage. print()
actually has a number of keyword arguments which can be used to greatly simplify code.
To use the same code on Python 2.6+, put the following line at the top of the file:
from __future__ import print_function
How to check for palindrome using Python logic
It looks prettier with recursion!
def isPalindrome(x):
z = numToList(x)
length = math.floor(len(z) / 2)
if length < 2:
if z[0] == z[-1]:
return True
else:
return False
else:
if z[0] == z[-1]:
del z[0]
del z[-1]
return isPalindrome(z)
else:
return False
PostgreSQL 'NOT IN' and subquery
You could also use a LEFT JOIN and IS NULL condition:
SELECT
mac,
creation_date
FROM
logs
LEFT JOIN consols ON logs.mac = consols.mac
WHERE
logs_type_id=11
AND
consols.mac IS NULL;
An index on the "mac" columns might improve performance.
Add vertical whitespace using Twitter Bootstrap?
In v2, there isn't anything built-in for that much vertical space, so you'll want to stick with a custom class. For smaller heights, I usually just throw a <div class="control-group">
around a button.
How to sort dates from Oldest to Newest in Excel?
I was just having the same problem. Here's what I found... I had copied my data from a website (loan payment information), pasted into Excel and then couldn't get it to sort appropriately by date and my calculation formulas wouldn't work. I copied the date columns and pasted as plain text in Word then turned on the formatting characters and found extra characters, namely the one that looks like a degree symbol. Same thing with my currency columns. So I used find and replace to get rid of the extra characters, then copy & paste back in to Excel. Boom! Everything worked the way it should.
Does Hive have a String split function?
Just a clarification on the answer given by Bkkbrad.
I tried this suggestion and it did not work for me.
For example,
split('aa|bb','\\|')
produced:
["","a","a","|","b","b",""]
But,
split('aa|bb','[|]')
produced the desired result:
["aa","bb"]
Including the metacharacter '|' inside the square brackets causes it to be interpreted literally, as intended, rather than as a metacharacter.
For elaboration of this behaviour of regexp, see: http://www.regular-expressions.info/charclass.html
Basic Python client socket example
It looks like your client is trying to connect to a non-existent server. In a shell window, run:
$ nc -l 5000
before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.
Getting the parent of a directory in Bash
Depending on whether you need absolute paths you may want to take an extra step:
child='/home/smith/Desktop/Test/'
parent=$(dirname "$child")
abs_parent=$(realpath "$parent")
APT command line interface-like yes/no input?
As you mentioned, the easiest way is to use raw_input()
(or simply input()
for Python 3). There is no built-in way to do this. From Recipe 577058:
import sys
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = raw_input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
Usage example:
>>> query_yes_no("Is cabbage yummier than cauliflower?")
Is cabbage yummier than cauliflower? [Y/n] oops
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [Y/n] [ENTER]
>>> True
>>> query_yes_no("Is cabbage yummier than cauliflower?", None)
Is cabbage yummier than cauliflower? [y/n] [ENTER]
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [y/n] y
>>> True
Latex - Change margins of only a few pages
I was struggling a lot with different solutions including \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:
You can change the margins of just one or more pages and then restore it to its default:
\usepackage{geometry}
...
...
...
\newgeometry{top=5mm, bottom=10mm} % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...
\restoregeometry %so it does not affect the rest of the pages.
...
...
...
PS:
1- This can also fix the following warning:
LaTeX Warning: Float too large for page by ...pt on input line ...
2- For more detailed answer look at this.
3- I just found that this is more elaboration on Kevin Chen's answer.
Visual Studio: ContextSwitchDeadlock
The above solution is good in some scenarios but there is another scenario where this happens when you are unit testing and you try to "Debug Selected Tests" from the Test Explorer when you solution is not set to Debug.
In this case you need to change your solution from Release or whatever it is set to to Debug in this case. If this is the problem then changing "ContextSwitchDeadlock" won't really help you.
I missed this myself because the error message was so nasty I didn't check the obvious thing which was the Debug setting!
Adding attribute in jQuery
You can do this with jQuery's .attr
function, which will set attributes. Removing them is done via the .removeAttr
function.
//.attr()
$("element").attr("id", "newId");
$("element").attr("disabled", true);
//.removeAttr()
$("element").removeAttr("id");
$("element").removeAttr("disabled");
Histogram Matplotlib
I know this does not answer your question, but I always end up on this page, when I search for the matplotlib solution to histograms, because the simple histogram_demo
was removed from the matplotlib example gallery page.
Here is a solution, which doesn't require numpy
to be imported. I only import numpy to generate the data x
to be plotted. It relies on the function hist
instead of the function bar
as in the answer by @unutbu.
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
import matplotlib.pyplot as plt
plt.hist(x, bins=50)
plt.savefig('hist.png')
Also check out the matplotlib gallery and the matplotlib examples.
Connection string with relative path to the database file
I had the same issue trying to specify the relative file path for a database connected to a Windows Forms application. I was able to resolve the issue by following the directions for adding a data source to Windows Forms from Microsoft (e.g., for connecting an Access database).
By using this method, Visual Studio will set the relative file paths to your database for you instead of trying to set it manually. If your database is external to your application, it will create a copy of the database and add it to your application in the proper location. Although you can manually alter you connection string in App.config and/or Settings.settings or within one of your scripts, I've found this method to be error prone. Instead, I've found it best to follow the Microsoft instructions, in general.
Assign JavaScript variable to Java Variable in JSP
Java script plays on browser where java code is server side thing so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server
HTML
<input type="hidden" id="hiddenField"/>
make sure this fields lays under <form>
Javascript
document.getElementById("hiddenField").value=yourCalculatedVariable;
on server you would get this as a part of request
How to redirect a URL path in IIS?
If you have loads of re-directs to create, having loads of virtual directories over the places is a nightmare to maintain. You could try using ISAPI redirect an IIS extension. Then all you re-directs are managed in one place.
http://www.isapirewrite.com/docs/
It allows also you to match patterns based on reg ex expressions etc. I've used where I've had to re-direct 100's of pages and its saved a lot of time.
What is the best way to update the entity in JPA
Using executeUpdate()
on the Query
API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.
Consider the following example :
Employee employee= (Employee)entityManager.find(Employee.class , 1);
entityManager
.createQuery("update Employee set name = \'xxxx\' where id=1")
.executeUpdate();
After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee)
to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.
Normally , executeUpdate()
is used in the bulk update process as it is faster due to bypassing the persistent context
The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.
Employee employee= (Employee)entityManager.find(Employee.class ,1);
employee.setName("Updated Name");