You can specify addresses as "R1C2" instead of "B2". Under File -> Options -> Formuals -> Workingg with Formulas there is a toggle R1C1 reference style. which can be set, as illustrated below.
I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)
But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver. Just build your JDBC URL like this:
jdbc:sqlserver://localhost;integratedSecurity=true;
And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver)
MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL
I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this
$("#panel").toggle().toggle();
_x000D_
it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.
Is key-value pair available in Typescript?
If you think of a C# KeyValuePair<string, string>: No, but you can easily define one yourself:
interface KeyValuePair {
key: string;
value: string;
}
Usage:
let foo: KeyValuePair = { key: "k", value: "val" };
See adeneo's answer, but to make this work in Excel in all countries you should add "SEP=," to the first line of the file. This will set the standard separator in Excel and will not show up in the actual document
var csvString = "SEP=, \n" + csvRows.join("\r\n");
If you are OK with using the numpy package, then you can do something like the following:
import numpy as np
lines = np.genfromtxt("coors.csv", delimiter=",", dtype=None)
my_dict = dict()
for i in range(len(lines)):
my_dict[lines[i][0]] = lines[i][1]
This is older but placing this here for my reference too. boto3.resource is just implementing the default Session, you can pass through boto3.resource session details.
Help on function resource in module boto3:
resource(*args, **kwargs)
Create a resource service client by name using the default session.
See :py:meth:`boto3.session.Session.resource`.
https://github.com/boto/boto3/blob/86392b5ca26da57ce6a776365a52d3cab8487d60/boto3/session.py#L265
you can see that it just takes the same arguments as Boto3.Session
import boto3
S3 = boto3.resource('s3', region_name='us-west-2', aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY)
S3.Object( bucket_name, key_name ).delete()
In Bash and zsh you can do this with Brace Expansion. This simply expands a list of items in braces. For example:
# echo {vanilla,chocolate,strawberry}-ice-cream
vanilla-ice-cream chocolate-ice-cream strawberry-ice-cream
So you can do your rename as follows:
mv {,new.}original.filename
as this expands to:
mv original.filename new.original.filename
Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.
public class MyViewModel
{
public string YourString { get; set; }
}
In the view
@model MyViewModel
@Html.Label(model => model.YourString)
In the controller
public ActionResult Index()
{
myViewModel = new MyViewModel();
myViewModel.YourString = "However you are setting this."
return View(myViewModel)
}
You can bind resize
using .resize()
and run your code when the browser is resized. You need to also add an else
condition to your if
statement so that your css values toggle the old and the new, rather than just setting the new.
If using GitHub on Windows:
This is why, before you start making changes of your own, that you should create a branch for each set of changes you plan to put into a pull request. That way, once you make the pull request, you can then make another branch and continue work on some other task/feature/bugfix without affecting the previous pull request.
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
Both styles are used within the Go's standard libraries.
if len(s) > 0 { ... }
can be found in the strconv
package: http://golang.org/src/pkg/strconv/atoi.go
if s != "" { ... }
can be found in the encoding/json
package: http://golang.org/src/pkg/encoding/json/encode.go
Both are idiomatic and are clear enough. It is more a matter of personal taste and about clarity.
Russ Cox writes in a golang-nuts thread:
The one that makes the code clear.
If I'm about to look at element x I typically write
len(s) > x, even for x == 0, but if I care about
"is it this specific string" I tend to write s == "".It's reasonable to assume that a mature compiler will compile
len(s) == 0 and s == "" into the same, efficient code.
...Make the code clear.
As pointed out in Timmmm's answer, the Go compiler does generate identical code in both cases.
Left Click on chart. «PivotTable Field List» will appear on right. On the right down quarter of PivotTable Field List (S Values), you see the names of the legends. Left Click on the legend name. Left Click on the «Value field settings». At the top there is «Source Name». You can’t change it. Below there is «Custom Name». Change the Custom Name as you wish. Now the legend name on the chart has the new name you gave.
You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters.
For your case:
... LIKE '%[_]d'
It should be as simple as...
LOAD DATA INFILE '/tmp/mydata.txt' INTO TABLE PerformanceReport;
By default LOAD DATA INFILE
uses tab delimited, one row per line, so should take it in just fine.
For the main logfile/appender, set up a .Threshold = INFO
to limit what is actually logged in the appender to INFO and above, regardless of whether or not the loggers have DEBUG, TRACE, etc, enabled.
As for catching DEBUG and nothing above that... you'd probably have to write a custom appender.
However I'd recommend not doing this, as it sounds like it would make troubleshooting and analysis pretty hard:
Here's the working code. Works in desktop and mobile browsers. hope it helps. thanks for everyone responding.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Layout</title>
<style type="text/css">
body, html
{
margin: 0; padding: 0; height: 100%; overflow: hidden;
}
#content
{
position:absolute; left: 0; right: 0; bottom: 0; top: 0px;
}
</style>
</head>
<body>
<div id="content">
<iframe width="100%" height="100%" frameborder="0" src="http://cnn.com" />
</div>
</body>
</html>
I think that optional arguments (specified with --
) are initialized to None
if they are not supplied. So you can test with is not None
. Try the example below:
import argparse as ap
def main():
parser = ap.ArgumentParser(description="My Script")
parser.add_argument("--myArg")
args, leftovers = parser.parse_known_args()
if args.myArg is not None:
print "myArg has been set (value is %s)" % args.myArg
A string to char array is as simple as
String str = "someString";
char[] charArray = str.toCharArray();
Can you explain a little more on what you are trying to do?
* Update *
if I am understanding your new comment, you can use a byte array and example is provided.
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
With the following output
0x65 0x10 0xf3 0x29
OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.
Data Used
This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.
Below is the implementation.
import numpy as np import cv2 # Read the image image = cv2.imread( 'digits.png' ) # gray scale conversion gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # We will divide the image # into 5000 small dimensions # of size 20x20 divisions = list (np.hsplit(i, 100 ) for i in np.vsplit(gray_img, 50 )) # Convert into Numpy array # of size (50,100,20,20) NP_array = np.array(divisions) # Preparing train_data # and test_data. # Size will be (2500,20x20) train_data = NP_array[:,: 50 ].reshape( - 1 , 400 ).astype(np.float32) # Size will be (2500,20x20) test_data = NP_array[:, 50 : 100 ].reshape( - 1 , 400 ).astype(np.float32) # Create 10 different labels # for each type of digit k = np.arange( 10 ) train_labels = np.repeat(k, 250 )[:,np.newaxis] test_labels = np.repeat(k, 250 )[:,np.newaxis] # Initiate kNN classifier knn = cv2.ml.KNearest_create() # perform training of data knn.train(train_data, cv2.ml.ROW_SAMPLE, train_labels) # obtain the output from the # classifier by specifying the # number of neighbors. ret, output ,neighbours, distance = knn.findNearest(test_data, k = 3 ) # Check the performance and # accuracy of the classifier. # Compare the output with test_labels # to find out how many are wrong. matched = output = = test_labels correct_OP = np.count_nonzero(matched) #Calculate the accuracy. accuracy = (correct_OP * 100.0 ) / (output.size) # Display accuracy. print (accuracy) |
Output
91.64
Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).
1) My first question was about letter_recognition.data
file that comes with OpenCV samples. I wanted to know what is inside that file.
It contains a letter, along with 16 features of that letter.
And this SOF
helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers
.
(Although I didn't understand some of the features at the end)
2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.
So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)
I took the below image for my training data:
(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).
To prepare the data for training, I made a small code in OpenCV. It does the following things:
key press manually
. This time we press the digit key ourselves corresponding to the letter in the box..txt
files.At the end of the manual classification of digits, all the digits in the training data (train.png
) are labeled manually by ourselves, image will look like below:
Below is the code I used for the above purpose (of course, not so clean):
import sys
import numpy as np
import cv2
im = cv2.imread('pitrain.png')
im3 = im.copy()
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
################# Now finding Contours ###################
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
samples = np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
cv2.imshow('norm',im)
key = cv2.waitKey(0)
if key == 27: # (escape to quit)
sys.exit()
elif key in keys:
responses.append(int(chr(key)))
sample = roismall.reshape((1,100))
samples = np.append(samples,sample,0)
responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"
np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)
Now we enter in to training and testing part.
For the testing part, I used the below image, which has the same type of letters I used for the training phase.
For training we do as follows:
.txt
files we already saved earlierFor testing purposes, we do as follows:
I included last two steps (training and testing) in single code below:
import cv2
import numpy as np
####### training part ###############
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))
model = cv2.KNearest()
model.train(samples,responses)
############################# testing part #########################
im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
roismall = roismall.reshape((1,100))
roismall = np.float32(roismall)
retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
string = str(int((results[0][0])))
cv2.putText(out,string,(x,y+h),0,1,(0,255,0))
cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)
And it worked, below is the result I got:
Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.
But anyway, this is a good start to go for beginners (I hope so).
The best and simplest way to read a line from a console is using the getchar() function, whereby you will store one character at a time in an array.
{
char message[N]; /* character array for the message, you can always change the character length */
int i = 0; /* loop counter */
printf( "Enter a message: " );
message[i] = getchar(); /* get the first character */
while( message[i] != '\n' ){
message[++i] = getchar(); /* gets the next character */
}
printf( "Entered message is:" );
for( i = 0; i < N; i++ )
printf( "%c", message[i] );
return ( 0 );
}
One way is to use the Grid's select()
and dataItem()
methods.
In single selection case, select()
will return a single row which can be passed to dataItem()
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
// selectedItem has EntityVersionId and the rest of your model
For multiple row selection select()
will return an array of rows. You can then iterate through the array and the individual rows can be passed into the grid's dataItem()
.
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function(index, row) {
var selectedItem = entityGrid.dataItem(row);
// selectedItem has EntityVersionId and the rest of your model
});
How about this in your .htaccess:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
It is possible to get a context from within a Fragment
Just do
public class YourFragment extends Fragment {
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.yout_fragment_layout, container, false);
// get context here
Context context = getContext();
// do as you please with the context
// if you decide to go with second option
SomeViewModel someViewModel = ViewModelProviders.of(this).get(SomeViewModel.class);
Context context = homeViewModel.getContext();
// do as you please with the context
return root;
}
}
You may also attached an AndroidViewModel
in the onCreateView
method that implements a method that returns the application context
public class SomeViewModel extends AndroidViewModel {
private MutableLiveData<ArrayList<String>> someMutableData;
Context context;
public SomeViewModel(Application application) {
super(application);
context = getApplication().getApplicationContext();
someMutableData = new MutableLiveData<>();
.
.
}
public Context getContext() {
return context
}
}
I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.
but I should add more infomation when you use pycharm and enable auto import
.
when you format the code, the code from mpl_toolkits.mplot3d import Axes3D
will auto remove by pycharm.
so, my solution is
from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
and it works well!
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
To find a hostname in your local network by IP address you can use:
nmblookup -A <ip>
To find a hostname on the internet you could use the host
program:
host <ip>
Or you can install nbtscan
by running:
sudo apt-get install nbtscan
And use:
nbtscan <ip>
Update 2018-05-13
You can query a name server with nslookup
. It works both ways!
nslookup <IP>
nslookup <hostname>
A related issue: I came to this page after searching for "how to know what are deleted branches".
While deleting many old branches, felt I mistakenly deleted one of the newer branches, but didn't know the name to recover it.
To know what branches are deleted recently, do the below:
If you go to your Git URL, which will look something like this:
https://your-website-name/orgs/your-org-name/dashboard
Then you can see the feed, of what is deleted, by whom, in the recent past.
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
Structure your HTML similar to this:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
In case someone needs a CSS background with different color repeating horizontal stripes, here is how I managed to achieve this:
body {_x000D_
font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;_x000D_
font-size: 13px;_x000D_
}_x000D_
_x000D_
.css-stripes {_x000D_
margin: 0 auto;_x000D_
width: 200px;_x000D_
padding: 100px;_x000D_
text-align: center;_x000D_
/* For browsers that do not support gradients */_x000D_
background-color: #F691FF;_x000D_
/* Safari 5.1 to 6.0 */_x000D_
background: -webkit-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Opera 11.1 to 12.0 */_x000D_
background: -o-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Firefox 3.6 to 15 */_x000D_
background: -moz-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Standard syntax */_x000D_
background-image: repeating-linear-gradient(to top, #F691FF, #EC72A8);_x000D_
background-size: 1px 2px;_x000D_
}
_x000D_
<div class="css-stripes">Hello World!</div>
_x000D_
mysql_real_escape_string() or str_replace() function will help you to solve your problem.
Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,
function get_key($array, $index){
$idx=0;
while($idx!=$index && next($array)) $idx++;
if($idx==$index) return key($array);
else return '';
}
Here is my take on it, seems like most peoples solutions don't check if the item exists and it removes random values if it does not exist.
First check if the element exists by looking for it's index. If it does exist, remove it by its index using the splice method
elementPosition = array.indexOf(value);
if(elementPosition != -1) {
array.splice(elementPosition, 1);
}
This is what I used to close all open forms (except for the main form)
private void CloseOpenForms()
{
// Close all open forms - except for the main form. (This is usually OpenForms[0].
// Closing a form decrmements the OpenForms count
while (Application.OpenForms.Count > 1)
{
Application.OpenForms[Application.OpenForms.Count-1].Close();
}
}
The jersey-container-servlet
actually uses the jersey-container-servlet-core
dependency. But if you use maven, that does not really matter. If you just define the jersey-container-servlet
usage, it will automatically download the dependency as well.
But for those who add jar files to their project manually (i.e. without maven) It is important to know that you actually need both jar files. The org.glassfish.jersey.servlet.ServletContainer
class is actually part of the core dependency.
Thread th = new Thread(function1);
th.Start();
th.Abort();
void function1(){
//code here
}
Don't reinvent the wheel.
ls -m
It does exactly that.
In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".
There are situations where it matters.
If you pass AF_INET to socket()
in Cygwin, your socket may or may not be randomly reset. Passing PF_INET ensures that the connection works right.
Cygwin is self-admittedly a huge mess for socket programming, but it is a real world case where AF_INET and PF_INET are not identical.
If you want to alter the original objects, then a simple Array#forEach
will do:
rockets.forEach(function(rocket) {
rocket.launches += 10;
});
If you want to keep the original objects unaltered, then use Array#map
and copy the objects using Object#assign
:
var newRockets = rockets.forEach(function(rocket) {
var newRocket = Object.assign({}, rocket);
newRocket.launches += 10;
return newRocket;
});
As to the actual code
get your CloudFront distribution id
aws cloudfront list-distributions
Invalidate all files in the distribution, so CloudFront fetches fresh ones
aws cloudfront create-invalidation --distribution-id=S11A16G5KZMEQD --paths /
My actual full release script is
#!/usr/bin/env bash
BUCKET=mysite.com
SOURCE_DIR=dist/
export AWS_ACCESS_KEY_ID=xxxxxxxxxxx
export AWS_SECRET_ACCESS_KEY=xxxxxxxxx
export AWS_DEFAULT_REGION=eu-west-1
echo "Building production"
if npm run build:prod ; then
echo "Build Successful"
else
echo "exiting.."
exit 1
fi
echo "Removing all files on bucket"
aws s3 rm s3://${BUCKET} --recursive
echo "Attempting to upload site .."
echo "Command: aws s3 sync $SOURCE_DIR s3://$BUCKET/"
aws s3 sync ${SOURCE_DIR} s3://${BUCKET}/
echo "S3 Upload complete"
echo "Invalidating cloudfrond distribution to get fresh cache"
aws cloudfront create-invalidation --distribution-id=S11A16G5KZMEQD --paths / --profile=myawsprofile
echo "Deployment complete"
http://docs.aws.amazon.com/cli/latest/reference/cloudfront/get-invalidation.html
http://docs.aws.amazon.com/cli/latest/reference/cloudfront/create-invalidation.html
You need to take out a float: left; property... because when you use float the parent div do not grub the height of it's children... If you want the parent dive to get the children height you need to give to the parent div a css property overflow:hidden; But to solve your problem you can use display: table-cell; instead of float... it will automatically scale the div height to its parent height...
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
Same as accepted answer, But note that it works even with .crt
file and not just .pem
file, just in case if you are not able to find .pem
file location.
openssl x509 -enddate -noout -in e71c8ea7fa97ad6c.crt
Result:
notAfter=Mar 29 06:15:00 2020 GMT
Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.
In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.
The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.
To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.
Why?
It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.
See the following information in MSDN about the GAC changes in 4.0.
For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application
The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. As a result of this, there was no need in the previous two framework releases to split the GAC. The problem of breaking older (in this case, .NET 2.0) applications resurfaces in Net Framework 4.0 at which point CLR 4.0 released. Hence, to avoid interference issues between CLR 2.0 and CLR 4.0, the GAC is now split into private GACs for each runtime.
As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.
This applies for "Intellij Idea- 2020.1.2" on window
Navigate to "IntelliJ IDEA->File->Settings->Editor->Code Style->java".
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
The closest thing to PHP's var_dump()
is pprint()
with the getmembers()
function in the built-in inspect
module:
from inspect import getmembers
from pprint import pprint
pprint(getmembers(yourObj))
ingconti is right.
www.dropbox.com
with dl.dropboxusercontent.com
in the link, like https://dl.dropboxusercontent.com/s/qgknrfngaxazm38/app.plistdownload.html
file with a link formatted as <a href="itms-services://?action=download-manifest&url=https://dl.dropboxusercontent.com/s/qgknrfngaxazm38/app.plist">INSTALL!!</a>
download.html
to dropboxwww.dropbox.com
with dl.dropboxusercontent.com
in the second link as well, like https://dl.dropboxusercontent.com/s/gnoctp7n9g0l3hx/download.htmlNow, visit https://dl.dropboxusercontent.com/s/gnoctp7n9g0l3hx/download.html
in your device, you can install the app like before.
WHAT A WONDERFUL WORLD!
Just adding another solution that works for me.. You can simply append it in the marker options:
var marker = new google.maps.Marker({
map: map,
position: position,
// Custom Attributes / Data / Key-Values
store_id: id,
store_address: address,
store_type: type
});
And then retrieve them with:
marker.get('store_id');
marker.get('store_address');
marker.get('store_type');
try this one, user json to serialize and deserialize:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
object newobj = new object();
for (int i = 0; i < 10; i++)
{
List<int> temp = new List<int>();
temp.Add(i);
temp.Add(i + 1);
newobj = newobj.AddNewField("item_" + i.ToString(), temp.ToArray());
}
}
}
public static class DynamicExtention
{
public static object AddNewField(this object obj, string key, object value)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string data = js.Serialize(obj);
string newPrametr = "\"" + key + "\":" + js.Serialize(value);
if (data.Length == 2)
{
data = data.Insert(1, newPrametr);
}
else
{
data = data.Insert(data.Length-1, ","+newPrametr);
}
return js.DeserializeObject(data);
}
}
}
On newer kernels you could also possibly use the the /sys/devices/system/cpu/
interface to get a bit more information:
$ ls /sys/devices/system/cpu/
cpu0 cpufreq kernel_max offline possible present release
cpu1 cpuidle modalias online power probe uevent
$ cat /sys/devices/system/cpu/kernel_max
255
$ cat /sys/devices/system/cpu/offline
2-63
$ cat /sys/devices/system/cpu/possible
0-63
$ cat /sys/devices/system/cpu/present
0-1
$ cat /sys/devices/system/cpu/online
0-1
See the official docs for more information on what all these mean.
var arr = ["20.0","40.1","80.2","400.3"],
sum = 0;
$.each(arr,function(){sum+=parseFloat(this) || 0; });
Worked perfectly for what i needed. Thanks vol7ron
I am adding this here even though the other answers are completely acceptable. JodaTime has parsers pre built in DateTimeFormat:
dateTime.toString(DateTimeFormat.longDate());
This is most of the options printed out with their format:
shortDate: 11/3/16
shortDateTime: 11/3/16 4:25 AM
mediumDate: Nov 3, 2016
mediumDateTime: Nov 3, 2016 4:25:35 AM
longDate: November 3, 2016
longDateTime: November 3, 2016 4:25:35 AM MDT
fullDate: Thursday, November 3, 2016
fullDateTime: Thursday, November 3, 2016 4:25:35 AM Mountain Daylight Time
For there to be an overlap the table's start_date has to be LESS THAN the interval end date (i.e. it has to start before the end of the interval) AND the table's end_date has to be GREATER THAN the interval start date. You may need to use <= and >= depending on your requirements.
I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white
to the HTML element. I overwrote that and everything was easy to handle from there.
For those who want a summary,
android:minSdkVersion
is minimum version till your application supports. If your device has lower version of android , app will not install.
while,
android:targetSdkVersion
is the API level till which your app is designed to run. Means, your phone's system don't need to use any compatibility behaviours to maintain forward compatibility because you have tested against till this API.
Your app will still run on Android versions higher than given targetSdkVersion
but android compatibility behaviour will kick in.
Freebie -
android:maxSdkVersion
if your device's API version is higher, app will not install. Ie. this is the max API till which you allow your app to install.
ie. for MinSDK -4, maxSDK - 8, targetSDK - 8 My app will work on minimum 1.6 but I also have used features that are supported only in 2.2 which will be visible if it is installed on a 2.2 device. Also, for maxSDK - 8, this app will not install on phones using API > 8.
At the time of writing this answer, Android documentation was not doing a great job at explaining it. Now it is very well explained. Check it here
Basic syntax is: $(selector).action()
A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)
In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.
It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.
As a note for the future: if you need a sentence parsed out and tag it as linguistics
(and syntax
or whatnot, if that's available), someone can probably parse it out for you and guide you through it.
In Java, you really want to use Integer.toString to convert an integer to its corresponding String value. If you are dealing with just the digits 0-9, then you could use something like this:
private static final char[] DIGITS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private static char getDigit(int digitValue) {
assertInRange(digitValue, 0, 9);
return DIGITS[digitValue];
}
Or, equivalently:
private static int ASCII_ZERO = 0x30;
private static char getDigit(int digitValue) {
assertInRange(digitValue, 0, 9);
return ((char) (digitValue + ASCII_ZERO));
}
function remote_file_exists($url){
return(bool)preg_match('~HTTP/1\.\d\s+200\s+OK~', @current(get_headers($url)));
}
$ff = "http://www.emeditor.com/pub/emed32_11.0.5.exe";
if(remote_file_exists($ff)){
echo "file exist!";
}
else{
echo "file not exist!!!";
}
Here's a list of keycodes that includes a way to look them up interactively.
Add this Annotation to Entity Class (Model) that works for me this cause lazy loading via the hibernate proxy object.
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
I used the method that you accepted a lot, but as someone pointed out it doesn't duplicate constraints (except for NOT NULL, I think).
A more advanced method if you want to duplicate the full structure is:
SET LONG 5000
SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME' ) FROM DUAL;
This will give you the full create statement text which you can modify as you wish for creating the new table. You would have to change the names of the table and all constraints of course.
(You could also do this in older versions using EXP/IMP, but it's much easier now.)
Edited to add If the table you are after is in a different schema:
SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME', 'OTHER_SCHEMA_NAME' ) FROM DUAL;
delete from emp
where rowid not in
(select max(rowid) from emp group by empno);
delete from emp where rowid in
(
select rid from
(
select rowid rid,
row_number() over(partition by empno order by empno) rn
from emp
)
where rn > 1
);
delete from emp e1
where rowid not in
(select max(rowid) from emp e2
where e1.empno = e2.empno );
Check if it's on first. That should get rid of the warning and it'll ensure that if your code is run on older versions of PHP that magic quotes are indeed off.
Don't just remove that line of code as suggested by others unless you can be 100% sure that the code will never be run on anything before PHP 5.3.
<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
// Deactivate
set_magic_quotes_runtime(false);
}
?>
get_magic_quotes_runtime
is NOT deprecated in PHP 5.3.
Source: http://us2.php.net/get_magic_quotes_runtime/
Swift 4+
NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: OperationQueue.main) { notification in
//you can do anything you want here.
}
by using this observer you can find out when user takes a screenshot, but you can not prevent him.
I'll tell you how it can be done in eclipse. My dev system - Windows 64bit, Eclipse Luna, Perlipse plugin for eclipse, Strawberry pearl installer. I use perl.exe as my interpreter.
Eclipse > create new perl project > right click project > build path > configure build path > libraries tab > add external source folder > go to the folder where all your perl modules are installed > ok > ok. Done !
I ran a quick test on SQL Server 2012 on an 8 GB RAM hyper-v box. You can see the results for yourself. I was not running any other windowed application apart from SQL Server Management Studio while running these tests.
My table schema:
CREATE TABLE [dbo].[employee](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_employee] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Total number of records in Employee
table: 178090131 (~ 178 million rows)
First Query:
Set Statistics Time On
Go
Select Count(*) From Employee
Go
Set Statistics Time Off
Go
Result of First Query:
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 35 ms.
(1 row(s) affected)
SQL Server Execution Times:
CPU time = 10766 ms, elapsed time = 70265 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
Second Query:
Set Statistics Time On
Go
Select Count(1) From Employee
Go
Set Statistics Time Off
Go
Result of Second Query:
SQL Server parse and compile time:
CPU time = 14 ms, elapsed time = 14 ms.
(1 row(s) affected)
SQL Server Execution Times:
CPU time = 11031 ms, elapsed time = 70182 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
You can notice there is a difference of 83 (= 70265 - 70182) milliseconds which can easily be attributed to exact system condition at the time queries are run. Also I did a single run, so this difference will become more accurate if I do several runs and do some averaging. If for such a huge data-set the difference is coming less than 100 milliseconds, then we can easily conclude that the two queries do not have any performance difference exhibited by the SQL Server Engine.
Note : RAM hits close to 100% usage in both the runs. I restarted SQL Server service before starting both the runs.
You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable
.
Main you have to consider three thing while binding the datasource of a dropdown.
you can use following code to bind a dropdownlist to a datasource as a datatable
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "QUIZ_Name";
DropDownList1.DataValueField = "QUIZ_ID"
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true"
you can use SelectedIndexChanged
event to write your code.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strQUIZ_ID=DropDownList1.SelectedValue;
string strQUIZ_Name=DropDownList1.SelectedItem.Text;
// Your code..............
}
The below statements show how to open/reopen Modal without using bootstrap.
Add two classes in css
And then use the below jQuery to reopen the modal if it is closed.
.hide_block
{
display:none !important;
}
.display_block
{
display:block !important;
}
$("#Modal").removeClass('hide_block');
$("#Modal").addClass('display_block');
$("Modal").show("slow");
It worked fine for me :)
$('#testID2').addClass('test3').removeClass('test2');
jQuery addClass API reference
"Note that you need to have image fully loaded first (otherwise ending up in having empty images), so in some cases you'd need to wrap handling into: bannerImage.addEventListener("load", function () {}); – yuga Nov 1 '17 at 13:04"
This is extremely IMPORTANT. One of the the options i'm exploring this afternoon is using javascript callback methods rather than addEventListeners since that doesn't seem to bind correctly either. Getting all the elements ready before page load WITHOUT a page refresh is critical.
If anyone can expand upon this please do - as in, did you use a settimeout, a wait, a callback, or an addEventListener method to get the desired result. Which one and why?
INDEXES
- to find data easily
UNIQUE INDEX
- duplicate values are not allowed
Syntax for INDEX
CREATE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);
Syntax for UNIQUE INDEX
CREATE UNIQUE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);
Right-click the icon, then click Properties. In the properties window, go to the Compatibility tab. There should be a checkbox labeled "Run this program as an administrator." Check that, then click OK. The next time you run the application from that shortcut, it will automatically run as the admin.
If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:
In [22]: orders_df['C'] = orders_df.Action.apply(
lambda x: (1 if x == 'Sell' else -1))
In [23]: orders_df # New column C represents the sign of the transaction
Out[23]:
Prices Amount Action C
0 3 57 Sell 1
1 89 42 Sell 1
2 45 70 Buy -1
3 6 43 Sell 1
4 60 47 Sell 1
5 19 16 Buy -1
6 56 89 Sell 1
7 3 28 Buy -1
8 56 69 Sell 1
9 90 49 Buy -1
Now we have eliminated the need for the if
statement. Using DataFrame.apply()
, we also do away with the for
loop. As Hayden noted, vectorized operations are always faster.
In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C
In [25]: orders_df # The resulting dataframe
Out[25]:
Prices Amount Action C Value
0 3 57 Sell 1 171
1 89 42 Sell 1 3738
2 45 70 Buy -1 -3150
3 6 43 Sell 1 258
4 60 47 Sell 1 2820
5 19 16 Buy -1 -304
6 56 89 Sell 1 4984
7 3 28 Buy -1 -84
8 56 69 Sell 1 3864
9 90 49 Buy -1 -4410
This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.
Using @property
and @attribute.setter
helps you to not only use the "pythonic" way but also to check the validity of attributes both while creating the object and when altering it.
class Person(object):
def __init__(self, p_name=None):
self.name = p_name
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
if type(new_name) == str: #type checking for name property
self._name = new_name
else:
raise Exception("Invalid value for name")
By this, you actually 'hide' _name
attribute from client developers and also perform checks on name property type. Note that by following this approach even during the initiation the setter gets called. So:
p = Person(12)
Will lead to:
Exception: Invalid value for name
But:
>>>p = person('Mike')
>>>print(p.name)
Mike
>>>p.name = 'George'
>>>print(p.name)
George
>>>p.name = 2.3 # Causes an exception
>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()
where a is your x data b is your y data c is your y error if any
note that c is the error in each direction already
You can hide a CommandField or ButtonField based on the position (index) in the GridView.
For example, if your CommandField is in the first position (index = 0), you can hide it adding the following code in the event RowDataBound of the GridView:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((System.Web.UI.Control)e.Row.Cells[0].Controls[0]).Visible = false;
}
}
Note: This was for Bootstrap 2 (relevant when the question was asked).
You can accomplish this by using row-fluid
to make a fluid (percentage) based row inside an existing block
.
<div class="row">
<div class="span5">span5</div>
<div class="span3">span3</div>
<div class="span2">
<div class="row-fluid">
<div class="span12">span2</div>
<div class="span12">span2</div>
</div>
</div>
<div class="span2">span2</div>
</div>
<div class="row">
<div class="span6">
<div class="row-fluid">
<div class="span12">span6</div>
<div class="span12">span6</div>
</div>
</div>
<div class="span6">span6</div>
</div>
Here's a JSFiddle example.
I did notice that there was an odd left margin that appears (or does not appear) for the spans inside of the row-fluid
after the first one. This can be fixed with a small CSS tweak (it's the same CSS that is applied to the first child, expanded to those past the first child):
.row-fluid [class*="span"] {
margin-left: 0;
}
import requests
r = requests.get("https://stackoverflow.com")
data = r.content # Content of response
print r.status_code # Status code of response
print data
Here is a simple way:
UIImage * image = [UIImage imageNamed:@"image"];
CGSize sacleSize = CGSizeMake(10, 10);
UIGraphicsBeginImageContextWithOptions(sacleSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, sacleSize.width, sacleSize.height)];
UIImage * resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
resizedImage is a new image.
This is somewhat of an extension to the answer when the comment line is too long to fit on a line (above 80 chars or whatever). If the comment is too long and text needs to wrap, it's better to keep it under control (rather than use the editor's text wrap feature). This plugin Rewrap helps do just that https://marketplace.visualstudio.com/items?itemName=stkb.rewrap&ssr=false#review-details
Install the plugin in VS Code, select the text comment, comment it using one of the right methods described in the answers (Ctrl + / is easiest) and then once it's commented, press Alt + Q and this will split the text to multiple lines and also comment it. Found it pretty useful. Hope this helps someone :)
As ibram stated, add the manifest thru solution explorer:
This creates a default manifest. Now, edit the manifest.
Not able to understand your actual problem but your case statement is incorrect
CASE
WHEN
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END
AS
COL4
If you work with generics, use List instead of ArrayList. The List has exactly the GetEnumerator method you need.
List<MyObject> myList = new List<MyObject>();
You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.
Use simple code in the link below :
http://msdn.microsoft.com/es-es/library/ie/cc836466%28v=vs.94%29.aspx
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
and reverse
var str = JSON.stringify(arr);
PDFCreator has a COM component, callable from .NET or VBScript (samples included in the download).
But, it seems to me that a printer is just what you need - just mix that with Word's automation, and you should be good to go.
using eq appears to grab the dynamic DOM whereas using .parent().parent() appears to grab the DOM that was initially loaded (if that is even possible).
I use them both on an element that has classes applied it to on onmouseover. eq shows the classes while .parent().parent() doesnt.
First of all, you need to deactivate node: (mac) after install new node version.
nvm deactivate
This is removed /Users/user_name/.nvm/*/bin from $PATH
And after that node was updated
node --version
v10.9.0
The popular answer here does work sometimes, but other times it creates horizontal scroll bars that are tough to deal with - especially when dealing with wide horizontal navigations and large pull down menus. Here is an even lighter-weight version that helps avoid those edge cases:
#wrap {
float: right;
position: relative;
left: -50%;
}
#content {
left: 50%;
position: relative;
}
To more specifically answer your question, it is probably not possible to do without setting up some containing element, however it is very possible to do without specifying a width value. Hope that saves someone out there some headaches!
Or on an actual device you can go to Settings -> Mobile Networks -> Preferred network types and chose the slowest available... Of course this is very limited, but for some test- purposes it might be enough.
To regain some single files or folders one may use the following
git reset -- path/to/file
git checkout -- path/to/file
This will first recreate the index entries for path/to/file
and recreate the file as it was in the last commit, i.e.HEAD
.
Hint: one may pass a commit hash to both commands to recreate files from an older commit. See git reset --help
and git checkout --help
for details.
If you are on a Unix system, Ctrl + Z will suspend Vim and give you a shell.
Type fg
to go back. Note that Vim creates a swap file while editing, and suspending Vim wouldn't delete that file (you aren't exiting Vim after all). On dumb terminals, this method was pretty standard for edit-compile-edit cycles using vi. I just found out that for me, gVim minimizes on typing Z.
I had some problems with lists of float values. I ended up using a code snippet from the python3 statistics.median and is working perfect with float values without imports. source
def calculateMedian(list):
data = sorted(list)
n = len(data)
if n == 0:
return None
if n % 2 == 1:
return data[n // 2]
else:
i = n // 2
return (data[i - 1] + data[i]) / 2
You can achieve this by using a spy (use the latest version of Mockito 1.8+ though).
public abstract class MyAbstract {
public String concrete() {
return abstractMethod();
}
public abstract String abstractMethod();
}
public class MyAbstractImpl extends MyAbstract {
public String abstractMethod() {
return null;
}
}
// your test code below
MyAbstractImpl abstractImpl = spy(new MyAbstractImpl());
doReturn("Blah").when(abstractImpl).abstractMethod();
assertTrue("Blah".equals(abstractImpl.concrete()));
Answer of @zolley is right. Just adding a Gif and steps for the reference.
Format > Conditional formatting..
Format cells if..
=countif(A:A,A1)>1
in field Custom formula is
A
with your own column.If you happen to use Vavr(formerly known as Javaslang), this can be as easy as:
Iterable i = //...
Stream.ofAll(i);
neither use inline; nor attachment; just use
response.setContentType("text/xml");
response.setHeader( "Content-Disposition", "filename=" + filename );
or
response.setHeader( "Content-Disposition", "filename=\"" + filename + "\"" );
or
response.setHeader( "Content-Disposition", "filename=\"" +
filename.substring(0, filename.lastIndexOf('.')) + "\"");
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
Check the Target framework. changed target framework from .NET framework 4.6.1
to .NET framework 4.6
has worked for me.
So it depends on how you want to pick the incrementer, but this should work:
Range("A1:" & Cells(1, i).Address).Select
Where i
is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)
If you want the beginning to be dynamic as well, you can try this:
Sub SelectCols()
Dim Col1 As Integer
Dim Col2 As Integer
Col1 = 2
Col2 = 4
Range(Cells(1, Col1), Cells(1, Col2)).Select
End Sub
In this particular case the clearest solution is the S.Lott answer
But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution.
Using De Morgan's law ¬(A^B) = ¬Av¬B
not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step
then
if u0 > u or u >= u0+step:
pass
... in this case the «clear» solution is not more clear :P
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
There is no bound checking in array in C programming. If you declare array as
int arr[50];
Then you can even write as
arr[51] = 10;
The compiler would not throw an error. Hope this answers your question.
Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.
The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:
e.g., given:
{
"store":
{
"book":
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle":
{
"color": "red",
"price": 19.95
}
}
}
And the expression: $.store.book[?(@.length-1)].title
, the tool returns a list of all titles.
the getText
method returns a String, while the setText
receives a String, so you can write it like label1.setText(nameField.getText());
in your listener.
Pay attention:
A Java char
corresponds to a UTF-16 code unit, and in some cases two consecutive char
s (a so-called surrogate pair) are needed for one real Unicode character (codepoint).
XORing two valid UTF-16 sequences (i.e. Java Strings char
by char
, or byte by byte after encoding to UTF-16) does not necessarily give you another valid UTF-16 string - you may have unpaired surrogates as a result. (It would still be a perfectly usable Java String, just the codepoint-concerning methods could get confused, and the ones that convert to other encodings for output and similar.)
The same is valid if you first convert your Strings to UTF-8 and then XOR these bytes - here you quite probably will end up with a byte sequence which is not valid UTF-8, if your Strings were not already both pure ASCII strings.
Even if you try to do it right and iterate over your two Strings by codepoint and try to XOR the codepoints, you can end up with codepoints outside the valid range (for example, U+FFFFF
(plane 15) XOR U+10000
(plane 16) = U+1FFFFF
(which would the last character of plane 31), way above the range of existing codepoints. And you could also end up this way with codepoints reserved for surrogates (= not valid ones).
If your strings only contain chars < 128, 256, 512, 1024, 2048, 4096, 8192, 16384, or 32768, then the (char-wise) XORed strings will be in the same range, and thus certainly not contain any surrogates. In the first two cases you could also encode your String as ASCII or Latin-1, respectively, and have the same XOR-result for the bytes. (You still can end up with control chars, which may be a problem for you.)
What I'm finally saying here: don't expect the result of encrypting Strings to be a valid string again - instead, simply store and transmit it as a byte[]
(or a stream of bytes). (And yes, convert to UTF-8 before encrypting, and from UTF-8 after decrypting).
you can specify fields like this:
LOAD XML LOCAL INFILE '/pathtofile/file.xml'
INTO TABLE my_tablename(personal_number, firstname, ...);
You can do this easily manually for each column like this:
df['A_perc'] = df['A']/df['sum']
If you want to do this in one step for all columns, you can use the div
method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):
ds.div(ds['sum'], axis=0)
And if you want this in one step added to the same dataframe:
>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
A B C D sum A_perc B_perc \
1 0.151722 0.935917 1.033526 0.941962 3.063127 0.049532 0.305543
2 0.033761 1.087302 1.110695 1.401260 3.633017 0.009293 0.299283
3 0.761368 0.484268 0.026837 1.276130 2.548603 0.298739 0.190013
C_perc D_perc sum_perc
1 0.337409 0.307517 1
2 0.305722 0.385701 1
3 0.010530 0.500718 1
All the previous posts are correct. There's more than one way to skin a cat. Here is another way to do the same thing: (just replace "what_ever_you_want_to_convert" with your string and run it in Oracle:
set serveroutput on;
DECLARE
v_str VARCHAR2(1000);
BEGIN
--Create encoded value
v_str := utl_encode.text_encode
('what_ever_you_want_to_convert','WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
--Decode the value..
v_str := utl_encode.text_decode
(v_str,'WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
END;
/
Travesal is O(n) for any order - because you are hitting each node once. Lookup is where it can be less than O(n) IF the tree has some sort of organizing schema (ie binary search tree).
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
Leave Hungarian to the Hungarians.
In the example I'd even leave out the definitive article and just go with
private const int Answer = 42;
Is that answer or is that the answer?
*Made edit as Pascal strictly correct, however I was thinking the question was seeking more of an answer to life, the universe and everything.
What do you mean by merging? JSON objects are key-value data structure. What would be a key and a value in this case? I think you need to create new directory and populate it with old data:
d = {}
d["new_key"] = jsonStringA[<key_that_you_did_not_mention_here>] + \
jsonStringB["timestamp_in_ms"]
Merging method is obviously up to you.
self.rx.viewDidAppearOnce
.flatMapLatest { _ in RxKeyboard.instance.isHidden }
.bind(onNext: { [unowned self] isHidden in
guard !isHidden else { return }
self.tableView.beginUpdates()
self.tableView.contentInsetAdjustmentBehavior = .automatic
self.tableView.endUpdates()
})
.disposed(by: self.disposeBag)
I'm using
/etc/bash_completion.d/git
It came with Git and provides a prompt with branch name and argument completion.
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
I just found the same issue with Aliases on a Windows install of Xampp.
To solve the 403 error:
<Directory "C:/Your/Directory/With/No/Trailing/Slash">
Require all granted
</Directory>
Alias /dev "C:/Your/Directory/With/No/Trailing/Slash"
The default Xampp set up should be fine with just this. Some people have experienced issues with a deny placed on the root directory so flipping out the directory tag to:
<Directory "C:/Your/Directory/With/No/Trailing/Slash">
Allow from all
Require all granted
</Directory>
Would help with this but the current version of Xampp (v1.8.1 at the time of writing) doesn't require it.
As for op's issue with port 80 Xampp includes a handy Netstat button to discover what's using your ports. Fire that off and fix the conflict, I imagine it could have been IIS but can't be sure.
In case your JENKINS_HOME directory is too large to copy, and all you need is to set up same jobs, Jenkins Plugins and Jenkins configurations (and don't need old Job artifacts and reports), then you can use the ThinBackup Plugin:
Install ThinBackup on both the source and the target Jenkins servers
Configure the backup directory on both (in Manage Jenkins ? ThinBackup ? Settings)
On the source Jenkins, go to ThinBackup ? Backup Now
Copy from Jenkins source backup directory to the Jenkins target backup directory
On the target Jenkins, go to ThinBackup ? Restore, and then restart the Jenkins service.
If some plugins or jobs are missing, copy the backup content directly to the target JENKINS_HOME.
If you had user authentication on the source Jenkins, and now locked out on the target Jenkins, then edit Jenkins config.xml, set <useSecurity>
to false, and restart Jenkins.
Found a way, thanks to the link here (with the original google group discussion here)
First, Telnet
to your server:
telnet 127.0.0.1 11211
Next, list the items to get the slab ids:
stats items STAT items:3:number 1 STAT items:3:age 498 STAT items:22:number 1 STAT items:22:age 498 END
The first number after ‘items’ is the slab id. Request a cache dump for each slab id, with a limit for the max number of keys to dump:
stats cachedump 3 100 ITEM views.decorators.cache.cache_header..cc7d9 [6 b; 1256056128 s] END stats cachedump 22 100 ITEM views.decorators.cache.cache_page..8427e [7736 b; 1256056128 s] END
You serialize it to JSON to persist in the Database and Deserialize it to reconstitute the .NET collection. This seems to perform better than I expected it to with Entity Framework 6 & SQLite. I know you asked for List<string>
but here's an example of an even more complex collection that works just fine.
I tagged the persisted property with [Obsolete]
so it would be very obvious to me that "this is not the property you are looking for" in the normal course of coding. The "real" property is tagged with [NotMapped]
so Entity framework ignores it.
(unrelated tangent): You could do the same with more complex types but you need to ask yourself did you just make querying that object's properties too hard for yourself? (yes, in my case).
using Newtonsoft.Json;
....
[NotMapped]
public Dictionary<string, string> MetaData { get; set; } = new Dictionary<string, string>();
/// <summary> <see cref="MetaData"/> for database persistence. </summary>
[Obsolete("Only for Persistence by EntityFramework")]
public string MetaDataJsonForDb
{
get
{
return MetaData == null || !MetaData.Any()
? null
: JsonConvert.SerializeObject(MetaData);
}
set
{
if (string.IsNullOrWhiteSpace(value))
MetaData.Clear();
else
MetaData = JsonConvert.DeserializeObject<Dictionary<string, string>>(value);
}
}
You can use Vim in Ex mode:
ex -sc 'a|BRAVO' -cx file
a
append text
x
save and close
Whenever a record has updated a record is "deleted". Here is my example:
ALTER TRIGGER [dbo].[UpdatePhyDate]
ON [dbo].[M_ContractDT1]
AFTER UPDATE
AS
BEGIN
-- on ContarctDT1 PhyQty is updated
-- I want system date in Phytate automatically saved
SET NOCOUNT ON;
declare @dt1ky as int
if(update(Phyqty))
begin
select @dt1ky = dt1ky from deleted
update M_ContractDT1 set PhyDate=GETDATE() where Dt1Ky= @dt1ky
end
END
It works fine
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="Sandro Alvares - KingRider">
</head>
<body>
<style type="text/css">
li.title {
font-size: 20px;
font-weight: lighter;
padding: 15px;
counter-increment: ordem;
}
.foo {
counter-reset: foo;
padding-left: 15px;
}
.foo li {
list-style-type: none;
}
.foo li:before {
counter-increment: foo;
content: counter(ordem) "." counter(foo) " ";
}
</style>
<ol>
<li class="title">TITLE ONE</li>
<ol class="foo">
<li>text 1 one</li>
<li>text 1 two</li>
<li>text 1 three</li>
<li>text 1 four</li>
</ol>
<li class="title">TITLE TWO</li>
<ol class="foo">
<li>text 2 one</li>
<li>text 2 two</li>
<li>text 2 three</li>
<li>text 2 four</li>
</ol>
<li class="title">TITLE THREE</li>
<ol class="foo">
<li>text 3 one</li>
<li>text 3 two</li>
<li>text 3 three</li>
<li>text 3 four</li>
</ol>
</ol>
</body>
</html>
In this code's thread creation, the address of a function pointer is being passed.
The original
pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0
It should read as
pthread_create(&some_thread, NULL, print_the_arguments, (void *) &args)
A good way to remember is that all of this function's arguments should be addresses.
some_thread
is declared statically, so the address is sent properly using &
.
I would create a pthread_attr_t
variable, then use pthread_attr_init()
on it and pass that variable's address. But, passing a NULL
pointer is valid as well.
The &
in front of the function label is what is causing the issue here. The label used is already a void*
to a function, so only the label is necessary.
To say != 0
with the final argument would seem to cause undetermined behavior. Adding this means that a boolean is being passed instead of a reference.
Akash Agrawal's answer is also part of the solution to this code's problem.
Possibly:
select lpad(column, 8, 0) from table;
Edited in response to question from mylesg, in comments below:
ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT
I'm assuming that you used a query similar to:
UPDATE table SET columnName=lpad(nums,8,0);
If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:
First:
ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);
Second, run the update:
UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');
This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.
References:
Change
CREATE DEFINER = `root`@`localhost` FUNCTION `fnc_calcWalkedDistance` (
By
FUNCTION `fnc_calcWalkedDistance` (
check out csvreader/writer library at http://www.codeproject.com/KB/cs/CsvReaderAndWriter.aspx
It might be useful to make an extension in Swift for this.
Swift 4 and Swift 5:
Swift extension (e.g. in a UITableViewExtension.swift file):
import UIKit
extension UITableView {
func deselectSelectedRow(animated: Bool)
{
if let indexPathForSelectedRow = self.indexPathForSelectedRow {
self.deselectRow(at: indexPathForSelectedRow, animated: animated)
}
}
}
Use e.g.:
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
self.tableView.deselectSelectedRow(animated: true)
}
You can groupby
on cols 'A' and 'B' and call size
and then reset_index
and rename
the generated column:
In [26]:
df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})
Out[26]:
A B count
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
update
A little explanation, by grouping on the 2 columns, this groups rows where A and B values are the same, we call size
which returns the number of unique groups:
In[202]:
df1.groupby(['A','B']).size()
Out[202]:
A B
no no 1
yes 2
yes no 4
yes 3
dtype: int64
So now to restore the grouped columns, we call reset_index
:
In[203]:
df1.groupby(['A','B']).size().reset_index()
Out[203]:
A B 0
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
This restores the indices but the size aggregation is turned into a generated column 0
, so we have to rename this:
In[204]:
df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})
Out[204]:
A B count
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
groupby
does accept the arg as_index
which we could have set to False
so it doesn't make the grouped columns the index, but this generates a series
and you'd still have to restore the indices and so on....:
In[205]:
df1.groupby(['A','B'], as_index=False).size()
Out[205]:
A B
no no 1
yes 2
yes no 4
yes 3
dtype: int64
This will find all .c or .cpp files on linux
$ find . -name "*.c" -o -name "*.cpp"
You don't need the escaped parenthesis unless you are doing some additional mods. Here from the man page they are saying if the pattern matches, print it. Perhaps they are trying to control printing. In this case the -print acts as a conditional and becomes an "AND'd" conditional. It will prevent any .c files from being printed.
$ find . -name "*.c" -o -name "*.cpp" -print
But if you do like the original answer you can control the printing. This will find all .c files as well.
$ find . \( -name "*.c" -o -name "*.cpp" \) -print
One last example for all c/c++ source files
$ find . \( -name "*.c" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -print
If dt is your datetime column, then
For 1:
SUBSTRING(CONVERT(varchar, dt, 13), 1, 2)
+ UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3))
For 2:
SUBSTRING(CONVERT(varchar, dt, 100), 13, 2)
+ SUBSTRING(CONVERT(varchar, dt, 100), 16, 3)
For this the System.Timers.Timer
works best
// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it
myTimer.Enabled = true;
// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }
See Timer Class (.NET 4.6 and 4.5) for details
You can use position:absolute
to position an overlay inside of your div and then stretch it in all directions like so:
CSS updated *
.overlay {
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
background-color:rgba(0, 0, 0, 0.85);
background: url(data:;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAABl0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuNUmK/OAAAAATSURBVBhXY2RgYNgHxGAAYuwDAA78AjwwRoQYAAAAAElFTkSuQmCC) repeat scroll transparent\9; /* ie fallback png background image */
z-index:9999;
color:white;
}
You just need to make sure that your parent div has the position:relative
property added to it and a lower z-index
.
Made a demo that should work in all browsers, including IE7+, for a commenter below.
Removed the opacity
property from the css and instead used an rGBA color to give the background, and only the background, an opacity level. This way the content that the overlay carries will not be affected. Since IE does not support rGBA i used an IE hack instead to give it an base64 encoded PNG background image that fills the overlay div instead, this way we can evade IEs opacity issue where it applies the opacity to the children elements as well.
I tried the above but they didn't work, i found this thought, that works a just fine for me.
var ContactID = db.GetLastInsertId();
Its less code and i easy to put in.
Hope this helps someone.
The formula provided by Blake doesn't seem to work for me. For past dates it returns due in xx days and for future dates, it returns overdue. Also, it will only return 15 days overdue, when it could actually be 30, 60 90+.
I created this, which seems to work and provides 'Due in xx days', 'Overdue xx days' and 'Due Today'.
=IF(ISBLANK(O10),"",IF(DAYS(TODAY(),O10)<0,CONCATENATE("Due in ",-DAYS(TODAY(),O10)," Days"),IF(DAYS(TODAY(),O10)>0,CONCATENATE("Overdue ",DAYS(TODAY(),O10)," Days"),"Due Today")))
If the column has a 0 value, you are fine, my guess is that you have a problem with a Null value, in that case you would need to use IsNull(Column, 0)
to ensure it is always 0 at minimum.
if type(varA) == str or type(varB) == str:
print 'string involved'
from EDX - online course MITx: 6.00.1x Introduction to Computer Science and Programming Using Python
If you want to use built-in code, you can use toLocaleString()
with minimumFractionDigits
. Browser compatibility for the extended options on toLocaleString()
was limited when I first wrote this answer, but the current status looks good.
var n = 100000;
var value = n.toLocaleString(
undefined, // leave undefined to use the browser's locale,
// or use a string like 'en-US' to override it.
{ minimumFractionDigits: 2 }
);
console.log(value);
// In en-US, logs '100,000.00'
// In de-DE, logs '100.000,00'
// In hi-IN, logs '1,00,000.00'
_x000D_
If you're using Node.js, you will need to npm install
the intl
package.
Use ?'%*%'
to get the documentation.
%*%
is matrix multiplication. For matrix multiplication, you need an m x n
matrix times an n x p
matrix.
To make it just show up in your JSP pages, you can use the Spring Security Tag Lib:
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html
To use any of the tags, you must have the security taglib declared in your JSP:
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
Then in a jsp page do something like this:
<security:authorize access="isAuthenticated()">
logged in as <security:authentication property="principal.username" />
</security:authorize>
<security:authorize access="! isAuthenticated()">
not logged in
</security:authorize>
NOTE: As mentioned in the comments by @SBerg413, you'll need to add
use-expressions="true"
to the "http" tag in the security.xml config for this to work.
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
var ParentId=dr["ParentId"].ToString();
}
}
All you have to do is: $variable =NULL;
// and pass it in the insert query. This will store the value as NULL in mysql db
This is late but this may help someone :) :) For adding the view programmatically try like
LinearLayout rlmain = new LinearLayout(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
LinearLayout ll1 = new LinearLayout (this);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.logo);
LinearLayout .LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
iv.setLayoutParams(lp);
ll1.addView(iv);
rlmain.addView(ll1);
setContentView(rlmain, llp);
This will create your entire view programmatcally. You can add any number of view as same. Hope this may help. :)
I've been not satisfied with all the solutions on this page (come on, where is our favorite copy-paste thing?) so I wrote my own based on answers here. It tries to be complete and more Pythonic. I've added a handler for dict and bool values in arguments to be more consumer-side (JS) friendly, but they are yet optional, you can drop them.
Test 1: Adding new arguments, handling Arrays and Bool values:
url = 'http://stackoverflow.com/test'
new_params = {'answers': False, 'data': ['some','values']}
add_url_params(url, new_params) == \
'http://stackoverflow.com/test?data=some&data=values&answers=false'
Test 2: Rewriting existing args, handling DICT values:
url = 'http://stackoverflow.com/test/?question=false'
new_params = {'question': {'__X__':'__Y__'}}
add_url_params(url, new_params) == \
'http://stackoverflow.com/test/?question=%7B%22__X__%22%3A+%22__Y__%22%7D'
Code itself. I've tried to describe it in details:
from json import dumps
try:
from urllib import urlencode, unquote
from urlparse import urlparse, parse_qsl, ParseResult
except ImportError:
# Python 3 fallback
from urllib.parse import (
urlencode, unquote, urlparse, parse_qsl, ParseResult
)
def add_url_params(url, params):
""" Add GET params to provided URL being aware of existing.
:param url: string of target URL
:param params: dict containing requested params to be added
:return: string with updated URL
>> url = 'http://stackoverflow.com/test?answers=true'
>> new_params = {'answers': False, 'data': ['some','values']}
>> add_url_params(url, new_params)
'http://stackoverflow.com/test?data=some&data=values&answers=false'
"""
# Unquoting URL first so we don't loose existing args
url = unquote(url)
# Extracting url info
parsed_url = urlparse(url)
# Extracting URL arguments from parsed URL
get_args = parsed_url.query
# Converting URL arguments to dict
parsed_get_args = dict(parse_qsl(get_args))
# Merging URL arguments dict with new params
parsed_get_args.update(params)
# Bool and Dict values should be converted to json-friendly values
# you may throw this part away if you don't like it :)
parsed_get_args.update(
{k: dumps(v) for k, v in parsed_get_args.items()
if isinstance(v, (bool, dict))}
)
# Converting URL argument to proper query string
encoded_get_args = urlencode(parsed_get_args, doseq=True)
# Creating new parsed result object based on provided with new
# URL arguments. Same thing happens inside of urlparse.
new_url = ParseResult(
parsed_url.scheme, parsed_url.netloc, parsed_url.path,
parsed_url.params, encoded_get_args, parsed_url.fragment
).geturl()
return new_url
Please be aware that there may be some issues, if you'll find one please let me know and we will make this thing better
First you need to turn on virtualization on your machine. To do that, restart your machine. Press F2. Goto BIOS. Make Virtualization Enabled. Press F10. Start windows. Now, goto Extras folder of Android installation folder and find intel-haxm-android.exe. Run it. Start Android Studio. Now, it should allow you to run your program using emulator.
Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.
function traverse(o, fn) {
const stack = [o]
while (stack.length) {
const obj = stack.shift()
Object.keys(obj).forEach((key) => {
fn(key, obj[key], obj)
if (obj[key] instanceof Object) {
stack.unshift(obj[key])
return
}
})
}
}
const o = {
name: 'Max',
legal: false,
other: {
name: 'Maxwell',
nested: {
legal: true
}
}
}
const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)
If expr is greater than or equal to min and expr is less than or equal to max,
BETWEEN
returns 1, otherwise it returns 0.
The important part here is EQUAL to max., which 1st of July is.
What about this (a bit late):
def remove_prefix(s, prefix):
return s[len(prefix):] if s.startswith(prefix) else s
You cannot show an alert from a controller. There is one way communication from the client to the server.The server can therefore not tell the client to do anything. The client requests and the server gives a response.
You therefore need to use javascript when the response returns to show a messagebox of some sort.
OR
using jquery on the button that calls the controller action
<script>
$(document).ready(function(){
$("#submitButton").on("click",function()
{
alert('Your Message');
});
});
<script>
You can define instance method for js class, via prototype of the constructor.
Following is the sample code:
// BaseClass
var BaseClass = function(name) {
// instance property
this.name = name;
};
// instance method
BaseClass.prototype.getName = function() {
return this.name;
};
BaseClass.prototype.setName = function(name) {
return this.name = name;
};
// test - start
function test() {
var b1 = new BaseClass("b1");
var b2 = new BaseClass("b2");
console.log(b1.getName());
console.log(b2.getName());
b1.setName("b1_new");
console.log(b1.getName());
console.log(b2.getName());
}
test();
// test - end
And, this should work for any browser, you can also simply use nodejs to run this code.
To split the difference of opinion
I prefer:
xls.DisplayAlerts = False
wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
xls.DisplayAlerts = True
I was able to fix this issue by changing $(document).ready()
to window.onLoad()
.
x = math.ceil(x * 100.0) / 100.0
No, int
in C is not defined to be 32 bits. int
and long
are not defined to be any specific size at all. The only thing the language guarantees is that sizeof(char)<=sizeof(short)<=sizeof(long)
.
Theoretically a compiler could make short
, char
, and long
all the same number of bits. I know of some that actually did that for all those types save char
.
This is why C now defines types like uint16_t
and uint32_t
. If you need a specific size, you are supposed to use one of those.
AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle
android {
signingConfigs {
release {
storeFile file('android.keystore')
storePassword "pwd"
keyAlias "alias"
keyPassword "pwd"
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
To actually run your application at emulator or device run gradle installDebug
or gradle installRelease
.
You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872
I have a simple solution based on the file name
#!/bin/bash
MY_FILENAME=`basename "$BASH_SOURCE"`
MY_PROCESS_COUNT=$(ps a -o pid,cmd | grep $MY_FILENAME | grep -v grep | grep -v $$ | wc -
l)
if [ $MY_PROCESS_COUNT -ne 0 ]; then
echo found another process
exit 0
if
# Follows the code to get the job done.
Checkout a project called Uploadify. http://www.uploadify.com/
It's a Flash + jQuery based file uploader. This uses Flash's file selection dialog, which gives you the ability to filter file types, select multiple files at the same time, etc.
You can use str.contains
alone with a regex pattern using OR (|)
:
s[s.str.contains('og|at')]
Or you could add the series to a dataframe
then use str.contains
:
df = pd.DataFrame(s)
df[s.str.contains('og|at')]
Output:
0 cat
1 hat
2 dog
3 fog
The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).
In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character
So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).
And you can mix “combining above” and “combining below” marks.
The sample text in the question starts with:
H
ͭ
̓
̓
̇
You can do this without any code behind by using a IValueConverter
.
<Grid>
<ComboBox
x:Name="comboBox1"
ItemsSource="{Binding MyItemSource}" />
<TextBlock
Visibility="{Binding SelectedItem, ElementName=comboBox1, Converter={StaticResource NullToVisibilityConverter}}"
IsHitTestVisible="False"
Text="... Select Team ..." />
</Grid>
Here you have the converter class that you can re-use.
public class NullToVisibilityConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
And finally, you need to declare your converter in a resource section.
<Converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
Where Converters is the place you have placed the converter class. An example is:
xmlns:Converters="clr-namespace:MyProject.Resources.Converters"
The very nice thing about this approach is no repetition of code in your code behind.
You can use getSimpleName().
Let's say we have a object: Dog d = new Dog(),
The we can use below statement to get the class name: Dog. E.g.:
d.getClass().getSimpleName(); // return String 'Dog'.
PS: d.getClass() will give you the full name of your object.
The answer that accepts empty string:
/^[a-zA-Z]*$/.test('something')
the *
means 0 or more occurrences of the preceding item.
If you ever have the same trouble and try everything online and it doesn't work, it is probably the config cache file that is sending the wrong information. You can find it in bootstrap/cache/config.php. Make sure the credentials are right in there. It took me a week to figure that out. I hope this will help someone someday.
I order to change the dialog buttons and background colors, you will need to extend the Dialog theme, eg.:
<style name="MyDialogStyle" parent="android:Theme.Material.Light.Dialog.NoActionBar">
<item name="android:buttonBarButtonStyle">@style/MyButtonsStyle</item>
<item name="android:colorBackground">@color/white</item>
</style>
<style name="MyButtonsStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">@color/light.blue</item>
</style>
After that, you need to pass this custom style to the dialog builder, eg. like this:
AlertDialog.Builder(requireContext(), R.style.MyDialogStyle)
If you want to change the color of the text inside the dialog, you can pass a custom view to this Builder:
AlertDialog.Builder.setView(View)
or
AlertDialog.Builder.setView(@LayoutResource int)
The jQuery plugin is probably the best option. http://farinspace.com/jquery-scrollable-table-plugin/
To fixing header you can check this post
Fixing Header of GridView or HtmlTable (there might be issue that this should work in IE only)
CSS for fixing header
div#gridPanel
{
width:900px;
overflow:scroll;
position:relative;
}
div#gridPanel th
{
top: expression(document.getElementById("gridPanel").scrollTop-2);
left:expression(parentNode.parentNode.parentNode.parentNode.scrollLeft);
position: relative;
z-index: 20;
}
<div height="200px" id="gridPanel" runat="server" scrollbars="Auto" width="100px">
table..
</div>
or
Very good post is here for this
How to Freeze Columns Using JavaScript and HTML.
or
No its not possible but you can make use of div and put table in div
<div style="height: 100px; overflow: auto">
<table style="height: 500px;">
...
</table>
</div>
If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'
you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
Pattern! The group names a (sub)pattern for later use in the regex. See the documentation here for details about how such groups are used.
Try destroying the datatable with bDestroy:true like this:
$("#ajaxchange").click(function(){
var campaign_id = $("#campaigns_id").val();
var fromDate = $("#from").val();
var toDate = $("#to").val();
var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
$.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
function( data ) {
$("#ajaxresponse").html(data);
oTable6 = $('#rankings').dataTable( {"bDestroy":true,
"sDom":'t<"bottom"filp><"clear">',
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "bSortable": false, "sWidth": "10px" },
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
]
}
);
});
});
bDestroy: true will first destroy and datatable instance associated with that selector before reinitializing a new one.
Aside from the many answers already supplied to this question, a simple check on the local repo branches that exist in your machine and those that don't in the remote, will help. In which case you don't use the
git prune
command as many have suggested.
Simply delete the local branch
git branch -d <branch name without a remote tracking branch by the same name>
as shown in the attached screenshot using -D to force delete when you are sure that a local branch does not have a remote branch tracked.
Update: This will create a second context same as in applicationContext.xml
or you can add this code snippet to your web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
instead of
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
If you change from using a lambda with one argument to a function with one argument, you will get this error.
For example:
You had:
foobar = lambda do |baz|
puts baz
end
and you changed the definition to
def foobar(baz)
puts baz
end
And you left your invocation as:
foobar.call(baz)
And then you got the message
ArgumentError: wrong number of arguments (0 for 1)
when you really meant:
foobar(baz)
This is how you can implement difference between dates without a framework.
function getDateDiff(dateOne, dateTwo) {
if(dateOne.charAt(2)=='-' & dateTwo.charAt(2)=='-'){
dateOne = new Date(formatDate(dateOne));
dateTwo = new Date(formatDate(dateTwo));
}
else{
dateOne = new Date(dateOne);
dateTwo = new Date(dateTwo);
}
let timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
let diffMonths = Math.ceil(diffDays/31);
let diffYears = Math.ceil(diffMonths/12);
let message = "Difference in Days: " + diffDays + " " +
"Difference in Months: " + diffMonths+ " " +
"Difference in Years: " + diffYears;
return message;
}
function formatDate(date) {
return date.split('-').reverse().join('-');
}
console.log(getDateDiff("23-04-2017", "23-04-2018"));
If you are experiencing errors during PKG installation following the accepted answer, I will give you another procedure that worked for me (please note the little changes to xar, cpio and mkbom commands):
mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc | cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o --format odc --owner 0:80 | gzip -c > Payload
mkbom -u 0 -g 80 Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar --compression none -cf ../Foo-new.pkg
The resulted PKG will have no compression, cpio now uses odc format and specify the owner of the file as well as mkbom.
When it says users are connected, what does the query "select * from pg_stat_activity;" say? Are the other users besides yourself now connected? If so, you might have to edit your pg_hba.conf file to reject connections from other users, or shut down whatever app is accessing the pg database to be able to drop it. I have this problem on occasion in production. Set pg_hba.conf to have a two lines like this:
local all all ident
host all all 127.0.0.1/32 reject
and tell pgsql to reload or restart (i.e. either sudo /etc/init.d/postgresql reload or pg_ctl reload) and now the only way to connect to your machine is via local sockets. I'm assuming you're on linux. If not this may need to be tweaked to something other than local / ident on that first line, to something like host ... yourusername.
Now you should be able to do:
psql postgres
drop database mydatabase;
Thanks @haind
Yes HTMLInputElement
worked for input field
//Example
var elem = e.currentTarget as HTMLInputElement;
elem.setAttribute('my-attribute','my value');
elem.value='5';
This HTMLInputElement
is interface is inherit from HTMLElement
which is inherited from EventTarget
at root level. Therefore we can assert using as
operator to use specific interfaces according to the context like in this case we are using HTMLInputElement
for input field other interfaces can be HTMLButtonElement
, HTMLImageElement
etc.
For more reference you can check other available interface here
I think the best and cleanest solution you can imagine is this:
@Component( {
selector: 'app-my-component',
template: `<p>{{ myData?.anyfield }}</p>`,
styles: [ '' ]
} )
export class MyComponent implements OnInit {
private myData;
constructor( private myService: MyService ) { }
ngOnInit( ) {
/*
async .. await
clears the ExpressionChangedAfterItHasBeenCheckedError exception.
*/
this.myService.myObservable.subscribe(
async (data) => { this.myData = await data }
);
}
}
Tested with Angular 5.2.9
Instead of giving localhost give the IP.
Try this:
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class currentTime {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println( sdf.format(cal.getTime()) );
}
}
You can format SimpleDateFormat in the way you like. For any additional information you can look in java api:
You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:
public class Item
{
public string name { get; set; }
public string index { get; set; }
public string optional { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
Usage:
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item>
{
new Item { name = "test1", index = "index1" },
new Item { name = "test2", index = "index2" }
};
And in the result you won't have to change things several times if you need to change data-structure.
p.s. Here's very nice tool for complex json
s
Inside of your loop, you have the key, which you can use to retrieve the value from the Map
:
for (String key: mss1.keySet()) {
System.out.println(key + ": " + mss1.get(key));
}
I definitely wouldn't use Block1. It doesn't seem right having the Error block in an IF statement unrelated to Errors.
Blocks 2,3 & 4 I guess are variations of a theme. I prefer the use of Blocks 3 & 4 over 2 only because of a dislike of the GOTO statement; I generally use the Block4 method. This is one example of code I use to check if the Microsoft ActiveX Data Objects 2.8 Library is added and if not add or use an earlier version if 2.8 is not available.
Option Explicit
Public booRefAdded As Boolean 'one time check for references
Public Sub Add_References()
Dim lngDLLmsadoFIND As Long
If Not booRefAdded Then
lngDLLmsadoFIND = 28 ' load msado28.tlb, if cannot find step down versions until found
On Error GoTo RefErr:
'Add Microsoft ActiveX Data Objects 2.8
Application.VBE.ActiveVBProject.references.AddFromFile _
Environ("CommonProgramFiles") + "\System\ado\msado" & lngDLLmsadoFIND & ".tlb"
On Error GoTo 0
Exit Sub
RefErr:
Select Case Err.Number
Case 0
'no error
Case 1004
'Enable Trust Centre Settings
MsgBox ("Certain VBA References are not available, to allow access follow these steps" & Chr(10) & _
"Goto Excel Options/Trust Centre/Trust Centre Security/Macro Settings" & Chr(10) & _
"1. Tick - 'Disable all macros with notification'" & Chr(10) & _
"2. Tick - 'Trust access to the VBA project objects model'")
End
Case 32813
'Err.Number 32813 means reference already added
Case 48
'Reference doesn't exist
If lngDLLmsadoFIND = 0 Then
MsgBox ("Cannot Find Required Reference")
End
Else
For lngDLLmsadoFIND = lngDLLmsadoFIND - 1 To 0 Step -1
Resume
Next lngDLLmsadoFIND
End If
Case Else
MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
End
End Select
On Error GoTo 0
End If
booRefAdded = TRUE
End Sub
Another way of running integration tests with Maven is to make use of the profile feature:
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration-tests</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
<excludes>
<exclude>**/*StagingIntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
...
Running 'mvn clean install' will run the default build. As specified above integration tests will be ignored. Running 'mvn clean install -P integration-tests' will include the integration tests (I also ignore my staging integration tests). Furthermore, I have a CI server that runs my integration tests every night and for that I issue the command 'mvn test -P integration-tests'.
There are a few answers outlining differences between <depedencies>
and <dependencyManagement>
tags with maven.
However, few points elaborated below in a concise way:
<dependencyManagement>
allows to consolidate all dependencies (used at child pom level) used across different modules -- clarity, central dependency version management<dependencyManagement>
allows to easily upgrade/downgrade dependencies based on need, in other scenario this needs to be exercised at every child pom level -- consistency<dependencies>
tag is always imported, while dependencies provided at <dependencyManagement>
in parent pom will be imported only if child pom has respective entry in its <dependencies>
tag.Facebook now supports hiding the count, use this in the markup:
data-layout="button"
I encountered the same issue after updating the maven-jar-plugin
to its latest version (at the time of writing), 3.0.2
.
Eclipse 4.5.2
started flagging the pom.xml
file with the org.apache.maven.archiver.MavenArchiver.getManifest
error and a Maven > Update Project.. would not fix it.
Easy solution: downgrade to 2.6 version
Indeed a possible solution is to get back to version 2.6
, a further update of the project would then remove any error. However, that's not the ideal scenario and a better solution is possible: update the m2e
extensions (Eclipse Maven integration).
Better solution: update Eclipse m2e extensions
From Help > Install New Software.., add a new repository (via the Add.. option), pointing to the following URL:
https://repo1.maven.org/maven2/.m2e/connectors/m2eclipse-mavenarchiver/0.17.2/N/LATEST/
Then follow the update wizard as usual. Eclipse would then require a restart. Afterwards, a further Update Project.. on the concerned Maven project would remove any error and your Maven build could then enjoy the benefit of the latest maven-jar-plugin
version.
Additonal notes
The reason for this issue is that from version 3.0.0
on, the concerned component, the maven-archiver
and the related plexus-archiver
has been upgraded to newer versions, breaking internal usages (via reflections) of the m2e
integration in Eclipse. The only solution is then to properly update Eclipse, as described above.
Also note: while Eclipse would initially report errors, the Maven build (e.g. from command line) would keep on working perfectly, this issue is only related to the Eclipse-Maven integration, that is, to the IDE.
If you just need some views not to use CSRF, you can use @csrf_exempt
:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
You can find more examples and other scenarios in the Django documentation:
I found this can be done using client
also and not just resource
.
from io import StringIO
import boto3
s3 = boto3.client("s3",\
region_name=region_name,\
aws_access_key_id=aws_access_key_id,\
aws_secret_access_key=aws_secret_access_key)
csv_buf = StringIO()
df.to_csv(csv_buf, header=True, index=False)
csv_buf.seek(0)
s3.put_object(Bucket=bucket, Body=csv_buf.getvalue(), Key='path/test.csv')
Programmatically change UITextField Keyboard type swift 3.0
lazy var textFieldTF: UITextField = {
let textField = UITextField()
textField.placeholder = "Name"
textField.frame = CGRect(x:38, y: 100, width: 244, height: 30)
textField.textAlignment = .center
textField.borderStyle = UITextBorderStyle.roundedRect
textField.keyboardType = UIKeyboardType.default //keyboard type
textField.delegate = self
return textField
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(textFieldTF)
}
I think this is the easiest way
<!-- Submit Button-->
<button
mat-raised-button
color="primary"
[disabled]="!f.valid"
>
Submit
</button>
Just use the ==
with the negation symbol (!
). If dtfm is the name of your data.frame:
dtfm[!dtfm$C == "Foo", ]
Or, to move the negation in the comparison:
dtfm[dtfm$C != "Foo", ]
Or, even shorter using subset()
:
subset(dtfm, C!="Foo")
in MainActivity call restartActivity Method:
public static void restartActivity(Activity mActivity) {
Intent mIntent = mActivity.getIntent();
mActivity.finish();
mActivity.startActivity(mIntent);
}
A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.