Try this:
<table class='borderless'>
.borderless {
border:none;
}
Note: What you were doing before was not working because your css code was targeting a table within your .borderless table (which probably didn't exist)
<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;
$.ajax({
type:"GET",
url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
crossDomain:true,
dataType:'jsonp',
success: function jsondata(data)
{
var parsedata=JSON.parse(JSON.stringify(data));
var logindata=parsedata["Status"];
if("sucess"==logindata)
{
alert("success");
}
else
{
alert("failed");
}
}
});
<script>
You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.
In my case when I use something like result.class.name
I got something like Module1::class_name
. But if we only want class_name
, use
result.class.table_name.singularize
If your URL is working and loads the file correctly, and you've said that adding the correct
<link rel="stylesheet" type="text/css" href="yourlink.css">
code doesn't fix it, then the only other problem is that's it's an error in the actual .css file. And to advise you on that, we'd need to see the file.
What you can do though is write one basic <div>
tag into your HTML, add in a basic CSS rule into your existing file, then see if you can influence this tag with your new CSS rule.
In my opinion, to answer this question, you need to think in terms of project life cycle and version control. In other words, does the parent pom have its own life cycle i.e. can it be released separately of the other modules or not?
If the answer is yes (and this is the case of most projects that have been mentioned in the question or in comments), then the parent pom needs his own module from a VCS and from a Maven point of view and you'll end up with something like this at the VCS level:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
`-- projectA
|-- branches
|-- tags
`-- trunk
|-- module1
| `-- pom.xml
|-- moduleN
| `-- pom.xml
`-- pom.xml
This makes the checkout a bit painful and a common way to deal with that is to use svn:externals
. For example, add a trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
With the following externals definition:
parent-pom http://host/svn/parent-pom/trunk
projectA http://host/svn/projectA/trunk
A checkout of trunks
would then result in the following local structure (pattern #2):
root/
parent-pom/
pom.xml
projectA/
Optionally, you can even add a pom.xml
in the trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
`-- pom.xml
This pom.xml
is a kind of "fake" pom: it is never released, it doesn't contain a real version since this file is never released, it only contains a list of modules. With this file, a checkout would result in this structure (pattern #3):
root/
parent-pom/
pom.xml
projectA/
pom.xml
This "hack" allows to launch of a reactor build from the root after a checkout and make things even more handy. Actually, this is how I like to setup maven projects and a VCS repository for large builds: it just works, it scales well, it gives all the flexibility you may need.
If the answer is no (back to the initial question), then I think you can live with pattern #1 (do the simplest thing that could possibly work).
Now, about the bonus questions:
- Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).
Honestly, I don't know how to not give a general answer here (like "use the level at which you think it makes sense to mutualize things"). And anyway, child poms can always override inherited settings.
- How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?
The setup I use works well, nothing particular to mention.
Actually, I wonder how the maven-release-plugin deals with pattern #1 (especially with the <parent>
section since you can't have SNAPSHOT dependencies at release time). This sounds like a chicken or egg problem but I just can't remember if it works and was too lazy to test it.
I had the same issue on linux, but I couldn't fix it with the accepted answer. I was able to solve it by using cd
to go to the correct folder and then executing:
svn remove --force filename
syn resolve --accept=working filename
svn up
That's all.
Add Regular to syntax and use gfn
:
set gfn= Monospace\ Regular:h13
Merge squash merges a tree (a sequence of commits) into a single commit. That is, it squashes all changes made in n commits into a single commit.
Rebasing is re-basing, that is, choosing a new base (parent commit) for a tree. Maybe the mercurial term for this is more clear: they call it transplant because it's just that: picking a new ground (parent commit, root) for a tree.
When doing an interactive rebase, you're given the option to either squash, pick, edit or skip the commits you are going to rebase.
Hope that was clear!
A static variable inside a function has a lifespan as long as your program runs. It won't be allocated every time your function is called and deallocated when your function returns.
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
Save this code in file myfile.php
and run as php myfile.php type=daily
<?php
$a = $argv;
$b = array();
if (count($a) === 1) exit;
foreach ($a as $key => $arg) {
if ($key > 0) {
list($x,$y) = explode('=', $arg);
$b["$x"] = $y;
}
}
?>
If you add var_dump($b);
before the ?>
tag, you will see that the array $b
contains type => daily
.
Use the 'And' keyword for a logical and. Like this:
If Not ((filename = testFileName) And (fileName <> "")) Then
Use the join
method from the Array type.
a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();
The join
method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.
Below is a fully functional example of what I believe you're trying to do (with a functional snippet).
Based on your question, you seem to be modifying 1 property in state
for all of your elements. That's why when you click on one, all of them are being changed.
In particular, notice that the state tracks an index of which element is active. When MyClickable
is clicked, it tells the Container
its index, Container
updates the state
, and subsequently the isActive
property of the appropriate MyClickable
s.
class Container extends React.Component {_x000D_
state = {_x000D_
activeIndex: null_x000D_
}_x000D_
_x000D_
handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
render() {_x000D_
return <div>_x000D_
<MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
<MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
<MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
</div>_x000D_
}_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
handleClick = () => this.props.onClick(this.props.index)_x000D_
_x000D_
render() {_x000D_
return <button_x000D_
type='button'_x000D_
className={_x000D_
this.props.isActive ? 'active' : 'album'_x000D_
}_x000D_
onClick={ this.handleClick }_x000D_
>_x000D_
<span>{ this.props.name }</span>_x000D_
</button>_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
display: block;_x000D_
margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable
elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.
// New render method for `Container`
render() {
const clickables = [
{ name: "a" },
{ name: "b" },
{ name: "c" },
]
return <div>
{ clickables.map(function(clickable, i) {
return <MyClickable key={ clickable.name }
name={ clickable.name }
index={ i }
isActive={ this.state.activeIndex === i }
onClick={ this.handleClick }
/>
} )
}
</div>
}
Assuming Column A contains the values you want to find single unique instance of, and has a Heading row I used the following formula. If you wanted it to scale with an unpredictable number of rows, you could replace A772 (where my data ended) with =ADDRESS(COUNTA(A:A),1).
=IF(COUNTIF(A5:$A$772,A5)=1,A5,"")
This will display the unique value at the LAST instance of each value in the column and doesn't assume any sorting. It takes advantage of the lack of absolutes to essentially have a decreasing "sliding window" of data to count. When the countif in the reduced window is equal to 1, then that row is the last instance of that value in the column.
It is a good approach to save database scripts into version control with change scripts so that you can upgrade any one database you have. Also you might want to save schemas for different versions so that you can create a full database without having to apply all the change scripts. Handling the scripts should be automated so that you don't have to do manual work.
I think its important to have a separate database for every developer and not use a shared database. That way the developers can create test cases and development phases independently from other developers.
The automating tool should have means for handling database metadata, which tells what databases are in what state of development and which tables contain version controllable data and so on.
dataURItoBlob(dataURI) {_x000D_
const byteString = window.atob(dataURI);_x000D_
const arrayBuffer = new ArrayBuffer(byteString.length);_x000D_
const int8Array = new Uint8Array(arrayBuffer);_x000D_
for (let i = 0; i < byteString.length; i++) {_x000D_
int8Array[i] = byteString.charCodeAt(i);_x000D_
}_x000D_
const blob = new Blob([int8Array], { type: 'application/pdf'});_x000D_
return blob;_x000D_
}_x000D_
_x000D_
// data should be your response data in base64 format_x000D_
_x000D_
const blob = this.dataURItoBlob(data);_x000D_
const url = URL.createObjectURL(blob);_x000D_
_x000D_
// to open the PDF in a new window_x000D_
window.open(url, '_blank');
_x000D_
To avoid a panic on a zero length input, wrap the truncate operation in an if
input, _ := src.ReadString('\n')
var inputFmt string
if len(input) > 0 {
inputFmt = input[:len(input)-1]
}
// Do something with inputFmt
I know I'm late, but this is my version:
from time import perf_counter
board = [
[8, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 6, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 9, 0, 2, 0, 0],
[0, 5, 0, 0, 0, 7, 0, 0, 0],
[0, 0, 0, 0, 4, 5, 7, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 3, 0],
[0, 0, 1, 0, 0, 0, 0, 6, 8],
[0, 0, 8, 5, 0, 0, 0, 1, 0],
[0, 9, 0, 0, 0, 0, 4, 0, 0]
]
def solve(bo):
find = find_empty(bo)
if not find: # if find is None or False
return True
else:
row, col = find
for num in range(1, 10):
if valid(bo, num, (row, col)):
bo[row][col] = num
if solve(bo):
return True
bo[row][col] = 0
return False
def valid(bo, num, pos):
# Check row
for i in range(len(bo[0])):
if bo[pos[0]][i] == num and pos[1] != i:
return False
# Check column
for i in range(len(bo)):
if bo[i][pos[1]] == num and pos[0] != i:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x*3, box_x*3 + 3):
if bo[i][j] == num and (i, j) != pos:
return False
return True
def print_board(bo):
for i in range(len(bo)):
if i % 3 == 0:
if i == 0:
print(" ?-------------------------?")
else:
print(" ?-------------------------?")
for j in range(len(bo[0])):
if j % 3 == 0:
print(" ? ", end=" ")
if j == 8:
print(bo[i][j], " ?")
else:
print(bo[i][j], end=" ")
print(" ?-------------------------?")
def find_empty(bo):
for i in range(len(bo)):
for j in range(len(bo[0])):
if bo[i][j] == 0:
return i, j # row, column
return None
print('\n--------------------------------------\n')
print('× Unsolved Suduku :-')
print_board(board)
print('\n--------------------------------------\n')
t1 = perf_counter()
solve(board)
t2 = perf_counter()
print('× Solved Suduku :-')
print_board(board)
print('\n--------------------------------------\n')
print(f' TIME TAKEN = {round(t2-t1,3)} SECONDS')
print('\n--------------------------------------\n')
It uses backtracking. But is not coded by me, it's Tech With Tim's. That list contains the world hardest sudoku, and by implementing the timing function, the time is:
===========================
[Finished in 2.838 seconds]
===========================
But with a simple sudoku puzzle like:
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]
The result is :
===========================
[Finished in 0.011 seconds]
===========================
Pretty fast I can say.
I solved my problem that way. Thank you for suggestions for improvements. Example in C#.
string dd, mm, aa, trc, data;
dd = nData.Text.Substring(0, 2);
mm = nData.Text.Substring(3, 2);
aa = nData.Text.Substring(6, 4);
trc = "-";
data = aa + trc + mm + trc + dd;
"Select * From bdPedidos Where Data Like '%" + data + "%'";
Try annotating your Configuration Class(es) with the @ComponentScan("com.esri.birthdays")
annotation.
Generally spoken: If you have sub-packages in your project, then you have to scan for your relevant classes on project-root. I guess for your case it'll be "com.esri.birthdays".
You won't need the ComponentScan, if you have no sub-packaging in your project.
The "string to long" (strtol
) function is standard for this ("long" can hold numbers much larger than "int"). This is how to use it:
#include <stdlib.h>
long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)
Since we use the decimal system, base is 10. The endpointer
argument will be set to the "first invalid character", i.e. the first non-digit. If you don't care, set the argument to NULL
instead of passing a pointer, as shown.
If you don't want non-digits to occur, you should make sure it's set to the "null terminator", since a \0
is always the last character of a string in C:
#include <stdlib.h>
char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string
As the man page mentions, you can use errno
to check that no errors occurred (in this case overflows or underflows).
#include <stdlib.h>
#include <errno.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
// Everything went well, print it as 'long decimal'
printf("%ld", arg);
So now we are stuck with this long
, but we often want to work with integers. To convert a long
into an int
, we should first check that the number is within the limited capacity of an int
. To do this, we add a second if-statement, and if it matches, we can just cast it.
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number
printf("%d", arg_int);
To see what happens if you don't do this check, test the code without the INT_MIN
/MAX
if-statement. You'll see that if you pass a number larger than 2147483647 (231), it will overflow and become negative. Or if you pass a number smaller than -2147483648 (-231-1), it will underflow and become positive. Values beyond those limits are too large to fit in an integer.
#include <stdio.h> // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h> // for errno
#include <limits.h> // for INT_MIN and INT_MAX
int main(int argc, char** argv) {
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number plus a newline
printf("Your value was: %d\n", arg_int);
return 0;
}
In Bash, you can test this with:
cc code.c -o example # Compile, output to 'example'
./example $((2**31-1)) # Run it
echo "exit status: $?" # Show the return value, also called 'exit status'
Using 2**31-1
, it should print the number and 0
, because 231-1 is just in range. If you pass 2**31
instead (without -1
), it will not print the number and the exit status will be 1
.
Beyond this, you can implement custom checks: test whether the user passed an argument at all (check argc
), test whether the number is in the range that you want, etc.
sender
refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.
EventArgs
is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.
When you implement your own events, use an EventHandler
or EventHandler<T>
as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).
If you do the following, you will be able to use opencv build from OpenCV_INSTALL_PATH.
cmake_minimum_required(VERSION 2.8)
SET(OpenCV_INSTALL_PATH /home/user/opencv/opencv-2.4.13/release/)
SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")
SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")
LINK_DIRECTORIES(${OpenCV_LIB_DIR})
set(OpenCV_LIBS opencv_core opencv_imgproc opencv_calib3d opencv_video opencv_features2d opencv_ml opencv_highgui opencv_objdetect opencv_contrib opencv_legacy opencv_gpu)
# find_package( OpenCV )
project(edge.cpp)
add_executable(edge edge.cpp)
My EditText was nested several layers inside my ScrollView, which itself isn't the layout's root view. Because getTop() and getBottom() were seeming to report the coordinates within it's containing view, I had it compute the distance from the top of the ScrollView to the top of the EditText by iterating through the parents of the EditText.
// Scroll the view so that the touched editText is near the top of the scroll view
new Thread(new Runnable()
{
@Override
public
void run ()
{
// Make it feel like a two step process
Utils.sleep(333);
// Determine where to set the scroll-to to by measuring the distance from the top of the scroll view
// to the control to focus on by summing the "top" position of each view in the hierarchy.
int yDistanceToControlsView = 0;
View parentView = (View) m_editTextControl.getParent();
while (true)
{
if (parentView.equals(scrollView))
{
break;
}
yDistanceToControlsView += parentView.getTop();
parentView = (View) parentView.getParent();
}
// Compute the final position value for the top and bottom of the control in the scroll view.
final int topInScrollView = yDistanceToControlsView + m_editTextControl.getTop();
final int bottomInScrollView = yDistanceToControlsView + m_editTextControl.getBottom();
// Post the scroll action to happen on the scrollView with the UI thread.
scrollView.post(new Runnable()
{
@Override
public void run()
{
int height =m_editTextControl.getHeight();
scrollView.smoothScrollTo(0, ((topInScrollView + bottomInScrollView) / 2) - height);
m_editTextControl.requestFocus();
}
});
}
}).start();
Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.
Would this be what you are looking for: Contains sample code
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests
I also had the same issue, trying to run a unit test calling code that uses readEntity
. Can't use getEntity
in production code because that just returns a ByteInputStream
and not the content of the body and there is no way I am adding production code that is hit only in unit tests.
My solution was to create a response and then use a Mockito spy to mock out the readEntity
method:
Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);
Note that you can't use the when(mockResponse.readEntity(String.class)
option because that throws the same IllegalStateException
.
Hope this helps!
If you want to avoid using write()
or writelines()
and joining the strings with a newline yourself, you can pass all of your lines to print()
, and the newline delimiter and your file handle as keyword arguments. This snippet assumes your strings do not have trailing newlines.
print(line1, line2, sep="\n", file=f)
You don't need to put a special newline character is needed at the end, because print()
does that for you.
If you have an arbitrary number of lines in a list, you can use list expansion to pass them all to print()
.
lines = ["The Quick Brown Fox", "Lorem Ipsum"]
print(*lines, sep="\n", file=f)
It is OK to use "\n"
as the separator on Windows, because print()
will also automatically convert it to a Windows CRLF newline ("\r\n"
).
For Formatting in mm-dd-yyyy
aa=date.split("-")
date=aa[1]+'-'+aa[2]+'-'+aa[0]
No need for "tricks". Python 3.3 comes with PyLauncher "py.exe", installs it in the path, and registers it as the ".py" extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:
#!python2
print "hello"
Or
#!python3
print("hello")
From the command line:
py -3 hello.py
Or
py -2 hello.py
py hello.py
by itself will choose the latest Python installed, or consult the PY_PYTHON
environment variable, e.g. set PY_PYTHON=3.6
.
Option 1. Use Visual Basic to iterate through each column and format each column as Text.
Use the Text-to-Columns menu, don't change the delimination, and change "General" to "Text"
In VScode, they call this Copy Line Up
and Copy Line Down
From the menu, go to:
File > Preferences > Keyboard Shortcuts
Check already assigned keyboard shortcut for this, or adjust yours.
Sometimes the default assigned shortcut may not work, mostly because of OS.
In my Ubuntu, I adjusted this to: Ctrl+Shift+D
The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:
DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);
In more explanation for n. 'pronouns' m.
's answer,
Public-key crypto is not for encrypting arbitrarily long files. One uses a symmetric cipher (say AES) to do the normal encryption. Each time a new random symmetric key is generated, used, and then encrypted with the RSA cipher (public key). The ciphertext together with the encrypted symmetric key is transferred to the recipient. The recipient decrypts the symmetric key using his private key, and then uses the symmetric key to decrypt the message.
There is the flow of Encryption:
+---------------------+ +--------------------+
| | | |
| generate random key | | the large file |
| (R) | | (F) |
| | | |
+--------+--------+---+ +----------+---------+
| | |
| +------------------+ |
| | |
v v v
+--------+------------+ +--------+--+------------+
| | | |
| encrypt (R) with | | encrypt (F) |
| your RSA public key | | with symmetric key (R) |
| | | |
| ASym(PublicKey, R) | | EF = Sym(F, R) |
| | | |
+----------+----------+ +------------+-----------+
| |
+------------+ +--------------+
| |
v v
+--------------+-+---------------+
| |
| send this files to the peer |
| |
| ASym(PublicKey, R) + EF |
| |
+--------------------------------+
And the flow of Decryption:
+----------------+ +--------------------+
| | | |
| EF = Sym(F, R) | | ASym(PublicKey, R) |
| | | |
+-----+----------+ +---------+----------+
| |
| |
| v
| +-------------------------+-----------------+
| | |
| | restore key (R) |
| | |
| | R <= ASym(PrivateKey, ASym(PublicKey, R)) |
| | |
| +---------------------+---------------------+
| |
v v
+---+-------------------------+---+
| |
| restore the file (F) |
| |
| F <= Sym(Sym(F, R), R) |
| |
+---------------------------------+
Besides, you can use this commands:
# generate random symmetric key
openssl rand -base64 32 > /config/key.bin
# encryption
openssl rsautl -encrypt -pubin -inkey /config/public_key.pem -in /config/key.bin -out /config/key.bin.enc
openssl aes-256-cbc -a -pbkdf2 -salt -in $file_name -out $file_name.enc -k $(cat /config/key.bin)
# now you can send this files: $file_name.enc + /config/key.bin.enc
# decryption
openssl rsautl -decrypt -inkey /config/private_key.pem -in /config/key.bin.enc -out /config/key.bin
openssl aes-256-cbc -d -a -in $file_name.enc -out $file_name -k $(cat /config/key.bin)
If you are looking to average column wise. Try this,
df.drop('Region', axis=1).apply(lambda x: x.mean())
# it drops the Region column
df.drop('Region', axis=1,inplace=True)
var1
and var2
are instance variables. That means that you have to send the instance of ClassA
to ClassB
in order for ClassB to access it, i.e:
class ClassA(object):
def __init__(self):
self.var1 = 1
self.var2 = 2
def methodA(self):
self.var1 = self.var1 + self.var2
return self.var1
class ClassB(ClassA):
def __init__(self, class_a):
self.var1 = class_a.var1
self.var2 = class_a.var2
object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum
On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.
class ClassA(object):
var1 = 0
var2 = 0
def __init__(self):
ClassA.var1 = 1
ClassA.var2 = 2
def methodA(self):
ClassA.var1 = ClassA.var1 + ClassA.var2
return ClassA.var1
class ClassB(ClassA):
def __init__(self):
print ClassA.var1
print ClassA.var2
object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum
Note, however, that class variables are shared among all instances of its class.
You can refresh the Python shell by pressing f5, or go to Run-> Run Module. This way you don't have to change the directory to read something from the file. Python will automatically change the directory. But if you want to work with different files from different directory in the Python Shell, then you can change the directory in sys, as Cameron said earlier.
Interface can be implemented by any classes and what if that value got changed by one of there implementing class then there will be mislead for other implementing classes. Interface is basically a reference to combine two corelated but different entity.so for that reason the declaring variable inside the interface will implicitly be final and also static because interface can not be instantiate.
This is very possible. I mocked up 3 pages which should give you a proof of concept:
.aspx page:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox TextMode="password" ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each s As String In Request.Form.AllKeys
Response.Write(s & ": " & Request.Form(s) & "<br />")
Next
End Sub
Separate HTML page:
<form action="http://localhost/MyTestApp/Default.aspx" method="post">
<input name="TextBox1" type="text" value="" id="TextBox1" />
<input name="TextBox2" type="password" id="TextBox2" />
<input type="submit" name="Button1" value="Button" id="Button1" />
</form>
...and it regurgitates the form values as expected. If this isn't working, as others suggested, use a traffic analysis tool (fiddler, ethereal), because something probably isn't going where you're expecting.
%w(foo bar)
is a shortcut for ["foo", "bar"]
. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.
Add a toolbar to your xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment title"/>
</android.support.v7.widget.Toolbar>
Then inside your onCreateView method in the Fragment:
Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
The other li elements are not siblings of the a element.
$('#menu li a').on('click', function(){
$(this).addClass('current').parent().siblings().children().removeClass('current');
});
In addition to Dan Williams' answer, if you want to add a Startup/Shutdown script, you need to be looking for Windows Settings under Computer Configuration. If you want to add a Logon/Logoff script, you need to be looking for Windows Settings under User Configuration.
So to reiterate what Dan said with this information included,
For Startup/Shutdown:
For Logon/Logoff:
Source: http://technet.microsoft.com/en-us/library/cc739591(WS.10).aspx
You can simply use the NPM package var_dump
npm install var_dump --save-dev
Usage:
const var_dump = require('var_dump')
var variable = {
'data': {
'users': {
'id': 12,
'friends': [{
'id': 1,
'name': 'John Doe'
}]
}
}
}
// print the variable using var_dump
var_dump(variable)
This will print:
object(1) {
["data"] => object(1) {
["users"] => object(2) {
["id"] => number(12)
["friends"] => array(1) {
[0] => object(2) {
["id"] => number(1)
["name"] => string(8) "John Doe"
}
}
}
}
}
Link: https://www.npmjs.com/package/@smartankur4u/vardump
Thank me later!
I found interesting solution to get SSID of currently connected Wifi AP.
You simply need to use iterate WifiManager.getConfiguredNetworks()
and find configuration with specific WifiInfo.getNetworkId()
My example
in Broadcast receiver with action WifiManager.NETWORK_STATE_CHANGED_ACTION
I'm getting current connection state from intent
NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
nwInfo.getState()
If NetworkInfo.getState
is equal to NetworkInfo.State.CONNECTED
then i can get current WifiInfo object
WifiManager wifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();
And after that
public String findSSIDForWifiInfo(WifiManager manager, WifiInfo wifiInfo) {
List<WifiConfiguration> listOfConfigurations = manager.getConfiguredNetworks();
for (int index = 0; index < listOfConfigurations.size(); index++) {
WifiConfiguration configuration = listOfConfigurations.get(index);
if (configuration.networkId == wifiInfo.getNetworkId()) {
return configuration.SSID;
}
}
return null;
}
And very important thing this method doesn't require Location nor Location Permisions
In API29 Google redesigned Wifi API so this solution is outdated for Android 10.
No need for regex. os.path.splitext
is your friend:
os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')
I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
Try This:
var info = document.getElementById("area1").value; // Javascript
var info = $("#area1").val(); // jQuery
stat's "%s" format gives you the actual number of bytes in a file.
find . -type f |
xargs stat --format=%s |
awk '{s+=$1} END {print s}'
Feel free to substitute your favourite method for summing numbers.
Here you can add in VM arguments after endorsed
-Xms64m -Xmx256m
main
is a static method. It cannot refer to balance
, which is an attribute (non-static variable). balance
has meaning only when it is referred through an object reference (such as myAccount.balance
or yourAccount.balance
). But it doesn't have any meaning when it is referred through class (such as Account.balance
(whose balance is that?))
I made some changes to your code so that it compiles.
public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(2500);
account.deposit(3000);
and:
public void withdraw(double withdrawAmount) {
balance -= withdrawAmount;
}
public void deposit(double depositAmount) {
balance += depositAmount;
}
You have to code it yourself I'm afraid. I wrote this, and it may be of some use to you
function printtable(table, indent)
indent = indent or 0;
local keys = {};
for k in pairs(table) do
keys[#keys+1] = k;
table.sort(keys, function(a, b)
local ta, tb = type(a), type(b);
if (ta ~= tb) then
return ta < tb;
else
return a < b;
end
end);
end
print(string.rep(' ', indent)..'{');
indent = indent + 1;
for k, v in pairs(table) do
local key = k;
if (type(key) == 'string') then
if not (string.match(key, '^[A-Za-z_][0-9A-Za-z_]*$')) then
key = "['"..key.."']";
end
elseif (type(key) == 'number') then
key = "["..key.."]";
end
if (type(v) == 'table') then
if (next(v)) then
printf("%s%s =", string.rep(' ', indent), tostring(key));
printtable(v, indent);
else
printf("%s%s = {},", string.rep(' ', indent), tostring(key));
end
elseif (type(v) == 'string') then
printf("%s%s = %s,", string.rep(' ', indent), tostring(key), "'"..v.."'");
else
printf("%s%s = %s,", string.rep(' ', indent), tostring(key), tostring(v));
end
end
indent = indent - 1;
print(string.rep(' ', indent)..'}');
end
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
It sounds like the method really should be static (i.e. it doesn't access any data members and it doesn't need an instance to be invoked on). Since you used the term "static class", I understand that the whole class is probably dedicated to utility-like methods that could be static.
However, Java doesn't allow the implementation of an interface-defined method to be static. So when you (naturally) try to make the method static, you get the "cannot-hide-the-instance-method" error. (The Java Language Specification mentions this in section 9.4: "Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.")
So as long as the method is present in xInterface
, and your class implements xInterface
, you won't be able to make the method static.
If you can't change the interface (or don't want to), there are several things you can do:
xInterface
), and a static method. The instance method will consist of a single line that delegates to the static method.This is a tool to open Java class file binaries, view their internal structure, modify portions of it if required and save the class file back. It also generates readable reports similar to the javap utility. Easy to use Java Swing GUI. The user interface tries to display as much detail as possible and tries to present a structure as close as the actual Java class file structure. At the same time ease of use and class file consistency while doing modifications is also stressed. For example, when a method is deleted, the associated constant pool entry will also be deleted if it is no longer referenced. In built verifier checks changes before saving the file. This tool has been used by people learning Java class file internals. This tool has also been used to do quick modifications in class files when the source code is not available." this is a quote from the website.
Add this into your httpd.conf file
Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore
<?php
$xml = $argv[1];
$dom = new DOMDocument();
// Initial block (must before load xml string)
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
// End initial block
$dom->loadXML($xml);
$out = $dom->saveXML();
print_R($out);
There should be no semicolon here:
class WordGame;
...but there should be one at the end of your class definition:
...
private:
string theWord;
}; // <-- Semicolon should be at the end of your class definition
With Shell.Application you can emulate the way explorer.exe zips files and folders The script is called zipjs.bat:
:: unzip content of a zip to given folder.content of the zip will be not preserved (-keep no).Destination will be not overwritten (-force no)
call zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep no -force no
:: lists content of a zip file and full paths will be printed (-flat yes)
call zipjs.bat list -source C:\myZip.zip\inZipDir -flat yes
:: lists content of a zip file and the content will be list as a tree (-flat no)
call zipjs.bat list -source C:\myZip.zip -flat no
:: prints uncompressed size in bytes
zipjs.bat getSize -source C:\myZip.zip
:: zips content of folder without the folder itself
call zipjs.bat zipDirItems -source C:\myDir\ -destination C:\MyZip.zip -keep yes -force no
:: zips file or a folder (with the folder itslelf)
call zipjs.bat zipItem -source C:\myDir\myFile.txt -destination C:\MyZip.zip -keep yes -force no
:: unzips only part of the zip with given path inside
call zipjs.bat unZipItem -source C:\myDir\myZip.zip\InzipDir\InzipFile -destination C:\OtherDir -keep no -force yes
call zipjs.bat unZipItem -source C:\myDir\myZip.zip\InzipDir -destination C:\OtherDir
:: adds content to a zip file
call zipjs.bat addToZip -source C:\some_file -destination C:\myDir\myZip.zip\InzipDir -keep no
call zipjs.bat addToZip -source C:\some_file -destination C:\myDir\myZip.zip
Makecab is the default compressing tool coming with windows. Though it can use different compression algorithms (including zip) file format is always a .cab
file. With some extensions it can be used on linux machines too.
compressing a file:
makecab file.txt "file.cab"
Compressing an entire folder needs a little bit more work. Here a directory is compressed with cabDir.bat:
call cabDir.bat ./myDir compressedDir.cab
Uncompressing is rather easy with expand
command:
EXPAND cabfile -F:* .
More hackier way is by creating self-extracting executable with extrac32 command:
copy /b "%windir%\system32\extrac32.exe"+"mycab.cab" "expandable.exe"
call expandable.exe
With the build 17063 of windows we have the tar command:
::compress directory
tar -cvf archive.tar c:\my_dir
::extract to dir
tar -xvf archive.tar.gz -C c:\data
.net (and powershell) offers a lot of ways to compress and uncompress files. The most straightforward is with gzip stream. The script is called gzipjs.bat:
::zip
call gzipjs.bat -c my.file my.zip
::unzip
call gzipjs.bat -u my.zip my.file
String a = "ABCD"
using this
a.toLowerCase();
all letters will convert to simple, "abcd"
using this
a.toUpperCase()
all letters will convert to Capital, "ABCD"
this conver first letter to capital:
a.substring(0,1).toUpperCase()
this conver other letter Simple
a.substring(1).toLowerCase();
we can get sum of these two
a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();
result = "Abcd"
Just use dt.Clear()
Also you can set your TableAdapter/DataAdapter to clear before it fills with data.
1 You can use a drawable
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_item1"
android:icon="@drawable/my_item_drawable"
android:title="@string/menu_item1"
android:showAsAction="ifRoom" />
</menu>
2 Create a style for the action bar and use a custom background:
<resources>
<!-- the theme applied to the application or activity -->
<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<!-- other activity and action bar styles here -->
</style>
<!-- style for the action bar backgrounds -->
<style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
<item name="android:background">@drawable/background</item>
<item name="android:backgroundStacked">@drawable/background</item>
<item name="android:backgroundSplit">@drawable/split_background</item>
</style>
</resources>
3 Style again android:actionBarDivider
The android documentation is very usefull for that.
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
I would have done using just single line like
List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(file => new string[] { ".jpg", ".gif", ".png" }
.Contains(Path.GetExtension(file)))
.ToList();
Declaration-wise:
New-style classes inherit from object, or from another new-style class.
class NewStyleClass(object):
pass
class AnotherNewStyleClass(NewStyleClass):
pass
Old-style classes don't.
class OldStyleClass():
pass
Python 3 Note:
Python 3 doesn't support old style classes, so either form noted above results in a new-style class.
You'll need to use fs
for that: http://nodejs.org/api/fs.html
And in particular the fs.rename()
function:
var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
if ( err ) console.log('ERROR: ' + err);
});
Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.
fs.readFile('/path/to/countries.json', function(error, data) {
if (error) {
console.log(error);
return;
}
var obj = JSON.parse(data);
for(var p in obj) {
fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
if ( err ) console.log('ERROR: ' + err);
});
}
});
(This assumes here that your .json
file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)
The getFilesDir()
somehow didn't work.
Using a method, which returns the entire path and filename gave the desired result. Here is the code:
File file = new File(inputHandle.getImgPath(id));
boolean deleted = file.delete();
Try C# 7.0
var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
? dt : DateTime.Parse("1800-01-01");
var marker = [];
for ( var i = 0; i < 6; i++) {
marker[i]='Hello'+i;
}
console.log(marker);
alert(marker);
Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:
"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage
which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh
"thought" that it is run in the regular terminal and since it may be accomplished by simple posix
functions, it is beyond what simple bash
offers.
My preference is:
console.debug("jQuery "+ (jQuery ? $().jquery : "NOT") +" loaded")
Result:
jQuery 1.8.0 loaded
Not PIL, but imageio.imread
might still be interesting:
import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So the pixel at position (x, y)
is
color = tuple(im[y][x])
r, g, b = color
scipy.misc.imread
is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)
I ran across the same issue after installing El Capitan, I tried to install sass and compass into a symfony project, the following command returned the following error:
$ sudo gem install compass
ERROR: Error installing compass: ERROR: Failed to build gem native extension.
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb
checking for ffi.h... /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:434:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
So I then tried to install sass with: $ sudo gem install sass
Got the same error message, after some googling I managed to install sass using the following command:
$ sudo gem install -n /usr/local/bin sass
The above worked for me with installing sass but did not work for installing compass. I read that someone somewhere had opened an instance of xcode then closed it again, then successfully ran the same command after which worked for them. I attempted to open xcode but was prompted with a message saying that the version of xcode installed was not compatible with El Capitan. So I then updated xcode from the app store, re-ran the following command which this time ran successfully:
$ sudo gem install -n /usr/local/bin compass
I was then able to run $ compass init
I now have all my gems working and can proceed to build some lovely sass stuff :)
On MinGW, the _WIN32
define check isn't working. Here's a solution:
#if defined(_WIN32) || defined(__CYGWIN__)
// Windows (x86 or x64)
// ...
#elif defined(__linux__)
// Linux
// ...
#elif defined(__APPLE__) && defined(__MACH__)
// Mac OS
// ...
#elif defined(unix) || defined(__unix__) || defined(__unix)
// Unix like OS
// ...
#else
#error Unknown environment!
#endif
For more information please look: https://sourceforge.net/p/predef/wiki/OperatingSystems/
You also can try this:
Step 1: adb shell Step 2: ip -f inet addr show wlan0
You can not make reference to static variable from non-static method. To understand this , you need to understand the difference between static and non-static.
Static variables are class variables , they belong to class with their only one instance , created at the first only. Non-static variables are initialized every time you create an object of the class.
Now coming to your question, when you use new() operator we will create copy of every non-static filed for every object, but it is not the case for static fields. That's why it gives compile time error if you are referencing a static variable from non-static method.
I wonder why no one mention that $broadcast
accept a parameter where you can pass an Object
that will be received by $on
using a callback function
Example:
// the object to transfert
var myObject = {
status : 10
}
$rootScope.$broadcast('status_updated', myObject);
$scope.$on('status_updated', function(event, obj){
console.log(obj.status); // 10
})
The substitute command can be applied to a visual selection. Make a visual block over the lines that you want to change, and type :, and notice that the command-line is initialized like this: :'<,'>
. This means that the substitute command will operate on the visual selection, like so:
:'<,'>s/$/,/
And this is a substitution that should work for your example, assuming that you really want the comma at the end of each line as you've mentioned. If there are trailing spaces, then you may need to adjust the command accordingly:
:'<,'>s/\s*$/,/
This will replace any amount of whitespace preceding the end of the line with a comma, effectively removing trailing whitespace.
The same commands can operate on a range of lines, e.g. for the next 5 lines: :,+5s/$/,/
, or for the entire buffer: :%s/$/,/
.
Here is the way I love, using LINQ:
public class EnumModel
{
public int Value { get; set; }
public string Name { get; set; }
}
public enum MyEnum
{
Name1=1,
Name2=2,
Name3=3
}
public class Test
{
List<EnumModel> enums = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).Select(c => new EnumModel() { Value = (int)c, Name = c.ToString() }).ToList();
// A list of Names only, does away with the need of EnumModel
List<string> MyNames = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).Select(c => c.ToString()).ToList();
// A list of Values only, does away with the need of EnumModel
List<int> myValues = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).Select(c => (int)c).ToList();
// A dictionnary of <string,int>
Dictionary<string,int> myDic = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).ToDictionary(k => k.ToString(), v => (int)v);
}
Hope it helps
reduce
easily.All you need to use initializer - third argument in the reduce
function.
reduce(
lambda result, _list: result.append(
list(set(_list)&set(c1))
) or result,
c2,
[])
Above code works for both python2 and python3, but you need to import reduce module as from functools import reduce
. Refer below link for details.
You can check the CSS display
property:
if ($('#car').css('display') == 'none') {
alert('Car 2 is hidden');
}
Here is a demo: http://jsfiddle.net/YjP4K/
Another suggestion is to do that way:
string = "abcd\n"
print(string.replace("\n","\\n"))
But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n
service: It runs in the background on your system. For example,
background process: chef making soup
IntentService:- it's consecutive service.. (i.e) when you order many food items at a time to server but the server delivers those items one by one and not deliver them all at once.
In ASPNET Core you do it in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}
where your connection is defined in appsettings.json
{
"ConnectionStrings": {
"BloggingDatabase": "..."
},
}
Example from MS docs
Usually before installing a package one has to know its exact name:
# define a string to search
export to_srch=perl
# get html output of search and pick only the cygwin package names
wget -qO- "https://cygwin.com/cgi-bin2/package-grep.cgi?grep=$to_srch&arch=x86_64" | \
perl -l -ne 'm!(.*?)<\/a>\s+\-(.*?)\:(.*?)<\/li>!;print $2'
# and install
# install multiple packages at once, note the
setup-x86_64.exe -q -s http://cygwin.mirror.constant.com -P "<<chosen_package_name>>"
@RequestParam
annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type.
This annotation indicates that a method parameter should be bound to a web request parameter.
For example Angular request for Spring RequestParam(s) would look like that:
$http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
.success(function (data, status, headers, config) {
...
})
Endpoint with RequestParam:
@RequestMapping(method = RequestMethod.POST, value = "/register")
public Map<String, String> register(Model uiModel,
@RequestParam String username,
@RequestParam String password,
@RequestParam boolean auth,
HttpServletRequest httpServletRequest) {...
@RequestBody
annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters.
This annotation indicates a method parameter should be bound to the body of the web request.
For example Angular request for Spring RequestBody would look like that:
$scope.user = {
username: "foo",
auth: true,
password: "bar"
};
$http.post('http://localhost:7777/scan/l/register', $scope.user).
success(function (data, status, headers, config) {
...
})
Endpoint with RequestBody:
@RequestMapping(method = RequestMethod.POST, produces = "application/json",
value = "/register")
public Map<String, String> register(Model uiModel,
@RequestBody User user,
HttpServletRequest httpServletRequest) {...
Hope this helps.
I just created a CodePen that shows how this can be done pretty easily using ES6.
http://codepen.io/travist/pen/GWRBQV
Basically, here is the class that does this.
let getPropertyValue = function(style, prop) {
let value = style.getPropertyValue(prop);
value = value ? value.replace(/[^0-9.]/g, '') : '0';
return parseFloat(value);
}
let getElementRect = function(element) {
let style = window.getComputedStyle(element, null);
return {
x: getPropertyValue(style, 'left'),
y: getPropertyValue(style, 'top'),
width: getPropertyValue(style, 'width'),
height: getPropertyValue(style, 'height')
}
}
class Resizer {
constructor(wrapper, element, options) {
this.wrapper = wrapper;
this.element = element;
this.options = options;
this.offsetX = 0;
this.offsetY = 0;
this.handle = document.createElement('div');
this.handle.setAttribute('class', 'drag-resize-handlers');
this.handle.setAttribute('data-direction', 'br');
this.wrapper.appendChild(this.handle);
this.wrapper.style.top = this.element.style.top;
this.wrapper.style.left = this.element.style.left;
this.wrapper.style.width = this.element.style.width;
this.wrapper.style.height = this.element.style.height;
this.element.style.position = 'relative';
this.element.style.top = 0;
this.element.style.left = 0;
this.onResize = this.resizeHandler.bind(this);
this.onStop = this.stopResize.bind(this);
this.handle.addEventListener('mousedown', this.initResize.bind(this));
}
initResize(event) {
this.stopResize(event, true);
this.handle.addEventListener('mousemove', this.onResize);
this.handle.addEventListener('mouseup', this.onStop);
}
resizeHandler(event) {
this.offsetX = event.clientX - (this.wrapper.offsetLeft + this.handle.offsetLeft);
this.offsetY = event.clientY - (this.wrapper.offsetTop + this.handle.offsetTop);
let wrapperRect = getElementRect(this.wrapper);
let elementRect = getElementRect(this.element);
this.wrapper.style.width = (wrapperRect.width + this.offsetX) + 'px';
this.wrapper.style.height = (wrapperRect.height + this.offsetY) + 'px';
this.element.style.width = (elementRect.width + this.offsetX) + 'px';
this.element.style.height = (elementRect.height + this.offsetY) + 'px';
}
stopResize(event, nocb) {
this.handle.removeEventListener('mousemove', this.onResize);
this.handle.removeEventListener('mouseup', this.onStop);
}
}
class Dragger {
constructor(wrapper, element, options) {
this.wrapper = wrapper;
this.options = options;
this.element = element;
this.element.draggable = true;
this.element.setAttribute('draggable', true);
this.element.addEventListener('dragstart', this.dragStart.bind(this));
}
dragStart(event) {
let wrapperRect = getElementRect(this.wrapper);
var x = wrapperRect.x - parseFloat(event.clientX);
var y = wrapperRect.y - parseFloat(event.clientY);
event.dataTransfer.setData("text/plain", this.element.id + ',' + x + ',' + y);
}
dragStop(event, prevX, prevY) {
var posX = parseFloat(event.clientX) + prevX;
var posY = parseFloat(event.clientY) + prevY;
this.wrapper.style.left = posX + 'px';
this.wrapper.style.top = posY + 'px';
}
}
class DragResize {
constructor(element, options) {
options = options || {};
this.wrapper = document.createElement('div');
this.wrapper.setAttribute('class', 'tooltip drag-resize');
if (element.parentNode) {
element.parentNode.insertBefore(this.wrapper, element);
}
this.wrapper.appendChild(element);
element.resizer = new Resizer(this.wrapper, element, options);
element.dragger = new Dragger(this.wrapper, element, options);
}
}
document.body.addEventListener('dragover', function (event) {
event.preventDefault();
return false;
});
document.body.addEventListener('drop', function (event) {
event.preventDefault();
var dropData = event.dataTransfer.getData("text/plain").split(',');
var element = document.getElementById(dropData[0]);
element.dragger.dragStop(event, parseFloat(dropData[1]), parseFloat(dropData[2]));
return false;
});
You can either create a new Stage
, add your controls into it or if you require the POPUP as Dialog
box, then you may consider using DialogsFX or ControlsFX(Requires JavaFX8)
For creating a new Stage, you can use the following snippet
@Override
public void start(final Stage primaryStage) {
Button btn = new Button();
btn.setText("Open Dialog");
btn.setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(primaryStage);
VBox dialogVbox = new VBox(20);
dialogVbox.getChildren().add(new Text("This is a Dialog"));
Scene dialogScene = new Scene(dialogVbox, 300, 200);
dialog.setScene(dialogScene);
dialog.show();
}
});
}
If you don't want it to be modal
(block other windows), use:
dialog.initModality(Modality.NONE);
I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta
table. You can find the corresponding products within wp_posts
table.
Use mysqli instead of mysql, and you need to pass the database name or schema:
before:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
after:
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $myDBname);
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
repartition
- it's recommended to use it while increasing the number of partitions, because it involve shuffling of all the data.
coalesce
- it's is recommended to use it while reducing the number of partitions. For example if you have 3 partitions and you want to reduce it to 2, coalesce
will move the 3rd partition data to partition 1 and 2. Partition 1 and 2 will remains in the same container.
On the other hand, repartition
will shuffle data in all the partitions, therefore the network usage between the executors will be high and it will impacts the performance.
coalesce
performs better than repartition
while reducing the number of partitions.
json utf8 encode and decode:
json_encode($data, JSON_UNESCAPED_UNICODE)
json_decode($json, false, 512, JSON_UNESCAPED_UNICODE)
force utf8 might be helpfull too: http://pastebin.com/2XKqYU49
If your table has relationship with other tables using its primary or foriegen key, may be it is impossible to alter your table. so you need to drop and create the table again.
To solve these problems you need to Generate Scripts by right click on the database and in advanced option set type of data to script to scheme and data. after that, using this script with the changing your column to identify and regenerate the table using run its query.
your query will be like here:
USE [Db_YourDbName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Drop TABLE [dbo].[Tbl_TourTable]
CREATE TABLE [dbo].[Tbl_TourTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Family] [nvarchar](150) NULL)
GO
SET IDENTITY_INSERT [dbo].[Tbl_TourTable] ON
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
SET IDENTITY_INSERT [dbo].[Tbl_TourTable] off
Another option: Do not float your right column; just give it a left margin to move it beyond the float. You'll need a hack or two to fix IE6, but that's the basic idea.
Look in your JBoss bin folder for the file run.bat (run.sh on Unix)
look for the line
set JAVA_OPTS
, (or just JAVA_OPTS on Unix) at the end of that line add -Xmx512m. Change the number to the amount of memory you want to allocate to JBoss.
If you are using a custom script to start your jboss instance, you can add the set JAVA_OPTS option there as well.
Update as an alternative to the excellent answer from 2010:
You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. to get and map users and groups
Example:
PS C:\WINDOWS\system32> Get-LocalGroupMember -name users
ObjectClass Name PrincipalSource
----------- ---- ---------------
User DESKTOP-R05QDNL\someUser1 Local
User DESKTOP-R05QDNL\someUser2 MicrosoftAccount
Group NT AUTHORITY\INTERACTIVE Unknown
You could combine that with Get-LocalUser. Alias glu can also be used instead. Aliases exists for the majority of the new cmndlets.
In case some are wondering (I know you didn't ask about this) Adding users could be for example done like so:
$description = "Netshare user"
$userName = "Test User"
$user = "test.user"
$pwd = "pwd123"
New-LocalUser $user -Password (ConvertTo-SecureString $pwd -AsPlainText -Force) -FullName $userName -Description $description
Great answer, "mu is too short". I was seeking the exact same thing, and after reading your post I found a solution that fitted my problem.
I was having two elements of the exact same size and wanted to stack them. As each have same size, what I could do was to make
position: absolute;
top: 0px;
left: 0px;
on only the last element. This way the first element is inserted correctly, "pushing" the parents height, and the second element is placed on top.
Hopes this helps other people trying to stacking 2+ elements with same (unknown) height.
COLUMN()
and ROW()
won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.
For instance, if you want to use this conditional formating on a range begining on cell A1
, you can try:
`COLUMN(A1)` and `ROW(A1)`
Excel will automatically adapt the conditional formating to the current cell.
Write this code from where you want to Intent into next activity.
yourimageView.setDrawingCacheEnabled(true);
Drawable drawable = ((ImageView)view).getDrawable();
Bitmap bitmap = imageView.getDrawingCache();
Intent intent = new Intent(getBaseContext(), NextActivity.class);
intent.putExtra("Image", imageBitmap);
In onCreate Function of NextActivity.class
Bitmap hotel_image;
Intent intent = getIntent();
hotel_image= intent.getParcelableExtra("Image");
Since ConsumerOffsetChecker
is no longer supported, you can use this command to check all messages in topic:
bin/kafka-run-class.sh kafka.admin.ConsumerGroupCommand \
--group my-group \
--bootstrap-server localhost:9092 \
--describe
Where LAG
is the count of messages in topic partition:
Also you can try to use kafkacat. This is an open source project that may help you to read messages from a topic and partition and prints them to stdout. Here is a sample that reads the last 10 messages from sample-kafka-topic
topic, then exit:
kafkacat -b localhost:9092 -t sample-kafka-topic -p 0 -o -10 -e
This is explained in the excellent free eBook ProGit. It assumes you already have a local Git repository and a remote one. To connect them use:
$ git remote
origin
$ git remote add pb git://github.com/paulboone/ticgit.git
$ git remote -v
origin git://github.com/schacon/ticgit.git
pb git://github.com/paulboone/ticgit.git
To push the data from the local repository to GitHub use:
$ git push pb master
If you have not setup a local and/or a remote repository yet, check out the help on GitHub and the previous chapters in the book.
I believe this should be the way this is done...
public void function(String [] array){
....
}
And the calling will be done like...
public void test(){
String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
function(stringArray);
}
I know this already has a marked answer, but I feel I have an improvement to it.
The marked answer is a bit misleading. He set a width to the button, which is not necessary, and set widths are not "responsive". To his defense, he mentions in a comment below it, that the width is not necessary and just an example.
One thing not mentioned here, is that the words may break in the middle of a word and look messed up.
My solution, forces the break to happen between words, a nice word wrap.
.btn-responsive {
white-space: normal !important;
word-wrap: break-word;
}
<a href="#" class="btn btn-primary btn-responsive">Click Here</a>
Not a lot of "slick" going on so far:
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
When you initialize an array with a number, it creates an array with the length
set to that value so that the array appears to contain that many undefined
elements. Though some Array instance methods skip array elements without values, .join()
doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1
in there.
Example usage:
pad(10, 4); // 0010
pad(9, 4); // 0009
pad(123, 4); // 0123
pad(10, 4, '-'); // --10
Oh yes, you can! (sort of, but you shouldn't). each(@array)
in a scalar context gives you the current index of the array.
@a = (a..z);
for (@a) {
print each(@a) . "\t" . $_ . "\n";
}
Here each(@a)
is in a scalar context and returns only the index, not the value at that index. Since we're in a for
loop, we have the value in $_ already. The same mechanism is often used in a while-each loop. Same problem.
The problem comes if you do for(@a)
again. The index isn't back to 0 like you'd expect; it's undef
followed by 0,1,2... one count off. The perldoc of each()
says to avoid this issue. Use a for
loop to track the index.
Basically:
for(my $i=0; $i<=$#a; $i++) {
print "The Element at $i is $a[$i]\n";
}
I'm a fan of the alternate method:
my $index=0;
for (@a) {
print "The Element at $index is $a[$index]\n";
$index++;
}
Use textContent
instead of value
to set the button text.
Typically the value attribute is used to associate a value with the button when it's submitted as form data.
Note that while it's possible to set the button text with innerHTML
, using textContext
should be preferred because it's more performant and it can prevent cross-site scripting attacks as its value is not parsed as HTML.
JS:
var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.textContent = 'test value';
var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);
Produces this in the DOM:
<div id="divWrapper">
<button content="test content" class="btn">test value</button>
</div>
First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local
.
Another simple way is to use @reboot
in your crontab. Read the cron manpage for details.
However, if you want to do things properly, in addition to adding a script to /etc/init.d
you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d
which creates a symlink from some of the /etc/rc*
directories to your script. So, you'd need to do something like:
update-rc.d yourscriptname start 2
However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README
has some details and further pointers.
Extension methods I commonly use to solve this problem:
public static string RemoveAfter(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(0, index);
}
return value;
}
public static string RemoveBefore(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(index + 1);
}
return value;
}
For me it was the "Start In" - I accidentally left in the '.py' at the end of the name of my program. And I forgot to capitalize the name of the folder it was in ('Apps').
You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.
One way around this is to use JSONP. This allows cross-site requests.
In JSON, you are returned:
{a: 5, b: 6}
In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.
callback({a: 5, b: 6})
You need to edit your REST service to accept a parameter called callback
, and then to use the value of that parameter as the function name. You should also change the content-type
to application/javascript
.
For example: http://localhost:8080/restws/json/product/get?callback=process
should output:
process({a: 5, b: 6})
In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=?
to the URL.
$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
function(data) {
alert(data);
});
If you use $.ajax
, it will auto append the ?callback=?
if you tell it to use jsonp
.
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/restws/json/product/get",
success: function(data){
alert(data);
}
});
I have written long back thought to share here
class SingletonDesignPattern {
//just for demo there will be only one instance
private static $instanceCount =0;
//create the private instance variable
private static $myInstance=null;
//make constructor private so no one create object using new Keyword
private function __construct(){}
//no one clone the object
private function __clone(){}
//avoid serialazation
public function __wakeup(){}
//ony one way to create object
public static function getInstance(){
if(self::$myInstance==null){
self::$myInstance=new SingletonDesignPattern();
self::$instanceCount++;
}
return self::$myInstance;
}
public static function getInstanceCount(){
return self::$instanceCount;
}
}
//now lets play with singleton design pattern
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
echo "number of instances: ".SingletonDesignPattern::getInstanceCount();
Take a look at ToolTipster
The Python installation normally associates .py
, .pyw
and .pyc
files with the Python interpreter. So you can run a Python script either by double-clicking it in Explorer or by typing its name in a command-line window (so no need to type python scriptname.py
, just scriptname.py
will do).
If you want to manually change this association, you can edit these keys in the Windows registry:
HKEY_CLASSES_ROOT\Python.File\shell\open\command
HKEY_CLASSES_ROOT\Python.NoConFile\shell\open\command
HKEY_CLASSES_ROOT\Python.CompiledFile\shell\open\command
People have been working on a Python launcher for Windows: a lightweight program associated with .py
and .pyw
files which would look for a "shebang" line (similar to Linux et al) on the first line, and launch Python 2.x or 3.x as required. See "A Python Launcher for Windows" blog post for details.
I would use the toggleClass function in jQuery and define the CSS to the class e.g.
/* start of css */
#user_button.active {
border-bottom-right-radius: 5px;
border-bottom-left-radius: 5px;
-webkit-border-bottom-right-radius: 5px; /* user-agent specific */
-webkit-border-bottom-left-radius: 5px;
-moz-border-radius-bottomright: 5px;
-moz-border-radius-bottomleft: 5px; /* etc... */
}
/* start of js */
$('#user_button').click(function() {
$('#user_options').toggle();
$(this).toggleClass('active');
return false;
})
for (let i = 1; i <= 5; i++) {_x000D_
for (let j = 1; j <= i; j++) {_x000D_
document.write('*');_x000D_
}_x000D_
document.write('<br />');_x000D_
}
_x000D_
Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.
The finally implemented code started like this:
try
{
// Create a new instance of the AesManaged class. This generates a new key and initialization vector (IV).
AesManaged myAes = new AesManaged();
// Override the cipher mode, key and IV
myAes.Mode = CipherMode.ECB;
myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
myAes.Key = CipherKey; // Byte array representing the key
myAes.Padding = PaddingMode.None;
// Create a encryption object to perform the stream transform.
ICryptoTransform encryptor = myAes.CreateEncryptor();
// TODO: perform the encryption / decryption as required...
}
catch (Exception ex)
{
// TODO: Log the error
throw ex;
}
You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.
Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}
Beware of innerHTML
, you sort of lose something when you use it:
theDiv.innerHTML += 'content';
Is equivalent to:
theDiv.innerHTML = theDiv.innerHTML + 'content';
Which will destroy all nodes inside your div
and recreate new ones. All references and listeners to elements inside it will be lost.
If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):
var newNode = document.createElement('div');
newNode.innerHTML = data;
theDiv.appendChild(newNode);
why do I have to pass seconds = uptime to timedelta
Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int
is superfluous as they could also accept floats.
and why does the string casting works so nicely that I get HH:MM:SS ?
It's not the typecasting that formats, is the internal __str__
method of the object. In fact you will achieve the same result if you write:
print datetime.timedelta(seconds=int(uptime))
// The answer that I was looking for when searching
public void Answer()
{
IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
// Assign to empty list so we can use later
IEnumerable<YourClass> second = new List<YourClass>();
if (IwantToUseSecondList)
{
second = this.GetSecondIEnumerableList();
}
IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
}
Visual Studio 2015 Update 3 does not support the C++17 feature you are looking for (emplace_back()
returning a reference).
Support For C++11/14/17 Features (Modern C++)
C++11/14/17 Features In VS 2015 RTM
As of November 17, 2015. This rule has officially changed. Instagram has deprecated the rule against using their API to upload images.
Good luck.
Don't use an array, use an object.
var foo = new Object();
This worked for me:
static void ClearLine(){
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
One that I use often:
Integer.parseInt("1234");
Point is, there are plenty of ways to do this, all equally valid. As to which is most optimum/efficient, you'd have to ask someone else.
I guess things have changed in python 3.4. This worked for me:
print("resp:" + json.dumps(resp.json()))
If you want dynamic email templates for your mail then save the email content in your database tables. This is what i saved as HTML code in database =
<p>Hello.. {{ first_name }} {{ last_name }}. <br> This is an <strong>important</strong> {{ message }}
<br> <b> By Admin.</b>
<p style='color:red'> Good Day </p>
In your views:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
def dynamic_email(request):
application_obj = AppDetails.objects.get(id=1)
subject = 'First Interview Call'
email = request.user.email
to_email = application_obj.email
message = application_obj.message
text_content = 'This is an important message.'
d = {'first_name': application_obj.first_name,'message':message}
htmly = FirstInterviewCall.objects.get(id=1).html_content #this is what i have saved previously in database which i have to send as Email template as mentioned above HTML code
open("partner/templates/first_interview.html", "w").close() # this is the path of my file partner is the app, Here i am clearing the file content. If file not found it will create one on given path.
text_file = open("partner/templates/first_interview.html", "w") # opening my file
text_file.write(htmly) #putting HTML content in file which i saved in DB
text_file.close() #file close
htmly = get_template('first_interview.html')
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, email, [to_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
This will send the dynamic HTML template what you have save in Db.
"java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable"
A had this error too, you need to: File -> import -> Existing Android Code Into Workspace -> Browse -> Android sdks -> extras -> google -> google_play_services -> lib_project -> google_play_services_lib and OK. Check the project and Finish.
The project goes to Package Explorer. Now go to your project (with error) -> properties -> Android and in Library click Add... the google_play_services_lib should be there! add and try again :)
You start recording by q<letter> and you can end it by typing q again.
Recording is a really useful feature of Vim.
It records everything you type. You can then replay it simply by typing @<letter>. Record search, movement, replacement...
One of the best feature of Vim IMHO.
This will work, and if you need where statement you can add it as parameter.
class GenericDAOWithJPA<T, ID extends Serializable> {
.......
public List<T> findAll() {
return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
}
}
#!/bin/bash
variable=`ps -ef | grep "port 10 -" | grep -v "grep port 10 -" | awk '{printf $12}'`
echo $variable
Notice that there's no space after the equal sign.
You can also use $()
which allows nesting and is readable.
Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.
With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:
width: calc(100% - 200px);
Would work as expected with the strict math option enabled.
However, note that Strict Math is applied globally, not only inside calc()
. That means, if you have:
font-size: 12px + 2px;
The math will no longer be processed by Less -- it will output font-size: 12px + 2px
which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:
font-size: (12px + 2px);
Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.
import os
for subdir, dirs, files in os.walk('./'):
for file in files:
do some stuff
print file
You can improve this code with del dirs[:]
which will be like following .
import os
for subdir, dirs, files in os.walk('./'):
del dirs[:]
for file in files:
do some stuff
print file
Or even better if you could point os.walk with current working directory .
import os
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd, topdown=True):
del dirs[:] # remove the sub directories.
for file in files:
do some stuff
print file
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
For rooted users :whats app store all message and contacts in msgstore.db and wa.db files in plain text.These files are available in /data/data/com.whatsapp/databases/. you can open these files using any sqlite browser like SQLite Database Browser.
It is safer to put the version number in the actual filename. This allows multiple versions to exist at once so you can roll out a new version and if any cached HTML pages still exist that are requesting the older version, they will get the version that works with their HTML.
Note, in one of the largest versioned deployments anywhere on the internet, jQuery uses version numbers in the actual filename and it safely allows multiple versions to co-exist without any special server-side logic (each version is just a different file).
This busts the cache once when you deploy new pages and new linked files (which is what you want) and from then on those versions can be effectively cached (which you also want).
Java 6 has a default embedded http server.
By the way, if you plan to have a rest web service, here is a simple example using jersey.
My own experience has been that it's best to stick to one of two kinds of assembly references:
I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.
Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).
This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D
Hope that helps!
I had this issue, jquery URL was valid, everything looked good and validation still worked. After a hard refresh CTL+F5 the error went away in Chrome.
The easy-to-remember, lazy and perhaps imperfect solution:
Directory.GetFiles(dir, "*.dll").Union(Directory.GetFiles(dir, "*.exe"))
You need to move the unique_ptr
:
vec.push_back(std::move(ptr2x));
unique_ptr
guarantees that a single unique_ptr
container has ownership of the held pointer. This means that you can't make copies of a unique_ptr
(because then two unique_ptr
s would have ownership), so you can only move it.
Note, however, that your current use of unique_ptr
is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:
std::unique_ptr<int> ptr(new int(1));
In C++14 we have an even better way to do so:
make_unique<int>(5);
For strings in general, is it always a good idea to use the copy attribute instead of retain?
Yes - in general always use the copy attribute.
This is because your NSString property can be passed an NSString instance or an NSMutableString instance, and therefore we can not really determine if the value being passed is an immutable or mutable object.
Is a "copied" property in any way less efficient than such a "retain-ed" property?
If your property is being passed an NSString instance, the answer is "No" - copying is not less efficient than retain.
(It's not less efficient because the NSString is smart enough to not actually perform a copy.)
If your property is passed an NSMutableString instance then the answer is "Yes" - copying is less efficient than retain.
(It's less efficient because an actual memory allocation and copy must occur, but this is probably a desirable thing.)
Generally speaking a "copied" property has the potential to be less efficient - however through the use of the NSCopying
protocol, it's possible to implement a class which is "just as efficient" to copy as it is to retain. NSString instances are an example of this.
Generally (not just for NSString), when should I use "copy" instead of "retain"?
You should always use copy
when you don't want the internal state of the property changing without warning. Even for immutable objects - properly written immutable objects will handle copy efficiently (see next section regarding immutability and NSCopying
).
There may be performance reasons to retain
objects, but it comes with a maintenance overhead - you must manage the possibility of the internal state changing outside your code. As they say - optimize last.
But, I wrote my class to be immutable - can't I just "retain" it?
No - use copy
. If your class is really immutable then it's best practice to implement the NSCopying
protocol to make your class return itself when copy
is used. If you do this:
copy
.copy
annotation makes your own code more maintainable - the copy
annotation indicates that you really don't need to worry about this object changing state elsewhere.I had the same issue with Axios requests in a Vue-CLI App. On further checking in Network tab of Chrome, I found that the request URL of axios correctly had https
but response 'location' header was http
.
This was caused by nginx
and I fixed it by adding these 2 lines to server config for nginx:
server {
...
add_header Strict-Transport-Security "max-age=31536000" always;
add_header Content-Security-Policy upgrade-insecure-requests;
...
}
Might be irrelevant but my Vue-CLI App was served under a subpath in nginx with config as:
location ^~ /admin {
alias /home/user/apps/app_admin/dist;
index index.html;
try_files $uri $uri/ /index.html;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Host $host;
}
In SQL Server:
SELECT LEN(REPLACE(myColumn, 'N', ''))
FROM ...
Use the .Select()
after grouping:
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyContractID, // required by your view model. should be omited
// in most cases because group by primary key
// makes no sense.
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyContractID = ac.Key.AgencyContractID,
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Amount = ac.Sum(acs => acs.Amount),
Fee = ac.Sum(acs => acs.Fee)
});
On Postgres 10:
SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)
Try This :-
set Read Only False ( Editable TextBox)
document.getElementById("txtID").readOnly=false;
set Read Only true(Not Editable )
var v1=document.getElementById("txtID");
v1.setAttribute("readOnly","true");
This can work on IE and Firefox also.
I assume the original question included how does Express use this environment variable.
Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error
, to avoid leaking implementation details to the world.
Have you tried with the custom format "#,##0.##"
?
You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.
With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.
http://www.dba-oracle.com/t_with_clause.htm
It requires some effort though. Don't be afraid to post a concrete example.
Using simple pseudo table DUAL helps too.
I use application link:AutoHotkey with below code saved in CommentDuplikateSaveClipboard.ahk
file. You can edit/remove shortcuts it is easy.
I have link to this file "Shortcut to CommentDuplikateSaveClipboard.ahk"
in Autostart
in windows.
This script protect your clipboard.
If you are more curious you would add shortcuts to thisable/enable script.
I sometimes use very impressive Multi Clipboard
script to easy handle with many clips
saved on disk and use with CTRL+C,X,V to copy,paste,cut,next,previous,delete this,delete all.
;CommentDuplikateSaveClipboard.ahk
!c:: ; Alt+C === Duplicate Line
^d:: ; Ctrl+D
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{CTRLDOWN}c{CTRLUP}{END}{ENTER}{CTRLDOWN}v{CTRLUP}{HOME}
Clipboard := ClipSaved
ClipSaved =
return
!x:: ; Alt+X === Comment Duplicate Line
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{CTRLDOWN}c{CTRLUP}{LEFT}//{END}{ENTER}{CTRLDOWN}v{CTRLUP}{HOME}
Clipboard := ClipSaved
ClipSaved =
return
!z:: ; Alt+Z === Del uncomment Line
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{UP}{END}{SHIFTUP}{DEL}{HOME}{DEL}{DEL}
Clipboard := ClipSaved
ClipSaved =
return
!d:: ; Alt+D === Delete line
Send, {END}{SHIFTDOWN}{UP}{END}{SHIFTUP}{DEL}
return
!s:: ; Alt+S === Swap lines
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{UP}{END}{SHIFTUP}{CTRLDOWN}x{CTRLUP}{UP}{END}{CTRLDOWN}v{CTRLUP}{HOME}
Clipboard := ClipSaved
ClipSaved =
return
!a:: ; Alt+A === Comment this line, uncomment above
Send, {END}{HOME}//{UP}{HOME}{DEL}{DEL}
return
You are getting AttributeError
because you're calling groups
on None
, which hasn't any methods.
regex.search
returning None
means the regex couldn't find anything matching the pattern from supplied string.
when using regex, it is nice to check whether a match has been made:
Result = re.search(SearchStr, htmlString)
if Result:
print Result.groups()
How about some Regex?
I wrote this for a text a file, but I believe this could work for you
(In case your text file contains line starting exactly with the "matched" ones below - simply adapt your Regex)
private static List<string> fileUploadRequestParser(Stream stream)
{
//-----------------------------111111111111111
//Content-Disposition: form-data; name="file"; filename="data.txt"
//Content-Type: text/plain
//...
//...
//-----------------------------111111111111111
//Content-Disposition: form-data; name="submit"
//Submit
//-----------------------------111111111111111--
List<String> lstLines = new List<string>();
TextReader textReader = new StreamReader(stream);
string sLine = textReader.ReadLine();
Regex regex = new Regex("(^-+)|(^content-)|(^$)|(^submit)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
while (sLine != null)
{
if (!regex.Match(sLine).Success)
{
lstLines.Add(sLine);
}
sLine = textReader.ReadLine();
}
return lstLines;
}
There are multiple ways to calculate the distance based on the coordinates i.e latitude and longitude
from geopy import distance
from math import sin, cos, sqrt, atan2, radians
from sklearn.neighbors import DistanceMetric
import osrm
import numpy as np
lat1, lon1, lat2, lon2, R = 20.9467,72.9520, 21.1702, 72.8311, 6373.0
coordinates_from = [lat1, lon1]
coordinates_to = [lat2, lon2]
dlon = radians(lon2) - radians(lon1)
dlat = radians(lat2) - radians(lat1)
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance_haversine_formula = R * c
print('distance using haversine formula: ', distance_haversine_formula)
dist = DistanceMetric.get_metric('haversine')
X = [[radians(lat1), radians(lon1)], [radians(lat2), radians(lon2)]]
distance_sklearn = R * dist.pairwise(X)
print('distance using sklearn: ', np.array(distance_sklearn).item(1))
osrm_client = osrm.Client(host='http://router.project-osrm.org')
coordinates_osrm = [[lon1, lat1], [lon2, lat2]] # note that order is lon, lat
osrm_response = osrm_client.route(coordinates=coordinates_osrm, overview=osrm.overview.full)
dist_osrm = osrm_response.get('routes')[0].get('distance')/1000 # in km
print('distance using OSRM: ', dist_osrm)
distance_geopy = distance.distance(coordinates_from, coordinates_to).km
print('distance using geopy: ', distance_geopy)
distance_geopy_great_circle = distance.great_circle(coordinates_from, coordinates_to).km
print('distance using geopy great circle: ', distance_geopy_great_circle)
distance using haversine formula: 26.07547017310917
distance using sklearn: 27.847882224769783
distance using OSRM: 33.091699999999996
distance using geopy: 27.7528030550408
distance using geopy great circle: 27.839182219511834
Try this function.
structure of node object:
class Node
{
private:
int data;
Node *next;
public:
Node(int);
~Node();
void setData(int);
int getData();
void setNext(Node*);
Node* getNext();
};
Implementation of the function:
Returning a status value is always a god practice, constants defined here are meant for debugging/logging the application usage.
//constants
static int const SUCCESS = 0;
static int const FAILURE = 1;
static int const NULL_OBJ = 2;
static int const POS_EXCEED = 3;
int addAt(int data, int pos){
Node *tmp = new Node(data);
if (tmp == NULL){
//print for debugging only.
cout << "Object not created. Out of memory maybe" << endl;
return NULL_OBJ;
}
if (pos == 0){
// add at beginning
tmp->setNext(this->head);
this->head = tmp;
return SUCCESS;
}else{
// add element in between or at end
int counter = 1;
Node* currentNode = this->head;
while (counter < pos && currentNode->getNext() != NULL){
currentNode= currentNode->getNext();
counter++;
}
tmp->setNext(currentNode->getNext());
currentNode->setNext(tmp);
return SUCCESS;
}
cout << "Failed due to unknown reason.";
return FAILURE;
}
Assumption here is that, you will call the function after validating the inputs (data and position). Though we can validate the parameters inside the function, it is not a good practice.
Hope this helps.
Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.
def __init__(self, city="Berlin"):
self.city = city
document.write()
doesn't work with XHTML. It's executed after the page has finished loading and does nothing more than write out a string of HTML.
Since the actual in-memory representation of HTML is the DOM, the best way to update a given page is to manipulate the DOM directly.
The way you'd go about doing this would be to programmatically create your nodes and then attach them to an existing place in the DOM. For [purposes of a contrived] example, assuming that I've got a div
element maintaining an ID
attribute of "header," then I could introduce some dynamic text by doing this:
// create my text
var sHeader = document.createTextNode('Hello world!');
// create an element for the text and append it
var spanHeader = document.createElement('span');
spanHeader.appendChild(sHeader);
// grab a reference to the div header
var divHeader = document.getElementById('header');
// append the new element to the header
divHeader.appendChild(spanHeader);
<?php
$timestamp=1486830234542;
echo date('Y-m-d H:i:s', $timestamp/1000);
?>
Add -t
install flag, as on the screenshot below:
Your view names need to be unique even if they are pointing to the same view method.
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods = ['GET'])
app.add_url_rule('/<page>/',
view_func=Main.as_view('page'),
methods = ['GET'])
You can use:
mpstat -P ALL 1
It shows how much each core is busy and it updates automatically each second. The output would be something like this (on a quad-core processor):
10:54:41 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle
10:54:42 PM all 8.20 0.12 0.75 0.00 0.00 0.00 0.00 0.00 90.93
10:54:42 PM 0 24.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 74.00
10:54:42 PM 1 22.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 76.00
10:54:42 PM 2 2.02 1.01 0.00 0.00 0.00 0.00 0.00 0.00 96.97
10:54:42 PM 3 2.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 98.00
10:54:42 PM 4 14.15 0.00 1.89 0.00 0.00 0.00 0.00 0.00 83.96
10:54:42 PM 5 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 99.00
10:54:42 PM 6 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
10:54:42 PM 7 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
This command doesn't answer original question though i.e. it does not show CPU core usage for a specific process.
element instanceof RenderedWebElement
should work.
I had the same problem but what worked for me was removing this from the Connection String:
persist security info=True
You can use java.util.Calendar class to get time in milliseconds. Example:
Calendar cal = Calendar.getInstance();
int milliSec = cal.get(Calendar.MILLISECOND);
// print milliSec
java.util.Date date = cal.getTime();
System.out.println("Output: " + new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss:SSS").format(date));
To accomodate all three points:
The file dialog is a setting in the browser.
For the button/save part assign the following function, boiled down from other answers, to your buttons onclick:
function DownloadCanvasAsImage(){
let downloadLink = document.createElement('a');
downloadLink.setAttribute('download', 'CanvasAsImage.png');
let canvas = document.getElementById('myCanvas');
let dataURL = canvas.toDataURL('image/png');
let url = dataURL.replace(/^data:image\/png/,'data:application/octet-stream');
downloadLink.setAttribute('href', url);
downloadLink.click();
}
Another, somewhat cleaner, approach is using Canvas.toBlob():
function DownloadCanvasAsImage(){
let downloadLink = document.createElement('a');
downloadLink.setAttribute('download', 'CanvasAsImage.png');
let canvas = document.getElementById('myCanvas');
canvas.toBlob(function(blob) {
let url = URL.createObjectURL(blob);
downloadLink.setAttribute('href', url);
downloadLink.click();
});
}
Neither solution is 100% cross browser compatible, so check the client
Try
Date.ParseExact("9/1/2009", "M/d/yyyy", new CultureInfo("en-US"))
The $.getJSON()
method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax()
method.
Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
So just use $.ajax()
and provide all the extra parameters you need.
Add this property to your grid-view : ShowHeaderWhenEmpty="True" it might help just check
Building off the accepted answer by @dennisg, I accomplished this successfully using jQuery.XDomainRequest.js by MoonScript.
The following code worked correctly in Chrome, Firefox and IE10, but failed in IE9. I simply included the script and it now automagically works in IE9. (And probably 8, but I haven't tested it.)
var displayTweets = function () {
$.ajax({
cache: false,
type: 'GET',
crossDomain: true,
url: Site.config().apiRoot + '/Api/GetTwitterFeed',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
for (var tweet in data) {
displayTweet(data[tweet]);
}
}
});
};
In addition to Benjamin's answer - in case if you are using Spring Security, placing the CharacterEncodingFilter in web.xml might not always work. In this case you need to create a custom filter and add it to the filter chain as the first filter. To make sure it's the first filter in the chain, you need to add it before ChannelProcessingFilter, using addFilterBefore
in your WebSecurityConfigurerAdapter:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//add your custom encoding filter as the first filter in the chain
http.addFilterBefore(new EncodingFilter(), ChannelProcessingFilter.class);
http.authorizeRequests()
.and()
// your code here ...
}
}
The ordering of all filters in Spring Security is available here: HttpSecurityBuilder - addFilter()
Your custom UTF-8 encoding filter can look like following:
public class EncodingFilter extends GenericFilterBean {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
}
Don't forget to add in your jsp files:
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
And remove the CharacterEncodingFilter from web.xml if it's there.
Most of the answers for this question can not helped me in 2020.
This notification from download site of Oracle may be the reason:
Important Oracle JDK License Update
The Oracle JDK License has changed for releases starting April 16, 2019.
I try to google a little bit and those tutorials below helped me a lot.
Remove completely the previous version of JVM installed on your PC.
sudo update-alternatives --remove-all java
sudo update-alternatives --remove-all javac
sudo update-alternatives --remove-all javaws
# /usr/lib/jvm/jdk1.7.0 is the path you installed the previous version of JVM on your PC
sudo rm -rf /usr/lib/jvm/jdk1.7.0
Check to see whether java is uninstalled or not
java -version
1.8.0_251
. Pay attention to this value, you may need it to edit commands in this answer when Java 8 is upgraded to another version.cd /usr/lib/jvm
sudo tar xzf ~/Downloads/jdk-8u251-linux-x64.tar.gz
sudo gedit /etc/environment
:/usr/lib/jvm/jdk1.8.0_251/bin:/usr/lib/jvm/jdk1.8.0_251/jre/bin
J2SDKDIR="/usr/lib/jvm/jdk1.8.0_251"
J2REDIR="/usr/lib/jvm/jdk1.8.0_251/jre"
JAVA_HOME="/usr/lib/jvm/jdk1.8.0_251"
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_251/bin/java" 0
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_251/bin/javac" 0
sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_251/bin/java
sudo update-alternatives --set javac /usr/lib/jvm/jdk1.8.0_251/bin/javac
update-alternatives --list java
update-alternatives --list javac
I think the error because the elements are undefined ,so you need to add window.onload
event which this event will defined your elements when the window is loaded.
window.addEventListener('load',Loaded,false);
function Loaded(){
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
Try This Code:Successfully
Written on click Button.
ScriptManager.RegisterStartupScript(this, GetType(),"alertMessage", "alert('Record Inserted Successfully');", true);
It can be used for a simple table, for example in an insert-only audit table, where there is no update to existing row, and no fk to other table. The insert is a simple insert, which has no or little chance of rollback.
// prepare json data
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData
// create post request
let url = NSURL(string: "http://httpbin.org/post")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData as Data
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
return
}
do {
let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
print("Result",result!)
} catch {
print("Error -> \(error)")
}
}
task.resume()
This download fixed my VB6 EXE and Access 2016 (using ACEDAO.DLL) run-time error 429. Took me 2 long days to get it resolved because there are so many causes of 429.
http://www.microsoft.com/en-ca/download/details.aspx?id=13255
QUOTE from link: "This download will install a set of components that can be used to facilitate transfer of data between 2010 Microsoft Office System files and non-Microsoft Office applications"
The overflow property can be used to clear floats with no additional mark-up:
.container { overflow: hidden; }
This works for all browsers except IE6, where all you need to do is enable hasLayout (zoom being my preferred method):
.container { zoom: 1; }
I would skip all of the above answers and start using the react-dimensions
Higher Order Component.
https://github.com/digidem/react-dimensions
Just add a simple import
and a function call, and you can access this.props.containerWidth
and this.props.containerHeight
in your component.
// Example using ES6 syntax
import React from 'react'
import Dimensions from 'react-dimensions'
class MyComponent extends React.Component {
render() (
<div
containerWidth={this.props.containerWidth}
containerHeight={this.props.containerHeight}
>
</div>
)
}
export default Dimensions()(MyComponent) // Enhanced component
after API >=21 there is inbuild method provided by TextView called setLetterSpacing
check this for more
You can add
from functools import reduce
before you use the reduce.
I was having the same problem. I ended up going into the subdirectory that was "not staged for commit" and adding, committing and pushing from there. after that, went up one level to master directory and was able to push correctly.
public static void main(String[] args) {
Season.add("Frühling");
Season.add("Sommer");
Season.add("Herbst");
Season.add("WINTER");
for (String s : Season) {
if(!s.equals("Sommer")) {
System.out.println(s);
continue;
}
Season.remove("Frühling");
}
}
If subtracting microtimes gives you negative results, try using the function with the argument true
(microtime(true)
). With true
, the function returns a float instead of a string (as it does if it is called without arguments).
The portable way to do this is:
sed -e 's/[ \t][ \t]*/\
/g'
That's an actual newline between the backslash and the slash-g. Many sed implementations don't know about \n
, so you need a literal newline. The backslash before the newline prevents sed from getting upset about the newline. (in sed scripts the commands are normally terminated by newlines)
With GNU sed you can use \n
in the substitution, and \s in the regex:
sed -e 's/\s\s*/\n/g'
GNU sed also supports "extended" regular expressions (that's egrep style, not perl-style) if you give it the -r flag, so then you can use +
:
sed -r -e 's/\s+/\n/g'
If this is for Linux only, you can probably go with the GNU command, but if you want this to work on systems with a non-GNU sed (eg: BSD, Mac OS-X), you might want to go with the more portable option.
Without ping
#!/bin/bash
wget -q --spider http://google.com
if [ $? -eq 0 ]; then
echo "Online"
else
echo "Offline"
fi
-q : Silence mode
--spider : don't get, just check page availability
$? : shell return code
0 : shell "All OK" code
Without wget
#!/bin/bash
echo -e "GET http://google.com HTTP/1.0\n\n" | nc google.com 80 > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Online"
else
echo "Offline"
fi
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_user_connections
maximum range: 4,294,967,295 (e.g. 2**32 - 1)
You'd probably run out of memory, file handles, and network sockets, on your server long before you got anywhere close to that limit.
I too have tried invalidate(), invalidateViews(), notifyDataSetChanged(). They all might work in some particular contexts but it did not do the job in my case.
In my case, I had to add some new rows to the list and it just does not work. Creating a new adapter solved the issue.
While debugging, I realized that the data was there but just not rendered. If invalidate() or invalidateViews() does not render (which it is supposed to), I don't know what would.
Creating a new Adapter object to refresh modified data does not seem to be a bad idea. It definitely works. The only downside could be the time consumed in allocating new memory for your adapter but that should be OK assuming the Android system is smart enough and takes care of that to keep it efficient.
If you take this out of the equation, the flow is almost same as to calling notifyDataSetChanged. In the sense, the same set of adapter functions are called in either case.
So we are not losing much but gaining a lot.
I have a set of scripting functions that I use extensively on my Red Hat system. They use the system functions from /etc/init.d/functions
to print green [ OK ]
and red [FAILED]
status indicators.
You can optionally set the $LOG_STEPS
variable to a log file name if you want to log which commands fail.
step "Installing XFS filesystem tools:"
try rpm -i xfsprogs-*.rpm
next
step "Configuring udev:"
try cp *.rules /etc/udev/rules.d
try udevtrigger
next
step "Adding rc.postsysinit hook:"
try cp rc.postsysinit /etc/rc.d/
try ln -s rc.d/rc.postsysinit /etc/rc.postsysinit
try echo $'\nexec /etc/rc.postsysinit' >> /etc/rc.sysinit
next
Installing XFS filesystem tools: [ OK ]
Configuring udev: [FAILED]
Adding rc.postsysinit hook: [ OK ]
#!/bin/bash
. /etc/init.d/functions
# Use step(), try(), and next() to perform a series of commands and print
# [ OK ] or [FAILED] at the end. The step as a whole fails if any individual
# command fails.
#
# Example:
# step "Remounting / and /boot as read-write:"
# try mount -o remount,rw /
# try mount -o remount,rw /boot
# next
step() {
echo -n "$@"
STEP_OK=0
[[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$
}
try() {
# Check for `-b' argument to run command in the background.
local BG=
[[ $1 == -b ]] && { BG=1; shift; }
[[ $1 == -- ]] && { shift; }
# Run the command.
if [[ -z $BG ]]; then
"$@"
else
"$@" &
fi
# Check if command failed and update $STEP_OK if so.
local EXIT_CODE=$?
if [[ $EXIT_CODE -ne 0 ]]; then
STEP_OK=$EXIT_CODE
[[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$
if [[ -n $LOG_STEPS ]]; then
local FILE=$(readlink -m "${BASH_SOURCE[1]}")
local LINE=${BASH_LINENO[0]}
echo "$FILE: line $LINE: Command \`$*' failed with exit code $EXIT_CODE." >> "$LOG_STEPS"
fi
fi
return $EXIT_CODE
}
next() {
[[ -f /tmp/step.$$ ]] && { STEP_OK=$(< /tmp/step.$$); rm -f /tmp/step.$$; }
[[ $STEP_OK -eq 0 ]] && echo_success || echo_failure
echo
return $STEP_OK
}
Here's a complete (yet simple) example of redirecting after X seconds, while updating a counter div:
<html>_x000D_
<body>_x000D_
<div id="counter">5</div>_x000D_
<script>_x000D_
setInterval(function() {_x000D_
var div = document.querySelector("#counter");_x000D_
var count = div.textContent * 1 - 1;_x000D_
div.textContent = count;_x000D_
if (count <= 0) {_x000D_
window.location.replace("https://example.com");_x000D_
}_x000D_
}, 1000);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
The initial content of the counter
div is the number of seconds to wait.
My issue was that I was using 'React.PureComponent' when I should have been using 'React.Component'.
If you add:
jquery.form.min.js
You can simply do this:
<script>
$('#myform').ajaxForm(function(response) {
alert(response);
});
// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>
You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.
When you create a folder with N entries, you create a list of N items at file-system level. This list is a system-wide shared data structure. If you then start modifying this list continuously by adding/removing entries, I expect at least some lock contention over shared data. This contention - theoretically - can negatively affect performance.
For read-only scenarios I can't imagine any reason for performance degradation of directories with large number of entries.
Easy.
open xampp control panel -> Config -> my.ini edit with notepad. now add this below [mysqld]
skip-grant-tables
Save. Start apache and mysql.
I hope help you