GitHub is svn compatible so you can use svn ls
svn ls https://github.com/user/repository.git/branches/master/
BitBucket supports git archive so you can download tar archive and list archived files. It is not very efficient but works:
git archive [email protected]:repository HEAD directory | tar -t
I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.
Practically speaking size_t
represents the number of bytes you can address. On most modern architectures for the last 10-15 years that has been 32 bits which has also been the size of a unsigned int. However we are moving to 64bit addressing while the uint
will most likely stay at 32bits (it's size is not guaranteed in the c++ standard). To make your code that depends on the memory size portable across architectures you should use a size_t
. For example things like array sizes should always use size_t
's. If you look at the standard containers the ::size()
always returns a size_t
.
Also note, visual studio has a compile option that can check for these types of errors called "Detect 64-bit Portability Issues".
This is a common problem . It can be easily solved by changing res/values/styles.xml
to
<!-- Base application theme. -->
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
open styles.xml
change from -> style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"
change to -> style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar"
(Just prepend "Base." to "Theme".)
Save the file and check Preview now.
Preview Works Perfeclty now.
Completely agree with user Daniel Saidi. In Order to have Color
for NotificationIcon
I'm writing this answer.
For that you've to make icon like Silhouette
and make some section Transparent
wherever you wants to add your Colors
. i.e,
You can add your color using
.setColor(your_color_resource_here)
NOTE : setColor
is only available in Lollipop
so, you've to check OSVersion
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Notification notification = new Notification.Builder(context)
...
} else {
// Lollipop specific setColor method goes here.
Notification notification = new Notification.Builder(context)
...
notification.setColor(your_color)
...
}
You can also achieve this using Lollipop
as the target SDK
.
All instruction regarding NotificationIcon
given at Google Developer Console Notification Guide Lines.
Preferred Notification Icon Size 24x24dp
mdpi @ 24.00dp = 24.00px
hdpi @ 24.00dp = 36.00px
xhdpi @ 24.00dp = 48.00px
And also refer this link for Notification Icon Sizes for more info.
$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10");
For an alternative solution, check if you added your app to settings.gradle successfully
include ':app'
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
If anyone get this error for ionic cordova install . just use this code npm install --no-optional
in your cmd.
And then run this code npm install -g ionic@latest cordova
@IBOutlet weak var yourButton: UIButton! {
didSet{
yourButton.backgroundColor = .clear
yourButton.layer.cornerRadius = 10
yourButton.layer.borderWidth = 2
yourButton.layer.borderColor = UIColor.white.cgColor
}
}
User the below code for omit/excludes from creating setter and getter. value key should use inside @Getter
and @Setter
.
@Getter(value = AccessLevel.NONE)
@Setter(value = AccessLevel.NONE)
private int mySecret;
Spring boot 2.3 version, this is working well.
n_values = data.income.value_counts()
First unique value count
n_at_most_50k = n_values[0]
Second unique value count
n_greater_50k = n_values[1]
n_values
Output:
<=50K 34014
>50K 11208
Name: income, dtype: int64
Output:
n_greater_50k,n_at_most_50k:-
(11208, 34014)
How to get the last N rows of a pandas DataFrame?
If you are slicing by position, __getitem__
(i.e., slicing with[]
) works well, and is the most succinct solution I've found for this problem.
pd.__version__
# '0.24.2'
df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df
A B
0 a 1
1 a 2
2 a 3
3 b 4
4 b 5
5 b 6
6 b 7
7 c 8
df[-3:]
A B
5 b 6
6 b 7
7 c 8
This is the same as calling df.iloc[-3:]
, for instance (iloc
internally delegates to __getitem__
).
As an aside, if you want to find the last N rows for each group, use groupby
and GroupBy.tail
:
df.groupby('A').tail(2)
A B
1 a 2
2 a 3
5 b 6
6 b 7
7 c 8
Visual Studio looks for headers in this order:
In your case, add the directory that the header is to the project properties (Project Properties ? Configuration ? C/C++ ? General ? Additional Include Directories).
use
SELECT DISTINCT Date FROM buy ORDER BY Date
so MySQL removes duplicates
BTW: using explicit column names in SELECT
uses less resources in PHP when you're getting a large result from MySQL
What is your output when you do java -version
? This will tell you what version the running JVM is.
The Unsupported major.minor version 51.0 error could mean:
Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor
error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)
See: http://www.java.com/en/download/manual.jsp (7 Update 25 )
and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)
for the latest version of the JRE and JDK respectively.
EDIT:
Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.
Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.
I have used below code in Angular 9. note that it is using http class instead of normal httpClient.
so import Headers from the module, otherwise Headers will be mistaken by typescript headers interface and gives error
import {Http, Headers, RequestOptionsArgs } from "@angular/http";
and in your method use following sample code and it is breaked down for easier understanding.
let customHeaders = new Headers({ Authorization: "Bearer " + localStorage.getItem("token")});
const requestOptions: RequestOptionsArgs = { headers: customHeaders };
return this.http.get("/api/orders", requestOptions);
All the answers here supply values with powers of 10. Here is a format using proper SI units (multiples of 1024, i.e. Mebibytes, Gibibytes, and Tebibytes):
[>1099511627776]#.##,,,," TiB";[>1073741824]#.##,,," GiB";0.##,," MiB"
This supports MiB, GiB, and TiB showing two decimal places.
I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\
) character:
Hello
\
\
\
World!
This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:
World!
Personally I find this cleaner for a large number of line breaks compared to using <br>
.
Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
import os
for subdir, dirs, files in os.walk('./'):
for file in files:
do some stuff
print file
You can improve this code with del dirs[:]
which will be like following .
import os
for subdir, dirs, files in os.walk('./'):
del dirs[:]
for file in files:
do some stuff
print file
Or even better if you could point os.walk with current working directory .
import os
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd, topdown=True):
del dirs[:] # remove the sub directories.
for file in files:
do some stuff
print file
The context parameter just sets the value of this
in the iterator function.
var someOtherArray = ["name","patrick","d","w"];
_.each([1, 2, 3], function(num) {
// In here, "this" refers to the same Array as "someOtherArray"
alert( this[num] ); // num is the value from the array being iterated
// so this[num] gets the item at the "num" index of
// someOtherArray.
}, someOtherArray);
Working Example: http://jsfiddle.net/a6Rx4/
It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray
, which is represented by this
since we passed it as the context parameter.
If you do not set the context, then this
will refer to the window
object.
This one is in my opinion the best one for online (offline however dreamweaver is best): http://www.maschek.hu/imagemap/imgmap
Using java.time
framework built into Java 8
int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22
If you need also information about time(hour,minute,second) use some conversion from LocalDate
to LocalDateTime
LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00
Update 2018-04-20: it seems that OP @Joshkunz was asking for finding which months are between two dates, instead of "how many months" are between two dates. So I am not sure why @JohnLaRooy is upvoted for more than 100 times. @Joshkunz indicated in the comment under the original question he wanted the actual dates [or the months], instead of finding the total number of months.
So it appeared the question wanted, for between two dates 2018-04-11
to 2018-06-01
Apr 2018, May 2018, June 2018
And what if it is between 2014-04-11
to 2018-06-01
? Then the answer would be
Apr 2014, May 2014, ..., Dec 2014, Jan 2015, ..., Jan 2018, ..., June 2018
So that's why I had the following pseudo code many years ago. It merely suggested using the two months as end points and loop through them, incrementing by one month at a time. @Joshkunz mentioned he wanted the "months" and he also mentioned he wanted the "dates", without knowing exactly, it was difficult to write the exact code, but the idea is to use one simple loop to loop through the end points, and incrementing one month at a time.
The answer 8 years ago in 2010:
If adding by a week, then it will approximately do work 4.35 times the work as needed. Why not just:
1. get start date in array of integer, set it to i: [2008, 3, 12],
and change it to [2008, 3, 1]
2. get end date in array: [2010, 10, 26]
3. add the date to your result by parsing i
increment the month in i
if month is >= 13, then set it to 1, and increment the year by 1
until either the year in i is > year in end_date,
or (year in i == year in end_date and month in i > month in end_date)
just pseduo code for now, haven't tested, but i think the idea along the same line will work.
The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.
It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.
I prefer TextMate on OS X. But Netbeans (multi-platform) is coming along quite nicely. Plus it comes with its IDE fully functional debugger.
Since not all versions of jQuery are created equal, you may run into the same issue I did which means calling $("#item").removeClass(); does not actually remove the class. (Probably a bug)
A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.
document.getElementById("item").removeAttribute("class");
cd DIRECTORY
tar -czf NAME.tar.gz *
the asterisk will include everything even hidden ones
fixed positioning on mobile safari
This link helped me lot.....Its easy.. There is a demo..
I have edited the code from one of the example here to use jquery. It's still not 100% jquery though. Any thoughts on the two different versions, like what are the pros and cons of each?
function column_sort() {
getCellValue = (tr, idx) => $(tr).find('td').eq( idx ).text();
comparer = (idx, asc) => (a, b) => ((v1, v2) =>
v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
)(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
table = $(this).closest('table')[0];
tbody = $(table).find('tbody')[0];
elm = $(this)[0];
children = elm.parentNode.children;
Array.from(tbody.querySelectorAll('tr')).sort( comparer(
Array.from(children).indexOf(elm), table.asc = !table.asc))
.forEach(tr => tbody.appendChild(tr) );
}
table.find('thead th').on('click', column_sort);
The following worked for me: https://github.com/microsoft/TypeScript/issues/28631#issuecomment-472606019 I fix it by doing something like this:
const Component = (isFoo ? FooComponent : BarComponent) as React.ElementType
If you used read.table()
(or one of it's ilk, e.g. read.csv()
) then the easy fix is to change the call to:
read.table(file = "foo.txt", row.names = 1, ....)
where ....
are the other arguments you needed/used. The row.names
argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table
for details/info.
If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames
attribute and remove the first variable from the object (assuming obj
is your object)
rownames(obj) <- obj[, 1] ## set rownames
obj <- obj[, -1] ## remove the first variable
Just as you said, I'd recommend weights. Percentages would be incredibly useful (don't know why they aren't supported), but one way you could do it is like so:
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
>
<LinearLayout
android:layout_height="0dp"
android:layout_width="fill_parent"
android:layout_weight="1"
>
</LinearLayout>
<View
android:layout_height="0dp"
android:layout_width="fill_parent"
android:layout_weight="1"
/>
</LinearLayout>
The takeaway being that you have an empty View that will take up the remaining space. Not ideal, but it does what you're looking for.
Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/
// The connection URL
String url = "https://ajax.googleapis.com/ajax/" +
"services/search/web?v=1.0&q={query}";
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");
The LoggerFactory class is msising according to the error message:
java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory
Apparently, the slf4j.jar
file is not getting loaded for some reason.
This old chestnut...
In short, you should be using require and letting node handle the parsing as part of the require call, not outsourcing it to a 3rd party module. You should also be taking care that your configs are bulletproof, which means you should check the returned data carefully.
But for brevity's sake, consider the following example:
For Example, let's say I have a config file 'admins.json' in the root of my app containing the following:
admins.json[{
"userName": "tech1337",
"passSalted": "xxxxxxxxxxxx"
}]
Note the quoted keys, "userName"
, "passSalted"
!
I can do the following and get the data out of the file with ease.
let admins = require('~/app/admins.json');
console.log(admins[0].userName);
Now the data is in and can be used as a regular (or array of) object.
The best thing is probably to create a variable that holds your binaries:
binaries=code1 code2
Then use that in the all
-target, to avoid repeating:
all: clean $(binaries)
Now, you can use this with the clean
-target, too, and just add some globs to catch object files and stuff:
.PHONY: clean
clean:
rm -f $(binaries) *.o
Note use of the .PHONY
to make clean
a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.
I am adding code to accomplish this: It is working fine for me:
# This works in python 3
# required python packages
# tabula-py==1.0.0
# PyPDF2==1.26.0
# Pillow==4.0.0
# pdfminer.six==20170720
import os
import shutil
import warnings
from io import StringIO
import requests
import tabula
from PIL import Image
from PyPDF2 import PdfFileWriter, PdfFileReader
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
warnings.filterwarnings("ignore")
def download_file(url):
local_filename = url.split('/')[-1]
local_filename = local_filename.replace("%20", "_")
r = requests.get(url, stream=True)
print(r)
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return local_filename
class PDFExtractor():
def __init__(self, url):
self.url = url
# Downloading File in local
def break_pdf(self, filename, start_page=-1, end_page=-1):
pdf_reader = PdfFileReader(open(filename, "rb"))
# Reading each pdf one by one
total_pages = pdf_reader.numPages
if start_page == -1:
start_page = 0
elif start_page < 1 or start_page > total_pages:
return "Start Page Selection Is Wrong"
else:
start_page = start_page - 1
if end_page == -1:
end_page = total_pages
elif end_page < 1 or end_page > total_pages - 1:
return "End Page Selection Is Wrong"
else:
end_page = end_page
for i in range(start_page, end_page):
output = PdfFileWriter()
output.addPage(pdf_reader.getPage(i))
with open(str(i + 1) + "_" + filename, "wb") as outputStream:
output.write(outputStream)
def extract_text_algo_1(self, file):
pdf_reader = PdfFileReader(open(file, 'rb'))
# creating a page object
pageObj = pdf_reader.getPage(0)
# extracting extract_text from page
text = pageObj.extractText()
text = text.replace("\n", "").replace("\t", "")
return text
def extract_text_algo_2(self, file):
pdfResourceManager = PDFResourceManager()
retstr = StringIO()
la_params = LAParams()
device = TextConverter(pdfResourceManager, retstr, codec='utf-8', laparams=la_params)
fp = open(file, 'rb')
interpreter = PDFPageInterpreter(pdfResourceManager, device)
password = ""
max_pages = 0
caching = True
page_num = set()
for page in PDFPage.get_pages(fp, page_num, maxpages=max_pages, password=password, caching=caching,
check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue()
text = text.replace("\t", "").replace("\n", "")
fp.close()
device.close()
retstr.close()
return text
def extract_text(self, file):
text1 = self.extract_text_algo_1(file)
text2 = self.extract_text_algo_2(file)
if len(text2) > len(str(text1)):
return text2
else:
return text1
def extarct_table(self, file):
# Read pdf into DataFrame
try:
df = tabula.read_pdf(file, output_format="csv")
except:
print("Error Reading Table")
return
print("\nPrinting Table Content: \n", df)
print("\nDone Printing Table Content\n")
def tiff_header_for_CCITT(self, width, height, img_size, CCITT_group=4):
tiff_header_struct = '<' + '2s' + 'h' + 'l' + 'h' + 'hhll' * 8 + 'h'
return struct.pack(tiff_header_struct,
b'II', # Byte order indication: Little indian
42, # Version number (always 42)
8, # Offset to first IFD
8, # Number of tags in IFD
256, 4, 1, width, # ImageWidth, LONG, 1, width
257, 4, 1, height, # ImageLength, LONG, 1, lenght
258, 3, 1, 1, # BitsPerSample, SHORT, 1, 1
259, 3, 1, CCITT_group, # Compression, SHORT, 1, 4 = CCITT Group 4 fax encoding
262, 3, 1, 0, # Threshholding, SHORT, 1, 0 = WhiteIsZero
273, 4, 1, struct.calcsize(tiff_header_struct), # StripOffsets, LONG, 1, len of header
278, 4, 1, height, # RowsPerStrip, LONG, 1, lenght
279, 4, 1, img_size, # StripByteCounts, LONG, 1, size of extract_image
0 # last IFD
)
def extract_image(self, filename):
number = 1
pdf_reader = PdfFileReader(open(filename, 'rb'))
for i in range(0, pdf_reader.numPages):
page = pdf_reader.getPage(i)
try:
xObject = page['/Resources']['/XObject'].getObject()
except:
print("No XObject Found")
return
for obj in xObject:
try:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj]._data
if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
mode = "RGB"
else:
mode = "P"
image_name = filename.split(".")[0] + str(number)
print(xObject[obj]['/Filter'])
if xObject[obj]['/Filter'] == '/FlateDecode':
data = xObject[obj].getData()
img = Image.frombytes(mode, size, data)
img.save(image_name + "_Flate.png")
# save_to_s3(imagename + "_Flate.png")
print("Image_Saved")
number += 1
elif xObject[obj]['/Filter'] == '/DCTDecode':
img = open(image_name + "_DCT.jpg", "wb")
img.write(data)
# save_to_s3(imagename + "_DCT.jpg")
img.close()
number += 1
elif xObject[obj]['/Filter'] == '/JPXDecode':
img = open(image_name + "_JPX.jp2", "wb")
img.write(data)
# save_to_s3(imagename + "_JPX.jp2")
img.close()
number += 1
elif xObject[obj]['/Filter'] == '/CCITTFaxDecode':
if xObject[obj]['/DecodeParms']['/K'] == -1:
CCITT_group = 4
else:
CCITT_group = 3
width = xObject[obj]['/Width']
height = xObject[obj]['/Height']
data = xObject[obj]._data # sorry, getData() does not work for CCITTFaxDecode
img_size = len(data)
tiff_header = self.tiff_header_for_CCITT(width, height, img_size, CCITT_group)
img_name = image_name + '_CCITT.tiff'
with open(img_name, 'wb') as img_file:
img_file.write(tiff_header + data)
# save_to_s3(img_name)
number += 1
except:
continue
return number
def read_pages(self, start_page=-1, end_page=-1):
# Downloading file locally
downloaded_file = download_file(self.url)
print(downloaded_file)
# breaking PDF into number of pages in diff pdf files
self.break_pdf(downloaded_file, start_page, end_page)
# creating a pdf reader object
pdf_reader = PdfFileReader(open(downloaded_file, 'rb'))
# Reading each pdf one by one
total_pages = pdf_reader.numPages
if start_page == -1:
start_page = 0
elif start_page < 1 or start_page > total_pages:
return "Start Page Selection Is Wrong"
else:
start_page = start_page - 1
if end_page == -1:
end_page = total_pages
elif end_page < 1 or end_page > total_pages - 1:
return "End Page Selection Is Wrong"
else:
end_page = end_page
for i in range(start_page, end_page):
# creating a page based filename
file = str(i + 1) + "_" + downloaded_file
print("\nStarting to Read Page: ", i + 1, "\n -----------===-------------")
file_text = self.extract_text(file)
print(file_text)
self.extract_image(file)
self.extarct_table(file)
os.remove(file)
print("Stopped Reading Page: ", i + 1, "\n -----------===-------------")
os.remove(downloaded_file)
# I have tested on these 3 pdf files
# url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Healthcare-January-2017.pdf"
url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Sample_Test.pdf"
# url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Sazerac_FS_2017_06_30%20Annual.pdf"
# creating the instance of class
pdf_extractor = PDFExtractor(url)
# Getting desired data out
pdf_extractor.read_pages(15, 23)
for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:
rows, columns = map(lambda i: i.value, tensor.get_shape())
Mostly the image is not displayed because you URL contains spaces. In your case you almost did everything correct. Except one thing - you have not added single quotes like you do if you specify background-image in css I.e.
.bg-img { \/ \/
background-image: url('http://...');
}
To do so escape quot character in HTML via \'
\/ \/
<div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>
use the command-line tool SQLCMD which is much leaner on memory. It is as simple as:
SQLCMD -d <database-name> -i filename.sql
You need valid credentials to access your SQL Server instance or even to access a database
Taken from here.
Here is how to see the visual diff between whole commits, as opposed to single files, in Visual Studio (tested in VS 2017). Unfortunately, it works only for commits within one branch: In the "Team Explorer", choose the "Branches" view, right-click on the repo, and choose "View history" as in the following image.
Then the history of the current branch appears in the main area. (Where branches that ended as earlier commits on the current branch are marked by labels.) Now select a couple of commits with Ctrl-Left, then right click and select "Compare Commits..." from the pop-up menu.
For more on comparing branches in the Microsoft world, see this stackoverflow question: Differences between git branches using Visual Studio.
If you use dplyr
package you can do:
library(dplyr)
filter(df, aged <= laclen)
import base64
from PIL import Image
from io import BytesIO
with open("image.jpg", "rb") as image_file:
data = base64.b64encode(image_file.read())
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')
Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:
$('.collapse').on('show.bs.collapse', function () {
$('.collapse.in').collapse('hide');
});
I modified his example to do this here: http://jsfiddle.net/QLfMU/116/
You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
That is it.
window.scrollTo(0,1);
this will help you but this javascript is may not work in all browsers
For PowerShell 3+
function Get-ScriptDirectory {
if ($psise) {
Split-Path $psise.CurrentFile.FullPath
}
else {
$global:PSScriptRoot
}
}
I've placed this function in my profile. It works in ISE using F8/Run Selection too.
you can invoke it using window.function_name() or directly function_name()
Consider exploiting the keys of associative arrays. I would presume this outperforms both regex/pattern matching and looping, although I haven't profiled it.
declare -A list=( [one]=1 [two]=two [three]='any non-empty value' )
for value in one two three four
do
echo -n "$value is "
# a missing key expands to the null string,
# and we've set each interesting key to a non-empty value
[[ -z "${list[$value]}" ]] && echo -n '*not* '
echo "a member of ( ${!list[*]} )"
done
Output:
one is a member of ( one two three ) two is a member of ( one two three ) three is a member of ( one two three ) four is *not* a member of ( one two three )
You need to use WITH ROLLBACK IMMEDIATE
to boot other conections out with no regards to what or who is is already using it.
Or use WITH NO_WAIT
to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details
I think the classic answer is to create a more decoupled application, which has no knowledge of which implementation will be used during runtime.
For example, we're a central payment provider, working with many payment providers around the world. However, when a request is made, I have no idea which payment processor I'm going to call. I could program one class with a ton of switch cases, such as:
class PaymentProcessor{
private String type;
public PaymentProcessor(String type){
this.type = type;
}
public void authorize(){
if (type.equals(Consts.PAYPAL)){
// Do this;
}
else if(type.equals(Consts.OTHER_PROCESSOR)){
// Do that;
}
}
}
Now imagine that now you'll need to maintain all this code in a single class because it's not decoupled properly, you can imagine that for every new processor you'll support, you'll need to create a new if // switch case for every method, this only gets more complicated, however, by using Dependency Injection (or Inversion of Control - as it's sometimes called, meaning that whoever controls the running of the program is known only at runtime, and not complication), you could achieve something very neat and maintainable.
class PaypalProcessor implements PaymentProcessor{
public void authorize(){
// Do PayPal authorization
}
}
class OtherProcessor implements PaymentProcessor{
public void authorize(){
// Do other processor authorization
}
}
class PaymentFactory{
public static PaymentProcessor create(String type){
switch(type){
case Consts.PAYPAL;
return new PaypalProcessor();
case Consts.OTHER_PROCESSOR;
return new OtherProcessor();
}
}
}
interface PaymentProcessor{
void authorize();
}
** The code won't compile, I know :)
Simply add the eventhandler to the button when creating it.
button.Click += new EventHandler(this.button_Click);
void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}
This isn't an answer, sadly. After running into the intermittent error for some time and finally being annoyed enough to try to fix it, I have yet to find a fix. I have, however, determined a recipe for reproducing my problem, which might help others.
In my case it is SOLELY a localhost problem, on my dev machine that also has the app's DB. It's a .NET 2.0 app I'm editing with VS2005. The Win7 64 bit machine also has VS2008 and .NET 3.5 installed.
Here's what will generate the error, from a variety of forms:
A minute or two delay "waiting for localhost" and then "Connection was reset" by the browser, and global.asax
's application error trap logs:
Application_Error event: Invalid length for a Base-64 char array.
Stack Trace:
at System.Convert.FromBase64String(String s)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
In this case, it is not the SIZE of the viewstate, but something to do with page and/or viewstate caching that seems to be biting me. Setting <pages>
parameters enableEventValidation="false"
, and viewStateEncryption="Never"
in the Web.config
did not change the behavior. Neither did setting the maxPageStateFieldLength
to something modest.
When wrapping a pointer in a unique_ptr
you cannot have multiple copies of unique_ptr
. The shared_ptr
holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr
is copied, this counter is incremented. Each time a shared_ptr
is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.
As you need access to your hostname variable in every component, and to change it to localhost while in development mode, or to production hostname when in production mode, you can define this variable in the prototype.
Like this:
Vue.prototype.$hostname = 'http://localhost:3000'
And $hostname will be available in all Vue instances:
new Vue({
beforeCreate: function () {
console.log(this.$hostname)
}
})
In my case, to automatically change from development to production, I've defined the $hostname prototype according to a Vue production tip variable in the file where I instantiated the Vue.
Like this:
Vue.config.productionTip = false
Vue.prototype.$hostname = (Vue.config.productionTip) ? 'https://hostname' : 'http://localhost:3000'
An example can be found in the docs: Documentation on Adding Instance Properties
More about production tip config can be found here:
If you want to examine elements inside a dataframe you should not be using ls()
which only looks at the names of objects in the current workspace (or if used inside a function in the current environment). Rownames or elements inside such objects are not visible to ls()
(unless of course you add an environment argument to the ls(.)
-call). Try using grep()
which is the workhorse function for pattern matching of character vectors:
result <- a[ grep("blue", a$x) , ] # Note need to use `a$` to get at the `x`
If you want to use subset then consider the closely related function grepl()
which returns a vector of logicals can be used in the subset argument:
subset(a, grepl("blue", a$x))
x
2 blue1
3 blue2
Edit: Adding one "proper" use of glob2rx within subset():
result <- subset(a, grepl(glob2rx("blue*") , x) )
result
x
2 blue1
3 blue2
I don't think I actually understood glob2rx
until I came back to this question. (I did understand the scoping issues that were ar the root of the questioner's difficulties. Anybody reading this should now scroll down to Gavin's answer and upvote it.)
I wasn't able to make the accepted answer work in a Docker container.
What worked for me was to set the Personal Access Token from github in a file .nextrc
ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n login $GITHUB_READ_TOKEN" > ~/.netrc
RUN npm install --only=production --force \
&& npm cache clean --force
RUN rm ~/.netrc
in package.json
"my-lib": "github:username/repo",
onMouseOver and onMouseLeave with setState at first seemed like a bit of overhead to me - but as this is how react works, it seems the easiest and cleanest solution to me.
rendering a theming css serverside for example, is also a good solution and keeps the react components more clean.
if you dont have to append dynamic styles to elements ( for example for a theming ) you should not use inline styles at all but use css classes instead.
this is a traditional html/css rule to keep html / JSX clean and simple.
Just for completeness: Stream solution since Java 8.
final String[] shiftedArray = Arrays.stream(array)
.skip(1)
.toArray(String[]::new);
I think I sticked with the System.arraycopy()
in your situtation. But the best long-term solution might be to convert everything to Immutable Collections (Guava, Vavr), as long as those collections are short-lived.
This means that You want a value "1" as output or Most of the time used as Inner Queries because for some reason you want to calculate the outer queries based on the result of inner queries.. not all the time you use 1 but you have some specific values...
This will statically gives you output as value 1.
I also needed to install npm in Windows and got it through the Chocolatey pacakage manager. For those who haven't heard about it, Chocolatey is a package manager for Windows, that gives you the convenience of an apt-get in Windows environments. To get it go to https://chocolatey.org/ where there's a PowerShell script to download it and install it. After that you can run:
chocolatey install npm
and you're good to go.
Note that the standalone npm is no longer being updated and the last version that is out there is known to have problems on Windows. Another option you can look at is extracting npm from the MSI using LessMSI.
To eliminate the need for the cmd variable, you can do this:
eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
I start versioning at the lowest (non hotfix) segement. I do not limit this segment to 10. Unless you are tracking builds then you just need to decide when you want to apply an increment. If you have a QA phase then that might be where you apply an increment to the lowest segment and then the next segement up when it passes QA and is released. Leave the topmost segment for Major behavior/UI changes.
If you are like me you will make it a hybrid of the methods so as to match the pace of your software's progression.
I think the most accepted pattern a.b.c. or a.b.c.d especially if you have QA/Compliance in the mix. I have had so much flack around date being a regular part of versions that I gave it up for mainstream.
I do not track builds so I like to use the a.b.c pattern unless a hotfix is involved. When I have to apply a hotfix then I apply parameter d as a date with time. I adopted the time parameter as d because there is always the potential of several in a day when things really blow up in production. I only apply the d segment (YYYYMMDDHHNN) when I'm diverging for a production fix.
I personally wouldn't be opposed to a software scheme of va.b revc where c is YYYYMMDDHHMM or YYYYMMDD.
All that said. If you can just snag a tool to configure and run with it will keep you from the headache having to marshall the opinion facet of versioning and you can just say "use the tool"... because everyone in the development process is typically so compliant.
http://www.vancelucas.com/blog/fixing-ie7-z-index-issues-with-jquery/
$(function() {
var zIndexNumber = 1000;
$('div').each(function() {
$(this).css('zIndex', zIndexNumber);
zIndexNumber -= 10;
});
});
Another crazy solution is (without converting in a string):
number = 123.456
temp = 1
while (number*temp)%10 != 0:
temp = temp *10
print temp
print number
temp = temp /10
number = number*temp
number_final = number%temp
print number_final
To simplify what others are saying:
Use Console.ReadKey();
.
This makes it so the program is waiting on the user to press a normal key on the keyboard
Source: I use it in my programs for console applications.
Try using setAttribute
instead:
document.getElementById('img')
.setAttribute(
'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
);
Real answer: (And make sure you remove the line-breaks in the base64.)
After doing an insert into a table with an identity column, you can reference @@IDENTITY to get the value: http://msdn.microsoft.com/en-us/library/aa933167%28v=sql.80%29.aspx
Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.
To append 'api'
to my baseURL, I have my default baseURL set as,
axios.defaults.baseURL = '/api/';
Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'
axios({
method:'post',
url:'logout',
baseURL: '/',
})
.then(response => {
window.location.reload();
})
.catch(error => {
console.log(error);
});
As of Java 1.7, there's a new way: java.nio.file.Files.write
import java.nio.file.Files;
import java.nio.file.Paths;
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
Files.write(Paths.get("target-file"), encoded);
Java 1.7 also resolves the embarrassment that Kevin describes: reading a file is now:
byte[] data = Files.readAllBytes(Paths.get("source-file"));
If we want the strict type safety and scoped enum, using enum class
is good in C++11.
If we had to work in C++98, we can using the advice given by InitializeSahib
,San
to enable the scoped enum.
If we also want the strict type safety, the follow code can implement somthing like enum
.
#include <iostream>
class Color
{
public:
static Color RED()
{
return Color(0);
}
static Color BLUE()
{
return Color(1);
}
bool operator==(const Color &rhs) const
{
return this->value == rhs.value;
}
bool operator!=(const Color &rhs) const
{
return !(*this == rhs);
}
private:
explicit Color(int value_) : value(value_) {}
int value;
};
int main()
{
Color color = Color::RED();
if (color == Color::RED())
{
std::cout << "red" << std::endl;
}
return 0;
}
The code is modified from the class Month example in book Effective C++ 3rd: Item 18
It's as easy as:
delete object.keyname;
or
delete object["keyname"];
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
$("#datepicker").datepicker("option", "dateFormat", "yy-mm-dd ");
For the time picker, you should add timepicker to Datepicker, and it would be formatted with one equivalent command.
EDIT
Use this one that extend jQuery UI Datepicker. You can pick up both date and time.
Option 1: Momentjs:
Install:
npm install moment --save
Import:
import * as moment from 'moment';
Usage:
let formattedDate = (moment(yourDate)).format('DD-MMM-YYYY HH:mm:ss')
Option 2: Use DatePipe if you are doing Angular:
Import:
import { DatePipe } from '@angular/common';
Usage:
const datepipe: DatePipe = new DatePipe('en-US')
let formattedDate = datepipe.transform(yourDate, 'DD-MMM-YYYY HH:mm:ss')
You can try doing a replace of #region with \n, turning extended search mode on.
use
%cd SwitchFrequencyAnalysis
to change the current working directory for the notebook environment (and not just the subshell that runs your ! command).
you can confirm it worked with the pwd
command like this:
!pwd
further information about jupyter / ipython magics: http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-cd
Probably something like this? (UNTESTED)
Sub Sample()
Dim strWB4, strMyMacro
strMyMacro = "Sheet1.my_macro_name"
'
'~~> Rest of Code
'
'loop through the folder and get the file names
For Each Fil In FLD.Files
Set x4WB = x1.Workbooks.Open(Fil)
x4WB.Application.Visible = True
x1.Run strMyMacro
x4WB.Close
Do Until IsWorkBookOpen(Fil) = False
DoEvents
Loop
Next
'
'~~> Rest of Code
'
End Sub
'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Note that Date.getDate
only returns the day of the month. You can add a day by calling Date.setDate
and appending 1.
// Create new Date instance
var date = new Date()
// Add a day
date.setDate(date.getDate() + 1)
JavaScript will automatically update the month and year for you.
EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.
Cause you need to add jQuery library to your file:
jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.
<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>
This method does the trick.
boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
Example of usage:
class Main {
static boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
public static void main(String[] a) {
char[] charArray = new char[] {'h','e','l','l','o'};
if (!contains('q', charArray)) {
// Do something...
System.out.println("Hello world!");
}
}
}
Alternative way:
if (!String.valueOf(charArray).contains("q")) {
// do something...
}
Based on some previous answers, I came up with this:
<form>
<button id='but' type='submit'>do not click me</button>
<input type='text' placeholder='press enter'>
</form>
$('#but').click(function(e) {
alert('button press');
e.preventDefault();
});
Take a look at the Fiddle
EDIT: If you dont want to add additional html elements, you can do this with JS only:
$("input").keyup(function(event) {
if (event.keyCode === 13) {
$("button").click();
}
});
Stored procedures can be executed like below
string cmd = Constants.StoredProcs.usp_AddRoles.ToString() + " @userId, @roleIdList";
int result = db.Database
.ExecuteSqlCommand
(
cmd,
new SqlParameter("@userId", userId),
new SqlParameter("@roleIdList", roleId)
);
Expanding on AnaPana's answer, how to remove an extension using pathlib (Python >= 3.4):
>>> from pathlib import Path
>>> filename = Path('/some/path/somefile.txt')
>>> filename_wo_ext = filename.with_suffix('')
>>> filename_replace_ext = filename.with_suffix('.jpg')
>>> print(filename)
/some/path/somefile.ext
>>> print(filename_wo_ext)
/some/path/somefile
>>> print(filename_replace_ext)
/some/path/somefile.jpg
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
This just worked for me on Ubuntu 16:
Download ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip') from Oracle web site and then do following script (you can do piece by piece and I did as a ROOT):
apt-get install -y python-dev build-essential libaio1
mkdir -p /opt/ora/
cd /opt/ora/
## Now put 2 ZIP files:
# ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip')
# into /opt/ora/ and unzip them -> both will be unzipped into 1 directory: /opt/ora/instantclient_12_2
rm -rf /etc/profile.d/oracle.sh
echo "export ORACLE_HOME=/opt/ora/instantclient_12_2" >> /etc/profile.d/oracle.sh
echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME" >> /etc/profile.d/oracle.sh
chmod 777 /etc/profile.d/oracle.sh
source /etc/profile.d/oracle.sh
env | grep -i ora # This will check current ENVIRONMENT settings for Oracle
rm -rf /etc/ld.so.conf.d/oracle.conf
echo "/opt/ora/instantclient_12_2" >> /etc/ld.so.conf.d/oracle.conf
ldconfig
cd $ORACLE_HOME
ls -lrth libclntsh* # This will show which version of 'libclntsh' you have... --> needed for following line:
ln -s libclntsh.so.12.1 libclntsh.so
pip install cx_Oracle # Maybe not needed but I did it anyway (only pip install cx_Oracle without above steps did not work for me...)
Your python scripts are now ready to use 'cx_Oracle'... Enjoy!
At the latest versions of asp.net core you should use the following initialization:
services.AddAutoMapper(typeof(YourMappingProfileClass));
Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:
SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
) AS SUBQUERY
Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.
Try
SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
FROM Project_Assigned pa
INNER JOIN Account a
ON pa.AccountID = a.Account_ID
INNER JOIN Project p
ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
ON a.Account_ID = c.Account_ID
WHERE a.Access_Type = 'Client';
<ListView
android:clipToPadding="false"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:dividerHeight="10dp"
android:divider="@null"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
and set paddingTop
, paddingBottom
and dividerHeight
to the same value to get equal spacing between all elements and space at the top and bottom of the list.
I set clipToPadding
to false
to let the views be drawn in this padded area.
I set divider
to @null
to remove the lines between list elements.
In the newer version of datatables (version 1.10.7) it seems things have changed. The way to prevent DataTables from automatically sorting by the first column is to set the order
option to an empty array.
You just need to add the following parameter to the DataTables options:
"order": []
Set up your DataTable as follows in order to override the default setting:
$('#example').dataTable( {
"order": [],
// Your other options here...
} );
That will override the default setting of "order": [[ 0, 'asc' ]]
.
You can find more details regarding the order
option here:
https://datatables.net/reference/option/order
//lower for v4 some version
public function videos() {
$instance =$this->hasMany('Video');
$instance->getQuery()->where('available','=', 1);
return $instance
}
//v5
public function videos() {
return $this->hasMany('Video')->where('available','=', 1);
}
While size(A,2)
is correct, I find it's much more readable to first define
rows = @(x) size(x,1);
cols = @(x) size(x,2);
and then use, for example, like this:
howManyColumns_in_A = cols(A)
howManyRows_in_A = rows(A)
It might appear as a small saving, but size(.., 1)
and size(.., 2)
must be some of the most commonly used functions, and they are not optimally readable as-is.
Throwable
is super class of Exception
as well as Error
. In normal cases we should always catch sub-classes of Exception
, so that the root cause doesn't get lost.
Only special cases where you see possibility of things going wrong which is not in control of your Java code, you should catch Error
or Throwable
.
I remember catching Throwable to flag that a native library is not loaded.
Using query comprehension syntax you could achieve the orderby as follows:
var uniqueColors = (from dbo in database.MainTable
where dbo.Property
orderby dbo.Color.Name ascending
select dbo.Color.Name).Distinct();
To change it permanently in Windows (10), edit the my.ini
file. To find the my.ini file, look at the path in the Windows server. E.g. for my MySQL 5.7 instance, the service is MYSQL57
, and in this service's properties the Path to executable is:
"C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe" --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.7\my.ini" MySQL57
I.e. edit the my.ini
file in C:\ProgramData\MySQL\MySQL Server 5.7\
. Note that C:\ProgramData\
is a hidden folder in Windows (10). My file has the following lines of interest:
# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Remove STRICT_TRANS_TABLES,
from this sql-mode line, save the file and restart the MYSQL57 service. Verify the result by executing SHOW VARIABLES LIKE 'sql_mode';
in a (new) MySQL Command Line Client window.
(I found the other answers and documents on the web useful, but none of them seem to tell you where to find the my.ini file in Windows.)
LocalDate.parse(
"23-Mar-2017" ,
DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US )
)
The Question and other Answers are now outdated, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
You seem to be dealing with date-only values. So do not use a date-time class. Instead use LocalDate
. The LocalDate
class represents a date-only value without time-of-day and without time zone.
Specify a Locale
to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Parse a string.
String input = "23-Mar-2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f );
Generate a string.
String output = ld.format( f );
If you were given numbers rather than text for the year, month, and day-of-month, use LocalDate.of
.
LocalDate ld = LocalDate.of( 2017 , 3 , 23 ); // ( year , month 1-12 , day-of-month )
See this code run live at IdeOne.com.
input: 23-Mar-2017
ld.toString(): 2017-03-23
output: 23-Mar-2017
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
PHP 7.1.0 has introduced the iterable
pseudo-type and the is_iterable()
function, which is specially designed for such a purpose:
This […] proposes a new
iterable
pseudo-type. This type is analogous tocallable
, accepting multiple types instead of one single type.
iterable
accepts anyarray
or object implementingTraversable
. Both of these types are iterable usingforeach
and can be used withyield
from within a generator.
function foo(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
This […] also adds a function
is_iterable()
that returns a boolean:true
if a value is iterable and will be accepted by theiterable
pseudo-type,false
for other values.
var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)
You can also use the function is_array($var)
to check if the passed variable is an array:
<?php
var_dump( is_array(array()) ); // true
var_dump( is_array(array(1, 2, 3)) ); // true
var_dump( is_array($_SERVER) ); // true
?>
Read more in How to check if a variable is an array in PHP?
Use document.write().
<html>_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
var number = 123;_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>_x000D_
the value for number is:_x000D_
<script type="text/javascript">_x000D_
document.write(number)_x000D_
</script>_x000D_
</h1>_x000D_
</body>_x000D_
</html>
_x000D_
try to compile
compile 'com.android.support:cardview-v7:25.3.1'
Description of the possible values:
left
: No floating elements allowed on the left sideright
: No floating elements allowed on the right sideboth
: No floating elements allowed on either the left or the right sidenone
: Default. Allows floating elements on both sidesinherit
: Specifies that the value of the clear property should be inherited from the parent element
Source: w3schools.com
intel mkl suggests in-place and out-of-place transposition/copying matrices. here is the link to the documentation. I would recommend trying out of place implementation as faster ten in-place and into the documentation of the latest version of mkl contains some mistakes.
You should never need to modify the path directly, either through environment variables or sys.path
. Whether you use the os (ex. apt-get
), or pip
in a virtualenv, packages will be installed to a location already on the path.
In your example, GNU Radio is installed to the system Python 2's standard site-packages
location, which is already in the path. Pointing PyCharm at the correct interpreter is enough; if it isn't there is something else wrong that isn't apparent. It may be that /usr/bin/python
does not point to the same interpreter that GNU Radio was installed in; try pointing specifically at the python2.7
binary. Or, PyCharm used to be somewhat bad at detecting packages; File > Invalidate Caches > Invalidate and Restart
would tell it to rescan.
This answer will cover how you should set up a project environment, install packages in different scenarios, and configure PyCharm. I refer multiple times to the Python Packaging User Guide, written by the same group that maintains the official Python packaging tools.
The correct way to develop a Python application is with a virtualenv. Packages and version are installed without affecting the system or other projects. PyCharm has a built-in interface to create a virtualenv and install packages. Or you can create it from the command line and then point PyCharm at it.
$ cd MyProject
$ python2 -m virtualenv env
$ . env/bin/activate
$ pip install -U pip setuptools # get the latest versions
$ pip install flask # install other packages
In your PyCharm project, go to File > Settings > Project > Project Interpreter
. If you used virtualenvwrapper
or PyCharm to create the env, then it should show up in the menu. If not, click the gear, choose Add Local
, and locate the Python binary in the env. PyCharm will display all the packages in the selected env.
In some cases, such as with GNU Radio, there is no package to install with pip
, the package was installed system-wide when you install the rest of GNU Radio (ex. apt-get install gnuradio
). In this case, you should still use a virtualenv, but you'll need to make it aware of this system package.
$ python2 -m virtualenv --system-site-packages env
Unfortunately it looks a little messy, because all system packages will now appear in your env, but they are just links, you can still safely install or upgrade packages without affecting the system.
In some cases, you will have multiple local packages you're developing, and will want one project to use the other package. In this case you might think you have to add the local package to the other project's path, but this is not the case. You should install your package in development mode. All this requires is adding a setup.py
file to your package, which will be required anyway to properly distribute and deploy the package later.
Minimal setup.py
for your first project:
from setuptools import setup, find_packages
setup(
name='mypackage',
version='0.1',
packages=find_packages(),
)
Then install it in your second project's env:
$ pip install -e /path/to/first/project
Just like normal background-color: #f0f
You just need a way to target it, eg: <option id="myPinkOption">blah</option>
Objective C
For iOS 10
we need integrate willPresentNotification
method for show notification banner in foreground
.
If app in foreground mode(active)
- (void)userNotificationCenter:(UNUserNotificationCenter* )center willPresentNotification:(UNNotification* )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
NSLog( @"Here handle push notification in foreground" );
//For notification Banner - when app in foreground
completionHandler(UNNotificationPresentationOptionAlert);
// Print Notification info
NSLog(@"Userinfo %@",notification.request.content.userInfo);
}
You can do it faster without any imports just by using magics:
%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0
Notice that all env variable are strings, so no need to use "
. You can verify that env-variable is set up by running: %env <name_of_var>
. Or check all of them with %env
.
How to use a clock and do assertions
This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.
The key idea is that the process
blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.
library ieee;
use ieee.std_logic_1164.all;
entity counter_tb is
end counter_tb;
architecture behav of counter_tb is
constant width : natural := 2;
constant clk_period : time := 1 ns;
signal clk : std_logic := '0';
signal data : std_logic_vector(width-1 downto 0);
signal count : std_logic_vector(width-1 downto 0);
type io_t is record
load : std_logic;
data : std_logic_vector(width-1 downto 0);
count : std_logic_vector(width-1 downto 0);
end record;
type ios_t is array (natural range <>) of io_t;
constant ios : ios_t := (
('1', "00", "00"),
('0', "UU", "01"),
('0', "UU", "10"),
('0', "UU", "11"),
('1', "10", "10"),
('0', "UU", "11"),
('0', "UU", "00"),
('0', "UU", "01")
);
begin
counter_0: entity work.counter port map (clk, load, data, count);
process
begin
for i in ios'range loop
load <= ios(i).load;
data <= ios(i).data;
wait until falling_edge(clk);
assert count = ios(i).count;
end loop;
wait;
end process;
process
begin
for i in 1 to 2 * ios'length loop
wait for clk_period / 2;
clk <= not clk;
end loop;
wait;
end process;
end behav;
The counter would look like this:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned
entity counter is
generic (
width : in natural := 2
);
port (
clk, load : in std_logic;
data : in std_logic_vector(width-1 downto 0);
count : out std_logic_vector(width-1 downto 0)
);
end entity counter;
architecture rtl of counter is
signal cnt : unsigned(width-1 downto 0);
begin
process(clk) is
begin
if rising_edge(clk) then
if load = '1' then
cnt <= unsigned(data);
else
cnt <= cnt + 1;
end if;
end if;
end process;
count <= std_logic_vector(cnt);
end architecture rtl;
Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches
You can do that with datetime.strptime()
Example:
>>> from datetime import datetime
>>> datetime.strptime('2012-02-10' , '%Y-%m-%d')
datetime.datetime(2012, 2, 10, 0, 0)
>>> _.isoweekday()
5
You can find the table with all the strptime
directive here.
To increment by 2 days if .isweekday() == 6
, you can use timedelta()
:
>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-11' , '%Y-%m-%d')
>>> if date.isoweekday() == 6:
... date += datetime.timedelta(days=2)
...
>>> date
datetime.datetime(2012, 2, 13, 0, 0)
>>> date.strftime('%Y-%m-%d') # if you want a string again
'2012-02-13'
Open app.config on client side and add maxBufferSize and maxReceivedMessageSize attributes if it is not available
Original
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap"/>
</basicHttpBinding>
</bindings>
After Edit/Update
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
</basicHttpBinding>
</bindings>
I always default to NOT EXISTS
.
The execution plans may be the same at the moment but if either column is altered in the future to allow NULL
s the NOT IN
version will need to do more work (even if no NULL
s are actually present in the data) and the semantics of NOT IN
if NULL
s are present are unlikely to be the ones you want anyway.
When neither Products.ProductID
or [Order Details].ProductID
allow NULL
s the NOT IN
will be treated identically to the following query.
SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
The exact plan may vary but for my example data I get the following.
A reasonably common misconception seems to be that correlated sub queries are always "bad" compared to joins. They certainly can be when they force a nested loops plan (sub query evaluated row by row) but this plan includes an anti semi join logical operator. Anti semi joins are not restricted to nested loops but can use hash or merge (as in this example) joins too.
/*Not valid syntax but better reflects the plan*/
SELECT p.ProductID,
p.ProductName
FROM Products p
LEFT ANTI SEMI JOIN [Order Details] od
ON p.ProductId = od.ProductId
If [Order Details].ProductID
is NULL
-able the query then becomes
SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
AND NOT EXISTS (SELECT *
FROM [Order Details]
WHERE ProductId IS NULL)
The reason for this is that the correct semantics if [Order Details]
contains any NULL
ProductId
s is to return no results. See the extra anti semi join and row count spool to verify this that is added to the plan.
If Products.ProductID
is also changed to become NULL
-able the query then becomes
SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
AND NOT EXISTS (SELECT *
FROM [Order Details]
WHERE ProductId IS NULL)
AND NOT EXISTS (SELECT *
FROM (SELECT TOP 1 *
FROM [Order Details]) S
WHERE p.ProductID IS NULL)
The reason for that one is because a NULL
Products.ProductId
should not be returned in the results except if the NOT IN
sub query were to return no results at all (i.e. the [Order Details]
table is empty). In which case it should. In the plan for my sample data this is implemented by adding another anti semi join as below.
The effect of this is shown in the blog post already linked by Buckley. In the example there the number of logical reads increase from around 400 to 500,000.
Additionally the fact that a single NULL
can reduce the row count to zero makes cardinality estimation very difficult. If SQL Server assumes that this will happen but in fact there were no NULL
rows in the data the rest of the execution plan may be catastrophically worse, if this is just part of a larger query, with inappropriate nested loops causing repeated execution of an expensive sub tree for example.
This is not the only possible execution plan for a NOT IN
on a NULL
-able column however. This article shows another one for a query against the AdventureWorks2008
database.
For the NOT IN
on a NOT NULL
column or the NOT EXISTS
against either a nullable or non nullable column it gives the following plan.
When the column changes to NULL
-able the NOT IN
plan now looks like
It adds an extra inner join operator to the plan. This apparatus is explained here. It is all there to convert the previous single correlated index seek on Sales.SalesOrderDetail.ProductID = <correlated_product_id>
to two seeks per outer row. The additional one is on WHERE Sales.SalesOrderDetail.ProductID IS NULL
.
As this is under an anti semi join if that one returns any rows the second seek will not occur. However if Sales.SalesOrderDetail
does not contain any NULL
ProductID
s it will double the number of seek operations required.
Just as a heads up...
var data = JSON.parse(responseBody);
has been deprecated.
Postman Learning Center now suggests
var jsonData = pm.response.json();
A couple of things:
(?:
not (:?
If you address the first problem, you won't need groups at all.
*That is, a blank or beginning/end of string.
It will prints the string"something" three times.
JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};
for ( JLabel label : labels )
{
label.setText("something");
panel.add(label);
}
EDIT
Disregard - you can't use ItemOf (that's what I get for typing before I test). I'd strikethrough the text if I could figure out how...or maybe I'll simply delete the answer, since it was ultimately wrong and useless.
END EDIT
You can use the ItemOf(string)
property in the XmlAttributesCollection to see if the attribute exists. It returns null if it's not found.
foreach (XmlNode xNode in nodeListName)
{
if (xNode.ParentNode.Attributes.ItemOf["split"] != null)
{
parentSplit = xNode.ParentNode.Attributes["split"].Value;
}
}
suppose you want to write a url to fetch some order, you can say
www.mydomain.com/order/123
where 123 is orderId.
So now the url you will use in spring mvc controller would look like
/order/{orderId}
Now order id can be declared a path variable
@RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public String getOrder(@PathVariable String orderId){
//fetch order
}
if you use url www.mydomain.com/order/123, then orderId variable will be populated by value 123 by spring
Also note that PathVariable differs from requestParam as pathVariable is part of URL.
The same url using request param would look like www.mydomain.com/order?orderId=123
The tel:
scheme was used in the late 1990s and documented in early 2000 with RFC 2806 (which was obsoleted by the more-thorough RFC 3966 in 2004) and continues to be improved. Supporting tel:
on the iPhone was not an arbitrary decision.
callto:
, while supported by Skype, is not a standard and should be avoided unless specifically targeting Skype users.
Me? I'd just start including properly-formed tel:
URIs on your pages (without sniffing the user agent) and wait for the rest of the world's phones to catch up :) .
Example:
<a href="tel:+18475555555">1-847-555-5555</a>
_x000D_
Here's a slightly less complicated answer:
NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];
See also substringWithRange and substringFromIndex
This worked for me in Swift 5.0. Set the Storyboard Id in the identity inspector as "destinationVC".
@IBAction func buttonTapped(_ sender: Any) {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let destVC = storyboard.instantiateViewController(withIdentifier: "destinationVC") as! MyViewController
destVC.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
destVC.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(destVC, animated: true, completion: nil)
}
For your purposes you can use this.activatedRoute.pathFromRoot
.
import {ActivatedRoute} from "@angular/router";
constructor(public activatedRoute: ActivatedRoute){
}
With the help of pathFromRoot you can get the list of parent urls and check if the needed part of the URL matches your condition.
For additional information please check this article http://blog.2muchcoffee.com/getting-current-state-in-angular2-router/ or install ng2-router-helper from npm
npm install ng2-router-helper
Learn more about PHP and the MySQLi Library at PHP.net.
First, start a connection to the database. Do this by making all the string variables needed in order to connect, adjust them to fit your environment, then create a new connection object with new mysqli()
and initialize it with the previously made variables as its parameters. Now, check the connection for errors and display a message whether any were found or not. Like this:
<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>
Next, make a variable that will hold the query as a string, in this case its a select
statement with a limit
of 100 records to keep the list small. Then, we can execute it by calling the mysqli::query()
function from our connection object. Now, it's time to display some data. Start by opening up a <table>
tag through echo
, then fetch one row at a time in the form of a numerical array with mysqli::fetch_row()
which can then be displayed with a simple for loop. mysqli::field_count
should be self explanatory. Don't forget to use <td></td>
for each value, and also to open and close each row with echo"<tr>"
and echo"</tr>
. Finally we close the table, and the connection as well with mysqli::close()
.
<?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
echo "<tr>";
for($i = 0; $i < $queryResult->field_count; $i++){
echo "<td>$queryRow[$i]</td>";
}
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
Based on the answer I created MapBuilder
class:
public class MapBuilder {
public static Map<String, Object> build(Object... data) {
Map<String, Object> result = new LinkedHashMap<>();
if (data.length % 2 != 0) {
throw new IllegalArgumentException("Odd number of arguments");
}
String key = null;
Integer step = -1;
for (Object value : data) {
step++;
switch (step % 2) {
case 0:
if (value == null) {
throw new IllegalArgumentException("Null key value");
}
key = (String) value;
continue;
case 1:
result.put(key, value);
break;
}
}
return result;
}
}
then I created class StringFormat
for String formatting:
public final class StringFormat {
public static String format(String format, Object... args) {
Map<String, Object> values = MapBuilder.build(args);
for (Map.Entry<String, Object> entry : values.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
format = format.replace("$" + key, value.toString());
}
return format;
}
}
which you could use like that:
String bookingDate = StringFormat.format("From $startDate to $endDate"),
"$startDate", formattedStartDate,
"$endDate", formattedEndDate
);
You can abort a task like a thread if you can cause the task to be created on its own thread and call Abort
on its Thread
object. By default, a task runs on a thread pool thread or the calling thread - neither of which you typically want to abort.
To ensure the task gets its own thread, create a custom scheduler derived from TaskScheduler
. In your implementation of QueueTask
, create a new thread and use it to execute the task. Later, you can abort the thread, which will cause the task to complete in a faulted state with a ThreadAbortException
.
Use this task scheduler:
class SingleThreadTaskScheduler : TaskScheduler
{
public Thread TaskThread { get; private set; }
protected override void QueueTask(Task task)
{
TaskThread = new Thread(() => TryExecuteTask(task));
TaskThread.Start();
}
protected override IEnumerable<Task> GetScheduledTasks() => throw new NotSupportedException(); // Unused
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => throw new NotSupportedException(); // Unused
}
Start your task like this:
var scheduler = new SingleThreadTaskScheduler();
var task = Task.Factory.StartNew(action, cancellationToken, TaskCreationOptions.LongRunning, scheduler);
Later, you can abort with:
scheduler.TaskThread.Abort();
Note that the caveat about aborting a thread still applies:
The
Thread.Abort
method should be used with caution. Particularly when you call it to abort a thread other than the current thread, you do not know what code has executed or failed to execute when the ThreadAbortException is thrown, nor can you be certain of the state of your application or any application and user state that it is responsible for preserving. For example, callingThread.Abort
may prevent static constructors from executing or prevent the release of unmanaged resources.
I experienced this issue and couldn't figure out a fix for a few hours, until I realised I had incorrectly prevented
native events from occurring with:
<input type="checkbox" @click.prevent="toggleConfirmedStatus(render.uuid)"
:checked="confirmed.indexOf(render.uuid) > -1"
:value="render.uuid"
/>
removing the .prevent
from the @click
handler fixed my issue.
Download Notepad++ (notepad-plus-plus.org) it opens nearly any file format and recognizes breaks, comments and does all the same color coding as the original language formatting.
The best source I have for this kind of question is this page: http://www.quirksmode.org/js/keys.html
What they say is that the key codes are odd on Safari, and consistent everywhere else (except that there's no keypress event on IE, but I believe keydown works).
I ran into this same error and solved it by running:
dev.off()
and then running the plot again. I think the graphics device was messed up earlier somehow by exporting some graphics and it didn't get reset. This worked for me and it's simpler than reinstalling ggplot2.
Use a memory stream
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, ...);
return ms.ToArray();
}
In English:
ContentType
: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8
, which is fine for most cases.Accepts
: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType
.DataType
: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp
.You can also do the following
string filename = Path.ChangeExtension(Path.GetTempFileName(), ".csv");
and this also works as expected
string filename = Path.ChangeExtension(Path.GetTempPath() + Guid.NewGuid().ToString(), ".csv");
Sounds like you're calling df.plot()
. That error indicates that you're trying to plot a frame that has no numeric data. The data types shouldn't affect what you print()
.
Use print(df.iloc[159220])
How about this?
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df
Out[16]:
one two three
0 a 1.2 4.2
1 b 70 0.03
2 x 5 0
df.dtypes
Out[17]:
one object
two object
three object
df[['two', 'three']] = df[['two', 'three']].astype(float)
df.dtypes
Out[19]:
one object
two float64
three float64
Another possible cause for this error message is if the HTTP Method is blocked by the server or load balancer.
It seems to be standard security practice to block unused HTTP Methods. We ran into this because HEAD was being blocked by the load balancer (but, oddly, not all of the load balanced servers, which caused it to fail only some of the time). I was able to test that the request itself worked fine by temporarily changing it to use the GET method.
The error code on iOS was: Error requesting App Code: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
I know it sucks. None of the above things were really working, but I found a work around. Please be extra careful to use spaces between the apostrophes [ ' ], otherwise it will get escaped.
SELECT 'Hello ' '&' ' World';
Hello & World
You're welcome ;)
All what you have to do is to revert the commit.
git revert {commit_id}'
Then push it
git push origin -f
Please after adding both framework also open each Bolts and Parse framework and add Parse and Bolts to the project then problem will be solve
The cleanest solution I have found is to set the following in my ConfigureServices method in Startup.cs (In my case I want the TZ info stripped. I always want to see the date time as the user saw it).
services.AddControllers()
.AddNewtonsoftJson(o =>
{
o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
});
The DateTimeZoneHandling options are Utc, Unspecified, Local or RoundtripKind
I would still like to find a way to be able to request this on a per-call bases.
something like
static readonly JsonMediaTypeFormatter _jsonFormatter = new JsonMediaTypeFormatter();
_jsonFormatter.SerializerSettings = new JsonSerializerSettings()
{DateTimeZoneHandling = DateTimeZoneHandling.Unspecified};
return Ok("Hello World", _jsonFormatter );
I am converting from ASP.NET and there I used the following helper method
public static ActionResult<T> Ok<T>(T result, HttpContext context)
{
var responseMessage = context.GetHttpRequestMessage().CreateResponse(HttpStatusCode.OK, result, _jsonFormatter);
return new ResponseMessageResult(responseMessage);
}
You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging
Public Sub test(mdate As String)
Dim toDay As String
mdate = Round(CDbl(CDate(mdate)), 0)
toDay = Round(CDbl(Now()), 0)
Dim Aging as String
Aging = toDay - mdate
MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub
NB: Used CDate
for convert Date String to Valid Date
I am using this in Office 2007 :)
am using this simple one
´´´´ class Connect {
public $url;
public $path;
public $username;
public $password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
//PROPFIND request that lists all requested properties.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
$response = curl_exec($ch);
curl_close($ch);
This works smoothly. Try this.
Paste these links in your head section.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
Following is the JS coding.
<script>
$(document).ready(function () {
$('#completionDate').datepicker({
dateFormat: 'yy-mm-dd', // enter date format you prefer (e.g. 2018-10-09)
changeMonth: true,
changeYear: true,
yearRange: "-50:+10",
clickInput: true,
onSelect: function (date) {
loadMusterChit();
}
});
});
</script>
UPDATE (Jan 2016): The nice little hack might not work on all browsers anymore so I have a new solution with a tiny bit of javascript below.
It doesn't feel nice, but you can just put the new lines in the html. Like this:
<textarea rows="6" id="myAddress" type="text" placeholder="My Awesome House,
1 Long St
London
Postcode
UK"></textarea>
_x000D_
Notice each line is on a new line (not being wrapped) and each 'tab' indent is 4 spaces. Granted it is not a very nice method, but it seems to work:
http://jsfiddle.net/01taylop/HDfju/
resize: none;
in the css so that the size of the textarea is fixed (See jsfiddle).Alternatively When you want a new line, hit return twice (So there is a empty line between your 'new lines'. This 'empty line' created needs to have enough tabs/spaces that would equate to the width of your textarea. It doesn't seem to matter if you have far too many, you just need enough. This is so dirty though and probably not browser compliant. I wish there was an easier way!
Check out the JSFiddle.
box-sizing
and display: block
properties on the textarea are important or the div behind it will not be the same size.resize: vertical
and a min-height
on the textarea are also important - notice how the placeholder text will wrap and expanding the textarea will keep the white background. However, commenting out the resize
property will cause issues when expanding the textarea horizontally.HTML:
<form>
<input type='text' placeholder='First Name' />
<input type='text' placeholder='Last Name' />
<div class='textarea-placeholder'>
<textarea></textarea>
<div>
First Line
<br /> Second Line
<br /> Third Line
</div>
</div>
</form>
SCSS:
$input-padding: 4px;
@mixin input-font() {
font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif;
font-size: 12px;
font-weight: 300;
line-height: 16px;
}
@mixin placeholder-style() {
color: #999;
@include input-font();
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
form {
width: 250px;
}
input,textarea {
display: block;
width: 100%;
padding: $input-padding;
border: 1px solid #ccc;
}
input {
margin-bottom: 10px;
background-color: #fff;
@include input-font();
}
textarea {
min-height: 80px;
resize: vertical;
background-color: transparent;
&.data-edits {
background-color: #fff;
}
}
.textarea-placeholder {
position: relative;
> div {
position: absolute;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: $input-padding;
background-color: #fff;
@include placeholder-style();
}
}
::-webkit-input-placeholder {
@include placeholder-style();
}
:-moz-placeholder {
@include placeholder-style();
}
::-moz-placeholder {
@include placeholder-style();
}
:-ms-input-placeholder {
@include placeholder-style();
}
Javascript:
$("textarea").on('change keyup paste', function() {
var length = $(this).val().length;
if (length > 0) {
$(this).addClass('data-edits');
} else {
$(this).removeClass('data-edits');
}
});
Either the parameter supplied for ZIP_CODE
is larger (in length) than ZIP_CODE
s column width or the parameter supplied for CITY
is larger (in length) than CITY
s column width.
It would be interesting to know the values supplied for the two ?
placeholders.
Very simple solution. Just rename your database and configure your new database name in your project.
The problem is the when you import your database, you got any errors and then the database will be corrupted. The log files will have the corrupted database name. You can rename your database easily using phpmyadmin for mysql.
phpmyadmin -> operations -> Rename database to
Resorting to a PivotTable might not count as using formulas only but seems more practical that most other suggestions so far:
if someone needs to view arrays so cool ;) use this method.. this will print to your browser console
function console($obj)
{
$js = json_encode($obj);
print_r('<script>console.log('.$js.')</script>');
}
you can use like this..
console($myObject);
Output will be like this.. so cool eh !!
You can edit the ~/.gitconfig
file in your home folder. This is where all --global
settings are saved.
I did the anaconda install but matplotlib is not plotting
It starts plotting when i did this
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Despite @Saint Hill's answer if you consider the time complexity of str.toCharArray(),
the first one is faster even for very large strings. You can run the code below to see it for yourself.
char [] ch = new char[1_000_000_00];
String str = new String(ch); // to create a large string
// ---> from here
long currentTime = System.nanoTime();
for (int i = 0, n = str.length(); i < n; i++) {
char c = str.charAt(i);
}
// ---> to here
System.out.println("str.charAt(i):"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");
/**
* ch = str.toCharArray() itself takes lots of time
*/
// ---> from here
currentTime = System.nanoTime();
ch = str.toCharArray();
for (int i = 0, n = str.length(); i < n; i++) {
char c = ch[i];
}
// ---> to here
System.out.println("ch = str.toCharArray() + c = ch[i] :"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");
output:
str.charAt(i):5.492102 (ms)
ch = str.toCharArray() + c = ch[i] :79.400064 (ms)
In the version 5.x, you can use useHistory
hook of react-router-dom
:
// Sample extracted from https://reacttraining.com/react-router/core/api/Hooks/usehistory
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
To setup GruntJS build here is the steps:
Make sure you have setup your package.json
or setup new one:
npm init
Install Grunt CLI as global:
npm install -g grunt-cli
Install Grunt in your local project:
npm install grunt --save-dev
Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:
npm install grunt-contrib-concat --save-dev
Now you need to setup your Gruntfile.js
which will describe your build process. For this sample I just combine two JS files file1.js
and file2.js
in the js
folder and generate app.js
:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
concat: {
"options": { "separator": ";" },
"build": {
"src": ["js/file1.js", "js/file2.js"],
"dest": "js/app.js"
}
}
});
// Load required modules
grunt.loadNpmTasks('grunt-contrib-concat');
// Task definitions
grunt.registerTask('default', ['concat']);
};
Now you'll be ready to run your build process by following command:
grunt
I hope this give you an idea how to work with GruntJS build.
NOTE:
You can use grunt-init
for creating Gruntfile.js
if you want wizard-based creation instead of raw coding for step 5.
To do so, please follow these steps:
npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile
For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile
to %USERPROFILE%\.grunt-init\
. PowerShell will recognize the ~
correctly.
You can use feather format file. It is extremely fast.
df.to_feather('filename.ft')
Use var args
public long sum(int... numbers){
if(numbers == null){ return 0L;}
long result = 0L;
for(int number: numbers){
result += number;
}
return result;
}
You can also check out github.com/wushilin/stream
It is a lazy stream like concept of java.util.stream.
// It doesn't really allocate the 10 elements.
stream1 := stream.Range(0, 10)
// Print each element.
stream1.Each(print)
// Add 3 to each element, but it is a lazy add.
// You only add when consume the stream
stream2 := stream1.Map(func(i int) int {
return i + 3
})
// Well, this consumes the stream => return sum of stream2.
stream2.Reduce(func(i, j int) int {
return i + j
})
// Create stream with 5 elements
stream3 := stream.Of(1, 2, 3, 4, 5)
// Create stream from array
stream4 := stream.FromArray(arrayInput)
// Filter stream3, keep only elements that is bigger than 2,
// and return the Sum, which is 12
stream3.Filter(func(i int) bool {
return i > 2
}).Sum()
Hope this helps
For example :
import java.util.ArrayList;
import java.util.List;
/**
*
* @author X2
*
* @param <T>
*/
public class HisTree<T>
{
private Node<T> root;
public HisTree(T rootData)
{
root = new Node<T>();
root.setData(rootData);
root.setChildren(new ArrayList<Node<T>>());
}
}
class Node<T>
{
private T data;
private Node<T> parent;
private List<Node<T>> children;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node<T> getParent() {
return parent;
}
public void setParent(Node<T> parent) {
this.parent = parent;
}
public List<Node<T>> getChildren() {
return children;
}
public void setChildren(List<Node<T>> children) {
this.children = children;
}
}
My Kotlin solution is to use a static Application context:
class App : Application() {
companion object {
lateinit var instance: App private set
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
And the Strings class, that I use everywhere:
object Strings {
fun get(@StringRes stringRes: Int, vararg formatArgs: Any = emptyArray()): String {
return App.instance.getString(stringRes, *formatArgs)
}
}
So you can have a clean way of getting resource strings
Strings.get(R.string.some_string)
Strings.get(R.string.some_string_with_arguments, "Some argument")
Please don't delete this answer, let me keep one.
As I needed to use this feature for my latest project (at one point we updated from 1.10.19), just to keep the users (that are already using the mockito-core version 2.1.0 or greater) up to date, the static methods from the above answers should be taken from ArgumentMatchers
class:
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.any;
Please keep this in mind if you are planning to keep your Mockito artefacts up to date as possibly starting from version 3, this class may no longer exist:
As per 2.1.0 and above, Javadoc of org.mockito.Matchers states:
Use
org.mockito.ArgumentMatchers
. This class is now deprecated in order to avoid a name clash with Hamcrest *org.hamcrest.Matchers
class. This class will likely be removed in version 3.0.
I have written a little article on mockito wildcards if you're up for further reading.
An Array of Objects
const aListOfObjects = [{
prop1: 50,
prop2: "Nothing",
prop3: "hello",
prop4: "What's up",
},
{
prop1: 88,
prop2: "Whatever",
prop3: "world",
prop4: "You get it",
},
]
Making a subset of an object or objects can be achieved by destructuring the object this way.
const sections = aListOfObjects.map(({prop1, prop2}) => ({prop1, prop2}));
Answered my own question:
IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).
So that's 39 characters max.
The issue seems to be that you are adding the deffered.promise
when deffered
is itself the promise you should be adding:
Try changing to promises.push(deffered);
so you don't add the unwrapped promise to the array.
UploadService.uploadQuestion = function(questions){
var promises = [];
for(var i = 0 ; i < questions.length ; i++){
var deffered = $q.defer();
var question = questions[i];
$http({
url : 'upload/question',
method: 'POST',
data : question
}).
success(function(data){
deffered.resolve(data);
}).
error(function(error){
deffered.reject();
});
promises.push(deffered);
}
return $q.all(promises);
}
The init(frame:)
version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:)
version will be called. Since Swift now requires an implementation of the required init?(coder:)
, I have updated the example below and changed the let
variable declarations to var
and optional. In this case, you would initialize them in awakeFromNib()
or at some later time.
class TestView : UIView {
var s: String?
var i: Int?
init(s: String, i: Int) {
self.s = s
self.i = i
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Update:
Improved and simplified version of previous directive (one instead of two) with same functionality:
.directive('myTestExpression', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
var expr = attrs.myTestExpression;
var watches = attrs.myTestExpressionWatch;
ctrl.$validators.mytestexpression = function (modelValue, viewValue) {
return expr == undefined || (angular.isString(expr) && expr.length < 1) || $parse(expr)(scope, { $model: modelValue, $view: viewValue }) === true;
};
if (angular.isString(watches)) {
angular.forEach(watches.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
ctrl.$validate();
});
});
}
}
};
}])
Example usage:
<input ng-model="price1"
my-test-expression="$model > 0"
my-test-expression-watch="price2,someOtherWatchedPrice" />
<input ng-model="price2"
my-test-expression="$model > 10"
my-test-expression-watch="price1"
required />
Result: Mutually dependent test expressions where validators are executed on change of other's directive model and current model.
Test expression has local $model
variable which you should use to compare it to other variables.
Previously:
I've made an attempt to improve @Plantface code by adding extra directive. This extra directive very useful if our expression needs to be executed when changes are made in more than one ngModel variables.
.directive('ensureExpression', ['$parse', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
controller: function () { },
scope: true,
link: function (scope, element, attrs, ngModelCtrl) {
scope.validate = function () {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelCtrl.$setValidity('expression', booleanResult);
};
scope.$watch(attrs.ngModel, function(value) {
scope.validate();
});
}
};
}])
.directive('ensureWatch', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ensureExpression',
link: function (scope, element, attrs, ctrl) {
angular.forEach(attrs.ensureWatch.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
scope.validate();
});
});
}
};
}])
Example how to use it to make cross validated fields:
<input name="price1"
ng-model="price1"
ensure-expression="price1 > price2"
ensure-watch="price2" />
<input name="price2"
ng-model="price2"
ensure-expression="price2 > price3"
ensure-watch="price3" />
<input name="price3"
ng-model="price3"
ensure-expression="price3 > price1 && price3 > price2"
ensure-watch="price1,price2" />
ensure-expression
is executed to validate model when ng-model
or any of ensure-watch
variables is changed.
My Mac OS didn't like that it didn't find the env variable set in the settings file:
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')
but after adding the env var to my local Mac OS dev environment, the error disappeared:
export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'
In my case, I also needed to add the --settings
param:
python3 manage.py check --deploy --settings myappname.settings.production
where production.py is a file containing production specific settings inside a settings folder.
memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:
(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))
If you don't yet have the distinguished name, you can search for it with:
(&(objectCategory=group)(cn=myCustomGroup))
and return the attribute distinguishedName
. Case may matter.
With JUnit 5.4, you can specify the order :
@Test
@Order(2)
public void sendEmailTestGmail() throws MessagingException {
you just need to annotate your class
@TestMethodOrder(OrderAnnotation.class)
https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-execution-order
i'm using this in my project and it works very well !
Use ifelse
df %>%
mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
ifelse(a == 0 | a == 1 | a == 4 | a == 3 | c == 4, 3, NA)))
Added - if_else: Note that in dplyr 0.5 there is an if_else
function defined so an alternative would be to replace ifelse
with if_else
; however, note that since if_else
is stricter than ifelse
(both legs of the condition must have the same type) so the NA
in that case would have to be replaced with NA_real_
.
df %>%
mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
if_else(a == 0 | a == 1 | a == 4 | a == 3 | c == 4, 3, NA_real_)))
Added - case_when Since this question was posted dplyr has added case_when
so another alternative would be:
df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
a == 0 | a == 1 | a == 4 | a == 3 | c == 4 ~ 3,
TRUE ~ NA_real_))
Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if
at the end to replace 0 with NA.
df %>%
mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
3 * (a == 0 | a == 1 | a == 4 | a == 3 | c == 4),
g = na_if(g, 0))
A combination of this http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment
with the php upload file example would work. In the upload file example instead of using move_uploaded_file to move it from the temporary folder you would just open it:
$attachment = chunk_split(base64_encode(file_get_contents($tmp_file)));
where $tmp_file = $_FILES['userfile']['tmp_name'];
and send it as an attachment like the rest of the example.
All in one file / self contained:
<? if(isset($_POST['submit'])){
//process and email
}else{
//display form
}
?>
I think its a quick exercise to get what you need working based on the above two available examples.
P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.
I also faced the same error msg, so i tried ng serve --port 12012 and it worked fine.
As dasblinkenlight already answered, the numbers come from the way that floating point numbers are represented in IEEE-754, and Andreas has a nice breakdown of the maths.
However - be careful that the precision of floating point numbers isn't exactly 6 or 15 significant decimal digits as the table suggests, since the precision of IEEE-754 numbers depends on the number of significant binary digits.
float
has 24 significant binary digits - which depending on the number represented translates to 6-8 decimal digits of precision.
double
has 53 significant binary digits, which is approximately 15 decimal digits.
Another answer of mine has further explanation if you're interested.
For anybody else stumbling over this, the same happened to me while trying to send a SOAP request header to a SOAP service. The issue was a wrong order in the code, I requested the input stream first before sending the XML body. In the code snipped below, the line InputStream in = conn.getInputStream();
came immediately after ByteArrayOutputStream out = new ByteArrayOutputStream();
which is the incorrect order of things.
ByteArrayOutputStream out = new ByteArrayOutputStream();
// send SOAP request as part of HTTP body
byte[] data = request.getHttpBody().getBytes("UTF-8");
conn.getOutputStream().write(data);
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d(TAG, "http response code is " + conn.getResponseCode());
return null;
}
InputStream in = conn.getInputStream();
FileNotFound
in this case was an unfortunate way to encode HTTP response code 400.
Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.
import pickle
class MyUser(object):
def __init__(self,name):
self.name = name
user = MyUser('Peter')
print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'
with open(filename,'wb') as file_object:
file_object.write(serialized)
with open(filename,'rb') as file_object:
raw_data = file_object.read()
deserialized = pickle.loads(raw_data)
print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
FOR MAC: I tried some of the above but to no avail, could not get anything to work.
I did have BREW INSTALLED, so although this not be the best approach, with zsh, I did:
This worked for me. Hope this helps someone. #1 bothers me, but I will live with for now.
try
Dialog dialog=new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen)
The main difference is ::
npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json
npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).
Ponits to note::
One more thing, npm build
and npm run build
are two different things, npm run build
will do custom work written inside package.json
and npm build
is a pre-defined script (not available to use directly)
You cannot specify some thing inside custom build script (npm run build
) script and expect npm build
to do the same. Try following thing to verify in your package.json
:
{ "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }
and run npm run build
and npm build
one by one and you will see the difference. For more about commands kindly follow npm documentation.
Cheers!!
@article = user.articles.build(:title => "MainTitle")
@article.save
SELECT table1.col,table2.col,table3.col
FROM table1
INNER JOIN
(table2 INNER JOIN table3
ON table3.id=table2.id)
ON table1.id(f-key)=table2.id
AND //add any additional filters HERE
document.querySelectorAll("[data-foo]")
will get you all elements with that attribute.
document.querySelectorAll("[data-foo='1']")
will only get you ones with a value of 1.
You have a few options other than using public key authentication:
If you decide to give sshpass a chance here is a working script snippet to do so:
export SSHPASS=your-password-here
sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
cd incoming
put your-log-file.log
bye
!
Or spin Linux instance for SFTP Gateway in your AWS infrastructure that saves uploaded files to your Amazon S3 bucket.
Supported by Thorntech
For the sake def plot_pca(data):
will work, it is necessary to replace the lines
data_resc, data_orig = PCA(data)
ax1.plot(data_resc[:, 0], data_resc[:, 1], '.', mfc=clr1, mec=clr1)
with lines
newData, data_resc, data_orig = PCA(data)
ax1.plot(newData[:, 0], newData[:, 1], '.', mfc=clr1, mec=clr1)
You can use the git show
command.
To get the last commit date from git repository in a long(Unix epoch timestamp):
git show -s --format=%ct
1605103148
Note: You can visit the git-show documentation to get a more detailed description of the options.
I know this is a late answer, I actually have a shortcut method that I use for posting/reading to/from MS based services.. it works with MVC as well as ASMX etc...
Use:
$.msajax(
'/services/someservice.asmx/SomeMethod'
,{} /*empty object for nothing, or object to send as Application/JSON */
,function(data,jqXHR) {
//use the data from the response.
}
,function(err,jqXHR) {
//additional error handling.
}
);
//sends a json request to an ASMX or WCF service configured to reply to JSON requests.
(function ($) {
var tries = 0; //IE9 seems to error out the first ajax call sometimes... will retry up to 5 times
$.msajax = function (url, data, onSuccess, onError) {
return $.ajax({
'type': "POST"
, 'url': url
, 'contentType': "application/json"
, 'dataType': "json"
, 'data': typeof data == "string" ? data : JSON.stringify(data || {})
,beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("X-MicrosoftAjax","Delta=true");
}
, 'complete': function(jqXHR, textStatus) {
handleResponse(jqXHR, textStatus, onSuccess, onError, function(){
setTimeout(function(){
$.msajax(url, data, onSuccess, onError);
}, 100 * tries); //try again
});
}
});
}
$.msajax.defaultErrorMessage = "Error retreiving data.";
function logError(err, errorHandler, jqXHR) {
tries = 0; //reset counter - handling error response
//normalize error message
if (typeof err == "string") err = { 'Message': err };
if (console && console.debug && console.dir) {
console.debug("ERROR processing jQuery.msajax request.");
console.dir({ 'details': { 'error': err, 'jqXHR':jqXHR } });
}
try {
errorHandler(err, jqXHR);
} catch (e) {}
return;
}
function handleResponse(jqXHR, textStatus, onSuccess, onError, onRetry) {
var ret = null;
var reterr = null;
try {
//error from jqXHR
if (textStatus == "error") {
var errmsg = $.msajax.defaultErrorMessage || "Error retreiving data.";
//check for error response from the server
if (jqXHR.status >= 300 && jqXHR.status < 600) {
return logError( jqXHR.statusText || msg, onError, jqXHR);
}
if (tries++ < 5) return onRetry();
return logError( msg, onError, jqXHR);
}
//not an error response, reset try counter
tries = 0;
//check for a redirect from server (usually authentication token expiration).
if (jqXHR.responseText.indexOf("|pageRedirect||") > 0) {
location.href = decodeURIComponent(jqXHR.responseText.split("|pageRedirect||")[1].split("|")[0]).split('?')[0];
return;
}
//parse response using ajax enabled parser (if available)
ret = ((JSON && JSON.parseAjax) || $.parseJSON)(jqXHR.responseText);
//invalid response
if (!ret) throw jqXHR.responseText;
// d property wrap as of .Net 3.5
if (ret.d) ret = ret.d;
//has an error
reterr = (ret && (ret.error || ret.Error)) || null; //specifically returned an "error"
if (ret && ret.ExceptionType) { //Microsoft Webservice Exception Response
reterr = ret
}
} catch (err) {
reterr = {
'Message': $.msajax.defaultErrorMessage || "Error retreiving data."
,'debug': err
}
}
//perform final logic outside try/catch, was catching error in onSuccess/onError callbacks
if (reterr) {
logError(reterr, onError, jqXHR);
return;
}
onSuccess(ret, jqXHR);
}
} (jQuery));
NOTE: I also have a JSON.parseAjax method that is modified from json.org's JS file, that adds handling for the MS "/Date(...)/" dates...
The modified json2.js file isn't included, it uses the script based parser in the case of IE8, as there are instances where the native parser breaks when you extend the prototype of array and/or object, etc.
I've been considering revamping this code to implement the promises interfaces, but it's worked really well for me.
Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.
The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.
Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.
If you use NetBeans, simply click on the frame on the design view, then the code tab on its properties. Next, check 'Generate Center'. That will get the job done.
Using -Dhttps.protocols=TLSv1.2 JVM argument didn't work for me. What worked is the following code
RequestConfig.Builder requestBuilder = RequestConfig.custom();
//other configuration, for example
requestBuilder = requestBuilder.setConnectTimeout(1000);
SSLContext sslContext = SSLContextBuilder.create().useProtocol("TLSv1.2").build();
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setProxy(new HttpHost("your.proxy.com", 3333)); //if you have proxy
builder.setSSLContext(sslContext);
HttpClient client = builder.build();
Use the following JVM argument to verify
-Djavax.net.debug=all
You can use jQuerys .animate(), .offset() and scrollTop
. Like
$(document.body).animate({
'scrollTop': $('#anchorName2').offset().top
}, 2000);
example link: http://jsbin.com/unasi3/edit
If you don't want to animate use .scrollTop() like
$(document.body).scrollTop($('#anchorName2').offset().top);
or javascripts native location.hash
like
location.hash = '#' + anchorid;
I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.
I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.
You can just do that too, it seems to work well too.
sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"
You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.
Try putting the following in the header:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
Courtesy Paul Irish's HTML5 Boilerplate (but it works in XHTML Transitional, too).
Although adding something to nodejs module is possible, it seems to be not the best way (if you try to run your code on other computer, the program will crash with the same error, obviously).
I would rather set max listeners number in your own code:
var options = {uri:headingUri, headers:headerData, maxRedirects:100};
request.setMaxListeners(0);
request.get(options, function (error, response, body) {
}
All upper code is not correct to the end.
This is because when searching zz*foo* or zz* you will not get correct results.
And if you search "abcd*" in "abcd" in TotalCommander will he find a abcd file so all upper code is wrong.
Here is the correct code.
public string WildcardToRegex(string pattern)
{
string result= Regex.Escape(pattern).
Replace(@"\*", ".+?").
Replace(@"\?", ".");
if (result.EndsWith(".+?"))
{
result = result.Remove(result.Length - 3, 3);
result += ".*";
}
return result;
}
try this one:
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];
[keychainItem setObject:@"password you are saving" forKey:kSecValueData];
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];
may it will help.
Using C++11
there is a nice version for a manually defined byte type:
enum class byte : std::uint8_t {};
That's at least what the GSL does.
Starting with C++17
(almost) this very version is defined in the standard as std::byte
(thanks Neil Macintosh for both).
Instead of launching the batch directly from explorer - create a shortcut to the batch and set the starting directory in the properties of the shortcut to a local path like %TEMP% or something.
To delete the symbolic link, use the rmdir command.
I had this problem in a unit test which opened a lot of connections to the DB via a connection pool and then "stopped" the connection pool (ManagedDataSource actually) to release the connections at the end of the each test. I always ran out of connections at some point in the suite of tests.
Added a Thread.sleep(500) in the teardown() of my tests and this resolved the issue. I think that what was happening was that the connection pool stop() releases the active connections in another thread so that if the main thread keeps running tests the cleanup thread(s) got so far behind that the Oracle server ran out of connections. Adding the sleep allows the background threads to release the pooled connections.
This is much less of an issue in the real world because the DB servers are much bigger and there is a healthy mix of operations (not just endless DB connect/disconnect operations).
A variation on @AndrewKennan's answer I ended up using recently for types obtained at runtime:
if (serviceType.IsInstanceOfType(service))
{
// 'service' does implement the 'serviceType' type
}
You also can draw line to see 80 limit:
let &colorcolumn=join(range(81,999),",")
let &colorcolumn="80,".join(range(400,999),",")
Result:
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace OTL
{
/// <summary>
/// Before usage: Define your class, sample:
/// [DataContract]
///public class MusicInfo
///{
/// [DataMember(Name="music_name")]
/// public string Name { get; set; }
/// [DataMember]
/// public string Artist{get; set;}
///}
/// </summary>
/// <typeparam name="T"></typeparam>
public class OTLJSON<T> where T : class
{
/// <summary>
/// Serializes an object to JSON
/// Usage: string serialized = OTLJSON<MusicInfo>.Serialize(musicInfo);
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public static string Serialize(T instance)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, instance);
return Encoding.Default.GetString(stream.ToArray());
}
}
/// <summary>
/// DeSerializes an object from JSON
/// Usage: MusicInfo deserialized = OTLJSON<MusicInfo>.Deserialize(json);
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static T Deserialize(string json)
{
if (string.IsNullOrEmpty(json))
throw new Exception("Json can't empty");
else
try
{
using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(typeof(T));
return serializer.ReadObject(stream) as T;
}
}
catch (Exception e)
{
throw new Exception("Json can't convert to Object because it isn't correct format.");
}
}
}
}
I don't believe that there is a formal limit here, and I'm pretty sure there isn't any hard limit specified in the RFC either, as you found.
I think that some pretty common limitations for subject lines in general (not just e-mail) are:
Obviously, you want to come up with something that is reasonable. If you're writing an e-mail client, you may want to go with something like 256 characters, and obviously test thoroughly against big commercial servers out there to make sure they serve your mail correctly.
Hope this helps!