Tried multiple of these, I switched to Cygwin instead which fixed python and some other problems I was having on Windows:
You may store the parameters for the blob detector in a file, but this is not necessary. Example:
// set up the parameters (check the defaults in opencv's code in blobdetector.cpp)
cv::SimpleBlobDetector::Params params;
params.minDistBetweenBlobs = 50.0f;
params.filterByInertia = false;
params.filterByConvexity = false;
params.filterByColor = false;
params.filterByCircularity = false;
params.filterByArea = true;
params.minArea = 20.0f;
params.maxArea = 500.0f;
// ... any other params you don't want default value
// set up and create the detector using the parameters
cv::SimpleBlobDetector blob_detector(params);
// or cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params)
// detect!
vector<cv::KeyPoint> keypoints;
blob_detector.detect(image, keypoints);
// extract the x y coordinates of the keypoints:
for (int i=0; i<keypoints.size(); i++){
float X = keypoints[i].pt.x;
float Y = keypoints[i].pt.y;
}
Move DropDownList1.Items.Add(new ListItem("Select", "0", true)); After bindStatusDropDownList();
so:
if (!IsPostBack)
{
bindStatusDropDownList(); //first create structure
DropDownList1.Items.Add(new ListItem("Select", "0", true)); // after add item
}
$(element).prop('disabled', true); //true|disabled will work on all
$(element).attr('disabled', true);
element.disabled = true;
element.setAttribute('disabled', true);
All of the above are perfectly valid solutions. Choose the one that fits your needs best.
I had the same issue of multiple DocumentCompleted
fired events and tried out all the suggestions above. Finally, seems that in my case neither IsBusy
property works right nor Url
property, but the ReadyState
seems to be what I needed, because it has the status 'Interactive' while loading the multiple frames and it gets the status 'Complete' only after loading the last one. Thus, I know when the page is fully loaded with all its components.
I hope this may help others too :)
This will show a model's weights and parameters (but not output shape).
from torch.nn.modules.module import _addindent
import torch
import numpy as np
def torch_summarize(model, show_weights=True, show_parameters=True):
"""Summarizes torch model by showing trainable parameters and weights."""
tmpstr = model.__class__.__name__ + ' (\n'
for key, module in model._modules.items():
# if it contains layers let call it recursively to get params and weights
if type(module) in [
torch.nn.modules.container.Container,
torch.nn.modules.container.Sequential
]:
modstr = torch_summarize(module)
else:
modstr = module.__repr__()
modstr = _addindent(modstr, 2)
params = sum([np.prod(p.size()) for p in module.parameters()])
weights = tuple([tuple(p.size()) for p in module.parameters()])
tmpstr += ' (' + key + '): ' + modstr
if show_weights:
tmpstr += ', weights={}'.format(weights)
if show_parameters:
tmpstr += ', parameters={}'.format(params)
tmpstr += '\n'
tmpstr = tmpstr + ')'
return tmpstr
# Test
import torchvision.models as models
model = models.alexnet()
print(torch_summarize(model))
# # Output
# AlexNet (
# (features): Sequential (
# (0): Conv2d(3, 64, kernel_size=(11, 11), stride=(4, 4), padding=(2, 2)), weights=((64, 3, 11, 11), (64,)), parameters=23296
# (1): ReLU (inplace), weights=(), parameters=0
# (2): MaxPool2d (size=(3, 3), stride=(2, 2), dilation=(1, 1)), weights=(), parameters=0
# (3): Conv2d(64, 192, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)), weights=((192, 64, 5, 5), (192,)), parameters=307392
# (4): ReLU (inplace), weights=(), parameters=0
# (5): MaxPool2d (size=(3, 3), stride=(2, 2), dilation=(1, 1)), weights=(), parameters=0
# (6): Conv2d(192, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), weights=((384, 192, 3, 3), (384,)), parameters=663936
# (7): ReLU (inplace), weights=(), parameters=0
# (8): Conv2d(384, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), weights=((256, 384, 3, 3), (256,)), parameters=884992
# (9): ReLU (inplace), weights=(), parameters=0
# (10): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), weights=((256, 256, 3, 3), (256,)), parameters=590080
# (11): ReLU (inplace), weights=(), parameters=0
# (12): MaxPool2d (size=(3, 3), stride=(2, 2), dilation=(1, 1)), weights=(), parameters=0
# ), weights=((64, 3, 11, 11), (64,), (192, 64, 5, 5), (192,), (384, 192, 3, 3), (384,), (256, 384, 3, 3), (256,), (256, 256, 3, 3), (256,)), parameters=2469696
# (classifier): Sequential (
# (0): Dropout (p = 0.5), weights=(), parameters=0
# (1): Linear (9216 -> 4096), weights=((4096, 9216), (4096,)), parameters=37752832
# (2): ReLU (inplace), weights=(), parameters=0
# (3): Dropout (p = 0.5), weights=(), parameters=0
# (4): Linear (4096 -> 4096), weights=((4096, 4096), (4096,)), parameters=16781312
# (5): ReLU (inplace), weights=(), parameters=0
# (6): Linear (4096 -> 1000), weights=((1000, 4096), (1000,)), parameters=4097000
# ), weights=((4096, 9216), (4096,), (4096, 4096), (4096,), (1000, 4096), (1000,)), parameters=58631144
# )
Edit: isaykatsman has a pytorch PR to add a model.summary()
that is exactly like keras https://github.com/pytorch/pytorch/pull/3043/files
Path.GetDirectoryName()
... but you need to know that the path you are passing to it does contain a file name; it simply removes the final bit from the path, whether it is a file name or directory name (it actually has no idea which).
You could validate first by testing File.Exists()
and/or Directory.Exists()
on your path first to see if you need to call Path.GetDirectoryName
Hi Please find the answer below.this is done by validating the date newly created
var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
|| d.getMonth() != (month - 1)
|| d.getDate() != date) {
alert("invalid date");
return false;
}
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
@SuppressWarnings("unchecked")
public static <E,T> E[] hashMapKeysToArray(HashMap<E,T> map)
{
int s;
if(map == null || (s = map.size())<1)
return null;
E[] temp;
E typeHelper;
try
{
Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
Entry<E, T> iK = iterator.next();
typeHelper = iK.getKey();
Object o = Array.newInstance(typeHelper.getClass(), s);
temp = (E[]) o;
int index = 0;
for (Map.Entry<E,T> mapEntry : map.entrySet())
{
temp[index++] = mapEntry.getKey();
}
}
catch (Exception e)
{
return null;
}
return temp;
}
//--------------------------------------------------------
@SuppressWarnings("unchecked")
public static <E,T> T[] hashMapValuesToArray(HashMap<E,T> map)
{
int s;
if(map == null || (s = map.size())<1)
return null;
T[] temp;
T typeHelper;
try
{
Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
Entry<E, T> iK = iterator.next();
typeHelper = iK.getValue();
Object o = Array.newInstance(typeHelper.getClass(), s);
temp = (T[]) o;
int index = 0;
for (Map.Entry<E,T> mapEntry : map.entrySet())
{
temp[index++] = mapEntry.getValue();
}
}
catch (Exception e)
{return null;}
return temp;
}
First, unzip the APK and extract the file /META-INF/ANDROID_.RSA (this file may also be CERT.RSA, but there should only be one .RSA file).
Then issue this command:
keytool -printcert -file ANDROID_.RSA
You will get certificate fingerprints like this:
MD5: B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB
SHA1: 16:59:E7:E3:0C:AA:7A:0D:F2:0D:05:20:12:A8:85:0B:32:C5:4F:68
Signature algorithm name: SHA1withRSA
Then use the keytool again to print out all the aliases of your signing keystore:
keytool -list -keystore my-signing-key.keystore
You will get a list of aliases and their certificate fingerprint:
android_key, Jan 23, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB
Voila! we can now determined the apk has been signed with this keystore, and with the alias 'android_key'.
Keytool is part of Java, so make sure your PATH has Java installation dir in it.
Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.
$ man memset
MEMSET(3) BSD Library Functions Manual MEMSET(3)
NAME
memset -- fill a byte string with a byte value
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <string.h>
void *
memset(void *b, int c, size_t len);
Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>
/<cstdio>
/<cstdlib>
/etc, rather than C's <string.h>
/<stdio.h>
/<stdlib.h>
/etc.
As of 2017, an easy method to achieve this is the following:
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
# Code of your program here
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
If you are using Python 2.x, then you should replace the last line for:
ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1)
Also note that if you converted you python script into an executable file (using tools like py2exe
, cx_freeze
, pyinstaller
) then you should use sys.argv[1:]
instead of sys.argv
in the fourth parameter.
Some of the advantages here are:
ctypes
and sys
from standard library.Documentation for the underlying ShellExecute call is here.
In my experience, using a PYTHONPATH variable at all is usually the wrong approach, because it does not play nicely with VENV on windows. PYTHON on loading will prepare the path by prepending PYTHONPATH to the path, which can result in your carefully prepared Venv preferentially fetching global site packages.
Instead of using PYTHON path, include a pythonpath.pth file in the relevant site-packages directory (although beware custom pythons occasionally look for them in different locations, e.g. enthought looks in the same directory as python.exe for its .pth files) with each virtual environment. This will act like a PYTHONPATH only it will be specific to the python installation, so you can have a separate one for each python installation/environment. Pycharm integrates strongly with VENV if you just go to yse the VENV's python as your python installation.
See e.g. this SO question for more details on .pth files....
That tool is part of the setuptools (now called Distribute) package. Install Distribute. Of course you'll have to fetch that one manually.
http://pypi.python.org/pypi/distribute#installation-instructions
It is possible and you don't need to code it on your own.
Just set the ringer volume to zero and vibration to none if incomingNumber equals an empty string. Thats it ...
Its just done for you with the application Nostalk from Android Market. Just give it a try ...
In my case function eval() works very good. Below I generate 10 variables and assign them 10 values.
lhs <- rnorm(10)
rhs <- paste("perf.a", 1:10, "<-", lhs, sep="")
eval(parse(text=rhs))
You can use :
composer self-update --2
To update to 2.0.8 version (Latest stable version)
You're not using splice correctly:
arr.splice(4, 1)
this will remove 1 item at index 4. see here
I think you want to use slice:
arr.slice(0,5)
this will return elements in position 0 through 4.
This assumes all the rest of your code (cookies etc) works correctly
public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
if (inputStream.isPresent()) {
ByteArrayOutputStream outpString base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
Then you can do whatever you like with the bytes like:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));ut = new ByteArrayOutputStream();
FileCopyUtils.copy(inputStream.get(), output);
//TODO retrieve content type from file, & replace png below with it
return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
}
return Optional.empty();
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
ObjC
NSDate *date = [NSDate date];
NSInteger era, year, month, day;
[[NSCalendar currentCalendar] getEra:&era year:&year month:&month day:&day fromDate:date];
Swift
let date = NSDate.init()
var era = 0, year = 0, month = 0, day = 0
NSCalendar.currentCalendar().getEra(&era, year:&year, month:&month, day:&day, fromDate: date)
If uploading an image, try reducing the image quality, which is the second parameter of the Bitmap. This was the solution in my case. Previously it was 90, then I tried with 60 (as it is in the code below now).
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
finalBitmap.compress(Bitmap.CompressFormat.JPEG,60,baos);
byte[] b = baos.toByteArray();
Try this
-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
You can see it in http://jsfiddle.net/wJ7qp/
I know this is a very old question, but here is another sed variation, which may be useful to someone. Unlike some of the others, it only replaces double quotes at the start or end...
echo "$opt" | sed -r 's/^"|"$//g'
you can also use this if you know the name of the primary key
SELECT
MAX(primary_key_name) + 1
FROM
TABLE_NAME
APC is going to be included in PHP 6, and I'd guess it has been chosen for good reason :)
It's fairly easy to install and certainly speeds things up.
>>> lst = ['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r']
>>> print [lst[2*i]+lst[2*i+1] for i in range(len(lst)/2)]
['abcde', 'fghijklmn', 'opqr']
Parameters passed to the C program executable is nothing but an array of string(or character pointer),so memory would have been already allocated for these input parameter before your program access these parameters,so no need to allocate buffer,and that way you can avoid error handling code in your program as well(Reduce chances of segfault :)).
echo "mydir/doc/ mydir/usoe ./mydir/usm" | awk '{ split($0,array," "); for(i in array){ system("cd "array[i]" && echo $PWD") } }'
You can try below query,
select * from players
where
us_reg_date between '2000-07-05'
and
DATE_ADD('2011-11-10',INTERVAL 1 DAY)
In general, there is no way to know when something on another site has been changed. If the site offers an RSS feed, you should try that. If the site does not offer an RSS feed (or if the RSS feed doesn't include the information you're looking for), then you have to scrape and compare.
I have tested the following regex which gives the same result as Chrome Html email input validation.
[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*
You can test it out on this website: regex101
If you want to remove duplicates from ArrayList means find the below logic,
public static Object[] removeDuplicate(Object[] inputArray)
{
long startTime = System.nanoTime();
int totalSize = inputArray.length;
Object[] resultArray = new Object[totalSize];
int newSize = 0;
for(int i=0; i<totalSize; i++)
{
Object value = inputArray[i];
if(value == null)
{
continue;
}
for(int j=i+1; j<totalSize; j++)
{
if(value.equals(inputArray[j]))
{
inputArray[j] = null;
}
}
resultArray[newSize++] = value;
}
long endTime = System.nanoTime()-startTime;
System.out.println("Total Time-B:"+endTime);
return resultArray;
}
Here, add this line to .zshrc
:
export PATH=/home/david/pear/bin:$PATH
EDIT: This does work, but ony's answer below is better, as it takes advantage of the structured interface ZSH provides for variables like $PATH
. This approach is standard for bash
, but as far as I know, there is no reason to use it when ZSH provides better alternatives.
I had a similar-looking problem after adding a directory tree which contained .svn directories (because it was an svn:external in its source environment): svn status told me "?", but when trying to add it, it was "already under version control".
Since no other versioned directories were present, I did
find . -mindepth 2 -name '.svn' -exec rm -rf '{}' \;
to remove the wrong .svn directories; after doing this, I was able to add the new directory.
Note:
ser.read(64)
should be ser.read(size=64)
; ser.read uses keyword arguments, not positional.
Also, you're reading from the port twice; what you probably want to do is this:
i=0
for modem in PortList:
for port in modem:
try:
ser = serial.Serial(port, 9600, timeout=1)
ser.close()
ser.open()
ser.write("ati")
time.sleep(3)
read_val = ser.read(size=64)
print read_val
if read_val is not '':
print port
except serial.SerialException:
continue
i+=1
you can do it by following way too ..
create table #test (a int, b char(1))
select * From #test
exec tempdb..sp_columns '#test'
I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)
This is for reading images from Azure Cognative Services's Vision API
const subscriptionKey = 'your_azure_subscrition_key';
const uriBase = // **MUST change your location (mine is 'eastus')**
'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';
// Request parameters.
const params = {
'visualFeatures': 'Categories,Description,Adult,Faces',
'maxCandidates': '2',
'details': 'Celebrities,Landmarks',
'language': 'en'
};
const options = {
uri: uriBase,
qs: params,
body: fs.readFileSync(./my_local_image_path.jpg),
headers: {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonString = JSON.stringify(JSON.parse(body), null, ' ');
body = JSON.parse(body);
if (body.code) // err
{
console.log("AZURE: " + body.message)
}
console.log('Response\n' + jsonString);
There is a JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.
In my case, I had a textbox that was attached to a datepicker. The only solution that worked for me was to handle it inside the onSelect event of the datepicker.
<input type="text" id="bookdate">
$("#bookdate").datepicker({
onSelect: function (selected) {
//handle change event here
}
});
A simple utility function for both id and class selector.
function exist(IdOrClassName, IsId) {
var elementExit = false;
if (IsId) {
elementExit = $("#" + "" + IdOrClassName + "").length ? true : false;
} else {
elementExit = $("." + "" + IdOrClassName + "").length ? true : false;
}
return elementExit;
}
calling this function like bellow
$(document).ready(function() {
$("#btnCheck").click(function() {
//address is the id so IsId is true. if address is class then need to set IsId false
if (exist("address", true)) {
alert("exist");
} else {
alert("not exist");
}
});
});
In C++, you can use a such function:
template <typename T>
T to(const std::string & s)
{
std::istringstream stm(s);
T result;
stm >> result;
if(stm.tellg() != s.size())
throw error;
return result;
}
This can help you to convert any string to any type such as float, int, double...
There is a typo in your SQL. Fixed version is below:
SELECT GETVARIABLE('SYSIBM.VERSION') FROM SYSIBM.SYSDUMMY1;
I ran this on the IBM Mainframe under Z/OS in QMF and got the following results. We are currently running DB2 Version 8 and upgrading to Ver 10.
DSN08015 -- Format seems to be DSNVVMMM
-- PPP IS PRODUCT STRING 'DSN'
-- VV IS VERSION NUMBER E.G. 08
-- MMM IS MAINTENANCE LEVEL E.G. 015
Not really, you have to assign a variable. So
var bar = Stuff.Elements.Foo;
bar.Name = "Bob Dylan";
bar.Age = 68;
bar.Location = "On Tour";
bar.IsCool = True;
Or in C# 3.0:
var bar = Stuff.Elements.Foo
{
Name = "Bob Dylan",
Age = 68,
Location = "On Tour",
IsCool = True
};
Use "%%"
. The man page describes this requirement:
%
A '%' is written. No argument is converted. The complete conversion specification is '%%
'.
If you use eg. "id" you can do it this way:
(function() {_x000D_
let x = document.getElementById("idName");_x000D_
let y = document.getElementById("liName");_x000D_
_x000D_
y.addEventListener('click', function(e) {_x000D_
y.appendChild(x);_x000D_
});_x000D_
_x000D_
_x000D_
})();
_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<title></title>_x000D_
<meta charset="UTF-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p id="idName">TEXT</p>_x000D_
<ul>_x000D_
<li id="liName">_x000D_
_x000D_
</li>_x000D_
</ul>_x000D_
</body>_x000D_
<script src="js/scripts/script.js"></script>_x000D_
_x000D_
</html>
_x000D_
Time 30 minutes later
$newTime = date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s")." +30 minutes"))
If you want just the summary of the exception use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you want to see the whole stack trace (usually better for debugging) use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Another method I sometime use is:
private DoSomthing(int arg1, int arg2, out string errorMessage)
{
int result ;
errorMessage = String.Empty;
try
{
//do stuff
int result = 42;
}
catch (Exception ex)
{
errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
result = -1;
}
return result;
}
And In your form you will have something like:
string ErrorMessage;
int result = DoSomthing(1, 2, out ErrorMessage);
if (!String.IsNullOrEmpty(ErrorMessage))
{
MessageBox.Show(ErrorMessage);
}
There is a bit of a contradiction in the question's title and the content. The title speaks of a parent div, but the question makes it sound like you want two sibling divs (navigation and content) to be the same height.
Do you (a) want both navigation and content to be 100% the height of main, or (b) want navigation and content to be be same height?
I'll assume (b)...if that is so, I don't think you will be able to do it given your current page structure (at least, not with pure CSS and no scripting). You would probably need to do something like:
<main div>
<content div>
<navigation div></div>
</div>
</div>
and set the content div to have a left margin of whatever the width of the navigation pane is. That way, the content's content is to the right of the navigation and you can set the navigation div to be 100% of the content's height.
EDIT: I'm doing this completely in my head, but you would probably also need to set the navigation div's left margin to a negative value or set it's absolute left to 0 to shove it back to the far left. Problem is, there are many ways to pull this off but not all of them are going to be compatible with all browsers.
I also found that the unit test code should put under the test folder, it can not be recognized as test class if you put it under the main folder. eg.
Wrong
/my_program/src/main/java/NotTest.java
Right
/my_program/src/test/java/MyTest.java
Sure it is OK. Actually you can see for yourself easily:
l = range(12000)
l = sorted(l, reverse=True)
Running the those lines on my machine took:
real 0m0.036s
user 0m0.024s
sys 0m0.004s
But sure as everyone else said. The larger the array the slower the operations will be.
Many answers using external programs, which is not really using Bash
.
If you know you will have Bash4 available you should really just use the ${VAR,,}
notation (it is easy and cool). For Bash before 4 (My Mac still uses Bash 3.2 for example). I used the corrected version of @ghostdog74 's answer to create a more portable version.
One you can call lowercase 'my STRING'
and get a lowercase version. I read comments about setting the result to a var, but that is not really portable in Bash
, since we can't return strings. Printing it is the best solution. Easy to capture with something like var="$(lowercase $str)"
.
How this works
The way this works is by getting the ASCII integer representation of each char with printf
and then adding 32
if upper-to->lower
, or subtracting 32
if lower-to->upper
. Then use printf
again to convert the number back to a char. From 'A' -to-> 'a'
we have a difference of 32 chars.
Using printf
to explain:
$ printf "%d\n" "'a"
97
$ printf "%d\n" "'A"
65
97 - 65 = 32
And this is the working version with examples.
Please note the comments in the code, as they explain a lot of stuff:
#!/bin/bash
# lowerupper.sh
# Prints the lowercase version of a char
lowercaseChar(){
case "$1" in
[A-Z])
n=$(printf "%d" "'$1")
n=$((n+32))
printf \\$(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
# Prints the lowercase version of a sequence of strings
lowercase() {
word="$@"
for((i=0;i<${#word};i++)); do
ch="${word:$i:1}"
lowercaseChar "$ch"
done
}
# Prints the uppercase version of a char
uppercaseChar(){
case "$1" in
[a-z])
n=$(printf "%d" "'$1")
n=$((n-32))
printf \\$(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
# Prints the uppercase version of a sequence of strings
uppercase() {
word="$@"
for((i=0;i<${#word};i++)); do
ch="${word:$i:1}"
uppercaseChar "$ch"
done
}
# The functions will not add a new line, so use echo or
# append it if you want a new line after printing
# Printing stuff directly
lowercase "I AM the Walrus!"$'\n'
uppercase "I AM the Walrus!"$'\n'
echo "----------"
# Printing a var
str="A StRing WITH mixed sTUFF!"
lowercase "$str"$'\n'
uppercase "$str"$'\n'
echo "----------"
# Not quoting the var should also work,
# since we use "$@" inside the functions
lowercase $str$'\n'
uppercase $str$'\n'
echo "----------"
# Assigning to a var
myLowerVar="$(lowercase $str)"
myUpperVar="$(uppercase $str)"
echo "myLowerVar: $myLowerVar"
echo "myUpperVar: $myUpperVar"
echo "----------"
# You can even do stuff like
if [[ 'option 2' = "$(lowercase 'OPTION 2')" ]]; then
echo "Fine! All the same!"
else
echo "Ops! Not the same!"
fi
exit 0
And the results after running this:
$ ./lowerupper.sh
i am the walrus!
I AM THE WALRUS!
----------
a string with mixed stuff!
A STRING WITH MIXED STUFF!
----------
a string with mixed stuff!
A STRING WITH MIXED STUFF!
----------
myLowerVar: a string with mixed stuff!
myUpperVar: A STRING WITH MIXED STUFF!
----------
Fine! All the same!
This should only work for ASCII characters though.
For me it is fine, since I know I will only pass ASCII chars to it.
I am using this for some case-insensitive CLI options, for example.
Unfortunately, detecting pinch gestures across browsers is a not as simple as one would hope, but HammerJS makes it a lot easier!
Check out the Pinch Zoom and Pan with HammerJS demo. This example has been tested on Android, iOS and Windows Phone.
You can find the source code at Pinch Zoom and Pan with HammerJS.
For your convenience, here is the source code:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport"_x000D_
content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">_x000D_
<title>Pinch Zoom</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div>_x000D_
_x000D_
<div style="height:150px;background-color:#eeeeee">_x000D_
Ignore this area. Space is needed to test on the iPhone simulator as pinch simulation on the_x000D_
iPhone simulator requires the target to be near the middle of the screen and we only respect_x000D_
touch events in the image area. This space is not needed in production._x000D_
</div>_x000D_
_x000D_
<style>_x000D_
_x000D_
.pinch-zoom-container {_x000D_
overflow: hidden;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
.pinch-zoom-image {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
</style>_x000D_
_x000D_
<script src="https://hammerjs.github.io/dist/hammer.js"></script>_x000D_
_x000D_
<script>_x000D_
_x000D_
var MIN_SCALE = 1; // 1=scaling when first loaded_x000D_
var MAX_SCALE = 64;_x000D_
_x000D_
// HammerJS fires "pinch" and "pan" events that are cumulative in nature and not_x000D_
// deltas. Therefore, we need to store the "last" values of scale, x and y so that we can_x000D_
// adjust the UI accordingly. It isn't until the "pinchend" and "panend" events are received_x000D_
// that we can set the "last" values._x000D_
_x000D_
// Our "raw" coordinates are not scaled. This allows us to only have to modify our stored_x000D_
// coordinates when the UI is updated. It also simplifies our calculations as these_x000D_
// coordinates are without respect to the current scale._x000D_
_x000D_
var imgWidth = null;_x000D_
var imgHeight = null;_x000D_
var viewportWidth = null;_x000D_
var viewportHeight = null;_x000D_
var scale = null;_x000D_
var lastScale = null;_x000D_
var container = null;_x000D_
var img = null;_x000D_
var x = 0;_x000D_
var lastX = 0;_x000D_
var y = 0;_x000D_
var lastY = 0;_x000D_
var pinchCenter = null;_x000D_
_x000D_
// We need to disable the following event handlers so that the browser doesn't try to_x000D_
// automatically handle our image drag gestures._x000D_
var disableImgEventHandlers = function () {_x000D_
var events = ['onclick', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover',_x000D_
'onmouseup', 'ondblclick', 'onfocus', 'onblur'];_x000D_
_x000D_
events.forEach(function (event) {_x000D_
img[event] = function () {_x000D_
return false;_x000D_
};_x000D_
});_x000D_
};_x000D_
_x000D_
// Traverse the DOM to calculate the absolute position of an element_x000D_
var absolutePosition = function (el) {_x000D_
var x = 0,_x000D_
y = 0;_x000D_
_x000D_
while (el !== null) {_x000D_
x += el.offsetLeft;_x000D_
y += el.offsetTop;_x000D_
el = el.offsetParent;_x000D_
}_x000D_
_x000D_
return { x: x, y: y };_x000D_
};_x000D_
_x000D_
var restrictScale = function (scale) {_x000D_
if (scale < MIN_SCALE) {_x000D_
scale = MIN_SCALE;_x000D_
} else if (scale > MAX_SCALE) {_x000D_
scale = MAX_SCALE;_x000D_
}_x000D_
return scale;_x000D_
};_x000D_
_x000D_
var restrictRawPos = function (pos, viewportDim, imgDim) {_x000D_
if (pos < viewportDim/scale - imgDim) { // too far left/up?_x000D_
pos = viewportDim/scale - imgDim;_x000D_
} else if (pos > 0) { // too far right/down?_x000D_
pos = 0;_x000D_
}_x000D_
return pos;_x000D_
};_x000D_
_x000D_
var updateLastPos = function (deltaX, deltaY) {_x000D_
lastX = x;_x000D_
lastY = y;_x000D_
};_x000D_
_x000D_
var translate = function (deltaX, deltaY) {_x000D_
// We restrict to the min of the viewport width/height or current width/height as the_x000D_
// current width/height may be smaller than the viewport width/height_x000D_
_x000D_
var newX = restrictRawPos(lastX + deltaX/scale,_x000D_
Math.min(viewportWidth, curWidth), imgWidth);_x000D_
x = newX;_x000D_
img.style.marginLeft = Math.ceil(newX*scale) + 'px';_x000D_
_x000D_
var newY = restrictRawPos(lastY + deltaY/scale,_x000D_
Math.min(viewportHeight, curHeight), imgHeight);_x000D_
y = newY;_x000D_
img.style.marginTop = Math.ceil(newY*scale) + 'px';_x000D_
};_x000D_
_x000D_
var zoom = function (scaleBy) {_x000D_
scale = restrictScale(lastScale*scaleBy);_x000D_
_x000D_
curWidth = imgWidth*scale;_x000D_
curHeight = imgHeight*scale;_x000D_
_x000D_
img.style.width = Math.ceil(curWidth) + 'px';_x000D_
img.style.height = Math.ceil(curHeight) + 'px';_x000D_
_x000D_
// Adjust margins to make sure that we aren't out of bounds_x000D_
translate(0, 0);_x000D_
};_x000D_
_x000D_
var rawCenter = function (e) {_x000D_
var pos = absolutePosition(container);_x000D_
_x000D_
// We need to account for the scroll position_x000D_
var scrollLeft = window.pageXOffset ? window.pageXOffset : document.body.scrollLeft;_x000D_
var scrollTop = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;_x000D_
_x000D_
var zoomX = -x + (e.center.x - pos.x + scrollLeft)/scale;_x000D_
var zoomY = -y + (e.center.y - pos.y + scrollTop)/scale;_x000D_
_x000D_
return { x: zoomX, y: zoomY };_x000D_
};_x000D_
_x000D_
var updateLastScale = function () {_x000D_
lastScale = scale;_x000D_
};_x000D_
_x000D_
var zoomAround = function (scaleBy, rawZoomX, rawZoomY, doNotUpdateLast) {_x000D_
// Zoom_x000D_
zoom(scaleBy);_x000D_
_x000D_
// New raw center of viewport_x000D_
var rawCenterX = -x + Math.min(viewportWidth, curWidth)/2/scale;_x000D_
var rawCenterY = -y + Math.min(viewportHeight, curHeight)/2/scale;_x000D_
_x000D_
// Delta_x000D_
var deltaX = (rawCenterX - rawZoomX)*scale;_x000D_
var deltaY = (rawCenterY - rawZoomY)*scale;_x000D_
_x000D_
// Translate back to zoom center_x000D_
translate(deltaX, deltaY);_x000D_
_x000D_
if (!doNotUpdateLast) {_x000D_
updateLastScale();_x000D_
updateLastPos();_x000D_
}_x000D_
};_x000D_
_x000D_
var zoomCenter = function (scaleBy) {_x000D_
// Center of viewport_x000D_
var zoomX = -x + Math.min(viewportWidth, curWidth)/2/scale;_x000D_
var zoomY = -y + Math.min(viewportHeight, curHeight)/2/scale;_x000D_
_x000D_
zoomAround(scaleBy, zoomX, zoomY);_x000D_
};_x000D_
_x000D_
var zoomIn = function () {_x000D_
zoomCenter(2);_x000D_
};_x000D_
_x000D_
var zoomOut = function () {_x000D_
zoomCenter(1/2);_x000D_
};_x000D_
_x000D_
var onLoad = function () {_x000D_
_x000D_
img = document.getElementById('pinch-zoom-image-id');_x000D_
container = img.parentElement;_x000D_
_x000D_
disableImgEventHandlers();_x000D_
_x000D_
imgWidth = img.width;_x000D_
imgHeight = img.height;_x000D_
viewportWidth = img.offsetWidth;_x000D_
scale = viewportWidth/imgWidth;_x000D_
lastScale = scale;_x000D_
viewportHeight = img.parentElement.offsetHeight;_x000D_
curWidth = imgWidth*scale;_x000D_
curHeight = imgHeight*scale;_x000D_
_x000D_
var hammer = new Hammer(container, {_x000D_
domEvents: true_x000D_
});_x000D_
_x000D_
hammer.get('pinch').set({_x000D_
enable: true_x000D_
});_x000D_
_x000D_
hammer.on('pan', function (e) {_x000D_
translate(e.deltaX, e.deltaY);_x000D_
});_x000D_
_x000D_
hammer.on('panend', function (e) {_x000D_
updateLastPos();_x000D_
});_x000D_
_x000D_
hammer.on('pinch', function (e) {_x000D_
_x000D_
// We only calculate the pinch center on the first pinch event as we want the center to_x000D_
// stay consistent during the entire pinch_x000D_
if (pinchCenter === null) {_x000D_
pinchCenter = rawCenter(e);_x000D_
var offsetX = pinchCenter.x*scale - (-x*scale + Math.min(viewportWidth, curWidth)/2);_x000D_
var offsetY = pinchCenter.y*scale - (-y*scale + Math.min(viewportHeight, curHeight)/2);_x000D_
pinchCenterOffset = { x: offsetX, y: offsetY };_x000D_
}_x000D_
_x000D_
// When the user pinch zooms, she/he expects the pinch center to remain in the same_x000D_
// relative location of the screen. To achieve this, the raw zoom center is calculated by_x000D_
// first storing the pinch center and the scaled offset to the current center of the_x000D_
// image. The new scale is then used to calculate the zoom center. This has the effect of_x000D_
// actually translating the zoom center on each pinch zoom event._x000D_
var newScale = restrictScale(scale*e.scale);_x000D_
var zoomX = pinchCenter.x*newScale - pinchCenterOffset.x;_x000D_
var zoomY = pinchCenter.y*newScale - pinchCenterOffset.y;_x000D_
var zoomCenter = { x: zoomX/newScale, y: zoomY/newScale };_x000D_
_x000D_
zoomAround(e.scale, zoomCenter.x, zoomCenter.y, true);_x000D_
});_x000D_
_x000D_
hammer.on('pinchend', function (e) {_x000D_
updateLastScale();_x000D_
updateLastPos();_x000D_
pinchCenter = null;_x000D_
});_x000D_
_x000D_
hammer.on('doubletap', function (e) {_x000D_
var c = rawCenter(e);_x000D_
zoomAround(2, c.x, c.y);_x000D_
});_x000D_
_x000D_
};_x000D_
_x000D_
</script>_x000D_
_x000D_
<button onclick="zoomIn()">Zoom In</button>_x000D_
<button onclick="zoomOut()">Zoom Out</button>_x000D_
_x000D_
<div class="pinch-zoom-container">_x000D_
<img id="pinch-zoom-image-id" class="pinch-zoom-image" onload="onLoad()"_x000D_
src="https://hammerjs.github.io/assets/img/pano-1.jpg">_x000D_
</div>_x000D_
_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService
" as the service reference name, that will generate the type TestUploaderWebService.Service1
. That class will have a method named GetFileListOnWebServer
, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:
string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
proxy = new TestUploaderWebService.Service1();
files = proxy.GetFileListOnWebServer();
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.
Just use an <a>
by itself, set it to display: block;
and set width
and height
. Get rid of the <span>
and <div>
. This is the semantic way to do it. There is no need to wrap things in <divs>
(or any element) for layout. That is what CSS is for.
Demo: http://jsfiddle.net/ThinkingStiff/89Enq/
HTML:
<a id="music" href="Music.html">Music I Like</a>
CSS:
#music {
background-color: black;
color: white;
display: block;
height: 40px;
line-height: 40px;
text-decoration: none;
width: 100px;
text-align: center;
}
Output:
I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.
Open Installation Details:
Choose Plug-ins tab => type org.eclipse.platform => check Version column.
You can match version code and version name on https://wiki.eclipse.org/Older_Versions_Of_Eclipse
For example, check out GitEye (Git GUI client)
Or checkout DBBeaver (DB manager):
change_column_default :employees, :foreign, false
I assume that you haven't set the TableName
property of the DataTable, for example via constructor:
var tbl = new DataTable("dtImage");
If you don't provide a name, it will be automatically created with "Table1"
, the next table will get "Table2"
and so on.
Then the solution would be to provide the TableName
and then check with Contains(nameOfTable)
.
To clarify it: You'll get an ArgumentException
if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException
if there's already a DataTable in the DataSet with the same name(not case-sensitive).
Try remove_missing
instead with vars = the_variable
. It is very important that you set the vars
argument, otherwise remove_missing
will remove all rows that contain an NA
in any column!! Setting na.rm = TRUE
will suppress the warning message.
ggplot(data = remove_missing(MyData, na.rm = TRUE, vars = the_variable),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) +
geom_bar(stat="bin")
The syntax for ng if else in angular is :
<div class="case" *ngIf="data.id === '5'; else elsepart; ">
<input type="checkbox" id="{{data.id}}" value="{{data.displayName}}"
data-ng-model="customizationCntrl.check[data.id1]" data-ng-checked="
{{data.status}}=='1'" onclick="return false;">{{data.displayName}}<br>
</div>
<ng-template #elsepart>
<div class="case">
<input type="checkbox" id="{{data.id}}" value={{data.displayName}}"
data-ng-model="customizationCntrl.check[data.id]" data-ng-checked="
{{data.status}}=='1'">{{data.displayName}}<br>
</div>
</ng-template>
I'm running an ASP.NET MVC 5 application on IIS 8.5. I tried all the variations posted here, and this is what my web.config
looks like:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="WebDAV" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
I couldn't uninstall WebDav from my Server because I didn't have admin privileges. Also, sometimes I was getting the method not allowed
on .css and .js files. In the end, with the configuration above set up everything started working again.
ByteArrayInputStream
extends InputStream
:
InputStream myInputStream = new ByteArrayInputStream(myBytes);
You may need read this https://developer.android.com/guide/topics/resources/drawable-resource.html#Shape
and below there is a Note.
Note Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero ("0dp") where you don't want rounded corners.
The problem may be that ssh is trying to connect to all the different IPs that www.google.com
resolves to. For example on my machine:
# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out
If I run it with a specific IP, it returns much faster.
EDIT: I've timed it (with time
) and the results are:
var x = parseInt(455/10);
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)
You can use DataSet.Tables(0).Columns.Contains(name)
to check whether the DataTable
contains a column with a particular name.
What is wrong with List<T>.Sort()
?
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort#overloads
It is safe to assume that popular handsets are WVGA800 or bigger. Although, there are a good amount of HVGA screens, they are of secondary concern.
List of android screen sizes
http://developer.android.com/guide/practices/screens_support.html
Aspect ratio calculator
I'm getting the following error when compiling Adam Rosenfield's code on Windows. It turns out few things are missing from the code.
Error (Before)
C:\C\Codes>gcc time.c -o time
time.c:3:12: error: initializer element is not constant
time_t t = time(NULL);
^
time.c:4:16: error: initializer element is not constant
struct tm tm = *localtime(&t);
^
time.c:6:8: error: expected declaration specifiers or '...' before string constant
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:36: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:55: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:70: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:82: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:94: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:105: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
C:\C\Codes>
Solution
C:\C\Codes>more time.c
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}
C:\C\Codes>
Compiling
C:\C\Codes>gcc time.c -o time
C:\C\Codes>
Final Output
C:\C\Codes>time
now: 2018-3-11 15:46:36
C:\C\Codes>
I hope this will helps others too
The solution is very simple if we consider the type of the constant value, which should be "unsigned int" instead of "int".
Instead of:
setval(0)
Use:
setval(0u)
The suffix "u" tell the compiler this is a unsigned integer. Then, no conversion would be needed, and the call will be unambiguous.
For anyone reading this who is using EclipseLink for JPA 2.0, here are the two annotations I had to use to get JPA to persist data, where "MySequenceGenerator" is whatever name you want to give the generator, "myschema" is the name of the schema in your database that contains the sequence object, and "mysequence" is the name of the sequence object in the database.
@GeneratedValue(strategy= GenerationType.SEQUENCE, generator="MySequenceGenerator")
@SequenceGenerator(allocationSize=1, schema="myschema", name="MySequenceGenerator", sequenceName = "mysequence")
For those using EclipseLink (and possibly other JPA providers), it is CRITICAL that you set the allocationSize attribute to match the INCREMENT value defined for your sequence in the database. If you don't, you'll get a generic persistence failure, and waste a good deal of time trying to track it down, like I did. Here is the reference page that helped me overcome this challenge:
http://wiki.eclipse.org/EclipseLink/Examples/JPA/PrimaryKey#Using_Sequence_Objects
Also, to give context, here is what we're using:
Java 7 Glassfish 3.1 PostgreSQL 9.1 PrimeFaces 3.2/JSF 2.1
Also, for laziness' sake, I built this in Netbeans with the wizards for generating Entities from DB, Controllers from Entities, and JSF from Entities, and the wizards (obviously) do not know how to deal with sequence-based ID columns, so you'll have to manually add these annotations.
You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:
var config=document.getElementsByName('configselect').value;
because you have declared only the name
attribute in your <select>
tag. So you should get this element by name.
After correcting this, it will run without any JavaScript error
Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:
>>> 0.4/100.
0.0040000000000000001
If you actually want a decimal value, do this:
>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")
That will give you an object that properly knows that 4 / 100 in base 10 is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.
It may be relevant to see if it's running in PHP via command line as well-
<path-to-php-binary>php -i | grep memcache
I faced the same issue as the author of the question. For our case answers in this question weren't enough since each of the members of my team had a different local environment and we definitely needed to .gitignore
the file that had the different db connection string and credentials, so people don't commit the common file by mistake and break others' db connections.
On top of that when we followed the procedure below it was easy to deploy on different environments and as en extra bonus we didn't need to have any sensitive information in the version control at all.
Getting the idea from PHP Symfony 3 framework that has a parameters.yml
(.gitignored) and a parameters.yml.dist
(which is a sample that creates the first one through composer install
),
I did the following combining the knowledge from answers below: https://stackoverflow.com/a/35534970/986160 and https://stackoverflow.com/a/35535138/986160.
Essentially this gives the freedom to use inheritance of spring configurations and choose active profiles through configuration at the top one plus any extra sensitive credentials as follows:
spring:
profiles:
active: local/dev/prod
datasource:
username:
password:
url: jdbc:mysql://localhost:3306/db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring:
profiles:
active: dev
datasource:
username: root
password: verysecretpassword
url: jdbc:mysql://localhost:3306/real_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring:
profiles:
active: dev
datasource:
username: root
password: rootroot
url: jdbc:mysql://localhost:3306/xampp_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring:
datasource:
testWhileIdle: true
validationQuery: SELECT 1
jpa:
show-sql: true
format-sql: true
hibernate:
ddl-auto: create-droop
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL57InnoDBDialect
Same can be done with .properties
Static variable retains it's previous value until the program exit. Static is used by calling directly class_Name.Method() or class_Name.Property. No object reference is needed. The most popular use of static is C#'s Math class. Math.Sin(), Math.Cos(), Math.Sqrt().
In case anyone is still struggling with this, as I was all morning today, I have found a solution that works for me:
Installation instructions:
git clone https://github.com/gstarnberger/uncompyle.git
cd uncompyle/
sudo ./setup.py install
Once the program is installed (note: it will be installed to your system-wide-accessible Python packages, so it should be in your $PATH
), you can recover your Python files like so:
uncompyler.py thank_goodness_this_still_exists.pyc > recovered_file.py
The decompiler adds some noise mostly in the form of comments, however I've found it to be surprisingly clean and faithful to my original code. You will have to remove a little line of text beginning with +++ near the end of the recovered file to be able to run your code.
void ul2chardec(char*pcIP, unsigned long ulIPN){
int i; int k=0; char c0, c1;
for (i = 0; i<4; i++){
c0 = ((((ulIPN & (0xff << ((3 - i) * 8))) >> ((3 - i) * 8))) / 100) + 0x30;
if (c0 != '0'){ *(pcIP + k) = c0; k++; }
c1 = (((((ulIPN & (0xff << ((3 - i) * 8))) >> ((3 - i) * 8))) % 100) / 10) + 0x30;
if (!(c1 =='0' && c0=='0')){ *(pcIP + k) = c1; k++; }
*(pcIP +k) = (((((ulIPN & (0xff << ((3 - i) * 8)))) >> ((3 - i) * 8))) % 10) + 0x30;
k++;
if (i<3){ *(pcIP + k) = '.'; k++;}
}
*(pcIP + k) = 0; // pcIP should be x10 bytes
}
If you bind events to the onmouseover and onmouseout events in Jquery, you can then trigger that effect using mouseenter().
What are you trying to accomplish?
If you see an out of memory, consider if that is plausible: Do you really need that much memory? If not (i.e. when you don't have huge objects and if you don't need to create millions of objects for some reason), chances are that you have a memory leak.
In Java, this means that you're keeping a reference to an object somewhere even though you don't need it anymore. Common causes for this is forgetting to call close() on resources (files, DB connections, statements and result sets, etc.).
If you suspect a memory leak, use a profiler to find which object occupies all the available memory.
Small addition to @user995502's answer on how to run the program.
g++ player.cpp main.cpp -o main.out && ./main.out
One requirement for remote debugging is that the windows account used to run SSMS be part of the sysadmin role. See this MSDN link: http://msdn.microsoft.com/en-us/library/cc646024%28v=sql.105%29.aspx
Cloud: the hardware running the application scales to meet the demand (potentially crossing multiple machines, networks, etc).
Grid: the application scales to take as much hardware as possible (for example in the hope of finding extra-terrestrial intelligence).
Cluster: this is an old term referring to one OS instance or one DB instance installed across multiple machines. It was done with special OS handling, proprietary drivers, low latency network cards with fat cables, and various hardware bedfellows.
(We love you SGI, but notice that "Cloud" and "Grid" are available to the little guy and your NUMAlink never has been...)
You can do it with a table, like this:
<table width="100%">
<tr>
<td style="width: 50%">Left Text</td>
<td style="width: 50%; text-align: right;">Right Text</td>
</tr>
</table>
Or, you can do it with CSS like this:
<div style="float: left;">
Left text
</div>
<div style="float: right;">
Right text
</div>
The compile()
method is always called at some point; it's the only way to create a Pattern object. So the question is really, why should you call it explicitly? One reason is that you need a reference to the Matcher object so you can use its methods, like group(int)
to retrieve the contents of capturing groups. The only way to get ahold of the Matcher object is through the Pattern object's matcher()
method, and the only way to get ahold of the Pattern object is through the compile()
method. Then there's the find()
method which, unlike matches()
, is not duplicated in the String or Pattern classes.
The other reason is to avoid creating the same Pattern object over and over. Every time you use one of the regex-powered methods in String (or the static matches()
method in Pattern), it creates a new Pattern and a new Matcher. So this code snippet:
for (String s : myStringList) {
if ( s.matches("\\d+") ) {
doSomething();
}
}
...is exactly equivalent to this:
for (String s : myStringList) {
if ( Pattern.compile("\\d+").matcher(s).matches() ) {
doSomething();
}
}
Obviously, that's doing a lot of unnecessary work. In fact, it can easily take longer to compile the regex and instantiate the Pattern object, than it does to perform an actual match. So it usually makes sense to pull that step out of the loop. You can create the Matcher ahead of time as well, though they're not nearly so expensive:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("");
for (String s : myStringList) {
if ( m.reset(s).matches() ) {
doSomething();
}
}
If you're familiar with .NET regexes, you may be wondering if Java's compile()
method is related to .NET's RegexOptions.Compiled
modifier; the answer is no. Java's Pattern.compile()
method is merely equivalent to .NET's Regex constructor. When you specify the Compiled
option:
Regex r = new Regex(@"\d+", RegexOptions.Compiled);
...it compiles the regex directly to CIL byte code, allowing it to perform much faster, but at a significant cost in up-front processing and memory use--think of it as steroids for regexes. Java has no equivalent; there's no difference between a Pattern that's created behind the scenes by String#matches(String)
and one you create explicitly with Pattern#compile(String)
.
(EDIT: I originally said that all .NET Regex objects are cached, which is incorrect. Since .NET 2.0, automatic caching occurs only with static methods like Regex.Matches()
, not when you call a Regex constructor directly. ref)
The following method works perfectly for me, so here's my full implementation:
<img id="my_image" style="display: none;" src="my.png" width="924" height="330" border="0" usemap="#map" />
<map name="map" id="map">
<area shape="poly" coords="774,49,810,21,922,130,920,222,894,212,885,156,874,146" href="#mylink" />
<area shape="poly" coords="649,20,791,157,805,160,809,217,851,214,847,135,709,1,666,3" href="#myotherlink" />
</map>
<script>
$(function(){
var image_is_loaded = false;
$("#my_image").on('load',function() {
$(this).data('width', $(this).attr('width')).data('height', $(this).attr('height'));
$($(this).attr('usemap')+" area").each(function(){
$(this).data('coords', $(this).attr('coords'));
});
$(this).css('width', '100%').css('height','auto').show();
image_is_loaded = true;
$(window).trigger('resize');
});
function ratioCoords (coords, ratio) {
coord_arr = coords.split(",");
for(i=0; i < coord_arr.length; i++) {
coord_arr[i] = Math.round(ratio * coord_arr[i]);
}
return coord_arr.join(',');
}
$(window).on('resize', function(){
if (image_is_loaded) {
var img = $("#my_image");
var ratio = img.width()/img.data('width');
$(img.attr('usemap')+" area").each(function(){
console.log('1: '+$(this).attr('coords'));
$(this).attr('coords', ratioCoords($(this).data('coords'), ratio));
});
}
});
});
</script>
Verified: it works well in Docker 1.7.0.
Don't specify --pull=true
when running the docker build
command
From this thread on reference locally-built image using FROM at dockerfile:
If you want use the local image as the base image, pass without the option
--pull=true
--pull=true
will always attempt to pull a newer version of the image.
here is a method to point
sh -> bash
run this command on terminal
sudo dpkg-reconfigure dash
After this you should see
ls -l /bin/sh
point to /bin/bash (and not to /bin/dash)
Any identifier of the form __name
(at least two leading underscores, at most one trailing underscore) is publicly replaced with _classname__name
, where classname
is the current class name with leading underscore(s) stripped.
Therefore, __name
is private, while _classname__name
is public.
https://docs.python.org/3/tutorial/classes.html#tut-private
class Cat:
def __init__(self, name='unnamed'):
self.name = name
def __print_my_name(self):
print(self.name)
tom = Cat()
tom.__print_my_name() #Error
tom._Cat__print_my_name() #Prints name
I think you've got the most efficient way
def shift(l,n):
n = n % len(l)
return l[-U:] + l[:-U]
You can use the onload=""
HTML attribute and use JavaScript to adjust the opacity style of your element.
Leave your CSS as you proposed. Edit your HTML code to:
<body onload="document.getElementById(test).style.opacity='1'">
<div id="test">
<p>?This is a test</p>
</div>
</body>
This also works to fade-in the complete page when finished loading:
HTML:
<body onload="document.body.style.opacity='1'">
</body>
CSS:
body{
opacity: 0;
transition: opacity 2s;
-webkit-transition: opacity 2s; /* Safari */
}
Check the W3Schools website: transitions and an article for changing styles with JavaScript.
All answers above are correct, However People who are coming from other programming language. The easiest approach to follow will be.
variable = 1
print("length " + format(variable))
If you really want to get the type by name you may use the following:
System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");
Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.
You could try using UpdateVersion by Matt Griffith. It's quite old now, but works well. To use it, you simply need to setup a pre-build event which points at your AssemblyInfo.cs file, and the application will update the version numbers accordingly, as per the command line arguments.
As the application is open-source, I've also created a version to increment the version number using the format (Major version).(Minor version).([year][dayofyear]).(increment). I've put the code for my modified version of the UpdateVersion application on GitHub: https://github.com/munr/UpdateVersion
New Function and apply() together works also
var a=new Function('alert(1);')
a.apply(null)
In my case, passing responsive: false
under options solved the problem. I'm not sure why everybody is telling you to do the opposite, especially since true is the default.
There is a way to SELECT NOTHING that solve your problem.
When you want that Excel SELECT NOTHING do it:
MYDOC.Shapes("Ready").visible=True
MYDOC.Shapes("Ready").Select
MYDOC.Shapes("Ready").visible=False
This HIDE the selection and nothing still selected in your window PLUS: The word "Ready" is shown at the Left Top in your Sheet.
Put all the 6 classes to 6 different projects. Then create jar files of all the 6 projects. In this manner you will get 6 executable jar files.
Preferred way to change the appearance/whatever of row views once the ListView is drawn is to change something in the data ListView draws from (the array of objects that is passed into your Adapter) and make sure to account for that in your getView() function, then redraw the ListView by calling
notifyDataSetChanged();
EDIT: while there is a way to do this, if you need to do this chances are doing something wrong. While are few edge cases I can think about, generally using notifyDataSetChanged()
and other built in mechanisms is a way to go.
EDIT 2: One of the common mistakes people make is trying to come up with their own way to respond to user clicking/selecting a row in the ListView, as in one of the comments to this post. There is an existing way to do this. Here's how:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/* Parameters
parent: The AdapterView where the click happened.
view: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position: The position of the view in the adapter.
id: The row id of the item that was clicked. */
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//your code here
}
});
ListView has a lot of build-in functionality and there is no need to reinvent the wheel for simpler cases. Since ListView extends AdapterView, you can set the same Listeners, such as OnItemClickListener as in the example above.
I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:
data<- rbind(c(480, 780, 431, 295, 670, 360, 190),
c(720, 350, 377, 255, 340, 615, 345),
c(460, 480, 179, 560, 60, 735, 1260),
c(220, 240, 876, 789, 820, 100, 75))
a <- cbind(data[, 1], 1, c(1:4))
b <- cbind(data[, 2], 2, c(1:4))
c <- cbind(data[, 3], 3, c(1:4))
d <- cbind(data[, 4], 4, c(1:4))
e <- cbind(data[, 5], 5, c(1:4))
f <- cbind(data[, 6], 6, c(1:4))
g <- cbind(data[, 7], 7, c(1:4))
data <- as.data.frame(rbind(a, b, c, d, e, f, g))
colnames(data) <-c("Time", "Type", "Group")
data$Type <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))
library(ggplot2)
ggplot(data = data, aes(x = Type, y = Time, fill = Group)) +
geom_bar(stat = "identity") +
opts(legend.position = "none")
In C#/.NET 3.5 you could write a little program to do:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
string controller = context.ConnectedServer;
Console.WriteLine( "Domain Controller:" + controller );
}
This will list all the users in the current domain:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(context))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
foreach (UserPrincipal principal in searcher.FindAll())
{
Console.WriteLine( principal.SamAccountName);
}
}
}
}
Files.exists()
Files.createDirectory()
Files.copy()
Overwriting Existing Files: Files.move()
Files.delete()
Files.walkFileTree() enter link description here
Why not use: CopyOnWriteArraySet from java.util.concurrent?
If you are interested in only selecting one column this will work.
df[["item1"]].to_dict("records")
The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.
df["item1"].to_dict("records")
I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.
I prefer to use the FindItem method and use the value path for locating the item. Make sure your PathSeparator property on the menu matches what you're using in FindItem parameter.
protected void Page_Load(object sender, EventArgs e)
{
// remove manage user accounts menu item for non-admin users.
if (!Page.User.IsInRole("Admin"))
{
MenuItem item = NavigationMenu.FindItem("Users/Manage Accounts");
item.Parent.ChildItems.Remove(item);
}
}
The chapter on CAST and CONVERT on MSDN Books Online, you've missed the right answer by one line.... you can use style no. 121 (ODBC canonical (with milliseconds)) to get the result you're looking for:
SELECT CONVERT(VARCHAR(30), GETDATE(), 121)
This gives me the output of:
2012-04-14 21:44:03.793
Update: based on your updated question - of course this won't work - you're converting a string (this: '4/14/2012 2:44:01 PM'
is just a string - it's NOT a datetime!) to a string......
You need to first convert the string you have to a DATETIME
and THEN convert it back to a string!
Try this:
SELECT CONVERT(VARCHAR(30), CAST('4/14/2012 2:44:01 PM' AS DATETIME), 121)
Now you should get:
2012-04-14 14:44:01.000
All zeroes for the milliseconds, obviously, since your original values didn't include any ....
I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:
Yourhostname here -vvvvvvvvvv
s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state
When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.
The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.
You are clearly sending a certificate. The server is clearly rejecting it.
The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.
This can be easily done by using enumerate function
code-
lst=[1,2,3,4,1,6,7,9,10,1,2]
for index,item in enumerate(lst):
if item==1:
lst[index]=10 #Replaces the item '1' in list with '10'
print(lst)
You could always follow the official guide on how to install Android Studio on Linux. There's even a video you can watch!
https://developer.android.com/studio/install.html
Remember to select Linux in the drop-down box.
To summarise the steps: download Android Studio and extract it and execute studio.sh
to run it. If you're running 64-bit Ubuntu, you will need to run:
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
In order to understand the use of curly braces in import
statements, first, you have to understand the concept of destructuring introduced in ES6
Object destructuring
var bodyBuilder = {
firstname: 'Kai',
lastname: 'Greene',
nickname: 'The Predator'
};
var {firstname, lastname} = bodyBuilder;
console.log(firstname, lastname); // Kai Greene
firstname = 'Morgan';
lastname = 'Aste';
console.log(firstname, lastname); // Morgan Aste
Array destructuring
var [firstGame] = ['Gran Turismo', 'Burnout', 'GTA'];
console.log(firstGame); // Gran Turismo
Using list matching
var [,secondGame] = ['Gran Turismo', 'Burnout', 'GTA'];
console.log(secondGame); // Burnout
Using the spread operator
var [firstGame, ...rest] = ['Gran Turismo', 'Burnout', 'GTA'];
console.log(firstGame);// Gran Turismo
console.log(rest);// ['Burnout', 'GTA'];
Now that we've got that out of our way, in ES6 you can export multiple modules. You can then make use of object destructuring like below.
Let's assume you have a module called module.js
export const printFirstname(firstname) => console.log(firstname);
export const printLastname(lastname) => console.log(lastname);
You would like to import the exported functions into index.js
;
import {printFirstname, printLastname} from './module.js'
printFirstname('Taylor');
printLastname('Swift');
You can also use different variable names like so
import {printFirstname as pFname, printLastname as pLname} from './module.js'
pFname('Taylor');
pLanme('Swift');
This one liner resigns Keyboard from all(any) the UITextField in a UIView
self.view.endEditing(true)
Very easily done with Post build task plugin.
Flexbox spec editor here.
This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.
Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.
Since your header and footer aren't meant to flex, they should both have flex: none;
set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto
, so they start at their auto height and can shrink but not grow, but they're also overflow:visible
by default, which triggers their default min-height:auto
to prevent them from shrinking at all. If you ever set an overflow
on them, the behavior of min-height:auto
changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article>
element.)
You can simplify the <article>
flex
too - just set flex: 1;
and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.
If you don't know what property caused the error, you can, using reflection, loop over all properties:
public static String ShowAllErrors<T>(this HtmlHelper helper) {
StringBuilder sb = new StringBuilder();
Type myType = typeof(T);
PropertyInfo[] propInfo = myType.GetProperties();
foreach (PropertyInfo prop in propInfo) {
foreach (var e in helper.ViewData.ModelState[prop.Name].Errors) {
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "field-validation-error");
div.SetInnerText(e.ErrorMessage);
sb.Append(div.ToString());
}
}
return sb.ToString();
}
Where T is the type of your "ViewModel".
You need to add else
in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.
sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x)
If you are exporting the data from the CSV file it can be as simple as this :
df = pd.read_csv(file_csv, na_values=' ')
This will create the data frame as well as replace blank values as Na
Nc is a link to nmap-ncat.
It would be nice to use nmap-ncat in your puppet, because NC is a virtual name of nmap-ncat.
Puppet cannot understand the links/virtualnames
your puppet should be:
package {
'nmap-ncat':
ensure => installed;
}
The assembly coming with Powershell SDK (C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0) does not come with Powershell 2 specific types.
Manually editing the csproj file solved my problem.
To fix this:
Go to Internet Information Service (IIS)
Click on your website you are trying to load image on
Under IIS section, Open the Authentication menu and Enable Windows Authentication as well.
Add this to your code:
.child { width: 100%; }
We know that a block-level child is supposed to occupy the full width of the parent.
Chrome understands this.
IE11, for whatever reason, wants an explicit request.
Using flex-basis: 100%
or flex: 1
also works.
.parent {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
width: 400px;_x000D_
border: 1px solid red;_x000D_
align-items: center;_x000D_
}_x000D_
.child {_x000D_
border: 1px solid blue;_x000D_
width: calc(100% - 2px); /* NEW; used calc to adjust for parent borders */_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry_x000D_
</div>_x000D_
<div class="child">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry_x000D_
</div>_x000D_
</div>
_x000D_
Note: Sometimes it will be necessary to sort through the various levels of the HTML structure to pinpoint which container gets the width: 100%
. CSS wrap text not working in IE
You also need to do manual re-centering if using jquery ui on mobile devices - the dialog is manually positioned via a 'left & top' css property. if the user switches orientation, the positioning is no longer centered, and must be adapted / re-centered afterwards.
If you are only trying to change the include paths for a project and not for all solutions then in Visual Studio 2008 do this: Right-click on the name of the project in the Solution Navigator. From the popup menu select Properties. In the property pages dialog select Configuration Properties->C/C++/General. Click in the text box next to the "Additional Include Files" label and browse for the appropriate directory. Select OK.
What annoys me is that some of the answers to the original question asked do not apply to the version of Visual Studio that was mentioned.
Aside from using %
, age of empires III
to lower case is age of empires iii
so your query should be:
select *
from games
where lower(title) like 'age of empires iii%'
In my case, problem was due to low disk space. I want to mention it for other users like me :)
If you need use it as a default configuration, just place min: 0
inside the node defaults.scale.ticks
, as follows:
defaults: {
global: {...},
scale: {
...
ticks: { min: 0 },
}
},
Reference: https://www.chartjs.org/docs/latest/axes/
After seeing this for deeply getting attributes, I made the following to safely get nested dict
values using dot notation. This works for me because my dicts
are deserialized MongoDB objects, so I know the key names don't contain .
s. Also, in my context, I can specify a falsy fallback value (None
) that I don't have in my data, so I can avoid the try/except pattern when calling the function.
from functools import reduce # Python 3
def deepgetitem(obj, item, fallback=None):
"""Steps through an item chain to get the ultimate value.
If ultimate value or path to value does not exist, does not raise
an exception and instead returns `fallback`.
>>> d = {'snl_final': {'about': {'_icsd': {'icsd_id': 1}}}}
>>> deepgetitem(d, 'snl_final.about._icsd.icsd_id')
1
>>> deepgetitem(d, 'snl_final.about._sandbox.sbx_id')
>>>
"""
def getitem(obj, name):
try:
return obj[name]
except (KeyError, TypeError):
return fallback
return reduce(getitem, item.split('.'), obj)
There second method will be many times more effective (mostly because of compilers inlining and boxing but still numbers are very expressive):
public static bool CheckObjectImpl(object o)
{
return o != null;
}
public static bool CheckNullableImpl<T>(T? o) where T: struct
{
return o.HasValue;
}
Benchmark test:
BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
[Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
Core : .NET Core 4.6.25009.03, 64bit RyuJIT
Method | Job | Runtime | Mean | Error | StdDev | Min | Max | Median | Rank | Gen 0 | Allocated |
-------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
CheckObject | Clr | Clr | 80.6416 ns | 1.1983 ns | 1.0622 ns | 79.5528 ns | 83.0417 ns | 80.1797 ns | 3 | 0.0060 | 24 B |
CheckNullable | Clr | Clr | 0.0029 ns | 0.0088 ns | 0.0082 ns | 0.0000 ns | 0.0315 ns | 0.0000 ns | 1 | - | 0 B |
CheckObject | Core | Core | 77.2614 ns | 0.5703 ns | 0.4763 ns | 76.4205 ns | 77.9400 ns | 77.3586 ns | 2 | 0.0060 | 24 B |
CheckNullable | Core | Core | 0.0007 ns | 0.0021 ns | 0.0016 ns | 0.0000 ns | 0.0054 ns | 0.0000 ns | 1 | - | 0 B |
Benchmark code:
public class BenchmarkNullableCheck
{
static int? x = (new Random()).Next();
public static bool CheckObjectImpl(object o)
{
return o != null;
}
public static bool CheckNullableImpl<T>(T? o) where T: struct
{
return o.HasValue;
}
[Benchmark]
public bool CheckObject()
{
return CheckObjectImpl(x);
}
[Benchmark]
public bool CheckNullable()
{
return CheckNullableImpl(x);
}
}
https://github.com/dotnet/BenchmarkDotNet was used
So if you have an option (e.g. writing custom serializers) to process Nullable in different pipeline than object
- and use their specific properties - do it and use Nullable specific properties.
So from consistent thinking point of view HasValue
should be preferred. Consistent thinking can help you to write better code do not spending too much time in details.
PS. People say that advice "prefer HasValue because of consistent thinking" is not related and useless. Can you predict the performance of this?
public static bool CheckNullableGenericImpl<T>(T? t) where T: struct
{
return t != null; // or t.HasValue?
}
PPS People continue minus, seems nobody tries to predict performance of CheckNullableGenericImpl
. I will tell you: there compiler will not help you replacing !=null
with HasValue
. HasValue
should be used directly if you are interested in performance.
You're missing an ending anchor.
if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
// ...
}
EDIT: If you can have anything between an initial 2 letters and a final 2 numbers:
if(Regex.IsMatch(myString, @"^[A-Za-z]{2}.*\d{2}\z")) {
// ...
}
This error “Sub or Function not defined”, will come every time when there is some compile error in script, so please check syntax again of your script.
I guess that is why when you used msqbox instead of msgbox it throws the error.
you can use a powerful library for management String which is undrescore.string.js
_('a <a href="#">link</a>').stripTags()
=> 'a link'
_('a <a href="#">link</a><script>alert("hello world!")</script>').stripTags()
=> 'a linkalert("hello world!")'
Don't forget to import this lib as following :
<script src="underscore.js" type="text/javascript"></script>
<script src="underscore.string.js" type="text/javascript"></script>
<script type="text/javascript"> _.mixin(_.str.exports())</script>
Groupby A:
In [0]: grp = df.groupby('A')
Within each group, sum over B and broadcast the values using transform. Then sort by B:
In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
B
2 -2.829710
5 -2.829710
1 0.253651
4 0.253651
0 0.551377
3 0.551377
Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:
In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]
In [3]: sort1
Out[3]:
A B C
2 baz -0.528172 False
5 baz -2.301539 True
1 bar -0.611756 True
4 bar 0.865408 False
0 foo 1.624345 False
3 foo -1.072969 True
Finally, sort the 'C' values within groups of 'A' using the sort=False
option to preserve the A sort order from step 1:
In [4]: f = lambda x: x.sort('C', ascending=False)
In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)
In [6]: sort2
Out[6]:
A B C
A
baz 5 baz -2.301539 True
2 baz -0.528172 False
bar 1 bar -0.611756 True
4 bar 0.865408 False
foo 3 foo -1.072969 True
0 foo 1.624345 False
Clean up the df index by using reset_index
with drop=True
:
In [7]: sort2.reset_index(0, drop=True)
Out[7]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
You can also add (keyup.enter)="xxxx()"
Sorry, brief moment of synapse failure. Here's the real answer.
require 'date'
Time.at(seconds_since_epoch_integer).to_datetime
Brief example (this takes into account the current system timezone):
$ date +%s
1318996912
$ irb
ruby-1.9.2-p180 :001 > require 'date'
=> true
ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
=> #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)>
Further update (for UTC):
ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
=> #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>
Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..)
outperforms DateTime.strptime(..)
(update: added more benchmarks).
# ~ % ruby -v
# => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]
irb(main):038:0> Benchmark.measure do
irb(main):039:1* ["1318996912", "1318496912"].each do |s|
irb(main):040:2* DateTime.strptime(s, '%s')
irb(main):041:2> end
irb(main):042:1> end
=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>
irb(main):044:0> Benchmark.measure do
irb(main):045:1> [1318996912, 1318496912].each do |i|
irb(main):046:2> DateTime.strptime(i.to_s, '%s')
irb(main):047:2> end
irb(main):048:1> end
=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>
irb(main):050:0* Benchmark.measure do
irb(main):051:1* ["1318996912", "1318496912"].each do |s|
irb(main):052:2* Time.at(s.to_i).to_datetime
irb(main):053:2> end
irb(main):054:1> end
=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>
irb(main):056:0* Benchmark.measure do
irb(main):057:1* [1318996912, 1318496912].each do |i|
irb(main):058:2* Time.at(i).to_datetime
irb(main):059:2> end
irb(main):060:1> end
=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>
To get all the values from a list of dictionaries, use the following code :
list = [{'text': 1, 'b': 2}, {'text': 3, 'd': 4}, {'text': 5, 'f': 6}]
subtitle=[]
for value in list:
subtitle.append(value['text'])
File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
You need the
fileItem.getOutputStream();
because it will throw NPE otherwise.
A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.
Simply :
$(".leaderMultiSelctdropdown").val()
I know this question has been answered but the answers i found here didn't work for my scenario ( or for Windows ).
I am using windows 10 laptop with PHP 7.2 in Xampp v3.2.4.
$command = 'php Cron.php send_email "'. $id .'"';
if ( substr(php_uname(), 0, 7) == "Windows" )
{
//windows
pclose(popen("start /B " . $command . " 1> temp/update_log 2>&1 &", "r"));
}
else
{
//linux
shell_exec( $command . " > /dev/null 2>&1 &" );
}
This worked perfectly for me.
I hope it will help someone with windows. Cheers.
This can be done by using PsExec
which can be downloaded here
psexec \\computer_name -u username -p password ipconfig
If this isn't working try doing this :-
Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.
Add a new DWORD value called LocalAccountTokenFilterPolicy
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
I rewrote the accepted answer and facile it for the newbies.
#break it down and understand it intuitively.
new = {}
for (key, value) in data:
if key not in new:
new[key] = [] # this is core of setdefault equals to new.setdefault(key, [])
new[key].append(value)
else:
new[key].append(value)
# easy with setdefault
new = {}
for (key, value) in data:
group = new.setdefault(key, []) # it is new[key] = []
group.append(value)
# even simpler with defaultdict
new = defaultdict(list)
for (key, value) in data:
new[key].append(value) # all keys have a default value of empty list []
Additionally,I categorized the methods as reference:
dict_methods_11 = {
'views':['keys', 'values', 'items'],
'add':['update','setdefault'],
'remove':['pop', 'popitem','clear'],
'retrieve':['get',],
'copy':['copy','fromkeys'],}
I suppose that you are using an array to create your select
form input.
In that case, use an array:
<?php
$selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
$fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
?>
<select name=‘yesnofine'>
<?php foreach ($fields as $k => $v): ?>
<option value="<?php echo $k;?>" <?php @print($selected[$k]);?>><?php echo $v;?></options>
<?php endforeach; ?>
</select>
If not, you may just unroll the above loop, and still use an array.
<option value="1" <?php @print($selected[$k]);?>>Yes</options>
<option value="2" <?php @print($selected[$k]);?>>No</options>
<option value="3" <?php @print($selected[$k]);?>>Fine</options>
Notes that I don't know:
$_REQUEST
, You will have to adapt the code to match requirements of the framework you are using, if any.
Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.
You could stil use @TEMP
if you quote the identifier "@TEMP"
:
declare @TEMP table (ID int, Name varchar(max));
insert into @temp SELECT 1 AS ID, 'a' Name;
SELECT * FROM @TEMP WHERE "@TEMP".ID = 1 ;
If your input rows are lists rather than dictionaries, then the following is a simple solution:
import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])
pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
# A B C
# 0 1 2 3
# 1 4 5 6
Well, I faced the same issue. For new users who may land at this page. Just follow their official documentation.
Install flask-cors
pip install -U flask-cors
then after app initialization, initialize flask-cors
with default arguments:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
Have that issue. So long time pass... Without side-fields of page it's break normal, but when fields appears, page and "page break space" will scale. So, with a normal field, within a document, it was shown incorrect. I fix it with set
width:100%
and use
div.page
{
page-break-before: always;
page-break-inside: avoid;
}
Use it on first line.
changing the width of the image will automatically change the height...
how many pictures do you want to have this functionality? If it's a lot and they all have DIFFERENT Heights you should probably just let the height change as well.
Lets say you have 5 images that have height 400px , in your html give those five tags the class of fixed
.fixed { width: 100%; height: 500px !important }
This should let the width change but keep the height the same.
You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...
import re
expression = "Nov 05 20:10:09 2020"
reg_ex = r'((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-2][0-9]|(3)[0-1]) (([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])) (\d{4}))'
assert re.fullmatch(reg_ex, expression), True
Expaination with respect to given Example
A group of possible months i.e. (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)
A group of valid days i.e. ([0-2][0-9]|(3)[0-1])
A group for getting valid Hours : ([0-1][0-9]|2[0-3]), Minutes : ([0-5][0-9]) and Seconds : ([0-5][0-9])
A group for getting year i.e (\d{4}))
You can use RoundingMode.#UNNECESSARY if you want/accept exception thrown otherwise
new BigDecimal(value).setScale(2, RoundingMode.UNNECESSARY);
If this rounding mode is specified on an operation that yields an inexact result, an ArithmeticException is thrown.
Exception if not integer value:
java.lang.ArithmeticException: Rounding necessary
No you don't need to check if you're in the main thread. Here is how you can do this in Swift:
runThisInMainThread { () -> Void in
runThisInMainThread { () -> Void in
// No problem
}
}
func runThisInMainThread(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
}
Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions
Primary key - we can put only one primary key on a table into a table and we can not left that column blank when we are entering the values into the table.
Unique Key - we can put more than one unique key on a table and we may left that column blank when we are entering the values into the table. column take unique values (not same) when we applied primary & unique key.
You are right, it's confusing that SQL Server allows you to create duplicate indexes on the same field(s). But the fact that you can create another doesn't indicate that the PK index doesn't also already exist.
The additional index does no good, but the only harm (very small) is the additional file size and row-creation overhead.
it might be nice toggling in one line of code:
let video = $('video')[0];_x000D_
video[video.paused ? 'play' : 'pause']();
_x000D_
import re
pattern = re.compile("<(\d{4,5})>")
for i, line in enumerate(open('test.txt')):
for match in re.finditer(pattern, line):
print 'Found on line %s: %s' % (i+1, match.group())
A couple of notes about the regex:
?
at the end and the outer (...)
if you don't want to match the number with the angle brackets, but only want the number itselfUpdate: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.
More about regex in python can be found here : Regular Expression HOWTO
I know there are a lot of answers, but another solution could be to go with decorators. This is an example to repeat a function everyday at a specific time. The cool think about using this way is that you only need to add the Syntactic Sugar to the function you want to schedule:
@repeatEveryDay(hour=6, minutes=30)
def sayHello(name):
print(f"Hello {name}")
sayHello("Bob") # Now this function will be invoked every day at 6.30 a.m
And the decorator will look like:
def repeatEveryDay(hour, minutes=0, seconds=0):
"""
Decorator that will run the decorated function everyday at that hour, minutes and seconds.
:param hour: 0-24
:param minutes: 0-60 (Optional)
:param seconds: 0-60 (Optional)
"""
def decoratorRepeat(func):
@functools.wraps(func)
def wrapperRepeat(*args, **kwargs):
def getLocalTime():
return datetime.datetime.fromtimestamp(time.mktime(time.localtime()))
# Get the datetime of the first function call
td = datetime.timedelta(seconds=15)
if wrapperRepeat.nextSent == None:
now = getLocalTime()
wrapperRepeat.nextSent = datetime.datetime(now.year, now.month, now.day, hour, minutes, seconds)
if wrapperRepeat.nextSent < now:
wrapperRepeat.nextSent += td
# Waiting till next day
while getLocalTime() < wrapperRepeat.nextSent:
time.sleep(1)
# Call the function
func(*args, **kwargs)
# Get the datetime of the next function call
wrapperRepeat.nextSent += td
wrapperRepeat(*args, **kwargs)
wrapperRepeat.nextSent = None
return wrapperRepeat
return decoratorRepeat
For Apache 2.4.9
in addition, look at the httpd-vhosts.conf file in C:\wamp\bin\apache\apache2.4.9\conf\extra
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require local
</Directory>
</VirtualHost>
Change to:
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>
</VirtualHost>
changing from "Require local" to "Require all granted" solved the error 403 in my local network
In CSS you need to use a Unicode escape sequence in place of HTML Entities. This is based on the hexadecimal value of a character.
I found that the easiest way to convert symbol to their hexadecimal equivalent is, such as from ▾ (▾
) to \25BE
is to use the Microsoft calculator =)
Yes. Enable programmers mode, turn on the decimal system, enter 9662
, then switch to hex and you'll get 25BE
. Then just add a backslash \
to the beginning.
One of the way is Using below sql queries
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
you have to include two more jar files.
xmlbeans-2.3.0.jar and dom4j-1.6.1.jar Add try it will work.
Note: It is required for the files with .xlsx formats only, not for just .xlt formats.
Explicit...
cursor foo is select * from blah; begin open fetch exit when close cursor yada yada yada
don't use them, use implicit
cursor foo is select * from blah;
for n in foo loop x = n.some_column end loop
I think you can even do this
for n in (select * from blah) loop...
Stick to implicit, they close themselves, they are more readable, they make life easy.
Comparisons are case insensitive when the column uses a collation which ends with _ci
(such as the default latin1_general_ci
collation) and they are case sensitive when the column uses a collation which ends with _cs
or _bin
(such as the utf8_unicode_cs
and utf8_bin
collations).
You can check your server, database and connection collations using:
mysql> show variables like '%collation%';
+----------------------+-------------------+
| Variable_name | Value |
+----------------------+-------------------+
| collation_connection | utf8_general_ci |
| collation_database | latin1_swedish_ci |
| collation_server | latin1_swedish_ci |
+----------------------+-------------------+
and you can check your table collation using:
mysql> SELECT table_schema, table_name, table_collation
FROM information_schema.tables WHERE table_name = `mytable`;
+----------------------+------------+-------------------+
| table_schema | table_name | table_collation |
+----------------------+------------+-------------------+
| myschema | mytable | latin1_swedish_ci |
You can change your database, table, or column collation to something case sensitive as follows:
-- Change database collation
ALTER DATABASE `databasename` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
-- or change table collation
ALTER TABLE `table` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;
-- or change column collation
ALTER TABLE `table` CHANGE `Value`
`Value` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_bin;
Your comparisons should now be case-sensitive.
Many of the answers discuss how many UUIDs would have to be generated to reach a 50% chance of a collision. But a 50%, 25%, or even 1% chance of collision is worthless for an application where collision must be (virtually) impossible.
Do programmers routinely dismiss as "impossible" other events that can and do occur?
When we write data to a disk or memory and read it back again, we take for granted that the data are correct. We rely on the device's error correction to detect any corruption. But the chance of undetected errors is actually around 2-50.
Wouldn't it make sense to apply a similar standard to random UUIDs? If you do, you will find that an "impossible" collision is possible in a collection of around 100 billion random UUIDs (236.5).
This is an astronomical number, but applications like itemized billing in a national healthcare system, or logging high frequency sensor data on a large array of devices could definitely bump into these limits. If you are writing the next Hitchhiker's Guide to the Galaxy, don't try to assign UUIDs to each article!
public static void main (String[] args) {
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
String[] wordArray = str1.trim().split("\\s+");
int wordCount = wordArray.length;
System.out.println("Word count is = " + wordCount);
}
The ideas is to split the string into words on any whitespace character occurring any number of times. The split function of the String class returns an array containing the words as its elements. Printing the length of the array would yield the number of words in the string.
Sets toast to a specific period in milli-seconds:
public void toast(int millisec, String msg) {
Handler handler = null;
final Toast[] toasts = new Toast[1];
for(int i = 0; i < millisec; i+=2000) {
toasts[0] = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toasts[0].show();
if(handler == null) {
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toasts[0].cancel();
}
}, millisec);
}
}
}
From the man page:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there
is only one file (or only standard input) to search.
I fixed this by running a clean of by gradle build (or delete the gradle build folder mannually)
This occurs if you move the main class to a new package and the old main class is still referenced in the claspath
Here you will find a better solution OLTP vs. OLAP
OLTP (On-line Transaction Processing) is involved in the operation of a particular system. OLTP is characterized by a large number of short on-line transactions (INSERT, UPDATE, DELETE). The main emphasis for OLTP systems is put on very fast query processing, maintaining data integrity in multi-access environments and an effectiveness measured by number of transactions per second. In OLTP database there is detailed and current data, and schema used to store transactional databases is the entity model (usually 3NF). It involves Queries accessing individual record like Update your Email in Company database.
OLAP (On-line Analytical Processing) deals with Historical Data or Archival Data. OLAP is characterized by relatively low volume of transactions. Queries are often very complex and involve aggregations. For OLAP systems a response time is an effectiveness measure. OLAP applications are widely used by Data Mining techniques. In OLAP database there is aggregated, historical data, stored in multi-dimensional schemas (usually star schema). Sometime query need to access large amount of data in Management records like what was the profit of your company in last year.
Nothing I've seen anywhere indicates you can ad-hoc deploy to a real iPhone without a (paid for) certificate.
You should use raw_input
to take a string input. then use islower
method of str
object.
s = raw_input('Type a word')
l = []
for c in s.strip():
if c.islower():
print c
l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)
Just do -
dir(s)
and you will find islower
and other attributes of str
The two errors you have in your code are very different.
The first problem is that you're initializing and populating your Map
in the body of the class without a statement.
You can either have a static Map
and a static {//TODO manipulate Map}
statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.
The second problem is that you cannot treat a Map
syntactically like an array
, so the statement data["John"] = "Taxi Driver";
should be replaced by data.put("John", "Taxi Driver")
.
If you already have a "John" key in your HashMap
, its value will be replaced with "Taxi Driver".
Here is the @Sang solution but without Jquery.
var socialFloat = document.querySelector('#social-float');_x000D_
var footer = document.querySelector('#footer');_x000D_
_x000D_
function checkOffset() {_x000D_
function getRectTop(el){_x000D_
var rect = el.getBoundingClientRect();_x000D_
return rect.top;_x000D_
}_x000D_
_x000D_
if((getRectTop(socialFloat) + document.body.scrollTop) + socialFloat.offsetHeight >= (getRectTop(footer) + document.body.scrollTop) - 10)_x000D_
socialFloat.style.position = 'absolute';_x000D_
if(document.body.scrollTop + window.innerHeight < (getRectTop(footer) + document.body.scrollTop))_x000D_
socialFloat.style.position = 'fixed'; // restore when you scroll up_x000D_
_x000D_
socialFloat.innerHTML = document.body.scrollTop + window.innerHeight;_x000D_
}_x000D_
_x000D_
document.addEventListener("scroll", function(){_x000D_
checkOffset();_x000D_
});
_x000D_
div.social-float-parent { width: 100%; height: 1000px; background: #f8f8f8; position: relative; }_x000D_
div#social-float { width: 200px; position: fixed; bottom: 10px; background: #777; }_x000D_
div#footer { width: 100%; height: 200px; background: #eee; }
_x000D_
<div class="social-float-parent">_x000D_
<div id="social-float">_x000D_
float..._x000D_
</div>_x000D_
</div>_x000D_
<div id="footer">_x000D_
</div>
_x000D_
If you want to have cd functionality (assuming shell=True) and still want to change the directory in terms of the Python script, this code will allow 'cd' commands to work.
import subprocess
import os
def cd(cmd):
#cmd is expected to be something like "cd [place]"
cmd = cmd + " && pwd" # add the pwd command to run after, this will get our directory after running cd
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # run our new command
out = p.stdout.read()
err = p.stderr.read()
# read our output
if out != "":
print(out)
os.chdir(out[0:len(out) - 1]) # if we did get a directory, go to there while ignoring the newline
if err != "":
print(err) # if that directory doesn't exist, bash/sh/whatever env will complain for us, so we can just use that
return
The fact that the first digit has to be in the range 5-9
only applies in case of two digits. So, check for that in the case of 2 digits, and allow any more digits directly:
^([5-9]\d|\d{3,})$
This regexp has beginning/ending anchors to make sure you're checking all digits, and the string actually represents a number. The |
means "or", so either [5-9]\d
or any number with 3 or more digits. \d
is simply a shortcut for [0-9]
.
Edit: To disallow numbers like 001
:
^([5-9]\d|[1-9]\d{2,})$
This forces the first digit to be not a zero in the case of 3 or more digits.
After opening local bootstrap.min.css in visual studio code, it looked unindented. Tried the commad ALT+Shift+F but in vain.
Then installed
CSS Formatter extension.
Reloaded it and ALT+Shift+F indented my CSS file with charm.
Bingo !!!
Try this:
-1 * numeric_limits<double>::max()
Reference: numeric_limits
This class is specialized for each of the fundamental types, with its members returning or set to the different values that define the properties that type has in the specific platform in which it compiles.
@codeling and @user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.
import datetime
x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)
Output:
15/02/2010
When you define you own html form then you have to include authentication token string ,that should be sent to controller for security reasons. If you use rails form helper to generate the authenticity token is added to form as follow.
<form accept-charset="UTF-8" action="/login/signin" method="post">
<div style="display:none">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="x37DrAAwyIIb7s+w2+AdoCR8cAJIpQhIetKRrPgG5VA=">
</div>
...
</form>
So the solution to the problem is either to add authenticity_token field or use rails form helpers rather then compromising security etc.
As the documentation clearly states, Character.getNumericValue()
returns the character's value as a digit.
It returns -1
if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character
object, you'll need to unbox it first:
int value = (int)c.charValue();
If angular cli is installed and ng command is not working then please see below suggestion, it may work
In my case problem was with npm config file (.npmrc ) which is available at C:\Users{user}. That file does not contain line
registry https://registry.npmjs.org/=true
. When i have added that line command started working. Use below command to edit config file. Edit file and save. Try to run command again. It should work now.
npm config edit
for
-loopA traditional for
-loop has three components :
These three components are seperated from each other by a ;
symbol. Content for each of these three components is optional, which means that the following is the most minimal for
-loop possible :
for (;;) {
// Do stuff
}
Of course, you will need to include an if(condition === true) { break; }
or an if(condition === true) { return; }
somewhere inside that for
-loop to get it to stop running.
Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index :
for (var i = 0, length = 10; i < length; i++) {
console.log(i);
}
for
-loop to loop through an arrayThe traditional way to loop through an array, is this :
for (var i = 0, length = myArray.length; i < length; i++) {
console.log(myArray[i]);
}
Or, if you prefer to loop backwards, you do this :
for (var i = myArray.length - 1; i > -1; i--) {
console.log(myArray[i]);
}
There are, however, many variations possible, like eg. this one :
for (var key = 0, value = myArray[key], var length = myArray.length; key < length; value = myArray[++key]) {
console.log(value);
}
... or this one ...
var i = 0, length = myArray.length;
for (; i < length;) {
console.log(myArray[i]);
i++;
}
... or this one :
var key = 0, value;
for (; value = myArray[key++];){
console.log(value);
}
Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.
Note :Each of these variations is supported by all browsers, including véry old ones!
while
-loopOne alternative to a for
-loop is a while
-loop. To loop through an array, you could do this :
var key = 0;
while(value = myArray[key++]){
console.log(value);
}
Note :
Like traditional for
-loops, while
-loops are supported by even the oldest of browsers.
Also, every while loop can be rewritten as a for
-loop. For example, the while
-loop hereabove behaves the exact same way as this for
-loop :
for(var key = 0;value = myArray[key++];){
console.log(value);
}
for...in
and for...of
In JavaScript, you can also do this :
for (i in myArray) {
console.log(myArray[i]);
}
This should be used with care, however, as it doesn't behave the same as a traditonal for
-loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad idea? for more details.
As an alternative to for...in
, there's now also for for...of
. The following example shows the difference between a for...of
loop and a for...in
loop :
var myArray = [3, 5, 7];
myArray.foo = "hello";
for (var i in myArray) {
console.log(i); // logs 0, 1, 2, "foo"
}
for (var i of myArray) {
console.log(i); // logs 3, 5, 7
}
Note :
You also need to consider that no version of Internet Explorer supports for...of
(Edge 12+ does) and that for...in
requires at least IE10.
Array.prototype.forEach()
An alternative to For
-loops is Array.prototype.forEach()
, which uses the following syntax :
myArray.forEach(function(value, key, myArray) {
console.log(value);
});
Note :
Array.prototype.forEach()
is supported by all modern browsers, as well as IE9+.
jQuery.each()
Additionally to the four other options mentioned, jQuery also had its own foreach
variation.
It uses the following syntax :
$.each(myArray, function(key, value) {
console.log(value);
});
Run in command prompt.
pip list
Check what version you have installed on your system if you have an old version.
Try to uninstall the package...
pip uninstall requests
Try after to install it:
pip install requests
You can also test if pip does not do the job.
easy_install requests
If you want to get the date when the user selects it, you can do this:
$("#datepicker").datepicker({
onSelect: function() {
var dateObject = $(this).datepicker('getDate');
}
});
I am not sure about the second part of your question. But, have you tried using style sheets and relative positioning?
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
If you have two []byte
, compare them using bytes.Equal. The Golang documentation says:
Equal returns a boolean reporting whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.
Usage:
package main
import (
"fmt"
"bytes"
)
func main() {
a := []byte {1,2,3}
b := []byte {1,2,3}
c := []byte {1,2,2}
fmt.Println(bytes.Equal(a, b))
fmt.Println(bytes.Equal(a, c))
}
This will print
true
false
You can't change the color of the line (you can't specify different foreground colors for the same element, and the text and its decoration form a single element). However there are some tricks:
a:link, a:visited {text-decoration: none; color: red; border-bottom: 1px solid #006699; }
a:hover, a:active {text-decoration: none; color: red; border-bottom: 1px solid #1177FF; }
Also you can make some cool effects this way:
a:link {text-decoration: none; color: red; border-bottom: 1px dashed #006699; }
Hope it helps.
If you're at the top level - or able to cleanly get to the top level - of the thread, then just returning is nice. Throwing an exception isn't as clean, as you need to be able to check that nothing's going to catch the exception and ignore it.
The reason you need to use Thread.currentThread()
in order to call interrupt()
is that interrupt()
is an instance method - you need to call it on the thread you want to interrupt, which in your case happens to be the current thread. Note that the interruption will only be noticed the next time the thread would block (e.g. for IO or for a monitor) anyway - it doesn't mean the exception is thrown immediately.
yaml.load
Consider the following example YAML. It is well-formed YAML syntax, however it uses (non-standard) curly-brace placeholders with embedded expressions.
The embedded expressions do not produce the desired result in YAML, because they are not part of the native YAML specification. Nevertheless, they are used in this example only to help illustrate what is available with standard YAML and what is not.
part01_customer_info:
cust_fname: "Homer"
cust_lname: "Himpson"
cust_motto: "I love donuts!"
cust_email: [email protected]
part01_government_info:
govt_sales_taxrate: 1.15
part01_purchase_info:
prch_unit_label: "Bacon-Wrapped Fancy Glazed Donut"
prch_unit_price: 3.00
prch_unit_quant: 7
prch_product_cost: "{{prch_unit_price * prch_unit_quant}}"
prch_total_cost: "{{prch_product_cost * govt_sales_taxrate}}"
part02_shipping_info:
cust_fname: "{{cust_fname}}"
cust_lname: "{{cust_lname}}"
ship_city: Houston
ship_state: Hexas
part03_email_info:
cust_email: "{{cust_email}}"
mail_subject: Thanks for your DoughNutz order!
mail_notes: |
We want the mail_greeting to have all the expected values
with filled-in placeholders (and not curly-braces).
mail_greeting: |
Greetings {{cust_fname}} {{cust_lname}}!
We love your motto "{{cust_motto}}" and we agree with you!
Your total purchase price is {{prch_total_cost}}
The substitutions marked in GREEN are readily available in standard YAML, using anchors, aliases, and merge keys.
The substitutions marked in YELLOW are technically available in standard YAML, but not without a custom type declaration, or some other binding mechanism.
The substitutions marked in RED are not available in standard YAML. Yet there are workarounds and alternatives; such as through string formatting or string template engines (such as python's str.format
).
A frequently-requested feature for YAML is the ability to insert arbitrary variable placeholders that support arbitrary cross-references and expressions that relate to the other content in the same (or transcluded) YAML file(s).
YAML supports anchors and aliases, but this feature does not support arbitrary placement of placeholders and expressions anywhere in the YAML text. They only work with YAML nodes.
YAML also supports custom type declarations, however these are less common, and there are security implications if you accept YAML content from potentially untrusted sources.
There are YAML extension libraries, but these are not part of the native YAML spec.
sprintf
or str.format
style functionality from the hosting languagefor i in range(16):
print datetime.date.today() + datetime.timedelta(days=i)
It's included in Jasny's fork of bootstrap.
A simple upload button can be created using
<span class="btn btn-file">Upload<input type="file" /></span>
With the fileupload plugin you can create more advanced widgets. Have a look at http://jasny.github.io/bootstrap/javascript/#fileinput
(ps: the answer given by Nick Craver is incorrect)
contentType specifies the format of data being sent to the server as part of request(it can be sent as part of response too, more on that later).
dataType specifies the expected format of data to be received by the client(browser).
Both are not interchangable.
contentType
is the header sent to the server, specifying the format of data(i.e the content of message body) being being to the server. This is used with POST and PUT requests. Usually when u send POST request, the message body comprises of passed in parameters like:==============================
Sample request:
POST /search HTTP/1.1
Content-Type: application/x-www-form-urlencoded
<<other header>>
name=sam&age=35
==============================
The last line above "name=sam&age=35" is the message body and contentType specifies it as application/x-www-form-urlencoded since we are passing the form parameters in the message body. However we aren't limited to just sending the parameters, we can send json, xml,... like this(sending different types of data is especially useful with RESTful web services):
==============================
Sample request:
POST /orders HTTP/1.1
Content-Type: application/xml
<<other header>>
<order>
<total>$199.02</total>
<date>December 22, 2008 06:56</date>
...
</order>
==============================
So the ContentType this time is: application/xml, cause that's what we are sending. The above examples showed sample request, similarly the response send from the server can also have the Content-Type header specifying what the server is sending like this:
==============================
sample response:
HTTP/1.1 201 Created
Content-Type: application/xml
<<other headers>>
<order id="233">
<link rel="self" href="http://example.com/orders/133"/>
<total>$199.02</total>
<date>December 22, 2008 06:56</date>
...
</order>
==============================
dataType
specifies the format of response to expect. Its related to Accept header. JQuery will try to infer it based on the Content-Type of the response.==============================
Sample request:
GET /someFolder/index.html HTTP/1.1
Host: mysite.org
Accept: application/xml
<<other headers>>
==============================
Above request is expecting XML from the server.
Regarding your question,
contentType: "application/json; charset=utf-8",
dataType: "json",
Here you are sending json data using UTF8 character set, and you expect back json data from the server. As per the JQuery docs for dataType,
The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data.
So what you get in success handler is proper javascript object(JQuery converts the json object for you)
whereas
contentType: "application/json",
dataType: "text",
Here you are sending json data, since you haven't mentioned the encoding, as per the JQuery docs,
If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.
and since dataType is specified as text, what you get in success handler is plain text, as per the docs for dataType,
The text and xml types return the data with no processing. The data is simply passed on to the success handler
ALTER IGNORE TABLE test ADD UNIQUE INDEX 'test' ('b');
@ here 'b' is column name to uniqueness, @ here 'test' is index name.
An Alternative Solution to the above
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
color: Colors.white,
child: ...
)
You can use BorderRadius.only() to customize the corners you wish to manage.
For my console program the answers with tkinter above did not quite work for me because the .destroy() always gave an error,:
can't invoke "event" command: application has been destroyed while executing...
or when using .withdraw() the console window did not get the focus back.
To solve this you also have to call .update() before the .destroy(). Example:
# Python 3
import tkinter
r = tkinter.Tk()
text = r.clipboard_get()
r.withdraw()
r.update()
r.destroy()
The r.withdraw() prevents the frame from showing for a milisecond, and then it will be destroyed giving the focus back to the console.
The SettingWithCopyWarning
was created to flag potentially confusing "chained" assignments, such as the following, which does not always work as expected, particularly when the first selection returns a copy. [see GH5390 and GH5597 for background discussion.]
df[df['A'] > 2]['B'] = new_val # new_val not set in df
The warning offers a suggestion to rewrite as follows:
df.loc[df['A'] > 2, 'B'] = new_val
However, this doesn't fit your usage, which is equivalent to:
df = df[df['A'] > 2]
df['B'] = new_val
While it's clear that you don't care about writes making it back to the original frame (since you are overwriting the reference to it), unfortunately this pattern cannot be differentiated from the first chained assignment example. Hence the (false positive) warning. The potential for false positives is addressed in the docs on indexing, if you'd like to read further. You can safely disable this new warning with the following assignment.
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
As the message says:
no changes added to commit (use "git add" and/or "git commit -a")
Git has a "staging area" where files need to be added before being committed, you can read an explanation of it here.
For your specific example, you can use:
git commit -am "save arezzo files"
(note the extra a
in the flags, can also be written as git commit -a -m "message"
- both do the same thing)
Alternatively, if you want to be more selective about what you add to the commit, you use the git add command to add the appropriate files to the staging area, and git status to preview what is about to be added (remembering to pay attention to the wording used).
You can also find general documentation and tutorials for how to use git on the git documentation page which will give more detail about the concept of staging/adding files.
One other thing worth knowing about is interactive staging - this allows you to add parts of a file to the staging area, so if you've made three distinct code changes (for related but different functionality), you can use interactive mode to split the changes and add/commit each part in turn. Having smaller specific commits like this can be helpful.
Normally you'd just stick the code in Page_Load
in your .aspx
page's code-behind.
if (someVar) {
Item1.Visible = true;
Item2.Visible = false;
} else {
Item1.Visible = false;
Item2.Visible = true;
}
This assumes you've got Item1
and Item2
laid out on the page already.